<commit_before>﻿#region

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using UlteriusServer.TaskServer.Network.Messages;
using UlteriusServer.TaskServer.Services.Network;
using UlteriusServer.Utilities;
using UlteriusServer.Utilities.Files;
using UlteriusServer.WebSocketAPI.Authentication;
using static UlteriusServer.TaskServer.Network.PacketManager;
using File = System.IO.File;

#endregion

namespace UlteriusServer.TaskServer.Network.PacketHandlers
{
    public class FilePacketHandler : PacketHandler
    {
        private const int EVERYTHING_OK = 0;
        private const int EVERYTHING_ERROR_MEMORY = 1;
        private const int EVERYTHING_ERROR_IPC = 2;
        private const int EVERYTHING_ERROR_REGISTERCLASSEX = 3;
        private const int EVERYTHING_ERROR_CREATEWINDOW = 4;
        private const int EVERYTHING_ERROR_CREATETHREAD = 5;
        private const int EVERYTHING_ERROR_INVALIDINDEX = 6;
        private const int EVERYTHING_ERROR_INVALIDCALL = 7;

        private MessageBuilder _builder;
        private AuthClient _client;
        private Packet _packet;


        public void CreateFileTree()
        {
            var argumentSize = _packet.Args.Count;
            var path = _packet.Args[0].ToString();
            var deepWalk = false;
            if (argumentSize > 1)
            {
                deepWalk = (bool) _packet.Args[1];
            }
            var tree = new FileTree(path, deepWalk);
            _builder.WriteMessage(tree);
        }


        public long DirSize(DirectoryInfo d)
        {
            // Add file sizes.
            var fis = d.GetFiles();
            var size = fis.Sum(fi => fi.Length);
            // Add subdirectory sizes.
            var dis = d.GetDirectories();
            size += dis.Sum(di => DirSize(di));
            return size;
        }

        public void SearchFile()
        {
            ConfigureSearch();
            if (Process.GetProcessesByName("Everything").Length > 0)
            {
                var query = _packet.Args[0].ToString();
                var stopwatch = Stopwatch.StartNew();
                const int bufferSize = 260;
                var buffer = new StringBuilder(bufferSize);
                // set the search
                Everything_SetSearchW(query);
                //execute the query
                Everything_QueryW(true);
                var totalResults = Everything_GetNumResults();
                var searchResults = new List<string>();
                for (var index = 0; index < totalResults; index++)
                {
                    Everything_GetResultFullPathNameW(index, buffer, bufferSize);
                    var filePath = buffer.ToString();
                    searchResults.Add(filePath);
                }
                stopwatch.Stop();
                var searchGenerationTime = stopwatch.ElapsedMilliseconds;
                var data = new
                {
                    success = true,
                    searchGenerationTime,
                    totalResults,
                    searchResults
                };
                _builder.WriteMessage(data);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = "Everything is not running."
                };
                _builder.WriteMessage(error);
            }
        }

        private void ConfigureSearch()
        {
            var startupDirEndingWithSlash = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) +
                                            "\\";
            var resolvedDomainTimeFileName = startupDirEndingWithSlash + "Everything.dll";
            if (!File.Exists(resolvedDomainTimeFileName))
            {
                if (IntPtr.Size == 8)
                {
                    Console.WriteLine(@"x64 Everything Loaded");
                    if (File.Exists(startupDirEndingWithSlash + "Everything64.dll"))

                        File.Copy(startupDirEndingWithSlash + "Everything64.dll", resolvedDomainTimeFileName);
                }
                else
                {
                    Console.WriteLine(@"x86 Everything Loaded");
                    if (File.Exists(startupDirEndingWithSlash + "Everything32.dll"))
                        File.Copy(startupDirEndingWithSlash + "Everything32.dll", resolvedDomainTimeFileName);
                }
            }
        }


        public void RequestFile()
        {
            var path = _packet.Args[0].ToString();
            var password = _packet.Args[1].ToString();
            if (File.Exists(path))
            {
                var totalSize = new FileInfo(path).Length;
                ProcessFile(path, password, totalSize);
            }
            else
            {
                var data = new
                {
                    path,
                    fileValid = false
                };
                _builder.WriteMessage(data);
            }
        }

        public void RemoveFile()
        {
            var fileName = _packet.Args[0].ToString();
            var webPath = Settings.Get("WebServer").WebFilePath.ToString();
            var tempFolderPath = webPath + "temp\\";
            string[] filePaths = Directory.GetFiles(tempFolderPath, "*.*",
                SearchOption.TopDirectoryOnly);
            foreach (var file in filePaths)
            {
                var path = Path.GetFileName(file);
                if (path != null && path.Equals(fileName))
                {
                    if (File.Exists(file))
                    {
                        try
                        {
                            File.Delete(file);
                            var deleteData = new
                            {
                                deleted = true,
                                message = "File removed."
                            };
                            _builder.WriteMessage(deleteData);
                        }
                        catch (Exception e)
                        {
                            var deleteDataException = new
                            {
                                deleted = false,
                                message = e.Message
                            };
                            _builder.WriteMessage(deleteDataException);
                        }
                    }
                    else
                    {
                        var deleteData = new
                        {
                            deleted = false,
                            message = "File does not exist or cannot be deleted"
                        };
                        _builder.WriteMessage(deleteData);
                    }
                }
            }
        }

        public void ApproveFile()
        {
            var fileKey = _packet.Args[0].ToString();
            var destPath = _packet.Args[1].ToString();
            var password = _packet.Args[2].ToString();
            FileManager.AddFile(password, destPath, fileKey);
            var approved = new
            {
                fileApproved = true,
                message = "File added to whitelist"
            };
            _builder.WriteMessage(approved);
        }
<commit_msg>search try catches<commit_after>﻿#region

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using UlteriusServer.TaskServer.Network.Messages;
using UlteriusServer.TaskServer.Services.Network;
using UlteriusServer.Utilities;
using UlteriusServer.Utilities.Files;
using UlteriusServer.WebSocketAPI.Authentication;
using static UlteriusServer.TaskServer.Network.PacketManager;
using File = System.IO.File;

#endregion

namespace UlteriusServer.TaskServer.Network.PacketHandlers
{
    public class FilePacketHandler : PacketHandler
    {
        private const int EVERYTHING_OK = 0;
        private const int EVERYTHING_ERROR_MEMORY = 1;
        private const int EVERYTHING_ERROR_IPC = 2;
        private const int EVERYTHING_ERROR_REGISTERCLASSEX = 3;
        private const int EVERYTHING_ERROR_CREATEWINDOW = 4;
        private const int EVERYTHING_ERROR_CREATETHREAD = 5;
        private const int EVERYTHING_ERROR_INVALIDINDEX = 6;
        private const int EVERYTHING_ERROR_INVALIDCALL = 7;

        private MessageBuilder _builder;
        private AuthClient _client;
        private Packet _packet;


        public void CreateFileTree()
        {
            var argumentSize = _packet.Args.Count;
            var path = _packet.Args[0].ToString();
            var deepWalk = false;
            if (argumentSize > 1)
            {
                deepWalk = (bool) _packet.Args[1];
            }
            var tree = new FileTree(path, deepWalk);
            _builder.WriteMessage(tree);
        }


        public long DirSize(DirectoryInfo d)
        {
            // Add file sizes.
            var fis = d.GetFiles();
            var size = fis.Sum(fi => fi.Length);
            // Add subdirectory sizes.
            var dis = d.GetDirectories();
            size += dis.Sum(di => DirSize(di));
            return size;
        }

        public void SearchFile()
        {
            try
            {
                ConfigureSearch();
            }
            catch (Exception)
            {
                var error = new
                {
                    success = false,
                    message = "Everything failed to configure."
                };
                _builder.WriteMessage(error);
                return;
            }
            try
            {
                if (Process.GetProcessesByName("Everything").Length > 0)
                {
                    var query = _packet.Args[0].ToString();
                    Console.WriteLine(query);
                    var stopwatch = Stopwatch.StartNew();
                    const int bufferSize = 260;
                    var buffer = new StringBuilder(bufferSize);
                    // set the search
                    Everything_SetSearchW(query);
                    //execute the query
                    Everything_QueryW(true);
                    var totalResults = Everything_GetNumResults();
                    var searchResults = new List<string>();
                    for (var index = 0; index < totalResults; index++)
                    {
                        Everything_GetResultFullPathNameW(index, buffer, bufferSize);
                        var filePath = buffer.ToString();
                        searchResults.Add(filePath);
                    }
                    stopwatch.Stop();
                    var searchGenerationTime = stopwatch.ElapsedMilliseconds;
                    var data = new
                    {
                        success = true,
                        searchGenerationTime,
                        totalResults,
                        searchResults
                    };
                    _builder.WriteMessage(data);
                }
                else
                {
                    var error = new
                    {
                        success = false,
                        message = "Everything is not running."
                    };
                    _builder.WriteMessage(error);
                }
            }
            catch (Exception e)
            {

                var error = new
                {
                    success = false,
                    message = e.Message
                };
                _builder.WriteMessage(error);
            }
        }

        private void ConfigureSearch()
        {
            var startupDirEndingWithSlash = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) +
                                            "\\";
            var resolvedDomainTimeFileName = startupDirEndingWithSlash + "Everything.dll";
            if (!File.Exists(resolvedDomainTimeFileName))
            {
                if (IntPtr.Size == 8)
                {
                    Console.WriteLine(@"x64 Everything Loaded");
                    if (File.Exists(startupDirEndingWithSlash + "Everything64.dll"))

                        File.Copy(startupDirEndingWithSlash + "Everything64.dll", resolvedDomainTimeFileName);
                }
                else
                {
                    Console.WriteLine(@"x86 Everything Loaded");
                    if (File.Exists(startupDirEndingWithSlash + "Everything32.dll"))
                        File.Copy(startupDirEndingWithSlash + "Everything32.dll", resolvedDomainTimeFileName);
                }
            }
        }


        public void RequestFile()
        {
            var path = _packet.Args[0].ToString();
            var password = _packet.Args[1].ToString();
            if (File.Exists(path))
            {
                var totalSize = new FileInfo(path).Length;
                ProcessFile(path, password, totalSize);
            }
            else
            {
                var data = new
                {
                    path,
                    fileValid = false
                };
                _builder.WriteMessage(data);
            }
        }

        public void RemoveFile()
        {
            var fileName = _packet.Args[0].ToString();
            var webPath = Settings.Get("WebServer").WebFilePath.ToString();
            var tempFolderPath = webPath + "temp\\";
            string[] filePaths = Directory.GetFiles(tempFolderPath, "*.*",
                SearchOption.TopDirectoryOnly);
            foreach (var file in filePaths)
            {
                var path = Path.GetFileName(file);
                if (path != null && path.Equals(fileName))
                {
                    if (File.Exists(file))
                    {
                        try
                        {
                            File.Delete(file);
                            var deleteData = new
                            {
                                deleted = true,
                                message = "File removed."
                            };
                            _builder.WriteMessage(deleteData);
                        }
                        catch (Exception e)
                        {
                            var deleteDataException = new
                            {
                                deleted = false,
                                message = e.Message
                            };
                            _builder.WriteMessage(deleteDataException);
                        }
                    } 
                    else
                    {
                        var deleteData = new
                        {
                            deleted = false,
                            message = "File does not exist or cannot be deleted"
                        };
                        _builder.WriteMessage(deleteData);
                    }
                }
            }
        }

        public void ApproveFile()
        {
            var fileKey = _packet.Args[0].ToString();
            var destPath = _packet.Args[1].ToString();
            var password = _packet.Args[2].ToString();
            FileManager.AddFile(password, destPath, fileKey);
            var approved = new
            {
                fileApproved = true,
                message = "File added to whitelist"
            };
            _builder.WriteMessage(approved);
        }

{'fraction_non_alphanumeric': 0.07581823959326342, 'fraction_numerical': 0.00457578646329838, 'mean_word_length': 1.1415351115949919, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4498163', 'n_tokens_mistral': 3720, 'n_tokens_neox': 3432, 'n_words': 764}