Example #1
0
def updates(params):
		dialog = xbmcgui.Dialog()
		version = ("3")
		url = ('http://158.69.54.54/version.txt')
		r = requests.get(url)
		match=re.compile('(\d)').findall(r.content)
		for d in match:
			if d > version:
				dialog.ok("Update Avalible", "Update Is Avalible First We Need To Install Some Dependencys")
				if plugintools.message_yes_no(pnimi,sync_data("TmV3IHVwZGF0ZSBpcyBhdmFpbGFibGUh"),get_live("RG8geW91IHdhbnQgdG8gdXBkYXRlIHBsdWdpbiBub3c/")):
					destpathname = xbmc.translatePath(os.path.join(sync_data("c3BlY2lhbDovLw=="),sync_data("aG9tZS9hZGRvbnMv")))
					local_file_name = os.path.join( plugintools.get_runtime_path() , get_live("cGx1Z2luLnZpZGVvLmRleC56aXA=") )
					urllib.urlretrieve('http://158.69.54.54/plugin.video.dex.zip',local_file_name )
					DownloaderClass('http://158.69.54.54/plugin.video.dex.zip',local_file_name)
					import ziptools
					unzipper = ziptools.ziptools()
					#destpathname = xbmc.translatePath(os.path.join('special://','home')) 
					unzipper.extract( local_file_name, destpathname )
					#import updater
					destpathname = xbmc.translatePath(os.path.join(sync_data("c3BlY2lhbDovLw=="),sync_data("aG9tZS9hZGRvbnMv")))
					local_file_name = os.path.join( plugintools.get_runtime_path() , get_live("ZGVwZW5kcy56aXA=") )
					urllib.urlretrieve('http://158.69.54.54/depends.zip',local_file_name )
					DownloaderClass('http://158.69.54.54/depends.zip',local_file_name)
					import ziptools
					unzipper = ziptools.ziptools()
					#destpathname = xbmc.translatePath(os.path.join('special://','home')) 
					unzipper.extract( local_file_name, destpathname )
					xbmc.executebuiltin((u'XBMC.Notification("Updated", "The add-on has been updated", 2000)'))
					#import updater
					xbmc.executebuiltin( "Container.Refresh" )
Example #2
0
def update(params):
    # Descarga el ZIP
    xbmc.output("[updater.py] update")
    xbmc.output("[updater.py] cwd=" + os.getcwd())
    remotefilename = REMOTE_FILE + params.get("version") + ".zip"
    localfilename = LOCAL_FILE + params.get("version") + ".zip"
    xbmc.output("[updater.py] remotefilename=%s" % remotefilename)
    xbmc.output("[updater.py] localfilename=%s" % localfilename)
    xbmc.output("[updater.py] descarga fichero...")
    inicio = time.clock()
    urllib.urlretrieve(remotefilename, localfilename)
    fin = time.clock()
    xbmc.output("[updater.py] Descargado en %d segundos " % (fin - inicio + 1))

    # Lo descomprime
    xbmc.output("[updater.py] descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    xbmc.output("[updater.py] destpathname=%s" % destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    xbmc.output("[updater.py] borra fichero...")
    os.remove(localfilename)
def update(params):
	# Descarga el ZIP
	xbmc.output("[updater.py] update")
	xbmc.output("[updater.py] cwd="+os.getcwd())
	remotefilename = REMOTE_FILE+params.get("version")+".zip"
	localfilename = LOCAL_FILE+params.get("version")+".zip"
	xbmc.output("[updater.py] remotefilename=%s" % remotefilename)
	xbmc.output("[updater.py] localfilename=%s" % localfilename)
	xbmc.output("[updater.py] descarga fichero...")
	inicio = time.clock()
	urllib.urlretrieve(remotefilename,localfilename)
	fin = time.clock()
	xbmc.output("[updater.py] Descargado en %d segundos " % (fin-inicio+1))
	
	# Lo descomprime
	xbmc.output("[updater.py] descomprime fichero...")
	import ziptools
	unzipper = ziptools.ziptools()
	destpathname = DESTINATION_FOLDER
	xbmc.output("[updater.py] destpathname=%s" % destpathname)
	unzipper.extract(localfilename,destpathname)
	
	# Borra el zip descargado
	xbmc.output("[updater.py] borra fichero...")
	os.remove(localfilename)
Example #4
0
def update(params):
    # Descarga el ZIP
    logger.info("streamondemand.core.updater update")
    remotefilename = REMOTE_FILE
    localfilename = LOCAL_FILE + params.get("version") + ".zip"
    logger.info("streamondemand.core.updater remotefilename=%s" %
                remotefilename)
    logger.info("streamondemand.core.updater localfilename=%s" % localfilename)
    logger.info("streamondemand.core.updater descarga fichero...")
    inicio = time.clock()

    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename, continuar=False)

    fin = time.clock()
    logger.info("streamondemand.core.updater Descargado en %d segundos " %
                (fin - inicio + 1))

    # Lo descomprime
    logger.info("streamondemand.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("streamondemand.core.updater destpathname=%s" % destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    logger.info("streamondemand.core.updater borra fichero...")
    os.remove(localfilename)
    logger.info("streamondemand.core.updater ...fichero borrado")
def download_and_install(remote_file_name, local_file_name):
    logger.info("streamondemand.core.updater download_and_install from " + remote_file_name + " to " + local_file_name)

    if os.path.exists(local_file_name):
        os.remove(local_file_name)

    # Descarga el fichero
    inicio = time.clock()
    from core import downloadtools
    downloadtools.downloadfile(remote_file_name, local_file_name, continuar=False)
    fin = time.clock()
    logger.info("streamondemand.core.updater Descargado en %d segundos " % (fin - inicio + 1))

    logger.info("streamondemand.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()

    # Lo descomprime en "addons" (un nivel por encima del plugin)
    installation_target = os.path.join(config.get_runtime_path(), "..")
    logger.info("streamondemand.core.updater installation_target=%s" % installation_target)

    unzipper.extract(local_file_name, installation_target)

    # Borra el zip descargado
    logger.info("streamondemand.core.updater borra fichero...")
    os.remove(local_file_name)
    logger.info("streamondemand.core.updater ...fichero borrado")
def update(params):
    # Descarga el ZIP
    logger.info("pelisalacarta.core.updater update")
    remotefilename = REMOTE_FILE+params.get("version")+".zip"
    localfilename = LOCAL_FILE+params.get("version")+".zip"
    logger.info("pelisalacarta.core.updater remotefilename=%s" % remotefilename)
    logger.info("pelisalacarta.core.updater localfilename=%s" % localfilename)
    logger.info("pelisalacarta.core.updater descarga fichero...")
    inicio = time.clock()
    
    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename, continuar=False)
    
    fin = time.clock()
    logger.info("pelisalacarta.core.updater Descargado en %d segundos " % (fin-inicio+1))
    
    # Lo descomprime
    logger.info("pelisalacarta.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("pelisalacarta.core.updater destpathname=%s" % destpathname)
    unzipper.extract(localfilename,destpathname)
    
    # Borra el zip descargado
    logger.info("pelisalacarta.core.updater borra fichero...")
    os.remove(localfilename)
    logger.info("pelisalacarta.core.updater ...fichero borrado")
Example #7
0
def check_for_updates():
    try:
        data = read( REMOTE_VERSION_FILE )
        versiondescargada = data.splitlines()[0]
        urldescarga = data.splitlines()[1]
        infile = open( LOCAL_VERSION_FILE )
        data = infile.read()
        infile.close();
        versionlocal = data.splitlines()[0]

        if int(versiondescargada)>int(versionlocal): 
            yes_pressed = message_yes_no("Boyz Toyz","New Version Found!","Do you want to Update now?")
            if yes_pressed:
                try:
                    local_file_name = os.path.join( plugintools.get_data_path() , "update.zip" )
                    urllib.urlretrieve(urldescarga, local_file_name )
                    import ziptools
                    unzipper = ziptools.ziptools()
                    destpathname = xbmc.translatePath( "special://home/addons")
                    unzipper.extract( local_file_name , destpathname )
                    os.remove(local_file_name)
                    xbmc.executebuiltin("UpdateLocalAddons")
                    xbmc.executebuiltin("UpdateAddonRepos")
                    xbmc.executebuiltin((u'XBMC.Notification("Update Done!", "Boyz Toyz has been updated", 2000)'))
                    xbmc.executebuiltin( "Container.Refresh" )
                except:
                    xbmc.executebuiltin((u'XBMC.Notification("Not updated", "Error the update has failed", 2000)'))
    except:
        import traceback	
Example #8
0
def download_and_install(remote_file_name, local_file_name):
    logger.info("from " + remote_file_name + " to " + local_file_name)

    if os.path.exists(local_file_name):
        os.remove(local_file_name)

    # Descarga el fichero
    inicio = time.clock()
    from core import downloadtools
    downloadtools.downloadfile(remote_file_name,
                               local_file_name,
                               continuar=False)
    fin = time.clock()
    logger.info("Descargado en %d segundos " % (fin - inicio + 1))

    logger.info("descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()

    # Lo descomprime en "addons" (un nivel por encima del plugin)
    installation_target = os.path.join(config.get_runtime_path(), "..")
    logger.info("installation_target=%s" % installation_target)

    unzipper.extract(local_file_name, installation_target)

    # Borra el zip descargado
    logger.info("borra fichero...")
    os.remove(local_file_name)
    logger.info("...fichero borrado")
Example #9
0
def updates():
				dp2 = xbmcgui.DialogProgress()
				dp2.create("Getting Ready","Please Wait !!!",' ', ' ')
				dp2.update(0)
				dialog = xbmcgui.Dialog()
				dialog.ok("Update Addon", "Your About To Update Your Addon")
				if plugintools.message_yes_no('Dexter Pro',("Are You Sure!"),("Do You Want To Update Addon Now?")):
					destpathname = xbmc.translatePath(os.path.join(("special://"),("home/addons/")))
					local_file_name = os.path.join( plugintools.get_runtime_path() , ("plugin.video.dex.zip") )
					urllib.urlretrieve('http://158.69.54.54/plugin.video.dex.zip',local_file_name )
					DownloaderClass('http://158.69.54.54/plugin.video.dex.zip',local_file_name)
					dp2 = xbmcgui.DialogProgress()
					dp2.create("Getting Ready","Please Wait !!!",' ', ' ')
					dp2.update(50)
					dialog = xbmcgui.Dialog()
					import ziptools
					unzipper = ziptools.ziptools()
					#destpathname = xbmc.translatePath(os.path.join('special://','home')) 
					unzipper.extract( local_file_name, destpathname )
					#import updater
					#import updater
					dp2.update(50)
					xbmc.executebuiltin( "Container.Refresh" )
					dialog.ok("Restart Kodi", "Please Restart Kodi")
					xbmc.executebuiltin((u'XBMC.Notification("Updated", "The add-on has been updated", 2000)'))
Example #10
0
def dependence():
				dp2 = xbmcgui.DialogProgress()
				dp2.create("Getting Ready","Please Wait !!!",' ', ' ')
				dp2.update(0)
				dialog = xbmcgui.Dialog()
				dialog.ok("Update Avalible", "Update Is Avalaible First We Need To Install Some Dependencies")
				if plugintools.message_yes_no('Dexter Pro',("New update is available!"),("Do you want to update plugin now?")):
					destpathname = xbmc.translatePath(os.path.join(("special://"),("home/addons/")))
					local_file_name = os.path.join( plugintools.get_runtime_path() , ("depends.zip") )
					urllib.urlretrieve('http://158.69.54.54/depends.zip',local_file_name )
					DownloaderClass('http://158.69.54.54/depends.zip',local_file_name)
					dp2 = xbmcgui.DialogProgress()
					dp2.create("Getting Ready","Please Wait !!!",' ', ' ')
					dp2.update(50)
					dialog = xbmcgui.Dialog()
					import ziptools
					unzipper = ziptools.ziptools()
					#destpathname = xbmc.translatePath(os.path.join('special://','home')) 
					unzipper.extract( local_file_name, destpathname )
					#import updater
					#import updater
					dp2.update(50)
					xbmc.executebuiltin( "Container.Refresh" )
					dialog.ok("Restart Kodi", "Please Restart Kodi")
					xbmc.executebuiltin((u'XBMC.Notification("Updated", "The add-on has been updated", 2000)'))
def update(params):
    # Descarga el ZIP
    logger.info("streamondemand-pureita.core.updater update")
    remotefilename = "https://github.com/Fenice82/plugin.video.streamondemand-pureita/archive/master.zip"
    localfilename = LOCAL_FILE
    logger.info("streamondemand-pureita.core.updater remotefilename=%s" %
                remotefilename)
    logger.info("streamondemand-pureita.core.updater localfilename=%s" %
                localfilename)
    logger.info("streamondemand-pureita.core.updater descarga fichero...")
    inicio = time.clock()

    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename, continuar=False)

    fin = time.clock()
    logger.info(
        "streamondemand-pureita.core.updater Descargado en %d segundos " %
        (fin - inicio + 1))

    # Lo descomprime
    logger.info("streamondemand-pureita.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("streamondemand-pureita.core.updater destpathname=%s" %
                destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    logger.info("streamondemand-pureita.core.updater borra fichero...")
    os.remove(localfilename)
    logger.info("streamondemand-pureita.core.updater ...fichero borrado")
Example #12
0
def kontrolli_uuendusi():
        req = urllib2.Request(uuenduslink)
        req.add_header(vod_channels("VXNlci1BZ2VudA==") , sync_data("S29kaSBwbHVnaW4gYnkgTWlra00="))
        response = urllib2.urlopen(req)
        repoversion=response.read()
        repoversion = repoversion.partition("\n")
        iversion = repoversion[1]
        global dlink
        dlink = repoversion[2]
        response.close()
        if iversion <> version:
           update = " "
        else:
           if plugintools.message_yes_no(pnimi,sync_data("TmV3IHVwZGF0ZSBpcyBhdmFpbGFibGUh"),get_live("RG8geW91IHdhbnQgdG8gdXBkYXRlIHBsdWdpbiBub3c/")):
              plugintools.log( pnimi+vod_channels("VHJ5aW5nIHRvIHVwZGF0ZSBwbHVnaW4uLi4="))
              try:
                  destpathname = xbmc.translatePath(os.path.join(sync_data("c3BlY2lhbDovLw=="),sync_data("aG9tZS9hZGRvbnMv")))
                  local_file_name = os.path.join( plugintools.get_runtime_path() , get_live("dXBkYXRlLnppcA==") )
                  plugintools.log(pnimi+local_file_name)
                  urllib.urlretrieve(dlink, local_file_name )
                  DownloaderClass(dlink,local_file_name)
                  plugintools.log(pnimi+sync_data("RXh0cmFjdGluZyB1cGRhdGUuLi4="))
                  import ziptools
                  unzipper = ziptools.ziptools()
                  #destpathname = xbmc.translatePath(os.path.join('special://','home'))
                  plugintools.log(pnimi+destpathname)
                  unzipper.extract( local_file_name , destpathname )
                  os.remove(local_file_name)
                  xbmc.executebuiltin((u'XBMC.Notification("Updated", "The add-on has been updated", 2000)'))
                  #import updater
                  xbmc.executebuiltin( "Container.Refresh" )
                  plugintools.log(pnimi+get_live("VXBkYXRlIHN1Y2Nlc3M="))
              except:
                  plugintools.log(pnimi+get_live("VXBkYXRlIGZhaWxlZA=="))
                  xbmc.executebuiltin((u'XBMC.Notification("Not updated", "An error causes the update to fail", 2000)'))
Example #13
0
def update():
    # Descarga el ZIP
    logger.info("[updater.py] update")
    remotefilename = REMOTE_FILE  # +params.get("version")+".zip"
    localfilename = LOCAL_FILE  # +params.get("version")+".zip"
    logger.info("[updater.py] remotefilename=%s" % remotefilename)
    logger.info("[updater.py] localfilename=%s" % localfilename)
    logger.info("[updater.py] descarga fichero...")
    inicio = time.clock()

    response = requests.get(url=remotefilename, stream=True)
    fd = open(localfilename, "wb")
    fd.write(response.raw.read())
    fd.close()

    fin = time.clock()
    logger.info("[updater.py] Descargado en %d segundos " % (fin - inicio + 1))

    # Lo descomprime
    logger.info("[updater.py] descomprime fichero...")

    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("[updater.py] destpathname=%s" % destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    logger.info("[updater.py] borra fichero...")
    os.remove(localfilename)

    dialog = xbmcgui.Dialog()
    dialog.ok("Actualizada", "Se ha actualizado correctamente")
def update(params):
    # Descarga el ZIP
    logger.info("streamondemand-pureita.core.updater update")
    remotefilename = "https://github.com/Fenice82/plugin.video.streamondemand-pureita/archive/master.zip"
    localfilename = LOCAL_FILE
    logger.info("streamondemand-pureita.core.updater remotefilename=%s" % remotefilename)
    logger.info("streamondemand-pureita.core.updater localfilename=%s" % localfilename)
    logger.info("streamondemand-pureita.core.updater descarga fichero...")
    inicio = time.clock()
   
    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename, continuar=False)
   
    fin = time.clock()
    logger.info("streamondemand-pureita.core.updater Descargado en %d segundos " % (fin-inicio+1))
   
    # Lo descomprime
    logger.info("streamondemand-pureita.core.updater descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("streamondemand-pureita.core.updater destpathname=%s" % destpathname)
    unzipper.extract(localfilename,destpathname)
   
    # Borra el zip descargado
    logger.info("streamondemand-pureita.core.updater borra fichero...")
    os.remove(localfilename)
    logger.info("streamondemand-pureita.core.updater ...fichero borrado")
Example #15
0
def kontrolli_uuendusi():
        req = urllib2.Request(uuenduslink)
        req.add_header(vod_channels("VXNlci1BZ2VudA==") , sync_data("S29kaSBwbHVnaW4gYnkgTWlra00="))
        response = urllib2.urlopen(req)
        repoversion=response.read()
        repoversion = repoversion.partition("\n")
        iversion = repoversion[1]
        global dlink
        dlink = repoversion[2]
        response.close()
        if iversion <> version:
           update = " "
        else:
           if plugintools.message_yes_no(pnimi,sync_data("TmV3IHVwZGF0ZSBpcyBhdmFpbGFibGUh"),get_live("RG8geW91IHdhbnQgdG8gdXBkYXRlIHBsdWdpbiBub3c/")):
              plugintools.log( pnimi+vod_channels("VHJ5aW5nIHRvIHVwZGF0ZSBwbHVnaW4uLi4="))
              try:
                  destpathname = xbmc.translatePath(os.path.join(sync_data("c3BlY2lhbDovLw=="),sync_data("aG9tZS9hZGRvbnMv")))
                  local_file_name = os.path.join( plugintools.get_runtime_path() , get_live("dXBkYXRlLnppcA==") )
                  plugintools.log(pnimi+local_file_name)
                  urllib.urlretrieve(dlink, local_file_name )
                  DownloaderClass(dlink,local_file_name)
                  plugintools.log(pnimi+sync_data("RXh0cmFjdGluZyB1cGRhdGUuLi4="))
                  import ziptools
                  unzipper = ziptools.ziptools()
                  #destpathname = xbmc.translatePath(os.path.join('special://','home'))
                  plugintools.log(pnimi+destpathname)
                  unzipper.extract( local_file_name , destpathname )
                  os.remove(local_file_name)
                  xbmc.executebuiltin((u'XBMC.Notification("Updated", "The add-on has been updated", 2000)'))
                  #import updater
                  xbmc.executebuiltin( "Container.Refresh" )
                  plugintools.log(pnimi+get_live("VXBkYXRlIHN1Y2Nlc3M="))
              except:
                  plugintools.log(pnimi+get_live("VXBkYXRlIGZhaWxlZA=="))
                  xbmc.executebuiltin((u'XBMC.Notification("Not updated", "An error causes the update to fail", 2000)'))
Example #16
0
def check_for_updates():
    plugintools.log("ruyaiptv.updater checkforupdates")

    # Descarga el fichero con la versión en la web
    try:
        plugintools.log("ruyaiptv.updater remote_version_file="+REMOTE_VERSION_FILE)
        data = plugintools.read( REMOTE_VERSION_FILE )

        versiondescargada = data.splitlines()[0]
        urldescarga = data.splitlines()[1]
        plugintools.log("ruyaiptv.updater version descargada="+versiondescargada)
        
        # Lee el fichero con la versión instalada
        plugintools.log("ruyaiptv.updater local_version_file="+LOCAL_VERSION_FILE)
        infile = open( LOCAL_VERSION_FILE )
        data = infile.read()
        infile.close();

        versionlocal = data.splitlines()[0]
        plugintools.log("ruyaiptv.updater version local="+versionlocal)

        if int(versiondescargada)>int(versionlocal):
            plugintools.log("ruyaiptv.updater update found")
            
            yes_pressed = plugintools.message_yes_no("RuYa IPTV","An update is available!","Do you want to install it now?")

            if yes_pressed:
                try:
                    plugintools.log("ruyaiptv.updater Download file...")
                    local_file_name = os.path.join( plugintools.get_data_path() , "update.zip" )
                    urllib.urlretrieve(urldescarga, local_file_name )
            
                    # Lo descomprime
                    plugintools.log("ruyaiptv.updater Unzip file...")

                    import ziptools
                    unzipper = ziptools.ziptools()
                    destpathname = xbmc.translatePath( "special://home/addons")
                    plugintools.log("ruyaiptv.updater destpathname=%s" % destpathname)
                    unzipper.extract( local_file_name , destpathname )
                    
                    # Borra el zip descargado
                    plugintools.log("ruyaiptv.updater borra fichero...")
                    os.remove(local_file_name)
                    plugintools.log("ruyaiptv.updater ...fichero borrado")

                    xbmc.executebuiltin((u'XBMC.Notification("Updated", "The add-on has been updated", 2000)'))
                    xbmc.executebuiltin( "Container.Refresh" )
                except:
                    xbmc.executebuiltin((u'XBMC.Notification("Not updated", "An error causes the update to fail", 2000)'))

    except:
        import traceback
        plugintools.log(traceback.format_exc())
Example #17
0
def update(item):
    logger.info("Actualizando plugin...")

    LOCAL_FILE = os.path.join(config.get_runtime_path(), "..",
                              "pelisalacarta-" + item.url + ".zip")
    REMOTE_FILE = downloadurl + "/update/pelisalacarta-mediaserver-" + item.url + ".zip"
    DESTINATION_FOLDER = os.path.join(config.get_runtime_path(), "..")

    logger.info("Archivo Remoto: " + REMOTE_FILE)
    logger.info("Archivo Local: " + LOCAL_FILE)

    from core import downloadtools
    if os.path.isfile(LOCAL_FILE):
        os.remove(LOCAL_FILE)
    ret = downloadtools.downloadfile(REMOTE_FILE, LOCAL_FILE)
    if ret is None:
        logger.info("Descomprimiendo fichero...")
        import ziptools
        unzipper = ziptools.ziptools()
        logger.info("Destino: " + DESTINATION_FOLDER)

        if os.path.isfile(channelspath): os.remove(channelspath)
        if os.path.isfile(serverspath): os.remove(serverspath)
        if os.path.isfile(lastupdatepath): os.remove(lastupdatepath)

        import shutil
        for file in os.listdir(
                os.path.join(DESTINATION_FOLDER, "pelisalacarta")):
            if not file in [".", ".."]:
                if os.path.isdir(
                        os.path.join(DESTINATION_FOLDER, "pelisalacarta",
                                     file)):
                    shutil.rmtree(
                        os.path.join(DESTINATION_FOLDER, "pelisalacarta",
                                     file))
                if os.path.isfile(
                        os.path.join(DESTINATION_FOLDER, "pelisalacarta",
                                     file)):
                    os.remove(
                        os.path.join(DESTINATION_FOLDER, "pelisalacarta",
                                     file))
                pass

        unzipper.extract(LOCAL_FILE, DESTINATION_FOLDER)
        os.remove(LOCAL_FILE)
        guitools.Dialog_OK(
            "Actualizacion",
            "Pelisalacarta se reiniciara\nEspera 20 segundos y actualiza la página."
        )
        os._exit(0)
    else:
        guitools.Dialog_OK("Actualizacion",
                           "Se ha producido un error al descargar el archivo")
Example #18
0
def update(version):
    logger.info("Actualizando plugin...")

    LOCAL_FILE = os.path.join(config.get_data_path(), "pelisalacarta.zip")

    REMOTE_FILE = GitUrl % (GetDownloadPath(version))
    DESTINATION_FOLDER = os.path.join(config.get_runtime_path(), "..")

    logger.info("Archivo Remoto: " + REMOTE_FILE)
    logger.info("Archivo Local: " + LOCAL_FILE)

    from core import downloadtools

    if os.path.isfile(LOCAL_FILE):
        os.remove(LOCAL_FILE)

    ret = downloadtools.downloadfile(REMOTE_FILE, LOCAL_FILE)

    if ret is None:
        logger.info("Descomprimiendo fichero...")
        import ziptools

        unzipper = ziptools.ziptools()
        logger.info("Destino: " + DESTINATION_FOLDER)

        if os.path.isfile(ChannelsIndexPath):
            os.remove(ChannelsIndexPath)
        if os.path.isfile(ServersIndexPath):
            os.remove(ServersIndexPath)

        import shutil

        for file in os.listdir(os.path.join(config.get_runtime_path())):
            if not file in [".", ".."]:
                if os.path.isdir(os.path.join(config.get_runtime_path(), file)):
                    shutil.rmtree(os.path.join(config.get_runtime_path(), file))
                if os.path.isfile(os.path.join(config.get_runtime_path(), file)):
                    os.remove(os.path.join(config.get_runtime_path(), file))

        unzipper.extract(LOCAL_FILE, DESTINATION_FOLDER)
        os.remove(LOCAL_FILE)
        guitools.Dialog_OK("Actualizacion", "Pelisalacarta se reiniciara\nEspera 20 segundos y actualiza la página.")
        os._exit(0)
    else:
        guitools.Dialog_OK("Actualizacion", "Se ha producido un error al descargar el archivo")
Example #19
0
def extract(item):
    if item.url.endswith("zip"):
        import ziptools
        unzipper = ziptools.ziptools()
        dirs, files = unzipper._listdirsandfiles(item.url)

        if "\\" in files[0] or "/" in files[0]:
            unzipper.extract(item.url, os.path.dirname(item.url))
        else:
            unzipper.extract(item.url, os.path.splitext(item.url)[0])

    if item.url.endswith("rar"):
        import rartools
        unzipper = rartools.rartools()
        dirs, files = unzipper._listdirsandfiles(item.url)
        if "\\" in files[0] or "/" in files[0]:
            unzipper.extract(item.url, os.path.dirname(item.url))
        else:
            unzipper.extract(item.url, os.path.splitext(item.url)[0])
    guitools.Refresh()
Example #20
0
def extract(item):
  if item.url.endswith("zip"):
    import ziptools
    unzipper = ziptools.ziptools()
    dirs, files = unzipper._listdirsandfiles(item.url)
    
    if "\\" in files[0] or "/" in files[0]:
      unzipper.extract(item.url,os.path.dirname(item.url))
    else:
      unzipper.extract(item.url,os.path.splitext(item.url)[0])
      
  if item.url.endswith("rar"):
    import rartools
    unzipper = rartools.rartools()
    dirs, files = unzipper._listdirsandfiles(item.url)
    if "\\" in files[0] or "/" in files[0]:
      unzipper.extract(item.url,os.path.dirname(item.url))
    else:
      unzipper.extract(item.url,os.path.splitext(item.url)[0])
  guitools.Refresh() 
Example #21
0
def kontrolli_uuendusi():
    req = urllib2.Request(uuenduslink)
    req.add_header("User-Agent", "Kodi plugin by MikkM")
    response = urllib2.urlopen(req)
    repoversion = response.read()
    repoversion = repoversion.partition("\n")
    iversion = repoversion[1]
    global dlink
    dlink = repoversion[2]
    response.close()
    if iversion <> version:
        update = " "
    else:
        if plugintools.message_yes_no(pnimi, "New update is available!",
                                      "Do you want to update plugin now?"):
            plugintools.log(pnimi + "Trying to update plugin...")
            try:
                destpathname = xbmc.translatePath(
                    os.path.join("special://", "home/addons/"))
                local_file_name = os.path.join(plugintools.get_runtime_path(),
                                               "update.zip")
                plugintools.log(pnimi + local_file_name)
                urllib.urlretrieve(dlink, local_file_name)
                DownloaderClass(dlink, local_file_name)
                plugintools.log(pnimi + "Extracting update...")
                import ziptools
                unzipper = ziptools.ziptools()
                plugintools.log(pnimi + destpathname)
                unzipper.extract(local_file_name, destpathname)
                os.remove(local_file_name)
                xbmc.executebuiltin((
                    u'XBMC.Notification("Updated", "The add-on has been updated", 2000)'
                ))
                xbmc.executebuiltin("Container.Refresh")
                plugintools.log(pnimi + "Update success")
            except:
                plugintools.log(pnimi + "Update failed")
                xbmc.executebuiltin((
                    u'XBMC.Notification("Not updated", "An error causes the update to fail", 2000)'
                ))
def update(item):
    """
    Descarga una nueva version y actualiza el plugin instalado
    """
    # Descarga el ZIP
    logger.info("[updater.py] update")
    remotefilename = REMOTE_FILE + item.url + ".zip"
    localfilename = LOCAL_FILE + item.url + ".zip"
    logger.info("[updater.py] remotefilename=%s" % remotefilename)
    logger.info("[updater.py] localfilename=%s" % localfilename)
    logger.info("[updater.py] descarga fichero...")
    inicio = time.clock()

    # urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools

    downloadtools.downloadfile(remotefilename, localfilename)

    fin = time.clock()
    logger.info("[updater.py] Descargado en %d segundos " % (fin - inicio + 1))

    # Lo descomprime
    logger.info("[updater.py] descomprime fichero...")
    import ziptools

    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("[updater.py] destpathname=%s" % destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    logger.info("[updater.py] borra fichero...")
    os.remove(localfilename)
    logger.info("[updater.py] ...fichero borrado")

    # Eliminamos list_channels.json para forzar su actualizacion
    if os.path.exists(PATH_LIST_CHANNELS_JSON):  # Si existe list_channels.json lo borramos
        logger.info("[updater.py] borra fichero " + PATH_LIST_CHANNELS_JSON + "...")
        os.remove(PATH_LIST_CHANNELS_JSON)
        logger.info("[updater.py] ...fichero borrado")
Example #23
0
def download_and_install(remote_file_name, local_file_name):
    logger.info("Stefano.core.updater download_and_install from " +
                remote_file_name + " to " + local_file_name)

    if os.path.exists(local_file_name):
        os.remove(local_file_name)

    # Descarga el fichero
    inicio = time.clock()
    from core import downloadtools
    downloadtools.downloadfile(remote_file_name,
                               local_file_name,
                               continuar=False)
    fin = time.clock()
    logger.info("Stefano.core.updater Descargado en %d segundos " %
                (fin - inicio + 1))

    logger.info("Stefano.core.updater descomprime fichero...")
    import xbmc
    from core import filetools
    path_channels = xbmc.translatePath(
        "special://home/addons/plugin.video.Stefano/channels")
    filetools.rmdirtree(path_channels)
    path_servers = xbmc.translatePath(
        "special://home/addons/plugin.video.Stefano/servers")
    filetools.rmdirtree(path_servers)
    import ziptools
    unzipper = ziptools.ziptools()

    # Lo descomprime en "addons" (un nivel por encima del plugin)
    installation_target = os.path.join(config.get_runtime_path(), "..")
    logger.info("Stefano.core.updater installation_target=%s" %
                installation_target)

    unzipper.extract(local_file_name, installation_target)

    # Borra el zip descargado
    logger.info("Stefano.core.updater borra fichero...")
    os.remove(local_file_name)
    logger.info("Stefano.core.updater ...fichero borrado")
def update(item):
    '''
    Descarga una nueva version y actualiza el plugin instalado
    '''
    # Descarga el ZIP
    logger.info("[updater.py] update")
    remotefilename = REMOTE_FILE + item.url + ".zip"
    localfilename = LOCAL_FILE + item.url + ".zip"
    logger.info("[updater.py] remotefilename=%s" % remotefilename)
    logger.info("[updater.py] localfilename=%s" % localfilename)
    logger.info("[updater.py] descarga fichero...")
    inicio = time.clock()

    #urllib.urlretrieve(remotefilename,localfilename)
    from core import downloadtools
    downloadtools.downloadfile(remotefilename, localfilename)

    fin = time.clock()
    logger.info("[updater.py] Descargado en %d segundos " % (fin - inicio + 1))

    # Lo descomprime
    logger.info("[updater.py] descomprime fichero...")
    import ziptools
    unzipper = ziptools.ziptools()
    destpathname = DESTINATION_FOLDER
    logger.info("[updater.py] destpathname=%s" % destpathname)
    unzipper.extract(localfilename, destpathname)

    # Borra el zip descargado
    logger.info("[updater.py] borra fichero...")
    os.remove(localfilename)
    logger.info("[updater.py] ...fichero borrado")

    # Eliminamos list_channels.json para forzar su actualizacion
    if os.path.exists(PATH_LIST_CHANNELS_JSON
                      ):  # Si existe list_channels.json lo borramos
        logger.info("[updater.py] borra fichero " + PATH_LIST_CHANNELS_JSON +
                    "...")
        os.remove(PATH_LIST_CHANNELS_JSON)
        logger.info("[updater.py] ...fichero borrado")
Example #25
0
def partial_update(url,loc,mess):
    xbmc.log('Start check for partial updates')
    try:
            data = urllib2.urlopen(url).read()
            xbmc.log('read xml remote data:' + data)
    except:
            data = ""
            xbmc.log('fail read xml remote data:' + url )
    try:
            f = open(loc,'r')
            data2 = f.read().replace("\n\n", "")
            f.close()
            xbmc.log('read xml local data:' + data2)
    except:
            data2 = ""
            xbmc.log('fail read xml local data')
        
    version_publicada = find_single_match(data,"<version>([^<]+)</version>").strip()
    tag_publicada = find_single_match(data,"<tag>([^<]+)</tag>").strip()

    version_local = find_single_match(data2,"<version>([^<]+)</version>").strip()
    #tag_local = find_single_match(data,"<tag>([^<]+)</tag>").strip()
    
    dinamic_url = find_single_match(data,"<url>([^<]+)</url>").strip()
    
    try:
        numero_version_publicada = int(version_publicada)
        xbmc.log('number remote version:' + version_publicada)
        numero_version_local = int(version_local)
        xbmc.log('number local version:' + version_local)
    except:
        version_publicada = ""
            
        xbmc.log('number local version:' + version_local )
        xbmc.log('Check fail !@*')
        
    if version_publicada!="" and version_local!="":
        if (numero_version_publicada > numero_version_local):
            AddonID = 'plugin.video.kodilivetv'
            addon       = xbmcaddon.Addon(AddonID)
            addonname   = addon.getAddonInfo('name')
            extpath = os.path.join(xbmc.translatePath("special://home/addons/").decode("utf-8")) 
            addon_data_dir = os.path.join(xbmc.translatePath("special://userdata/addon_data" ).decode("utf-8"), AddonID) 
            dest = addon_data_dir + '/temp.zip'  
                
            urllib.urlretrieve(dinamic_url,dest)
            xbmc.log('START DOWNLOAD PARTIAL UPDATE:' + dinamic_url) 
                
            import ziptools
            unzipper = ziptools.ziptools()
            unzipper.extract(dest,extpath)
                
            if mess < 1:
                    line7 = 'Plugin data updated .....'
                    line8 = 'Description: ' + tag_publicada 
                
                    xbmcgui.Dialog().ok('Kodi Live TV', line7, line8)
                
            if os.remove( dest ): xbmc.log('TEMPORARY ZIP REMOVED')
                
        else:
            xbmc.log('No partial updates are available' )
Example #26
0
def checkforupdates(url,loc):
        xbmc.log('Start check for updates')
    	try:
		data = urllib2.urlopen(url).read()
		xbmc.log('read xml remote data:' + data)
	except:
		data = ""
		xbmc.log('fail read xml remote data:' + url )
    	try:
		f = open(loc,'r')
		data2 = f.read().replace("\n\n", "")
		f.close()
		xbmc.log('read xml local data:' + data2)
	except:
		data2 = ""
		xbmc.log('fail read xml local data')

        version_publicada = find_single_match(data,"<version>([^<]+)</version>").strip()
        tag_publicada = find_single_match(data,"<tag>([^<]+)</tag>").strip()

        version_local = find_single_match(data2,"<version>([^<]+)</version>").strip()
        tag_local = find_single_match(data,"<tag>([^<]+)</tag>").strip()

        try:
            numero_version_publicada = int(version_publicada)
            xbmc.log('number remote version:' + version_publicada)
            numero_version_local = int(version_local)
            xbmc.log('number local version:' + version_local)
        except:
            version_publicada = ""
            
            xbmc.log('number local version:' + version_local )
            xbmc.log('Check fail !@*')
        if version_publicada!="" and version_local!="":
            if (numero_version_publicada > numero_version_local):
                AddonID = 'plugin.video.kodilivetv'
                addon       = xbmcaddon.Addon(AddonID)
                addonname   = addon.getAddonInfo('name')
                extpath = os.path.join(xbmc.translatePath("special://home/addons/").decode("utf-8")) 
                addon_data_dir = os.path.join(xbmc.translatePath("special://userdata/addon_data" ).decode("utf-8"), AddonID) 
                dest = addon_data_dir + '/lastupdate.zip'                
                
                UPDATE_URL = 'http://kodilive.eu/repo/plugin.video.kodilivetv-' + tag_publicada + '.zip'
                xbmc.log('START DOWNLOAD UPDATE:' + UPDATE_URL)
                
                DownloaderClass(UPDATE_URL,dest)  

                import ziptools
                unzipper = ziptools.ziptools()
                unzipper.extract(dest,extpath)
                
                line7 = 'New version installed .....'
                line8 = 'Version: ' + tag_publicada 
                
                xbmcgui.Dialog().ok('Kodi Live TV', line7, line8)
                
                if os.remove( dest ): xbmc.log('TEMPORARY ZIP REMOVED') 
            else:
                AddonID = 'plugin.video.kodilivetv'
                addon = xbmcaddon.Addon(AddonID)
                addonname = addon.getAddonInfo('name')
                icon = xbmcaddon.Addon(AddonID).getAddonInfo('icon')
                xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(addonname,"Check updates: no update is available", 3200, icon))
                xbmc.log('No updates are available' )
Example #27
0
def install_alfa_assistant(update=False, remote='', verbose=False):
    if update:
        logger.info('update=%s' % str(update))
    # Si ya está instalada, devolvemos el control
    app_name = 'com.alfa.alfamobileassistant'
    if not verbose: verbose = config.get_setting('addon_update_message')        # Verbose en la actualización/instalación
    assistant_flag_install = config.get_setting('assistant_flag_install', default=True)
    addonid = 'alfa-mobile-assistant'
    download = addonid + '.apk'
    package = addonid + '.apk'
    version = addonid + '.version'
    forced_menu = False
    respuesta = False
    alfa_s = True
    addons_path = config.get_runtime_path()
    if filetools.exists(filetools.join(addons_path, 'channels', 'custom.py')):
        alfa_s = False

    if not remote:
        ANDROID_STORAGE = os.getenv('ANDROID_STORAGE')
        if not ANDROID_STORAGE: ANDROID_STORAGE = '/storage'
    else:
        # Remote es la url de un servidor FTP o SMB activo que apunta a la ruta "/storage" del dispositivo Android
        ANDROID_STORAGE = remote
        if ANDROID_STORAGE.endswith('/'):
            ANDROID_STORAGE = ANDROID_STORAGE[:-1]
    apk_files = '%s/%s/%s/%s/%s/%s' % (ANDROID_STORAGE, 'emulated', '0', 'Android', 'data', app_name)
    if ASSISTANT_MODE == 'este' and not filetools.exists(filetools.dirname(apk_files)):
        apk_files_alt = scrapertools.find_single_match(os.getenv('HOME'), '(.*?)\/\w*.\w*.\w*\/files')
        logger.info('HOME: ' + apk_files_alt)
        if apk_files_alt and filetools.exists(apk_files_alt):
            apk_files = '%s/%s' % (apk_files_alt, app_name)

    version_path = filetools.join(config.get_data_path(), version)
    version_act = filetools.read(version_path, silent=True)
    if not version_act: version_act = '0.0.0'
    
    # Averiguamos si es instalacción, update, o forzado desde el Menú de Ajustes
    if not update and ASSISTANT_MODE == 'este' and filetools.exists(apk_files):
        return version_act, app_name
    if ASSISTANT_MODE == 'este' and not update:
        check_permissions_alfa_assistant()                                      # activamos la app por si no se ha inicializado
        time.sleep(1)
        if filetools.exists(apk_files):
            return version_act, app_name
    # Mirarmos si la app está activa y obtenemos el nº de versión
    version_dict = get_generic_call('getWebViewInfo', timeout=2-EXTRA_TIMEOUT, alfa_s=True)
    if isinstance(version_dict, dict):
        version_app = version_dict.get('assistantVersion', '')
        try:
            android_version = int(scrapertools.find_single_match(version_dict.get('userAgent', ''), r"Android\s*(\d+)"))
        except:
            android_version = 8
    else:
        version_app = version_dict
        android_version = 8
    if version_app and not update:
        return version_app, app_name
    
    if version_app:
        app_active = True
    else:
        app_active = False
        if ASSISTANT_MODE == "este":
            execute_in_alfa_assistant_with_cmd('open')                          # activamos la app por si no se ha inicializado
            time.sleep(5)
            version_dict = get_generic_call('getWebViewInfo', timeout=2-EXTRA_TIMEOUT, alfa_s=True)
            if isinstance(version_dict, dict):
                version_app = version_dict.get('assistantVersion', '')
                try:
                    android_version = int(scrapertools.find_single_match(version_dict.get('userAgent', ''), r"Android\s*(\d+)"))
                except:
                    android_version = 8
            else:
                version_app = version_dict
                android_version = 8
    version_actual = filetools.read(version_path, silent=True)
    if not version_actual and version_app:
        version_actual = version_app
        filetools.write(version_path, version_actual, mode='wb', silent=True)
    elif not version_actual:
        version_actual = '0.0.0'

    if ASSISTANT_MODE != 'este':
        if not version_app:
            if verbose or (update and not isinstance(update, bool)):
                platformtools.dialog_notification("Active Alfa Assistant", 
                            "o Instale manualmente desde [COLOR yellow]https://bit.ly/2Zwpfzq[/COLOR]")
            logger.info("Active Alfa Assistant, o Instale manualmente desde [COLOR yellow]https://bit.ly/2Zwpfzq[/COLOR]", force=True)
            config.set_setting('assistant_flag_install', False)
            return version_app, app_name
        else:
            config.set_setting('assistant_flag_install', True)
            if not update:
                return version_app, app_name
    elif not update and not assistant_flag_install and not filetools.exists(apk_files):
        logger.info('NO está instalada. El usuario no quiere instalaciñon automática: %s' % app_name)
        return False, app_name
    elif update and isinstance(update, bool) and not filetools.exists(apk_files):
        logger.info('NO está instalada. No se va a actualizar: %s' % app_name)
        return False, app_name
    elif update and not isinstance(update, bool) and not filetools.exists(apk_files):
        logger.info('NO está instalada. Viene del Menú y se va a instalar: %s' % app_name)
        update = False
        forced_menu = True
    elif not remote and not xbmc.getCondVisibility("system.platform.android"):
        logger.info('El sistema local no es Android: %s' % app_name)
        return False, app_name

    logger.info('assistant_mode=%s, update=%s, forced_menu=%s, assistant_flag_install=%s, version_actual=%s, version_app=%s, android=%s, app_active=%s' \
            % (ASSISTANT_MODE, str(update), str(forced_menu), str(assistant_flag_install), version_actual, \
            version_app, str(android_version), str(app_active)))
    
    # Si no está instalada, o se quiere actualizar, empezamos el proceso
    alfa_assistant_pwd = ''
    assistant_urls = ['https://github.com/alfa-addon/alfa-repo/raw/master/downloads/assistant/%s' % version, \
            'https://bitbucket.org/alfa_addon/alfa-repo/raw/master/downloads/assistant/%s' % version]
    
    apk_updated = filetools.join(addons_path, 'tools')
    apk_path = filetools.join(apk_updated, download)
    apk_apk = filetools.join(apk_updated, package)
    upk_install_path = filetools.join('special://xbmc/', 'files').replace('/cache/apk/assets', '')
    if not remote:
        apk_install = filetools.join(ANDROID_STORAGE, 'emulated', '0', 'Download')
        apk_install_SD = filetools.join(apk_install, package)
    else:
        apk_install = '%s/%s/%s/%s' % (ANDROID_STORAGE, 'emulated', '0', 'Download')
        apk_install_SD = '%s/%s' % (apk_install, package)

    if not update and not remote and not forced_menu:
        # Probamos a iniciar por si se ha instalado manualmente y no se ha iniciado la estrucutra de archivos
        check_permissions_alfa_assistant()
        try:
            command = ['pm', 'list', 'packages']
            p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            PM_LIST, error_cmd = p.communicate()
            if PY3 and isinstance(label_a, bytes):
                PM_LIST = PM_LIST.decode()
            if app_name in PM_LIST:
                logger.info('Ya instalada. Volvemos: %s' % app_name)
                return version_actual, app_name
        except:
            logger.error(traceback.format_exc(1))
    
    if not update and not forced_menu and not platformtools.dialog_yesno("Instalación Alfa Assistant", \
                    "¿Desea instalar la App [COLOR yellow][B]%s[/B][/COLOR]\n" % app_name +
                    " como ayuda para acceder a ciertos canales y servidores?"):
        config.set_setting('assistant_flag_install', False)
        return respuesta, app_name
    elif update and not isinstance(update, bool):
        platformtools.dialog_notification("Instalación Alfa Assistant", "Comienza la actualización")
    elif forced_menu:
        platformtools.dialog_notification("Instalación Alfa Assistant", "Comienza la instalación")

    # Comprobamos si el dispositivo está rooteado
    is_rooted = config.is_rooted(silent=True)                                   # ¡OJO! puede pedir permisos root en algunos dispositivos
    if is_rooted == 'rooted' and ASSISTANT_MODE == 'este':                      # El dispositivo esta rooteado?
        update_install = 'py'                                                   # Se actualiza desde esta función
    else:
        update_install = 'app'                                                  # Se actualiza desde la app
    cmd = 'update'                                                              # Comando de la app para auto actualizarse
    dataURI = 'Version:%s'                                                      # Versión a actualizar
    
    # Comprobamos si hay acceso a Github o BitBucket
    for assistant_rar in assistant_urls:
        response = httptools.downloadpage(assistant_rar, timeout=5, ignore_response_code=True, alfa_s=alfa_s, json_to_utf8=False)
        if response.sucess:
            break
    
    # Descargamos el archivo de version.  Si hay error avisamos, pero continuamos
    if not response.sucess:
        if update and isinstance(update, bool):
            logger.error("Error en la descarga de control de versión. No se puede actualizar: %s" % str(response.code))
            return respuesta, app_name
        platformtools.dialog_notification("Instalación Alfa Assistant", "Error en la descarga de control de versión. Seguimos")
        logger.error("Error en la descarga de control de versión. Seguimos...: %s" % str(response.code))

    #Si es una actualización programada, comprobamos las versiones de Github y de lo instalado
    if update and isinstance(update, bool):
        if version_actual != response.data:
            if version_app:
                version_actual = version_app
                filetools.write(version_path, version_actual, mode='wb', silent=True)
        if version_actual == response.data:
            if verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Ya está actualizado a version %s" % response.data)
            logger.info("Alfa Assistant ya actualizado a versión: %s" % response.data)
            if not app_active and ASSISTANT_MODE == "este":
                execute_in_alfa_assistant_with_cmd('quit')                      # desactivamos la app si no estaba iniciada
            return version_actual, app_name

    # Guardamos archivo de versión
    if remote:
        version_path = '%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s/%s' % (ANDROID_STORAGE, 'emulated', '0', 'Android', 
                        'data', 'org.xbmc.kodi', 'files', '.kodi', 'addons', 'plugin.video.alfa', 
                        'tools', version)
        if not filetools.exists(filetools.dirname(version_path)):
            logger.error("Ruta a carpeta remota de versión no es estándar: %s" % version_path)
            version_path = ''
    version_old = version_actual
    version_actual = response.data
    if version_path:
        res = filetools.write(version_path, response.data, mode='wb', silent=True)
        if not res:
            if not update: platformtools.dialog_notification("Instalación Alfa Assistant", \
                            "Error en la escritura de control de versión. Seguimos...")
            logger.error("Error en la escritura de control de versión. Seguimos...: %s" % assistant_rar)

    # Descargamos y guardamos el .APK
    assistant_rar = assistant_rar.replace(version, download)                    # Sustituir en la url la versión por el apk
    res = False
    if not update: platformtools.dialog_notification("Instalación Alfa Assistant", "Descargando APK")
    logger.info('Descargando de_ %s' % assistant_rar)
    response = httptools.downloadpage(assistant_rar, timeout=5, ignore_response_code=True, alfa_s=alfa_s, json_to_utf8=False)
    if not response.sucess:
        if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error en la descarga del .apk")
        response.data = ''
        logger.error("Error en la descarga del .apk: %s" % str(response.code))
    else:
        # Guardamos archivo descargado de APK
        res = filetools.write(apk_path, response.data, mode='wb', silent=True)
        if not res:
            if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error en la escritura del APK")
            logger.error("Error en la escritura del APK: %s" % apk_path)
        
        else:
            if '.rar' in download:
                # Empezando la extracción del .rar del APK
                try:
                    import rarfile
                    archive = rarfile.RarFile(apk_path)
                    if alfa_assistant_pwd: archive.setpassword(alfa_assistant_pwd)
                    archive.extractall(apk_updated)
                except:
                    logger.error(traceback.format_exc(1))
            elif '.zip' in download:
                # Empezando la extracción del .rar del APK
                try:
                    import ziptools
                    archive = ziptools.ziptools()
                    #if alfa_assistant_pwd: archive.setpassword(alfa_assistant_pwd)      # No hay password en .zip
                    archive.extract(filetools.basename(apk_updated), filetools.dirname(apk_updated))
                except:
                    xbmc.executebuiltin('Extract("%s","%s")' % (filetools.basename(apk_updated), filetools.dirname(apk_updated)))
                    time.sleep(1)

            # Verificado si está el APK, y si está y es LOCAL lo instalamos
            if ASSISTANT_MODE == "este":
                res = filetools.copy(apk_apk, apk_install_SD, silent=True)
                if not res or not filetools.exists(apk_install_SD):
                    if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error de Extracción o Copia %s" % package)
                    logger.error("Error de Extracción o copia %s" % package)
                
                # Si está rooteado se instala/actualiza directamente
                elif update_install == 'py' and res and filetools.exists(apk_install_SD):

                    # Instalamos: nueva o actualización. 
                    if not update: platformtools.dialog_notification("Instalación Alfa Assistant", "Installando %s" % package)
                    logger.info("Installing %s" % package)
                    
                    # Instalación Remota
                    if remote:
                        filetools.remove(apk_apk, silent=True)
                        platformtools.dialog_notification("Alfa Assistant: Descarga Remota terminada", "Instale manualmente desde: %s" % apk_install_SD)
                        logger.info("Alfa Assistant: Descarga Remota terminada. Instale manualmente desde: %s" % apk_install_SD)
                        return version_actual, app_name

                    # Instalación Local
                    if not filetools.exists(upk_install_path):
                        filetools.mkdir(upk_install_path)
                    upk_install_path = filetools.join(upk_install_path, package)
                    res = filetools.copy(apk_install_SD, upk_install_path, ch_mod='777')    # Copiamos APK a la partición del Sistema, y cambiamos permisos
                    if not res:
                        if not update or verbose: platformtools.dialog_notification("Instalación Alfa Assistant", "Error de Copia %s" % package)
                        logger.error(str(filetools.listdir(apk_install)))
                        logger.error(filetools.file_info(filetools.dirname(upk_install_path)))
                        logger.error(str(filetools.listdir(filetools.dirname(upk_install_path), file_inf=True)))
                    else:

                        # Intenta la instalación vía ROOT y si no funciona como NO ROOT
                        
                        # Marcamos la opción de instalación, -r si es actualización, -g (todos los permisos granted) si es instalación
                        if filetools.exists(apk_files):
                            pm_opt = '-r'
                        else:
                            pm_opt = '-g'
                        
                        # Listamos todas las opciones de comandos, según las variantes de Android
                        command_list = [
                                        ['adb', 'install', '%s' % upk_install_path],
                                        ['su', '-c', 'pm install %s %s' % (pm_opt, upk_install_path)],
                                        ['su', '-c', 'pm', 'install', pm_opt, '%s' % upk_install_path],
                                        ['su', '-0', 'pm install %s %s' % (pm_opt, upk_install_path)],
                                        ['su', '-0', 'pm', 'install', pm_opt, '%s' % upk_install_path]
                                       ]
                        
                        for command in command_list:
                            try:
                                logger.info(command, force=True)
                                p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
                                output_cmd, error_cmd = p.communicate()
                                if error_cmd:
                                    if error_cmd.startswith('su:'): continue
                                    if update:
                                        ver_upd = get_generic_call('ping', timeout=2-EXTRA_TIMEOUT, alfa_s=True)
                                        if not ver_upd:
                                            execute_in_alfa_assistant_with_cmd('open')  # activamos la app por si no se ha inicializado
                                            time.sleep(5)
                                            ver_upd = get_generic_call('ping', timeout=2-EXTRA_TIMEOUT, alfa_s=True)
                                            execute_in_alfa_assistant_with_cmd('quit')
                                        if ver_upd == version_actual:
                                            logger.debug(str(error_cmd), force=True)
                                            error_cmd = ''
                                    else:
                                        check_permissions_alfa_assistant()
                                        time.sleep(1)
                                        if filetools.exists(apk_files):
                                            logger.debug(str(error_cmd), force=True)
                                            error_cmd = ''
                                    if error_cmd:
                                        logger.error(str(error_cmd))
                                    else:
                                        respuesta = version_actual
                                        break
                                else:
                                    respuesta = version_actual
                                    break
                            except Exception as e:
                                if not PY3:
                                    e = unicode(str(e), "utf8", errors="replace").encode("utf8")
                                logger.error('Command ERROR: %s, %s' % (str(command), str(e)))
                                continue
      
    # Ùltimo resorte: instalación manual desde GitHub o actualización desde la app
    if not respuesta and update:
        
        # Si hay que actualizar se verifica el vehículo de instalación
        logger.info("Instalación Alfa Assistant. Actualización desde la app de %s a %s" % (version_old, version_actual))
        version_mod = version_actual
        if not isinstance(update, bool):
            version_mod = '9.9.999'                                             # Intenta forzar la actualización si viene desde el Menú
        if ASSISTANT_MODE == "este":
            if android_version >= 10:
                app_active = False
                respuesta = execute_in_alfa_assistant_with_cmd(cmd, dataURI=dataURI % version_mod)
            else:
                if not app_active:
                    execute_in_alfa_assistant_with_cmd('openAndQuit')           # activamos la app por si no se ha inicializado
                    time.sleep(5)
                app_active = False
                respuesta = get_generic_call(cmd, version=version_mod, alfa_s=alfa_s)
        else:
            if app_active:
                respuesta = get_generic_call(cmd, version=version_mod, alfa_s=alfa_s)

        if not respuesta and ASSISTANT_MODE != "este":
            if verbose or not isinstance(update, bool):
                platformtools.dialog_notification("Instalación Alfa Assistant", "Intente la actualización manualmente %s" % version_actual)
            logger.info("Instalación Alfa Assistant. Intente la actualización manualmente %s" % version_actual)
            return False, app_name
        elif not respuesta:
            # Update local
            #respuesta = execute_in_alfa_assistant_with_cmd(cmd, dataURI=dataURI % version_mod)
            if not respuesta:
                if verbose or not isinstance(update, bool):
                    platformtools.dialog_notification("Instalación Alfa Assistant", "Actualización en error %s. REINTENTANDO" % version_actual)
                logger.info("Instalación Alfa Assistant. Actualización en error %s. REINTENTANDO" % version_actual)
        else:
            respuesta = version_actual
        
    if not respuesta:
        config.set_setting('assistant_flag_install', False)                     # No vuelve a intentar la instalación
        try:
            #xbmc.executebuiltin('StartAndroidActivity("","android.intent.action.VIEW","application/vnd.android.package-archive","file:%s")' % apk_install_SD)
            
            if ASSISTANT_MODE == "este":
                from lib import generictools
                assistant_rar = assistant_rar.replace('/raw/', '/tree/')            # Apuntar a la web de descargas
                browser, res = generictools.call_browser(assistant_rar, lookup=True)
                if browser:
                    filetools.remove(apk_install_SD, silent=True)
                    platformtools.dialog_ok("Alfa Assistant: Instale desde [COLOR yellow]%s[/COLOR]" % browser.capitalize(), 
                                    "O Instale manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_install_SD)
                    logger.info('Browser: %s, Ruta: %s' % (browser.capitalize(), apk_install_SD))
                    time.sleep(5)
                    browser, res = generictools.call_browser(assistant_rar, dataType='application/vnd.android.package-archive')
                    filetools.remove(apk_path, silent=True)
                    filetools.remove(upk_install_path, silent=True)
                else:
                    logger.error('Error de Instalación: NO Browser, Ruta: %s' % apk_install_SD)
                    raise
            else:
                logger.error('Error de Instalación: no se puede instalar en remoto: %s' % ASSISTANT_SERVER)
                raise
        except:
            if ASSISTANT_MODE == "este":
                platformtools.dialog_ok("Alfa Assistant: Error", "Instale manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_install_SD)
                logger.error("Alfa Assistant: Error. Instale manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_install_SD)
                filetools.remove(apk_path, silent=True)
                filetools.remove(upk_install_path, silent=True)
            else:
                platformtools.dialog_ok("Alfa Assistant: Error", "Copie a Android manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_apk)
                logger.error("Alfa Assistant: Error. Copie a Android manualmente desde: [COLOR yellow]%s[/COLOR]" % apk_apk)
            logger.error(traceback.format_exc(1))

    if respuesta:
        if update:
            if verbose or not isinstance(update, bool): platformtools.dialog_notification("Alfa Assistant", \
                                "Actualización con exito: %s" % respuesta)
            logger.info("Actualización terminada con éxito: %s" % respuesta)
        else:
            platformtools.dialog_notification("Alfa Assistant", "Instalación con exito: %s" % respuesta)
            logger.info("Instalación terminada con éxito: %s" % respuesta)
        filetools.remove(apk_path, silent=True)
        filetools.remove(apk_install_SD, silent=True)
        filetools.remove(upk_install_path, silent=True)
        if not update and not forced_menu:
            time.sleep(1)
            check_permissions_alfa_assistant()
            time.sleep(1)
        if app_active and ASSISTANT_MODE == "este":
            execute_in_alfa_assistant_with_cmd('open')                          # re-activamos la app para dejarla como estaba
        
    return respuesta, app_name