Python xbmcvfs 模块,delete() 实例源码

我们从Python开源项目中,提取了以下44个代码示例,用于说明如何使用xbmcvfs.delete()

项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def backup_theme(self, themename):
        '''backup a colortheme to a zipfile'''
        import zipfile
        backup_path = xbmcgui.Dialog().browse(3, self.addon.getLocalizedString(32029), "files").decode("utf-8")
        if backup_path:
            xbmc.executebuiltin("ActivateWindow(busydialog)")
            backup_name = u"%s ColorTheme - %s" % (get_skin_name().capitalize(), themename)
            backupfile = os.path.join(backup_path, backup_name + u".zip")
            zip_temp = u'special://temp/%s.zip' % backup_name
            xbmcvfs.delete(zip_temp)
            xbmcvfs.delete(backupfile)
            zip_temp = xbmc.translatePath(zip_temp).decode("utf-8")
            zip_file = zipfile.ZipFile(zip_temp, "w", zipfile.ZIP_DEFLATED)
            abs_src = os.path.abspath(xbmc.translatePath(self.userthemes_path).decode("utf-8"))
            for filename in xbmcvfs.listdir(self.userthemes_path)[1]:
                if (filename.startswith("%s_" % themename) or
                        filename.replace(".theme", "").replace(".jpg", "") == themename):
                    filename = filename.decode("utf-8")
                    filepath = xbmc.translatePath(self.userthemes_path + filename).decode("utf-8")
                    absname = os.path.abspath(filepath)
                    arcname = absname[len(abs_src) + 1:]
                    zip_file.write(absname, arcname)
            zip_file.close()
            xbmcvfs.copy(zip_temp, backupfile)
            xbmc.executebuiltin("Dialog.Close(busydialog)")
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def restore_colortheme(self):
        '''restore zipbackup of colortheme to colorthemes folder'''
        zip_path = xbmcgui.Dialog().browse(1, self.addon.getLocalizedString(32030), "files", ".zip")
        if zip_path and zip_path.endswith(".zip"):

            # create temp path
            temp_path = u'special://temp/skinbackup/'
            temp_zip = u"special://temp/colortheme.zip"
            if xbmcvfs.exists(temp_path):
                recursive_delete_dir(temp_path)
            xbmcvfs.mkdir(temp_path)

            # unzip to temp
            xbmcvfs.copy(zip_path, temp_zip)
            unzip_fromfile(temp_zip, temp_path)
            for filename in xbmcvfs.listdir(temp_path)[1]:
                filename = filename.decode("utf-8")
                sourcefile = os.path.join(temp_path, filename)
                destfile = os.path.join(self.userthemes_path, filename)
                xbmcvfs.copy(sourcefile, destfile)
            # cleanup temp
            xbmcvfs.delete(temp_zip)
            recursive_delete_dir(temp_path)
            xbmcgui.Dialog().ok(self.addon.getLocalizedString(32026), self.addon.getLocalizedString(32027))
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def __init__(self):

        #Check if a path has been set in the addon settings
        settings_path = common.addon.get_setting('meta_folder_location')

        if settings_path:
            self.path = xbmc.translatePath(settings_path)
        else:
            self.path = xbmc.translatePath('special://profile/addon_data/script.module.metahandler')

        self.work_path = os.path.join(self.path, 'work', '')
        self.cache_path = os.path.join(self.path,  'meta_cache')
        self.videocache = os.path.join(self.cache_path, 'video_cache.db')
        self.work_videocache = os.path.join(self.work_path, 'video_cache.db')
        self.movie_images = os.path.join(self.cache_path, 'movie')
        self.tv_images = os.path.join(self.cache_path, 'tvshow')        

        self.table_list = ['movie_meta', 'tvshow_meta', 'season_meta', 'episode_meta']

        common.addon.log('---------------------------------------------------------------------------------------', 0)
        #delete and re-create work_path to ensure no previous files are left over
        self._del_path(self.work_path)

        #Re-Create work folder
        self.make_dir(self.work_path)
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def _del_path(self, path):

        common.addon.log('Attempting to remove folder: %s' % path, 0)
        if xbmcvfs.exists(path):
            try:
                common.addon.log('Removing folder: %s' % path, 0)
                try:
                    dirs, files = xbmcvfs.listdir(path)
                    for file in files:
                        xbmcvfs.delete(os.path.join(path, file))
                    success = xbmcvfs.rmdir(path)
                    if success == 0:
                        raise
                except Exception, e:
                    try:
                        common.addon.log('Failed to delete path using xbmcvfs: %s' % e, 4)
                        common.addon.log('Attempting to remove with shutil: %s' % path, 0)
                        shutil.rmtree(path)
                    except:
                        raise
            except Exception, e:
                common.addon.log('Failed to delete path: %s' % e, 4)
                return False
        else:
            common.addon.log('Folder does not exist: %s' % path)
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def clear_catchup(self):
        if not self.playing_catchup_channel:
            return
        self.playing_catchup_channel = False
        filename = 'special://profile/addon_data/script.tvguide.fullscreen/catchup_channel.list'
        f = xbmcvfs.File(filename,'rb')
        alarms = f.read().splitlines()
        f.close()
        if not alarms:
            return
        xbmcvfs.delete(filename)
        for name in alarms:
            xbmc.executebuiltin('CancelAlarm(%s,True)' % name.encode('utf-8', 'replace'))
        programList = []
        catchup = ADDON.getSetting('catchup.text')
        channel = utils.Channel("catchup", catchup, '', "special://home/addons/plugin.video.%s/icon.png" % catchup.lower(), "catchup", True)
        self.database.updateProgramList(None,programList,channel)
        self.onRedrawEPG(self.channelIdx, self.viewStartDate)
项目:script.module.metadatautils    作者:marcelveldt    | 项目源码 | 文件源码
def process_image(image_url, art_type, imdb_id):
        '''animated gifs need to be stored locally, otherwise they won't work'''
        # make sure that our local path for the gif images exists
        addon = xbmcaddon.Addon(ADDON_ID)
        gifs_path = "%sanimatedgifs/" % addon.getAddonInfo('profile')
        del addon
        if not xbmcvfs.exists(gifs_path):
            xbmcvfs.mkdirs(gifs_path)
        # only process existing images
        if not image_url or not xbmcvfs.exists(image_url):
            return None
        # copy the image to our local path and return the new path as value
        local_filename = "%s%s_%s.gif" % (gifs_path, imdb_id, art_type)
        if xbmcvfs.exists(local_filename):
            xbmcvfs.delete(local_filename)
        # we don't use xbmcvfs.copy because we want to wait for the action to complete
        img = xbmcvfs.File(image_url)
        img_data = img.readBytes()
        img.close()
        img = xbmcvfs.File(local_filename, 'w')
        img.write(img_data)
        img.close()
        return local_filename
项目:script.module.metadatautils    作者:marcelveldt    | 项目源码 | 文件源码
def download_image(filename, url):
    '''download specific image to local folder'''
    if not url:
        return url
    refresh_needed = False
    if xbmcvfs.exists(filename) and filename == url:
        # only overwrite if new image is different
        return filename
    else:
        if xbmcvfs.exists(filename):
            xbmcvfs.delete(filename)
            refresh_needed = True
        if xbmcvfs.copy(url, filename):
            if refresh_needed:
                refresh_image(filename)
            return filename

    return url
项目:script.module.metadatautils    作者:marcelveldt    | 项目源码 | 文件源码
def refresh_image(imagepath):
    '''tell kodi texture cache to refresh a particular image'''
    import sqlite3
    dbpath = xbmc.translatePath("special://database/Textures13.db").decode('utf-8')
    connection = sqlite3.connect(dbpath, timeout=30, isolation_level=None)
    try:
        cache_image = connection.execute('SELECT cachedurl FROM texture WHERE url = ?', (imagepath,)).fetchone()
        if cache_image and isinstance(cache_image, (unicode, str)):
            if xbmcvfs.exists(cache_image):
                xbmcvfs.delete("special://profile/Thumbnails/%s" % cache_image)
            connection.execute('DELETE FROM texture WHERE url = ?', (imagepath,))
        connection.close()
    except Exception as exc:
        log_exception(__name__, exc)
    finally:
        del connection

# pylint: disable-msg=too-many-local-variables
项目:kodi_plugins    作者:pitpompej    | 项目源码 | 文件源码
def playTrack(asin):
    content = trackPostUnicodeGetHLSPage('https://music.amazon.de/dmls/', asin)
    temp_file_path = addonUserDataFolder
    if forceDVDPlayer:
        temp_file_path += "/temp.mp4"
    else:
        temp_file_path += "/temp.m3u8"
    if xbmcvfs.exists(temp_file_path):
        xbmcvfs.delete(temp_file_path)
    m3u_temp_file = xbmcvfs.File(temp_file_path, 'w')
    manifest_match = re.compile('manifest":"(.+?)"',re.DOTALL).findall(content)
    if manifest_match:
        m3u_string = manifest_match[0]
        m3u_string = m3u_string.replace("\\n", os.linesep)
        m3u_temp_file.write(m3u_string.encode("ascii"))
    m3u_temp_file.close()
    play_item = xbmcgui.ListItem(path=temp_file_path)
    play_item = setPlayItemInfo(play_item)
    xbmcplugin.setResolvedUrl(pluginhandle, True, listitem=play_item)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
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("import.py", "Couldn't clear the UserDefined directory")
        errorTrace("import.py", str(e))
        return False
    return True
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
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("service.vpn.manager").getSetting("1_vpn_validated")
    if service_source == "": errorTrace("platform.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)
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def remove_theme(filename):
        '''remove theme from disk'''
        xbmcvfs.delete(filename.replace(".theme", ".jpg"))
        xbmcvfs.delete(filename)
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def set_icon_for_theme(filename):
        '''sets an icon for an existing theme'''
        iconpath = filename.replace(".theme", ".jpg")
        dialog = xbmcgui.Dialog()
        custom_thumbnail = dialog.browse(2, xbmc.getLocalizedString(1030), 'files')
        if custom_thumbnail:
            xbmcvfs.delete(iconpath)
            xbmcvfs.copy(custom_thumbnail, iconpath)
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def backup(self, filters=None, backup_file="", silent=False):
        '''create skin backup'''
        if not filters:
            filters = []

        if not backup_file:
            return

        # create temp path
        temp_path = self.create_temp()
        zip_temp = u'%s/skinbackup-%s.zip' % (temp_path, datetime.now().strftime('%Y-%m-%d %H.%M'))
        temp_path = temp_path + "skinbackup/"

        # backup skinshortcuts preferences
        if not filters or (filters and "skinshortcuts" in filters):
            self.backup_skinshortcuts(temp_path + "skinshortcuts/")

        # backup skin settings
        if "skinshortcutsonly" not in filters:
            skinsettings_path = os.path.join(temp_path, u"guisettings.txt")
            self.backup_skinsettings(skinsettings_path, filters, temp_path)

        # zip the backup
        zip_temp = xbmc.translatePath(zip_temp).decode("utf-8")
        zip_tofile(temp_path, zip_temp)

        # copy file to destination - wait untill it's really copied
        copy_file(zip_temp, backup_file, True)

        # cleanup temp
        recursive_delete_dir(temp_path)
        xbmcvfs.delete(zip_temp)

        # show success message
        if not silent:
            xbmcgui.Dialog().ok(self.addon.getLocalizedString(32004), self.addon.getLocalizedString(32005))
项目:script.skin.helper.skinbackup    作者:marcelveldt    | 项目源码 | 文件源码
def delete_file(filepath, do_wait=False):
    '''delete a file on the filesystem, wait for the action to be completed'''
    xbmcvfs.delete(filepath)
    if do_wait:
        count = 20
        while count:
            xbmc.sleep(500)  # this first sleep is intentional
            if not xbmcvfs.exists(filepath):
                break
            count -= 1
项目:script.module.simplecache    作者:marcelveldt    | 项目源码 | 文件源码
def _do_cleanup(self):
        '''perform cleanup task'''
        if self._exit or self._monitor.abortRequested():
            return
        self._busy_tasks.append(__name__)
        cur_time = datetime.datetime.now()
        cur_timestamp = self._get_timestamp(cur_time)
        self._log_msg("Running cleanup...")
        if self._win.getProperty("simplecachecleanbusy"):
            return
        self._win.setProperty("simplecachecleanbusy", "busy")

        query = "SELECT id, expires FROM simplecache"
        for cache_data in self._execute_sql(query).fetchall():
            cache_id = cache_data[0]
            cache_expires = cache_data[1]
            if self._exit or self._monitor.abortRequested():
                return
            # always cleanup all memory objects on each interval
            self._win.clearProperty(cache_id.encode("utf-8"))
            # clean up db cache object only if expired
            if cache_expires < cur_timestamp:
                query = 'DELETE FROM simplecache WHERE id = ?'
                self._execute_sql(query, (cache_id,))
                self._log_msg("delete from db %s" % cache_id)

        # compact db
        self._execute_sql("VACUUM")

        # remove task from list
        self._busy_tasks.remove(__name__)
        self._win.setProperty("simplecache.clean.lastexecuted", repr(cur_time))
        self._win.clearProperty("simplecachecleanbusy")
        self._log_msg("Auto cleanup done")
项目:script.module.simplecache    作者:marcelveldt    | 项目源码 | 文件源码
def _get_database(self):
        '''get reference to our sqllite _database - performs basic integrity check'''
        addon = xbmcaddon.Addon(ADDON_ID)
        dbpath = addon.getAddonInfo('profile')
        dbfile = xbmc.translatePath("%s/simplecache.db" % dbpath).decode('utf-8')
        if not xbmcvfs.exists(dbpath):
            xbmcvfs.mkdirs(dbpath)
        del addon
        try:
            connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
            connection.execute('SELECT * FROM simplecache LIMIT 1')
            return connection
        except Exception as error:
            # our _database is corrupt or doesn't exist yet, we simply try to recreate it
            if xbmcvfs.exists(dbfile):
                xbmcvfs.delete(dbfile)
            try:
                connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
                connection.execute(
                    """CREATE TABLE IF NOT EXISTS simplecache(
                    id TEXT UNIQUE, expires INTEGER, data TEXT, checksum INTEGER)""")
                return connection
            except Exception as error:
                self._log_msg("Exception while initializing _database: %s" % str(error), xbmc.LOGWARNING)
                self.close()
                return None
项目:plugin.video.netflix    作者:asciidisco    | 项目源码 | 文件源码
def remove_movie(self, title, year):
        """Removes the DB entry & the strm file for the movie given

        Parameters
        ----------
        title : :obj:`str`
            Title of the movie

        year : :obj:`int`
            Release year of the movie

        Returns
        -------
        bool
            Delete successfull
        """
        title = re.sub(r'[?|$|!|:|#]', r'', title)
        movie_meta = '%s (%d)' % (title, year)
        folder = re.sub(
            pattern=r'[?|$|!|:|#]',
            repl=r'',
            string=self.db[self.movies_label][movie_meta]['alt_title'])
        progress = xbmcgui.DialogProgress()
        progress.create(self.kodi_helper.get_local_string(1210), movie_meta)
        progress.update(50)
        time.sleep(0.5)
        del self.db[self.movies_label][movie_meta]
        self._update_local_db(filename=self.db_filepath, db=self.db)
        dirname = self.kodi_helper.check_folder_path(
            path=os.path.join(self.movie_path, folder))
        filename = os.path.join(self.movie_path, folder, movie_meta + '.strm')
        if xbmcvfs.exists(dirname):
            xbmcvfs.delete(filename)
            xbmcvfs.rmdir(dirname)
            return True
        return False
        time.sleep(1)
        progress.close()
项目:plugin.video.netflix    作者:asciidisco    | 项目源码 | 文件源码
def remove_season(self, title, season):
        """Removes the DB entry & the strm files for a season of a show given

        Parameters
        ----------
        title : :obj:`str`
            Title of the show

        season : :obj:`int`
            Season sequence number

        Returns
        -------
        bool
            Delete successfull
        """
        title = re.sub(r'[?|$|!|:|#]', r'', title.encode('utf-8'))
        season = int(season)
        season_list = []
        episodes_list = []
        show_meta = '%s' % (title)
        for season_entry in self.db[self.series_label][show_meta]['seasons']:
            if season_entry != season:
                season_list.append(season_entry)
        self.db[self.series_label][show_meta]['seasons'] = season_list
        alt_title = self.db[self.series_label][show_meta]['alt_title']
        show_dir = self.kodi_helper.check_folder_path(
            path=os.path.join(self.tvshow_path, alt_title))
        if xbmcvfs.exists(show_dir):
            show_files = [f for f in xbmcvfs.listdir(show_dir) if xbmcvfs.exists(os.path.join(show_dir, f))]
            for filename in show_files:
                if 'S%02dE' % (season) in filename:
                    xbmcvfs.delete(os.path.join(show_dir, filename))
                else:
                    episodes_list.append(filename.replace('.strm', ''))
            self.db[self.series_label][show_meta]['episodes'] = episodes_list
        self._update_local_db(filename=self.db_filepath, db=self.db)
        return True
项目:plugin.video.netflix    作者:asciidisco    | 项目源码 | 文件源码
def remove_episode(self, title, season, episode):
        """Removes the DB entry & the strm files for an episode of a show given

        Parameters
        ----------
        title : :obj:`str`
            Title of the show

        season : :obj:`int`
            Season sequence number

        episode : :obj:`int`
            Episode sequence number

        Returns
        -------
        bool
            Delete successfull
        """
        title = re.sub(r'[?|$|!|:|#]', r'', title.encode('utf-8'))
        episodes_list = []
        show_meta = '%s' % (title)
        episode_meta = 'S%02dE%02d' % (season, episode)
        alt_title = self.db[self.series_label][show_meta]['alt_title']
        show_dir = self.kodi_helper.check_folder_path(
            path=os.path.join(self.tvshow_path, alt_title))
        if xbmcvfs.exists(os.path.join(show_dir, episode_meta + '.strm')):
            xbmcvfs.delete(os.path.join(show_dir, episode_meta + '.strm'))
        for episode_entry in self.db[self.series_label][show_meta]['episodes']:
            if episode_meta != episode_entry:
                episodes_list.append(episode_entry)
        self.db[self.series_label][show_meta]['episodes'] = episodes_list
        self._update_local_db(filename=self.db_filepath, db=self.db)
        return True
项目:plugin.video.stream-cinema    作者:bbaronSVK    | 项目源码 | 文件源码
def _do_cleanup(self):
        '''perform cleanup task'''
        if self._exit or self._monitor.abortRequested():
            return
        self._busy_tasks.append(__name__)
        cur_time = datetime.datetime.now()
        cur_timestamp = self._get_timestamp(cur_time)
        self._log_msg("Running cleanup...")
        if self._win.getProperty("simplecachecleanbusy"):
            return
        self._win.setProperty("simplecachecleanbusy", "busy")

        query = "SELECT id, expires FROM simplecache"
        for cache_data in self._execute_sql(query).fetchall():
            cache_id = cache_data[0]
            cache_expires = cache_data[1]
            if self._exit or self._monitor.abortRequested():
                return
            # always cleanup all memory objects on each interval
            self._win.clearProperty(cache_id.encode("utf-8"))
            # clean up db cache object only if expired
            if cache_expires < cur_timestamp:
                query = 'DELETE FROM simplecache WHERE id = ?'
                self._execute_sql(query, (cache_id,))
                self._log_msg("delete from db %s" % cache_id)

        # compact db
        self._execute_sql("VACUUM")

        # remove task from list
        self._busy_tasks.remove(__name__)
        self._win.setProperty("simplecache.clean.lastexecuted", repr(cur_time))
        self._win.clearProperty("simplecachecleanbusy")
        self._log_msg("Auto cleanup done")
项目:plugin.video.stream-cinema    作者:bbaronSVK    | 项目源码 | 文件源码
def _get_database(self):
        '''get reference to our sqllite _database - performs basic integrity check'''
        addon = xbmcaddon.Addon(ADDON_ID)
        dbpath = addon.getAddonInfo('profile')
        dbfile = xbmc.translatePath("%s/simplecache.db" % dbpath).decode('utf-8')
        if not xbmcvfs.exists(dbpath):
            xbmcvfs.mkdirs(dbpath)
        del addon
        try:
            connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
            connection.execute('SELECT * FROM simplecache LIMIT 1')
            return connection
        except Exception as error:
            # our _database is corrupt or doesn't exist yet, we simply try to recreate it
            if xbmcvfs.exists(dbfile):
                xbmcvfs.delete(dbfile)
            try:
                connection = sqlite3.connect(dbfile, timeout=30, isolation_level=None)
                connection.execute(
                    """CREATE TABLE IF NOT EXISTS simplecache(
                    id TEXT UNIQUE, expires INTEGER, data TEXT, checksum INTEGER)""")
                return connection
            except Exception as error:
                self._log_msg("Exception while initializing _database: %s" % str(error), xbmc.LOGWARNING)
                self.close()
                return None
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def getContextMenuItems(self):
        cm = []
        if self.numberOfVideos > 0:
            cm.append((_T(30252), 'Container.Update(%s)' % plugin.url_for_path('/playlist/%s/tracks/0' % self.id)))
        if self.type == 'USER' and ALBUM_PLAYLIST_TAG in self.description:
            cm.append((_T(30254), 'Container.Update(%s)' % plugin.url_for_path('/playlist/%s/items/0' % self.id)))
        else:
            cm.append((_T(30255), 'Container.Update(%s)' % plugin.url_for_path('/playlist/%s/albums/0' % self.id)))
        if self._is_logged_in:
            if self.type == 'USER':
                cm.append((_T(30251), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/rename/%s' % self.id)))
                if self.numberOfItems > 0:
                    cm.append((_T(30258), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/clear/%s' % self.id)))
                cm.append((_T(30235), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/delete/%s' % self.id)))
            else:
                if self._isFavorite:
                    cm.append((_T(30220), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/remove/playlists/%s' % self.id)))
                else:
                    cm.append((_T(30219), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/add/playlists/%s' % self.id)))
            cm.append((_T(30239), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/add/playlist/%s' % self.id)))
            if self.type == 'USER' and sys.argv[0].lower().find('user_playlists') >= 0:
                if str(self.id) == addon.getSetting('default_trackplaylist_id'):
                    cm.append((_T(30250) % _T('Track'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_reset_default/tracks')))
                else:
                    cm.append((_T(30249) % _T('Track'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_set_default/tracks/%s' % self.id)))
                if str(self.id) == addon.getSetting('default_videoplaylist_id'):
                    cm.append((_T(30250) % _T('Video'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_reset_default/videos')))
                else:
                    cm.append((_T(30249) % _T('Video'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_set_default/videos/%s' % self.id)))
                if str(self.id) == addon.getSetting('default_albumplaylist_id'):
                    cm.append((_T(30250) % _T('Album'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_reset_default/albums')))
                else:
                    cm.append((_T(30249) % _T('Album'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_set_default/albums/%s' % self.id)))
        return cm
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def delete_cache(self):
        try:
            if xbmcvfs.exists(FAVORITES_FILE):
                xbmcvfs.delete(FAVORITES_FILE)
                log('Deleted Favorites file.')
        except:
            return False
        return True
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def delete_cache(self):
        try:
            if xbmcvfs.exists(PLAYLISTS_FILE):
                xbmcvfs.delete(PLAYLISTS_FILE)
                log('Deleted Playlists file.')
        except:
            return False
        return True
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def insertAlbumJson(self, json_obj):
        if CACHE_ALBUMS and json_obj.get('id') and json_obj.get('releaseDate'):
            self.insert('album', '%s' % json_obj.get('id'), json_obj, overwrite=True)
            if json_obj.get('numberOfVideos', 0) > 0:
                self.insert('album_with_videos', '%s' % json_obj.get('id'), json_obj, overwrite=True)
            #if json_obj.get('_mqa', False):
            #    self.insertMasterAlbumId(json_obj.get('id'))
            json_obj.update({'_cached': True})

    #def insertMasterAlbumId(self, album_id):
    #    success = self.insert('master_album', '%s' % album_id, '%s' % album_id, overwrite=False)
    #    # debug.log('Inserting Master Album ID %s: %s' % (album_id, success))
    #    return success

    #def deleteMasterAlbumId(self, album_id):
    #    success = True
    #    if self.isMasterAlbum(album_id):
    #        success = self.delete('master_album', '%s' % album_id)
    #        # debug.log('Deleting Master Album ID %s: %s' % (album_id, success))
    #    return success

    #def isMasterAlbum(self, album_id):
    #    master_album_id = self.fetch('master_album', '%s' % album_id)
    #    isMaster = True if master_album_id and '%s' % master_album_id == '%s' % album_id else False 
    #    # debug.log('Checking Master Album ID %s: %s' % (album_id, isMaster))
    #    return isMaster
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def deleteOldMasterAlbums(self):
        allIds = self.fetchAllIds('master_album')
        deletedMasterAlbums = 0
        deletedAlbums = 0
        for nextId in allIds:
            if self.delete('master_album', '%s' % nextId):
                deletedMasterAlbums += 1
            if self.delete('album', '%s' % nextId):
                deletedAlbums += 1
        debug.log('Deleted %s old Master Albums from Cache.' % deletedMasterAlbums)
        debug.log('Deleted %s Albums from Cache.' % deletedAlbums)
项目:plugin.audio.tidal2    作者:arnesongit    | 项目源码 | 文件源码
def deleteDatabase(self):
        try:
            filename = os.path.join(METACACHE_DIR, METACACHE_FILE)
            if xbmcvfs.exists(filename):
                xbmcvfs.delete(filename)
                debug.log('Deleted Database file %s' % METACACHE_FILE)
        except:
            return False
        return True

# End of File
项目:specto    作者:mrknow    | 项目源码 | 文件源码
def remove_DataBase() :
    xbmc.log("metahandler - deleting database...")
    try:
        if xbmcvfs.exists(DBLOCATION): xbmcvfs.delete(DBLOCATION)
    except:
        if os.path.exists(DBLOCATION): os.remove(DBLOCATION)
    xbmcgui.Dialog().ok("Metahandler", "Database deleted")    
    xbmc.log("Metahandler - Clearing database cache. Done!")
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def _deleteLineup(self, lineup):
        c = self.conn.cursor()
        # delete channels associated with the lineup
        xbmc.log('[%s] Removing Channels for lineup: %s' % (
            ADDON.getAddonInfo('id'), str(lineup)), xbmc.LOGDEBUG)
        c.execute('DELETE FROM channels WHERE source=? AND lineup=?', [self.source.KEY, lineup])

        c.execute("UPDATE sources SET channels_updated=? WHERE id=?",
                  [datetime.datetime.now(), self.source.KEY])
        self.conn.commit()
项目:script.tvguide.fullscreen    作者:primaeval    | 项目源码 | 文件源码
def _saveLineup(self, channelList, lineup):
        c = self.conn.cursor()
        # delete removed channels
        c.execute('SELECT * FROM channels WHERE source=? AND lineup=?',
                  [self.source.KEY, lineup])
        to_delete = []
        for row in c:
            station_id = row['id']
            found = False
            for channel in channelList:
                if channel.id == station_id:
                    found = True
                    break
            if not found:
                xbmc.log('[%s] Removing Channel: %s from lineup: %s' % (
                    ADDON.getAddonInfo('id'), str(station_id), str(lineup)), xbmc.LOGDEBUG)
                to_delete.append(station_id)

        if to_delete:
            c.execute('DELETE FROM channels WHERE id IN (%s)' %
                      ','.join('?' * len(to_delete)), to_delete)

        # Add new channels
        for channel in channelList:
            xbmc.log('[%s] Adding Channel: %s from lineup: %s' % (
                ADDON.getAddonInfo('id'), str(channel.id), str(lineup)), xbmc.LOGDEBUG)

            logo = get_logo(channel)
            c.execute(
                'INSERT OR IGNORE INTO channels(id, title, logo, stream_url, visible, weight, source, lineup) VALUES(?, ?, ?, ?, ?, (CASE ? WHEN -1 THEN (SELECT COALESCE(MAX(weight)+1, 0) FROM channels WHERE source=?) ELSE ? END), ?, ?)',
                [channel.id, channel.title, logo, '', True, -1, self.source.KEY, -1, self.source.KEY, lineup])

        c.execute("UPDATE sources SET channels_updated=? WHERE id=?",
                  [datetime.datetime.now(), self.source.KEY])
        self.conn.commit()
项目:context.clean_remove    作者:5-star    | 项目源码 | 文件源码
def deleteFile(file):
    if xbmcvfs.exists(file):
        xbmcvfs.delete(file)
项目:context.clean_remove    作者:5-star    | 项目源码 | 文件源码
def dltMovie(id, path, video):
    kodiJsonRequest({'jsonrpc': '2.0', 'method': 'VideoLibrary.RemoveMovie', 'params': {'movieid': int(id)}, 'id': 1})
    if separate_movies == "true":
        xdir, xfil = xbmcvfs.listdir(path)
        for fl in xfil:
            xbmcvfs.delete(path + fl)
        deleteDir(path)
    else:
        deleteVideo(path, video)
    xbmc.executebuiltin('Notification(' + xbmc.getInfoLabel('ListItem.Label').replace(",",";") + ',' + lang(30002) + ')')
项目:plugin.video.youtube    作者:Kolifanes    | 项目源码 | 文件源码
def maintenance_actions(self, context, re_match):
        maint_type = re_match.group('maint_type')
        action = re_match.group('action')
        if action == 'clear':
            if maint_type == 'function_cache':
                if context.get_ui().on_remove_content(context.localize(30557)):
                    context.get_function_cache().clear()
                    context.get_ui().show_notification(context.localize(30575))
            elif maint_type == 'search_cache':
                if context.get_ui().on_remove_content(context.localize(30558)):
                    context.get_search_history().clear()
                    context.get_ui().show_notification(context.localize(30575))
        elif action == 'delete':
                _maint_files = {'function_cache': 'cache.sqlite',
                                'search_cache': 'search.sqlite',
                                'settings_xml': 'settings.xml'}
                _file = _maint_files.get(maint_type, '')
                if _file:
                    if 'sqlite' in _file:
                        _file_w_path = os.path.join(context._get_cache_path(), _file)
                    else:
                        _file_w_path = os.path.join(context._data_path, _file)
                    if context.get_ui().on_delete_content(_file):
                        success = xbmcvfs.delete(_file_w_path)
                        if success:
                            context.get_ui().show_notification(context.localize(30575))
                        else:
                            context.get_ui().show_notification(context.localize(30576))
项目:script.kodi.loguploader    作者:XBMC-Addons    | 项目源码 | 文件源码
def showResult(self, message, url=None):
        if url:
            imagefile = os.path.join(xbmc.translatePath(PROFILE),'%s.png'%str(url.split('/')[-2]))
            qrIMG = pyqrcode.create(url)
            qrIMG.png(imagefile, scale=10)
            qr = QRCode( "script-loguploader-main.xml" , CWD, "default", image=imagefile, text=message)
            qr.doModal()
            del qr
            xbmcvfs.delete(imagefile)
        else:
            dialog = xbmcgui.Dialog()
            confirm = dialog.ok(ADDONNAME, message)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def clearKeysAndCerts(vpn_provider):
    # Clear all of the keys for the given provider
    keys = getUserKeys(vpn_provider)
    for file in keys:
        if xbmcvfs.exists(file): xbmcvfs.delete(file)
    certs = getUserCerts(vpn_provider)
    for file in certs:
        if xbmcvfs.exists(file): xbmcvfs.delete(file)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def writeKeyPass(key_pass_name, password):   
    # Return the password being used for a given key file
    try:
        if xbmcvfs.exists(key_pass_name):
            xbmcvfs.delete(key_pass_name)
        debugTrace("Writing key password file " + key_pass_name)
        pass_file = open(key_pass_name, 'w')
        pass_file.write(password)
        pass_file.close()
        return True
    except Exception as e:
        errorTrace("vpnproviders.py", "Failed to write key password file to userdata")
        errorTrace("vpnproviders.py", str(e))
        return False
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def cleanPassFiles():
    # Delete the pass.txt file from all of the VPN provider directorys
    for provider in providers:
        filename = getAddonPath(True, provider + "/pass.txt")
        if xbmcvfs.exists(filename) : xbmcvfs.delete(filename)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def cleanGeneratedFiles():
    # Delete the GENERATED.txt file from all of the VPN provider directorys    
    for provider in providers:
        filename = getAddonPath(True, provider + "/GENERATED.txt")
        if xbmcvfs.exists(filename) : xbmcvfs.delete(filename)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def removeGeneratedFiles():
    for provider in providers:
        try:
            files = getAddonList(provider, "*")    
            for file in files:
                xbmcvfs.delete(file)
        except:
            pass
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def generateSecureVPN():
    # Can't use a template as SecureVPN use multiple everything. 
    # Copy the file to the target directory and strip it of user keys
    existing_profiles = glob.glob(getUserDataPath("providers/SecureVPN" + "/*.ovpn"))
    for connection in existing_profiles:
        xbmcvfs.delete(connection)
    # Get the list from the provider data directory
    profiles = getProfileList("SecureVPN")
    destination_path = getProviderPath("SecureVPN" + "/")   
    for profile in profiles:
        shortname = profile[profile.index("SecureVPN")+10:]
        shortname = shortname[:shortname.index(".")]
        proto = "(UDP)"
        filename = shortname + " " + proto + ".ovpn"
        profile_file = open(profile, 'r')
        output_file = open(destination_path + filename, 'w')
        profile_contents = profile_file.readlines()
        profile_file.close()
        output = ""
        i = 0
        write = True;
        for line in profile_contents:
            line = line.strip(' \t\n\r')
            if not (line == "" or line.startswith("#")) :
                if "<key>" in line or "<cert>" in line: write = False
                if "</key>" in line: 
                    write = True
                    line = "key #USERKEY"
                if "</cert>" in line:
                    write = True
                    line = "cert #USERCERT"
                if write : output_file.write(line + "\n")
            i = i + 1    
        output_file.close()
    generateMetaData("SecureVPN", MINIMUM_LEVEL)
项目:service.vpn.manager    作者:Zomboided    | 项目源码 | 文件源码
def fakeItTillYouMakeIt(fake):
    try:
        if fake:
            if not fakeConnection():
                f = open(getUserDataPath(fake_name),'w')
                f.close()
        else:
            if fakeConnection():
                xbmcvfs.delete(getUserDataPath(fake_name))
    except Exception as e:
        errorTrace("platform.py", "fakeItTillYouMakeIt " + str(fake) + " failed")
        errorTrace("platform.py", str(e))
项目:plugin.video.netflix    作者:asciidisco    | 项目源码 | 文件源码
def remove_show(self, title):
        """Removes the DB entry & the strm files for the show given

        Parameters
        ----------
        title : :obj:`str`
            Title of the show

        Returns
        -------
        bool
            Delete successfull
        """
        title = re.sub(r'[?|$|!|:|#]', r'', title)
        label = self.series_label
        rep_str = self.db[label][title]['alt_title'].encode('utf-8')
        folder = re.sub(
            pattern=r'[?|$|!|:|#]',
            repl=r'',
            string=rep_str)
        progress = xbmcgui.DialogProgress()
        progress.create(self.kodi_helper.get_local_string(1210), title)
        time.sleep(0.5)
        del self.db[self.series_label][title]
        self._update_local_db(filename=self.db_filepath, db=self.db)
        show_dir = self.kodi_helper.check_folder_path(
            path=os.path.join(self.tvshow_path, folder))
        if xbmcvfs.exists(show_dir):
            show_files = xbmcvfs.listdir(show_dir)[1]
            episode_count_total = len(show_files)
            step = round(100.0 / episode_count_total, 1)
            percent = 100 - step
            for filename in show_files:
                progress.update(int(percent))
                xbmcvfs.delete(os.path.join(show_dir, filename))
                percent = percent - step
                time.sleep(0.05)
            xbmcvfs.rmdir(show_dir)
            return True
        return False
        time.sleep(1)
        progress.close()
项目:plugin.video.youtube    作者:jdf76    | 项目源码 | 文件源码
def maintenance_actions(self, context, re_match):
        maint_type = re_match.group('maint_type')
        action = re_match.group('action')
        if action == 'clear':
            if maint_type == 'function_cache':
                if context.get_ui().on_remove_content(context.localize(self.LOCAL_MAP['youtube.function.cache'])):
                    context.get_function_cache().clear()
                    context.get_ui().show_notification(context.localize(self.LOCAL_MAP['youtube.succeeded']))
            elif maint_type == 'search_cache':
                if context.get_ui().on_remove_content(context.localize(self.LOCAL_MAP['youtube.search.history'])):
                    context.get_search_history().clear()
                    context.get_ui().show_notification(context.localize(self.LOCAL_MAP['youtube.succeeded']))
        elif action == 'reset':
            if maint_type == 'access_manager':
                if context.get_ui().on_yes_no_input(context.get_name(), context.localize(self.LOCAL_MAP['youtube.reset.access.manager.confirm'])):
                    try:
                        context.get_function_cache().clear()
                        access_manager = context.get_access_manager()
                        client = self.get_client(context)
                        if access_manager.has_refresh_token():
                            refresh_tokens = access_manager.get_refresh_token().split('|')
                            refresh_tokens = list(set(refresh_tokens))
                            for refresh_token in refresh_tokens:
                                client.revoke(refresh_token)
                        self.reset_client()
                        access_manager.update_access_token(access_token='', refresh_token='')
                        context.get_ui().refresh_container()
                        context.get_ui().show_notification(context.localize(self.LOCAL_MAP['youtube.succeeded']))
                    except:
                        context.get_ui().show_notification(context.localize(self.LOCAL_MAP['youtube.failed']))
        elif action == 'delete':
            _maint_files = {'function_cache': 'cache.sqlite',
                            'search_cache': 'search.sqlite',
                            'settings_xml': 'settings.xml'}
            _file = _maint_files.get(maint_type, '')
            if _file:
                if 'sqlite' in _file:
                    _file_w_path = os.path.join(context._get_cache_path(), _file)
                else:
                    _file_w_path = os.path.join(context._data_path, _file)
                if context.get_ui().on_delete_content(_file):
                    success = xbmcvfs.delete(_file_w_path)
                    if success:
                        context.get_ui().show_notification(context.localize(self.LOCAL_MAP['youtube.succeeded']))
                    else:
                        context.get_ui().show_notification(context.localize(self.LOCAL_MAP['youtube.failed']))