Exemple #1
0
        public Stream DownloadFileRest(long sessionID, RelPath relPath, long offsetFromEnd)
        {
            if (TryGetScadaInstance(sessionID, out var scadaInstance))
            {
                try {
                    string path   = scadaInstance.GetAbsPath(relPath);
                    Stream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);

                    if (offsetFromEnd >= 0)
                    {
                        long offset = -Math.Min(offsetFromEnd, stream.Length);
                        stream.Seek(offset, SeekOrigin.End);
                    }

                    return(stream);
                } catch (FileNotFoundException) {
                    return(null);
                } catch (Exception ex) {
                    Log.WriteException(ex,
                                       Localization.UseRussian ? "Ошибка при открытии файла" : "Error opening file");
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
 public NewFileBroadcast(RelPath fileName, FsFile<RelPath> descriptor, string seedUser, IList<PieceHash> hashes)
 {
     this.fileName = fileName;
     this.descriptor = descriptor;
     this.seedUser = seedUser;
     this.hashes = hashes;
 }
 public ProjectWatcherTests()
 {
     _project   = new Project(RelPath.FromString("Example.csproj"));
     _watcher   = new Mock <IFilesystemWatcher>(MockBehavior.Strict);
     _scheduler = new TestScheduler();
     _testee    = new ProjectWatcher(_project, _watcher.Object, _scheduler, new Mock <ILogger <ProjectWatcher> >().Object);
 }
Exemple #4
0
 /// <summary>
 /// Упаковать директорию
 /// </summary>
 private void PackDir(ZipArchive zipArchive, RelPath relPath, PathDict ignoredPathDict)
 {
     PackDir(zipArchive,
             GetAbsPath(relPath),
             DirectoryBuilder.GetDirectory(relPath.ConfigPart, relPath.AppFolder, '/'),
             ignoredPathDict.GetOrAdd(relPath.ConfigPart, relPath.AppFolder));
 }
        public NewFileSignal(RelPath fileName, FsFile<RelPath> descriptor, IList<PieceHash> hashes)
        {
            this.fileName = fileName;
            this.descriptor = descriptor;

            this.hashes = hashes;
        }
Exemple #6
0
        private bool ApplySingleGroupFiles(RelPath relPath, int selection, HashSet <GamePath> paths)
        {
            // Selection contains the path, merge all GamePaths for this config.
            if (Options[selection].OptionFiles.TryGetValue(relPath, out var groupPaths))
            {
                paths.UnionWith(groupPaths);
                return(true);
            }

            // If the group contains the file in another selection, return true to skip it for default files.
            for (var i = 0; i < Options.Count; ++i)
            {
                if (i == selection)
                {
                    continue;
                }

                if (Options[i].OptionFiles.ContainsKey(relPath))
                {
                    return(true);
                }
            }

            return(false);
        }
Exemple #7
0
        public Stream DownloadFileRest(long sessionID, RelPath relPath, long position)
        {
            if (TryGetScadaInstance(sessionID, out ScadaInstance scadaInstance))
            {
                try
                {
                    string path   = scadaInstance.GetAbsPath(relPath);
                    Stream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);

                    if (position > 0)
                    {
                        stream.Position = position;
                    }

                    return(stream);
                }
                catch (FileNotFoundException)
                {
                    return(null);
                }
                catch (Exception ex)
                {
                    Log.WriteException(ex, Localization.UseRussian ?
                                       "Ошибка при открытии файла" :
                                       "Error opening file");
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
Exemple #8
0
        /// <summary>
        /// Directory Overview
        /// </summary>
        public bool Browse(RelPath relPath, out ICollection <string> directories, out ICollection <string> files)
        {
            try {
                string absPath = GetAbsPath(relPath);
                var    dirInfo = new DirectoryInfo(absPath);

                // getting subdirectories
                directories = new List <string>();
                DirectoryInfo[] subdirInfoArr = dirInfo.GetDirectories("*", SearchOption.TopDirectoryOnly);

                foreach (var subdirInfo in subdirInfoArr)
                {
                    directories.Add(subdirInfo.Name);
                }

                // receiving files
                files = new List <string>();
                FileInfo[] fileInfoArr = dirInfo.GetFiles("*", SearchOption.TopDirectoryOnly);

                foreach (var fileInfo in fileInfoArr)
                {
                    files.Add(fileInfo.Name);
                }

                return(true);
            } catch (Exception ex) {
                log.WriteException(ex,
                                   Localization.UseRussian ? "Ошибка при обзоре директории" : "Error browsing directory");
                directories = null;
                files       = null;
                return(false);
            }
        }
        // TODO: no reload same project twice?

        private void SetupLeafProject(RelPath projectPath)
        {
            var projectText = @"<Project Sdk=""Microsoft.NET.Sdk""></Project>";

            _filesystem
            .Setup(x => x.ReadFile(projectPath.Path))
            .Returns(projectText);
        }
Exemple #10
0
 // Adds all game paths from the given option that correspond to the given RelPath to paths, if any exist.
 internal bool ApplyGroupFiles(RelPath relPath, int selection, HashSet <GamePath> paths)
 {
     return(SelectionType switch
     {
         SelectType.Single => ApplySingleGroupFiles(relPath, selection, paths),
         SelectType.Multi => ApplyMultiGroupFiles(relPath, selection, paths),
         _ => throw new InvalidEnumArgumentException("Invalid option group type."),
     });
        public void LoadsIslandProject()
        {
            var projectFilePath = RelPath.FromString("./Example.csproj");

            SetupLeafProject(projectFilePath);
            var project = _testee.Load(projectFilePath);

            project.Should().BeEquivalentTo(new Project(projectFilePath));
        }
Exemple #12
0
 protected override void OnCreate(AbsPath path)
 {
     if (path.Extension == "" || allowedExtensions.Contains(path.Extension))
     {
         RelPath relPath  = path.ReplaceAsRelativePath(srcFolder);
         AbsPath destPath = destFolder.Combine(relPath);
         Console.WriteLine($"create '{relPath}' (from '{path.PathStr}' to '{destPath.PathStr}')");
         path.CopyToFiltered(destPath, allowedExtensions);
     }
 }
Exemple #13
0
 protected override void OnDelete(AbsPath path)
 {
     if (path.Extension == "" || allowedExtensions.Contains(path.Extension))
     {
         RelPath relPath = path.ReplaceAsRelativePath(srcFolder);
         Console.WriteLine($"delete '{relPath}'");
         AbsPath destPath = destFolder.Combine(relPath);
         destPath.Delete();
     }
 }
Exemple #14
0
        /// <summary>
        /// Очистить директорию
        /// </summary>
        private void ClearDir(RelPath relPath, PathDict ignoredPathDict)
        {
            DirectoryInfo dirInfo = new DirectoryInfo(GetAbsPath(relPath));

            if (dirInfo.Exists)
            {
                ClearDir(dirInfo, ignoredPathDict.GetOrAdd(relPath.ConfigPart, relPath.AppFolder),
                         out bool dirEmpty);
            }
        }
Exemple #15
0
        public void RelativeTo(string origin, string rel, string expected)
        {
            var originPath = RelPath.FromString(origin);

            var relativePath = RelPath.FromString(rel);

            var result = relativePath.RelativeTo(originPath);

            result.Path.Should().Be(expected);
        }
Exemple #16
0
 private NBTString TryMakeRawJsonFileNBT(JToken jToken)
 {
     if (jToken.Type == JTokenType.String)
     {
         string path = (string)((JValue)jToken).Value;
         path = RelPath.GetRootedPathByFile(basePath, path);
         return(new NBTString(new RawJson(path).GetEscapedJsonText('"')));
     }
     else
     {
         throw new FormatException($"<{jToken.Path}> value must be string.");
     }
 }
Exemple #17
0
 public DateTime GetFileAgeUtc(long sessionID, RelPath relPath)
 {
     if (TryGetScadaInstance(sessionID, out ScadaInstance scadaInstance))
     {
         string path = scadaInstance.GetAbsPath(relPath);
         try { return(File.Exists(path) ? File.GetLastWriteTimeUtc(path) : DateTime.MinValue); }
         catch { return(DateTime.MinValue); }
     }
     else
     {
         return(DateTime.MinValue);
     }
 }
Exemple #18
0
        public bool AddFile(RelPath filePath, GamePath gamePath)
        {
            if (OptionFiles.TryGetValue(filePath, out var set))
            {
                return(set.Add(gamePath));
            }

            OptionFiles[filePath] = new HashSet <GamePath>()
            {
                gamePath
            };
            return(true);
        }
Exemple #19
0
 protected override void OnRename(AbsPath oldPath, AbsPath newPath)
 {
     // todo: test oldPath.Extension == "" for directory?
     if ((oldPath.Extension == "" && newPath.Extension == "") ||
         (allowedExtensions.Contains(oldPath.Extension) && allowedExtensions.Contains(newPath.Extension)))
     {
         RelPath relOldPath  = oldPath.ReplaceAsRelativePath(srcFolder);
         RelPath relNewPath  = newPath.ReplaceAsRelativePath(srcFolder);
         AbsPath destOldPath = destFolder.Combine(relOldPath);
         AbsPath destNewPath = destFolder.Combine(relNewPath);
         Console.WriteLine($"rename '{relOldPath}' as '{relNewPath}' (from '{destOldPath}' to '{destNewPath}')");
         destOldPath.RenameFullPath(destNewPath.PathStr);
     }
 }
Exemple #20
0
 public bool Browse(long sessionID, RelPath relPath,
                    out ICollection <string> directories, out ICollection <string> files)
 {
     if (TryGetScadaInstance(sessionID, out var scadaInstance))
     {
         return(scadaInstance.Browse(relPath, out directories, out files));
     }
     else
     {
         directories = null;
         files       = null;
         return(false);
     }
 }
Exemple #21
0
        public static HashSet <GamePath> GetFilesForConfig(RelPath relPath, ModSettings settings, ModMeta meta)
        {
            var doNotAdd = false;
            var files    = new HashSet <GamePath>();

            foreach (var group in meta.Groups.Values.Where(g => g.Options.Count > 0))
            {
                doNotAdd |= group.ApplyGroupFiles(relPath, settings.Settings[group.GroupName], files);
            }

            if (!doNotAdd)
            {
                files.Add(new GamePath(relPath));
            }

            return(files);
        }
Exemple #22
0
 protected override void OnChange(AbsPath path)
 {
     if (allowedExtensions.Contains(path.Extension))
     {
         RelPath relPath = path.ReplaceAsRelativePath(srcFolder);
         Console.WriteLine($"change '{relPath}'");
         AbsPath destPath = destFolder.Combine(relPath);
         if (path is FilePath srcFile)
         {
             if (destPath.Exists)
             {
                 destPath.Delete();
             }
             srcFile.CopyToFiltered(destPath, allowedExtensions);
         }
     }
 }
Exemple #23
0
        public static HashSet <GamePath> GetAllFiles(RelPath relPath, ModMeta meta)
        {
            var ret = new HashSet <GamePath>();

            foreach (var option in meta.Groups.Values.SelectMany(g => g.Options))
            {
                if (option.OptionFiles.TryGetValue(relPath, out var files))
                {
                    ret.UnionWith(files);
                }
            }

            if (ret.Count == 0)
            {
                ret.Add(relPath.ToGamePath());
            }

            return(ret);
        }
Exemple #24
0
        private bool ApplyMultiGroupFiles(RelPath relPath, int selection, HashSet <GamePath> paths)
        {
            var doNotAdd = false;

            for (var i = 0; i < Options.Count; ++i)
            {
                if ((selection & (1 << i)) != 0)
                {
                    if (Options[i].OptionFiles.TryGetValue(relPath, out var groupPaths))
                    {
                        paths.UnionWith(groupPaths);
                        doNotAdd = true;
                    }
                }
                else if (Options[i].OptionFiles.ContainsKey(relPath))
                {
                    doNotAdd = true;
                }
            }

            return(doNotAdd);
        }
Exemple #25
0
 /// <summary>
 /// Получить абсолютный путь из относительного
 /// </summary>
 public string GetAbsPath(RelPath relPath)
 {
     return(GetAbsPath(relPath.ConfigPart, relPath.AppFolder, relPath.Path));
 }
 public BlockMessage(RelPath fileName, int pieceIndex, short inPieceOffset)
 {
     blockInfo = new BlockInfo(fileName, pieceIndex, inPieceOffset);
 }
Exemple #27
0
 /// <summary>
 /// Reads the log file.
 /// </summary>
 public bool ReadLog(RelPath relPath, ref DateTime fileAge, out ICollection <string> lines)
 {
     return(ReadLog(relPath, -1, ref fileAge, out lines));
 }
 public BlockRequest(RelPath fileName, int pieceIndex, short inPieceOffset)
     : base(fileName, pieceIndex, inPieceOffset)
 {
 }
Exemple #29
0
        public HashSet <GamePath> GetFiles(FileInfo file)
        {
            var relPath = new RelPath(file, Data.BasePath);

            return(ModFunctions.GetFilesForConfig(relPath, Settings, Data.Meta));
        }
Exemple #30
0
 public override int GetHashCode()
 {
     return(SnippetHtml.GetHashCode() ^ RelPath.GetHashCode() ^ Text.GetHashCode());
 }
Exemple #31
0
 public BlockInfo(RelPath filePath, int pieceIndex, short inPieceOffset)
 {
     pieceInfo = new PieceInfo(filePath, pieceIndex);
     this.inPieceOffset = inPieceOffset;
 }
Exemple #32
0
 public PieceInfo(RelPath relFilePath, int index)
 {
     this.relFilePath = relFilePath;
     this.index = index;
 }
 public PieceAvailable(RelPath fileName, int pieceIndex)
     : base(fileName, pieceIndex)
 {
 }
 public override int GetHashCode()
 {
     return(SnippetNode.GetHashCode() ^ RelPath.GetHashCode() ^ Date.GetHashCode());
 }
Exemple #35
0
 /// <summary>
 /// Initializes a new instance of the class.
 /// </summary>
 public RemoteLogBox(ListBox listBox, bool colorize = false)
     : base(listBox, colorize)
 {
     logPath     = new RelPath();
     AgentClient = null;
 }
Exemple #36
0
        /// <summary>
        /// Reads the rest of the log file.
        /// </summary>
        public bool ReadLog(RelPath relPath, long offsetFromEnd, ref DateTime fileAge, out ICollection <string> lines)
        {
            if (relPath == null)
            {
                throw new ArgumentNullException("relPath");
            }

            RestoreConnection();
            DateTime newFileAge = client.GetFileAgeUtc(sessionID, relPath);

            if (newFileAge == DateTime.MinValue) // log doesn't exist
            {
                fileAge = newFileAge;
                lines   = new string[] { CommonPhrases.FileNotFound };
                return(true);
            }
            else if (fileAge != newFileAge)
            {
                Stream downloadStream = client.DownloadFileRest(sessionID, relPath, offsetFromEnd);

                if (downloadStream == null) // error opening the log
                {
                    lines = new string[] { CommonPhrases.Error };
                    return(true);
                }
                else
                {
                    List <string> lineList = new List <string>();

                    try {
                        using (StreamReader reader = new StreamReader(downloadStream, Encoding.UTF8)) {
                            // add or skip the first line
                            if (!reader.EndOfStream)
                            {
                                string s = reader.ReadLine();
                                if (offsetFromEnd < 0)
                                {
                                    lineList.Add(s);
                                }
                            }

                            // read the rest lines
                            while (!reader.EndOfStream)
                            {
                                lineList.Add(reader.ReadLine());
                            }
                        }
                    } finally {
                        downloadStream.Dispose();
                    }

                    if (lineList.Count == 0)
                    {
                        lineList.Add(CommonPhrases.NoData);
                    }

                    RegisterActivity();
                    fileAge = newFileAge;
                    lines   = lineList;
                    return(true);
                }
            }
            else
            {
                lines = null;
                return(false);
            }
        }
 public PieceMessage(RelPath fileName, int pieceIndex)
 {
     pieceInfo = new PieceInfo(fileName, pieceIndex);
 }
Exemple #38
0
 public Stream DownloadFile(long sessionID, RelPath relPath)
 {
     return(DownloadFileRest(sessionID, relPath, -1));
 }
Exemple #39
0
 //        private bool complete;
 public ActivePiece(RelPath fileName, int pieceIndex, int pieceByteSize)
     : this(new PieceInfo(fileName, pieceIndex), pieceByteSize)
 {
 }
 public BlockTransfer(RelPath fileName, int pieceIndex, byte inPieceOffset, byte[] data)
     : base(fileName, pieceIndex, inPieceOffset)
 {
     this.data = data;
 }