public override void Execute(CancellationToken cancellationToken) { base.Execute(cancellationToken); Checks.FileExists(_packagePath); if (_versionDiffSummary.CompressionMethod == "pack1") { Assert.IsTrue(File.Exists(_packageMetaPath), "Compression method is pack1, but meta file does not exist"); DebugLogger.Log("Parsing package meta file"); _pack1Meta = Pack1Meta.ParseFromFile(_packageMetaPath); DebugLogger.Log("Package meta file parsed succesfully"); } DebugLogger.Log("Installing diff."); var packageDirPath = _temporaryData.GetUniquePath(); DebugLogger.LogVariable(packageDirPath, "packageDirPath"); DebugLogger.Log("Creating package directory."); DirectoryOperations.CreateDirectory(packageDirPath); try { DebugLogger.Log("Unarchiving files."); string usedSuffix; IUnarchiver unarchiver = CreateUnrachiver(packageDirPath, out usedSuffix); _unarchivePackageStatusReporter.OnProgressChanged(0.0, "Unarchiving package..."); unarchiver.UnarchiveProgressChanged += (name, isFile, entry, amount, entryProgress) => { var entryMinProgress = Mathf.Max(0, entry - 1) / (double)amount; // entry could be zero var entryMaxProgress = entry / (double)amount; var progress = entryMinProgress + (entryMaxProgress - entryMinProgress) * entryProgress; _unarchivePackageStatusReporter.OnProgressChanged(progress, "Unarchiving package..."); }; unarchiver.Unarchive(cancellationToken); _unarchivePackageStatusReporter.OnProgressChanged(1.0, string.Empty); ProcessAddedFiles(packageDirPath, usedSuffix, cancellationToken); ProcessRemovedFiles(cancellationToken); ProcessModifiedFiles(packageDirPath, usedSuffix, cancellationToken); DeleteEmptyMacAppDirectories(); } finally { DebugLogger.Log("Deleting package directory."); if (Directory.Exists(packageDirPath)) { DirectoryOperations.Delete(packageDirPath, true); } } }
private void AddFile(string fileName, string packageDirPath, string suffix, CancellationToken cancellationToken) { _logger.LogDebug(string.Format("Processing add file entry {0}", fileName)); var filePath = _localData.Path.PathCombine(fileName); _logger.LogTrace("filePath = " + filePath); var sourceFilePath = Path.Combine(packageDirPath, fileName + suffix); _logger.LogTrace("sourceFilePath = " + sourceFilePath); if (!File.Exists(sourceFilePath)) { throw new MissingFileFromPackageException(string.Format("Cannot find file {0} in diff package.", fileName)); } _logger.LogDebug("Creating file parent directories in local data..."); var fileParentDirPath = Path.GetDirectoryName(filePath); _logger.LogTrace("fileParentDirPath = " + fileParentDirPath); //TODO: Assert that fileParentDirPath is not null // ReSharper disable once AssignNullToNotNullAttribute DirectoryOperations.CreateDirectory(fileParentDirPath, cancellationToken); _logger.LogDebug("File parent directories created in local data."); _logger.LogDebug("Copying file to local data (overwriting if needed)..."); FileOperations.Copy(sourceFilePath, filePath, true, cancellationToken); _logger.LogDebug("File copied to local data."); _localMetaData.RegisterEntry(fileName, _versionId); _logger.LogDebug("Add file entry processed."); }
private void RemoveDir(string dirName, CancellationToken cancellationToken) { _logger.LogDebug(string.Format("Processing remove directory entry {0}", dirName)); string dirPath = _localData.Path.PathCombine(dirName); _logger.LogTrace("dirPath = " + dirPath); _logger.LogDebug("Deleting directory in local data. Checking whether it actually exists..."); if (Directory.Exists(dirPath)) { _logger.LogDebug("Directory exists. Checking whether directory is empty..."); if (IsDirectoryEmpty(dirPath)) { _logger.LogDebug("Directory is empty. Deleting it..."); DirectoryOperations.Delete(dirPath, cancellationToken); _logger.LogDebug("Directory deleted."); } else { _logger.LogDebug("Directory is not empty. Couldn't delete it."); } } _logger.LogDebug("Remove directory entry processed."); // TODO: Uncomment this after fixing directory registration in install content command //_localMetaData.UnregisterEntry(dirName); }
private void ReleaseUnmanagedResources() { if (!_keep && Directory.Exists(Path)) { DirectoryOperations.Delete(Path, CancellationToken.Empty, true); } }
private static string GenerateOrRead() { var filePath = GetFilePath(); if (File.Exists(filePath)) { string savedSenderId = File.ReadAllText(filePath); if (!string.IsNullOrEmpty(savedSenderId)) { UnityEngine.Debug.Log("SenderId: " + savedSenderId + " (loaded from " + filePath + ")"); return(savedSenderId); } } string senderId = Guid.NewGuid().ToString().Replace("-", ""); string parentDirPath = Path.GetDirectoryName(filePath); if (parentDirPath != null) { DirectoryOperations.CreateDirectory(parentDirPath, CancellationToken.Empty); } File.WriteAllText(filePath, senderId); UnityEngine.Debug.Log("SenderId: " + senderId + " (saved in " + filePath + ")"); return(senderId); }
private ChunkedFileStream OpenFileStream(CancellationToken cancellationToken) { var parentDirectory = Path.GetDirectoryName(_destinationFilePath); if (!string.IsNullOrEmpty(parentDirectory)) { DirectoryOperations.CreateDirectory(parentDirectory, cancellationToken); } var chunksRange = CalculateContainingChunksRange(_range); int startChunk = (int)(chunksRange.Start / _chunksData.ChunkSize); int endChunk = (int)_range.End; if (_range.End != -1) { endChunk = (int)(chunksRange.End / _chunksData.ChunkSize); if (chunksRange.End % _chunksData.ChunkSize != 0) { endChunk += 1; } } _logger.LogTrace(string.Format("Opening chunked file stream for chunks {0}-{1}", startChunk, endChunk)); return(new ChunkedFileStream(_destinationFilePath, _size, _chunksData, HashFunction, ChunkedFileStream.WorkFlags.PreservePreviousFile, startChunk, endChunk)); }
private void UnpackDirectory(Pack1Meta.FileEntry file, CancellationToken cancellationToken) { string destPath = Path.Combine(_destinationDirPath, file.Name); DebugLogger.Log("Creating directory " + destPath); DirectoryOperations.CreateDirectory(destPath, cancellationToken); DebugLogger.Log("Directory " + destPath + " created successfully!"); }
public static void CreateParents(string path) { var dirName = Path.GetDirectoryName(path); if (dirName != null) { DirectoryOperations.CreateDirectory(dirName, CancellationToken.Empty); } }
private void CreateDataDir() { string dirPath = Path.GetDirectoryName(_filePath); if (dirPath != null) { DirectoryOperations.CreateDirectory(dirPath, CancellationToken.Empty); } }
public void Clear() { DebugLogger.Log("Clearing download data."); if (Directory.Exists(Path)) { DirectoryOperations.Delete(Path, true); DirectoryOperations.CreateDirectory(Path); } }
public virtual void PrepareForWriting() { DebugLogger.Log("Preparing directory for writing."); DirectoryOperations.CreateDirectory(_path, CancellationToken.Empty); _hasWriteAccess = true; DebugLogger.Log("Directory prepared for writing."); }
private FileStream OpenFileStream(CancellationToken cancellationToken) { var parentDirectory = Path.GetDirectoryName(_destinationFilePath); if (!string.IsNullOrEmpty(parentDirectory)) { DirectoryOperations.CreateDirectory(parentDirectory, cancellationToken); } return(new FileStream(_destinationFilePath, FileMode.Create, FileAccess.Write, FileShare.None)); }
public virtual void PrepareForWriting() { DebugLogger.Log("Preparing directory for writing."); if (!_hasWriteAccess) { DebugLogger.Log("Creating directory."); DirectoryOperations.CreateDirectory(_path); _hasWriteAccess = true; } }
public override void Execute(CancellationToken cancellationToken) { base.Execute(cancellationToken); Checks.FileExists(_packagePath); if (_versionDiffSummary.CompressionMethod == "pack1") { Assert.IsTrue(File.Exists(_packageMetaPath), "Compression method is pack1, but meta file does not exist"); DebugLogger.Log("Parsing package meta file"); _pack1Meta = Pack1Meta.ParseFromFile(_packageMetaPath); DebugLogger.Log("Package meta file parsed succesfully"); } DebugLogger.Log("Installing diff."); var packageDirPath = _temporaryData.GetUniquePath(); DebugLogger.LogVariable(packageDirPath, "packageDirPath"); DebugLogger.Log("Creating package directory."); DirectoryOperations.CreateDirectory(packageDirPath); try { DebugLogger.Log("Unarchiving files."); IUnarchiver unarchiver = CreateUnrachiver(packageDirPath); unarchiver.UnarchiveProgressChanged += (name, isFile, entry, amount) => { _unarchivePackageStatusReporter.OnProgressChanged(entry / (double)amount); }; unarchiver.Unarchive(cancellationToken); _unarchivePackageStatusReporter.OnProgressChanged(1.0); ProcessAddedFiles(packageDirPath, cancellationToken); ProcessRemovedFiles(cancellationToken); ProcessModifiedFiles(packageDirPath, cancellationToken); } finally { DebugLogger.Log("Deleting package directory."); if (Directory.Exists(packageDirPath)) { DirectoryOperations.Delete(packageDirPath, true); } } }
private void AddDirectory(string dirName, CancellationToken cancellationToken) { _logger.LogDebug(string.Format("Processing add directory entry {0}", dirName)); var dirPath = _localData.Path.PathCombine(dirName); _logger.LogTrace("dirPath = " + dirPath); _logger.LogDebug("Creating directory in local data..."); DirectoryOperations.CreateDirectory(dirPath, cancellationToken); _logger.LogDebug("Directory created."); _logger.LogDebug("Add directory entry processed."); }
private void DeleteOldTmpDirectories() { DebugLogger.Log("TemporaryDirectory: ParentFullName: " + Directory.GetParent(Path).FullName); DirectoryInfo[] tmpDirs = Directory.GetParent(Path).GetDirectories(_prefix + "*"); for (int i = 0; i < tmpDirs.Length; i++) { if (tmpDirs[i].CreationTime < _createdAt) { DebugLogger.LogFormat("TemporaryDirectory: Deleting old tmp directory[{0}/{1}]: {2}", (i + 1), tmpDirs.Length, tmpDirs[i].FullName); DirectoryOperations.Delete(tmpDirs[i].FullName, true); } } }
private void ProcessRemovedFiles(CancellationToken cancellationToken) { DebugLogger.Log("Processing removed files."); var files = _versionDiffSummary.RemovedFiles.Where(s => !s.EndsWith("/")); var directories = _versionDiffSummary.RemovedFiles.Where(s => s.EndsWith("/")); int counter = 0; _removeFilesStatusReporter.OnProgressChanged(0.0, "Installing package..."); foreach (var fileName in files) { cancellationToken.ThrowIfCancellationRequested(); string filePath = _localData.Path.PathCombine(fileName); if (File.Exists(filePath)) { FileOperations.Delete(filePath); } _localMetaData.UnregisterEntry(fileName); counter++; _removeFilesStatusReporter.OnProgressChanged(counter / (double)_versionDiffSummary.RemovedFiles.Length, "Installing package..."); } foreach (var dirName in directories) { cancellationToken.ThrowIfCancellationRequested(); string dirPath = _localData.Path.PathCombine(dirName); if (Directory.Exists(dirPath) && DirectoryOperations.IsDirectoryEmpty(dirPath)) { DirectoryOperations.Delete(dirPath, false); } // TODO: Uncomment this after fixing directory registration in install content command //_localMetaData.UnregisterEntry(dirName); counter++; _removeFilesStatusReporter.OnProgressChanged(counter / (double)_versionDiffSummary.RemovedFiles.Length, "Installing package..."); } _removeFilesStatusReporter.OnProgressChanged(1.0, string.Empty); }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } DebugLogger.LogDispose(); if (Directory.Exists(Path)) { DirectoryOperations.Delete(Path, true); } _disposed = true; }
private TemporaryDirectory([NotNull] string path) { if (string.IsNullOrEmpty(path)) { throw new ArgumentException("Value cannot be null or empty.", "path"); } Path = path; if (Directory.Exists(Path)) { DirectoryOperations.Delete(Path, CancellationToken.Empty, true); } DirectoryOperations.CreateDirectory(Path, CancellationToken.Empty); }
// TODO: Temporary solution for situation when .app directory is not deleted private void DeleteEmptyMacAppDirectories(CancellationToken cancellationToken) { if (!Platform.IsOSX()) { return; } _logger.LogDebug("Deleting empty Mac OSX '.app' directories..."); foreach (var dir in FindEmptyMacAppDirectories()) { _logger.LogDebug(string.Format("Deleting {0}", dir)); DirectoryOperations.Delete(dir, cancellationToken, true); _logger.LogDebug("Directory deleted."); } _logger.LogDebug("Empty Mac OSX '.app' directories deleted."); }
private void EmplaceFile(string source, string target, CancellationToken cancellationToken) { _logger.LogDebug(string.Format("Installing file {0} into {1}", source, target)); if (!File.Exists(source)) { throw new Exception(string.Format("Source file {0} doesn't exist.", source)); } DirectoryOperations.CreateParentDirectory(target, cancellationToken); if (File.Exists(target)) { FileOperations.Delete(target, cancellationToken); } FileOperations.Move(source, target, cancellationToken); }
private void ProcessAddedFiles(string packageDirPath, string suffix, CancellationToken cancellationToken) { DebugLogger.Log("Processing added files."); _addFilesStatusReporter.OnProgressChanged(0.0, "Installing package..."); for (int i = 0; i < _versionDiffSummary.AddedFiles.Length; i++) { cancellationToken.ThrowIfCancellationRequested(); var entryName = _versionDiffSummary.AddedFiles[i]; string entryPath = _localData.Path.PathCombine(entryName); if (entryName.EndsWith("/")) { DirectoryOperations.CreateDirectory(entryPath); // TODO: Uncomment this after fixing directory registration in install content command //_localMetaData.RegisterEntry(entryName, _versionId); } else { string sourceFilePath = Path.Combine(packageDirPath, entryName + suffix); if (!File.Exists(sourceFilePath)) { throw new InstallerException(string.Format("Cannot find file <{0}> in content package.", entryName)); } DebugLogger.LogFormat("Copying {0} -> {1}", sourceFilePath, entryName); DirectoryOperations.CreateParentDirectory(entryPath); FileOperations.Copy(sourceFilePath, entryPath, true); _localMetaData.RegisterEntry(entryName, _versionId); } _addFilesStatusReporter.OnProgressChanged((i + 1) / (double)_versionDiffSummary.AddedFiles.Length, "Installing package..."); } _addFilesStatusReporter.OnProgressChanged(1.0, "Installing package..."); }
protected virtual void Dispose(bool disposing) { if (_disposed) { return; } DebugLogger.Log("TemporaryDirectory: Deleting: " + Path); if (Directory.Exists(Path)) { DirectoryOperations.Delete(Path, true); } DeleteOldTmpDirectories(); DebugLogger.LogDispose(); _disposed = true; }
private void InstallFile(SourceFile sourceFile, CancellationToken cancellationToken) { DebugLogger.Log(string.Format("Installing file {0}", sourceFile.Name)); if (!sourceFile.Exists()) { throw new InstallerException(string.Format("Cannot find file {0} in content package.", sourceFile.Name)); } string destinationFilePath = _localData.Path.PathCombine(sourceFile.Name); DirectoryOperations.CreateParentDirectory(destinationFilePath, cancellationToken); if (File.Exists(destinationFilePath)) { DebugLogger.LogFormat("Destination file {0} already exists, removing it.", destinationFilePath); FileOperations.Delete(destinationFilePath, cancellationToken); } FileOperations.Move(sourceFile.FullPath, destinationFilePath, cancellationToken); _localMetaData.RegisterEntry(sourceFile.Name, _versionId); }
private void Cleanup() { DebugLogger.Log("Cleaning up..."); if (Directory.Exists(DownloadDirectoryPath)) { SafeInvoker.Invoke(() => DirectoryOperations.Delete(DownloadDirectoryPath, true), null, _ => { DebugLogger.LogWarning("Unable to cleanup torrent download directory."); }); } if (File.Exists(TorrentFilePath)) { SafeInvoker.Invoke(() => FileOperations.Delete(TorrentFilePath), null, _ => { DebugLogger.LogWarning("Unable to cleanup torrent file."); }); } DebugLogger.Log("Cleanup completed."); }
// TODO: Temporary solution for situation when .app directory is not deleted private void DeleteEmptyMacAppDirectories() { if (Platform.IsOSX()) { DebugLogger.Log("Deleting empty Mac OSX '.app' directories..."); var appDirectories = Directory .GetFileSystemEntries(_localData.Path) .Where(s => Directory.Exists(s) && s.EndsWith(".app") && Directory.GetFiles(s, "*", SearchOption.AllDirectories).Length == 0); foreach (var dir in appDirectories) { if (Directory.Exists(dir)) { DirectoryOperations.Delete(dir, true); } } DebugLogger.Log("Empty Mac OSX '.app' directories has been deleted."); } }
private void InstallFile(string fileName, string packageDirPath, string suffix) { DebugLogger.Log(string.Format("Installing file {0}", fileName + suffix)); string sourceFilePath = Path.Combine(packageDirPath, fileName + suffix); if (!File.Exists(sourceFilePath)) { throw new InstallerException(string.Format("Cannot find file {0} in content package.", fileName)); } string destinationFilePath = _localData.Path.PathCombine(fileName); DirectoryOperations.CreateParentDirectory(destinationFilePath); if (File.Exists(destinationFilePath)) { DebugLogger.LogFormat("Destination file {0} already exists, removing it.", destinationFilePath); FileOperations.Delete(destinationFilePath); } FileOperations.Move(sourceFilePath, destinationFilePath); _localMetaData.RegisterEntry(fileName, _versionId); }
public override void Execute(CancellationToken cancellationToken) { base.Execute(cancellationToken); foreach (var entry in _entries) { var tempDirName = _packagePath + string.Format("{0}_{1}_{2}", entry.Name, entry.Offset, entry.Size); TemporaryDirectory.ExecuteIn(tempDirName, (tempDir) => { _logger.LogDebug(string.Format("Repairing the file {0}", entry.Name)); string packagePath = Path.Combine(tempDir.Path, ".pack" + Path.GetRandomFileName()); string unarchivePath = Path.Combine(tempDir.Path, Path.GetRandomFileName()); if (!Directory.Exists(unarchivePath)) { DirectoryOperations.CreateDirectory(unarchivePath, cancellationToken); } var downloader = new ChunkedHttpDownloader(packagePath, _resource.ResourceUrls, _resource.ChunksData, _resource.Size); long start = entry.Offset.GetValueOrDefault(); long end = (start + entry.Size.GetValueOrDefault()) - 1; // Offset by 1 to denote a byte index var range = new BytesRange(start, end); downloader.SetRange(range); var effectiveRange = downloader.CalculateContainingChunksRange(range); long totalData = effectiveRange.End == -1 ? _resource.Size - effectiveRange.Start : effectiveRange.End - effectiveRange.Start; var downloadStatus = _entryStatus[entry].DownloadStatus; var repairStatus = _entryStatus[entry].RepairStatus; downloadStatus.IsActive.Value = true; downloadStatus.TotalBytes.Value = totalData; downloadStatus.Description.Value = "Downloading broken file..."; downloadStatus.Bytes.Value = 0; downloader.DownloadProgressChanged += downloadedBytes => { downloadStatus.Bytes.Value = downloadedBytes; }; _logger.LogDebug(string.Format("Downloading the partial package with range {0}-{1}", start, end)); downloader.Download(cancellationToken); downloadStatus.IsActive.Value = false; repairStatus.IsActive.Value = true; repairStatus.Description.Value = "Reparing broken file..."; repairStatus.Progress.Value = 0.0; _logger.LogDebug("Unarchiving the package."); var unarchiver = new Pack1Unarchiver(packagePath, _meta, unarchivePath, _packagePassword, _unpackingSuffix, effectiveRange); unarchiver.UnarchiveProgressChanged += (name, isFile, unarchiveEntry, amount, entryProgress) => { repairStatus.Progress.Value = entryProgress; }; unarchiver.UnarchiveSingleFile(entry, cancellationToken); EmplaceFile(Path.Combine(unarchivePath, entry.Name + _unpackingSuffix), Path.Combine(_localData.Path, entry.Name), cancellationToken); repairStatus.IsActive.Value = false; }); } }
public override void Execute(CancellationToken cancellationToken) { base.Execute(cancellationToken); DebugLogger.Log("Uninstalling."); var entries = _localMetaData.GetRegisteredEntries(); var files = entries.Where(s => !s.EndsWith("/")).ToArray(); // TODO: Uncomment this after fixing directory registration in install content command //var directories = entries.Where(s => s.EndsWith("/")); int counter = 0; foreach (var fileName in files) { cancellationToken.ThrowIfCancellationRequested(); var filePath = _localData.Path.PathCombine(fileName); if (File.Exists(filePath)) { FileOperations.Delete(filePath); } _localMetaData.UnregisterEntry(fileName); counter++; _statusReporter.OnProgressChanged(counter / (double)entries.Length); } // TODO: Delete this after fixing directory registration in install content command // Temporary solution for deleting directories during uninstallation. foreach (var fileName in files) { cancellationToken.ThrowIfCancellationRequested(); string parentDirName = fileName; do { parentDirName = Path.GetDirectoryName(parentDirName); var parentDirPath = _localData.Path.PathCombine(parentDirName); if (Directory.Exists(parentDirPath)) { if (DirectoryOperations.IsDirectoryEmpty(parentDirPath)) { DirectoryOperations.Delete(parentDirPath, false); } else { break; } } } while (parentDirName != null); } // TODO: Uncomment this after fixing directory registration in install content command /* * foreach (var dirName in directories) * { * cancellationToken.ThrowIfCancellationRequested(); * * var dirPath = _localData.Path.PathCombine(dirName); * * if (Directory.Exists(dirPath) && DirectoryOperations.IsDirectoryEmpty(dirPath)) * { * DirectoryOperations.Delete(dirPath, false); * } * * _localMetaData.UnregisterEntry(dirName); * * counter++; * _statusReporter.OnProgressChanged(counter / (double)entries.Length); * }*/ }
public override void Execute(CancellationToken cancellationToken) { base.Execute(cancellationToken); Checks.FileExists(_packagePath); Assert.IsTrue(_localMetaData.GetRegisteredEntries().Length == 0, "Cannot install content if previous version is still present."); if (_versionContentSummary.CompressionMethod == "pack1") { Assert.IsTrue(File.Exists(_packageMetaPath), "Compression method is pack1, but meta file does not exist"); DebugLogger.Log("Parsing package meta file"); _pack1Meta = Pack1Meta.ParseFromFile(_packageMetaPath); DebugLogger.Log("Package meta file parsed succesfully"); } DebugLogger.Log("Installing content."); var packageDirPath = _temporaryData.GetUniquePath(); DebugLogger.LogVariable(packageDirPath, "destinationDir"); DebugLogger.Log("Creating package directory."); DirectoryOperations.CreateDirectory(packageDirPath); try { DebugLogger.Log("Unarchiving package."); IUnarchiver unarchiver = CreateUnrachiver(packageDirPath); unarchiver.UnarchiveProgressChanged += (name, isFile, entry, amount) => { _unarchivePackageStatusReporter.OnProgressChanged(entry / (double)amount); }; unarchiver.Unarchive(cancellationToken); _unarchivePackageStatusReporter.OnProgressChanged(1.0); DebugLogger.Log("Copying files."); for (int i = 0; i < _versionContentSummary.Files.Length; i++) { cancellationToken.ThrowIfCancellationRequested(); InstallFile(_versionContentSummary.Files[i].Path, packageDirPath); _copyFilesStatusReporter.OnProgressChanged((i + 1) / (double)_versionContentSummary.Files.Length); } _copyFilesStatusReporter.OnProgressChanged(1.0); } finally { DebugLogger.Log("Deleting package directory."); if (Directory.Exists(packageDirPath)) { DirectoryOperations.Delete(packageDirPath, true); } } }