我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用xbmcvfs.File()。
def backup_skinsettings(self, dest_file, filters, temp_path): '''backup the skinsettings (guisettings)''' # save guisettings skinfile = xbmcvfs.File(dest_file, "w") skinsettings = self.get_skinsettings(filters) skinfile.write(repr(skinsettings)) skinfile.close() # copy any custom skin images or themes for item in ["custom_images/", "themes/"]: custom_images_folder = u"special://profile/addon_data/%s/%s" % (xbmc.getSkinDir(), item) if xbmcvfs.exists(custom_images_folder): custom_images_folder_temp = os.path.join(temp_path, item) for file in xbmcvfs.listdir(custom_images_folder)[1]: source = os.path.join(custom_images_folder, file) dest = os.path.join(custom_images_folder_temp, file) copy_file(source, dest)
def backup_skinshortcuts_properties(propertiesfile, dest_path): '''parse skinshortcuts properties file and translate images''' # look for any backgrounds and translate them propfile = xbmcvfs.File(propertiesfile) data = propfile.read() propfile.close() allprops = eval(data) if data else [] for count, prop in enumerate(allprops): if prop[2] == "background": background = prop[3] if prop[3] else "" defaultid = prop[1] if background.endswith(".jpg") or background.endswith(".png") or background.endswith(".gif"): background = get_clean_image(background) extension = background.split(".")[-1] newthumb = os.path.join(dest_path, "%s-background-%s.%s" % (xbmc.getSkinDir(), normalize_string(defaultid), extension)) newthumb_vfs = "special://profile/addon_data/script.skinshortcuts/%s-background-%s.%s" % ( xbmc.getSkinDir(), normalize_string(defaultid), extension) if xbmcvfs.exists(background): copy_file(background, newthumb) allprops[count] = [prop[0], prop[1], prop[2], newthumb_vfs] # write updated properties file propfile = xbmcvfs.File(propertiesfile, "w") propfile.write(repr(allprops)) propfile.close()
def get_current_view(): skinPath = translate_path('special://skin/') xml = os.path.join(skinPath, 'addon.xml') f = xbmcvfs.File(xml) read = f.read() f.close() try: src = re.search('defaultresolution="([^"]+)', read, re.DOTALL).group(1) except: src = re.search('<res.+?folder="([^"]+)', read, re.DOTALL).group(1) src = os.path.join(skinPath, src, 'MyVideoNav.xml') f = xbmcvfs.File(src) read = f.read() f.close() match = re.search('<views>([^<]+)', read, re.DOTALL) if match: views = match.group(1) for view in views.split(','): if xbmc.getInfoLabel('Control.GetLabel(%s)' % view): return view
def write_strm_file(self, path, url, title_player): """Writes the stream file that Kodi can use to integrate it into the DB Parameters ---------- path : :obj:`str` Filepath of the file to be created url : :obj:`str` Stream url title_player : :obj:`str` Video fallback title for m3u """ f = xbmcvfs.File(path, 'w') f.write('#EXTINF:-1,'+title_player.encode('utf-8')+'\n') f.write(url) f.close()
def write_metadata_file(self, video_id, content): """Writes the metadata file that caches grabbed content from netflix Parameters ---------- video_id : :obj:`str` ID of video content : Unchanged metadata from netflix """ meta_file = os.path.join(self.metadata_path, video_id+'.meta') if not xbmcvfs.exists(meta_file): f = xbmcvfs.File(meta_file, 'wb') pickle.dump(content, f) f.close()
def read_metadata_file(self, video_id): """Reads the metadata file that caches grabbed content from netflix Parameters ---------- video_id : :obj:`str` ID of video content : Unchanged metadata from cache file """ meta_file = os.path.join(self.metadata_path, str(video_id)+'.meta') if xbmcvfs.exists(meta_file): f = xbmcvfs.File(meta_file, 'rb') content = f.read() f.close() meta_data = pickle.loads(content) return meta_data return
def write_artdata_file(self, video_id, content): """Writes the art data file that caches grabbed content from netflix Parameters ---------- video_id : :obj:`str` ID of video content : Unchanged artdata from netflix """ meta_file = os.path.join(self.metadata_path, video_id+'.art') if not xbmcvfs.exists(meta_file): f = xbmcvfs.File(meta_file, 'wb') pickle.dump(content, f) f.close()
def saveSubtitle(self, content, lang, convert=True): codePageDict = {'ara': 'cp1256', 'ar': 'cp1256', 'cs': 'cp1250', 'ell': 'cp1253', 'el': 'cp1253', 'heb': 'cp1255', 'he': 'cp1255', 'sk': 'cp1250', 'tur': 'cp1254', 'tr': 'cp1254', 'rus': 'cp1251', 'ru': 'cp1251'} subtitle = xbmc.validatePath(xbmc.translatePath('special://temp/')) subtitle = os.path.join(subtitle, 'AutomatickeTitulky.%s.srt' % lang) codepage = codePageDict.get(lang, '') if codepage and self.getSetting('subtitles.utf') == 'true': try: content_encoded = codecs.decode(content, codepage) content = codecs.encode(content_encoded, 'utf-8') except Exception, e: util.debug("[SC] chyba ukladania titulkov....") pass file = xbmcvfs.File(subtitle, 'w') file.write(str(content)) file.close() return subtitle
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 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 get(version): try: import xbmc,xbmcgui,xbmcaddon,xbmcvfs f = xbmcvfs.File(xbmcaddon.Addon().getAddonInfo('changelog')) text = f.read() ; f.close() label = '%s - %s' % (xbmc.getLocalizedString(24054), xbmcaddon.Addon().getAddonInfo('name')) id = 10147 xbmc.executebuiltin('ActivateWindow(%d)' % id) xbmc.sleep(100) win = xbmcgui.Window(id) retry = 50 while (retry > 0): try: xbmc.sleep(10) win.getControl(1).setLabel(label) win.getControl(5).setText(text) retry = 0 except: retry -= 1 return '1' except: return '1'
def get_skin_colorthemes(self): '''returns all available skinprovided colorthemes as listitems''' listitems = [] for file in xbmcvfs.listdir(self.skinthemes_path)[1]: if file.endswith(".theme"): file = file.decode("utf-8") themefile = self.skinthemes_path + file icon = themefile.replace(".theme", ".jpg") if not xbmcvfs.exists(icon): icon = "" xbmcfile = xbmcvfs.File(themefile) data = xbmcfile.read() xbmcfile.close() for skinsetting in eval(data): if skinsetting[0] == "DESCRIPTION": desc = skinsetting[1] if skinsetting[0] == "THEMENAME": label = skinsetting[1] if label == self.get_activetheme(): desc = xbmc.getLocalizedString(461) listitem = xbmcgui.ListItem(label, iconImage=icon) listitem.setLabel2(desc) listitem.setPath(themefile) listitems.append(listitem) return listitems
def backup_skinshortcuts_images(shortcutfile, dest_path): '''parse skinshortcuts file and copy images to backup location''' shortcutfile = xbmc.translatePath(shortcutfile).decode("utf-8") doc = parse(shortcutfile) listing = doc.documentElement.getElementsByTagName('shortcut') for shortcut in listing: defaultid = shortcut.getElementsByTagName('defaultID') if defaultid: defaultid = defaultid[0].firstChild if defaultid: defaultid = defaultid.data if not defaultid: defaultid = shortcut.getElementsByTagName('label')[0].firstChild.data thumb = shortcut.getElementsByTagName('thumb') if thumb: thumb = thumb[0].firstChild if thumb: thumb = thumb.data if thumb and (thumb.endswith(".jpg") or thumb.endswith(".png") or thumb.endswith(".gif")): thumb = get_clean_image(thumb) extension = thumb.split(".")[-1] newthumb = os.path.join(dest_path, "%s-thumb-%s.%s" % (xbmc.getSkinDir(), normalize_string(defaultid), extension)) newthumb_vfs = "special://profile/addon_data/script.skinshortcuts/%s-thumb-%s.%s" % ( xbmc.getSkinDir(), normalize_string(defaultid), extension) if xbmcvfs.exists(thumb): copy_file(thumb, newthumb) shortcut.getElementsByTagName('thumb')[0].firstChild.data = newthumb_vfs # write changes to skinshortcuts file shortcuts_file = xbmcvfs.File(shortcutfile, "w") shortcuts_file.write(doc.toxml(encoding='utf-8')) shortcuts_file.close()
def restore_guisettings(self, filename, progressdialog): '''restore guisettings''' kodifile = xbmcvfs.File(filename, 'r') data = kodifile.read() importstring = eval(data) kodifile.close() xbmc.sleep(200) for count, skinsetting in enumerate(importstring): if progressdialog and progressdialog.iscanceled(): return setting = skinsetting[1] settingvalue = skinsetting[2] if progressdialog: progressdialog.update((count * 100) / len(importstring), '%s %s' % (self.addon.getLocalizedString(32033), setting)) if skinsetting[0] == "string": if settingvalue: xbmc.executebuiltin("Skin.SetString(%s,%s)" % (setting, settingvalue)) else: xbmc.executebuiltin("Skin.Reset(%s)" % setting) elif skinsetting[0] == "bool": if settingvalue == "true": xbmc.executebuiltin("Skin.SetBool(%s)" % setting) else: xbmc.executebuiltin("Skin.Reset(%s)" % setting) xbmc.sleep(30)
def playlist_path(pcs_file_path, stream): user_info = get_user_info() user_name = user_info['username'] user_cookie = user_info['cookie'] user_tokens = user_info['tokens'] if stream: playlist_data = pcs.get_streaming_playlist(user_cookie, pcs_file_path, stream) if playlist_data: raw_dir = os.path.dirname(pcs_file_path) m = re.search('\/(.*)', raw_dir) dirname = m.group(1) basename = os.path.basename(pcs_file_path) r = re.search('(.*)\.(.*)$', basename) filename = ''.join([r.group(1), stream, '.m3u8']) dirpath = os.path.join(utils.data_dir(), user_name, dirname) if not xbmcvfs.exists(dirpath): xbmcvfs.mkdirs(dirpath) filepath = os.path.join(dirpath, filename) tmpFile = xbmcvfs.File(filepath, 'w') tmpFile.write(bytearray(playlist_data, 'utf-8')) return filepath else: dialog.notification('', u'??????', xbmcgui.NOTIFICATION_INFO, 4000) return None else: url = pcs.stream_download(user_cookie, user_tokens, pcs_file_path) if url: return url else: dialog.notification('', u'??????????????', xbmcgui.NOTIFICATION_INFO, 4000) return None
def getOfflineFileList(self,cachePath): localFiles = [] #workaround for this issue: https://github.com/xbmc/xbmc/pull/8531 if xbmcvfs.exists(cachePath) or os.path.exists(cachePath): dirs,files = xbmcvfs.listdir(cachePath) for dir in dirs: subdir,subfiles = xbmcvfs.listdir(str(cachePath) + '/' + str(dir)) for file in subfiles: if bool(re.search('\.stream\.mp4', file)): try: nameFile = xbmcvfs.File(str(cachePath) + '/' + str(dir) + '/' + str(dir) + '.name') filename = nameFile.read() nameFile.close() except: filename = file try: nameFile = xbmcvfs.File(str(cachePath) + '/' + str(dir) + '/' + str(os.path.splitext(file)[0]) + '.resolution') resolution = nameFile.read() nameFile.close() except: resolution = file offlineFile = offlinefile.offlinefile(filename, str(cachePath) + '/' + str(dir) +'.jpg', resolution.rstrip(), str(cachePath) + '/' + str(dir) + '/' + str(os.path.splitext(file)[0]) + '.mp4') localFiles.append(offlineFile) return localFiles ## # Add a media file to a directory listing screen # parameters: package, context type, whether file is encfs, encfs:decryption path, encfs:encryption path ##
def downloadGeneralFile(self, url, file, force=False): req = urllib2.Request(url, None, self.getHeadersList()) # already downloaded if not force and xbmcvfs.exists(file) and xbmcvfs.File(file).size() > 0: return f = xbmcvfs.File(file, 'w') # if action fails, validate login try: f.write(urllib2.urlopen(req).read()) f.close() except urllib2.URLError, e: self.refreshToken() req = urllib2.Request(url, None, self.getHeadersList()) try: f.write(urllib2.urlopen(req).read()) f.close() except urllib2.URLError, e: xbmc.log(self.addon.getAddonInfo('name') + ': downloadGeneralFle ' + str(e), xbmc.LOGERROR) return None #can't write to cache for some reason except IOError: return None return file ## # retrieve/download a general file # parameters: title of video, whether to prompt for quality/format (optional), medial url object, package object, whether to force download (overwrite), whether folder is encrypted, folder name ##
def downloadPicture(self, url, file): req = urllib2.Request(url, None, self.getHeadersList()) # already downloaded if xbmcvfs.exists(file) and xbmcvfs.File(file).size() > 0: return f = xbmcvfs.File(file, 'w') # if action fails, validate login try: f.write(urllib2.urlopen(req).read()) f.close() except urllib2.URLError, e: self.refreshToken() req = urllib2.Request(url, None, self.getHeadersList()) try: f.write(urllib2.urlopen(req).read()) f.close() except urllib2.URLError, e: xbmc.log(self.addon.getAddonInfo('name') + ': downloadPicture ' + str(e), xbmc.LOGERROR) return None #can't write to cache for some reason except IOError: return None return file
def getFiles(self,service): if not constants.CONST.CACHE: return None #load cachePath if not already loaded if self.cachePath == '': self.cachePath = service.settings.cachePath localResolutions = [] localFiles = [] # no local cache, no local files to look for if self.cachePath == '': return (localResolutions,localFiles) cachePath = str(self.cachePath) + '/' + str(self.package.file.id) + '/' #workaround for this issue: https://github.com/xbmc/xbmc/pull/8531 if xbmcvfs.exists(cachePath) or os.path.exists(cachePath): dirs,files = xbmcvfs.listdir(cachePath) for file in files: if '.stream.mp4' in file: try: resolutionFile = xbmcvfs.File(cachePath + str(os.path.splitext(file)[0]) + '.resolution') resolution = resolutionFile.read() resolutionFile.close() except: resolution = file localResolutions.append('offline - ' + str(resolution)) localFiles.append(str(cachePath) + str(file)) return (localResolutions,localFiles)
def save_file(msl_data_path, filename, content): """ Saves the given content under given filename :param filename: The filename :param content: The content of the file """ file_handle = xbmcvfs.File( filepath=msl_data_path + filename, mode='w') file_content = file_handle.write(content) file_handle.close()
def load_file(msl_data_path, filename): """ Loads the content of a given filename :param filename: The file to load :return: The content of the file """ file_handle = xbmcvfs.File( filepath=msl_data_path + filename) file_content = file_handle.read() file_handle.close() return file_content
def fetch_url(self, url, file): f = xbmcvfs.File(file, 'wb') f.write(requests.get(url).content) f.write(url) f.close()
def add_item_to_library(self, item_path, item_url): error = False new = False item_path = xbmc.validatePath(item_path) if item_path: item_path = xbmc.translatePath(item_path) dir = os.path.dirname(item_path) if not xbmcvfs.exists(dir): try: xbmcvfs.mkdirs(dir) except Exception: error = True util.error('[SC] Failed to create directory 1: ' + dir) if not xbmcvfs.exists(item_path): try: file_desc = xbmcvfs.File(item_path, 'w') file_desc.write(str(item_url)) file_desc.close() new = True except Exception, e: util.error('[SC] Failed to create .strm file: ' + item_path + " | " + str(e)) error = True else: error = True util.debug("[SC] add item: %s" % item_path) return (error, new)
def onExceptionRaised(extraData=None): """ Invoke this method in an except clause to allow the user to submit a bug report with stacktrace, system information, etc. This also avoids the 'Script error' popup in XBMC, unless of course an exception is thrown in this code :-) @param extraData: str or dict """ # start by logging the usual info to stderr (etype, value, traceback) = sys.exc_info() tb.print_exception(etype, value, traceback) if not SCRIPT_ADDON: try: # signal error to XBMC to hide progress dialog HANDLE = int(sys.argv[1]) xbmcplugin.endOfDirectory(HANDLE, succeeded=False) except Exception: pass try: f = F(xbmc.translatePath('special://userdata/addon_data/plugin.video.stream-cinema/settings.xml')) sett = f.read(8129 * 10) f.close() except: sett = None else: sett = None heading = getRandomHeading() data = client.gatherData(etype, value, traceback, extraData, EXTRA_DATA) if set is not None: data['addon']['set'] = str(sett) d = gui.BuggaloDialog(SUBMIT_URL, GMAIL_RECIPIENT, heading, data) d.doModal() del d
def load_cache(self): try: fd = xbmcvfs.File(FAVORITES_FILE, 'r') self.ids_content = fd.read() self.ids = eval(self.ids_content) fd.close() self.ids_loaded = not (self.ids['artists'] == None or self.ids['albums'] == None or self.ids['playlists'] == None or self.ids['tracks'] == None or self.ids['videos'] == None) if self.ids_loaded: log('Loaded %s Favorites from disk.' % sum(len(self.ids[content]) for content in ['artists', 'albums', 'playlists', 'tracks', 'videos'])) except: self.ids_loaded = False self.reset() return self.ids_loaded
def save_cache(self): try: if self.ids_loaded: new_ids = repr(self.ids) if new_ids <> self.ids_content: fd = xbmcvfs.File(FAVORITES_FILE, 'w') fd.write(new_ids) fd.close() log('Saved %s Favorites to disk.' % sum(len(self.ids[content]) for content in ['artists', 'albums', 'playlists', 'tracks', 'videos'])) except: return False return True
def load_cache(self): try: fd = xbmcvfs.File(PLAYLISTS_FILE, 'r') self.playlists_cache = eval(fd.read()) fd.close() self.playlists_loaded = True log('Loaded %s Playlists from disk.' % len(self.playlists_cache.keys())) except: self.playlists_loaded = False self.playlists_cache = {} return self.playlists_loaded
def save_cache(self): try: if self.playlists_loaded: fd = xbmcvfs.File(PLAYLISTS_FILE, 'w') fd.write(repr(self.playlists_cache)) fd.close() log('Saved %s Playlists to disk.' % len(self.playlists_cache.keys())) except: return False return True
def readLog(self, path): try: lf = xbmcvfs.File(path) content = lf.read() lf.close() if content: return True, content else: log('file is empty') return False, LANGUAGE(32001) except: log('unable to read file') return False, LANGUAGE(32002)
def getCommandActions(): commands = COMMANDS.copy() for command in commands: actions = commands[command] actions = [ACTIONS[x] for x in actions] commands[command] = actions f = xbmcvfs.File('special://profile/addon_data/script.tvguide.fullscreen/commands.json','rb') j = f.read() f.close() if j: new_commands = json.loads(j) for c in new_commands: if c in commands: commands[c] = new_commands[c] return commands
def getCustomStreamUrls(success): if success: stream_urls = database.getCustomStreamUrls() file_name = 'special://profile/addon_data/script.tvguide.fullscreen/custom_stream_urls.ini' f = xbmcvfs.File(file_name,'wb') for (name,stream) in stream_urls: write_str = "%s=%s\n" % (name,stream) f.write(write_str.encode("utf8")) f.close() xbmcgui.Dialog().notification(ADDON.getAddonInfo('name'), 'Exported channel mappings') else: database.close()
def setCustomStreamUrls(success): if success: file_name = 'special://profile/addon_data/script.tvguide.fullscreen/custom_stream_urls.ini' f = xbmcvfs.File(file_name) lines = f.read().splitlines() stream_urls = [line.decode("utf8").split("=",1) for line in lines] f.close() database.setCustomStreamUrls(stream_urls) xbmcgui.Dialog().notification(ADDON.getAddonInfo('name'), 'Imported channel mappings') else: database.close()
def getAltCustomStreamUrls(success): if success: stream_urls = database.getAltCustomStreamUrls() file_name = 'special://profile/addon_data/script.tvguide.fullscreen/alt_custom_stream_urls.tsv' f = xbmcvfs.File(file_name,'wb') for (name,title,stream) in stream_urls: write_str = "%s\t%s\t%s\n" % (name,title,stream) f.write(write_str.encode("utf8")) f.close() xbmcgui.Dialog().notification(ADDON.getAddonInfo('name'), 'Exported alternative channel mappings') else: database.close()
def setAltCustomStreamUrls(success): if success: file_name = 'special://profile/addon_data/script.tvguide.fullscreen/alt_custom_stream_urls.tsv' f = xbmcvfs.File(file_name) lines = f.read().splitlines() stream_urls = [line.decode("utf8").split("\t",2) for line in lines if '\t' in line] f.close() database.setAltCustomStreamUrls(stream_urls) xbmcgui.Dialog().notification(ADDON.getAddonInfo('name'), 'Imported alternative channel mappings') else: database.close()
def close(self): if not self.isClosing: self.isClosing = True if self.player.isPlaying(): if ADDON.getSetting('stop.on.exit') == "true": self.player.stop() self.clear_catchup() f = xbmcvfs.File('special://profile/addon_data/script.tvguide.fullscreen/tvdb.pickle','wb') try: pickle.dump(self.tvdb_urls,f) except: pass f.close() file_name = 'special://profile/addon_data/script.tvguide.fullscreen/custom_stream_urls_autosave.ini' xbmcvfs.copy(file_name,file_name+".last") f = xbmcvfs.File(file_name,'wb') if self.database: stream_urls = self.database.getCustomStreamUrls() for (name,stream) in stream_urls: write_str = "%s=%s\n" % (name,stream) f.write(write_str.encode("utf8")) f.close() if self.database: self.database.close(super(TVGuide, self).close) else: super(TVGuide, self).close()
def categorySearch(self): d = xbmcgui.Dialog() f = xbmcvfs.File('special://profile/addon_data/script.tvguide.fullscreen/category_count.ini',"rb") category_count = [x.split("=",1) for x in f.read().splitlines()] f.close() categories = [] for (c,v) in category_count: if not self.category or self.category == "All Channels": s = "%s (%s)" % (c,v) else: s = c categories.append(s) which = d.select("Program Category Search",categories) if which == -1: return category = category_count[which][0] programList = self.database.programCategorySearch(category) title = "%s" % category d = ProgramListDialog(title, programList, ADDON.getSetting('listing.sort.time') == 'true') d.doModal() index = d.index action = d.action if action == ACTION_RIGHT: self.showNext() elif action == ACTION_LEFT: self.showListing(programList[index].channel) elif action == KEY_CONTEXT_MENU: if index > -1: self._showContextMenu(programList[index]) else: if index > -1: program = programList[index] now = datetime.datetime.now() start = program.startDate end = program.endDate ask = ADDON.getSetting('catchup.dialog') if (ask == "3") or (ask=="2" and end < now) or (ask=="1" and start < now): self.play_catchup(program) else: self.playOrChoose(program)
def saveActions(self): file_name = 'special://profile/addon_data/script.tvguide.fullscreen/actions.json' f = xbmcvfs.File(file_name,"wb") data = json.dumps(self.actions,indent=2) f.write(data) f.close()
def loadActions(self): file_name = 'special://profile/addon_data/script.tvguide.fullscreen/actions.json' f = xbmcvfs.File(file_name,"rb") data = f.read() f.close() if data: self.actions = json.loads(data) else: self.actions = []
def exportChannelIdList(self): channelsList = self.getChannelList(False,True) channels = [(channel.id,channel.title) for channel in channelsList] f = xbmcvfs.File('special://profile/addon_data/script.tvguide.fullscreen/channel_id_title.ini','wb') for channel in sorted(channels,key=lambda x: x[1].lower()): f.write("%s=%s\n" % (channel[0].encode("utf8"),channel[1].encode("utf8"))) f.close()
def _setCustomStreamUrl(self, channel, stream_url): if stream_url is not None: image = "" if ADDON.getSetting("addon.logos") == "true": file_name = 'special://profile/addon_data/script.tvguide.fullscreen/icons.ini' f = xbmcvfs.File(file_name) items = f.read().splitlines() f.close() for item in items: if item.startswith('['): pass elif item.startswith('#'): pass else: url_icon = item.rsplit('|',1) if len(url_icon) == 2: url = url_icon[0] icon = url_icon[1] if url == stream_url: if icon and icon != "nothing": image = icon.rstrip('/') c = self.conn.cursor() if image: c.execute('UPDATE OR REPLACE channels SET logo=? WHERE id=?' , (image, channel.id)) c.execute("DELETE FROM custom_stream_url WHERE channel=?", [channel.id]) c.execute("INSERT INTO custom_stream_url(channel, stream_url) VALUES(?, ?)", [channel.id, stream_url.decode('utf-8', 'ignore')]) self.conn.commit() c.close()
def __init__(self, filename): self.vfsfile = xbmcvfs.File(filename,"rb") self.size = self.vfsfile.size() self.bytesRead = 0
def setAddonStream(self, section, id, stream): self.addonsParser.set(section, id, stream) self.addonsParser.write(xbmcvfs.File(self.path,"wb"))
def getGUID(): if xbmcvfs.exists("special://temp/rrmj.key"): f = xbmcvfs.File("special://temp/rrmj.key") result = f.read() f.close() if result != "": return result import uuid key = str(uuid.uuid1()) f = xbmcvfs.File("special://temp/rrmj.key", 'w') result = f.write(key) f.close() return key
def save_to_file(content, filename, path=""): if path == "": return False if not xbmcvfs.exists(path): xbmcvfs.mkdirs(path) text_file_path = os.path.join(path, filename + ".txt") now = time.time() text_file = xbmcvfs.File(text_file_path, "w") json.dump(content, text_file) text_file.close() logger.info("saved textfile %s. Time: %f" % (text_file_path, time.time() - now)) return True
def __init(): ''' Contains all network related functionality. ''' cookies = helper.get_profile() + 'cookies.txt' net = NetHelper(cookies, False) # Make sure the cookies exist if not os.path.exists(cookies): cookiesfile = xbmcvfs.File(cookies, 'w') cookiesfile.close() return net, cookies