コード例 #1
0
ファイル: ArchiveFatroy.cs プロジェクト: midgithub/KouXiaGu
        public Archive Create(string archiveDirectory)
        {
            DirectoryContent   directoryContent = new DirectoryContent(archiveDirectory);
            ArchiveDescription description      = ReadDescription(directoryContent);

            return(new Archive(directoryContent, description));
        }
コード例 #2
0
        public DirectoryViewModel(IScreen hostScreen, IDirectoryTools directoryTools)
        {
            this.directoryTools = directoryTools;
            HostScreen          = hostScreen;

            var sourceDirectory = Preferences.Get("sourceDirectory", string.Empty);

            subDirectories.DisposeWith(Disposables);

            SelectedDirectory = new DirectoryContent(Path.GetFileName(sourceDirectory), sourceDirectory);

            this.WhenAnyValue(vm => vm.SelectedDirectory)
            .Where(x => x != null)
            .Subscribe(directoryContent => SetDirectoryContent(directoryContent.FullPath))
            .DisposeWith(Disposables);

            subDirectoriesHelper = subDirectories.ToProperty(this, vm => vm.SubDirectories);
            subDirectoriesHelper.DisposeWith(Disposables);

            CmdSetSoureDirectory = ReactiveCommand.CreateFromTask(_ =>
            {
                Preferences.Set("sourceDirectory", SelectedDirectory.FullPath);

                HostScreen.Router.Navigate.Execute(new ScannedChatsViewModel(hostScreen, directoryTools))
                .Subscribe()
                .DisposeWith(Disposables);

                return(Task.FromResult(Unit.Default));
            })
                                   .SetupErrorHandling(Disposables);

            SetDirectoryContent(sourceDirectory);
        }
コード例 #3
0
        /// <summary>
        /// получение запрашиваемых директорий с сервера
        /// </summary>
        /// <param name="netStream"></param>
        /// <param name="directory"></param>
        /// <returns></returns>
        private DirectoryContent GetDirectoriesFromServer(NetworkStream netStream, string directory)
        {
            try
            {
                //создание запроса на получение директорий
                GetDirectoryContentTask getDirectoryContentTask = new GetDirectoryContentTask();

                //установка запросу, что нужно получить именно директории
                getDirectoryContentTask.Directory = directory;

                //отправка запроса к серверу
                netStream.Send(getDirectoryContentTask);

                //прочитать из потока
                Stream stream = netStream.WriteToStream();

                //получить запрошенную информацию о директории
                DirectoryContent directoryInfoClass =
                    Serializer.Deserialize <DirectoryContent>(((MemoryStream)stream).ToArray());

                //вернуть сведения о директории
                return(directoryInfoClass);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            return(null);
        }
コード例 #4
0
        public IEnumerable <DirectoryContentBase> GetDirectoryContent(DirectoryContent baseDirectory = null,
                                                                      string searchPattern           = "*")
        {
            try
            {
                if (string.IsNullOrEmpty(baseDirectory.FullPath))
                {
                    var dir = Environment.ExternalStorageDirectory.AbsolutePath;
                    baseDirectory = new DirectoryContent(Path.GetFileName(dir), dir);
                }

                var directoryContents = Directory.GetDirectories(baseDirectory.FullPath)
                                        .Select(dirName => new DirectoryContent(Path.GetFileName(dirName), dirName));

                var fileContents = Directory.GetFiles(baseDirectory.FullPath, searchPattern)
                                   .Select(fullPath =>
                {
                    var fileName  = Path.GetFileName(fullPath);
                    var extension = Path.GetExtension(fullPath);
                    return(new FileContent(fileName, fullPath, extension));
                });

                var contents = new List <DirectoryContentBase>();
                contents.AddRange(directoryContents);
                contents.AddRange(fileContents);
                return(contents);
            }
            catch
            {
                return(new[] { baseDirectory });
            }
        }
コード例 #5
0
        public DirectoryContent  ReadDir(string dir)
        {
            DirectoryContent tmpContent = new DirectoryContent();

            tmpContent.Directory = dir;
            tmpContent.List      = ProcessFiles(dir);
            return(tmpContent);
        }
コード例 #6
0
 public ScenarioInfo ReadInfo(string directory)
 {
     using (var content = new DirectoryContent(directory))
     {
         var description = ReadDescription(content);
         var contentInfo = new DirectoryContentInfo(directory);
         return(new ScenarioInfo(contentInfo, description));
     }
 }
コード例 #7
0
        public object GetParentByPath(string parentOf)
        {
            if (Directory.Exists(parentOf))
            {
                if (Directory.GetParent(parentOf) != null)
                {
                    DirectoryContent dr = new DirectoryContent(Directory.GetParent(parentOf).FullName);
                    dr.FilesCountWithSpecificCondition = new List <TotalFilesWithCondition>();

                    dr.FilesCountWithSpecificCondition.Add(new TotalFilesWithCondition
                    {
                        ConditionName = "Less 10Mb",
                        FilesCount    =
                            HDDInspector.FilesCountWithCondition(x => x.Length / 1048576 <= 10,
                                                                 new DirectoryInfo(dr.DirPath))
                    });

                    dr.FilesCountWithSpecificCondition.Add(new TotalFilesWithCondition
                    {
                        ConditionName = "10Mb - 50Mb",
                        FilesCount    =
                            HDDInspector.FilesCountWithCondition(x => x.Length / 1048576 > 10 && x.Length / 1048576 <= 50,
                                                                 new DirectoryInfo(dr.DirPath))
                    });

                    dr.FilesCountWithSpecificCondition.Add(new TotalFilesWithCondition
                    {
                        ConditionName = "More 100Mb",
                        FilesCount    =
                            HDDInspector.FilesCountWithCondition(x => x.Length / 1048576 >= 100,
                                                                 new DirectoryInfo(dr.DirPath))
                    });
                    return(dr);
                }
                else
                {
                    return new RequestError()
                           {
                               ErrorMessage = "", OpenDriveSelectionDlg = true
                           }
                };
            }
            else
            {
                return("{\"DirPath\":\"Error\", \"OriginalPath\":\"Error\"," +
                       " \"Message\":\"Syntax error or directory doesn't exists. Check out input parameters\"," +
                       " \"PassedParameter\":\"" + parentOf + "\"}");
            }
        }
コード例 #8
0
 private static bool TryReadFromDirectory(string directory, out ICustomCursor cursor)
 {
     try
     {
         using (var content = new DirectoryContent(directory))
         {
             return(TryRead(content, out cursor));
         }
     }
     catch (Exception ex)
     {
         UnityEngine.Debug.Log(ex);
         cursor = null;
         return(false);
     }
 }
コード例 #9
0
        public async Task Methods()
        {
            byte[]       file               = System.IO.File.ReadAllBytes("File.rsf");
            const string brickFilePath      = "../prjs/xunit/File.rsf";
            const string brickDirectoryPath = "../prjs/xunit/";
            bool         success;

            success = await F.SystemMethods.CreateDirectory(Socket.Instance, brickDirectoryPath);

            Assert.True(success);

            success = await F.SystemMethods.UploadFile(Socket.Instance, file, brickFilePath);

            Assert.True(success);


            byte[] data = await F.SystemMethods.DownLoadFile(Socket.Instance, brickFilePath);

            Assert.Equal(data, file);

            DirectoryContent content = await F.SystemMethods.GetDirectoryContent(Socket.Instance, brickDirectoryPath);

            Assert.True(content.Files.Length == 1);

            //can not delete non empty directory
            success = await F.SystemMethods.Delete(Socket.Instance, brickDirectoryPath);

            Assert.False(success);

            success = await F.SystemMethods.Delete(Socket.Instance, brickFilePath);

            Assert.True(success);


            content = await F.SystemMethods.GetDirectoryContent(Socket.Instance, brickDirectoryPath);

            Assert.True(content.Files.Length == 0);

            success = await F.SystemMethods.Delete(Socket.Instance, brickDirectoryPath);

            Assert.True(success);
        }
コード例 #10
0
        public object GetDirectoryByPath(string dir_path)
        {
            if (Directory.Exists(dir_path))
            {
                DirectoryContent dr = new DirectoryContent(dir_path);
                dr.FilesCountWithSpecificCondition = new List <TotalFilesWithCondition>();

                dr.FilesCountWithSpecificCondition.Add(new TotalFilesWithCondition
                {
                    ConditionName = "Less 10Mb",
                    FilesCount    =
                        HDDInspector.FilesCountWithCondition(x => x.Length / 1048576 <= 10,
                                                             new DirectoryInfo(dr.DirPath))
                });

                dr.FilesCountWithSpecificCondition.Add(new TotalFilesWithCondition
                {
                    ConditionName = "10Mb - 50Mb",
                    FilesCount    =
                        HDDInspector.FilesCountWithCondition(x => x.Length / 1048576 > 10 && x.Length / 1048576 <= 50,
                                                             new DirectoryInfo(dr.DirPath))
                });

                dr.FilesCountWithSpecificCondition.Add(new TotalFilesWithCondition
                {
                    ConditionName = "More 100Mb",
                    FilesCount    =
                        HDDInspector.FilesCountWithCondition(x => x.Length / 1048576 >= 100,
                                                             new DirectoryInfo(dr.DirPath))
                });
                return(dr);
            }
            else
            {
                return("{\"DirPath\":\"Error\", \"OriginalPath\":\"Error\"," +
                       " \"Message\":\"Syntax error or directory doesn't exists. Check out input parameters\"," +
                       " \"PassedParameter\":\"" + dir_path + "\"}");
            }
        }
コード例 #11
0
        public URespose <DirectoryContent> DirectoryContent(string Owner, string path)
        {
            try
            {
                var(token, ownerToken) = StandartHeader(Owner, ref path);

                var directoryDescription = storageManager
                                           .GetDirectoryInfo(token, ownerToken, path ?? "");

                var content = new DirectoryContent
                {
                    Files       = directoryDescription.Files.ToList(),
                    Documents   = directoryDescription.Documents.ToList(),
                    Directories = directoryDescription.Directories.ToList()
                };

                return(content);
            }
            catch
            {
                return(URespose.BadResponse());
            }
        }
コード例 #12
0
        /// <summary>
        /// отправка полученных директорий и файлов в поток к клиенту
        /// </summary>
        /// <param name="task">запрос на получение директорий</param>
        /// <param name="networkStream">сетевой поток клиента</param>
        private void SendDirectoryDataToClient(GetDirectoryContentTask task, NetworkStream networkStream)
        {
            try
            {
                //получение коллекцию директорий по запросу
                List <DirectoryInfo> directories = this.GetDirectories(task.Directory);

                //создание нового экземпляра для сведений о директории
                DirectoryContent directoryContent = new DirectoryContent();

                //проход по каждой директории в коллекции директорий
                foreach (var dir in directories)
                {
                    //проверка, если файл имеет флаг директории и не является
                    if (dir.Attributes.HasFlag(FileAttributes.Directory) &&
                        !dir.Attributes.HasFlag(FileAttributes.Hidden) &&//скрытым
                        !dir.Attributes.HasFlag(FileAttributes.System) &&//системным
                        !dir.Attributes.HasFlag(FileAttributes.Temporary))   //временным
                    {
                        //создать Data Object Model директории
                        DirectoryMetadata directoryMetadata = new DirectoryMetadata()
                        {
                            FullPath    = dir.FullName,
                            Name        = dir.Name,
                            LastChanged = dir.LastWriteTime,
                        };

                        //добавление в лист сведений о директории
                        directoryContent.Directories.Add(directoryMetadata);
                    }
                }

                //получение коллекции файлов
                List <FileInfo> files = this.GetFiles(task.Directory);

                //прохождение по каждому файлу в коллекции файлов
                foreach (var file in files)
                {
                    //если файл не является
                    if (!file.Attributes.HasFlag(FileAttributes.Hidden) &&//скрытым
                        !file.Attributes.HasFlag(FileAttributes.System) &&//системным
                        !file.Attributes.HasFlag(FileAttributes.Temporary))   //временным
                    {
                        //создать Data Object Model файла
                        DirectoryMetadata fileMetadata = new DirectoryMetadata()
                        {
                            FullPath    = file.FullName,
                            Name        = file.Name,
                            LastChanged = file.LastWriteTime,
                        };

                        //добавление в лист сведений о файле
                        directoryContent.Files.Add(fileMetadata);
                    }
                }

                //отправка клиенту запроса файлов и директорий
                networkStream.Send(directoryContent);
            }
            catch (UnauthorizedAccessException) { }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
コード例 #13
0
 public override int ReadDir(ReadOnlySpan <byte> path, ulong offset, ReadDirFlags flags, DirectoryContent content, ref FuseFileInfo fi)
 {
     return(base.ReadDir(path, offset, flags, content, ref fi));
 }
コード例 #14
0
        public override int ReadDir(ReadOnlySpan <byte> path, ulong offset, ReadDirFlags flags, DirectoryContent content, ref FuseFileInfo fi)
        {
            Console.WriteLine("ReadDir -> " + Encoding.UTF8.GetString(path));
            string convPath = Encoding.UTF8.GetString(path);

            try
            {
                FileSystemPath fsPath;
                bool           exists = false;
                ICollection <VirtualFileSystemInfo> ents;
                if (convPath == "/")
                {
                    fsPath = FileSystemPath.Parse("/");
                    exists = true;
                    content.AddEntry("stats");
                }
                else
                {
                    fsPath = FileSystemPath.Parse(convPath + "/");
                    exists = fs.Exists(FileSystemPath.Parse(Encoding.UTF8.GetString(path)));
                }

                ents = fs.GetExtendedEntities(fsPath);

                if (ents.Count == 0 && !exists)
                {
                    Console.WriteLine("no files!!!");
                    return(-ENOENT);
                }

                content.AddEntry(".");
                content.AddEntry("..");
                foreach (var e in ents)
                {
                    content.AddEntry(e.Name);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(0);
        }
コード例 #15
0
 public override int ReadDir(ReadOnlySpan <byte> path, ulong offset, ReadDirFlags flags, DirectoryContent content, ref FuseFileInfo fi)
 {
     if (!path.SequenceEqual(RootPath))
     {
         return(-ENOENT);
     }
     content.AddEntry(".");
     content.AddEntry("..");
     content.AddEntry("hello");
     return(0);
 }
コード例 #16
0
        public override int ReadDir(ReadOnlySpan <byte> path, ulong offset, ReadDirFlags flags, DirectoryContent content, ref FuseFileInfo fi)
        {
            int error = 0, level = 0;
            var procs = ProcPath(path, ref error, ref level, isADir: true);

            if (error != 0)
            {
                return(-LibC.ENOENT);
            }

            //var sb = new StringBuilder();
            //foreach (var v in procs)
            //{
            //    sb.Append(v.Item2.Name.GetString());
            //    sb.Append("{");
            //    sb.Append(v.Item2._id.ToString());
            //    sb.Append("}/");
            //}


            var last = procs.Pop();


            if (last.Item2 == null)
            {
                return(-last.Item3);                     // No such file
            }
            // Just return everything - someday we need to break into batches

            content.AddEntry(".");
            content.AddEntry("..");

            if (verbosity > 5)
            {
                Console.WriteLine($"ReadDir Path={path.GetString()} offset={offset} flags={flags} ParentId={last.Item2._id}");
            }

            // This could conceivably return millions of records - Once we figure out how to set up batches
            // we can use OpenDir to create a file handle which we can bind an enumerator to (RelaseDir can close it).


            //Console.WriteLine($"Full: {sb}");
            //Console.WriteLine($"Item: Path={path.GetString()} {last.Item2.Name.GetString()} Parent: {last.Item2._id}");


            // ParentId should be indexed (with a hash)
            var filter = Builders <NeoAssets.Mongo.NeoVirtFS> .Filter.Eq(x => x.ParentId, last.Item2._id);

            foreach (var rec in NeoVirtFSCol.FindSync(filter).ToList())
            {
                //Console.WriteLine($"  Contents: {rec._id} - {rec.Name.GetString()}");
                content.AddEntry(rec.Name);

                // For now, also populate the cache with this

                NodeCacheSet(rec, 5);
            }

            return(0);
        }
コード例 #17
0
        public override int ReadDir(ReadOnlySpan <byte> path, ulong offset, ReadDirFlags flags, DirectoryContent content, ref FuseFileInfo fi, Guid fileGuid)
        {
            if (debug)
            {
                Console.WriteLine($"TopLevel::ReadDir({RawDirs.HR(path)},{offset},{flags})");
            }

            try
            {
                content.AddEntry(".");
                content.AddEntry("..");

                foreach (var v in Mountpoints)
                {
                    content.AddEntry(v.Key.AsSpan());
                }

                return(0);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"TopLevel::ReadDir() - error {ex.Message}");
                return(-LibC.EACCES);
            }
        }
コード例 #18
0
        public override int ReadDir(ReadOnlySpan <byte> path, ulong offset, ReadDirFlags flags, DirectoryContent content, ref FuseFileInfo fi, Guid fileGuid)
        {
            if (debug)
            {
                Console.WriteLine($"NeoFS::ReadDir({RawDirs.HR(path)},{offset},{flags})");
            }
            path = base.TransformPath(path);

            // We only have the low level calls, so we need to do opendir/readdir ourself

            var dirFd = RawDirs.opendir(RawDirs.ToNullTerm(path.ToArray()));

            if (dirFd == IntPtr.Zero)
            {
                return(0);
            }

            content.AddEntry(".");  // This can eat strings
            content.AddEntry("..");

            while (true)
            {
                var dir = RawDirs.readdir_wrap(dirFd, false);  // Don't remove the null
                if (dir == null)
                {
                    break;
                }

                var d = dir.Value;

                if (debug)
                {
                    Console.WriteLine($"{RawDirs.HR(path)} -> {RawDirs.HR(d.d_name)}");
                }

                content.AddEntry(d.d_name.AsSpan());
            }

            RawDirs.closedir(dirFd);

            return(0);
        }
コード例 #19
0
 public virtual int ReadDir(ReadOnlySpan <byte> path, ulong offset, ReadDirFlags flags, DirectoryContent content, ref FuseFileInfo fi, Guid fileGuid)
 => - LibC.ENOSYS;
コード例 #20
0
        /// <summary>
        /// Gets a list of folders and/or files for given path
        /// </summary>
        /// <param name="socket">socket for executing command to brick</param>
        /// <param name="brickDirectoryPath">relative path to folder on brick</param>
        /// <returns>DirectoryContent</returns>
        /// <exception cref="ArgumentException"/>
        /// <exception cref="ArgumentNullException"/>
        /// <exception cref="FirmwareException"/>
        public static async Task <DirectoryContent> GetDirectoryContent(ISocket socket, string brickDirectoryPath)
        {
            await semaPhoreSlim.WaitAsync();

            try
            {
                brickDirectoryPath = FileSystem.ToBrickDirectoryPath(brickDirectoryPath);
                brickDirectoryPath.IsBrickDirectoryPath();

                Command cmd = null;
                using (CommandBuilder cb = new CommandBuilder(CommandType.SYSTEM_COMMAND_REPLY))
                {
                    cb.OpCode(SYSTEM_OP.LIST_FILES);
                    cb.Raw((ushort)PAYLOAD_SIZE);
                    cb.Raw(brickDirectoryPath);
                    cmd = cb.ToCommand();
                }


                Response response = await socket.Execute(cmd);

                if (!(response.Status == ResponseStatus.SUCCESS || response.Status == ResponseStatus.END_OF_FILE))
                {
                    throw new FirmwareException(response);
                }

                byte[] data     = response.PayLoad;
                ushort listSize = (ushort)BitConverter.ToUInt32(data, 0);
                byte   handle   = data[4];

                List <byte> list = new List <byte>();

                if (data.Length > 5)
                {
                    byte[] chunk = new byte[data.Length - 5];
                    Array.Copy(data, 5, chunk, 0, chunk.Length);
                    list.AddRange(chunk);

                    int bytesRead = chunk.Length;
                    while (bytesRead < listSize)
                    {
                        ushort payLoadSize = (ushort)Math.Min(PAYLOAD_SIZE, listSize - bytesRead);
                        response = await ContinueList(socket, handle, payLoadSize);

                        if (!(response.Status == ResponseStatus.SUCCESS || response.Status == ResponseStatus.END_OF_FILE))
                        {
                            throw new FirmwareException(response);
                        }

                        data = response.PayLoad;
                        if (data.Length > 1)
                        {
                            chunk = new byte[data.Length - 1];
                            Array.Copy(data, 1, chunk, 0, chunk.Length);
                            list.AddRange(chunk);
                        }
                        bytesRead += payLoadSize;
                    }
                }

                data = list.ToArray();
                string   value   = Encoding.UTF8.GetString(data, 0, data.Length).TrimEnd(LIST_DELIMITER);
                string[] entries = value.Split(LIST_DELIMITER);

                DirectoryContent contents    = new DirectoryContent();
                List <Directory> directories = new List <Directory>();
                List <File>      files       = new List <File>();
                foreach (string entry in entries)
                {
                    string item = entry.Trim();
                    if (string.IsNullOrWhiteSpace(item))
                    {
                        continue;
                    }
                    switch (item)
                    {
                    case FileSystem.ROOT_PATH:
                    {
                        contents.Root = new Directory(item);
                        break;
                    }

                    case FileSystem.PARENT_PATH:
                    {
                        if (brickDirectoryPath == FileSystem.ROOT_PATH)
                        {
                            contents.Parent = new Directory(FileSystem.ROOT_PATH);
                        }
                        else
                        {
                            string parent = brickDirectoryPath.Substring(0, brickDirectoryPath.LastIndexOf(FileSystem.DIRECTORY_SEPERATOR));
                            contents.Parent = new Directory(parent);
                        }
                        break;
                    }

                    default:
                    {
                        if (item.EndsWith(FileSystem.DIRECTORY_SEPERATOR))
                        {
                            string directoryPath = $"{brickDirectoryPath}{item}";
                            directories.Add(new Directory(directoryPath));
                        }
                        else
                        {
                            string[] fileInfo = entry.Split(' ');
                            if (fileInfo.Length >= 3)
                            {
                                string md5sum   = fileInfo[0].Trim();
                                long   byteSize = Convert.ToInt64(fileInfo[1].Trim(), 16);
                                string fileName = string.Join(" ", fileInfo, 2, fileInfo.Length - 2);
                                if (!string.IsNullOrWhiteSpace(fileName))
                                {
                                    files.Add(new File(brickDirectoryPath, fileName, md5sum, byteSize));
                                }
                            }
                        }
                        break;
                    }
                    }
                }
                directories.Sort(delegate(Directory obj1, Directory obj2) { return(obj1.Name.CompareTo(obj2.Name)); });
                contents.Directories = directories.ToArray();
                files.Sort(delegate(File obj1, File obj2) { return(obj1.FileName.CompareTo(obj2.FileName)); });
                contents.Files = files.ToArray();
                return(contents);
            }
            finally
            {
                semaPhoreSlim.Release();
            }
        }