def convert(path): input = xbmcvfs.File(path, 'rb') output = xbmcvfs.File(path.replace('.ts', '.mp4'), 'wb') error = open(xbmc.translatePath( "special://profile/addon_data/plugin.video.iptv.archive.downloader/errors.txt" ), "w", encoding='utf-8') cmd = [ ffmpeg_location(), "-fflags", "+genpts", "-y", "-i", "-", "-vcodec", "copy", "-acodec", "copy", "-f", "mpegts", "- >>" ] p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=error, shell=windows()) t = threading.Thread(target=read_thread, args=[p, output]) t.start() while True: data_bytes = bytes(input.readBytes(100000)) if not data_bytes: break p.stdin.write(bytearray(data_bytes)) p.stdin.close() error.close()
def get_device_id(reset=False): ''' Return the device_id if already loaded. It will load from jellyfin_guid file. If it's a fresh setup, it will generate a new GUID to uniquely identify the setup for all users. window prop: jellyfin_deviceId ''' client_id = window('jellyfin_deviceId') if client_id: return client_id directory = xbmc.translatePath( 'special://profile/addon_data/plugin.video.jellyfin/') if not xbmcvfs.exists(directory): xbmcvfs.mkdir(directory) jellyfin_guid = os.path.join(directory, "jellyfin_guid") file_guid = xbmcvfs.File(jellyfin_guid) client_id = file_guid.read() if not client_id or reset: LOG.debug("Generating a new GUID.") client_id = str(create_id()) file_guid = xbmcvfs.File(jellyfin_guid, 'w') file_guid.write(client_id) file_guid.close() LOG.debug("DeviceId loaded: %s", client_id) window('jellyfin_deviceId', value=client_id) return client_id
def get_device(): device = None if xbmc.getCondVisibility('system.platform.windows'): device = 'Windows' if xbmc.getCondVisibility('system.platform.linux') \ and not xbmc.getCondVisibility('system.platform.android'): device = 'Linux' if xbmc.getCondVisibility('system.platform.osx'): device = 'Darwin' if xbmc.getCondVisibility('system.platform.android'): device = 'Android' if xbmcvfs.exists('/proc/device-tree/model'): with closing(xbmcvfs.File('/proc/device-tree/model')) as open_file: if 'Raspberry Pi' in open_file.read(): device = 'Raspberry Pi' if xbmcvfs.exists('/etc/os-release'): with closing(xbmcvfs.File('/etc/os-release')) as open_file: contents = open_file.read() if 'libreelec' in contents: device = 'LibreELEC' if 'osmc' in contents: device = 'OSMC' if device is None: try: device = platform.system() except: # pylint: disable=bare-except try: device = platform.platform(terse=True) except: # pylint: disable=bare-except device = sys.platform return device
def writeConfig(cfile, value): cfgfile = OSPJoin(writeConfig.configPath, cfile) cfglockfile = OSPJoin(writeConfig.configPath, cfile + '.lock') if not xbmcvfs.exists(writeConfig.configPath): xbmcvfs.mkdirs(writeConfig.configPath) while True: if not xbmcvfs.exists(cfglockfile): l = xbmcvfs.File(cfglockfile, 'w') l.write(str(time.time())) l.close() if value == '': xbmcvfs.delete(cfgfile) else: f = xbmcvfs.File(cfgfile, 'w') f.write(value.__str__()) f.close() xbmcvfs.delete(cfglockfile) return True else: try: l = xbmcvfs.File(cfglockfile) modified = float(l.read()) l.close() if time.time() - modified > 0.1: xbmcvfs.delete(cfglockfile) except: pass
def writeConfig(cfile, value=''): cfgfile = os.path.join(configpath, cfile) cfglockfile = os.path.join(configpath, cfile + '.lock') if not xbmcvfs.exists(configpath): xbmcvfs.mkdirs(configpath) while True: if not xbmcvfs.exists(cfglockfile): l = xbmcvfs.File(cfglockfile, 'w') l.write(str(time.time())) l.close() if value == '': xbmcvfs.delete(cfgfile) else: f = xbmcvfs.File(cfgfile, 'w') f.write(value.__str__()) f.close() xbmcvfs.delete(cfglockfile) xbmcvfs.delete(cfglockfile) return True else: l = xbmcvfs.File(cfglockfile) modified = l.read() modified = float(modified) if modified else 0 l.close() if time.time() - modified > 0.1: xbmcvfs.delete(cfglockfile)
def sync_list_intern(src_file, dest_file): PLog('sync_list_intern:') # 1. Vorprüfung: Setting Sync / externe Merkliste if SETTINGS.getSetting('pref_merksync') == 'false' or SETTINGS.getSetting( 'pref_merkextern') == 'false': PLog("Sync_OFF") return # 2. Vorprüfung: externe Merkliste ist gleichzeitig interne Merkliste? if src_file == WATCHFILE: PLog("Sync_Block_WATCHFILE") return f = xbmcvfs.File(src_file) s1 = f.size() f.close() ret1 = False ret2 = False if s1 > 100: # Mindestbreite bis dirID=, Eintrag immer > 100 Zeichen ret1 = xbmcvfs.delete(dest_file) PLog('xbmcvfs.delete: ' + str(ret1)) ret2 = xbmcvfs.copy(src_file, dest_file) PLog('xbmcvfs.copy: ' + str(ret2)) f = xbmcvfs.File(dest_file) s2 = f.size() f.close() # Größenvergleich PLog("s1: %d, s2: %d" % (s1, s2)) if ret1 and ret2 and s2 == s1: # ohne Rückgabe PLog("Sync_OK") else: PLog("Sync_Error, s1: %d" % s1) return
def sync_list_intern(src_file, dest_file): PLog('sync_list_intern:') # Vorprüfung Setting Sync / externe Merkliste if SETTINGS.getSetting('pref_merksync') == 'false' or SETTINGS.getSetting( 'pref_merkextern') == 'false': PLog("Sync_OFF") return f = xbmcvfs.File(src_file) s1 = f.size() f.close() if s1 > 100: # Mindestbreite bis dirID=, Eintrag immer größer ret1 = xbmcvfs.delete(dest_file) PLog('xbmcvfs.delete: ' + str(ret1)) ret2 = xbmcvfs.copy(src_file, dest_file) PLog('xbmcvfs.copy: ' + str(ret2)) f = xbmcvfs.File(dest_file) s2 = f.size() f.close() # Größenvergleich PLog("s1: %d, s2: %d" % (s1, s2)) if ret1 and ret2 and s2 == s1: # ohne Rückgabe PLog("Sync_OK") else: PLog("Sync_Error") return
def profile(self, profile): # read addon settings sVolume = ADDON.getSetting('volume') sPlayer = ADDON.getSetting('player') sVideo = ADDON.getSetting('video') sCec = ADDON.getSetting('profile' + profile + '_cec') # read settings from profile f = xbmcvfs.File( os.path.join(ADDON_PATH_DATA, 'profile' + profile + '.json'), 'r') result = f.read() try: jsonResult = json.loads(result) f.close() except ValueError: notify.popup('%s %s (%s)' % (ADDON_LANG(32104), profile, sName[int(profile)])) notify.logError( '[LOAD JSON FROM FILE]: Error reading from profile - %s' % str(profile)) return False # settings needed quote for value quote_needed = [ 'audiooutput.audiodevice', 'audiooutput.passthroughdevice', 'locale.audiolanguage', 'lookandfeel.soundskin' ] # set settings readed from profile file notify.logInfo('[RESTORING SETTING]: %s' % sName[int(profile)]) for setName, setValue in jsonResult.items(): # skip setting that type is disable to changing if 'false' in sPlayer and setName.startswith('videoplayer'): continue if 'false' in sVideo and setName.startswith('videoscreen'): continue notify.logDebug('[RESTORING SETTING]: %s: %s' % (setName, setValue)) # add quotes if setName in quote_needed: setValue = '"%s"' % setValue # set setting if 'true' in sVolume and setName == 'volume': xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "method": "Application.SetVolume", "params": {"volume": %s}, "id": 1}' % jsonResult['volume']) else: xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "method": "Settings.SetSettingValue", "params": {"setting": "%s", "value": %s}, "id": 1}' % (setName, setValue)) notify.popup(sName[int(profile)]) # write curent profile f = xbmcvfs.File(os.path.join(ADDON_PATH_DATA, 'profile'), 'w') f.write(profile) f.close() # CEC if sCec != '' and int(sCec) > 0: notify.logInfo('[SENDING CEC COMMAND]: %s' % cecCommands[int(sCec)]) xbmc.executebuiltin(cecCommands[int(sCec)])
def __init__(self, filename, mode): log("VFSFile: trying to open " + filename) if mode == 'w': self.currentFile = xbmcvfs.File(filename, 'wb') else: self.currentFile = xbmcvfs.File(filename) log("VFSFile: Opening " + filename, xbmc.LOGDEBUG) if self.currentFile == None: log("VFSFile: Couldnt open " + filename, xbmc.LOGERROR)
def recordSegment(cmd, ffmpeg_recording_path): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=False) f = xbmcvfs.File(ffmpeg_recording_path, "w") f.write(bytearray(repr(p.pid).encode('utf-8'))) f.close() video = xbmcvfs.File(ffmpeg_recording_path, "w") # playing = False while True: data = p.stdout.read(1000000) if data: video.write(bytearray(data)) else: break video.close()
def save_merkliste(fname, merkliste, my_ordner): PLog('save_merkliste:') # Merkliste + Ordnerinfo + Ordner: err_msg = '' # gefüllt von Aufrufer my_ordner = " ".join(my_ordner) if my_ordner == '': my_ordner = ORDNER ordner_info = "\n".join(ORDNER_INFO) merkliste = "<merkliste>\n%s</merkliste>\n\n%s\n\n<ordnerliste>%s</ordnerliste>\n" %\ (merkliste, ordner_info, my_ordner) try: if '//' not in fname: err_msg = RSave(fname, merkliste, withcodec=True) # Merkliste speichern if err_msg: ret = False else: ret = True else: PLog("xbmcvfs_fname: " + fname) f = xbmcvfs.File(fname, 'w') # extern - Share ret = f.write(merkliste) f.close() PLog("xbmcvfs_ret: " + str(ret)) if ret: sync_list_intern(src_file=fname, dest_file=WATCHFILE) # Synchronisation return ret, err_msg except Exception as exception: ret = False PLog(str(exception)) err_msg = str(exception) return ret, err_msg
def stat_all(self, current_archive_file=None): files_out = list() if current_archive_file is None: current_archive_file = self.archive_file if current_archive_file is not None: if 'archive://' in current_archive_file or 'rar://' in current_archive_file: archive_path = current_archive_file else: if self.use_vfs_rar: archive_path = 'rar://%(archive_file)s' % { 'archive_file': url_quote(xbmc.translatePath(current_archive_file)) } else: archive_path = 'archive://%(archive_file)s' % { 'archive_file': url_quote(xbmc.translatePath(current_archive_file)) } files_in_archive = self.list_all() for ff in files_in_archive: files_out.append({ 'fullpath': ff, 'filename': os.path.split(ff)[-1], 'size': int(xbmcvfs.File(ff).size()) }) return files_out
def _readFile(self): if (xbmcvfs.exists(self.jsonFile)): # read in the custom file aFile = xbmcvfs.File(self.jsonFile) # load paths in the format {path:path,expression:expression,content:type} tempPaths = json.loads(aFile.read()) # update values in path for aPath in tempPaths: # old files are only video, update if ('content' not in aPath): aPath['content'] = 'video' if ('id' not in aPath): aPath['id'] = self._getNextId() self.paths.append(aPath) aFile.close() else: # write a blank file self._writeFile()
def export_ids(self, what, filename, action): try: ok = False path = settings.import_export_path if len(path) == 0: return items = action() items = [ item for item in items if not isinstance(item, PlayableMedia) or item.available ] if items and len(items) > 0: lines = [ '%s' % item.id + '\t' + item.getLabel(extended=False) + '\n' for item in items ] full_path = os.path.join(path, filename) f = xbmcvfs.File(full_path, 'w') for line in lines: f.write(line.encode('utf-8')) f.close() xbmcgui.Dialog().notification( _P(what), _S(Msg.i30428).format(n=len(lines)), xbmcgui.NOTIFICATION_INFO) ok = True except Exception as e: log.logException(e) return ok
def toggle(self, mode): # create profile file if not xbmcvfs.exists(ADDON_PATH_DATA): xbmcvfs.mkdir(ADDON_PATH_DATA) # try read last active profile f = xbmcvfs.File(os.path.join(ADDON_PATH_DATA, 'profile')) try: profile = f.read() except IOError: profile = '' f.close() if profile: if (len(self.aProfile) == 1) or (profile not in self.aProfile): profile = self.aProfile[0] else: ip = int(self.aProfile.index(profile)) if len(self.aProfile) == ip: try: profile = self.aProfile[0] except IndexError: profile = self.aProfile[0] else: try: profile = self.aProfile[ip + 1] except IndexError: profile = self.aProfile[0] else: profile = self.aProfile[0] self.profile(profile)
def export_playlists(self, playlists, filename): path = settings.import_export_path if len(path) == 0: return full_path = os.path.join(path, filename) fd = xbmcvfs.File(full_path, 'w') numItems = 0 progress = xbmcgui.DialogProgress() progress.create(_S(Msg.i30433)) idx = 0 for playlist in playlists: idx = idx + 1 percent = int((idx * 100) / len(playlists)) progress.update(percent, playlist.getLabel(extended=False)) items = self._session.get_playlist_items(playlist=playlist) items = [item for item in items if item.available] if len(items) > 0: numItems = numItems + playlist.numberOfItems fd.write( repr({ 'uuid': playlist.id, 'title': playlist.title, 'description': playlist.description, 'parentFolderId': playlist.parentFolderId, 'parentFolderName': playlist.parentFolderName, 'ids': [item.id for item in items] }) + '\n') fd.close() progress.close() xbmcgui.Dialog().notification(_P('Playlists'), _S(Msg.i30428).format(n=numItems), xbmcgui.NOTIFICATION_INFO)
def writeLastRun(self): runFile = xbmcvfs.File( xbmcvfs.translatePath(utils.data_dir() + "last_run.txt"), 'w') runFile.write(str(self.last_run)) runFile.close() self.showNotify(True)
def _writeFile(self): # sort the ids self.paths = sorted(self.paths, reverse=True, key=lambda k: k['id']) # create the custom file aFile = xbmcvfs.File(self.jsonFile, 'w') aFile.write(json.dumps(self.paths)) aFile.close()
def cache(self, file_name, data): file_ = self.get_filepath(file_name) try: f = xbmcvfs.File(file_, 'w') json.dump(data, f) f.close() except Exception as e: self.log("[{0}] cache error: {1}".format(self.addon_id, e))
def clean_settings():#Fen code import xml.etree.ElementTree as ET def _make_content(dict_object): if getKodiVersion() >= 18: content = '<settings version="2">' for item in dict_object: if item['id'] in active_settings: if 'default' in item and 'value' in item: content += '\n <setting id="%s" default="%s">%s</setting>' % (item['id'], item['default'], item['value']) elif 'default' in item: content += '\n <setting id="%s" default="%s"></setting>' % (item['id'], item['default']) elif 'value' in item: content += '\n <setting id="%s">%s</setting>' % (item['id'], item['value']) else: content += '\n <setting id="%s"></setting>' else: removed_settings.append(item) else: content = '<settings>' for item in dict_object: if item['id'] in active_settings: if 'value' in item: content += '\n <setting id="%s" value="%s" />' % (item['id'], item['value']) else: content += '\n <setting id="%s" value="" />' % item['id'] else: removed_settings.append(item) content += '\n</settings>' return content try: for addon_id in ('plugin.video.prophet', 'script.module.prophetscrapers'): removed_settings = [] active_settings = [] current_user_settings = [] addon = xbmcaddon.Addon(id=addon_id) addon_dir = transPath(addon.getAddonInfo('path')) profile_dir = transPath(addon.getAddonInfo('profile')) addon_name = addon.getAddonInfo('name') active_settings_xml = os.path.join(addon_dir, 'resources', 'settings.xml') root = ET.parse(active_settings_xml).getroot() for item in root.findall('./category/setting'): setting_id = item.get('id') if setting_id: active_settings.append(setting_id) settings_xml = os.path.join(profile_dir, 'settings.xml') root = ET.parse(settings_xml).getroot() for item in root: dict_item = {} setting_id = item.get('id') setting_default = item.get('default') if getKodiVersion() >= 18: setting_value = item.text else: setting_value = item.get('value') dict_item['id'] = setting_id if setting_value: dict_item['value'] = setting_value if setting_default: dict_item['default'] = setting_default current_user_settings.append(dict_item) new_content = _make_content(current_user_settings) nfo_file = xbmcvfs.File(settings_xml, 'w') nfo_file.write(new_content) nfo_file.close() infoDialog(lang(32110).format(str(len(removed_settings))), heading=addon_name) except: infoDialog('Error Cleaning Settings.xml. Old settings.xml files Restored.', heading=addon_name) sleep(200)
def WriteLog(data, fn=''): if not s.verbLog: return fn = '-' + fn if fn else '' fn = 'avod{}.log'.format(fn) path = OSPJoin(g.HOME_PATH, fn) logfile = xbmcvfs.File(path, 'w') logfile.write(py2_encode(data)) logfile.close()
def SaveFile(filename, data, dirname=None): from contextlib import closing if dirname: filename = cleanName(filename) filename = os.path.join(dirname, filename) if not xbmcvfs.exists(dirname): xbmcvfs.mkdirs(cleanName(dirname.strip(), isfile=False)) filename = cleanName(filename, isfile=False) with closing(xbmcvfs.File(filename, 'w')) as outfile: outfile.write(bytearray(py2_decode(data).encode('utf-8')))
def getConfig(cfile, defvalue=''): cfgfile = os.path.join(configpath, cfile) value = '' if xbmcvfs.exists(cfgfile): f = xbmcvfs.File(cfgfile, 'r') value = f.read() f.close() return value if value else defvalue
def get_cache(self, file_name): json_data = {} file_ = self.get_filepath(file_name) if xbmcvfs.exists(file_): try: f = xbmcvfs.File(file_, 'r') json_data = json.load(f) f.close() except Exception as e: self.log("[{0}] get cache error: {1}".format(self.addon_id, e)) return json_data
def getLastProfile(self): try: f = xbmcvfs.File(os.path.join(ADDON_PATH_DATA, 'profile')) p = f.read() f.close() except IOError: return '' if p in profiles: return p else: return ''
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(self, file, pretty_print=False): """ write(file, pretty_print=False) -> None Write XML to filename of file object in 'file'. If pretty_print is True, the XML will contain whitespace to make it human-readable. """ if pretty_print: indent(self.root) et = ElementTree(self.root).getroot() fle = xbmcvfs.File(file, "wb") fle.write(tostring(et, encoding='utf8', method='xml').decode('utf-8')) fle.close()
def save_merkliste(merkliste, my_ordner): PLog('save_merkliste:') fname = WATCHFILE if SETTINGS.getSetting( 'pref_merkextern') == 'true': # externe Merkliste gewählt? fname = SETTINGS.getSetting('pref_MerkDest_path') if fname == '' or xbmcvfs.exists(fname) == False: PLog("merkextern: %s, %d" % (fname, xbmcvfs.exists(fname))) msg1 = u"Merkliste nicht gefunden\nBitte Settings überprüfen" return False, err_msg PLog(fname) # Merkliste + Ordnerinfo + Ordner: err_msg = '' # gefüllt von Aufrufer if my_ordner == '' or my_ordner == []: # Fallback Basis-Ordner-Liste my_ordner = ORDNER my_ordner = " ".join(my_ordner) ordner_info = "\n".join(ORDNER_INFO) merkliste = "<merkliste>\n%s</merkliste>\n\n%s\n\n<ordnerliste>%s</ordnerliste>\n" %\ (merkliste, ordner_info, my_ordner) try: if '//' not in fname: err_msg = RSave(fname, merkliste, withcodec=True) # Merkliste speichern if err_msg: ret = False else: ret = True else: PLog("xbmcvfs_fname: " + fname) f = xbmcvfs.File(fname, 'w') if PYTHON2: ret = f.write(merkliste) f.close() else: # Python3: Bytearray buf = bytearray() buf.extend(merkliste.encode()) ret = f.write(buf) f.close() PLog("xbmcvfs_ret: " + str(ret)) if ret: sync_list_intern(src_file=fname, dest_file=WATCHFILE) # Synchronisation return ret, err_msg except Exception as exception: ret = False PLog(str(exception)) err_msg = str(exception) return ret, err_msg
def import_playlists(self, filename): try: ok = False f = xbmcvfs.File(filename, 'r') lines = f.read().split('\n') f.close() playlists = [] names = [] for line in lines: try: if len(line) > 0: item = eval(line) names.append(item.get('title')) playlists.append(item) except: pass if len(names) < 1: return False selected = xbmcgui.Dialog().select( _S(Msg.i30432).format(what=_T('Playlist')), names) if selected < 0: return False item = playlists[selected] item_ids = [] for bItem in item.get('ids'): bItem = '%s' % bItem if bItem not in item_ids: item_ids.append(bItem) dialog = xbmcgui.Dialog() title = dialog.input(_T(Msg2.i30233), item.get('title'), type=xbmcgui.INPUT_ALPHANUM) if not title: return False description = dialog.input(_T(Msg2.i30234), item.get('description'), type=xbmcgui.INPUT_ALPHANUM) playlist = self.create_playlist(title, description) if playlist: ok = self.add_playlist_entries(playlist=playlist, item_ids=item_ids) if ok: xbmcgui.Dialog().notification( _T('Playlist'), _S(Msg.i30429).format(n=playlist.title), xbmcgui.NOTIFICATION_INFO) except Exception as e: log.logException(e) return ok
def _read_log_file(self): #try and open the log file lw.log(['trying to open logfile ' + self.LOGFILE]) try: f = xbmcvfs.File(self.LOGFILE) except Exception as e: lw.log(['unexpected error when reading log file', e], xbmc.LOGERROR) return ('', '') lw.log(['opened logfile ' + self.LOGFILE]) #get the first and last line of the log file #the first line has the header information, and the last line has the last log entry first_line = self._parse_line(f, 0) last_line = self._parse_line(f, 2) f.close() lw.log(['first line: ' + first_line, 'last line: ' + last_line]) return first_line, last_line