Python xbmcvfs.delete() Examples

The following are 30 code examples of xbmcvfs.delete(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module xbmcvfs , or try the search function .
Example #1
Source File: vpnplatform.py    From service.vpn.manager with GNU General Public License v2.0 6 votes vote down vote up
def copySystemdFiles():
    # Delete any existing openvpn.service and copy openvpn service file to config directory
    service_source = getAddonPath(True, "openvpn.service")
    service_dest = getSystemdPath("system.d/openvpn.service")
    debugTrace("Copying openvpn.service " + service_source + " to " + service_dest)
    if not fakeSystemd():
        if xbmcvfs.exists(service_dest): xbmcvfs.delete(service_dest)
        xbmcvfs.copy(service_source, service_dest)
        if not xbmcvfs.exists(service_dest): raise IOError('Failed to copy service ' + service_source + " to " + service_dest)
    
    # Delete any existing openvpn.config and copy first VPN to openvpn.config
    config_source = sudo_setting = xbmcaddon.Addon(getID()).getSetting("1_vpn_validated")
    if service_source == "": errorTrace("vpnplatform.py", "Nothing has been validated")
    config_dest = getSystemdPath("openvpn.config")
    debugTrace("Copying openvpn.config " + config_source + " to " + config_dest)
    if not fakeSystemd():
        if xbmcvfs.exists(config_dest): xbmcvfs.delete(config_dest)
        xbmcvfs.copy(config_source, config_dest)
        if not xbmcvfs.exists(config_dest): raise IOError('Failed to copy service ovpn ' + config_source + " to " + config_dest) 
Example #2
Source File: __init__.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def get_credentials():

    path = xbmc.translatePath("special://profile/addon_data/plugin.video.emby/").decode('utf-8')
    
    if not xbmcvfs.exists(path):
        xbmcvfs.mkdirs(path)

    try:
        with open(os.path.join(path, 'data.json')) as infile:
            credentials = json.load(infile)
    except Exception:

        try:
            with open(os.path.join(path, 'data.txt')) as infile:
                credentials = json.load(infile)
                save_credentials(credentials)
            
            xbmcvfs.delete(os.path.join(path, 'data.txt'))
        except Exception:
            credentials = {}

    credentials['Servers'] = credentials.get('Servers', [])

    return credentials 
Example #3
Source File: playerMP3.py    From bugatsinho.github.io with GNU General Public License v3.0 6 votes vote down vote up
def deleteFile(filename):
    log('Deleting %s' % filename)

    if len(filename) < 1:
        log('Empty filename')
        return

    try:    current = xbmc.Player().getPlayingFile() if xbmc.Player().isPlaying() else ''
    except: current = ''

    while current == filename:
        try:    current = xbmc.Player().getPlayingFile() if xbmc.Player().isPlaying() else ''
        except: current = ''
        xbmc.sleep(1000)

    tries = 15
    while xbmcvfs.exists(filename) and tries > 0:
        tries -= 1 
        try: 
            xbmcvfs.delete(filename)
        except Exception, e: 
            log('ERROR %s in deleteFile %s' % (str(e), filename))
            log('ERROR tries=%d' % tries)
            xbmc.sleep(500) 
Example #4
Source File: utils.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def delete_folder(path=None):

    ''' Delete objects from kodi cache
    '''
    LOG.debug("--[ delete folder ]")
    delete_path = path is not None
    path = path or xbmc.translatePath('special://temp/emby').decode('utf-8')
    dirs, files = xbmcvfs.listdir(path)

    delete_recursive(path, dirs)

    for file in files:
        xbmcvfs.delete(os.path.join(path, file.decode('utf-8')))

    if delete_path:
        xbmcvfs.delete(path)
    
    LOG.warn("DELETE %s", path) 
Example #5
Source File: dbupdate.py    From romcollectionbrowser with GNU General Public License v2.0 6 votes vote down vote up
def download_thumb(self, thumburl, destfilename):
        log.info("begin download_thumb using requests module: thumburl = %s" % thumburl)

        # Download file to tmp folder
        tmp = util.joinPath(util.getTempDir(), os.path.basename(destfilename))

        log.info("download_thumb: start downloading to temp file: %s" % tmp)
        response = requests.get(thumburl, headers=WebScraper._headers, stream=True)
        log.info("download_thumb: status code = %s" % response.status_code)
        if response.status_code != 200:
            log.info("download_thumb: invalid response status code. Can't download image.")
            return

        with open(tmp, 'wb') as f:
            response.raw.decode_content = True
            shutil.copyfileobj(response.raw, f)

        log.info("download_thumb: copy from temp file to final destination: %s" % destfilename)

        # Copy from the tmp folder to the target location
        xbmcvfs.copy(tmp, destfilename)
        xbmcvfs.delete(tmp)
        log.info("end download_thumb") 
Example #6
Source File: filetools.py    From addon with GNU General Public License v3.0 6 votes vote down vote up
def remove(path, silent=False, vfs=True):
    """
    Elimina un archivo
    @param path: ruta del fichero a eliminar
    @type path: str
    @rtype: bool
    @return: devuelve False en caso de error
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            return bool(xbmcvfs.delete(path))
        elif path.lower().startswith("smb://"):
            samba.remove(path)
        else:
            os.remove(path)
    except:
        logger.error("ERROR al eliminar el archivo: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
            platformtools.dialog_notification("Error al eliminar el archivo", path)
        return False
    else:
        return True 
Example #7
Source File: util.py    From xbmc.service.pushbullet with GNU General Public License v3.0 6 votes vote down vote up
def youtubeDLDownload(self,vid,path,target=None):
        import YDStreamExtractor as StreamExtractor 
        import YDStreamUtils as StreamUtils    
        if not target: target = self.chooseDirectory()
        if not target: return
        
        with StreamUtils.DownloadProgress() as prog:
            try:
                StreamExtractor.disableDASHVideo(True)
                StreamExtractor.setOutputCallback(prog)
                result = StreamExtractor.downloadVideo(vid,path)
            finally:
                StreamExtractor.setOutputCallback(None)
        if not result and result.status != 'canceled':
                xbmcgui.Dialog().ok(T(32103),'[CR]',result.message)
        elif result:
            xbmcgui.Dialog().ok(T(32062),T(32104),'[CR]',result.filepath)
        if target:
            xbmcvfs.copy(result.filepath,os.path.join(target,os.path.basename(result.filepath)))
            xbmcvfs.delete(result.filepath) 
Example #8
Source File: filemanager.py    From script.artwork.beef with MIT License 6 votes vote down vote up
def remove_deselected_files(self, mediaitem, assignedart=False):
        if self.debug:
            return
        for arttype, newimage in mediaitem.selectedart.iteritems():
            if newimage is not None:
                continue
            if assignedart:
                oldimage = mediaitem.art.get(arttype)
            else:
                oldimage = mediaitem.forcedart.get(arttype)
            if not oldimage:
                continue
            old_url = oldimage['url'] if isinstance(oldimage, dict) else \
                oldimage if isinstance(oldimage, basestring) else oldimage[0]['url']
            if not old_url or old_url.startswith(pykodi.notimagefiles) \
            or old_url in mediaitem.selectedart.values() or not xbmcvfs.exists(old_url):
                continue
            if settings.recycle_removed:
                recyclefile(old_url)
            xbmcvfs.delete(old_url) 
Example #9
Source File: reporting.py    From script.artwork.beef with MIT License 6 votes vote down vote up
def _rotate_file():
    newdate = ndate = pykodi.get_infolabel('System.Date(yyyy-mm-dd)')
    count = 0
    while _exists(newdate):
        count += 1
        newdate = ndate + '.' + str(count)
    if not xbmcvfs.copy(_get_filepath(), _get_filepath(newdate)):
        log("Could not copy latest report to new filename", xbmc.LOGWARNING, 'reporting')
        return False
    if not xbmcvfs.delete(_get_filepath()):
        log("Could not delete old copy of latest report", xbmc.LOGWARNING, 'reporting')
        return False

    # delete old reports
    _, files = xbmcvfs.listdir(settings.datapath)
    reportfiles = sorted(f[:-4] for f in files if f.startswith(REPORT_NAME))
    while len(reportfiles) > REPORT_COUNT:
        filename = reportfiles[0] + '.txt'
        if not xbmcvfs.delete(settings.datapath + filename):
            log("Could not delete old report '{0}'".format(filename), xbmc.LOGWARNING, 'reporting')
            return False
        del reportfiles[0]
    report_startup()
    return True 
Example #10
Source File: sopcast.py    From program.plexus with GNU General Public License v2.0 6 votes vote down vote up
def onPlayBackStopped(self):
        self._playbackLock = False
        url = "http://" + LOCAL_IP + ":" + str(VIDEO_PORT) + "/"
        xbmc.sleep(300)
        if os.path.exists("/proc/" + str(self.spsc_pid)) and xbmc.getCondVisibility(
                "Window.IsActive(epg.xml)") and settings.getSetting('safe_stop') == "true":
            if not xbmc.Player().isPlaying():
                player = streamplayer(spsc_pid=self.spsc_pid, listitem=self.listitem)
                player.play(url, self.listitem)
        else:
            try:
                os.kill(self.spsc_pid, 9)
            except:
                pass
        try:
            xbmcvfs.delete(os.path.join(pastaperfil, 'sopcast.avi'))
        except:
            pass 
Example #11
Source File: fileops.py    From plugin.video.netflix with MIT License 6 votes vote down vote up
def delete_folder_contents(path, delete_subfolders=False):
    """
    Delete all files in a folder
    :param path: Path to perform delete contents
    :param delete_subfolders: If True delete also all subfolders
    """
    directories, files = list_dir(path)
    for filename in files:
        xbmcvfs.delete(os.path.join(path, filename))
    if not delete_subfolders:
        return
    for directory in directories:
        delete_folder_contents(os.path.join(path, directory), True)
        # Give time because the system performs previous op. otherwise it can't delete the folder
        xbmc.sleep(80)
        xbmcvfs.rmdir(os.path.join(path, directory)) 
Example #12
Source File: db.py    From plugin.program.openwizard with GNU General Public License v3.0 6 votes vote down vote up
def fix_update():
    if os.path.exists(os.path.join(CONFIG.USERDATA, 'autoexec.py')):
        temp = os.path.join(CONFIG.USERDATA, 'autoexec_temp.py')
        if os.path.exists(temp):
            xbmcvfs.delete(temp)
        xbmcvfs.rename(os.path.join(CONFIG.USERDATA, 'autoexec.py'), temp)
    xbmcvfs.copy(os.path.join(CONFIG.PLUGIN, 'resources', 'libs', 'autoexec.py'),
                 os.path.join(CONFIG.USERDATA, 'autoexec.py'))
    dbfile = os.path.join(CONFIG.DATABASE, latest_db('Addons'))
    try:
        os.remove(dbfile)
    except:
        logging.log("Unable to remove {0}, Purging DB".format(dbfile))
        purge_db_file(dbfile)

    from resources.libs.common import tools
    tools.kill_kodi(over=True) 
Example #13
Source File: userdefined.py    From service.vpn.manager with GNU General Public License v2.0 6 votes vote down vote up
def clearUserData():
    # Deleting everything here, but not deleting 'DEFAULT.txt' as 
    # any existing user and password info will get deleted
    path = getUserDataPath("UserDefined" + "/*.*")
    debugTrace("Deleting contents of User Defined directory" + path)
    files = glob.glob(path)
    try:
        for file in files:
            if not file.endswith("DEFAULT.txt") and xbmcvfs.exists(file): 
                debugTrace("Deleting " + file)
                xbmcvfs.delete(file)
    except Exception as e:
        errorTrace("userdefined.py", "Couldn't clear the UserDefined directory")
        errorTrace("userdefined.py", str(e))
        return False
    return True 
Example #14
Source File: main.py    From plugin.video.iptv.recorder with GNU General Public License v3.0 5 votes vote down vote up
def delete_ffmpeg():
    if xbmc.getCondVisibility('system.platform.android'):
        ffmpeg_dst = '/data/data/%s/ffmpeg' % android_get_current_appid()
        xbmcvfs.delete(ffmpeg_dst) 
Example #15
Source File: downloader.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 5 votes vote down vote up
def recursive_delete_dir(self, fullpath):
        '''helper to recursively delete a directory'''
        success = True
        if not isinstance(fullpath, unicode):
            fullpath = fullpath.decode("utf-8")
        dirs, files = xbmcvfs.listdir(fullpath)
        for file in files:
            file = file.decode("utf-8")
            success = xbmcvfs.delete(os.path.join(fullpath, file))
        for directory in dirs:
            directory = directory.decode("utf-8")
            success = self.recursive_delete_dir(os.path.join(fullpath, directory))
        success = xbmcvfs.rmdir(fullpath)
        return success 
Example #16
Source File: dialog.py    From script.module.clouddrive.common with GNU General Public License v3.0 5 votes vote down vote up
def __del__(self):
        xbmcvfs.delete(self._image_path)
        pass 
Example #17
Source File: kodiutils.py    From script.module.inputstreamhelper with MIT License 5 votes vote down vote up
def delete(path):
    """Remove a file (using xbmcvfs)"""
    from xbmcvfs import delete as vfsdelete
    log(2, "Delete file '{path}'.", path=path)
    return vfsdelete(from_unicode(path)) 
Example #18
Source File: backup.py    From plugin.program.openwizard with GNU General Public License v3.0 5 votes vote down vote up
def _backup_info(self, name, extractsize, programs, video, music, picture, repos, scripts, binaries):
        backup_path = CONFIG.MYBUILDS
        zipname = name + '.zip'
        txtname = name + '.txt'
        backup_zip = os.path.join(backup_path, zipname)
        temp_txt = os.path.join(CONFIG.PACKAGES, txtname)
        info_txt = os.path.join(backup_path, txtname)
        
        _skin_root = xbmc.translatePath('special://skin/')
        _skin_id = os.path.basename(os.path.normpath(_skin_root))
        _skin = xbmcaddon.Addon(_skin_id)
        _skin_name = xbmc.translatePath(_skin.getAddonInfo('name'))

        with open(temp_txt, 'w') as f:
            f.write('name="{0}"\n'.format(name))
            f.write('extracted="{0}"\n'.format(extractsize))
            f.write('zipsize="{0}"\n'.format(os.path.getsize(backup_zip)))
            f.write('skin="{0}"\n'.format(_skin_name))
            f.write('created="{0}"\n'.format(tools.get_date(formatted=True)))
            f.write('programs="{0}"\n'.format(', '.join(programs)) if len(programs) > 0 else 'programs="none"\n')
            f.write('video="{0}"\n'.format(', '.join(video)) if len(video) > 0 else 'video="none"\n')
            f.write('music="{0}"\n'.format(', '.join(music)) if len(music) > 0 else 'music="none"\n')
            f.write('picture="{0}"\n'.format(', '.join(picture)) if len(picture) > 0 else 'picture="none"\n')
            f.write('repos="{0}"\n'.format(', '.join(repos)) if len(repos) > 0 else 'repos="none"\n')
            f.write('scripts="{0}"\n'.format(', '.join(scripts)) if len(scripts) > 0 else 'scripts="none"\n')
            f.write('binaries="{0}"\n'.format(', '.join(binaries)) if len(binaries) > 0 else 'binaries="none"\n')
            
        xbmcvfs.copy(temp_txt, info_txt)
        xbmcvfs.delete(temp_txt) 
Example #19
Source File: httpclient.py    From ru with GNU General Public License v2.0 5 votes vote down vote up
def drop_cookie(self):
        xbmcvfs.delete(self.cookie_path) 
Example #20
Source File: filetools.py    From addon with GNU General Public License v3.0 5 votes vote down vote up
def rename(path, new_name, silent=False, strict=False, vfs=True):
    """
    Renombra un archivo o carpeta
    @param path: ruta del fichero o carpeta a renombrar
    @type path: str
    @param new_name: nuevo nombre
    @type new_name: str
    @rtype: bool
    @return: devuelve False en caso de error
    """
    path = encode(path)
    try:
        if xbmc_vfs and vfs:
            path_end = path
            if path_end.endswith('/') or path_end.endswith('\\'):
                path_end = path_end[:-1]
            dest = encode(join(dirname(path_end), new_name))
            result = xbmcvfs.rename(path, dest)
            if not result and not strict:
                logger.error("ERROR al RENOMBRAR el archivo: %s.  Copiando y borrando" % path)
                if not silent:
                    dialogo = platformtools.dialog_progress("Copiando archivo", "")
                result = xbmcvfs.copy(path, dest)
                if not result:
                    return False
                xbmcvfs.delete(path)
            return bool(result)
        elif path.lower().startswith("smb://"):
            new_name = encode(new_name, True)
            samba.rename(path, join(dirname(path), new_name))
        else:
            new_name = encode(new_name, False)
            os.rename(path, os.path.join(os.path.dirname(path), new_name))
    except:
        logger.error("ERROR al renombrar el archivo: %s" % path)
        if not silent:
            logger.error(traceback.format_exc())
            platformtools.dialog_notification("Error al renombrar", path)
        return False
    else:
        return True 
Example #21
Source File: plugin_content.py    From plugin.audio.spotify with GNU General Public License v3.0 5 votes vote down vote up
def switch_user_multi(self):
        '''switch the currently logged in user'''
        usernames = []
        count = 1
        while True:
            username = self.addon.getSetting("username%s" % count).decode("utf-8")
            count += 1
            if not username:
                break
            else:
                display_name = ""
                try:
                    display_name = self.sp.user(username)["display_name"]
                except Exception:
                    pass
                if not display_name:
                    display_name = username
                usernames.append(display_name)
        dialog = xbmcgui.Dialog()
        ret = dialog.select(self.addon.getLocalizedString(11048), usernames)
        del dialog
        if ret != -1:
            ret += 1
            new_user = self.addon.getSetting("username%s" % ret)
            new_pass = self.addon.getSetting("password%s" % ret)
            self.addon.setSetting("username", new_user)
            self.addon.setSetting("password", new_pass)
            xbmcvfs.delete("special://profile/addon_data/%s/credentials.json" % ADDON_ID)
            self.win.setProperty("spotify-cmd", "__LOGOUT__")
            self.win.clearProperty("spotify-token")
            self.win.clearProperty("spotify-username")
            self.win.clearProperty("spotify-country")
            xbmc.executebuiltin("Container.Refresh") 
Example #22
Source File: plugin_content.py    From plugin.audio.spotify with GNU General Public License v3.0 5 votes vote down vote up
def logoff_user(self):
        ''' logoff user '''
        dialog = xbmcgui.Dialog()
        if dialog.yesno(self.addon.getLocalizedString(11066), self.addon.getLocalizedString(11067)):
            xbmcvfs.delete("special://profile/addon_data/%s/credentials.json" % ADDON_ID)
            xbmcvfs.delete("special://profile/addon_data/%s/spotipy.cache" % ADDON_ID)
            self.win.clearProperty("spotify-token")
            self.win.clearProperty("spotify-username")
            self.win.clearProperty("spotify-country")
            self.addon.setSetting("username", "")
            self.addon.setSetting("password", "")
            self.win.setProperty("spotify-cmd", "__LOGOUT__")
            xbmc.executebuiltin("Container.Refresh")
        del dialog 
Example #23
Source File: history.py    From program.plexus with GNU General Public License v2.0 5 votes vote down vote up
def remove_history():
	if xbmcvfs.exists(history_file):
		xbmcvfs.delete(history_file)
		xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(30000), translate(30017), 1,os.path.join(addonpath,"icon.png"))) 
Example #24
Source File: acecore.py    From program.plexus with GNU General Public License v2.0 5 votes vote down vote up
def __del__(self):
        self.log.out('delete') 
Example #25
Source File: sopcast.py    From program.plexus with GNU General Public License v2.0 5 votes vote down vote up
def onPlayBackStopped(self):
        self._playbackLock = False
        url = "http://"+LOCAL_IP+":"+str(VIDEO_PORT)+"/"
        xbmc.sleep(300)
        if os.path.exists("/proc/"+str(self.spsc_pid)) and xbmc.getCondVisibility("Window.IsActive(epg.xml)") and settings.getSetting('safe_stop')=="true":
            if not xbmc.Player(xbmc.PLAYER_CORE_AUTO).isPlaying(): 
                player = streamplayer(xbmc.PLAYER_CORE_AUTO , spsc_pid=self.spsc_pid , listitem=self.listitem)
                player.play(url, self.listitem)
        else:
            try: os.kill(self.spsc_pid,9)
            except: pass
        try:
        	xbmcvfs.delete(os.path.join(pastaperfil,'sopcast.avi'))
        except:
        	pass 
Example #26
Source File: sopcast.py    From program.plexus with GNU General Public License v2.0 5 votes vote down vote up
def onPlayBackEnded(self):
        url = "http://"+LOCAL_IP+":"+str(VIDEO_PORT)+"/"
        xbmc.sleep(300)
        if os.path.exists("/proc/"+str(self.spsc_pid)) and xbmc.getCondVisibility("Window.IsActive(epg.xml)") and settings.getSetting('safe_stop')=="true":
            if not xbmc.Player(xbmc.PLAYER_CORE_AUTO).isPlaying():
                player = streamplayer(xbmc.PLAYER_CORE_AUTO , spsc_pid=self.spsc_pid , listitem=self.listitem)
                player.play(url, self.listitem) 
        try:
        	xbmcvfs.delete(os.path.join(pastaperfil,'sopcast.avi'))
        except:
        	pass 
Example #27
Source File: advancedfunctions.py    From program.plexus with GNU General Public License v2.0 5 votes vote down vote up
def clear_cache(url):
	dirs, files = xbmcvfs.listdir(url)
	for fich in files:
		xbmcvfs.delete(os.path.join(url,fich))
	if files: xbmc.executebuiltin("Notification(%s,%s,%i,%s)" % (translate(40000), translate(40161), 1,addonpath+"/icon.png"))
	xbmc.executebuiltin("Container.Refresh") 
Example #28
Source File: advancedfunctions.py    From program.plexus with GNU General Public License v2.0 5 votes vote down vote up
def delete_advancedxml():
	userdatapath = xbmc.translatePath(os.path.join('special://home/userdata'.decode('utf-8'),''.decode('utf-8')))
	advancedsettings_var = os.path.join(userdatapath,'advancedsettings.xml')
	advancedsettingsbackup_var = os.path.join(userdatapath,'advancedsettingsbackup.xml')
	xbmcvfs.delete(advancedsettings_var)
	mensagemok(translate(40000),translate(40066))
	xbmc.executebuiltin("Container.Refresh") 
Example #29
Source File: advancedfunctions.py    From program.plexus with GNU General Public License v2.0 5 votes vote down vote up
def recoverbackup_advancedxml():
	userdatapath = xbmc.translatePath(os.path.join('special://home/userdata'.decode('utf-8'),''.decode('utf-8')))
	advancedsettings_var = os.path.join(userdatapath,'advancedsettings.xml')
	advancedsettingsbackup_var = os.path.join(userdatapath,'advancedsettingsbackup.xml')
	xbmcvfs.delete(advancedsettings_var)
	xbmcvfs.rename(advancedsettingsbackup_var,advancedsettings_var)
	mensagemok(translate(40000),translate(40062))
	xbmc.executebuiltin("Container.Refresh") 
Example #30
Source File: downloader.py    From plugin.video.themoviedb.helper with GNU General Public License v3.0 5 votes vote down vote up
def clear_dir(self, folder):
        for filename in os.listdir(folder):
            file_path = os.path.join(folder, filename)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                elif os.path.isdir(file_path):
                    self.recursive_delete_dir(file_path)
            except Exception as e:
                utils.kodi_log(u'Could not delete file {0}: {1}'.format(file_path, str(e)))