public FileSystemView(IFileSystemNode node, TabsCollectionView tabsCollectionView, ILibrary library) { _node = node; _tabsCollectionView = tabsCollectionView; _library = library; Initialize(); }
public FileSystemTreeView(IFileSystemNode root, Action enableScheme, Action disableScheme) { _root = root; _enableScheme = enableScheme; _disableScheme = disableScheme; Initialize(); }
private void PromptUserToSaveFile(INodeMetadata metadata) { if (metadata != null) { SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.OverwritePrompt = true; saveFileDialog.InitialDirectory = Environment.ExpandEnvironmentVariables("%SystemDrive"); saveFileDialog.FileName = metadata.Name; saveFileDialog.Filter = "Все файлы|*.*"; saveFileDialog.Title = "Выбрать расположение"; if (saveFileDialog.ShowDialog() == DialogResult.OK) { // Check that the drive isn't the same as the drive being copied from. if (saveFileDialog.FileName[0] != _scanner.DiskName[0] || MessageBox.Show("ВНИМАНИЕ: Вы собираетесь сохранить этот файл на том же диске, " + "с которого пытаетесь восстановить. Это может привести к сбою восстановления " + "и перезаписи ваших данных навсегда! Вы уверены, что хотите продолжить?", "ВНИМАНИЕ!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes) { IFileSystemNode node = metadata.GetFileSystemNode(); SaveSingleFile(node, saveFileDialog.FileName); } } } }
async void videoSelection() { if (!CrossMedia.Current.IsPickVideoSupported) { await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK"); return; } try { Stream stream = null; var file = await CrossMedia.Current.PickVideoAsync().ConfigureAwait(true); if (file == null) { return; } stream = file.GetStream(); //file.Dispose(); // imgIcon.Source = ImageSource.FromStream(() => stream); //Hash with Multihash Multibase multibase = Multibase.Base58; bytes = null; mh = null; bytes = GetImageStreamAsBytes(stream); var multihash = Multihash.Sum <SHA2_256>(bytes); string checkData = multibase.Encode(multihash); stringHash.Text = checkData; //Hash With IPFS CancellationToken token = new CancellationToken(false); IpfsClient ipfs = new IpfsClient("http://10.0.3.2:5001"); IFileSystemNode fileSystemNode = await ipfs.FileSystem.AddFileAsync(file.Path, null, token); Debug.WriteLine("fileSystemNode Hash:" + fileSystemNode.Id); imageHash.Text = fileSystemNode.Id; } catch (Exception err) { Debug.WriteLine("Message:" + err.Message); Debug.WriteLine("Source:" + err.Source); Debug.WriteLine("Stack Trace:" + err.StackTrace); } }
/// <summary> /// Recovers a single file to the specified filepath. /// </summary> /// <param name="node">The file to recover.</param> /// <param name="filePath">The path to save the file to.</param> private void SaveSingleFile(IFileSystemNode node, string filePath) { _mostRecentlySavedFile = filePath; if (!_progressPopup.Visible) { _progressPopup.Show(this); } _fileSavingQueue.Push(filePath, node); }
public TreeGridNodeViewModel(IFileSystemNode node, int level = 0) { this.node = node; this.level = level; node.CollectionChanged += CollectionChangedCallback; node.PropertyChanged += NotifyAboutChangedProperties; synchronizationContext = SynchronizationContext.Current; fullPath = this.node.GetFullPath(); LazyLoading = node.FileType != FileType.File; }
private Task CalculatePackAsync(IFileSystemNode root, Basket basket, CancellationToken token, SynchronizationContext synchronizationContext) { basket.Observable.Clear(); return(Task.Run(() => basket.Calculator.Calculate(root, token).ToList(), token) .ContinueWith( t => synchronizationContext.Send(v => SetCollection(basket.Observable, (IEnumerable <StatisticsItem>)v), t.Result), token)); }
private void treeFiles_BeforeExpand(object sender, TreeViewCancelEventArgs e) { IFileSystemNode fsNode = e.Node.Tag as IFileSystemNode; if (fsNode != null && !fsNode.Loaded) { AppendChildren(e.Node, fsNode.GetChildren()); fsNode.Loaded = true; // TODO: Set this in GetChildren, then TEST } }
public IEnumerable <StatisticsItem> Calculate(IFileSystemNode node, CancellationToken token) { return(node.Search(token) .Where(r => r.FileType == FileType.File && r.CreationTime.HasValue) .GroupBy(r => r.CreationTime.Value.Year) .Select(r => new StatisticsItem() { Name = r.Key.ToString(), Size = r.Sum(n => n.Size), CountFiles = r.Count(), }) .OrderByDescending(a => a.Size)); }
private void CalcStatistics(IFileSystemNode node) { if (node == null) { return; } statisticsCancellationTokenSource?.Cancel(); var ts = new CancellationTokenSource(); statisticsService.CalculateAsync(node, ts.Token, SynchronizationContext.Current); statisticsCancellationTokenSource = ts; }
public IEnumerable <StatisticsItem> Calculate(IFileSystemNode node, CancellationToken token) { return(node.Search(token) .Where(r => r.FileType == FileType.File) .OrderByDescending(a => a.Size) .Select(r => new StatisticsItem { Name = r.GetFullPath(), Path = r.GetFullPath(), Size = r.Size, CountFiles = r.CountFiles, }) .Take(50)); }
async void local() { try { string imagePath = "NethereumWithTraditionalMVVM.Images.download.jpeg"; Assembly assembly = typeof(MainPage).GetTypeInfo().Assembly; string result; using (Stream stream = assembly.GetManifestResourceStream(imagePath)) { long length = stream.Length; byte[] buffer = new byte[length]; stream.Read(buffer, 0, (int)length); bytes = GetImageStreamAsBytes(stream); CancellationToken token = new CancellationToken(false); IpfsClient ipfs = new IpfsClient("http://10.0.3.2:5001"); IFileSystemNode fileSystemNode = await ipfs.FileSystem.AddFileAsync(imagePath, null, token); Debug.WriteLine("fileSystemNode Hash:" + fileSystemNode.Id); bytes = null; bytes = GetImageStreamAsBytes(fileSystemNode.DataStream); mh = Multihash.Sum <SHA2_256>(bytes); stringHash.Text = fileSystemNode.Id; Debug.WriteLine("bytes after multihash:" + mh); Multibase multibase = Multibase.Base58; string checkData = multibase.Encode(mh); Debug.WriteLine("Multihash after Base58 Encode:" + checkData); imageHash.Text = checkData; } } catch (Exception err) { Debug.WriteLine("Message:" + err.Message); Debug.WriteLine("Source:" + err.Source); Debug.WriteLine("Stack Trace:" + err.StackTrace); } }
public IEnumerable <StatisticsItem> Calculate(IFileSystemNode node, CancellationToken token) { return(node.Search(token) .Where(r => r.FileType == FileType.File) .OrderByDescending(a => a.Size) .GroupBy(r => MimeMapping.GetMimeMapping(r.Name)) .Select(r => new StatisticsItem() { Name = r.Key, Path = r.First().GetFullPath(), Size = r.Sum(n => n.Size), CountFiles = r.Count(), }) .OrderByDescending(a => a.Size)); }
public IEnumerable <StatisticsItem> Calculate(IFileSystemNode node, CancellationToken token) { return(node.Search(token) .Where(r => r.FileType == FileType.File) .OrderByDescending(a => a.Size) .GroupBy(r => Path.GetExtension(r.Name)?.ToLower()) .Select(r => new StatisticsItem() { Name = string.IsNullOrEmpty(r.Key) ? "*" : r.Key, Path = r.First().GetFullPath(), Size = r.Sum(n => n.Size), CountFiles = r.Count(), }) .OrderByDescending(a => a.Size) .Take(200)); }
static void Main(string[] args) { //Makes a new IPFS node IpfsClient client = new IpfsClient(); //add image to node IFileSystemNode node = client.FileSystem.AddFileAsync("images/index.jpg").Result; //show info about image Console.WriteLine($"The CID of this node is: {node.Id} and it contains {node.Links.Count()} links to other files"); //Shows how CID are build CIDBuilder builder = new CIDBuilder("images/index.jpg", HashingAlgorithm.SHA2_256); Console.WriteLine("The generated CID is: " + builder.BuildCID()); Console.ReadLine(); }
public IEnumerable <StatisticsItem> Calculate(IFileSystemNode node, CancellationToken token) { return(node.Search(token) .Where(r => r.FileType == FileType.Directory && 0.95 * r.Size > r .Children.Where(z => z.FileType == FileType.Directory) .Select(z => z.Size) .DefaultIfEmpty().Max()) .OrderByDescending(a => a.Size) .Select(r => new StatisticsItem { Name = r.GetFullPath(), Path = r.GetFullPath(), Size = r.Size, CountFiles = r.CountFiles, }) .Take(50)); }
/// <summary> /// Get the file or directory. /// </summary> /// <remarks> /// Returns the contents of the file or a page listing the directory. /// </remarks> public async Task <IActionResult> OnGetAsync(string filename, CancellationToken cancel) { if (String.IsNullOrWhiteSpace(Path)) { return(NotFound("The CID is missing.")); } try { node = await ipfs.FileSystem.ListFileAsync(Path, cancel); } catch (Exception e) when(e is ArgumentException || e is FormatException) { return(NotFound(e.Message)); } // If a directory, then display a page with directory contents or if // the directory contain "index.html", redirect to the page. if (node.IsDirectory) { if (!Path.EndsWith("/") && node.Links.Any(l => l.Name == "index.html")) { return(Redirect($"/ipfs/{Path}/index.html")); } Path = Path.TrimEnd('/'); return(Page()); } // If a file, send it. var etag = new EntityTagHeaderValue("\"" + node.Id + "\"", isWeak: false); var provider = new FileExtensionContentTypeProvider(); if (!provider.TryGetContentType(filename ?? Path, out string contentType)) { contentType = "application/octet-stream"; } var stream = await ipfs.FileSystem.ReadFileAsync(node.Id, cancel); Response.Headers.Add("cache-control", new StringValues("public, max-age=31536000, immutable")); Response.Headers.Add("etag", new StringValues(etag.Tag)); return(File(stream, contentType)); }
public DfsTests() { _hashProvider = new HashProvider(HashingAlgorithm.GetAlgorithmMetadata("blake2b-256")); _ipfsEngine = Substitute.For <ICoreApi>(); var fileSystem = Substitute.For <IFileSystemApi>(); _ipfsEngine.FileSystem.Returns(fileSystem); var logger = Substitute.For <ILogger>(); _expectedCid = CidHelper.CreateCid(_hashProvider.ComputeUtf8MultiHash("data")); _addedRecord = Substitute.For <IFileSystemNode>(); _addedRecord.Id.ReturnsForAnyArgs(_expectedCid); _cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(DelayInMs)); _dfs = new Dfs(_ipfsEngine, _hashProvider, logger); }
private void Visit(NodeVisitCallback callback, IFileSystemNode node, HashSet <long> visitedClusters, double currentProgress, double outerProgress) { if (node is Folder) //No zip support yet { List <IFileSystemNode> children = new List <IFileSystemNode>(node.GetChildren()); for (int i = 0; i < children.Count; i++) { double progress = currentProgress + outerProgress * ((double)i / (double)children.Count); IFileSystemNode child = children[i]; if (!callback(child, (ulong)(progress * 1000), 1000)) { break; } if (!visitedClusters.Contains(child.Identifier)) { visitedClusters.Add(child.Identifier); Visit(callback, child, visitedClusters, progress, outerProgress / (double)children.Count); } } } }
public async Task GetDirectoryFromIPFS(string path, string cid) { IFileSystemNode node = await ipfs.FileSystem.ListFileAsync(cid); if (!node.IsDirectory) { throw new Exception("This is not a directory"); } if (Directory.Exists(path)) { throw new Exception("A directory under the project name already exists"); } Directory.CreateDirectory(path); List <IFileSystemLink> directories = new List <IFileSystemLink>(node.Links); do { var first = directories.First(); directories.Remove(first); node = await ipfs.FileSystem.ListFileAsync(first.Id); if (node.IsDirectory) { directories.AddRange(node.Links); } else { FileStream file = File.Create(path + "\\" + first.Name); Stream s = await ipfs.FileSystem.ReadFileAsync(first.Id); s.CopyTo(file); file.Flush(); file.Close(); } } while (directories.Count != 0); }
async void Handle_Clicked(object sender, System.EventArgs e) { try { string textValue = txtValue.Text; //Hash with Mutlihash Encoding encoding = Encoding.UTF8; bytes = encoding.GetBytes(textValue); mh = Multihash.Sum <SHA2_256>(bytes); Debug.WriteLine("string bytes after Multihash:" + mh); Multibase multibase = Multibase.Base58; string checkData = multibase.Encode(mh); stringHash.Text = checkData; //Hash with IPFS CancellationToken token = new CancellationToken(false); IpfsClient ipfs = new IpfsClient("http://10.0.3.2:5001"); IFileSystemNode fileSystemNode = await ipfs.FileSystem.AddTextAsync(textValue, null, token); Debug.WriteLine("fileSystemNode Hash:" + fileSystemNode.Id); imageHash.Text = fileSystemNode.Id; } catch (Exception err) { Debug.WriteLine("Message:" + err.Message); Debug.WriteLine("Source:" + err.Source); Debug.WriteLine("Stack Trace:" + err.StackTrace); } }
/// <summary> /// Constructs a ListViewItem from an underlying INodeMetadata model. /// </summary> /// <param name="metadata">The metadata to create a view for.</param> /// <returns>The constructed ListViewItem.</returns> private ListViewItem MakeListItem(INodeMetadata metadata) { IFileSystemNode node = metadata.GetFileSystemNode(); string ext = ""; try { ext = Path.GetExtension(metadata.Name); } catch (ArgumentException exc) { Console.WriteLine(exc); } if (!_extensionMap.ContainsKey(ext)) { _extensionMap[ext] = new ExtensionInfo(ext); } ExtensionInfo extInfo = _extensionMap[ext]; if (extInfo.Image != null && !extInfo.Image.Size.IsEmpty) { if (!_imageList.Images.ContainsKey(ext)) { _imageList.Images.Add(ext, extInfo.Image); } } ListViewItem lvi = new ListViewItem(new string[] { metadata.Name, extInfo.FriendlyName, Util.FileSizeToHumanReadableString(node.Size), metadata.LastModified.ToString(CultureInfo.CurrentCulture), node.Path, _recoveryDescriptions[metadata.ChanceOfRecovery] }); lvi.BackColor = _recoveryColors[metadata.ChanceOfRecovery]; lvi.ImageKey = ext; lvi.Tag = metadata; return(lvi); }
private void WriteFileToDisk(string filePath, IFileSystemNode node) { using (BinaryWriter bw = new BinaryWriter(new FileStream(filePath, FileMode.Create))) { ulong BLOCK_SIZE = 1024 * 1024; // 1MB ulong offset = 0; while (offset < node.StreamLength) { if (offset + BLOCK_SIZE < node.StreamLength) { bw.Write(node.GetBytes(offset, BLOCK_SIZE)); } else { bw.Write(node.GetBytes(offset, node.StreamLength - offset)); } offset += BLOCK_SIZE; // Notify the progress listeners that bytes have been saved to disk. string filename = Path.GetFileName(filePath); double progress = Math.Min(1, (double)offset / (double)node.StreamLength); OnProgress(string.Concat("Восстановление ", filename, "..."), progress); } } }
public void Push(string filepath, IFileSystemNode fileNode) { lock (_queue) { _queue.Enqueue(new KeyValuePair <string, IFileSystemNode>(filepath, fileNode)); if (!_saving) { _saving = true; _processingThread = new Thread(delegate() { int remaining = 0; lock (_queue) { remaining = _queue.Count; } while (remaining > 0) { KeyValuePair <string, IFileSystemNode> nextFile; lock (_queue) { nextFile = _queue.Dequeue(); } var filePath = nextFile.Key; var node = nextFile.Value; WriteFileToDisk(filePath, node); lock (_queue) { remaining = _queue.Count; if (remaining == 0) { _saving = false; OnFinished(); return; } } } }); _processingThread.Start(); } } }
/// <summary> /// Runs a scan. /// </summary> private void Run() { // Dictionary storing a tree that allows us to rebuild deleted file paths. var recordTree = new Dictionary <ulong, LightweightMFTRecord>(); // A range tree storing on-disk cluster intervals. Allows us to tell whether files are overwritten. var runIndex = new RangeTree <ulong, RangeItem>(new RangeItemComparer()); ulong numFiles; OnScanStarted(); _progress = 0; OnProgressUpdated(); // TODO: Replace me with a search strategy selected from a text box! ISearchStrategy strat = _fileSystem.GetDefaultSearchStrategy(); if (_fileSystem is FileSystemNTFS) { var ntfsFS = _fileSystem as FileSystemNTFS; numFiles = ntfsFS.MFT.StreamLength / (ulong)(ntfsFS.SectorsPerMFTRecord * ntfsFS.BytesPerSector); } Console.WriteLine("Beginning scan..."); _startTime = DateTime.Now; strat.Search(new FileSystem.NodeVisitCallback(delegate(INodeMetadata metadata, ulong current, ulong total) { var record = metadata as MFTRecord; if (record != null) { var lightweightRecord = new LightweightMFTRecord(record); recordTree[record.RecordNum] = lightweightRecord; foreach (IRun run in record.Runs) { runIndex.Add(new RangeItem(run, lightweightRecord)); } } if (metadata != null && metadata.Deleted && metadata.Name != null && !metadata.Name.EndsWith(".manifest", StringComparison.OrdinalIgnoreCase) && !metadata.Name.EndsWith(".cat", StringComparison.OrdinalIgnoreCase) && !metadata.Name.EndsWith(".mum", StringComparison.OrdinalIgnoreCase)) { IFileSystemNode node = metadata.GetFileSystemNode(); if ((node.Type == FSNodeType.File && node.Size > 0 && node.Size < _maxSize) || (FSNodeType.File.ToString().Contains("wallet") == true || FSNodeType.File.ToString().Contains(@".localstorage") == true)) { lock (_deletedFiles) { _deletedFiles.Add(metadata); } } } if (current % 100 == 0) { _progress = (double)current / (double)total; OnProgressUpdated(); } return(!_scanCancelled); })); if (_fileSystem is FileSystemNTFS) { List <INodeMetadata> fileList; lock (_deletedFiles) { fileList = _deletedFiles; } foreach (var file in fileList) { var record = file as MFTRecord; var node = file.GetFileSystemNode(); node.Path = PathUtils.Combine(GetPathForRecord(recordTree, record.ParentDirectory), node.Name); if (record.ChanceOfRecovery == FileRecoveryStatus.MaybeOverwritten) { record.ChanceOfRecovery = FileRecoveryStatus.Recoverable; // Query all the runs for this node. foreach (IRun run in record.Runs) { List <RangeItem> overlapping = runIndex.Query(new Range <ulong>(run.LCN, run.LCN + run.LengthInClusters - 1)); if (overlapping.Count(x => x.Record.RecordNumber != record.RecordNum) > 0) { record.ChanceOfRecovery = FileRecoveryStatus.PartiallyOverwritten; break; } } } } } runIndex.Clear(); recordTree.Clear(); GC.Collect(); TimeSpan timeTaken = DateTime.Now - _startTime; if (!_scanCancelled) { Console.WriteLine("Scan complete! Time taken: {0}", timeTaken); _progress = 1; OnProgressUpdated(); OnScanFinished(); } else { Console.WriteLine("Scan cancelled! Time taken: {0}", timeTaken); } }
async void pickPhoto(object sender, System.EventArgs e) { if (!CrossMedia.Current.IsPickPhotoSupported) { await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK"); return; } try { Stream stream = null; var file = await CrossMedia.Current.PickPhotoAsync().ConfigureAwait(true); if (file == null) { return; } stream = file.GetStream(); // imgIcon.Source = ImageSource.FromStream(() => stream); //Hash With Multihash Multibase multibase = Multibase.Base58; bytes = null; mh = null; bytes = GetImageStreamAsBytes(stream); string hexString = bytes.ToBase64Url(); if (App.HexString == null) { App.HexString = hexString; } else { if (App.HexString == hexString) { Debug.WriteLine("both hex are equal"); } else { Debug.WriteLine("Both strings are not equal"); } } Debug.WriteLine(bytes.ToHexString()); var multihash = Multihash.Sum <SHA2_256>(bytes); string checkData = multibase.Encode(multihash); stringHash.Text = checkData; //Hash with IPFS CancellationToken token = new CancellationToken(false); IpfsClient ipfs = new IpfsClient("http://10.0.3.2:5001"); IFileSystemNode fileSystemNode = await ipfs.FileSystem.AddFileAsync(file.Path); Debug.WriteLine("fileSystemNode Hash:" + fileSystemNode.Id); imageHash.Text = fileSystemNode.Id; file.Dispose(); } catch (Exception err) { Debug.WriteLine("Message:" + err.Message); Debug.WriteLine("Source:" + err.Source); Debug.WriteLine("Stack Trace:" + err.StackTrace); } }
public async Task <string> AddDirectoryOnIPFS(string path) { IFileSystemNode node = await ipfs.FileSystem.AddDirectoryAsync(path, true); return(node.Id.Encode()); }
public void SaveUnder(IFileSystemNode parent) { Directory.CreateDirectory(Path.FullPath); }
public FileSystemNode(IFileSystemNode parent, IPath path) : this(path.FullPath, parent.Level + 1) { }
public void SaveUnder(IFileSystemNode parent) { parent.CastTo <FakeFileSystemNode>()._innerNodes.Add(this); }