コード例 #1
0
        public FileHashChecker(ServerSettings serverSettings)
        {
            if (!serverSettings.IsModsWhitelisted)
            {
                return;
            }

            setupApproveWorldType(serverSettings);

            var result = new Dictionary <FolderType, CheckedDirAndFile>();

            var folderTree = FoldersTree.GenerateTree(serverSettings.ModsDirectory);

            result.Add(FolderType.ModsFolder, new CheckedDirAndFile()
            {
                ServerDirectory = serverSettings.ModsDirectory,
                FolderTree      = folderTree,
                HashFiles       = getFiles(serverSettings.ModsDirectory, serverSettings.IgnoredLocalModFiles),
                IgrnoredFiles   = serverSettings.IgnoredLocalModFiles,
            });

            folderTree = new FoldersTree();
            result.Add(FolderType.ModsConfigPath, new CheckedDirAndFile()
            {
                ServerDirectory = serverSettings.ModsConfigsDirectoryPath,
                FolderTree      = folderTree,
                HashFiles       = getFiles(serverSettings.ModsConfigsDirectoryPath, serverSettings.IgnoredLocalConfigFiles),
                IgrnoredFiles   = serverSettings.IgnoredLocalConfigFiles,
            });

            CheckedDirAndFiles = result;
        }
コード例 #2
0
        static void Main(string[] args)
        {
            string rootDirectory = @"C:\Windows";
            Folder rootFolder    = new Folder(rootDirectory, false);

            Console.WriteLine("Getting items in {0}, this can take a while", rootDirectory);
            Console.WriteLine();

            PopulateFolders(rootDirectory, rootFolder);

            // Create the Windows Folder tree
            FoldersTree windowsFolderTree = new FoldersTree(rootFolder);

            try
            {
                // Get the subtree, by folder path string
                Folder      subFolderFilesSize = windowsFolderTree.GetFolderByName("C:\\Windows\\addins\\Test");
                FoldersTree subFoldersTree     = windowsFolderTree.GetSubTree(subFolderFilesSize);

                long sumFilesSize = subFoldersTree.GetTreeFilesLength();

                Console.WriteLine("Files size sum in Tree({0}) = {1}", subFolderFilesSize.Name, sumFilesSize);
            }
            catch (FileNotFoundException ex)
            {
                Console.WriteLine("Error finding files size: {0}", ex.Message);
            }
        }
コード例 #3
0
        public InboxView(FoldersTree foldersTree) : base("Inbox")
        {
            InitializeComponent();

            FoldersTree = foldersTree;
            SortOrderBase.DefaultSortOrder = CRSortOrder.SortOrder.Date;
        }
コード例 #4
0
 /// <summary>
 /// Go to the next priority unread message.
 /// </summary>
 private void GoToNextPriorityUnread(InboxConversation conversation)
 {
     if (conversation != null && conversation.UnreadCount > 0)
     {
         conversation.MarkRead();
     }
     FoldersTree.NextUnread(FolderOptions.NextUnread | FolderOptions.Priority);
 }
コード例 #5
0
ファイル: Starter.cs プロジェクト: kaloyan-penkov/SoftUni
    static void Main()
    {
        FoldersTree fTree = new FoldersTree();

        fTree.SaveFilesAndDirectories();

        fTree.PrintAllFolders();

        Console.Read();
    }
コード例 #6
0
ファイル: DirectoryView.cs プロジェクト: cixonline/cixreader
        public DirectoryView(FoldersTree foldersTree) : base("Directory")
        {
            InitializeComponent();

            FoldersTree = foldersTree;
            SortOrderBase.DefaultSortOrder = CRSortOrder.SortOrder.Popularity;
            SortOrderBase.Ascending        = false;

            _imageList.Images.Add(Resources.ReadLock);

            dvForumsList.SmallImageList = _imageList;
        }
コード例 #7
0
        /// <summary>
        /// Display the page for the specified forum.
        /// </summary>
        public override bool ViewFromFolder(FolderBase folder, Address address, FolderOptions flags)
        {
            if (folder is TopicFolder)
            {
                _currentFolder = (TopicFolder)folder;
                _thisForum     = CIX.DirectoryCollection.ForumByName(_currentFolder.Name);

                FoldersTree.SetTopicName(folder.Name);

                if (CIX.Online)
                {
                    CIX.DirectoryCollection.RefreshForum(folder.Name);
                }

                FillCanvas();
            }
            return(true);
        }
コード例 #8
0
ファイル: FileChecker.cs プロジェクト: creepyhauz/OnlineCity
        private static void restoreFolderTree(string modsDir, FoldersTree foldersTree)
        {
            if (foldersTree.SubDirs == null)
            {
                return;
            }

            foreach (var folder in foldersTree.SubDirs)
            {
                var dirName = Path.Combine(modsDir, folder.directoryName);
                if (!Directory.Exists(dirName))
                {
                    Loger.Log($"Create directory: {dirName}");
                    Directory.CreateDirectory(dirName);
                }

                // check and create subdirs
                restoreFolderTree(dirName, folder);
            }
        }
コード例 #9
0
        /// <summary>
        /// Action the specified ID.
        /// </summary>
        /// <param name="id">An action ID</param>
        public override void Action(ActionID id)
        {
            switch (id)
            {
            case ActionID.Refresh:
                if (_thisForum != null)
                {
                    _thisForum.Refresh();
                }
                foreach (Folder topic in _currentFolder.Folder.Children)
                {
                    topic.Refresh();
                }
                break;

            case ActionID.Participants:
                FoldersTree.DisplayParticipants(_thisForum.Name);
                break;

            case ActionID.ManageForum:
                FoldersTree.ManageForum(_thisForum);
                break;

            case ActionID.NextUnread:
                FoldersTree.NextUnread(FolderOptions.NextUnread);
                break;

            case ActionID.NextPriorityUnread:
                FoldersTree.NextUnread(FolderOptions.NextUnread | FolderOptions.Priority);
                break;

            case ActionID.PageMessage:
                FoldersTree.NextUnread(FolderOptions.NextUnread);
                break;
            }
        }
コード例 #10
0
        private ModelModsFiles checkFiles(ModelModsFiles packet, ServiceContext context)
        {
            var NoApproveWorld = ServerManager.FileHashChecker.ApproveWorldType[packet.FolderType];
            var filesDir       = ServerManager.FileHashChecker.CheckedDirAndFiles[packet.FolderType].ServerDirectory;
            var foldersTree    = ServerManager.FileHashChecker.CheckedDirAndFiles[packet.FolderType].FolderTree;
            var workDict       = ServerManager.FileHashChecker.CheckedDirAndFiles[packet.FolderType].HashFiles;
            var ignoredFiles   = ServerManager.FileHashChecker.CheckedDirAndFiles[packet.FolderType].IgrnoredFiles;

            var result         = new List <ModelFileInfo>();
            var allServerFiles = new HashSet <string>(workDict.Keys);
            var packetFiles    = packet.Files != null ? packet.Files : new List <ModelFileInfo>(0);

            long packetSize = 0;
            long totalSize  = 0;

            foreach (var modelFile in packetFiles)
            {
                var modelFileFileName = modelFile.FileName.ToLower();
                if (FileHashChecker.FileNameContainsIgnored(modelFileFileName, ignoredFiles))
                {
                    continue;
                }

                if (workDict.TryGetValue(modelFileFileName, out ModelFileInfo fileInfo))
                {
                    allServerFiles.Remove(modelFileFileName); //

                    if (!ModelFileInfo.UnsafeByteArraysEquale(modelFile.Hash, fileInfo.Hash))
                    {
                        // read file for send to Client
                        // файл  найден, но хеши не совпадают, необходимо заменить файл
                        if (packetSize < MaxPacketSize)
                        {
                            var addFile = GetFile(filesDir, fileInfo.FileName);
                            result.Add(addFile);
                            packetSize += addFile.Size;
                            totalSize  += addFile.Size;
                            //Loger.Log($"packetSize={packetSize} totalSize={totalSize}");
                        }
                        else
                        {
                            var size = GetFileSize(filesDir, fileInfo.FileName);
                            totalSize += size;
                        }
                    }
                }
                else
                {
                    // mark file for delete
                    // Если файл с таким именем не найден, помечаем файл на удаление
                    modelFile.Hash = null;
                    result.Add(modelFile);
                }
            }

            lock (context.Player)
            {
                // проверяем в обратном порядке: что бы у клиенты были все файлы
                if (allServerFiles.Any())
                {
                    context.Player.ApproveLoadWorldReason = context.Player.ApproveLoadWorldReason | ApproveLoadWorldReason.NotAllFilesOnClient;
                    foreach (var fileName in allServerFiles)
                    {
                        if (packetSize < MaxPacketSize)
                        {
                            var addFile = GetFile(filesDir, workDict[fileName].FileName); //workDict[fileName].FileName вместо fileName для восстановления заглавных
                            result.Add(addFile);
                            packetSize += addFile.Size;
                            totalSize  += addFile.Size;
                            //Loger.Log($"packetSize={packetSize} totalSize={totalSize}");
                        }
                        else
                        {
                            var size = GetFileSize(filesDir, workDict[fileName].FileName);
                            totalSize += size;
                        }
                    }
                }

                // Если файлы не прошли проверку, помечаем флагом, запрет загрузки мира
                if (result.Any())
                {
                    context.Player.ApproveLoadWorldReason = context.Player.ApproveLoadWorldReason | NoApproveWorld;
                }
            }

            if (!result.Any())
            {
                // микроптимизация: если файлы не будут восстанавливаться, не отправляем обратно список папок
                // на восстановление ( десериализацию папок также тратится время)
                foldersTree = new FoldersTree();
            }

            return(new ModelModsFiles()
            {
                Files = result,
                FolderType = packet.FolderType,
                FoldersTree = foldersTree,
                TotalSize = totalSize,
            });
        }
コード例 #11
0
ファイル: ServerManager.cs プロジェクト: natsfr/OnlineCity
        private void createFilesDictionary()
        {
            if (!ServerSettings.IsModsWhitelisted)
            {
                return;
            }

            // 1. Создаем словарь со всеми файлами
            Loger.Log($"Calc hash {ServerSettings.ModsDirectory}");
            var modFiles = FileChecker.GenerateHashFiles(ServerSettings.ModsDirectory, Directory.GetDirectories(ServerSettings.ModsDirectory));

            Loger.Log($"Calc hash {ServerSettings.SteamWorkShopModsDir}");
            ///!!!!!!!!!!!!!!!! STEAM FOLDER CHECK SWITCH HERE  !!!!!!!!!!!!!!!
            // 1. Если будем использовать steamworkshop диреторию, эти две строчки ниже закомментировать
            // 2. remove JsobIgnrore atribbute in ServerSettings
            ServerSettings.SteamWorkShopModsDir = Environment.CurrentDirectory;
            ///!!!!!!!!!!!!!!!! STEAM FOLDER CHECK SWITCH HERE  !!!!!!!!!!!!!!!
            var steamFiles = FileChecker.GenerateHashFiles(ServerSettings.SteamWorkShopModsDir, new string[0]);

            ModFilesDict   = modFiles.ToDictionary(f => f.FileName);
            SteamFilesDict = steamFiles.ToDictionary(f => f.FileName);

            // 2. Создаем файлы со списком разрешенных папок, которые отправим клиенту
            var modsFolders = new ModelFileInfo() // 0
            {
                FileName = "ApprovedMods.txt",
                Hash     = FileChecker.CreateListFolder(ServerSettings.ModsDirectory)
            };
            var steamFolders = new ModelFileInfo() // 1
            {
                FileName = "ApprovedSteamWorkShop.txt",
                Hash     = FileChecker.CreateListFolder(ServerSettings.SteamWorkShopModsDir)
            };
            var modsConfigFileName = Path.Combine(ServerSettings.WorkingDirectory, "ModsConfig.xml");
            var modsConfig         = new ModelFileInfo() // 2
            {
                FileName = "ModsConfig.xml",
                Hash     = Encoding.UTF8.GetBytes(File.ReadAllText(modsConfigFileName))
            };

            // index: 0 - list Folders in Mods dir, 1 -list Folders in Steam dir , 2 - ModsConfig.xml
            ServerSettings.AppovedFolderAndConfig = new ModelModsFiles()
            {
                Files = new List <ModelFileInfo>()
                {
                    modsFolders,
                    steamFolders,
                    modsConfig,
                }
            };

            ServerSettings.ModsDirConfig = new ModelModsFiles()
            {
                IsSteam = false,
                Files   = new List <ModelFileInfo>()
                {
                    modsFolders
                },
                FoldersTree = FoldersTree.GenerateTree(ServerSettings.ModsDirectory),
            };

            ServerSettings.SteamDirConfig = new ModelModsFiles()
            {
                IsSteam = true,
                Files   = new List <ModelFileInfo>()
                {
                    steamFolders
                },
                FoldersTree = FoldersTree.GenerateTree(ServerSettings.SteamWorkShopModsDir),
            };
        }
コード例 #12
0
        private ModelModsFiles checkFiles(ModelModsFiles packet, ServiceContext context)
        {
            var modsDir        = packet.IsSteam ? ServerManager.ServerSettings.SteamWorkShopModsDir : ServerManager.ServerSettings.ModsDirectory;
            var NoApproveWorld = packet.IsSteam ? ApproveLoadWorldReason.ModsSteamWorkShopFail : ApproveLoadWorldReason.ModsFilesFail;
            var workDict       = packet.IsSteam ? ServerManager.SteamFilesDict : ServerManager.ModFilesDict;
            var foldersTree    = packet.IsSteam ? ServerManager.ServerSettings.SteamDirConfig.FoldersTree : ServerManager.ServerSettings.ModsDirConfig.FoldersTree;

            var result = new List <ModelFileInfo>();

            var allServerFiles = new HashSet <string>(workDict.Keys);

            foreach (var file in packet.Files)
            {
                if (workDict.TryGetValue(file.FileName, out ModelFileInfo fileInfo))
                {
                    allServerFiles.Remove(file.FileName); //

                    if (!ModelFileInfo.UnsafeByteArraysEquale(file.Hash, fileInfo.Hash))
                    {
                        // read file for send to Client
                        // файл  найден, но хеши не совпадают, необходимо заменить файл
                        result.Add(GetFile(modsDir, fileInfo.FileName));
                    }
                }
                else
                {
                    // mark file for delete
                    // Если файл с таким именем не найден, помечаем файл на удаление
                    file.Hash = null;
                    result.Add(file);
                }
            }

            lock (context.Player)
            {
                // проверяем в обратном порядке: что бы у клиенты были все файлы
                if (allServerFiles.Any())
                {
                    context.Player.ApproveLoadWorldReason = context.Player.ApproveLoadWorldReason | ApproveLoadWorldReason.NotAllFilesOnClient;
                    foreach (var fileName in allServerFiles)
                    {
                        result.Add(GetFile(modsDir, fileName));
                    }
                }

                // Если файлы не прошли проверку, помечаем флагом, запрет загрузки мира
                if (result.Any())
                {
                    context.Player.ApproveLoadWorldReason = context.Player.ApproveLoadWorldReason | NoApproveWorld;
                }
            }

            if (!result.Any())
            {
                // микроптимизация: если файлы не будут восстанавливаться, не отправляем обратно список папок
                // на восстановление ( десериализацию папок также тратится время)
                foldersTree = new FoldersTree();
            }

            return(new ModelModsFiles()
            {
                Files = result,
                IsSteam = packet.IsSteam,
                FoldersTree = foldersTree
            });
        }
コード例 #13
0
 /// <summary>
 /// Initialises a new instance of the <see cref="ForumsView"/> class.
 /// </summary>
 /// <param name="foldersTree">The parent forum view</param>
 public ForumsView(FoldersTree foldersTree) : base("Forums")
 {
     FoldersTree = foldersTree;
     InitializeComponent();
 }
コード例 #14
0
ファイル: WelcomeView.cs プロジェクト: cixonline/cixreader
 public WelcomeView(FoldersTree foldersTree) : base("Welcome")
 {
     FoldersTree = foldersTree;
     InitializeComponent();
 }
コード例 #15
0
        /// <summary>
        /// Display the directory for the specified CategoryFolder
        /// </summary>
        public override bool ViewFromFolder(FolderBase folder, Address address, FolderOptions options)
        {
            if (folder != _currentFolder)
            {
                _currentFolder = folder;
                SortConversations();
            }

            // If an address is specified then it refers to a conversation ID that
            // needs to be selected. If it is not found, the first message is selected
            // instead.
            if (address != null && address.Scheme == "cixmailbox")
            {
                int selectedID;

                Int32.TryParse(address.Data, out selectedID);

                int selectedIndex;
                for (selectedIndex = 0; selectedIndex < _conversations.Count; ++selectedIndex)
                {
                    InboxConversation conversation = _conversations[selectedIndex];
                    if (conversation.RemoteID == selectedID)
                    {
                        break;
                    }
                }
                if (selectedIndex == _conversations.Count)
                {
                    selectedIndex = 0;
                }
                SelectedRow = selectedIndex;
                if (address.Unread)
                {
                    SelectedMessage.MarkUnread();
                }
                return(true);
            }

            // If options are specified then search for the next unread
            // in the list otherwise set the initial selection to something
            // useful.
            if (options == 0 && SelectedRow == -1)
            {
                SetInitialSelection();
            }
            else
            {
                int row = inboxConversations.SearchRow;
                if (row < 0 || options.HasFlag(FolderOptions.Reset))
                {
                    row = 0;
                }
                else if (_conversations.Count > 0)
                {
                    InboxConversation conversation = _conversations[row];
                    if (conversation.UnreadCount > 0)
                    {
                        conversation.MarkRead();
                    }
                }
                if (!FirstUnreadAfterRow(row, options))
                {
                    inboxConversations.SearchRow = 0;
                    return(false);
                }
            }

            FoldersTree.SetTopicName(_currentFolder.FullName);

            ActiveControl = inboxConversations;
            inboxConversations.Focus();
            return(true);
        }