示例#1
0
    def __init__(self, parent):
    
        top = self.top = parent
        
        Label(top, text="Introduzca la URL del video de Antena 3").pack()
        
        self.e = Entry(top)
        self.e.config(width="75")
        self.e.insert(0, "http://www.antena3.com/videos/karlos-arguinano/2011-junio-1.html")
        self.e.pack(padx=5)
        
        Label(top, text="Introduzca el directorio de descarga").pack()
        
        self.e2 = Entry(top)
        self.e2.config(width="75")

        import os
        confpath = os.path.join( config.get_data_path() , "descargar-antena3.conf" )
        if os.path.exists( confpath ):
            print "Leyendo ruta anterior "+confpath
            fichero = open(confpath,"r")
            ruta = fichero.read()
            fichero.close()
        else:
            ruta=config.get_data_path()

        self.e2.insert(0, ruta)
        self.e2.pack(padx=5)
        
        b = Button(top, text="Descargar", command=self.ok)
        b.pack(pady=5)
def get_filtered_tvshows(from_channel):
    """
    Obtiene las series filtradas de un canal

    :param from_channel: canal que tiene las series filtradas
    :type from_channel: str
    :return: dict con las series
    :rtype: dict
    """
    logger.info("[filtertools.py] get_filtered_tvshows")
    dict_series = {}
    name_file = from_channel

    if not os.path.exists(os.path.join(config.get_data_path(), "settings_channels")):
        os.mkdir(os.path.join(config.get_data_path(), "settings_channels"))

    fname = os.path.join(config.get_data_path(), "settings_channels", name_file + "_data.json")

    data = filetools.read(fname)
    dict_data = jsontools.load_json(data)

    check_json_file(data, fname, dict_data)

    if TAG_TVSHOW_FILTER in dict_data:
        dict_series = dict_data[TAG_TVSHOW_FILTER]

    if DEBUG:
        logger.info("json_series: {0}".format(dict_series))

    return dict_series
def update_json_data(dict_series, filename):
    """
    actualiza el json_data de un fichero con el diccionario pasado

    :param dict_series: diccionario con las series
    :type dict_series: dict
    :param filename: nombre del fichero para guardar
    :type filename: str
    :return: fname, json_data
    :rtype: str, dict
    """
    logger.info("[filtertools.py] update_json_data")
    if not os.path.exists(os.path.join(config.get_data_path(), "settings_channels")):
        os.mkdir(os.path.join(config.get_data_path(), "settings_channels"))
    fname = os.path.join(config.get_data_path(), "settings_channels", filename + "_data.json")
    data = filetools.read(fname)
    dict_data = jsontools.load_json(data)
    # es un dict
    if dict_data:
        if TAG_TVSHOW_FILTER in dict_data:
            logger.info("   existe el key SERIES")
            dict_data[TAG_TVSHOW_FILTER] = dict_series
        else:
            logger.info("   NO existe el key SERIES")
            new_dict = {TAG_TVSHOW_FILTER: dict_series}
            dict_data.update(new_dict)
    else:
        logger.info("   NO es un dict")
        dict_data = {TAG_TVSHOW_FILTER: dict_series}
    json_data = jsontools.dump_json(dict_data)
    return fname, json_data
def Check():
  import guitools
  progress = guitools.Dialog_ProgressBG("Pelisalacarta","Comprobando actualizaciones...")

  DownloadServers = []
  DownloadChannels = []
  ServersPath = os.path.join( config.get_runtime_path(), "servers" )
  ServersIndexPath = os.path.join(config.get_data_path(), "Servers.json")
  ChannelsPath = os.path.join( config.get_runtime_path(), "channels" )
  ChannelsIndexPath = os.path.join(config.get_data_path(), "Channels.json")
  if not os.path.isfile(ServersIndexPath): CreateIndex(ServersIndexPath,"servers")
  if not os.path.isfile(ChannelsIndexPath): CreateIndex(ChannelsIndexPath,"channels")
  
  #Servers
  progress.Actualizar(25, "Descargando lista de Servidores...")
  RemoteJSONData = json.loads(scrapertools.downloadpage(GitApi + "servers", headers=headers))
  LocalJSONData = json.loads(open(ServersIndexPath,"r").read())
  #open(ServersIndexPath.replace(".json","-remote.json"),"w").write(json.dumps(RemoteJSONData, indent=4, sort_keys=True))
  if RemoteJSONData <> LocalJSONData:
    for Server in RemoteJSONData:
      if not Server in LocalJSONData:
        DownloadServers.append(Server)
        
  #Channels
  progress.Actualizar(50, "Descargando lista de Canales...")
  RemoteJSONData = json.loads(scrapertools.downloadpage(GitApi + "channels", headers=headers))
  LocalJSONData = json.loads(open(ChannelsIndexPath,"r").read())
  #open(ChannelsIndexPath.replace(".json","-remote.json"),"w").write(json.dumps(RemoteJSONData, indent=4, sort_keys=True))
  progress.Actualizar(75, "Comprobando...")
  if RemoteJSONData <> LocalJSONData:
    for Channel in RemoteJSONData:
      if not Channel in LocalJSONData:
        logger.info(Channel)
        DownloadChannels.append(Channel)
               
  if DownloadServers or DownloadChannels:    
    
    for File in  DownloadServers:   
      Progreso = DownloadServers.index(File) * 100 / (len(DownloadServers) + len(DownloadChannels))
      progress.Actualizar(Progreso ,'Actualizando Archivo: "' + File["name"] + '"')
      open(os.path.join(config.get_runtime_path(), "servers", File["name"]),"wb").write(scrapertools.downloadpage(File["download_url"]))
    for File in  DownloadChannels:   
      Progreso = (DownloadChannels.index(File) + len(DownloadServers)  ) * 100 / (len(DownloadServers) + len(DownloadChannels))
      progress.Actualizar(Progreso ,'Actualizando Archivo: "' + File["name"] + '"')
      open(os.path.join(config.get_runtime_path(), "channels", File["name"]),"wb").write(scrapertools.downloadpage(File["download_url"]))
      
    CreateIndex(ServersIndexPath,"servers")
    CreateIndex(ChannelsIndexPath,"channels")

  progress.Actualizar(100, "Todos los canales y servidores estan actualizados")
  import time
  time.sleep(3)
  progress.Cerrar()
def backups(item):
    from platformcode import platformtools

    logger.info("pelisalacarta.channel.configuracion backups")

    ruta = filetools.join(config.get_data_path(), "backups")
    ruta_split = ""
    if "ruta" in item.title:
        heading = "Ruta de copias de seguridad"
        if not filetools.exists(ruta):
            folders = "Carpeta no creada"
        else:
            folders = str(len(filetools.listdir(ruta))) + " copia/s de seguridad guardadas"
        if len(ruta) > 55:
            ruta_split = ruta[55:]
            ruta = ruta[:55]
        platformtools.dialog_ok(heading, ruta, ruta_split, folders)
    else:
        if not filetools.exists(ruta):
            platformtools.dialog_ok("La carpeta no existe", "No hay copias de seguridad guardadas")
        else:
            dyesno = platformtools.dialog_yesno("Las copias de seguridad se eliminarán", "¿Está seguro?")
            if dyesno:
                import shutil

                shutil.rmtree(ruta, ignore_errors=True)
def get_saved_searches(channel):
    if os.path.exists(os.path.join(config.get_data_path(), "saved_searches.txt")):
        f = open(os.path.join(config.get_data_path(), "saved_searches.txt"), "r")
        saved_searches_list = f.readlines()
        f.close()
    else:
        saved_searches_list = []

    # Invierte la lista, para que el último buscado salga el primero
    saved_searches_list.reverse()

    trimmed = []
    for saved_search_text in saved_searches_list:
        trimmed.append(saved_search_text.strip())

    return trimmed
示例#7
0
def get_file_handle_for_reading(_file, url):
    logger.info("[lib.samba.py] get_file_handle_for_reading")

    server_name, share_name, path, user, password = parse_url(url)
    remote = connect(server_name, user, password)

    # Crea un fichero temporal con el bookmark
    logger.info("[lib.samba.py] Crea fichero temporal")
    try:
        import xbmc
        localfilename = xbmc.translatePath("special://temp")
    except ImportError:
        xbmc = None
        localfilename = config.get_data_path()
    logger.info("[lib.samba.py] localfilename=" + localfilename)

    localfilename = os.path.join(localfilename, "bookmark.tmp")

    # Lo abre
    bookmarkfile = open(localfilename, "wb")

    # Lo copia de la URL
    try:
        remote.retrieveFile(share_name, path + _file, bookmarkfile)
    finally:
        bookmarkfile.close()

    remote.close()

    return open(localfilename)
def play(item):
    logger.info("pelisalacarta.channels.seriesdanko play (url="+item.url+", server="+item.server+")" )

    data = scrapertools.cache_page(item.url)

    patron = '<input type="hidden" name="id" value="([^"]+)" />.*?'
    patron+= '<img src="([^"]+)"'

    matches = re.compile(patron,re.DOTALL).findall(data)

    id = matches[0][0]
    captcha = matches[0][1]

    image = os.path.join( config.get_data_path(), 'captcha.png')

    imgurl = "http://seriesdanko.com/" + captcha
    req = urllib2.Request(imgurl)
    req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0')
    req.add_header('Accept-Encoding','gzip, deflate')
    f = urllib2.urlopen(req)
    img = open(image, 'wb')
    img.write(f.read())
    img.close()

    spc = get_captcha(image)
    post = "id=%s&spc=%s" % (id,spc)

    data = scrapertools.cache_page( "http://seriesdanko.com/anonim.php", post=post )

    return servertools.find_video_items(data=data)
示例#9
0
def play(item):
    logger.info()
    itemlist = []

    try:
        from core import filetools
        ficherosubtitulo = filetools.join( config.get_data_path(), 'subtitulo_areadocu.srt' )
        if filetools.exists(ficherosubtitulo):
            try:
                filetools.remove(ficherosubtitulo)
            except IOError:
                logger.info("Error al eliminar el archivo "+ficherosubtitulo)
                raise
        
        data = httptools.downloadpage(item.subtitle, headers={'Referer': item.extra}).data
        filetools.write(ficherosubtitulo, data)
        subtitle = ficherosubtitulo
    except:
        subtitle = ""
        logger.info("Error al descargar el subtítulo")

    extension = item.url.rsplit("|", 1)[0][-4:]
    itemlist.append(['%s %s [directo]' % (extension, item.calidad), item.url, 0, subtitle])
    #itemlist.append(item.clone(subtitle=subtitle))

    return itemlist
示例#10
0
def generate_usertoken(auth_token):

       
        LOGIN = config.get_setting("serieslyuser")
        PASSWORD = config.get_setting("serieslypassword")

        url = "http://api.series.ly/v2/user/user_token"
        post = "auth_token=%s&username=%s&password=%s&remember=1&user_agent=''" % ( auth_token, qstr(LOGIN), qstr(PASSWORD) )
        data = scrapertools.cache_page(url,post=post)
        logger.info("****")
        logger.info(data)
        logger.info("****")
       
        user_data=load_json(data)


        if "error" in user_data:
            if user_data["error"]!=0:
                error_message(user_data["error"])
                return False
        else:
            return False

        path=config.get_data_path()
        logger.info(path)
        f =open(path+"seriesly_auth", "a")
        f.write(str(data))
        logger.info(str(data))
        f.close()

        user_token=user_data["user_token"]

        return user_token
示例#11
0
def mainlist(item):
    logger.info()
    itemlist = []
    item.text_color = color1

    logueado, error_message = login("copiapop.com")

    if not logueado:
        itemlist.append(item.clone(title=error_message, action="configuracion", folder=False))
    else:
        item.extra = "http://copiapop.com"
        itemlist.append(item.clone(title="Copiapop", action="", text_color=color2))
        itemlist.append(item.clone(title="     Búsqueda", action="search", url="http://copiapop.com/action/SearchFiles"))
        itemlist.append(item.clone(title="     Colecciones", action="colecciones",
                                   url="http://copiapop.com/action/home/MoreNewestCollections?pageNumber=1"))
        itemlist.append(item.clone(title="     Búsqueda personalizada", action="filtro", url="http://copiapop.com/action/SearchFiles"))
        itemlist.append(item.clone(title="     Mi cuenta", action="cuenta"))

    item.extra = "http://diskokosmiko.mx/"
    itemlist.append(item.clone(title="DiskoKosmiko", action="", text_color=color2))
    itemlist.append(item.clone(title="     Búsqueda", action="search", url="http://diskokosmiko.mx/action/SearchFiles"))
    itemlist.append(item.clone(title="     Colecciones", action="colecciones",
                               url="http://diskokosmiko.mx/action/home/MoreNewestCollections?pageNumber=1"))
    itemlist.append(item.clone(title="     Búsqueda personalizada", action="filtro", url="http://diskokosmiko.mx/action/SearchFiles"))
    itemlist.append(item.clone(title="     Mi cuenta", action="cuenta"))
    itemlist.append(item.clone(action="", title=""))

    folder_thumb = filetools.join(config.get_data_path(), 'thumbs_copiapop')
    files = filetools.listdir(folder_thumb)
    if files:
        itemlist.append(item.clone(title="Eliminar caché de imágenes (%s)" % len(files), action="delete_cache", text_color="red"))
    itemlist.append(item.clone(title="Configuración del canal", action="configuracion", text_color="gold"))

    return itemlist
示例#12
0
def store_file(_file, data, url):
    logger.info("[lib.samba.py] write_file")

    server_name, share_name, path, user, password = parse_url(url)
    remote = connect(server_name, user, password)

    logger.info("Crea fichero temporal")
    try:
        import xbmc
        localfilename = xbmc.translatePath("special://temp")
    except ImportError:
        xbmc = None
        localfilename = config.get_data_path()
    logger.info("localfilename="+localfilename)

    localfilename = os.path.join(localfilename, "bookmark.tmp")
    bookmarkfile = open(localfilename, "wb")
    bookmarkfile.write(data)
    bookmarkfile.flush()
    bookmarkfile.close()

    # Copia el bookmark al directorio Samba
    logger.info("Crea el fichero remoto")
    bookmarkfile = open(localfilename, "rb")
    remote.storeFile(share_name, path + _file, bookmarkfile)
    bookmarkfile.close()

    # Borra el fichero temporal
    logger.info("Borra el fichero local")
    os.remove(localfilename)

    remote.close()
def download_subtitles (url):

    tmp_sub_dir= SUB_PATH #Carpeta temporal
    fullpath = os.path.join( config.get_data_path(), 'subtitulo.srt' )
    if os.path.exists(fullpath):   #Borro subtitulo anterior
        try:
          os.remove(fullpath)
        except IOError:
          xbmc.output("Error al eliminar el archivo subtitulo.srt "+fullpath)
          raise	
    for root, dirs, files in os.walk(tmp_sub_dir): #Borro archivos de la carpeta temporal
        for f in files:
            f = unicode(f,'utf8')
            os.unlink(os.path.join(root, f)) 
        for d in dirs:
            from shutil import rmtree						
            shutil.rmtree(os.path.join(root, d))
    #Mensaje de información
    mensaje = xbmcgui.DialogProgress()
    linea1 = 'Extrayendo archivo de subtítulos...'
    linea2 = 'Seleccione uno de la lista'
    linea3 = 'que aparecerá a continuación'
    mensaje.create(linea1 , linea2 , linea3)
    time.sleep(3)
    mensaje.close()	
    try:
        req = urllib2.Request(url)
        req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
        opener = urllib2.build_opener(SmartRedirectHandler())
        content = opener.open(req)
    except ImportError, inst:
        status,location = inst	
        response = urllib.urlopen(location)
        content =response.read()
示例#14
0
def get_main_page():

    file_name = os.path.join( config.get_data_path() , "tnu.cached" )
    logger.info("tvalacarta.channels.tnu get_main_page file_name="+file_name)

    if not os.path.exists(file_name):
        logger.info("tvalacarta.channels.tnu get_main_page no existe")
        data = scrapertools.cachePage("http://www.tnu.com.uy/videoteca/")
        f = open(file_name,"w")
        f.write(data)
        f.close()
        return data

    # Calcula la antiguedad del fichero
    file_timestap = os.path.getmtime(file_name)
    file_datetime = datetime.datetime.fromtimestamp(file_timestap)
    now_datetime = datetime.datetime.now()

    # Si tiene más de 3 horas
    diferencia = (now_datetime - file_datetime).seconds

    if diferencia > 60*60*3:
        logger.info("tvalacarta.channels.tnu get_main_page tiene más de 3 horas, lee de nuevo y actualiza la cache")
        data = scrapertools.cachePage("http://www.tnu.com.uy/videoteca/")
        f = open(file_name,"w")
        f.write(data)
        f.close()
        return data
    else:
        logger.info("tvalacarta.channels.tnu get_main_page tiene menos de 3 horas, devuelve la cache")
        f = open(file_name,"r")
        data = f.read()
        f.close()
        return data
示例#15
0
def generate_authtoken():


        url = "http://api.series.ly/v2/auth_token/"
        #post='id_api=1363&secret=zHX3TPEW2tvZRFneAAU7'
        post='id_api=8&secret=N5X54c4OeDUwU8dWBbMW'
        data = scrapertools.cache_page(url,post=post)
        logger.info("****")
        logger.info(data)
        logger.info("****")
       
        auth_data= load_json(data)

        if "error" in auth_data:
            if auth_data["error"]!=0:
                error_message(auth_data["error"])
                return False
        else:
            return False


        auth_token = auth_data["auth_token"]

        path=config.get_data_path()
        f =open(path+"seriesly_auth", "w+")
        f.write(str(data+";"))
        f.close()

       
        return auth_token
示例#16
0
def syncBibliteca(item):

	path=config.get_data_path()


	idmList=[]
	
	f=open(path+"series.xml","r")
	for line in f.readlines():
		name,url,channel=line.split(',')
		if 'seriesly' in channel:	
			for data in url.split('&'):
				if "idm" in data:
					idm=data.split("=")[1]	
					idmList.append(idm)
					
	f.close()

	auth_token, user_token = getCredentials()

	xbmctvshows=getTVShows()

	for idm in idmList:
		url = 'http://api.series.ly/v2/media/full_info?auth_token='+ auth_token+'&user_token='+user_token+'&idm=%s&mediaType=1' %(idm)
	

		serieInfo = load_json(scrapertools.cache_page(url, modo_cache=1))
		logger.info("Syncronizando: %s"%(serieInfo["name"]))
		if "imdb" in serieInfo:
			serieInfo["tvdb"] = gettvdbname(serieInfo["imdb"])
		sync(serieInfo, xbmctvshows)
		#logger.info(serieInfo)
	
	return []
示例#17
0
    def __init__(self, parent):
    
        top = self.top = parent
        
        Label(top, text="Introduzca la URL del video de Aragón TV").pack()
        
        self.e = Entry(top)
        self.e.config(width="75")
        self.e.insert(0, "http://alacarta.aragontelevision.es/programas/aragoneses-por-el-mundo/shangai-09062011-2123")
        self.e.pack(padx=5)
        
        Label(top, text="Introduzca el directorio de descarga").pack()
        
        self.e2 = Entry(top)
        self.e2.config(width="75")

        import os
        confpath = os.path.join( config.get_data_path() , "descargar-aragontv.conf" )
        if os.path.exists( confpath ):
            print "Leyendo ruta anterior "+confpath
            fichero = open(confpath,"r")
            ruta = fichero.read()
            fichero.close()
        else:
            import os
            ruta=os.path.expanduser("~")

        self.e2.insert(0, ruta)
        self.e2.pack(padx=5)

        b = Button(top, text="Descargar", command=self.ok)
        b.pack(pady=5)
示例#18
0
def play(item):
    logger.info("tvalacarta.channels.a3media play")

    itemlist = []

    # Si es un stream de directo, no lo procesa
    if item.url.startswith("rtmp://") or item.url.startswith("http://a3live-lh"):
        itemlist.append(item)
        return itemlist
    else:
        token = d(item.extra, "QWtMLXs414Yo+c#_+Q#K@NN)")
        url = item.url + token

        if account:
            cookies = os.path.join( config.get_data_path(), 'cookies.dat' )
            cookiedatafile = open(cookies,'r')
            cookiedata = cookiedatafile.read()
            cookiedatafile.close();
            jsessionid = scrapertools.find_single_match(cookiedata,"servicios.atresplayer.com.*?JSESSIONID\s+([A-Za-z0-9\+\-]+)")
            ANDROID_HEADERS.append(['Cookie','JSESSIONID='+jsessionid])

        data = scrapertools.cachePage(url,headers=ANDROID_HEADERS)
        logger.info(data)
        lista = jsontools.load_json(data)
        if lista != None: 
            item.url = lista['resultObject']['es']
            logger.info("tvalacarta.channels.a3media item.url="+item.url)
            itemlist.append(item)

        return itemlist
示例#19
0
文件: cinetube.py 项目: Medisan/TVWeb
def login(item):
    if config.get_platform() in ("wiimc", "rss", "mediaserver"):
        login = config.get_setting("cinetubeuser")
        password = config.get_setting("cinetubepassword")
        if login<>"" and password<>"":
            url="http://www.cinetube.es/login.php"
            data = scrapertools.cache_page("http://www.cinetube.es/login.php",post="usuario=%s&clave=%s" % (login,password))
            itemlist = []
            itemlist.append( Item(channel=__channel__, title="Sesión iniciada", action="mainlist"))
    else:
        import xbmc
        keyboard = xbmc.Keyboard("","Login")
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            login = keyboard.getText()

        keyboard = xbmc.Keyboard("","Password")
        keyboard.doModal()
        if (keyboard.isConfirmed()):
            password = keyboard.getText()

        nombre_fichero_config_canal = os.path.join( config.get_data_path() , __channel__+".xml" )
        config_canal = open( nombre_fichero_config_canal , "w" )
        config_canal.write("<settings>\n<session>true</session>\n<login>"+login+"</login>\n<password>"+password+"</password>\n</settings>")
        config_canal.close();

        itemlist = []
        itemlist.append( Item(channel=__channel__, title="Sesión iniciada", action="mainlist"))
    return itemlist
示例#20
0
def login():
    logger.info("pelisalacarta.channels.verseriesynovelas login")

    try:
        user = config.get_setting("verseriesynovelasuser", "verseriesynovelas")
        password = config.get_setting("verseriesynovelaspassword", "verseriesynovelas")
        if user == "" and password == "":
            return False, "Para ver los enlaces de este canal es necesario registrarse en www.verseriesynovelas.tv"
        elif user == "" or password == "":
            return False, "Usuario o contraseña en blanco. Revisa tus credenciales"
        data = scrapertools.downloadpage("http://www.verseriesynovelas.tv/")
        if user in data:
            return True, ""
        
        try:
            os.remove(os.path.join(config.get_data_path(), 'cookies', 'verseriesynovelas.tv.dat'))
        except:
            pass

        post = "log=%s&pwd=%s&redirect_to=http://www.verseriesynovelas.tv/wp-admin/&action=login" % (user, password)
        data = scrapertools.downloadpage("http://www.verseriesynovelas.tv/iniciar-sesion", post=post)
        if "La contraseña que has introducido" in data:
            logger.info("pelisalacarta.channels.verseriesynovelas Error en el login")
            return False, "Contraseña errónea. Comprueba tus credenciales"
        elif "Nombre de usuario no válido" in data:
            logger.info("pelisalacarta.channels.verseriesynovelas Error en el login")
            return False, "Nombre de usuario no válido. Comprueba tus credenciales"            
        else:
            logger.info("pelisalacarta.channels.verseriesynovelas Login correcto")
            return True, ""
    except:
        import traceback
        logger.info(traceback.format_exc())
        return False, "Error durante el login. Comprueba tus credenciales"
def GuardarSerie(itemlist):
    # Progreso
    pDialog = xbmcgui.DialogProgress()
    ret = pDialog.create('pelisalacarta', 'Añadiendo episodios...')
    pDialog.update(0, 'Añadiendo episodio...')
    totalepisodes = len(itemlist)
    i = 0
    for item in itemlist:
        i = i + 1
        pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
        
        if (pDialog.iscanceled()):
            return
        if item.action!="add_serie_to_library" and item.action!="download_all_episodes": 
            item.category='Series'
            item.action= 'play_from_library'
            Guardar(item)      
    pDialog.close()
    
    #Lista con series para actualizar
    nombre_fichero_listado_series = os.path.join( config.get_library_path() , "series.xml" )
    if not os.path.exists(nombre_fichero_listado_series):
        nombre_fichero_listado_series = os.path.join( config.get_data_path() , "series.xml" )

    #logger.info("nombre_fichero_listado_series="+nombre_fichero_listado_series)
    fichero_listado_series= open(nombre_fichero_listado_series.decode("utf8") ,"a")
    fichero_listado_series.write(LimpiarNombre(item.show)+"|"+item.url+"|"+item.channel+"\n")
    fichero_listado_series.flush()
    fichero_listado_series.close()
    
    ActualizarBiblioteca(item)
示例#22
0
def start():
    logger.info("pelisalacarta server init...")
    config.verify_directories_created()
    try:
        HTTPServer.start(MostrarInfo)
        WebSocket.start(MostrarInfo)

        # Da por levantado el servicio
        logger.info("--------------------------------------------------------------------")
        logger.info("Pelisalacarta Iniciado")
        logger.info("La URL para acceder es http://" + myip + ":" + str(http_port))
        logger.info("WebSocket Server iniciado en ws://" + myip + ":" + str(websocket_port))
        logger.info("--------------------------------------------------------------------")
        logger.info("Runtime Path      : " + config.get_runtime_path())
        logger.info("Data Path         : " + config.get_data_path())
        logger.info("Download Path     : " + config.get_setting("downloadpath"))
        logger.info("DownloadList Path : " + config.get_setting("downloadlistpath"))
        logger.info("Bookmark Path     : " + config.get_setting("bookmarkpath"))
        logger.info("Library Path      : " + config.get_setting("librarypath"))
        logger.info("--------------------------------------------------------------------")
        MostrarInfo()

        start = True
        while start:
            time.sleep(1)

    except KeyboardInterrupt:
        print 'Deteniendo el servidor HTTP...'
        HTTPServer.stop()
        print 'Deteniendo el servidor WebSocket...'
        WebSocket.stop()
        print 'Pelisalacarta Detenido'
        start = False
def yearsearch(item):
    user_id = config.get_setting("stormtvuser")
    user_pass = config.get_setting("stormtvpassword")
    path = config.get_data_path() + "stormtv/temp/"
    urllib.urlretrieve(SERVER + "tvseries/years", path + "temp.xml")
    xml = path + "/" + "temp.xml"
    doc = minidom.parse(xml)
    node = doc.documentElement
    years = doc.getElementsByTagName("year")
    if DEBUG:
        print len(years)
    itemlist = []
    for year in years:
        name = year.getElementsByTagName("name")[0].childNodes[0].data
        if DEBUG:
            logger.info("[stormtv.py] yearsearch ###" + name + "$$")
        id = year.getElementsByTagName("id")[0].childNodes[0].data
        itemlist.append(
            Item(
                channel=__channel__,
                action="yeartvs",
                title=name,
                fulltitle=name,
                url=id,
                thumbnail=SERVER + "logo.jpg",
                plot="",
                viewmode="movie_with_plot",
                show=id,
                fanart=SERVER + "logo.jpg",
            )
        )
    return itemlist
示例#24
0
def add_serie_to_library(item):
  from core import library
  channelmodule = ImportarCanal(item.channel)
  if item.extra: action = item.extra
  if item.refered_action: action = item.refered_action
  
  if "###" in action:
    item.extra = action.split("###")[1]
    action = action.split("###")[0]
  item.action = action
  
  nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )
  if not os.path.exists(nombre_fichero_config_canal):
      f = open( nombre_fichero_config_canal , "w" )
  else:
      f = open( nombre_fichero_config_canal , "r" )
      contenido = f.read()
      f.close()
      f = open( nombre_fichero_config_canal , "w" )
      f.write(contenido)

  f.write(item.serialize()+"\n")
  f.close();

  exec "itemlist = channelmodule."+action+"(item)"
  for episodio in itemlist:
    if episodio.action!="add_serie_to_library" and episodio.action!="download_all_episodes":
        episodio.category="Series"
        episodio.refered_action = action
        library.Guardar(episodio)
  guitools.Dialog_OK(config.get_localized_string(30101) , item.title +"\n"+ config.get_localized_string(30135)) # 'Se ha añadido a la Biblioteca'
  library.ActualizarBiblioteca(item)   
def MostrarInfo():
    os.system('cls' if os.name == 'nt' else 'clear')
    print ("--------------------------------------------------------------------")
    print ("Pelisalacarta Iniciado")
    print ("La URL para acceder es http://" + myip + ":" + str(PORT))
    print ("WebSocket Server iniciado en ws://"+ myip + ":" + config.get_setting("websocket.port")+"/")
    print ("--------------------------------------------------------------------")
    print ("Runtime Path      : " + config.get_runtime_path())
    print ("Data Path         : " + config.get_data_path())
    print ("Download Path     : " + config.get_setting("downloadpath") )
    print ("DownloadList Path : " + config.get_setting("downloadlistpath"))
    print ("Bookmark Path     : " + config.get_setting("bookmarkpath"))  
    print ("Library Path      : " + config.get_setting("library_path"))  
    print ("Cache Path        : " + config.get_setting("cache.dir"))  
    print ("Cookies Path      : " + config.get_setting("cookies.dir"))  
    print ("--------------------------------------------------------------------")
    conexiones = []
    for a in sys.argv:
      conexiones.append(sys.argv[a]["Socket"].client.getpeername()[0])
    if len(conexiones) >0:
      print ("Clientes conectados:")
      for conexion in conexiones:
        print (conexion)
    else:
      print ("No hay conexiones")
示例#26
0
def play(item):
    logger.info("pelisalacarta.channels.areadocumental play")
    itemlist = []
    headers.append(['Referer',item.extra])
    try:
        ficherosubtitulo = os.path.join( config.get_data_path(), 'subtitulo_areadocu.srt' )
        if os.path.exists(ficherosubtitulo):
            try:
                os.remove(ficherosubtitulo)
            except IOError:
                logger.info("Error al eliminar el archivo "+ficherosubtitulo)
                raise
        
        data2 = scrapertools.cache_page(item.subtitle, headers=headers)
        fichero = open(ficherosubtitulo,"wb")
        fichero.write(data2)
        fichero.close()
        subtitle = ficherosubtitulo
    except:
        subtitle = ""
        logger.info("Error al descargar el subtítulo")
    
    itemlist.append(Item(channel=item.channel, action="play", server="directo", title=bbcode_kodi2html(item.title), url=item.url, thumbnail=item.thumbnail, plot=item.plot, subtitle=subtitle, folder=False))

    return itemlist
def download_and_install_package(item):
    logger.info()

    from core import updater
    from platformcode import platformtools

    if item.package=="plugin":
        if int(item.version)<updater.get_current_plugin_version():
            if not platformtools.dialog_yesno("Installazione versione precedente","Sei sicuro di voler installare una versione precedente?"):
                return
        elif int(item.version)==updater.get_current_plugin_version():
            if not platformtools.dialog_yesno("Reinstallare versione attuale","Sei sicuro di voler reinstallare la stessa versione già presente?"):
                return
        elif int(item.version)>updater.get_current_plugin_version():
            if not platformtools.dialog_yesno("Installazione nuova versione","Sei sicuro di voler installare questa nuova versione?"):
                return
    else:
        if not platformtools.dialog_yesno("Pacchetto di installazione","Sei sicuro di voler installare questo pacchetto?"):
            return

    local_file_name = os.path.join( config.get_data_path() , item.filename)
    updater.download_and_install(item.url,local_file_name)

    if item.package=="channels":
        updater.set_current_channels_version(item.version)
    elif item.package=="servers":
        updater.set_current_servers_version(item.version)
    elif item.package=="plugin":
        updater.set_current_plugin_version(item.version)

    if config.is_xbmc() and config.get_system_platform() != "xbox":
        import xbmc
        xbmc.executebuiltin("Container.Refresh")
def create_tvshows_from_json(_actualizado):
    logger.info("pelisalacarta.platformcode.library_service create_tvshows_from_json")
    fname = filetools.join(config.get_data_path(), library.TVSHOW_FILE)

    if filetools.exists(fname):
        if not _actualizado:
            platformtools.dialog_ok("Biblioteca: Actualizando formato",
                                    "Espere por favor mientras se completa el proceso")

        try:
            data = jsontools.loads(filetools.read(fname))
            for tvshow in data:
                for channel in data[tvshow]["channels"]:

                    serie = Item(contentSerieName=data[tvshow]["channels"][channel]["tvshow"],
                                 url=data[tvshow]["channels"][channel]["url"], channel=channel, action="episodios",
                                 title=data[tvshow]["name"], active=True)
                    if not tvshow.startswith("t_"):
                        serie.infoLabels["tmdb_id"] = tvshow
                    library.save_library_tvshow(serie, list())

            filetools.rename(fname, "series.json.old")

        except EnvironmentError:
            logger.info("ERROR al leer el archivo: {0}".format(fname))
示例#29
0
    def __init__(self, parent):
    
        top = self.top = parent
        
        Label(top, text="Introduzca la URL del video de El Trece").pack()
        
        self.e = Entry(top)
        self.e.config(width="75")
        self.e.insert(0, "http://www.eltrecetv.com.ar/periodismo-para-todos/2-de-diciembre-periodismo-para-todos_057591")
        self.e.pack(padx=5)
        
        Label(top, text="Introduzca el directorio de descarga").pack()
        
        self.e2 = Entry(top)
        self.e2.config(width="75")

        import os
        confpath = os.path.join( config.get_data_path() , "descargar-eltrece.conf" )
        if os.path.exists( confpath ):
            print "Leyendo ruta anterior "+confpath
            fichero = open(confpath,"r")
            ruta = fichero.read()
            fichero.close()
        else:
            import os
            ruta=os.path.expanduser("~")

        self.e2.insert(0, ruta)
        self.e2.pack(padx=5)

        b = Button(top, text="Descargar", command=self.ok)
        b.pack(pady=5)
示例#30
0
def download_and_install_package(item):
    logger.info()

    from core import updater
    from core import versiontools

    if item.package=="plugin":
        if int(item.version)<versiontools.get_current_plugin_version():
            if not platformtools.dialog_yesno("Instalando versión anterior","¿Seguro que quieres instalar una versión anterior?"):
                return
        elif int(item.version)==versiontools.get_current_plugin_version():
            if not platformtools.dialog_yesno("Reinstalando versión actual","¿Seguro que quieres reinstalar la misma versión que ya tienes?"):
                return
        elif int(item.version)>versiontools.get_current_plugin_version():
            if not platformtools.dialog_yesno("Instalando nueva versión","¿Seguro que quieres instalar esta nueva versión?"):
                return
    else:
        if not platformtools.dialog_yesno("Instalando paquete","¿Seguro que quieres instalar este paquete?"):
            return

    local_file_name = os.path.join( config.get_data_path() , item.filename)
    updater.download_and_install(item.url,local_file_name)

    if config.is_xbmc() and config.get_system_platform() != "xbox":
        import xbmc
        xbmc.executebuiltin("Container.Refresh")
示例#31
0
def Check():
    import guitools
    progress = guitools.Dialog_ProgressBG("Pelisalacarta",
                                          "Comprobando actualizaciones...")

    DownloadServers = []
    DownloadChannels = []
    ServersPath = os.path.join(config.get_runtime_path(), "servers")
    ServersIndexPath = os.path.join(config.get_data_path(), "Servers.json")
    ChannelsPath = os.path.join(config.get_runtime_path(), "channels")
    ChannelsIndexPath = os.path.join(config.get_data_path(), "Channels.json")
    if not os.path.isfile(ServersIndexPath):
        CreateIndex(ServersIndexPath, "servers")
    if not os.path.isfile(ChannelsIndexPath):
        CreateIndex(ChannelsIndexPath, "channels")

    #Servers
    progress.Actualizar(25, "Descargando lista de Servidores...")
    RemoteJSONData = json.loads(
        scrapertools.downloadpage(GitApi + "servers", headers=headers))
    LocalJSONData = json.loads(open(ServersIndexPath, "r").read())
    #open(ServersIndexPath.replace(".json","-remote.json"),"w").write(json.dumps(RemoteJSONData, indent=4, sort_keys=True))
    if RemoteJSONData <> LocalJSONData:
        for Server in RemoteJSONData:
            if not Server in LocalJSONData:
                DownloadServers.append(Server)

    #Channels
    progress.Actualizar(50, "Descargando lista de Canales...")
    RemoteJSONData = json.loads(
        scrapertools.downloadpage(GitApi + "channels", headers=headers))
    LocalJSONData = json.loads(open(ChannelsIndexPath, "r").read())
    #open(ChannelsIndexPath.replace(".json","-remote.json"),"w").write(json.dumps(RemoteJSONData, indent=4, sort_keys=True))
    progress.Actualizar(75, "Comprobando...")
    if RemoteJSONData <> LocalJSONData:
        for Channel in RemoteJSONData:
            if not Channel in LocalJSONData:
                logger.info(Channel)
                DownloadChannels.append(Channel)

    if DownloadServers or DownloadChannels:

        for File in DownloadServers:
            Progreso = DownloadServers.index(File) * 100 / (
                len(DownloadServers) + len(DownloadChannels))
            progress.Actualizar(Progreso,
                                'Actualizando Archivo: "' + File["name"] + '"')
            open(
                os.path.join(config.get_runtime_path(), "servers",
                             File["name"]),
                "wb").write(scrapertools.downloadpage(File["download_url"]))
        for File in DownloadChannels:
            Progreso = (DownloadChannels.index(File) +
                        len(DownloadServers)) * 100 / (len(DownloadServers) +
                                                       len(DownloadChannels))
            progress.Actualizar(Progreso,
                                'Actualizando Archivo: "' + File["name"] + '"')
            open(
                os.path.join(config.get_runtime_path(), "channels",
                             File["name"]),
                "wb").write(scrapertools.downloadpage(File["download_url"]))

        CreateIndex(ServersIndexPath, "servers")
        CreateIndex(ChannelsIndexPath, "channels")

    progress.Actualizar(100,
                        "Todos los canales y servidores estan actualizados")
    import time
    time.sleep(3)
    progress.Cerrar()
示例#32
0
def conf_tools(item):
    logger.info()

    # Activar o desactivar canales
    if item.extra == "channels_onoff":
        import channelselector
        from core import channeltools

        channel_list = channelselector.filterchannels("allchannelstatus")

        excluded_channels = [
            'tengourl', 'buscador', 'biblioteca', 'configuracion', 'novedades',
            'personal', 'ayuda', 'descargas'
        ]

        list_controls = []
        try:
            list_controls.append({
                'id':
                "all_channels",
                'type':
                "list",
                'label':
                "Todos los canales",
                'default':
                0,
                'enabled':
                True,
                'visible':
                True,
                'lvalues': [
                    '', 'Activar todos', 'Desactivar todos',
                    'Establecer estado por defecto'
                ]
            })

            for channel in channel_list:
                # Si el canal esta en la lista de exclusiones lo saltamos
                if channel.channel not in excluded_channels:

                    channel_parameters = channeltools.get_channel_parameters(
                        channel.channel)

                    status_control = ""
                    status = config.get_setting("enabled", channel.channel)
                    # si status no existe es que NO HAY valor en _data.json
                    if status is None:
                        status = channel_parameters["active"]
                        logger.debug("%s | Status (XML): %s" %
                                     (channel.channel, status))
                        if not status:
                            status_control = " [COLOR grey](Desactivado por defecto)[/COLOR]"
                    else:
                        logger.debug("%s  | Status: %s" %
                                     (channel.channel, status))

                    control = {
                        'id': channel.channel,
                        'type': "bool",
                        'label': channel_parameters["title"] + status_control,
                        'default': status,
                        'enabled': True,
                        'visible': True
                    }
                    list_controls.append(control)

                else:
                    continue

        except:
            import traceback
            logger.error("Error: %s" % traceback.format_exc())
        else:
            return platformtools.show_channel_settings(
                list_controls=list_controls,
                item=item.clone(channel_list=channel_list),
                caption="Canales",
                callback="channel_status",
                custom_button={"visible": False})

    # Comprobacion de archivos channel_data.json
    elif item.extra == "lib_check_datajson":
        itemlist = []
        import channelselector
        from core import channeltools
        channel_list = channelselector.filterchannels("allchannelstatus")

        # Tener una lista de exclusion no tiene mucho sentido por que se comprueba si
        # el xml tiene "settings", pero por si acaso se deja
        excluded_channels = ['tengourl', 'configuracion', 'personal', 'ayuda']

        try:
            import os
            from core import jsontools
            for channel in channel_list:

                list_status = None
                default_settings = None

                # Se comprueba si el canal esta en la lista de exclusiones
                if channel.channel not in excluded_channels:
                    # Se comprueba que tenga "settings", sino se salta
                    jsonchannel = channeltools.get_channel_json(
                        channel.channel)
                    if not jsonchannel.get("settings"):
                        itemlist.append(
                            Item(channel=CHANNELNAME,
                                 title=channel.title +
                                 " - No tiene ajustes por defecto",
                                 action="",
                                 folder=False,
                                 thumbnail=channel.thumbnail))
                        continue
                        # logger.info(channel.channel + " SALTADO!")

                    # Se cargan los ajustes del archivo json del canal
                    file_settings = os.path.join(
                        config.get_data_path(), "settings_channels",
                        channel.channel + "_data.json")
                    dict_settings = {}
                    dict_file = {}
                    if filetools.exists(file_settings):
                        # logger.info(channel.channel + " Tiene archivo _data.json")
                        channeljson_exists = True
                        # Obtenemos configuracion guardada de ../settings/channel_data.json
                        try:
                            dict_file = jsontools.load_json(
                                open(file_settings, "rb").read())
                            if isinstance(dict_file,
                                          dict) and 'settings' in dict_file:
                                dict_settings = dict_file['settings']
                        except EnvironmentError:
                            logger.error("ERROR al leer el archivo: %s" %
                                         file_settings)
                    else:
                        # logger.info(channel.channel + " No tiene archivo _data.json")
                        channeljson_exists = False

                    if channeljson_exists == True:
                        try:
                            datajson_size = filetools.getsize(file_settings)
                        except:
                            import traceback
                            logger.error(channel.title +
                                         " | Detalle del error: %s" %
                                         traceback.format_exc())
                    else:
                        datajson_size = None

                    # Si el _data.json esta vacio o no existe...
                    if (len(dict_settings) and
                            datajson_size) == 0 or channeljson_exists == False:
                        # Obtenemos controles del archivo ../channels/channel.xml
                        needsfix = True
                        try:
                            # Se cargan los ajustes por defecto
                            list_controls, default_settings = channeltools.get_channel_controls_settings(
                                channel.channel)
                            # logger.info(channel.title + " | Default: %s" % default_settings)
                        except:
                            import traceback
                            logger.error(channel.title +
                                         " | Detalle del error: %s" %
                                         traceback.format_exc())
                            # default_settings = {}

                        # Si _data.json necesita ser reparado o no existe...
                        if needsfix == True or channeljson_exists == False:
                            if default_settings is not None:
                                # Creamos el channel_data.json
                                default_settings.update(dict_settings)
                                dict_settings = default_settings
                                dict_file['settings'] = dict_settings
                                # Creamos el archivo ../settings/channel_data.json
                                json_data = jsontools.dump_json(dict_file)
                                try:
                                    open(file_settings, "wb").write(json_data)
                                    # logger.info(channel.channel + " - Archivo _data.json GUARDADO!")
                                    # El channel_data.json se ha creado/modificado
                                    list_status = " - [COLOR red] CORREGIDO!![/COLOR]"
                                except EnvironmentError:
                                    logger.error(
                                        "ERROR al salvar el archivo: %s" %
                                        file_settings)
                            else:
                                if default_settings is None:
                                    list_status = " - [COLOR red] Imposible cargar los ajustes por defecto![/COLOR]"

                    else:
                        # logger.info(channel.channel + " - NO necesita correccion!")
                        needsfix = False

                    # Si se ha establecido el estado del canal se añade a la lista
                    if needsfix is not None:
                        if needsfix == True:
                            if channeljson_exists == False:
                                list_status = " - Ajustes creados"
                                list_colour = "red"
                            else:
                                list_status = " - No necesita corrección"
                                list_colour = "green"
                        else:
                            # Si "needsfix" es "false" y "datjson_size" es None habra
                            # ocurrido algun error
                            if datajson_size is None:
                                list_status = " - Ha ocurrido algun error"
                                list_colour = "red"
                            else:
                                list_status = " - No necesita corrección"
                                list_colour = "green"

                    if list_status is not None:
                        itemlist.append(
                            Item(channel=CHANNELNAME,
                                 title=channel.title + list_status,
                                 action="",
                                 folder=False,
                                 thumbnail=channel.thumbnail,
                                 text_color=list_colour))
                    else:
                        logger.error("Algo va mal con el canal %s" %
                                     channel.channel)

                # Si el canal esta en la lista de exclusiones lo saltamos
                else:
                    continue
        except:
            import traceback
            logger.error("Error: %s" % traceback.format_exc())

        return itemlist
示例#33
0
    def show_channel_settings(self,
                              list_controls=None,
                              dict_values=None,
                              caption="",
                              callback=None,
                              item=None,
                              custom_button=None,
                              channelpath=None):
        from core import config
        from core import channeltools
        from core import servertools
        import inspect
        if not os.path.isdir(
                os.path.join(config.get_data_path(), "settings_channels")):
            os.mkdir(os.path.join(config.get_data_path(), "settings_channels"))

        title = caption

        if type(custom_button) == dict:
            custom_button = {
                "label": custom_button.get("label", ""),
                "function": custom_button.get("function", ""),
                "visible": bool(custom_button.get("visible", True)),
                "close": bool(custom_button.get("close", False))
            }

        else:
            custom_button = None

        #Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal
        if not channelpath:
            channelpath = inspect.currentframe(
            ).f_back.f_back.f_code.co_filename
        channelname = os.path.basename(channelpath).replace(".py", "")
        ch_type = os.path.basename(os.path.dirname(channelpath))

        #Si no tenemos list_controls, hay que sacarlos del xml del canal
        if not list_controls:

            #Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools
            if os.path.join(config.get_runtime_path(),
                            "channels") in channelpath:

                # La llamada se hace desde un canal
                list_controls, default_values = channeltools.get_channel_controls_settings(
                    channelname)
                kwargs = {"channel": channelname}

            #Si la ruta del canal esta en la carpeta "servers", obtenemos los controles y valores mediante servertools
            elif os.path.join(config.get_runtime_path(),
                              "servers") in channelpath:
                # La llamada se hace desde un server
                list_controls, default_values = servertools.get_server_controls_settings(
                    channelname)
                kwargs = {"server": channelname}

            #En caso contrario salimos
            else:
                return None

        #Si no se pasan dict_values, creamos un dict en blanco
        if dict_values == None:
            dict_values = {}

        #Ponemos el titulo
        if caption == "":
            caption = str(config.get_localized_string(
                30100)) + " -- " + channelname.capitalize()
        elif caption.startswith('@') and unicode(caption[1:]).isnumeric():
            caption = config.get_localized_string(int(caption[1:]))

        JsonData = {}
        JsonData["action"] = "OpenConfig"
        JsonData["data"] = {}
        JsonData["data"]["title"] = self.kodi_labels_to_html(caption)
        JsonData["data"]["custom_button"] = custom_button
        JsonData["data"]["items"] = []

        # Añadir controles
        for c in list_controls:
            if not "default" in c: c["default"] = ""
            if not "color" in c: c["color"] = "auto"
            if not "label" in c: continue

            #Obtenemos el valor
            if not c["id"] in dict_values:
                if not callback:
                    c["value"] = config.get_setting(c["id"], **kwargs)
                else:
                    c["value"] = c["default"]

                dict_values[c["id"]] = c["value"]

            else:
                c["value"] = dict_values[c["id"]]

            # Translation
            if c['label'].startswith('@') and unicode(
                    c['label'][1:]).isnumeric():
                c['label'] = str(config.get_localized_string(c['label'][1:]))
            if c["label"].endswith(":"): c["label"] = c["label"][:-1]

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

            c["label"] = self.kodi_labels_to_html(c["label"])

            JsonData["data"]["items"].append(c)

        ID = self.send_message(JsonData)
        close = False

        while True:
            data = self.get_data(ID)
            if type(data) == dict:
                JsonData["action"] = "HideLoading"
                JsonData["data"] = {}
                self.send_message(JsonData)

                for v in data:
                    if data[v] == "true": data[v] = True
                    if data[v] == "false": data[v] = False
                    if unicode(data[v]).isnumeric(): data[v] = int(data[v])

                if callback and '.' in callback:
                    package, callback = callback.rsplit('.', 1)
                else:
                    package = '%s.%s' % (ch_type, channelname)

                cb_channel = None
                try:
                    cb_channel = __import__(package, None, None, [package])
                except ImportError:
                    logger.error('Imposible importar %s' % package)

                if callback:
                    # Si existe una funcion callback la invocamos ...
                    return getattr(cb_channel, callback)(item, data)
                else:
                    # si no, probamos si en el canal existe una funcion 'cb_validate_config' ...
                    try:
                        return getattr(cb_channel, 'cb_validate_config')(item,
                                                                         data)
                    except AttributeError:
                        # ... si tampoco existe 'cb_validate_config'...
                        for v in data:
                            config.set_setting(v, data[v], **kwargs)

            elif data == "custom_button":
                if '.' in callback:
                    package, callback = callback.rsplit('.', 1)
                else:
                    package = '%s.%s' % (ch_type, channelname)
                try:
                    cb_channel = __import__(package, None, None, [package])
                except ImportError:
                    logger.error('Imposible importar %s' % package)
                else:
                    return_value = getattr(
                        cb_channel, custom_button['function'])(item,
                                                               dict_values)
                    if custom_button["close"] == True:
                        return return_value
                    else:
                        JsonData["action"] = "custom_button"
                        JsonData["data"] = {}
                        JsonData["data"]["values"] = dict_values
                        JsonData["data"]["return_value"] = return_value
                        ID = self.send_message(JsonData)

            elif data == False:
                return None
示例#34
0
def init(channel, list_servers, list_quality):
    '''
    Comprueba la existencia de canal en el archivo de configuracion de Autoplay y si no existe lo añade. 
    Es necesario llamar a esta funcion al entrar a cualquier canal que incluya la funcion Autoplay.
    
    :param channel: (str) id del canal
    :param list_servers: (list) lista inicial de servidores validos para el canal. No es necesario incluirlos todos, 
        ya que la lista de servidores validos se ira actualizando dinamicamente.
    :param list_quality: (list) lista inicial de calidades validas para el canal. No es necesario incluirlas todas, 
        ya que la lista de calidades validas se ira actualizando dinamicamente.
    :return: (bool) True si la inicializacion ha sido correcta.
    '''
    logger.info()
    change = False
    result = True

    if not config.is_xbmc():
        platformtools.dialog_notification('AutoPlay ERROR',
                                          'Sólo disponible para XBMC/Kodi')
        result = False
    else:
        autoplay_path = os.path.join(config.get_data_path(),
                                     "settings_channels", 'autoplay_data.json')
        if os.path.exists(autoplay_path):
            autoplay_node = jsontools.get_node_from_data_json(
                'autoplay', "AUTOPLAY")
        else:
            change = True
            autoplay_node = {"AUTOPLAY": {}}

        if channel not in autoplay_node:
            change = True

            # Se comprueba que no haya calidades ni servidores duplicados
            list_servers = list(set(list_servers))
            list_quality = list(set(list_quality))

            # Creamos el nodo del canal y lo añadimos
            channel_node = {
                "servers": list_servers,
                "quality": list_quality,
                "settings": {
                    "active": False,
                    "custom_servers": False,
                    "custom_quality": False,
                    "priority": 0
                }
            }
            for n in range(1, 4):
                s = c = 0
                if len(list_servers) >= n:
                    s = n - 1
                if len(list_quality) >= n:
                    c = n - 1

                channel_node["settings"]["server_%s" % n] = s
                channel_node["settings"]["quality_%s" % n] = c

            autoplay_node[channel] = channel_node

        if change:
            result, json_data = jsontools.update_json_data(
                autoplay_node, 'autoplay', 'AUTOPLAY')

            if result:
                heading = "AutoPlay Disponible"
                msj = "Seleccione '<Configurar AutoPlay>' para activarlo."
                icon = 0
            else:
                heading = "Error al iniciar AutoPlay"
                msj = "Consulte su log para obtener mas información."
                icon = 1

            platformtools.dialog_notification(heading, msj, icon, sound=False)

    return result
示例#35
0
def searchSubtitle(item):

    if config.get_setting("subtitle_type") == 0:
        subtitlepath = config.get_setting("subtitlepath_folder")
        if subtitlepath == "":
            subtitlepath = os.path.join(config.get_data_path(), "subtitles")
            config.set_setting("subtitlepath_folder", subtitlepath)

    elif config.get_setting("subtitle_type") == 1:
        subtitlepath = config.get_setting("subtitlepath_keyboard")
        if subtitlepath == "":
            subtitlepath = os.path.join(config.get_data_path(), "subtitles")
            config.set_setting("subtitlepathkeyboard", subtitlepath)
        elif subtitlepath.startswith("http"):
            subtitlepath = config.get_setting("subtitlepath_folder")

    else:
        subtitlepath = config.get_setting("subtitlepath_folder")
    if subtitlepath == "":
        subtitlepath = os.path.join(config.get_data_path(), "subtitles")
        config.set_setting("subtitlepath_folder", subtitlepath)
    if not os.path.exists(subtitlepath):
        try:
            os.mkdir(subtitlepath)
        except:
            logger.error("error no se pudo crear path subtitulos")
            return

    path_movie_subt = xbmc.translatePath(os.path.join(subtitlepath, "Movies"))
    if not os.path.exists(path_movie_subt):
        try:
            os.mkdir(path_movie_subt)
        except:
            logger.error("error no se pudo crear el path Movies")
            return
    full_path_tvshow = ""
    path_tvshow_subt = xbmc.translatePath(os.path.join(subtitlepath,
                                                       "Tvshows"))
    if not os.path.exists(path_tvshow_subt):
        try:
            os.mkdir(path_tvshow_subt)
        except:
            logger.error("error no pudo crear el path Tvshows")
            return
    if item.show in item.title:
        title_new = title = urllib.unquote_plus(item.title)
    else:
        title_new = title = urllib.unquote_plus(item.show + " - " + item.title)
    path_video_temp = xbmc.translatePath(
        os.path.join(config.get_runtime_path(), "resources", "subtitle.mp4"))
    if not os.path.exists(path_video_temp):
        logger.error("error : no existe el video temporal de subtitulos")
        return
    #path_video_temp = xbmc.translatePath(os.path.join( ,video_temp + ".mp4" ))

    title_new = _normalize(title_new)
    tvshow_title, season, episode = regex_tvshow(False, title_new)
    if episode != "":
        full_path_tvshow = xbmc.translatePath(
            os.path.join(path_tvshow_subt, tvshow_title))
        if not os.path.exists(full_path_tvshow):
            os.mkdir(full_path_tvshow)  #title_new + ".mp4"
        full_path_video_new = xbmc.translatePath(
            os.path.join(full_path_tvshow,
                         "%s %sx%s.mp4" % (tvshow_title, season, episode)))
        logger.info(full_path_video_new)
        listitem = xbmcgui.ListItem(title_new,
                                    iconImage="DefaultVideo.png",
                                    thumbnailImage="")
        listitem.setInfo(
            "video", {
                "Title": title_new,
                "Genre": "Tv shows",
                "episode": int(episode),
                "season": int(season),
                "tvshowtitle": tvshow_title
            })

    else:
        full_path_video_new = xbmc.translatePath(
            os.path.join(path_movie_subt, title_new + ".mp4"))
        listitem = xbmcgui.ListItem(title,
                                    iconImage="DefaultVideo.png",
                                    thumbnailImage="")
        listitem.setInfo("video", {"Title": title_new, "Genre": "Movies"})

    import shutil

    try:
        shutil.copy(path_video_temp, full_path_video_new)
        copy = True
        logger.info("nuevo path =" + full_path_video_new)
        xbmc.sleep(2 * 1000)
        playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        playlist.clear()
        playlist.add(full_path_video_new, listitem)
        #xbmcPlayer = xbmc.Player(  xbmc.PLAYER_CORE_AUTO )
        xbmcPlayer = xbmc.Player()
        xbmcPlayer.play(playlist)

        #xbmctools.launchplayer(full_path_video_new,listitem)
    except:
        copy = False
        logger.error("Error : no se pudo copiar")

    xbmc.sleep(1 * 1000)

    if copy:
        if xbmc.Player().isPlayingVideo():
            xbmc.executebuiltin("RunScript(script.xbmc.subtitles)")
            while xbmc.Player().isPlayingVideo():
                continue

        xbmc.sleep(1 * 1000)
        os.remove(full_path_video_new)
        try:
            if full_path_tvshow != "":
                os.rmdir(full_path_tvshow)
        except OSError:
            pass
def get_video_url(page_url,
                  premium=False,
                  user="",
                  password="",
                  video_password=""):
    logger.info("streamondemand.servers.flashx url=" + page_url)

    # Lo pide una vez
    data = scrapertools.cache_page(page_url, headers=headers)
    # Si salta aviso, se carga la pagina de comprobacion y luego la inicial
    if "You try to access this video with Kodi" in data:
        url_reload = scrapertools.find_single_match(
            data, 'try to reload the page.*?href="([^"]+)"')
        url_reload = "http://www.flashx.tv" + url_reload[1:]
        try:
            data = scrapertools.cache_page(url_reload, headers=headers)
            data = scrapertools.cache_page(page_url, headers=headers)
        except:
            pass

    matches = scrapertools.find_multiple_matches(
        data, "<script type='text/javascript'>(.*?)</script>")
    for n, m in enumerate(matches):
        if m.startswith("eval"):
            try:
                m = jsunpack.unpack(m)
                fake = (scrapertools.find_single_match(m, "(\w{40,})") == "")
                if fake:
                    m = ""
                else:
                    break
            except:
                m = ""
    match = m

    if not "sources:[{file:" in match:
        page_url = page_url.replace("playvid-", "")
        data = scrapertools.downloadpageWithoutCookies(page_url)

        file_id = scrapertools.find_single_match(data, "'file_id', '([^']+)'")
        aff = scrapertools.find_single_match(data, "'aff', '([^']+)'")
        headers_c = [[
            'User-Agent',
            'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:46.0) Gecko/20100101 Firefox/46.0'
        ], ['Referer', page_url], ['Cookie', '; lang=1']]
        coding_url = scrapertools.find_single_match(
            data, '(?i)src="(http://www.flashx.tv/\w+.js\?[^"]+)"')
        if coding_url.endswith("="):
            coding_url += file_id
        coding = scrapertools.downloadpage(coding_url, headers=headers_c)

        data = scrapertools.downloadpage(page_url, headers=headers)
        flashx_id = scrapertools.find_single_match(
            data, 'name="id" value="([^"]+)"')
        fname = scrapertools.find_single_match(data,
                                               'name="fname" value="([^"]+)"')
        hash_f = scrapertools.find_single_match(data,
                                                'name="hash" value="([^"]+)"')
        post = 'op=download1&usr_login=&id=%s&fname=%s&referer=&hash=%s&imhuman=Proceed+to+video' % (
            flashx_id, urllib.quote(fname), hash_f)

        time.sleep(6)
        headers.append(['Referer', page_url])
        headers.append(
            ['Cookie', 'lang=1; file_id=%s; aff=%s' % (file_id, aff)])
        data = scrapertools.downloadpage('http://www.flashx.tv/dl',
                                         post=post,
                                         headers=headers)

        matches = scrapertools.find_multiple_matches(
            data, "(eval\(function\(p,a,c,k.*?)\s+</script>")
        for match in matches:
            try:
                match = jsunpack.unpack(match)
            except:
                match = ""
            if "file" in match:
                break

        if not match:
            match = data

    # Extrae la URL
    # {file:"http://f11-play.flashx.tv/luq4gfc7gxixexzw6v4lhz4xqslgqmqku7gxjf4bk43u4qvwzsadrjsozxoa/video1.mp4"}
    video_urls = []
    media_urls = scrapertools.find_multiple_matches(
        match, '\{file\:"([^"]+)",label:"([^"]+)"')
    subtitle = ""
    for media_url, label in media_urls:
        if media_url.endswith(".srt") and label == "Italian":
            try:
                from core import filetools
                data = scrapertools.downloadpage(media_url)
                subtitle = os.path.join(config.get_data_path(),
                                        'sub_flashx.srt')
                filetools.write(subtitle, data)
            except:
                import traceback
                logger.info(
                    "streamondemand.servers.flashx Error al descargar el subtítulo: "
                    + traceback.format_exc())

    for media_url, label in media_urls:
        if not media_url.endswith("png") and not media_url.endswith(".srt"):
            video_urls.append([
                "." + media_url.rsplit('.', 1)[1] + " [flashx]", media_url, 0,
                subtitle
            ])

    for video_url in video_urls:
        logger.info("streamondemand.servers.flashx %s - %s" %
                    (video_url[0], video_url[1]))

    return video_urls
def favoritos(item):
    user = config.get_setting("filesmonsteruser")
    password = config.get_setting("filesmonsterpassword")
    logger.info()
    name_file = os.path.splitext(os.path.basename(__file__))[0]
    fname = os.path.join(config.get_data_path(), "settings_channels",
                         name_file + "_favoritos.txt")
    fa = open(fname, 'a+')
    fa.close()
    f = open(fname, 'r')
    lines = f.readlines()
    f.close()
    itemlist = []
    post2 = "username="******"&password="******"http://filesmonster.com/api/public/login"
    data1 = scrapertools.cache_page(login_url, post=post2)
    partes1 = data1.split('"')
    estado = partes1[3]
    if estado != 'success':
        itemlist.append(
            Item(
                channel=item.channel,
                title=
                "No pudo accederse con tus datos de acceso de Filesmonster.com, introdúcelos en con el apartado figuración. Error: "
                + estado + data1))
    url_favoritos = "http://filesmonster.com/?favorites=1"
    data2 = scrapertools.cache_page(url_favoritos, post=post2)
    data2 = scrapertools.find_single_match(data2, 'favorites-table(.*?)pager')
    patronvideos = '<a href="([^"]+)">([^<]+)</a>.*?del=([^"]+)"'
    matches = re.compile(patronvideos, re.DOTALL).findall(data2)
    contador = 0
    for url, title, borrar in matches:
        contador = contador + 1
        imagen = ''
        for linea in lines:
            partes2 = linea.split("@")
            parte_url = partes2[0]
            parte_imagen = partes2[1]
            if (parte_url == url):
                imagen = parte_imagen.rstrip('\n').rstrip('\r')

        if url.find("?fid=") == -1:
            itemlist.append(
                Item(channel=item.channel,
                     action="play",
                     server="filesmonster",
                     title=title,
                     fulltitle=item.title,
                     url=url,
                     thumbnail=imagen,
                     folder=False))
        else:
            itemlist.append(
                Item(channel=item.channel,
                     action="detail",
                     server="filesmonster",
                     title=title,
                     fulltitle=title,
                     thumbnail=imagen,
                     url=url,
                     folder=True))
        itemlist.append(
            Item(channel=item.channel,
                 action="quitar_favorito",
                 title="(-) quitar de mis favoritos en filesmonster.com",
                 thumbnail=imagen,
                 url="http://filesmonster.com/?favorites=1&del=" + borrar,
                 plot=borrar))
        itemlist.append(Item(channel=item.channel, title="", folder=True))
    if contador == 0 and estado == 'success':
        itemlist.append(
            Item(
                channel=item.channel,
                title=
                "No tienes ningún favorito, navega por las diferentes fuentes y añádelos"
            ))
    return itemlist
示例#38
0
def numbered_for_tratk(show, season, episode):
    """
    Devuelve la temporada y episodio convertido para que se marque correctamente en tratk.tv

    :param show: Nombre de la serie a comprobar
    :type show: str
    :param season: Temporada que devuelve el scrapper
    :type season: int
    :param episode: Episodio que devuelve el scrapper
    :type episode: int
    :return: season, episode
    :rtype: int, int
    """
    logger.info("pelisalacarta.channels.animeflv_me numbered_for_tratk")
    show = show.lower()

    new_season = season
    new_episode = episode
    dict_series = {}

    name_file = os.path.splitext(os.path.basename(__file__))[0]
    fname = os.path.join(config.get_data_path(), "settings_channels", name_file + "_data.json")

    if os.path.isfile(fname):

        data = ""

        try:
            with open(fname, "r") as f:
                for line in f:
                    data += line
        except EnvironmentError:
            logger.info("ERROR al leer el archivo: {0}".format(fname))

        json_data = jsontools.load_json(data)

        if 'TVSHOW_RENUMBER' in json_data:
            dict_series = json_data['TVSHOW_RENUMBER']

        # ponemos en minusculas el key, ya que previamente hemos hecho lo mismo con show.
        for key in dict_series.keys():
            new_key = key.lower()
            if new_key != key:
                dict_series[new_key] = dict_series[key]
                del dict_series[key]

    if show in dict_series:
        logger.info("ha encontrado algo: {0}".format(dict_series[show]))

        if len(dict_series[show]['season_episode']) > 1:
            for row in dict_series[show]['season_episode']:

                if new_episode > row[1]:
                    new_episode -= row[1]
                    new_season = row[0]
                    break

        else:
            new_season = dict_series[show]['season_episode'][0][0]
            new_episode += dict_series[show]['season_episode'][0][1]

    logger.info("pelisalacarta.channels.animeflv_me numbered_for_tratk: {0}:{1}".format(new_season, new_episode))
    return new_season, new_episode
示例#39
0
    def show_channel_settings(self,
                              list_controls=None,
                              dict_values=None,
                              caption="",
                              callback=None,
                              item=None,
                              custom_button=None,
                              channelpath=None):
        from core import config
        from core import channeltools
        import inspect
        if not os.path.isdir(
                os.path.join(config.get_data_path(), "settings_channels")):
            os.mkdir(os.path.join(config.get_data_path(), "settings_channels"))

        title = caption

        if type(custom_button) == dict:
            custom_button = {
                "label": custom_button.get("label", ""),
                "function": custom_button.get("function", ""),
                "visible": bool(custom_button.get("visible", True)),
                "close": bool(custom_button.get("close", False))
            }

        else:
            custom_button = None

        #Obtenemos el canal desde donde se ha echo la llamada y cargamos los settings disponibles para ese canal
        if not channelpath:
            channelpath = inspect.currentframe(
            ).f_back.f_back.f_code.co_filename
        channelname = os.path.basename(channelpath).replace(".py", "")

        #Si no tenemos list_controls, hay que sacarlos del xml del canal
        if not list_controls:

            #Si la ruta del canal esta en la carpeta "channels", obtenemos los controles y valores mediante chaneltools
            if os.path.join(config.get_runtime_path(),
                            "channels") in channelpath:

                # La llamada se hace desde un canal
                list_controls, default_values = channeltools.get_channel_controls_settings(
                    channelname)

            #En caso contrario salimos
            else:
                return None

        #Si no se pasan dict_values, creamos un dict en blanco
        if dict_values == None:
            dict_values = {}

        #Ponemos el titulo
        if caption == "":
            caption = str(config.get_localized_string(
                30100)) + " -- " + channelname.capitalize()
        elif caption.startswith('@') and unicode(caption[1:]).isnumeric():
            caption = config.get_localized_string(int(caption[1:]))

        JsonData = {}
        JsonData["action"] = "OpenConfig"
        JsonData["data"] = {}
        JsonData["data"]["title"] = caption
        JsonData["data"]["custom_button"] = custom_button
        JsonData["data"]["items"] = []

        # Añadir controles
        for c in list_controls:
            if not "default" in c: c["default"] = ""
            if not "color" in c: c["color"] = "auto"
            if not "label" in c: continue

            #Obtenemos el valor
            if not c["id"] in dict_values:
                if not callback:
                    c["value"] = config.get_setting(c["id"], channelname)
                else:
                    c["value"] = c["default"]

            # Translation
            if c['label'].startswith('@') and unicode(
                    c['label'][1:]).isnumeric():
                c['label'] = str(config.get_localized_string(c['label'][1:]))
            if c["label"].endswith(":"): c["label"] = c["label"][:-1]

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

            JsonData["data"]["items"].append(c)

        ID = self.send_message(JsonData)
        close = False

        while True:
            data = self.get_data(ID)
            if type(data) == dict:
                JsonData["action"] = "HideLoading"
                JsonData["data"] = {}
                self.send_message(JsonData)

                for v in data:
                    if data[v] == "true": data[v] = True
                    if data[v] == "false": data[v] = False
                    if unicode(data[v]).isnumeric(): data[v] = int(data[v])

                if not callback:
                    for v in data:
                        config.set_setting(v, data[v], channelname)
                    return None

                else:
                    exec "from channels import " + channelname + " as cb_channel"
                    exec "return_value = cb_channel." + callback + "(item, data)"
                    return return_value

            elif data == "custom_button":
                try:
                    cb_channel = __import__('channels.%s' % channelname, None,
                                            None,
                                            ["channels.%s" % channelname])
                except ImportError:
                    logger.error('Imposible importar %s' % channelname)

                else:
                    return_value = getattr(cb_channel,
                                           custom_button['function'])(item)
                    if custom_button["close"] == True:
                        return return_value

            elif data == False:
                return None
示例#40
0
    def play_torrent(self, item):
        import time
        import os
        played = False

        #Importamos el cliente
        from btserver import Client

        #Iniciamos el cliente:
        c = Client(url=item.url,
                   is_playing_fnc=self.is_playing,
                   wait_time=None,
                   timeout=5,
                   temp_path=os.path.join(config.get_data_path(), "torrent"))

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

        #Mientras el progreso no sea cancelado ni el cliente cerrado
        while not progreso.iscanceled() and not c.closed:
            try:
                #Obtenemos el estado del torrent
                s = c.status

                #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)

                progreso.update(s.buffer, txt, txt2, txt3)

                time.sleep(1)

                #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
                    item.video_url = c.get_play_list()
                    item.server = "directo"

                    self.play_video(item)

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

                    #Y esperamos a que el reproductor se cierre
                    while self.is_playing():
                        time.sleep(1)

                    #Cuando este cerrado,  Volvemos a mostrar el dialogo
                    progreso = self.dialog_progress("Pelisalacarta - Torrent",
                                                    "Iniciando...")

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

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

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

        #Y cerramos el progreso
        progreso.close()

        return
示例#41
0
from core import servertools
from core.downloader import Downloader
from core import library
from core.item import Item
from platformcode import platformtools

STATUS_COLORS = {0: "orange", 1: "orange", 2: "green", 3: "red"}
STATUS_CODES = type("StatusCode", (), {
    "stoped": 0,
    "canceled": 1,
    "completed": 2,
    "error": 3
})
DOWNLOAD_LIST_PATH = config.get_setting("downloadlistpath")
DOWNLOAD_PATH = config.get_setting("downloadpath")
STATS_FILE = os.path.join(config.get_data_path(), "servers.json")

TITLE_FILE = "[COLOR %s][%i%%][/COLOR] %s"
TITLE_TVSHOW = "[COLOR %s][%i%%][/COLOR] %s [%s]"


def mainlist(item):
    logger.info()
    itemlist = []

    #Lista de archivos
    for file in sorted(filetools.listdir(DOWNLOAD_LIST_PATH)):
        #Saltamos todos los que no sean JSON
        if not file.endswith(".json"): continue

        #cargamos el item
示例#42
0
import xbmcplugin

import gdata.youtube
import gdata.youtube.service
from servers import youtube

from platformcode import xbmctools
from core import scrapertools
from core import logger
from core import config

import os
CHANNELNAME = "trailertools"

DEBUG = True
IMAGES_PATH = xbmc.translatePath( os.path.join( config.get_data_path(), 'resources' , 'images'  ) )

def mainlist(params,url,category):
    logger.info("[trailertools.py] mainlist")
    titulo = ""
    listavideos = GetTrailerbyKeyboard(titulo,category)
    if len(listavideos)>0:
        for video in listavideos:
            titulo = video[1]
            url        = video[0]
            thumbnail  = video[2]
            xbmctools.addnewvideo( "trailertools" , "youtubeplay" , category , "Directo" ,  titulo , url , thumbnail , "Ver Video" )
            
    xbmcplugin.setPluginCategory( handle=int( sys.argv[ 1 ] ), category=category )
    xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_NONE )
    xbmcplugin.endOfDirectory( handle=int( sys.argv[ 1 ] ), succeeded=True )        
示例#43
0
def run():
    logger.info("streamondemand.platformcode.launcher run")

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

        #Esto es para mantener la compatiblidad con el formato anterior...
        #Contretamente para que funcionen los STRM hasta que no se actualicen al nuevo formato
        except:
            params, fanart, channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, viewmode, category, show, password, hasContentDetails, contentTitle, contentThumbnail, contentPlot = extract_parameters(
            )
            item = Item(fanart=fanart,
                        channel=channel_name,
                        title=title,
                        fulltitle=fulltitle,
                        url=url,
                        thumbnail=thumbnail,
                        plot=plot,
                        action=action,
                        server=server,
                        extra=extra,
                        subtitle=subtitle,
                        viewmode=viewmode,
                        category=category,
                        show=show,
                        password=password,
                        hasContentDetails=hasContentDetails,
                        contentTitle=contentTitle,
                        contentThumbnail=contentThumbnail,
                        contentPlot=contentPlot)
    else:
        item = Item(action="selectchannel")
        params = ""

    logger.info(item.tostring())

    if config.get_setting('filter_servers') == 'true':
        server_white_list, server_black_list = set_server_list()

    try:
        # Default action: open channel and launch mainlist function
        if (item.action == "selectchannel"):
            import channelselector
            itemlist = channelselector.mainlist(params, item.url,
                                                item.category)
            from platformcode import xbmctools
            xbmctools.renderItems(itemlist, item)

        # Actualizar version
        elif (item.action == "update"):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info(
                    "streamondemand.platformcode.launcher Actualizacion automática desactivada"
                )

            #import channelselector as plugin
            #plugin.listchannels(params, url, category)
            if config.get_system_platform() != "xbox":
                import xbmc
                xbmc.executebuiltin("Container.Refresh")

        elif (item.action == "channeltypes"):
            import channelselector
            itemlist = channelselector.channeltypes(params, item.url,
                                                    item.category)
            from platformcode import xbmctools
            xbmctools.renderItems(itemlist, item)

        elif (item.action == "listchannels"):
            import channelselector
            itemlist = channelselector.listchannels(params, item.url,
                                                    item.category)
            from platformcode import xbmctools
            xbmctools.renderItems(itemlist, item)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:

            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") != "":

                    import xbmc
                    keyboard = xbmc.Keyboard("", "PIN para canales de adultos",
                                             True)
                    keyboard.doModal()

                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        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

            if item.action == "mainlist" and config.get_setting(
                    "updatechannels") == "true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(item.channel)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin", channel_name,
                                       config.get_localized_string(30063))
                except:
                    pass

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en streamondemand
            regular_channel_path = os.path.join(config.get_runtime_path(),
                                                'channels',
                                                item.channel + ".py")
            core_channel_path = os.path.join(config.get_runtime_path(), 'core',
                                             item.channel + ".py")
            logger.info(
                "streamondemand.platformcode.launcher regular_channel_path=%s"
                % regular_channel_path)
            logger.info(
                "streamondemand.platformcode.launcher core_channel_path=%s" %
                core_channel_path)

            if item.channel == "personal" or item.channel == "personal2" or item.channel == "personal3" or item.channel == "personal4" or item.channel == "personal5":
                import channels.personal as channel
            elif os.path.exists(regular_channel_path):
                exec "import channels." + item.channel + " as channel"
            elif os.path.exists(core_channel_path):
                exec "from core import " + item.channel + " as channel"

            logger.info(
                "streamondemand.platformcode.launcher running channel %s %s" %
                (channel.__name__, channel.__file__))

            generico = False
            # Esto lo he puesto asi porque el buscador puede ser generico o normal, esto estará asi hasta que todos los canales sean genericos
            if item.category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            if not generico:
                logger.info(
                    "streamondemand.platformcode.launcher xbmc native channel")
                if (item.action == "strm"):
                    from platformcode import xbmctools
                    xbmctools.playstrm(params, item.url, item.category)
                else:
                    exec "channel." + item.action + "(params, item.url, item.category)"
            else:
                logger.info(
                    "streamondemand.platformcode.launcher multiplatform channel"
                )
                '''
                if item.subtitle!="":
                    logger.info("streamondemand.platformcode.launcher Downloading subtitle file "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("streamondemand.platformcode.launcher No subtitle")
                '''
                from platformcode import xbmctools

                if item.action == "play":
                    logger.info("streamondemand.platformcode.launcher play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info(
                            "streamondemand.platformcode.launcher executing channel 'play' method"
                        )
                        itemlist = channel.play(item)
                        if len(itemlist) > 0:
                            item = itemlist[0]
                            xbmctools.play_video(item)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok("plugin",
                                                  "Niente da riprodurre")
                    else:
                        logger.info(
                            "streamondemand.platformcode.launcher no channel 'play' method, executing core method"
                        )
                        xbmctools.play_video(item)

                elif item.action == "strm_detail" or item.action == "play_from_library":
                    logger.info(
                        "streamondemand.platformcode.launcher play_from_library"
                    )

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")

                    logger.info("item.server=#" + item.server + "#")
                    # Ejecuta find_videos, del canal o común
                    if item.server != "":
                        try:
                            from servers import servertools
                            videourls = servertools.resolve_video_urls_for_playing(
                                server=item.server,
                                url=item.url,
                                video_password=item.video_password)
                            return videourls
                        except:
                            itemlist = []
                            pass
                    else:
                        try:
                            itemlist = channel.findvideos(item)
                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(
                                    itemlist, server_white_list,
                                    server_black_list)
                        except:
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)
                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(
                                    itemlist, server_white_list,
                                    server_black_list)

                    if len(itemlist) > 0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)

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

                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(
                            config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]

                        if seleccion == -1:
                            return
                    else:
                        elegido = item

                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" %
                                (item.title, item.subtitle))

                    from platformcode import xbmctools
                    logger.info("subtitle=" + item.subtitle)
                    xbmctools.play_video(item, strmfile=True)

                elif item.action == "add_pelicula_to_library":
                    logger.info(
                        "streamondemand.platformcode.launcher add_pelicula_to_library"
                    )
                    from platformcode import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary(titulo=item.fulltitle,
                                        url=item.url,
                                        thumbnail=item.thumbnail,
                                        server=item.server,
                                        plot=item.plot,
                                        canal=item.channel,
                                        category="Cine",
                                        Serie=item.show.strip(),
                                        verbose=False,
                                        accion="play_from_library",
                                        pedirnombre=False,
                                        subtitle=item.subtitle)

                elif item.action == "add_serie_to_library":
                    logger.info(
                        "streamondemand.platformcode.launcher add_serie_to_library, show=#"
                        + item.show + "#")
                    from platformcode import library
                    import xbmcgui

                    # Obtiene el listado desde el que se llamó
                    action = item.extra

                    # Esta marca es porque el item tiene algo más aparte en el atributo "extra"
                    if "###" in item.extra:
                        action = item.extra.split("###")[0]
                        item.extra = item.extra.split("###")[1]

                    exec "itemlist = channel." + action + "(item)"

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('streamondemand',
                                         'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info("[launcher.py] Total Episodios:" +
                                str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i * 100 / totalepisodes,
                                       'Añadiendo episodio...', item.title)
                        logger.info(
                            "streamondemand.platformcode.launcher add_serie_to_library, title="
                            + item.title)
                        if (pDialog.iscanceled()):
                            return

                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el que dice "Añadir esta serie..." o "Descargar esta serie..."
                            if item.action != "add_serie_to_library" and item.action != "download_all_episodes":
                                nuevos = nuevos + library.savelibrary(
                                    titulo=item.title,
                                    url=item.url,
                                    thumbnail=item.thumbnail,
                                    server=item.server,
                                    plot=item.plot,
                                    canal=item.channel,
                                    category="Series",
                                    Serie=item.show.strip(),
                                    verbose=False,
                                    accion="play_from_library",
                                    pedirnombre=False,
                                    subtitle=item.subtitle,
                                    extra=item.extra)
                        except IOError:

                            for line in sys.exc_info():
                                logger.error("%s" % line)
                            logger.info(
                                "streamondemand.platformcode.launcher Error al grabar el archivo "
                                + item.title)
                            errores = errores + 1

                    pDialog.close()

                    # Actualizacion de la biblioteca
                    itemlist = []
                    if errores > 0:
                        itemlist.append(
                            Item(
                                title=
                                "ERRORE, la serie NON si è aggiunta alla biblioteca o l'ha fatto in modo incompleto"
                            ))
                        logger.info("[launcher.py] No se pudo añadir " +
                                    str(errores) + " episodios")
                    else:
                        itemlist.append(
                            Item(title=
                                 "La serie è stata aggiunta alla biblioteca"))
                        logger.info("[launcher.py] Ningún error al añadir " +
                                    str(errores) + " episodios")

                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, item)

                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join(
                        config.get_library_path(), "series.xml")
                    if not os.path.exists(nombre_fichero_config_canal):
                        nombre_fichero_config_canal = os.path.join(
                            config.get_data_path(), "series.xml")

                    logger.info("nombre_fichero_config_canal=" +
                                nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open(nombre_fichero_config_canal, "w")
                    else:
                        f = open(nombre_fichero_config_canal, "r")
                        contenido = f.read()
                        f.close()
                        f = open(nombre_fichero_config_canal, "w")
                        f.write(contenido)
                    from platformcode import library
                    f.write(
                        library.title_to_folder_name(item.show) + "," +
                        item.url + "," + item.channel + "," + item.extra +
                        "\n")
                    f.close()

                elif item.action == "download_all_episodes":
                    download_all_episodes(item, channel)

                elif item.action == "search":
                    logger.info("streamondemand.platformcode.launcher search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item, tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, item)

                else:
                    logger.info(
                        "streamondemand.platformcode.launcher executing channel '"
                        + item.action + "' method")
                    if item.action != "findvideos":
                        exec "itemlist = channel." + item.action + "(item)"

                        #for item in itemlist:
                        #    logger.info("viemode="+item.viewmode)
                    else:

                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        if hasattr(channel, 'findvideos'):
                            exec "itemlist = channel." + item.action + "(item)"

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

                        # Si no funciona, lanza el método genérico para detectar vídeos
                        else:
                            logger.info(
                                "streamondemand.platformcode.launcher no channel 'findvideos' method, executing core method"
                            )
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)
                            if config.get_setting('filter_servers') == 'true':
                                itemlist = filtered_servers(
                                    itemlist, server_white_list,
                                    server_black_list)

                        from platformcode import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin

                    handle = sys.argv[1]
                    xbmcplugin.setContent(int(handle), "movies")

                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, item)

    except urllib2.URLError, e:
        import traceback
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)

        import xbmcgui
        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %d , Razon: %s" %
                        (e.reason[0], e.reason[1]))
            texto = config.get_localized_string(
                30050)  # "No se puede conectar con el sitio web"
            ok = ventana_error.ok("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado
        elif hasattr(e, 'code'):
            logger.info("codigo de error HTTP : %d" % e.code)
            texto = (
                config.get_localized_string(30051) % e.code
            )  # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok("plugin", texto)
示例#44
0
def addchannel(item):
    import os
    import time
    logger.info()

    tecleado = platformtools.dialog_input("", "Inserire l'URL")
    if not tecleado:
        return
    logger.info("url=%s" % tecleado)

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

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

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

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

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

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

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

    platformtools.dialog_ok(
        "Successo", "Aggiornamento/installazione eseguita correttamente")
示例#45
0
    import xbmc

CHANNELNAME = "favoritos"
DEBUG = True
BOOKMARK_PATH = config.get_setting("bookmarkpath")

if not BOOKMARK_PATH.upper().startswith("SMB://"):
    if BOOKMARK_PATH.startswith("special://") and config.is_xbmc():
        logger.info(
            "tvalacarta.channels.favoritos Se esta utilizando el protocolo 'special'"
        )
        # Se usa "translatePath" para que convierta la ruta a la completa.
        # Usando esto se evitan todos los problemas relacionados con "special"
        BOOKMARK_PATH = xbmc.translatePath(config.get_setting("bookmarkpath"))
    if BOOKMARK_PATH == "":
        BOOKMARK_PATH = os.path.join(config.get_data_path(), "bookmarks")
    if not os.path.exists(BOOKMARK_PATH):
        logger.debug("[favoritos.py] Path de bookmarks no existe, se crea: " +
                     BOOKMARK_PATH)
        os.mkdir(BOOKMARK_PATH)

logger.info("tvalacarta.core.favoritos path=" + BOOKMARK_PATH)


def isGeneric():
    return True


def mainlist(item):
    logger.info("tvalacarta.core.favoritos mainlist")
    itemlist = []
示例#46
0
def episodios(item):
    logger.info("streamondemand.mondolunatico episodios")

    itemlist = []

    # Descarga la página
    data = scrapertools.cache_page(item.url, headers=headers)

    html = []

    for i in range(2):
        patron = 'href="(https?://www\.keeplinks\.eu/p92/([^"]+))"'
        matches = re.compile(patron, re.DOTALL).findall(data)
        for keeplinks, id in matches:
            _headers = list(headers)
            _headers.append([
                'Cookie', 'flag[' + id + ']=1; defaults=1; nopopatall=' +
                str(int(time.time()))
            ])
            _headers.append(['Referer', keeplinks])

            html.append(scrapertools.cache_page(keeplinks, headers=_headers))

        patron = r'="(%s/pass/index\.php\?ID=[^"]+)"' % host
        matches = re.compile(patron, re.DOTALL).findall(data)
        for scrapedurl in matches:
            tmp = scrapertools.cache_page(scrapedurl, headers=headers)

            if 'CaptchaSecurityImages.php' in tmp:
                # Descarga el captcha
                img_content = scrapertools.cache_page(captcha_url,
                                                      headers=headers)

                captcha_fname = os.path.join(config.get_data_path(),
                                             __channel__ + "captcha.img")
                with open(captcha_fname, 'wb') as ff:
                    ff.write(img_content)

                from platformcode import captcha

                keyb = captcha.Keyboard(heading='', captcha=captcha_fname)
                keyb.doModal()
                if keyb.isConfirmed():
                    captcha_text = keyb.getText()
                    post_data = urllib.urlencode({
                        'submit1': 'Invia',
                        'security_code': captcha_text
                    })
                    tmp = scrapertools.cache_page(scrapedurl,
                                                  post=post_data,
                                                  headers=headers)

                try:
                    os.remove(captcha_fname)
                except:
                    pass

            html.append(tmp)

        data = '\n'.join(html)

    encontrados = set()

    patron = '<p><a href="([^"]+?)">([^<]+?)</a></p>'
    matches = re.compile(patron, re.DOTALL).findall(data)
    for scrapedurl, scrapedtitle in matches:
        scrapedtitle = scrapedtitle.split('/')[-1]
        if not scrapedtitle or scrapedtitle in encontrados: continue
        encontrados.add(scrapedtitle)
        scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)
        itemlist.append(
            Item(channel=__channel__,
                 extra=item.extra,
                 action="findvideos",
                 title=scrapedtitle,
                 url=scrapedurl,
                 thumbnail=item.thumbnail,
                 fulltitle=item.fulltitle,
                 show=item.show))

    patron = '<a href="([^"]+)" target="_blank" class="selecttext live">([^<]+)</a>'
    matches = re.compile(patron, re.DOTALL).findall(data)
    for scrapedurl, scrapedtitle in matches:
        scrapedtitle = scrapedtitle.split('/')[-1]
        if not scrapedtitle or scrapedtitle in encontrados: continue
        encontrados.add(scrapedtitle)
        scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle)
        itemlist.append(
            Item(channel=__channel__,
                 extra=item.extra,
                 action="findvideos",
                 title=scrapedtitle,
                 url=scrapedurl,
                 thumbnail=item.thumbnail,
                 fulltitle=item.fulltitle,
                 show=item.show))

    return itemlist
示例#47
0
import time

from core import scrapertools
from core import config
from core import filetools
from core import logger
from core.item import Item
from platformcode import platformtools

try:
    # Fijamos la ruta a favourites.xml
    if config.is_xbmc():
        import xbmc
        FAVOURITES_PATH = xbmc.translatePath("special://profile/favourites.xml")
    else:
        FAVOURITES_PATH = os.path.join(config.get_data_path(), "favourites.xml")
except:
    import traceback
    logger.error(traceback.format_exc())


def mainlist(item):
    logger.info()
    itemlist = []

    for name, thumb, data in read_favourites():
        if "plugin://plugin.video.%s/?" % config.PLUGIN_NAME in data:
            url = scrapertools.find_single_match(data, 'plugin://plugin.video.%s/\?([^;]*)' % config.PLUGIN_NAME)\
                .replace("&quot", "")

            item = Item().fromurl(url)
示例#48
0
# -*- coding: iso-8859-1 -*-
#------------------------------------------------------------
# pelisalacarta - XBMC Plugin
# Conector para Metadivx
# http://blog.tvalacarta.info/plugin-xbmc/pelisalacarta/
#------------------------------------------------------------

import urlparse, urllib2, urllib, re

from core import scrapertools
from core import logger
from core import config
from core import unpackerjs

import os
COOKIEFILE = os.path.join(config.get_data_path(), "cookies.lwp")


def geturl(urlvideo):
    logger.info("[metadivx.py] url=" + urlvideo)
    # ---------------------------------------
    #  Inicializa la libreria de las cookies
    # ---------------------------------------
    ficherocookies = COOKIEFILE
    try:
        os.remove(ficherocookies)
    except:
        pass
    # the path and filename to save your cookies in

    cj = None
示例#49
0
def delete_cache(url):
    folder = filetools.join(config.get_data_path(), 'thumbs_copiapop')
    filetools.rmdirtree(folder)
    if config.is_xbmc():
        import xbmc
        xbmc.executebuiltin("Container.Refresh")
def clear_saved_searches(item):
    f = open(os.path.join(config.get_data_path(), "saved_searches.txt"), "w")
    f.write("")
    f.close()
示例#51
0
def listado(item):
    logger.info()
    itemlist = []

    data_thumb = httptools.downloadpage(item.url, item.post.replace("Mode=List", "Mode=Gallery")).data
    if not item.post:
        data_thumb = ""
        item.url = item.url.replace("/gallery,", "/list,")

    data = httptools.downloadpage(item.url, item.post).data
    data = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|<br>", "", data)

    folder = filetools.join(config.get_data_path(), 'thumbs_copiapop')
    patron = '<div class="size">(.*?)</div></div></div>'
    bloques = scrapertools.find_multiple_matches(data, patron)
    for block in bloques:
        if "adult_info" in block and not adult_content:
            continue
        size = scrapertools.find_single_match(block, '<p>([^<]+)</p>')
        scrapedurl, scrapedtitle = scrapertools.find_single_match(block, '<div class="name"><a href="([^"]+)".*?>([^<]+)<')
        scrapedthumbnail = scrapertools.find_single_match(block, "background-image:url\('([^']+)'")
        if scrapedthumbnail:
            try:
                thumb = scrapedthumbnail.split("-", 1)[0].replace("?", "\?")
                if data_thumb:
                    url_thumb = scrapertools.find_single_match(data_thumb, "(%s[^']+)'" % thumb)
                else:
                    url_thumb = scrapedthumbnail
                scrapedthumbnail = filetools.join(folder, "%s.jpg" % url_thumb.split("e=", 1)[1][-20:])
            except:
                scrapedthumbnail = ""

        if scrapedthumbnail:
            t = threading.Thread(target=download_thumb, args=[scrapedthumbnail, url_thumb])
            t.setDaemon(True) 
            t.start()

        else:
            scrapedthumbnail = item.extra + "/img/file_types/gallery/movie.png"

        scrapedurl = item.extra + scrapedurl
        title = "%s (%s)" % (scrapedtitle, size)
        if "adult_info" in block:
            title += " [COLOR %s][+18][/COLOR]" % color4
        plot = scrapertools.find_single_match(block, '<div class="desc">(.*?)</div>')
        if plot:
            plot = scrapertools.decodeHtmlentities(plot)

        new_item = Item(channel=item.channel, action="findvideos", title=title, url=scrapedurl,
                        thumbnail=scrapedthumbnail, contentTitle=scrapedtitle, text_color=color2,
                        extra=item.extra, infoLabels={'plot': plot}, post=item.post)
        if item.post:
            try:
                new_item.folderurl, new_item.foldername = scrapertools.find_single_match(block, '<p class="folder"><a href="([^"]+)".*?>([^<]+)<')
            except:
                pass
        else:
            new_item.folderurl = item.url.rsplit("/", 1)[0]
            new_item.foldername = item.foldername
            new_item.fanart = item.thumbnail

        itemlist.append(new_item)

    next_page = scrapertools.find_single_match(data, '<div class="pageSplitterBorder" data-nextpage-number="([^"]+)"')
    if next_page:
        if item.post:
            post = re.sub(r'pageNumber=(\d+)', "pageNumber="+next_page, item.post)
            url = item.url
        else:
            url = re.sub(r',\d+\?ref=pager', ",%s?ref=pager" % next_page, item.url)
            post = ""
        itemlist.append(Item(channel=item.channel, action="listado", title=">> Página Siguiente (%s)" % next_page,
                             url=url, post=post, extra=item.extra))

    return itemlist
示例#52
0
def colecciones(item):
    logger.info()
    from core import jsontools
    itemlist = []

    usuario = False
    data = httptools.downloadpage(item.url).data
    if "Ver colecciones del usuario" not in item.title and not item.index:
        data = jsontools.load_json(data)["Data"]
        content = data["Content"]
        content = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|<br>", "", content)
    else:
        usuario = True
        if item.follow:
            content = scrapertools.find_single_match(data, 'id="followed_collections"(.*?)<div id="recommended_collections"')
        else:
            content = scrapertools.find_single_match(data, '<div id="collections".*?<div class="collections_list(.*?)<div class="collections_list')
        content = re.sub(r"\n|\r|\t|\s{2}|&nbsp;|<br>", "", content)

    patron = '<a class="name" href="([^"]+)".*?>([^<]+)<.*?src="([^"]+)".*?<p class="info">(.*?)</p>'
    matches = scrapertools.find_multiple_matches(content, patron)

    index = ""
    if item.index and item.index != "0":
        matches = matches[item.index:item.index + 20]
        if len(matches) > item.index + 20:
            index = item.index + 20
    elif len(matches) > 20:
        matches = matches[:20]
        index = 20

    folder = filetools.join(config.get_data_path(), 'thumbs_copiapop')
    for url, scrapedtitle, thumb, info in matches:
        url = item.extra + url + "/gallery,1,1?ref=pager"
        title = "%s  (%s)" % (scrapedtitle, scrapertools.htmlclean(info))
        try:
            scrapedthumbnail = filetools.join(folder, "%s.jpg" % thumb.split("e=", 1)[1][-20:])
        except:
            try:
                scrapedthumbnail = filetools.join(folder, "%s.jpg" % thumb.split("/thumbnail/", 1)[1][-20:])
                thumb = thumb.replace("/thumbnail/", "/")
            except:
                scrapedthumbnail = ""
        if scrapedthumbnail:
            t = threading.Thread(target=download_thumb, args=[scrapedthumbnail, thumb])
            t.setDaemon(True) 
            t.start()
        else:
            scrapedthumbnail = thumb

        itemlist.append(Item(channel=item.channel, action="listado", title=title, url=url,
                             thumbnail=scrapedthumbnail, text_color=color2, extra=item.extra,
                             foldername=scrapedtitle))

    if not usuario and data.get("NextPageUrl"):
        url = item.extra + data["NextPageUrl"]
        itemlist.append(item.clone(title=">> Página Siguiente", url=url, text_color=""))
    elif index:
        itemlist.append(item.clone(title=">> Página Siguiente", url=item.url, index=index, text_color=""))

    return itemlist
示例#53
0
def run():
    logger.info("[launcher.py] run")
    
    # Test if all the required directories are created
    config.verify_directories_created()
    
    # Extract parameters from sys.argv
    params, channel_name, title, channel_title, show_title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password = extract_parameters()
    logger.info("[launcher.py] channel_name=%s, title=%s, fulltitle=%s, url=%s, thumbnail=%s, plot=%s, action=%s, server=%s, extra=%s, subtitle=%s, category=%s, show=%s, password=%s" % (channel_name, title, fulltitle, url, thumbnail, plot, action, server, extra, subtitle, category, show, password))

    if action=="":
        return

    try:
        # Accion por defecto - elegir canal
        if ( action=="selectchannel" ):
            # Borra el fichero de las cookies para evitar problemas con MV
            #ficherocookies = os.path.join( config.get_data_path(), 'cookies.lwp' )
            #if os.path.exists(ficherocookies):
            #    os.remove(ficherocookies)
            
            if config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel("channelselector")

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("tvalacarta",config.get_localized_string(30064))
                except:
                    pass

            import channelselector as plugin
            plugin.mainlist(params, url, category)

        # Actualizar version
        elif ( action=="update" ):
            try:
                from core import updater
                updater.update(params)
            except ImportError:
                logger.info("[launcher.py] Actualizacion automática desactivada")

            #import channelselector as plugin
            #plugin.listchannels(params, url, category)
            if config.get_system_platform()!="xbox":
                import xbmc
                xbmc.executebuiltin( "Container.Refresh" )

        elif (action=="channeltypes"):
            import channelselector as plugin
            plugin.channeltypes(params,url,category)

        elif (action=="listchannels"):
            import channelselector as plugin
            plugin.listchannels(params,url,category)

        # El resto de acciones vienen en el parámetro "action", y el canal en el parámetro "channel"
        else:
            if action=="mainlist" and config.get_setting("updatechannels")=="true":
                try:
                    from core import updater
                    actualizado = updater.updatechannel(channel_name)

                    if actualizado:
                        import xbmcgui
                        advertencia = xbmcgui.Dialog()
                        advertencia.ok("plugin",channel_name,config.get_localized_string(30063))
                except:
                    pass

            # La acción puede estar en el core, o ser un canal regular. El buscador es un canal especial que está en pelisalacarta
            regular_channel_path = os.path.join( config.get_runtime_path() , 'channels' , channel_name+".py" )
            core_channel_path = os.path.join( config.get_runtime_path(), 'core' , channel_name+".py" )
            logger.info("[launcher.py] regular_channel_path=%s" % regular_channel_path)
            logger.info("[launcher.py] core_channel_path=%s" % core_channel_path)

            if channel_name=="buscador":
                import pelisalacarta.buscador as channel
            elif os.path.exists( regular_channel_path ):
                exec "import channels."+channel_name+" as channel"
            elif os.path.exists( core_channel_path ):
                exec "from core import "+channel_name+" as channel"

            logger.info("[launcher.py] running channel %s %s" % (channel.__name__ , channel.__file__))

            generico = False
            # Esto lo he puesto asi porque el buscador puede ser generico o normal, esto estará asi hasta que todos los canales sean genericos 
            if category == "Buscador_Generico":
                generico = True
            else:
                try:
                    generico = channel.isGeneric()
                except:
                    generico = False

            if not generico:
                logger.info("[launcher.py] xbmc native channel")
                if (action=="strm"):
                    from platformcode import xbmctools
                    xbmctools.playstrm(params, url, category)
                else:
                    exec "channel."+action+"(params, url, category)"
            else:            
                logger.info("[launcher.py] multiplatform channel")
                from core.item import Item
                item = Item(channel=channel_name, title=title , channel_title=channel_title , show_title=show_title , fulltitle=fulltitle, url=url, thumbnail=thumbnail , plot=plot , server=server, category=category, extra=extra, subtitle=subtitle, show=show, password=password)
                
                '''
                if item.subtitle!="":
                    logger.info("[launcher.py] Downloading subtitle file "+item.subtitle)
                    from core import downloadtools
                    
                    ficherosubtitulo = os.path.join( config.get_data_path() , "subtitulo.srt" )
                    if os.path.exists(ficherosubtitulo):
                        os.remove(ficherosubtitulo)

                    downloadtools.downloadfile(item.subtitle, ficherosubtitulo )
                    config.set_setting("subtitulo","true")
                else:
                    logger.info("[launcher.py] No subtitle")
                '''
                from platformcode import xbmctools

                if action=="play":
                    logger.info("[launcher.py] play")
                    # Si el canal tiene una acción "play" tiene prioridad
                    if hasattr(channel, 'play'):
                        logger.info("[launcher.py] executing channel 'play' method")
                        itemlist = channel.play(item)
                        if len(itemlist)>0:
                            item = itemlist[0]
                            xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle)
                        else:
                            import xbmcgui
                            ventana_error = xbmcgui.Dialog()
                            ok = ventana_error.ok ("plugin", "No hay nada para reproducir")
                    else:
                        logger.info("[launcher.py] no channel 'play' method, executing core method")
                        xbmctools.play_video(channel=channel_name, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=item.fulltitle)

                elif action=="strm_detail" or action=="play_from_library":
                    logger.info("[launcher.py] play_from_library")

                    fulltitle = item.show + " " + item.title
                    elegido = Item(url="")                    

                    logger.info("item.server=#"+item.server+"#")
                    # Ejecuta find_videos, del canal o común
                    try:
                        itemlist = channel.findvideos(item)
                    except:
                        from servers import servertools
                        itemlist = servertools.find_video_items(item)

                    if len(itemlist)>0:
                        #for item2 in itemlist:
                        #    logger.info(item2.title+" "+item2.subtitle)
    
                        # El usuario elige el mirror
                        opciones = []
                        for item in itemlist:
                            opciones.append(item.title)
                    
                        import xbmcgui
                        dia = xbmcgui.Dialog()
                        seleccion = dia.select(config.get_localized_string(30163), opciones)
                        elegido = itemlist[seleccion]
    
                        if seleccion==-1:
                            return
                    else:
                        elegido = item
                
                    # Ejecuta el método play del canal, si lo hay
                    try:
                        itemlist = channel.play(elegido)
                        item = itemlist[0]
                    except:
                        item = elegido
                    logger.info("Elegido %s (sub %s)" % (item.title,item.subtitle))
                    
                    from platformcode import xbmctools
                    logger.info("subtitle="+item.subtitle)
                    xbmctools.play_video(strmfile=True, channel=item.channel, server=item.server, url=item.url, category=item.category, title=item.title, thumbnail=item.thumbnail, plot=item.plot, extra=item.extra, subtitle=item.subtitle, video_password = item.password, fulltitle=fulltitle)

                elif action=="add_pelicula_to_library":
                    logger.info("[launcher.py] add_pelicula_to_library")
                    from platformcode import library
                    # Obtiene el listado desde el que se llamó
                    library.savelibrary( titulo=item.fulltitle , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Cine" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )

                elif action=="add_serie_to_library":
                    logger.info("[launcher.py] add_serie_to_library")
                    from platformcode import library
                    import xbmcgui
                
                    # Obtiene el listado desde el que se llamó
                    action = item.extra
                    exec "itemlist = channel."+action+"(item)"

                    # Progreso
                    pDialog = xbmcgui.DialogProgress()
                    ret = pDialog.create('pelisalacarta', 'Añadiendo episodios...')
                    pDialog.update(0, 'Añadiendo episodio...')
                    totalepisodes = len(itemlist)
                    logger.info ("[launcher.py] Total Episodios:"+str(totalepisodes))
                    i = 0
                    errores = 0
                    nuevos = 0
                    for item in itemlist:
                        i = i + 1
                        pDialog.update(i*100/totalepisodes, 'Añadiendo episodio...',item.title)
                        if (pDialog.iscanceled()):
                            return
                
                        try:
                            #(titulo="",url="",thumbnail="",server="",plot="",canal="",category="Cine",Serie="",verbose=True,accion="strm",pedirnombre=True):
                            # Añade todos menos el último (el que dice "Añadir esta serie...")
                            if i<len(itemlist):
                                nuevos = nuevos + library.savelibrary( titulo=item.title , url=item.url , thumbnail=item.thumbnail , server=item.server , plot=item.plot , canal=item.channel , category="Series" , Serie=item.show.strip() , verbose=False, accion="play_from_library", pedirnombre=False, subtitle=item.subtitle )
                        except IOError:
                            import sys
                            for line in sys.exc_info():
                                logger.error( "%s" % line )
                            logger.info("[launcher.py]Error al grabar el archivo "+item.title)
                            errores = errores + 1
                        
                    pDialog.close()
                    
                    # Actualizacion de la biblioteca
                    itemlist=[]
                    if errores > 0:
                        itemlist.append(Item(title="ERROR, la serie NO se ha añadido a la biblioteca o lo ha hecho incompleta"))
                        logger.info ("[launcher.py] No se pudo añadir "+str(errores)+" episodios")
                    else:
                        itemlist.append(Item(title="La serie se ha añadido a la biblioteca"))
                        logger.info ("[launcher.py] Ningún error al añadir "+str(errores)+" episodios")
                    
                    # FIXME:jesus Comentado porque no funciona bien en todas las versiones de XBMC
                    #library.update(totalepisodes,errores,nuevos)
                    xbmctools.renderItems(itemlist, params, url, category)
                    
                    #Lista con series para actualizar
                    nombre_fichero_config_canal = os.path.join( config.get_data_path() , "series.xml" )
                    logger.info("nombre_fichero_config_canal="+nombre_fichero_config_canal)
                    if not os.path.exists(nombre_fichero_config_canal):
                        f = open( nombre_fichero_config_canal , "w" )
                    else:
                        f = open( nombre_fichero_config_canal , "r" )
                        contenido = f.read()
                        f.close()
                        f = open( nombre_fichero_config_canal , "w" )
                        f.write(contenido)
                    f.write(item.show+","+item.url+","+item.channel+"\n")
                    f.close();

                elif action.startswith("serie_options##"):
                    from core import suscription
                    import xbmcgui
                    dia = xbmcgui.Dialog()
                    opciones = []

                    suscription_item = Item(channel=item.channel, title=item.show, url=item.url, action=action.split("##")[1], extra=item.extra, plot=item.plot, show=item.show, thumbnail=item.thumbnail)

                    if not suscription.already_suscribed(suscription_item):
                        opciones.append("Suscribirme a esta serie")
                    else:
                        opciones.append("Quitar suscripción a esta serie")

                    #opciones.append("Añadir esta serie a favoritos")
                    opciones.append("Descargar todos los episodios")
                    seleccion = dia.select("Elige una opción", opciones) # "Elige una opción"

                    if seleccion==0:
                        if not suscription.already_suscribed(suscription_item):
                            suscription.append_suscription(suscription_item)

                            yes_pressed = xbmcgui.Dialog().yesno( "tvalacarta" , "Suscripción a \""+suscription_item.title+"\" creada" , "¿Quieres descargar los vídeos existentes ahora?" )

                            if yes_pressed:
                                download_all_episodes(suscription_item,channel)

                        else:
                            suscription.remove_suscription(suscription_item)
                            xbmcgui.Dialog().ok( "tvalacarta" , "Suscripción a \""+suscription_item.title+"\" eliminada" , "Los vídeos que hayas descargado se mantienen" )

                    elif seleccion==1:
                        download_all_episodes(suscription_item,channel)

                    '''
                    elif seleccion==1:
                        from core import favoritos
                        from core import downloadtools
                        import xbmc

                        keyboard = xbmc.Keyboard(downloadtools.limpia_nombre_excepto_1(item.show)+" ["+item.channel+"]")
                        keyboard.doModal()
                        if keyboard.isConfirmed():
                            title = keyboard.getText()
                            favoritos.savebookmark(titulo=title,url=item.url,thumbnail=item.thumbnail,server="",plot=item.plot,fulltitle=title)
                            advertencia = xbmcgui.Dialog()
                            resultado = advertencia.ok(config.get_localized_string(30102) , title , config.get_localized_string(30108)) # 'se ha añadido a favoritos'
                        return
                    '''

                elif action=="search":
                    logger.info("[launcher.py] search")
                    import xbmc
                    keyboard = xbmc.Keyboard("")
                    keyboard.doModal()
                    if (keyboard.isConfirmed()):
                        tecleado = keyboard.getText()
                        #tecleado = tecleado.replace(" ", "+")
                        itemlist = channel.search(item,tecleado)
                    else:
                        itemlist = []
                    xbmctools.renderItems(itemlist, params, url, category)

                else:
                    logger.info("[launcher.py] executing channel '"+action+"' method")
                    if action!="findvideos":
                        exec "itemlist = channel."+action+"(item)"
                    else:
                        # Intenta ejecutar una posible funcion "findvideos" del canal
                        try:
                            exec "itemlist = channel."+action+"(item)"
                        # Si no funciona, lanza el método genérico para detectar vídeos
                        except:
                            logger.info("[launcher.py] no channel 'findvideos' method, executing core method")
                            from servers import servertools
                            itemlist = servertools.find_video_items(item)
                        from core import subtitletools
                        subtitletools.saveSubtitleName(item)

                    # Activa el modo biblioteca para todos los canales genéricos, para que se vea el argumento
                    import xbmcplugin
                    import sys
                    handle = sys.argv[1]
                    xbmcplugin.setContent(int( handle ),"movies")
                    
                    # Añade los items a la lista de XBMC
                    xbmctools.renderItems(itemlist, params, url, category)

    except urllib2.URLError,e:
        import traceback
        import sys
        from pprint import pprint
        exc_type, exc_value, exc_tb = sys.exc_info()
        lines = traceback.format_exception(exc_type, exc_value, exc_tb)
        for line in lines:
            line_splits = line.split("\n")
            for line_split in line_splits:
                logger.error(line_split)
        import xbmcgui
        ventana_error = xbmcgui.Dialog()
        # Agarra los errores surgidos localmente enviados por las librerias internas
        if hasattr(e, 'reason'):
            logger.info("Razon del error, codigo: %d , Razon: %s" %(e.reason[0],e.reason[1]))
            texto = config.get_localized_string(30050) # "No se puede conectar con el sitio web"
            ok = ventana_error.ok ("plugin", texto)
        # Agarra los errores con codigo de respuesta del servidor externo solicitado     
        elif hasattr(e,'code'):
            logger.info("codigo de error HTTP : %d" %e.code)
            texto = (config.get_localized_string(30051) % e.code) # "El sitio web no funciona correctamente (error http %d)"
            ok = ventana_error.ok ("plugin", texto)    
示例#54
0
import urllib2
import urlparse
import cookielib
import os
import time
from StringIO import StringIO
import gzip
from core import logger
from core import config
from threading import Lock
from core.cloudflare import Cloudflare

cookies_lock = Lock()

cj = cookielib.MozillaCookieJar()
ficherocookies = os.path.join(config.get_data_path(), "cookies.dat")

# Headers por defecto, si no se especifica nada
default_headers = dict()
default_headers[
    "User-Agent"] = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0"
default_headers[
    "Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
default_headers["Accept-Language"] = "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3"
default_headers["Accept-Charset"] = "UTF-8"
default_headers["Accept-Encoding"] = "gzip"


def get_url_headers(url):
    logger.info()
    domain_cookies = cj._cookies.get("." + urlparse.urlparse(url)[1],
示例#55
0
def get_video_url(page_url,
                  premium=False,
                  user="",
                  password="",
                  video_password=""):
    logger.info("url=" + page_url)

    # Lo pide una vez
    data = httptools.downloadpage(page_url, cookies=False).data
    # Si salta aviso, se carga la pagina de comprobacion y luego la inicial
    if "You try to access this video with Kodi" in data:
        url_reload = scrapertools.find_single_match(
            data, 'try to reload the page.*?href="([^"]+)"')
        url_reload = "http://www.flashx.tv" + url_reload[1:]
        try:
            data = httptools.downloadpage(url_reload, cookies=False).data
            data = httptools.downloadpage(page_url, cookies=False).data
        except:
            pass

    matches = scrapertools.find_multiple_matches(
        data, "<script type='text/javascript'>(.*?)</script>")
    for n, m in enumerate(matches):
        if m.startswith("eval"):
            try:
                m = jsunpack.unpack(m)
                fake = (scrapertools.find_single_match(m, "(\w{40,})") == "")
                if fake:
                    m = ""
                else:
                    break
            except:
                m = ""
    match = m
    if "sources:[{file:" not in match:
        page_url = page_url.replace("playvid-", "")

        headers = {
            'Host': 'www.flashx.tv',
            'User-Agent':
            'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.137 Safari/537.36',
            'Accept':
            'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Accept-Encoding': 'gzip, deflate, br',
            'Connection': 'keep-alive',
            'Upgrade-Insecure-Requests': '1',
            'Cookie': ''
        }
        data = httptools.downloadpage(page_url,
                                      headers=headers,
                                      replace_headers=True).data
        flashx_id = scrapertools.find_single_match(
            data, 'name="id" value="([^"]+)"')
        fname = scrapertools.find_single_match(data,
                                               'name="fname" value="([^"]+)"')
        hash_f = scrapertools.find_single_match(data,
                                                'name="hash" value="([^"]+)"')
        post = 'op=download1&usr_login=&id=%s&fname=%s&referer=&hash=%s&imhuman=Proceed+to+video' % (
            flashx_id, urllib.quote(fname), hash_f)
        wait_time = scrapertools.find_single_match(data,
                                                   "<span id='xxc2'>(\d+)")

        file_id = scrapertools.find_single_match(data, "'file_id', '([^']+)'")
        coding_url = 'https://files.fx.fastcontentdelivery.com/jquery2.js?fx=%s' % base64.encodestring(
            file_id)
        headers['Host'] = "files.fx.fastcontentdelivery.com"
        headers['Referer'] = "https://www.flashx.tv/"
        headers['Accept'] = "*/*"
        coding = httptools.downloadpage(coding_url,
                                        headers=headers,
                                        replace_headers=True).data

        coding_url = 'https://www.flashx.tv/counter.cgi?fx=%s' % base64.encodestring(
            file_id)
        headers['Host'] = "www.flashx.tv"
        coding = httptools.downloadpage(coding_url,
                                        headers=headers,
                                        replace_headers=True).data

        coding_url = 'https://www.flashx.tv/flashx.php?fxfx=3'
        headers['X-Requested-With'] = 'XMLHttpRequest'
        coding = httptools.downloadpage(coding_url,
                                        headers=headers,
                                        replace_headers=True).data

        try:
            time.sleep(int(wait_time) + 1)
        except:
            time.sleep(6)

        headers.pop('X-Requested-With')
        headers['Content-Type'] = 'application/x-www-form-urlencoded'
        data = httptools.downloadpage('https://www.flashx.tv/dl?playthis',
                                      post,
                                      headers,
                                      replace_headers=True).data

        matches = scrapertools.find_multiple_matches(
            data, "(eval\(function\(p,a,c,k.*?)\s+</script>")
        for match in matches:
            if match.startswith("eval"):
                try:
                    match = jsunpack.unpack(match)
                    fake = (scrapertools.find_single_match(match,
                                                           "(\w{40,})") == "")
                    if fake:
                        match = ""
                    else:
                        break
                except:
                    match = ""

        if not match:
            match = data

    # Extrae la URL
    # {file:"http://f11-play.flashx.tv/luq4gfc7gxixexzw6v4lhz4xqslgqmqku7gxjf4bk43u4qvwzsadrjsozxoa/video1.mp4"}
    video_urls = []
    media_urls = scrapertools.find_multiple_matches(
        match, '\{file\:"([^"]+)",label:"([^"]+)"')
    subtitle = ""
    for media_url, label in media_urls:
        if media_url.endswith(".srt") and label == "Italian":
            try:
                from core import filetools
                data = scrapertools.downloadpage(media_url)
                subtitle = os.path.join(config.get_data_path(),
                                        'sub_flashx.srt')
                filetools.write(subtitle, data)
            except:
                import traceback
                logger.info(
                    "streamondemand.servers.flashx Error al descargar el subtítulo: "
                    + traceback.format_exc())

    for media_url, label in media_urls:
        if not media_url.endswith("png") and not media_url.endswith(".srt"):
            video_urls.append([
                "." + media_url.rsplit('.', 1)[1] + " [flashx]", media_url, 0,
                subtitle
            ])

    for video_url in video_urls:
        logger.info("%s - %s" % (video_url[0], video_url[1]))

    return video_urls
示例#56
0
def convert_old_to_v4():
    logger.info()
    path_series_xml = filetools.join(config.get_data_path(), "series.xml")
    path_series_json = filetools.join(config.get_data_path(), "series.json")
    series_insertadas = 0
    series_fallidas = 0
    version = 'v?'

    # Renombrar carpeta Series y crear una vacia
    import time
    new_name = str(time.time())
    path_series_old = filetools.join(library.LIBRARY_PATH,
                                     "SERIES_OLD_" + new_name)
    if filetools.rename(library.TVSHOWS_PATH, "SERIES_OLD_" + new_name):
        if not filetools.mkdir(library.TVSHOWS_PATH):
            logger.error(
                "ERROR, no se ha podido crear la nueva carpeta de SERIES")
            return False
    else:
        logger.error(
            "ERROR, no se ha podido renombrar la antigua carpeta de SERIES")
        return False

    path_cine_old = filetools.join(library.LIBRARY_PATH,
                                   "CINE_OLD_" + new_name)
    if filetools.rename(library.MOVIES_PATH, "CINE_OLD_" + new_name):
        if not filetools.mkdir(library.MOVIES_PATH):
            logger.error(
                "ERROR, no se ha podido crear la nueva carpeta de CINE")
            return False
    else:
        logger.error(
            "ERROR, no se ha podido renombrar la antigua carpeta de CINE")
        return False

    # Convertir libreria de v1(xml) a v4
    if filetools.exists(path_series_xml):
        try:
            data = filetools.read(path_series_xml)
            for line in data.splitlines():
                try:
                    aux = line.rstrip('\n').split(",")
                    tvshow = aux[0].strip()
                    url = aux[1].strip()
                    channel = aux[2].strip()

                    serie = Item(contentSerieName=tvshow,
                                 url=url,
                                 channel=channel,
                                 action="episodios",
                                 title=tvshow,
                                 active=True)

                    patron = "^(.+)[\s]\((\d{4})\)$"
                    matches = re.compile(patron, re.DOTALL).findall(
                        serie.contentSerieName)

                    if matches:
                        serie.infoLabels['title'] = matches[0][0]
                        serie.infoLabels['year'] = matches[0][1]
                    else:
                        serie.infoLabels['title'] = tvshow

                    insertados, sobreescritos, fallidos = library.save_library_tvshow(
                        serie, list())
                    if fallidos == 0:
                        series_insertadas += 1
                        platformtools.dialog_notification(
                            "Serie actualizada", serie.infoLabels['title'])
                    else:
                        series_fallidas += 1
                except:
                    series_fallidas += 1

            filetools.rename(path_series_xml, "series.xml.old")
            version = 'v4'

        except EnvironmentError:
            logger.error("ERROR al leer el archivo: %s" % path_series_xml)
            return False

    # Convertir libreria de v2(json) a v4
    if filetools.exists(path_series_json):
        try:
            data = jsontools.load_json(filetools.read(path_series_json))
            for tvshow in data:
                for channel in data[tvshow]["channels"]:
                    try:
                        serie = Item(
                            contentSerieName=data[tvshow]["channels"][channel]
                            ["tvshow"],
                            url=data[tvshow]["channels"][channel]["url"],
                            channel=channel,
                            action="episodios",
                            title=data[tvshow]["name"],
                            active=True)
                        if not tvshow.startswith("t_"):
                            serie.infoLabels["tmdb_id"] = tvshow

                        insertados, sobreescritos, fallidos = library.save_library_tvshow(
                            serie, list())
                        if fallidos == 0:
                            series_insertadas += 1
                            platformtools.dialog_notification(
                                "Serie actualizada", serie.infoLabels['title'])
                        else:
                            series_fallidas += 1
                    except:
                        series_fallidas += 1

            filetools.rename(path_series_json, "series.json.old")
            version = 'v4'

        except EnvironmentError:
            logger.error("ERROR al leer el archivo: %s" % path_series_json)
            return False

    # Convertir libreria de v3 a v4
    if version != 'v4':
        # Obtenemos todos los tvshow.json de la biblioteca de SERIES_OLD recursivamente
        for raiz, subcarpetas, ficheros in filetools.walk(path_series_old):
            for f in ficheros:
                if f == "tvshow.json":
                    try:
                        serie = Item().fromjson(
                            filetools.read(filetools.join(raiz, f)))
                        insertados, sobreescritos, fallidos = library.save_library_tvshow(
                            serie, list())
                        if fallidos == 0:
                            series_insertadas += 1
                            platformtools.dialog_notification(
                                "Serie actualizada", serie.infoLabels['title'])
                        else:
                            series_fallidas += 1
                    except:
                        series_fallidas += 1

        movies_insertadas = 0
        movies_fallidas = 0
        for raiz, subcarpetas, ficheros in filetools.walk(path_cine_old):
            for f in ficheros:
                if f.endswith(".strm.json"):
                    try:
                        movie = Item().fromjson(
                            filetools.read(filetools.join(raiz, f)))
                        insertados, sobreescritos, fallidos = library.save_library_movie(
                            movie)
                        if fallidos == 0:
                            movies_insertadas += 1
                            platformtools.dialog_notification(
                                "Película actualizada",
                                movie.infoLabels['title'])
                        else:
                            movies_fallidas += 1
                    except:
                        movies_fallidas += 1

    config.set_setting("library_version", 'v4')

    platformtools.dialog_notification(
        "Biblioteca actualizada al nuevo formato",
        "%s series convertidas y %s series descartadas.\n"
        "%s peliculas convertidas y %s peliculas descartadas."
        "A continuación se va a obtener la información de todos los episodios"
        % (series_insertadas, series_fallidas, movies_insertadas,
           movies_fallidas),
        time=12000)

    # Por ultimo limpia la libreria, por que las rutas anteriores ya no existen
    xbmc_library.clean()

    return True
示例#57
0
def play_torrent(item, xlistitem, mediaurl):
    logger.info("platformtools play_torrent")
    # Opciones disponibles para Reproducir torrents
    torrent_options = list()
    torrent_options.append(["Cliente interno (necesario libtorrent)"])
    torrent_options.append(["Cliente interno MCT (necesario libtorrent)"])

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

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

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

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

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

        # Importamos el cliente
        from btserver import Client

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Y cerramos el progreso
        progreso.close()
def anadir_favorito(item):
    logger.info()
    name_file = os.path.splitext(os.path.basename(__file__))[0]
    fname = os.path.join(config.get_data_path(), "settings_channels",
                         name_file + "_favoritos.txt")
    user = config.get_setting("filesmonsteruser")
    password = config.get_setting("filesmonsterpassword")
    itemlist = []
    post2 = "username="******"&password="******"http://filesmonster.com/api/public/login"
    data1 = scrapertools.cache_page(login_url, post=post2)
    if item.plot == 'el archivo':
        id1 = item.url.split('?id=')
        id = id1[1]
        que = "file"
    if item.plot == 'la carpeta':
        id1 = item.url.split('?fid=')
        id = id1[1]
        que = "folder"
    url = "http://filesmonster.com/ajax/add_to_favorites"
    post3 = "username="******"&password="******"&id=" + id + "&obj_type=" + que
    data2 = scrapertools.cache_page(url, post=post3)
    if data2 == 'Already in Your favorites':
        itemlist.append(
            Item(channel=item.channel,
                 action="favoritos",
                 title="" + item.plot +
                 " ya estaba en tu lista de favoritos (" + user +
                 ") en Filesmonster"))
    if data2 != 'You are not logged in' and data2 != 'Already in Your favorites':
        itemlist.append(
            Item(channel=item.channel,
                 action="favoritos",
                 title="Se ha añadido correctamente " + item.plot +
                 " a tu lista de favoritos (" + user + ") en Filesmonster",
                 plot=data1 + data2))
        f = open(fname, "a+")
        if (item.plot == 'la carpeta'):
            ruta = "http://filesmonster.com/folders.php?"
        if (item.plot == 'el archivo'):
            ruta = "http://filesmonster.com/download.php"
        laruta = ruta + item.url
        laruta = laruta.replace(
            "http://filesmonster.com/folders.php?http://filesmonster.com/folders.php?",
            "http://filesmonster.com/folders.php?")
        laruta = laruta.replace(
            "http://filesmonster.com/download.php?http://filesmonster.com/download.php?",
            "http://filesmonster.com/download.php?")
        f.write(laruta + '@' + item.thumbnail + '\n')
        f.close()
    if data2 == 'You are not logged in':
        itemlist.append(
            Item(
                channel=item.channel,
                action="favoritos",
                title="No ha sido posible añadir " + item.plot +
                " a tu lista de favoritos (" + user +
                " no logueado en Filesmonster)",
            ))

    return itemlist
    from core.item import Item

    logger.info("streamondemand.library_service Actualizando series...")
    from platformcode import library
    import imp

    directorio = os.path.join(config.get_library_path(), "SERIES")
    logger.info("directorio=" + directorio)

    if not os.path.exists(directorio):
        os.mkdir(directorio)

    nombre_fichero_config_canal = os.path.join(config.get_library_path(),
                                               "series.xml")
    if not os.path.exists(nombre_fichero_config_canal):
        nombre_fichero_config_canal = os.path.join(config.get_data_path(),
                                                   "series.xml")

    try:

        if config.get_setting("updatelibrary") == "true":
            config_canal = open(nombre_fichero_config_canal, "r")

            for serie in config_canal.readlines():
                logger.info("streamondemand.library_service serie=" + serie)
                serie = serie.split(",")

                ruta = os.path.join(config.get_library_path(), "SERIES",
                                    serie[0])
                logger.info("streamondemand.library_service ruta =#" + ruta +
                            "#")
示例#60
0
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()