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)")
python类delete()的实例源码
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))
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)
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)
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)
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
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
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
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)
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
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)
def remove_theme(filename):
'''remove theme from disk'''
xbmcvfs.delete(filename.replace(".theme", ".jpg"))
xbmcvfs.delete(filename)
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)
backuprestore.py 文件源码
项目:script.skin.helper.skinbackup
作者: marcelveldt
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
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))
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
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")
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
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()
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
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
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")
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
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
def delete_cache(self):
try:
if xbmcvfs.exists(FAVORITES_FILE):
xbmcvfs.delete(FAVORITES_FILE)
log('Deleted Favorites file.')
except:
return False
return True
def delete_cache(self):
try:
if xbmcvfs.exists(PLAYLISTS_FILE):
xbmcvfs.delete(PLAYLISTS_FILE)
log('Deleted Playlists file.')
except:
return False
return True
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
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)
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
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!")
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()