def play_url_ind(self, index=0, title='', icon='', thumb=''): self.log.out('play') self.player = _TSPlayer() if thumb == "": thumb = addon_icon self.thumb = thumb lnk = self.get_link(index, title, icon, thumb) if not lnk: return False self.player.link = lnk self.player.vod = True if self.progress: self.progress.close() item = xbmcgui.ListItem(title, iconImage="", thumbnailImage=self.thumb, path=lnk) #xbmcplugin.setResolvedUrl(int(sys.argv[1]),True,item) if self.local: xbmcvfs.rename(lnk, lnk) xbmc.Player().play(lnk, item) else: self.player.play(lnk, item) while self.player.active and not self.local: self.loop() xbmc.sleep(300) if xbmc.abortRequested: self.log.out("XBMC is shutting down") break self.log.out('ended play')
def createNfos(self): progressDialog = xbmcgui.DialogProgress() progressDialog.create( "Extras", "Searching for files" ) pendingFiles = self.getExtraNfoFiles( self.get_movie_sources() ) pattern = "-extras-nfo-" current = 0 total = len( pendingFiles ) for file in pendingFiles: current = current + 1 log( "Creating nfo for " + file ) progressDialog.update( current / total, "Creating nfo for " + file ) directory = os.path.dirname( file ) filename = os.path.basename( file ) patternStart = filename.index(pattern) patternEnd = len( pattern ) displayName = filename[patternStart + patternEnd:] displayName = os.path.splitext(displayName)[0].replace(".sample", "") newName = filename[0:patternStart] + "-" + filename[patternStart + patternEnd:] newName = newName.replace( ".sample", "" ) xbmcvfs.rename( file, os.path.join( directory, newName ) ) seasonAndEpisode = self.getSeasonAndEpisode(filename) nfoFile = xbmcvfs.File( os.path.join( directory, os.path.splitext(newName)[0] ) + ".nfo", 'w' ) nfoFile.write( "<episodedetails><title>" + displayName.replace(":", ":") + "</title>" + seasonAndEpisode[0] + seasonAndEpisode[1] + "</episodedetails>" ) nfoFile.close() progressDialog.close() if current > 0: xbmc.executebuiltin("UpdateLibrary(video)") xbmcgui.Dialog().ok("Extras", "Finished scan")
def panFetch(song, path): global _high isad = int(_settings.getSetting('isad')) * 1024 wait = int(_settings.getSetting('delay')) qual = _settings.getSetting('quality') skip = _settings.getSetting('skip') url = urlparse.urlsplit(song.audioUrl[qual]) conn = httplib.HTTPConnection(url.netloc, timeout = 9) conn.request('GET', "%s?%s" % (url.path, url.query)) strm = conn.getresponse() size = int(strm.getheader('content-length')) if size in (341980, 173310): # empty song cause requesting to fast xbmc.log("%s.Fetch MT (%13s,%8d) '%s - %s - %s'" % (_plugin, _stamp, size, song.songId[:4], song.artist, song.title), xbmc.LOGDEBUG) panMsg(song, 'To Many Songs Requested') return xbmc.log("%s.Fetch %s (%13s,%8d) '%s - %s - %s'" % (_plugin, strm.reason, _stamp, size, song.songId[:4], song.artist, song.title)) totl = 0 qued = False last = time.time() file = open(path, 'wb', 0) while (totl < size) and (not xbmc.abortRequested): try: data = strm.read(min(4096, size - totl)) except socket.timeout: xbmc.log("%s.Fetch TO (%13s,%8d) '%s - %s - %s'" % (_plugin, _stamp, totl, song.songId[:4], song.artist, song.title), xbmc.LOGDEBUG) break if _high < (time.time() - last): _high = time.time() - last last = time.time() file.write(data) totl += len(data) if (not qued) and (size > isad): threading.Timer(wait, panQueue, (song, path)).start() qued = True file.close() conn.close() if totl < size: # incomplete file xbmc.log("%s.Fetch RM (%13s) '%s - %s - %s'" % (_plugin, _stamp, song.songId[:4], song.artist, song.title), xbmc.LOGDEBUG) xbmcvfs.delete(path) elif size <= isad: # looks like an ad if skip == 'true': xbmc.log("%s.Fetch AD (%13s) '%s - %s - %s'" % (_plugin, _stamp, song.songId[:4], song.artist, song.title), xbmc.LOGDEBUG) xbmcvfs.delete(path) elif qued == False: # play it anyway song.artist = song.album = song.title = 'Advertisement' dest = path + '.ad.m4a' xbmcvfs.rename(path, dest) panQueue(song, dest) else: panSave(song, path)
def downloadVideo(title, vid): headers = {'User-Agent': 'Android'} global downloadDir if not downloadDir: xbmcgui.Dialog().notification('Download:', translation(30110), _icon, 5000, False) return url = getStreamUrl(vid) vidfile = xbmc.makeLegalFilename(downloadDir + title + '.mp4') if not xbmcvfs.exists(vidfile): tmp_file = tempfile.mktemp(dir=downloadDir, suffix='.mp4') tmp_file = xbmc.makeLegalFilename(tmp_file) pDialog.create('Dailymotion', translation(30044), title) dfile = requests.get(url, headers=headers, stream=True) totalsize = float(dfile.headers['content-length']) handle = open(tmp_file, "wb") chunks = 0 for chunk in dfile.iter_content(chunk_size=2097152): if chunk: # filter out keep-alive new chunks handle.write(chunk) chunks += 1 percent = int(float(chunks * 209715200) / totalsize) pDialog.update(percent) if pDialog.iscanceled(): handle.close() xbmcvfs.delete(tmp_file) break handle.close() try: xbmcvfs.rename(tmp_file, vidfile) return vidfile except: return tmp_file else: xbmcgui.Dialog().notification('Download:', translation(30109), _icon, 5000, False)
def _double_dot_fix_hack(video_filename): """Corrects filename of downloaded subtitle from Foo-Blah..srt to Foo-Blah.es.srt""" log(u"video_filename = %s" % video_filename) work_path = video_filename if _subtitles_setting('storagemode'): custom_subs_path = _subtitles_setting('custompath') if custom_subs_path: _, fname = os.path.split(video_filename) work_path = pjoin(custom_subs_path, fname) log(u"work_path = %s" % work_path) parts = work_path.rsplit('.', 1) if len(parts) > 1: rest = parts[0] for ext in ('srt', 'ssa', 'sub', 'idx'): bad = rest + '..' + ext old = rest + '.es.' + ext if xbmcvfs.exists(bad): log(u"%s exists" % bad) if xbmcvfs.exists(old): log(u"%s exists, removing" % old) xbmcvfs.delete(old) log(u"renaming %s to %s" % (bad, old)) xbmcvfs.rename(bad, old)
def unInstallFont(paths=None): paths = paths or getPaths() if not os.path.exists(paths.fontBackupPath): return False if os.path.exists(paths.fontPath): xbmcvfs.delete(paths.fontPath) xbmcvfs.rename(paths.fontBackupPath,paths.fontPath) dialogs.showMessage(T(32417),T(32590)) return True
def rename(src, dest, quiet=False): if not quiet: msg = "Confirmation" msg2 = "Please confirm rename file!" if not confirm(msg, msg2, src): return False xbmcvfs.rename(src, dest)
def _download( self, src, dst, dst2 ): if (not xbmc.abortRequested): tmpname = xbmc.translatePath('special://profile/addon_data/%s/temp/%s' % ( addonname , xbmc.getCacheThumbName(src) )) lw.log( ['the tmpname is ' + tmpname] ) if xbmcvfs.exists(tmpname): success, loglines = deleteFile( tmpname ) lw.log( loglines ) success, loglines, urldata = imgURL.Get( src, params=self.params ) lw.log( loglines ) if success: success, loglines = writeFile( urldata, tmpname ) lw.log( loglines ) if not success: return False if xbmcvfs.Stat( tmpname ).st_size() > 999: image_ext = getImageType( tmpname ) if not xbmcvfs.exists ( dst + image_ext ): lw.log( ['copying %s to %s' % (tmpname, dst2 + image_ext)] ) xbmcvfs.copy( tmpname, dst2 + image_ext ) lw.log( ['moving %s to %s' % (tmpname, dst + image_ext)] ) xbmcvfs.rename( tmpname, dst + image_ext ) return True else: lw.log( ['image already exists, deleting temporary file'] ) success, loglines = deleteFile( tmpname ) lw.log( loglines ) return False else: success, loglines = deleteFile( tmpname ) lw.log( loglines ) return False
def import_advancedxml(): userdatapath = xbmc.translatePath(os.path.join('special://home/userdata'.decode('utf-8'),''.decode('utf-8'))) advancedsettings_var = os.path.join(userdatapath,'advancedsettings.xml') advancedsettingsbackup_var = os.path.join(userdatapath,'advancedsettingsbackup.xml') if xbmcvfs.exists(advancedsettings_var): print("An advanced settings XML file already exists") if xbmcvfs.exists(advancedsettingsbackup_var): print("An advanced settings backup already exists") xbmcvfs.delete(advancedsettingsbackup_var) xbmcvfs.rename(advancedsettings_var,advancedsettingsbackup_var) advancedname = ["Cachemembuffer=252420","freememorycachepercent=5"] advancedurl = ["http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettings.xml","http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettingstonicillo.xml"] index = xbmcgui.Dialog().select(translate(40185), advancedname) if index > -1: download_tools().Downloader(advancedurl[index],advancedsettings_var,translate(40059),translate(40000)) mensagemok(translate(40000),translate(40060)) else: xbmcvfs.rename(advancedsettings_var,advancedsettingsbackup_var) advancedname = ["Cachemembuffer=252420","freememorycachepercent=5"] advancedurl = ["http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettings.xml","http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettingstonicillo.xml"] index = xbmcgui.Dialog().select(translate(40185), advancedname) if index > -1: download_tools().Downloader(advancedurl[index],advancedsettings_var,translate(40059),translate(40000)) mensagemok(translate(40000),translate(40060)) else: print("No advancedsettings.xml in the system yet") advancedname = ["Cachemembuffer=252420","freememorycachepercent=5"] advancedurl = ["http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettings.xml","http://p2p-strm.googlecode.com/svn/trunk/Advancedsettings/advancedsettingstonicillo.xml"] index = xbmcgui.Dialog().select(translate(40185), advancedname) if index > -1: download_tools().Downloader(advancedurl[index],advancedsettings_var,translate(40059),translate(40000)) mensagemok(translate(40000),translate(40060)) xbmc.executebuiltin("Container.Refresh")
def renameColorTheme(self, file, themeNameOld): dialog = xbmcgui.Dialog() themeNameNew = dialog.input( 'Enter a name for the theme', themeNameOld.decode('utf-8'), type=xbmcgui.INPUT_ALPHANUM).decode("utf-8") if not themeNameNew: return f = open(file, "r") data = f.read() f.close() f = open(file, "w") data = data.replace(themeNameOld.decode('utf-8'), themeNameNew) f.write(data) f.close() if xbmcvfs.exists(file.replace(".theme", ".jpg")): xbmcvfs.rename( file.replace(".theme", ".jpg"), os.path.join(self.userThemesPath, themeNameNew + ".jpg")) xbmcvfs.rename( file, os.path.join(self.userThemesPath, themeNameNew + ".theme")) self.refreshListing()
def migrate_library_to_db(): common.debug('Migrate library from file cache library.ndb2 to database') file_loc = [g.DATA_PATH, 'library.ndb2'] library_file = xbmc.translatePath(os.path.join(*file_loc)) if xbmcvfs.exists(library_file): handle = xbmcvfs.File(library_file, 'r') lib = pickle.loads(handle.read()) handle.close() for item in lib['content'].values(): videoid = item['videoid'].convert_old_videoid_type() if videoid.mediatype == common.VideoId.MOVIE: library.add_to_library(videoid, item['file'], False, False) elif videoid.mediatype == common.VideoId.SHOW: for season_key in item.keys(): if season_key not in [ 'videoid', 'nfo_export', 'exclude_from_update' ]: for episode_key in item[season_key].keys(): if episode_key not in ['videoid', 'nfo_export']: library.add_to_library( item[season_key][episode_key] ['videoid'].convert_old_videoid_type(), item[season_key][episode_key]['file'], item.get('nfo_export', False), item.get('exclude_from_update', False)) xbmcvfs.rename(library_file, library_file + '.bak')
def recordAction(action): log = getActionLogName(False) old_log = getActionLogName(True) addon = xbmcaddon.Addon("service.zomboided.tools") if addon.getSetting("enable_action_log") == "true": try: if xbmcvfs.exists(log): st = xbmcvfs.Stat(log) size = st.st_size() if size > 1024000: # Limit log files to 1MB...this allow for ~10000 entries debugTrace("Action log size is " + str(size) + ", starting new action log") if xbmcvfs.exists(old_log): xbmcvfs.delete(old_log) xbmcvfs.rename(log, old_log) except Exception as e: errorTrace("common.py", "Couldn't manage existing action log file") errorTrace("common.py", str(e)) try: log_file = open(log, 'a+') time = datetime.datetime.fromtimestamp(now()) log_file.write(str(time) + " " + action + "\n") log_file.close() except Exception as e: errorTrace("common.py", "Couldn't record action") errorTrace("common.py", str(e))
def recoverbackup_advancedxml(): userdatapath = xbmc.translatePath(os.path.join('special://home/userdata'.decode('utf-8'),''.decode('utf-8'))) advancedsettings_var = os.path.join(userdatapath,'advancedsettings.xml') advancedsettingsbackup_var = os.path.join(userdatapath,'advancedsettingsbackup.xml') xbmcvfs.delete(advancedsettings_var) xbmcvfs.rename(advancedsettingsbackup_var,advancedsettings_var) mensagemok(translate(40000),translate(40062)) xbmc.executebuiltin("Container.Refresh")
def loop(self): pos = self.pos if len(self.player.coms) > 0: comm = self.player.coms[0] self.player.coms.remove(comm) self.TSpush(comm) if self.player.isPlaying(): if self.player.getTotalTime() > 0: cpos = int( (1 - (self.player.getTotalTime() - self.player.getTime()) / self.player.getTotalTime()) * 100) else: cpos = 0 if cpos in pos: pos.remove(cpos) comm = 'PLAYBACK ' + self.player.link.replace( '\r', '').replace('\n', '') + ' %s' % cpos self.TSpush(comm) if self.tsserv.event and self.save: self.log.out('Try to save file in loop') comm = 'SAVE %s path=%s' % (self.tsserv.event[0] + ' ' + self.tsserv.event[1], urllib.quote(self.filename)) self.TSpush(comm) self.tsserv.event = None succ = True self.saved = True if self.saved and self.player.started: self.log.out('saving content') if self.player.isPlaying() and os.path.exists( self.filename.decode('utf-8')): xbmc.sleep(10000) self.log.out('Start local file') self.tsserv.got_url = self.filename self.local = True self.sm('Start Local File') try: time1 = self.player.getTime() except: time1 = 0 i = xbmcgui.ListItem("***%s" % self.title) i.setProperty('StartOffset', str(time1)) self.log.out('Play local file') try: xbmcvfs.rename(self.filename.decode('utf-8'), self.filename.decode('utf-8')) xbmc.Player().play(self.filename.decode('utf-8'), i) except: xbmcvfs.rename(self.filename, self.filename) xbmc.Player().play(self.filename, i) self.local = True self.player.active = False
def move_file(self, source, dest_folder): """Move a file to a new destination. Will create destination if it does not exist. Example: success = move_file(a, b) :type source: str :param source: the source path (absolute) :type dest_folder: str :param dest_folder: the destination path (absolute) :rtype: bool :return: True if (at least one) file was moved successfully, False otherwise. """ if isinstance(source, unicode): source = source.encode("utf-8") paths = self.unstack(source) success = [] dest_folder = xbmc.makeLegalFilename(dest_folder) if self.is_excluded(paths[0]): debug("Detected a file on an excluded path. Aborting.") return False for p in paths: debug("Attempting to move %r to %r." % (p, dest_folder)) if xbmcvfs.exists(p): if not xbmcvfs.exists(dest_folder): if xbmcvfs.mkdirs(dest_folder): debug("Created destination %r." % dest_folder) else: debug("Destination %r could not be created." % dest_folder, xbmc.LOGERROR) return False new_path = os.path.join(dest_folder, os.path.basename(p)) if xbmcvfs.exists(new_path): debug("A file with the same name already exists in the holding folder. Checking file sizes.") existing_file = xbmcvfs.File(new_path) file_to_move = xbmcvfs.File(p) if file_to_move.size() > existing_file.size(): debug("This file is larger than the existing file. Replacing it with this one.") existing_file.close() file_to_move.close() success.append(bool(xbmcvfs.delete(new_path) and xbmcvfs.rename(p, new_path))) else: debug("This file isn't larger than the existing file. Deleting it instead of moving.") existing_file.close() file_to_move.close() success.append(bool(xbmcvfs.delete(p))) else: debug("Moving %r to %r." % (p, new_path)) success.append(bool(xbmcvfs.rename(p, new_path))) else: debug("File %r no longer exists." % p, xbmc.LOGWARNING) success.append(False) return any(success)
def saveTorrent(self, torrentUrl): if re.match("^magnet\:.+$", torrentUrl): self.magnetLink = torrentUrl self.magnetToTorrent(torrentUrl) self.magnetLink = None return self.torrentFile else: if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) torrentFile = self.torrentFilesPath + self.md5( torrentUrl) + '.torrent' try: if not re.match("^http\:.+$", torrentUrl): contentFile = xbmcvfs.File(torrentUrl, "rb") content = contentFile.read() contentFile.close() else: request = urllib2.Request(torrentUrl) request.add_header('Referer', torrentUrl) request.add_header('Accept-encoding', 'gzip') result = urllib2.urlopen(request) if result.info().get('Content-Encoding') == 'gzip': buf = StringIO(result.read()) decomp = zlib.decompressobj(16 + zlib.MAX_WBITS) content = decomp.decompress(buf.getvalue()) else: content = result.read() localFile = xbmcvfs.File(torrentFile, "w+b") localFile.write(content) localFile.close() except Exception, e: log('Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str(e)) return if xbmcvfs.exists(torrentFile): try: e = self.lt.bdecode(xbmcvfs.File(torrentFile, 'rb').read()) self.torrentFileInfo = self.lt.torrent_info(e) except Exception, e: log('Exception: ' + str(e)) xbmcvfs.delete(torrentFile) return if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) newFile = self.torrentFilesPath + self.md5( torrentUrl) + '.torrent' if newFile != torrentFile: if xbmcvfs.exists(newFile): xbmcvfs.delete(newFile) if not xbmcvfs.exists(newFile): try: xbmcvfs.rename(torrentFile, newFile) except Exception, e: log('Unable to rename torrent file from %s to %s in Torrent::renameTorrent. Exception: %s' % (torrentFile, newFile, str(e))) return
def dump_dict(self): if xbmcvfs.exists(self.uri): if xbmcvfs.exists(self.uri + '.old'): xbmcvfs.delete(self.uri + '.old') xbmcvfs.rename(self.uri, self.uri + '.old') storage_file = xbmcvfs.File(self.uri, 'w') storage_file.write( json.dumps(self.info, sort_keys=True, indent=4 * ' ')) storage_file.close()
def checkKBModRemove(skinPath): backupPath = getSkinFilePath(skinPath,'DialogKeyboard.xml.FBbackup') dialogPath = getSkinFilePath(skinPath,'DialogKeyboard.xml') if backupPath and dialogPath: xbmcvfs.delete(dialogPath) xbmcvfs.rename(backupPath,dialogPath) setSetting('keyboard_installed',False) dialogs.showMessage(T(32476),T(32476),' ',T(32477)) return True
def saveTorrent(self, torrentUrl): if re.match("^magnet\:.+$", torrentUrl): self.magnetLink = torrentUrl self.magnetToTorrent(torrentUrl) self.magnetLink = None return self.torrentFile else: if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) torrentFile = self.torrentFilesPath + self.md5( torrentUrl) + '.torrent' try: if not re.match("^http\:.+$", torrentUrl): content = xbmcvfs.File(torrentUrl, "rb").read() else: request = urllib2.Request(torrentUrl) request.add_header('Referer', torrentUrl) request.add_header('Accept-encoding', 'gzip') result = urllib2.urlopen(request) if result.info().get('Content-Encoding') == 'gzip': buf = StringIO(result.read()) f = gzip.GzipFile(fileobj=buf) content = f.read() else: content = result.read() localFile = xbmcvfs.File(torrentFile, "w+b") localFile.write(content) localFile.close() except Exception, e: log('Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str(e)) return if xbmcvfs.exists(torrentFile): try: e = self.lt.bdecode(xbmcvfs.File(torrentFile, 'rb').read()) self.torrentFileInfo = self.lt.torrent_info(e) except Exception, e: log('Exception: ' + str(e)) xbmcvfs.delete(torrentFile) return baseName = file_encode(os.path.basename(self.getFilePath())) if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) newFile = self.torrentFilesPath + self.md5( baseName) + '.' + self.md5( torrentUrl) + '.torrent' # + '.'+ baseName if xbmcvfs.exists(newFile): xbmcvfs.delete(newFile) if not xbmcvfs.exists(newFile): try: xbmcvfs.rename(torrentFile, newFile) except Exception, e: print 'Unable to rename torrent file from "' + torrentFile + '" to "' + newFile + '" in Torrent::renameTorrent' + '. Exception: ' + str( e) return
def killme(spsc_pid=False): global SPSC_BINARY if not xbmc.getCondVisibility('system.platform.windows'): if settings.getSetting('sop_debug_mode') == "true": try: stdout, stderr = spsc.communicate() print(stdout, stderr) except: pass try: os.kill(spsc_pid, 9) except: pass xbmc.sleep(100) try: os.system("killall -9 " + SPSC_BINARY) except: pass xbmc.sleep(100) try: spsc.kill() except: pass xbmc.sleep(100) try: spsc.wait() except: pass print("Player ended at last") else: print("Player reached the end") cmd = ['sc', 'stop', 'sopcastp2p'] import subprocess proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) servicecreator = False for line in proc.stdout: print("result line" + line.rstrip()) #dirty hack to break sopcast.exe player codec - renaming the file later import _winreg aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) try: aKey = _winreg.OpenKey(aReg, r'SOFTWARE\SopCast\Player\InstallPath', 0, _winreg.KEY_READ) name, value, type = _winreg.EnumValue(aKey, 0) codec_file = os.path.join( os.path.join(value.replace("SopCast.exe", "")), 'codec', 'sop.ocx.old') _winreg.CloseKey(aKey) if xbmcvfs.exists(codec_file): xbmcvfs.rename( codec_file, os.path.join( os.path.join(value.replace("SopCast.exe", "")), 'codec', 'sop.ocx')) except: pass
def rename_folder(path, name): d = xbmcgui.Dialog() new_name = d.input("New Name for: %s" % name, name) if not new_name: return old_folder = "%s%s/" % (path, name) new_folder = "%s%s/" % (path, new_name) xbmcvfs.rename(old_folder, new_folder) xbmc.executebuiltin('Container.Refresh')
def download_sub(subtitle): xbmc_temp = xbmc.translatePath('special://temp') tempdir = os.path.join(xbmc_temp, 'phudeVMF') if 'subscene.com' in subtitle: response = urlfetch.get(subtitle) sub = re.search(r'href=\"(/subtitle/download?.*?)\"', response.body) sub = sub.group(1) subpath = "https://subscene.com" + sub if 'phudeviet.org' in subtitle: f = urlfetch.get(subtitle) match = re.search(r"(http://phudeviet.org/download/.+?html)", f.body) subpath = match.group(1) f = urlfetch.get(subpath) subpath = f.getheader('location') vDialog.create('Vietmediaf','Bắt đầu tải phụ đề xin vui lòng đợi trong giây lát.','Downloading...') if not os.path.exists(tempdir): try: xbmcvfs.mkdirs(tempdir) time.sleep(20) except:pass else: for root, dirs, files in os.walk(tempdir, topdown=False): for name in files: try:os.remove(os.path.join(root, name)) except:pass for name in dirs: try:os.rmdir(os.path.join(root, name)) except:pass useragent = ("User-Agent=Mozilla/5.0 (Windows NT 10.0; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0") headers = {'User-Agent': useragent, 'Referer': subtitle} tmp_file = os.path.join(tempdir, "phude.zip") try: if os.path.exists(tmp_file): os.remove(tmp_file) request = urllib2.Request(subpath, '', headers) response = urllib2.urlopen(request) file_handle = xbmcvfs.File(tmp_file, "wb") file_handle.write(response.read()) xbmc.sleep(500) file_handle.close() xbmc.executebuiltin('XBMC.Extract("%s","%s")' % (tmp_file, tempdir)) except: notify('Không tải được phụ đề') pass vDialog.close() exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"] sub_temp = os.path.join(tempdir, "sub.file") for file in xbmcvfs.listdir(tempdir)[1]: if os.path.splitext(file)[1] in exts: sub_file = os.path.join(tempdir, file) xbmcvfs.rename(sub_file, sub_temp) return sub_temp
def Restore(bak, org): log('Restore ' + str(bak) + ' - ' + str(org)) if FileAccess.exists(bak): if FileAccess.exists(org): try: xbmcvfs.delete(org) except: pass xbmcvfs.rename(bak, org) xbmc.executebuiltin("Notification( %s, %s, %d, %s)" % ("PseudoTV Live", "Restore Complete, Restarting...", 1000, THUMB) )
def saveTorrent(self, torrentUrl): if re.match("^magnet\:.+$", torrentUrl): self.magnetLink = torrentUrl self.magnetToTorrent(torrentUrl) self.magnetLink = None return self.torrentFile else: if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) torrentFile = self.torrentFilesPath + self.md5( torrentUrl) + '.torrent' try: if not re.match("^http\:.+$", torrentUrl): content = xbmcvfs.File(torrentUrl, "rb").read() else: request = urllib2.Request(torrentUrl) request.add_header('Referer', torrentUrl) request.add_header('Accept-encoding', 'gzip') result = urllib2.urlopen(request) if result.info().get('Content-Encoding') == 'gzip': buf = StringIO(result.read()) f = gzip.GzipFile(fileobj=buf) content = f.read() else: content = result.read() localFile = xbmcvfs.File(torrentFile, "w+b") localFile.write(content) localFile.close() except Exception, e: print 'Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str( e) return if xbmcvfs.exists(torrentFile): try: e=self.lt.bdecode(xbmcvfs.File(torrentFile,'rb').read()) self.torrentFileInfo = self.lt.torrent_info(e) except Exception, e: print 'Exception: ' + str(e) xbmcvfs.delete(torrentFile) return baseName = file_encode(os.path.basename(self.getFilePath())) if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) newFile = self.torrentFilesPath + self.md5(baseName) + '.' + self.md5( torrentUrl) + '.torrent' # + '.'+ baseName if xbmcvfs.exists(newFile): xbmcvfs.delete(newFile) if not xbmcvfs.exists(newFile): try: xbmcvfs.rename(torrentFile, newFile) except Exception, e: print 'Unable to rename torrent file from "' + torrentFile + '" to "' + newFile + '" in Torrent::renameTorrent' + '. Exception: ' + str( e) return
def download(self, path, url): try: cookie = None anonymous = (self.user == '' or self.password == '') code, result = client.request(url, output='response', error=True) if code == '429' and anonymous is True: control.dialog.ok(str('xsubs.tv'), str(result), str('')) return elif anonymous is False: cookie = cache.get(self.cookie, 12) result, headers, content, cookie = client.request( url, cookie=cookie, output='extended') subtitle = content['Content-Disposition'] subtitle = re.findall('"(.+?)"', subtitle)[0] try: subtitle = subtitle.decode('utf-8') except Exception: pass subtitle = control.join(path, subtitle) if not subtitle.endswith('.srt'): raise Exception() with open(subtitle, 'wb') as subFile: subFile.write(result) fileparts = os_split(subtitle)[1].split('.') result = control.join( os_split(subtitle)[0], 'subtitles.' + fileparts[len(fileparts) - 1]) rename(subtitle, result) return result except Exception as e: log.log( 'Xsubstv subtitle download failed for the following reason: ' + str(e)) return
def loop(self): if self.local: return pos=self.pos self.log.out('1') if len(self.player.coms)>0: comm=self.player.coms[0] self.player.coms.remove(comm) self.TSpush(comm) self.log.out('2') if self.player.isPlaying(): if self.player.getTotalTime()>0: cpos= int((1-(self.player.getTotalTime()-self.player.getTime())/self.player.getTotalTime())*100) else: cpos=0 if cpos in pos: pos.remove(cpos) comm='PLAYBACK '+self.player.link.replace('\r','').replace('\n','')+' %s'%cpos self.TSpush(comm) self.log.out('3') if self.tsserv.event and self.save: self.log.out('Try to save file in loop') try: comm='SAVE %s path=%s'%(self.tsserv.event[0]+' '+self.tsserv.event[1],urllib.quote(self.filename)) except: comm='SAVE %s path=%s'%(self.tsserv.event[0]+' '+self.tsserv.event[1],urllib.quote(self.filenam.encode('utf-8'))) self.TSpush(comm) self.tsserv.event=None succ=True self.saved=True self.log.out('4') if self.saved: self.log.out('4.1') try: tt=os.path.exists(self.filename.decode('utf-8')) except: tt=os.path.exists(self.filename) if self.player.isPlaying() and tt: xbmc.sleep(3000) self.log.out('Start local file') self.tsserv.got_url=self.filename self.local=True self.sm('Start Local File') try: time1=self.player.getTime() except: time1=0 i = xbmcgui.ListItem("***%s"%self.title) i.setProperty('StartOffset', str(time1)) self.log.out('Play local file') try: xbmcvfs.rename(self.filename.decode('utf-8'),self.filename.decode('utf-8')) xbmc.Player().play(self.filename.decode('utf-8'),i) except: xbmcvfs.rename(self.filename,self.filename) xbmc.Player().play(self.filename,i) self.local=True self.player.active=False saved=False self.save=False self.log.out('loop succ')
def saveTorrent(self, torrentUrl): if re.match("^magnet\:.+$", torrentUrl): self.magnetLink = torrentUrl self.magnetToTorrent(torrentUrl) self.magnetLink = None return self.torrentFile else: if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) torrentFile = self.torrentFilesPath + self.md5( torrentUrl) + '.torrent' try: if not re.match("^http\:.+$", torrentUrl): contentFile = xbmcvfs.File(torrentUrl, "rb") content = contentFile.read() contentFile.close() else: request = urllib2.Request(torrentUrl) request.add_header('Referer', torrentUrl) request.add_header('Accept-encoding', 'gzip') result = urllib2.urlopen(request) if result.info().get('Content-Encoding') == 'gzip': buf = StringIO(result.read()) decomp = zlib.decompressobj(16 + zlib.MAX_WBITS) content = decomp.decompress(buf.getvalue()) else: content = result.read() localFile = xbmcvfs.File(torrentFile, "w+b") localFile.write(content) localFile.close() except Exception, e: log('Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str(e)) return if xbmcvfs.exists(torrentFile): try: e=self.lt.bdecode(xbmcvfs.File(torrentFile,'rb').read()) self.torrentFileInfo = self.lt.torrent_info(e) except Exception, e: log('Exception: ' + str(e)) xbmcvfs.delete(torrentFile) return if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) newFile = self.torrentFilesPath + self.md5(torrentUrl) + '.torrent' if newFile != torrentFile: if xbmcvfs.exists(newFile): xbmcvfs.delete(newFile) if not xbmcvfs.exists(newFile): try: xbmcvfs.rename(torrentFile, newFile) except Exception, e: log('Unable to rename torrent file from %s to %s in Torrent::renameTorrent. Exception: %s' % (torrentFile, newFile, str(e))) return
def rename_folder(path,name): d = xbmcgui.Dialog() unquoted_name = urllib.unquote(name) new_name = d.input("New Name for: %s" % unquoted_name,unquoted_name) if not new_name: return quoted_new_name = urllib.quote(new_name,safe='') old_folder = "%s%s/" % (path,name) new_folder = "%s%s/" % (path,quoted_new_name) xbmcvfs.rename(old_folder,new_folder) xbmc.executebuiltin('Container.Refresh')
def _create_temp_item(self, file_path): if os.path.exists(file_path): if os.path.isfile(file_path): self._destroy_file_if_exists(TEMP_FORMAT.format(file_path)) xbmcvfs.rename(file_path, TEMP_FORMAT.format(file_path)) else: if xbmcvfs.exists(tools.ensure_path_is_dir(TEMP_FORMAT.format(file_path))): shutil.rmtree(TEMP_FORMAT.format(file_path)) os.rename(tools.ensure_path_is_dir(file_path), tools.ensure_path_is_dir(TEMP_FORMAT.format(file_path))) self._temporary_items.append(file_path)
def save_session(): temp_file = utility.session_file() + '.tmp' if xbmcvfs.exists(temp_file): xbmcvfs.delete(temp_file) session_backup = pickle.dumps(session) file_handler = xbmcvfs.File(temp_file, 'wb') file_handler.write(session_backup) file_handler.close() if xbmcvfs.exists(utility.session_file()): xbmcvfs.delete(utility.session_file()) xbmcvfs.rename(temp_file, utility.session_file())
def break_sopcast(): if xbmc.getCondVisibility('system.platform.windows'): import _winreg aReg = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE) try: aKey = _winreg.OpenKey(aReg, r'SOFTWARE\SopCast\Player\InstallPath',0, _winreg.KEY_READ) name, value, type = _winreg.EnumValue(aKey, 0) codec_file = os.path.join(os.path.join(value.replace("SopCast.exe","")),'codec','sop.ocx.old') _winreg.CloseKey(aKey) if xbmcvfs.exists(codec_file): xbmcvfs.rename(codec_file,os.path.join(os.path.join(value.replace("SopCast.exe","")),'codec','sop.ocx')) except:pass
def loop(self): pos = self.pos if len(self.player.coms) > 0: comm = self.player.coms[0] self.player.coms.remove(comm) self.TSpush(comm) if self.player.isPlaying(): if self.player.getTotalTime() > 0: cpos = int( (1 - (self.player.getTotalTime() - self.player.getTime()) / self.player.getTotalTime()) * 100 ) else: cpos = 0 if cpos in pos: pos.remove(cpos) comm = "PLAYBACK " + self.player.link.replace("\r", "").replace("\n", "") + " %s" % cpos self.TSpush(comm) if self.tsserv.event and self.save: self.log.out("Try to save file in loop") comm = "SAVE %s path=%s" % (self.tsserv.event[0] + " " + self.tsserv.event[1], urllib.quote(self.filename)) self.TSpush(comm) self.tsserv.event = None succ = True self.saved = True if self.saved and self.player.started: self.log.out("saving content") if self.player.isPlaying() and os.path.exists(self.filename.decode("utf-8")): xbmc.sleep(10000) self.log.out("Start local file") self.tsserv.got_url = self.filename self.local = True self.sm("Start Local File") try: time1 = self.player.getTime() except: time1 = 0 i = xbmcgui.ListItem("***%s" % self.title) i.setProperty("StartOffset", str(time1)) self.log.out("Play local file") try: xbmcvfs.rename(self.filename.decode("utf-8"), self.filename.decode("utf-8")) xbmc.Player().play(self.filename.decode("utf-8"), i) except: xbmcvfs.rename(self.filename, self.filename) xbmc.Player().play(self.filename, i) self.local = True self.player.active = False
def killme(spsc_pid=False): global SPSC_BINARY if not xbmc.getCondVisibility("system.platform.windows"): if settings.getSetting("sop_debug_mode") == "true": try: stdout, stderr = spsc.communicate() print (stdout, stderr) except: pass try: os.kill(spsc_pid, 9) except: pass xbmc.sleep(100) try: os.system("killall -9 " + SPSC_BINARY) except: pass xbmc.sleep(100) try: spsc.kill() except: pass xbmc.sleep(100) try: spsc.wait() except: pass print ("Player ended at last") else: print ("Player reached the end") cmd = ["sc", "stop", "sopcastp2p"] import subprocess proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) servicecreator = False for line in proc.stdout: print ("result line" + line.rstrip()) # dirty hack to break sopcast.exe player codec - renaming the file later import _winreg aReg = _winreg.ConnectRegistry(None, _winreg.HKEY_LOCAL_MACHINE) try: aKey = _winreg.OpenKey(aReg, r"SOFTWARE\SopCast\Player\InstallPath", 0, _winreg.KEY_READ) name, value, type = _winreg.EnumValue(aKey, 0) codec_file = os.path.join(os.path.join(value.replace("SopCast.exe", "")), "codec", "sop.ocx.old") _winreg.CloseKey(aKey) if xbmcvfs.exists(codec_file): xbmcvfs.rename( codec_file, os.path.join(os.path.join(value.replace("SopCast.exe", "")), "codec", "sop.ocx") ) except: pass
def move_file(self, source, dest_folder): """Move a file to a new destination. Returns True if the move succeeded, False otherwise. Will create destination if it does not exist. Example: success = move_file(a, b) :type source: basestring :param source: the source path (absolute) :type dest_folder: str :param dest_folder: the destination path (absolute) :rtype : bool """ if self.is_excluded(source): self.debug("This file is found on an excluded path and will not be moved.") return False if isinstance(source, unicode): source = source.encode("utf-8") dest_folder = xbmc.makeLegalFilename(dest_folder) self.debug("Moving %s to %s" % (os.path.basename(source), dest_folder)) if xbmcvfs.exists(source): if not xbmcvfs.exists(dest_folder): self.debug("XBMC could not find destination %s" % dest_folder) self.debug("Creating destination %s" % dest_folder) if xbmcvfs.mkdirs(dest_folder): self.debug("Successfully created %s" % dest_folder) else: self.debug("XBMC could not create destination %s" % dest_folder, xbmc.LOGERROR) return False new_path = os.path.join(dest_folder, os.path.basename(source)) if xbmcvfs.exists(new_path): self.debug("A file with the same name already exists in the holding folder. Checking file sizes.") existing_file = xbmcvfs.File(new_path) file_to_move = xbmcvfs.File(source) if file_to_move.size() > existing_file.size(): self.debug("This file is larger than the existing file. Replacing the existing file with this one.") existing_file.close() file_to_move.close() return xbmcvfs.delete(new_path) and xbmcvfs.rename(source, new_path) else: self.debug("This file is smaller than the existing file. Deleting this file instead of moving.") existing_file.close() file_to_move.close() return self.delete_file(source) else: self.debug("Moving %s\nto %s\nNew path: %s" % (source, dest_folder, new_path)) return xbmcvfs.rename(source, new_path) else: self.debug("XBMC could not find the file at %s" % source, xbmc.LOGWARNING) return False
def upgrade_addon_labelID( self, path = None ): # This function will upgrade the labelIDs of addons (and any other out of date labelIDs) to the new format if path is not None: profilelist = [path] else: # Get all profiles profile_file = xbmc.translatePath( 'special://userdata/profiles.xml' ).decode("utf-8") tree = None if xbmcvfs.exists( profile_file ): tree = xmltree.parse( profile_file ) profilelist = [] if tree is not None: profiles = tree.findall( "profile" ) for profile in profiles: name = profile.find( "name" ).text.encode( "utf-8" ) dir = profile.find( "directory" ).text.encode( "utf-8" ) # Localise the directory if "://" in dir: dir = xbmc.translatePath( os.path.join( dir, "addon_data", "script.skinshortcuts" ) ).decode( "utf-8" ) else: # Base if off of the master profile dir = xbmc.translatePath( os.path.join( "special://masterprofile", dir, "addon_data", "script.skinshortcuts" ) ).decode( "utf-8" ) profilelist.append( dir ) else: profilelist = [xbmc.translatePath( "special://masterprofile/addon_data/script.skinshortcuts" )] DATA = DataFunctions() for folder in profilelist: file = os.path.join( folder, "mainmenu.DATA.xml" ) if xbmcvfs.exists( file ): DATA._clear_labelID() root = xmltree.parse( file ).getroot() oldLabelID = [] newLabelID = [] for shortcut in root.findall( "shortcut" ): DATA.labelIDList = oldLabelID oldLabel = DATA._get_labelID( shortcut.find( "label" ).text, shortcut.find( "action" ).text, includeAddOnID = False ) oldLabelID = DATA.labelIDList DATA.labelIDList = newLabelID newLabel = DATA._get_labelID( shortcut.find( "label" ).text, shortcut.find( "action" ).text ) newLabelID = DATA.labelIDList if oldLabel != newLabel: if xbmcvfs.exists( DATA.slugify( os.path.join( folder, oldLabel + ".DATA.xml" ) ) ): xbmcvfs.rename( DATA.slugify( os.path.join( folder, oldLabel + ".DATA.xml" ) ), DATA.slugify( os.path.join( folder, newLabel + ".DATA.xml" ) ) )
def download(src, dst, dst2): if (not xbmc.abortRequested): tmpname = xbmc.translatePath('special://profile/addon_data/%s/temp/%s' % ( __addonname__ , xbmc.getCacheThumbName(src) )) if xbmcvfs.exists(tmpname): xbmcvfs.delete(tmpname) urllib.urlretrieve(src, tmpname) if os.path.getsize(tmpname) > 999: log( 'copying file to transition directory' ) xbmcvfs.copy(tmpname, dst2) log( 'moving file to cache directory' ) xbmcvfs.rename(tmpname, dst) else: xbmcvfs.delete(tmpname)
def clean_related_files(self, source, dest_folder=None): """Clean files related to another file based on the user's preferences. Related files are files that only differ by extension, or that share a prefix in case of stacked movies. Examples of related files include NFO files, thumbnails, subtitles, fanart, etc. :type source: str :param source: Location of the file whose related files should be cleaned. :type dest_folder: str :param dest_folder: (Optional) The folder where related files should be moved to. Not needed when deleting. """ if get_setting(clean_related): debug("Cleaning related files.") path_list = self.unstack(source) path, name = os.path.split( path_list[0] ) # Because stacked movies are in the same folder, only check one if source.startswith("stack://"): name = self.get_stack_bare_title(path_list) else: name, ext = os.path.splitext(name) debug("Attempting to match related files in %r with prefix %r" % (path, name)) for extra_file in xbmcvfs.listdir(path)[1]: if isinstance(path, unicode): path = path.encode("utf-8") if isinstance(extra_file, unicode): extra_file = extra_file.encode("utf-8") if isinstance(name, unicode): name = name.encode("utf-8") if extra_file.startswith(name): debug("%r starts with %r." % (extra_file, name)) extra_file_path = os.path.join(path, extra_file) if get_setting(cleaning_type) == self.CLEANING_TYPE_DELETE: if extra_file_path not in path_list: debug("Deleting %r." % extra_file_path) xbmcvfs.delete(extra_file_path) elif get_setting(cleaning_type) == self.CLEANING_TYPE_MOVE: new_extra_path = os.path.join( dest_folder, os.path.basename(extra_file)) if new_extra_path not in path_list: debug("Moving %r to %r." % (extra_file_path, new_extra_path)) xbmcvfs.rename(extra_file_path, new_extra_path) debug("Finished searching for related files.") else: debug("Cleaning of related files is disabled.")
def download_video(video_url, video_name=None): # print('URL Video to download ' + video_url) # Now that we have video URL we can try to download this one YDStreamUtils = __import__('YDStreamUtils') YDStreamExtractor = __import__('YDStreamExtractor') vid = YDStreamExtractor.getVideoInfo( video_url, quality=cq_utils.get_quality_YTDL(download_mode=True), resolve_redirects=True ) path = Script.setting.get_string('dl_folder') download_ok = False with YDStreamUtils.DownloadProgress() as prog: try: YDStreamExtractor.setOutputCallback(prog) result = YDStreamExtractor.handleDownload( vid, bg=Script.setting.get_boolean('dl_background'), path=path ) if result: if result.status == 'canceled': error_message = result.message Script.log('Download failed: %s' % error_message) else: full_path_to_file = result.filepath Script.log('Download success: %s' % full_path_to_file) download_ok = True finally: YDStreamExtractor.setOutputCallback(None) if path != '' and \ Script.setting.get_boolean('dl_item_filename') and \ video_name is not None and \ download_ok: try: filename = os.path.basename(full_path_to_file) _, file_extension = os.path.splitext(full_path_to_file) current_filepath = os.path.join(path, filename) final_filepath = os.path.join(path, video_name + file_extension) xbmcvfs.rename(current_filepath, final_filepath) except Exception: Script.log('Failed to rename video file') return False
def __erase(self, siteName): try: folder = 'plugin.video.vstream/resources/sites/' sMath = cConfig().getAddonPath().replace('plugin.video.vstream', '') sFolder = os.path.join(sMath, folder) oldName = sFolder + siteName newName = sFolder + siteName + '.desactiver' xbmcvfs.rename(oldName, newName) except: pass return
def download(src, dst, dst2, display_dialog): if (not xbmc.abortRequested): tmpname = xbmc.translatePath('special://profile/addon_data/%s/temp/%s' % ( __addonname__ , xbmc.getCacheThumbName(src) )) if xbmcvfs.exists(tmpname): xbmcvfs.delete(tmpname) global __last_time__ __last_time__ = 0 urllib.urlretrieve( src, tmpname, lambda nb, bs, fs: reporthook(nb, bs, fs, display_dialog) ) if os.path.getsize(tmpname) > 999: log( 'copying file to transition directory' ) xbmcvfs.copy(tmpname, dst2) log( 'moving file to cache directory' ) xbmcvfs.rename(tmpname, dst) else: xbmcvfs.delete(tmpname)
def changestreams(): nameoriginal = '' nametochange = '' count = 0 alreadychanged = False dir, files = xbmcvfs.listdir(libraryfolder_change) for directories in dir: nametochange = '' nameoriginal = '' alreadychanged = False libfolder = os.path.join(libraryfolder, directories) libfolder_change = os.path.join(libraryfolder_change, directories) ano = directories[len(directories) - 5:-1] titulo = directories[:-5] if ano: yearbefore = int(ano) - 1 yearafter = int(ano) + 1 libfolder1 = os.path.join(libraryfolder, titulo + str(yearbefore) + ')') libfolder2 = os.path.join(libraryfolder, titulo + str(yearafter) + ')') if xbmcvfs.exists(libfolder1): libfolder = libfolder1 if xbmcvfs.exists(libfolder2): libfolder = libfolder2 if xbmcvfs.exists(libfolder): dir2, files2 = xbmcvfs.listdir(libfolder) for name2 in files2: if '.strm' in name2: nametochange = name2 if '.bak' in name2: alreadychanged = True if not alreadychanged: dir3, files3 = xbmcvfs.listdir(libfolder_change) for name3 in files3: if '.strm' in name3: nameoriginal = name3 if nametochange and nameoriginal: count = count + 1 source = os.path.join(libfolder, nametochange) destination = os.path.join(libfolder, nametochange[:-4] + 'bak') xbmcvfs.rename(source, destination) shutil.copy(os.path.join(libfolder_change, nameoriginal), os.path.join(libfolder, nametochange)) else: print '##falhou' + libfolder ok = mensagemok( 'Trocar Streams', 'Processo terminado\nForam alterados ' + str(count) + ' streams')
def rename(path, newpath): FileAccess.log("rename " + path + " to " + newpath) try: if xbmcvfs.rename(path, newpath): return True except: pass if path[0:6].lower() == 'smb://' or newpath[0:6].lower() == 'smb://': if os.name.lower() == 'nt': FileAccess.log("Modifying name") if path[0:6].lower() == 'smb://': path = '\\\\' + path[6:] if newpath[0:6].lower() == 'smb://': newpath = '\\\\' + newpath[6:] try: os.rename(path, newpath) FileAccess.log("os.rename") return True except: pass try: shutil.move(path, newpath) FileAccess.log("shutil.move") return True except: pass FileAccess.log("OSError") raise OSError()
def _legacy_conversion(self, folder, tmdb_id): # Get details details = TMDb().get_request_sc('tv', tmdb_id, append_to_response='external_ids') if not details or not details.get('first_air_date'): return # Skip shows without details/year # Get new name and compare to old name name = u'{} ({})'.format(details.get('name'), details['first_air_date'][:4]) if folder == name: return # Skip if already converted # Convert name basedir = BASEDIR_TV.replace('\\', '/') old_folder = u'{}{}/'.format(basedir, validify_filename(folder)) new_folder = u'{}{}/'.format(basedir, validify_filename(name)) xbmcvfs.rename(old_folder, new_folder)
def move_dir(source, destination): xbmc.log( "contextMenu move_dir, source = " + source + " destination = " + destination, xbmc.LOGINFO) if not xbmcvfs.exists(source + "/"): xbmc.log( "ERROR: contextMenu move_dir, source = " + source + " does not exist!", xbmc.LOGERROR) return False if xbmcvfs.exists(destination + "/"): xbmc.log( "ERROR: contextMenu move_dir, destination = " + destination + " already exists!", xbmc.LOGERROR) return False if xbmcvfs.rename(source, destination) == True: return True if source.startswith('/') and destination.startswith('/'): try: shutil.move(source, destination) return True except Error as err: xbmc.log( "ERROR contextMenu move_dir, shutil.move, source = " + source + " destination = " + destination, xbmc.LOGERROR) return False return False
def _moveToThemeFolder(self, directory): log("moveToThemeFolder: path = %s" % directory) # Handle the case where we have a disk image if (os_path_split(directory)[1] == 'VIDEO_TS') or (os_path_split(directory)[1] == 'BDMV'): directory = os_path_split(directory)[0] dirs, files = list_dir(directory) for aFile in files: m = re.search(Settings.getThemeFileRegEx(directory), aFile, re.IGNORECASE) if m: srcpath = os_path_join(directory, aFile) log("fetchAllMissingThemes: Found match: %s" % srcpath) targetpath = os_path_join(directory, Settings.getThemeDirectory()) # Make sure the theme directory exists if not dir_exists(targetpath): try: xbmcvfs.mkdir(targetpath) except: log( "fetchAllMissingThemes: Failed to create directory: %s" % targetpath, True, LOGERROR) break else: log("moveToThemeFolder: directory already exists %s" % targetpath) # Add the filename to the path targetpath = os_path_join(targetpath, aFile) if not xbmcvfs.rename(srcpath, targetpath): log("moveToThemeFolder: Failed to move file from %s to %s" % (srcpath, targetpath))
def move_file(self, source, destination): """ Move a file to a new destination. Returns True if the move succeeded, False otherwise. Will create destination if it does not exist. Keyword arguments: source -- the source path (absolute) destination -- the destination path (absolute) """ self.debug("Moving %s to %s" % (os.path.basename(source), destination)) if xbmcvfs.exists(source): if not xbmcvfs.exists(destination): self.debug("XBMC could not find destination %s" % destination) self.debug("Creating destination %s" % destination) if xbmcvfs.mkdirs(destination): self.debug("Successfully created %s" % destination) else: self.debug("XBMC could not create destination %s" % destination) return False self.debug("Moving %s\nto %s\nNew path: %s" % (source, destination, os.path.join(destination, os.path.basename(source)))) return xbmcvfs.rename(source, os.path.join(destination, os.path.basename(source))) else: self.debug("XBMC could not find the file at %s" % source) return False
def _moveToThemeFolder(self, directory): log("moveToThemeFolder: path = %s" % directory) # Handle the case where we have a disk image if (os_path_split(directory)[1] == 'VIDEO_TS') or (os_path_split(directory)[1] == 'BDMV'): directory = os_path_split(directory)[0] dirs, files = list_dir(directory) for aFile in files: m = re.search(Settings.getThemeFileRegEx(directory), aFile, re.IGNORECASE) if m: srcpath = os_path_join(directory, aFile) log("fetchAllMissingThemes: Found match: %s" % srcpath) targetpath = os_path_join(directory, Settings.getThemeDirectory()) # Make sure the theme directory exists if not dir_exists(targetpath): try: xbmcvfs.mkdir(targetpath) except: log("fetchAllMissingThemes: Failed to create directory: %s" % targetpath, True, xbmc.LOGERROR) break else: log("moveToThemeFolder: directory already exists %s" % targetpath) # Add the filename to the path targetpath = os_path_join(targetpath, aFile) if not xbmcvfs.rename(srcpath, targetpath): log("moveToThemeFolder: Failed to move file from %s to %s" % (srcpath, targetpath))
def rename(path, newpath): FileAccess.log("rename " + path + " to " + newpath) try: if xbmcvfs.rename(path, newpath): return True except Exception,e: pass
def clean_related_files(self, source, dest_folder=None): """Clean files related to another file based on the user's preferences. Related files are files that only differ by extension, or that share a prefix in case of stacked movies. Examples of related files include NFO files, thumbnails, subtitles, fanart, etc. :type source: str :param source: Location of the file whose related files should be cleaned. :type dest_folder: str :param dest_folder: (Optional) The folder where related files should be moved to. Not needed when deleting. """ if get_setting(clean_related): debug("Cleaning related files.") path_list = self.unstack(source) path, name = os.path.split(path_list[0]) # Because stacked movies are in the same folder, only check one if source.startswith("stack://"): name = self.get_stack_bare_title(path_list) else: name, ext = os.path.splitext(name) debug("Attempting to match related files in %r with prefix %r" % (path, name)) for extra_file in xbmcvfs.listdir(path)[1]: if isinstance(path, unicode): path = path.encode("utf-8") if isinstance(extra_file, unicode): extra_file = extra_file.encode("utf-8") if isinstance(name, unicode): name = name.encode("utf-8") if extra_file.startswith(name): debug("%r starts with %r." % (extra_file, name)) extra_file_path = os.path.join(path, extra_file) if get_setting(cleaning_type) == self.CLEANING_TYPE_DELETE: if extra_file_path not in path_list: debug("Deleting %r." % extra_file_path) xbmcvfs.delete(extra_file_path) elif get_setting(cleaning_type) == self.CLEANING_TYPE_MOVE: new_extra_path = os.path.join(dest_folder, os.path.basename(extra_file)) if new_extra_path not in path_list: debug("Moving %r to %r." % (extra_file_path, new_extra_path)) xbmcvfs.rename(extra_file_path, new_extra_path) debug("Finished searching for related files.") else: debug("Cleaning of related files is disabled.")
def saveTorrent(self, torrentUrl): if re.match("^magnet\:.+$", torrentUrl): self.magnetLink = torrentUrl self.magnetToTorrent(torrentUrl) self.magnetLink = None return self.torrentFile else: if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) torrentFile = localize_path(os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent')) try: if not re.match("^[htps]+?://.+$|^://.+$", torrentUrl): log('xbmcvfs.File for %s' % torrentUrl) content = xbmcvfs.File(torrentUrl, "rb").read() else: log('request for %s' % torrentUrl) content = self.makeRequest(torrentUrl) localFile = xbmcvfs.File(torrentFile, "w+b") localFile.write(content) localFile.close() except Exception, e: log('Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str(e)) return if xbmcvfs.exists(torrentFile): try: e=self.lt.bdecode(xbmcvfs.File(torrentFile,'rb').read()) self.torrentFileInfo = self.lt.torrent_info(e) except Exception, e: log('Exception: ' + str(e)) xbmcvfs.delete(torrentFile) return if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) newFile = localize_path(self.torrentFilesPath + self.md5(torrentUrl) + '.torrent') if newFile != torrentFile: if xbmcvfs.exists(newFile): xbmcvfs.delete(newFile) if not xbmcvfs.exists(newFile): try: xbmcvfs.rename(torrentFile, newFile) except Exception, e: log('Unable to rename torrent file from %s to %s in Torrent::renameTorrent. Exception: %s' % (torrentFile, newFile, str(e))) return
def rename(src, dst): if not exists(src): return if isdir(src): copytree(src, dst) rmtree(src) return return xbmcvfs.rename(src, dst)
def download(url, destination, title, _wait=""): t1 = time.time() OK, dl_path = False, "" DIALOG_PROGRESS = xbmcgui.DialogProgress() try: DIALOG_PROGRESS.create(title) ext1 = os.path.splitext(destination)[1] if ext1: ext2 = "-trailer%s" % os.path.splitext(url)[1] destination = destination.replace(ext1, ext2) else: destination = destination + os.path.basename(url) try: destination = destination.decode("utf-8") except: pass download._wait = _wait = "Please wait[B].[/B]" def please_wait(): download._wait += "[B].[/B]" if download._wait.count(".") >= 4: download._wait = "Please wait[B].[/B]" def _report_hook(count, blocksize, totalsize, please_wait=None): if please_wait: please_wait() percent = int(float(count * blocksize * 100) / totalsize) DIALOG_PROGRESS.update(percent, "Downloading: %s " % url, "to: %s" % destination, download._wait) if DIALOG_PROGRESS.iscanceled(): raise IOError try: part = destination + ".part" hook = lambda c, b, t, please_wait=please_wait: _report_hook(c, b, t, please_wait) fp, h = urllib.urlretrieve(url, part, hook) try: print "%r" % fp print str(h).replace("\r", "") except: pass if xbmcvfs.exists(destination): xbmcvfs.delete(destination) OK = xbmcvfs.rename(part, destination) dl_path = destination except IOError: xbmcvfs.delete(destination) print "%r xbmcvfs.delete(%r)" % (not xbmcvfs.exists(destination), destination) except: print_exc() DIALOG_PROGRESS.close() print "[%s] Download took %s for trailer %r" % (ADDON_NAME, time_took(t1), dl_path) return OK and dl_path