diff --git a/.editorconfig b/.editorconfig
new file mode 100644
index 0000000..b872f8f
--- /dev/null
+++ b/.editorconfig
@@ -0,0 +1,13 @@
+[*.cs]
+
+# IDE0058: Значение выражения никогда не используется
+dotnet_diagnostic.IDE0058.severity = none
+
+# IDE0008: Использование явного типа
+dotnet_diagnostic.IDE0008.severity = none
+
+# IDE0040: Добавьте модификаторы доступности
+dotnet_diagnostic.IDE0040.severity = none
+
+# Default severity for analyzer diagnostics with category 'Style'
+dotnet_analyzer_diagnostic.category-Style.severity = none
diff --git a/.old 0/dtlauncher-client/App.config b/.old 0/dtlauncher-client/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 0/dtlauncher-client/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 0/dtlauncher-client/Program.cs b/.old 0/dtlauncher-client/Program.cs
new file mode 100644
index 0000000..211d681
--- /dev/null
+++ b/.old 0/dtlauncher-client/Program.cs
@@ -0,0 +1,153 @@
+using DTLib;
+using System;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+
+namespace dtlauncher_client
+{
+ class Program
+ {
+ static ConsoleGUI gui = new ConsoleGUI(90, 30);
+ static Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ static string logfile = $"logs\\client-{DateTime.UtcNow}.log".Replace(':', '-').Replace(' ', '_');
+ static bool enter = false;
+
+ static void Main()
+ {
+ try
+ {
+ Console.Title = "dtlauncher";
+ gui.ReadFromFile("gui\\start_tab.gui");
+ gui.ShowAll();
+ NetWork.Log += Log;
+ // подключение к серверу
+ /*mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(
+ FileWork.ReadFromConfig("client.cfg", "central server ip"))[0],
+ Convert.ToInt32(FileWork.ReadFromConfig("client.cfg", "central server port"))));
+ mainSocket.ReceiveTimeout = 5000;
+ gui.ChangeLine(3, 4, 'y', "trying to connect to the main server...");
+ string recieved = mainSocket.Request("new user connection try").ToStr();
+ if (recieved != "new user connection created")
+ throw new Exception("can't connect to the main server");
+ gui.ChangeLine(3, 5, 'g', "connected to the main server");
+ //NetWork.RequestServersList(mainSocket);
+ gui.ResetCursor();*/
+ Input();
+ }
+ catch (Exception e)
+ {
+ Log("r", "\nerror:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ Console.ReadLine();
+ }
+ }
+
+ static string inputText = "";
+ static void Input()
+ {
+ while (true)
+ {
+ ConsoleKeyInfo readKeyResult = Console.ReadKey(true); // Считывание ввода
+ switch (readKeyResult.Key)
+ {
+ case ConsoleKey.F1:
+ gui.ReadFromFile("gui\\files_tab.gui");
+ for (sbyte i = 3; i < 89; i++)
+ gui.ChangeColor(i, 1, 'w');
+ for (sbyte i = 3; i < 13; i++)
+ gui.ChangeColor(i, 1, 'c');
+ gui.UpdateAll();
+ break;
+ case ConsoleKey.F2:
+ gui.ReadFromFile("gui\\servers_tab.gui");
+ for (sbyte i = 3; i < 89; i++)
+ gui.ChangeColor(i, 1, 'w');
+ for (sbyte i = 19; i < 31; i++)
+ gui.ChangeColor(i, 1, 'c');
+ gui.UpdateAll();
+ break;
+ case ConsoleKey.F3:
+ gui.ReadFromFile("gui\\settings_tab.gui");
+ for (sbyte i = 3; i < 89; i++)
+ gui.ChangeColor(i, 1, 'w');
+ for (sbyte i = 37; i < 50; i++)
+ gui.ChangeColor(i, 1, 'c');
+ gui.UpdateAll();
+ break;
+ case ConsoleKey.F4:
+ return;
+ case ConsoleKey.F5:
+ Console.Clear();
+ gui.ShowAll();
+ break;
+ case ConsoleKey.F6:
+ break;
+ /*case ConsoleKey.F7:
+ break;
+ case ConsoleKey.F8:
+ break;
+ case ConsoleKey.F9:
+ break;
+ case ConsoleKey.F10:
+ break;
+ case ConsoleKey.F11:
+ break;
+ case ConsoleKey.F12:
+ break;
+ case ConsoleKey.UpArrow:
+ break;
+ case ConsoleKey.DownArrow:
+ break;
+ case ConsoleKey.LeftArrow:
+ break;
+ case ConsoleKey.RightArrow:
+ break;
+ case ConsoleKey.PageUp:
+ break;
+ case ConsoleKey.PageDown:
+ break;
+ case ConsoleKey.Home:
+ break;
+ case ConsoleKey.End:
+ break;
+ case ConsoleKey.Escape:
+ break;
+ case ConsoleKey.Enter:
+ enter = true;
+ break;
+ case ConsoleKey.Backspace:
+ if (inputText.Length > 0)
+ inputText = inputText.Remove(inputText.Length - 1);
+ break;*/
+ default:
+ inputText += readKeyResult.KeyChar;
+ break;
+ }
+ }
+ }
+ static void Log(string color, string msg)
+ {
+ ColoredText.WriteColored(color, msg);
+ FileWork.Log(logfile, msg);
+ }
+
+ static void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ ColoredText.WriteColored(input);
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ str += input[++i];
+ }
+ FileWork.Log(logfile, str);
+ }
+ else
+ {
+ throw new Exception("error in Log(): every text string must have color string before");
+ }
+ }
+ }
+}
diff --git a/.old 0/dtlauncher-client/Properties/AssemblyInfo.cs b/.old 0/dtlauncher-client/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..a46c9ad
--- /dev/null
+++ b/.old 0/dtlauncher-client/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные с этой сборкой.
+[assembly: AssemblyTitle("dtlauncher-client")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-client")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM задайте для атрибута ComVisible этого типа значение true.
+[assembly: ComVisible(false)]
+
+// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
+[assembly: Guid("eab95dec-0d9b-4e17-8875-0159358ac240")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 0/dtlauncher-client/dtlauncher-client.csproj b/.old 0/dtlauncher-client/dtlauncher-client.csproj
new file mode 100644
index 0000000..541ab01
--- /dev/null
+++ b/.old 0/dtlauncher-client/dtlauncher-client.csproj
@@ -0,0 +1,52 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {EAB95DEC-0D9B-4E17-8875-0159358AC240}
+ Exe
+ dtlauncher_client
+ dtlauncher-client
+ v4.8
+ 512
+ true
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+ del /f /q dtlauncher-client.exe.config
+
+
\ No newline at end of file
diff --git a/.old 0/dtlauncher-server/App.config b/.old 0/dtlauncher-server/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 0/dtlauncher-server/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 0/dtlauncher-server/Program.cs b/.old 0/dtlauncher-server/Program.cs
new file mode 100644
index 0000000..f0e9b2d
--- /dev/null
+++ b/.old 0/dtlauncher-server/Program.cs
@@ -0,0 +1,145 @@
+using DTLib;
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using static DTLib.NetWork;
+
+namespace dtlauncher_server
+{
+ class Program
+ {
+ static ConsoleGUI gui = new ConsoleGUI(90, 30);
+ static string logfile = $"logs\\client-{DateTime.UtcNow}.log".Replace(':', '-').Replace(' ', '_');
+ static Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ //static Dictionary users = new Dictionary();
+
+ static void Main(string[] args)
+ {
+ while (true)
+ {
+ try
+ {
+ Console.Title = "dtlauncher server";
+ gui.ReadFromFile("gui\\main.gui");
+ gui.ShowAll();
+ NetWork.Log += Log;
+ Log("b", $"<{FileWork.ReadFromConfig("server.cfg", "server ip")}> : <{Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))}>\n");
+ mainSocket.Bind(new IPEndPoint(IPAddress.Parse(
+ FileWork.ReadFromConfig("server.cfg", "server ip")),
+ Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))));
+ Log("g", "server started succesfully\n");
+ //Thread userCheckThread = new Thread(CloseUnusedUserThreads);
+ //userCheckThread.Start();
+ try
+ {
+ mainSocket.Listen(200);
+ while (true)
+ {
+ var userSocket = mainSocket.Accept();
+ var userThread = new Thread(new ParameterizedThreadStart(UserStart));
+ //users.Add(userSocket, userThread);
+ userThread.Start(userSocket);
+ }
+ }
+ catch (Exception ex)
+ {
+ Log("r", $"handler error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ }
+ catch (Exception ex)
+ {
+ if (mainSocket.IsBound) mainSocket.CloseSocket();
+ Log("r", $"Main() error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ Thread.Sleep(1500);
+ }
+ }
+
+ static void Log(string color, string msg)
+ {
+ ColoredText.WriteColored(color, msg);
+ FileWork.Log(logfile, msg);
+ }
+
+ static void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ ColoredText.WriteColored(input);
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ str += input[++i];
+ }
+ FileWork.Log(logfile, str);
+ }
+ else
+ {
+ throw new Exception("error in Log(): every text string must have color string before");
+ }
+ }
+
+ static void UserStart(dynamic _handlerSocket)
+ {
+ Socket handlerSocket = (Socket)_handlerSocket;
+ try
+ {
+ string recieved = handlerSocket.GetData().ToStr();
+ if (recieved == "new user connection try")
+ {
+ handlerSocket.Send("new user connection created".ToBytes());
+ while (true)
+ {
+ recieved = handlerSocket.GetData().ToStr();
+ switch (recieved)
+ {
+ // ответ на NetWork.Ping()
+ case "ping":
+ handlerSocket.Send("pong".ToBytes());
+ break;
+ // отправка списка активных серверов
+ case "requesting servers list":
+
+ break;
+ case "requesting file":
+ recieved = handlerSocket.GetData().ToStr();
+ break;
+ default:
+ throw new Exception("unknown request: " + recieved);
+ }
+ }
+ }
+
+ else
+ {
+ throw new Exception("incorrect connection try");
+ }
+
+ }
+ catch (Exception ex)
+ {
+ Log("y", $"UserStart() error:\n message:\n {ex.Message}\n");
+ handlerSocket.CloseSocket();
+ Thread.CurrentThread.Abort();
+ }
+ }
+
+ /*static void CloseUnusedUserThreads()
+ {
+ while (true)
+ {
+ foreach (Socket s in users.Keys)
+ {
+ if (!NetWork.Ping(s))
+ {
+ Log("y", "closing unused user thread\n");
+ users[s].Abort();
+ users.Remove(s);
+ }
+ }
+ Thread.Sleep(300000);
+ }
+ }*/
+ }
+}
diff --git a/.old 0/dtlauncher-server/Properties/AssemblyInfo.cs b/.old 0/dtlauncher-server/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..13ba653
--- /dev/null
+++ b/.old 0/dtlauncher-server/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные с этой сборкой.
+[assembly: AssemblyTitle("dtlauncher-server")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-server")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM задайте для атрибута ComVisible этого типа значение true.
+[assembly: ComVisible(false)]
+
+// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
+[assembly: Guid("4f183e7c-a23d-4f5f-933c-f9f32bdc403a")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 0/dtlauncher-server/dtlauncher-server.csproj b/.old 0/dtlauncher-server/dtlauncher-server.csproj
new file mode 100644
index 0000000..38fca35
--- /dev/null
+++ b/.old 0/dtlauncher-server/dtlauncher-server.csproj
@@ -0,0 +1,56 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {4F183E7C-A23D-4F5F-933C-F9F32BDC403A}
+ Exe
+ dtlauncher_server
+ dtlauncher-server
+ v4.8
+ 512
+ true
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ DEBUG;TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+
+
+
+
+ del /f /q dtlauncher-server.exe.config
+
+
\ No newline at end of file
diff --git a/.old 0/dtlauncher.sln b/.old 0/dtlauncher.sln
new file mode 100644
index 0000000..85d73f0
--- /dev/null
+++ b/.old 0/dtlauncher.sln
@@ -0,0 +1,36 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30907.101
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-client", "dtlauncher-client\dtlauncher-client.csproj", "{EAB95DEC-0D9B-4E17-8875-0159358AC240}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-server", "dtlauncher-server\dtlauncher-server.csproj", "{4F183E7C-A23D-4F5F-933C-F9F32BDC403A}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Build|Any CPU = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {EAB95DEC-0D9B-4E17-8875-0159358AC240}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {EAB95DEC-0D9B-4E17-8875-0159358AC240}.Build|Any CPU.Build.0 = Build|Any CPU
+ {4F183E7C-A23D-4F5F-933C-F9F32BDC403A}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {4F183E7C-A23D-4F5F-933C-F9F32BDC403A}.Build|Any CPU.Build.0 = Build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.Build.0 = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {E6569C0C-DD32-4F7D-AD4C-DBC5434D2F8C}
+ EndGlobalSection
+EndGlobal
diff --git a/.old 1/dtlauncher-client/App.config b/.old 1/dtlauncher-client/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 1/dtlauncher-client/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 1/dtlauncher-client/Program.cs b/.old 1/dtlauncher-client/Program.cs
new file mode 100644
index 0000000..6969987
--- /dev/null
+++ b/.old 1/dtlauncher-client/Program.cs
@@ -0,0 +1,161 @@
+using DTLib;
+using System;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using static DTLib.NetWork;
+
+namespace dtlauncher_client
+{
+ class Program
+ {
+ static DTLib.ConsoleGUI.Window gui = new DTLib.ConsoleGUI.Window(90, 30);
+ static Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ static string logfile = $"logs\\client-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+ //static bool enter = false;
+ //static string inputText = "";
+
+ static void Main()
+ {
+ try
+ {
+ Console.Title = "dtlauncher";
+ gui.ReadFromFile("gui\\start_tab.gui");
+ gui.ShowAll();
+ NetWork.Log += Log;
+ Log("b", "launcher is starting\n");
+ // подключение к серверу
+ mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(
+ FileWork.ReadFromConfig("client.cfg", "central server ip"))[0],
+ Convert.ToInt32(FileWork.ReadFromConfig("client.cfg", "central server port"))));
+ mainSocket.ReceiveTimeout = 2000;
+ gui.ChangeLine(3, 4, 'y', "trying to connect to the main server...");
+ string recieved = mainSocket.Request("new user connection try").ToStr();
+ if (recieved != "new user connection created")
+ throw new Exception("can't connect to the main server");
+ gui.ChangeLine(3, 5, 'g', "connected to the main server");
+ //NetWork.RequestServersList(mainSocket);
+ gui.ResetCursor();
+ Input();
+ }
+ catch (System.Threading.ThreadAbortException)
+ {
+
+ }
+ catch (Exception e)
+ {
+ Log("r", "\nerror:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ Console.ResetColor();
+ Console.ReadLine();
+ }
+ }
+
+ static void Input()
+ {
+ while (true)
+ {
+ ConsoleKeyInfo readKeyResult = Console.ReadKey(true); // Считывание ввода
+ switch (readKeyResult.Key)
+ {
+ case ConsoleKey.F1:
+ gui.ReadFromFile("gui\\files_tab.gui");
+ for (sbyte i = 3; i < 89; i++)
+ gui.ChangeColor(i, 1, 'w');
+ for (sbyte i = 3; i < 13; i++)
+ gui.ChangeColor(i, 1, 'c');
+ gui.UpdateAll();
+ break;
+ case ConsoleKey.F2:
+ gui.ReadFromFile("gui\\servers_tab.gui");
+ for (sbyte i = 3; i < 89; i++)
+ gui.ChangeColor(i, 1, 'w');
+ for (sbyte i = 19; i < 31; i++)
+ gui.ChangeColor(i, 1, 'c');
+ gui.UpdateAll();
+ break;
+ case ConsoleKey.F3:
+ gui.ReadFromFile("gui\\settings_tab.gui");
+ for (sbyte i = 3; i < 89; i++)
+ gui.ChangeColor(i, 1, 'w');
+ for (sbyte i = 37; i < 50; i++)
+ gui.ChangeColor(i, 1, 'c');
+ gui.UpdateAll();
+ break;
+ case ConsoleKey.F4:
+ Log("m", SimpleConverter.Truncate(9 / 4).ToString());
+ break;
+ case ConsoleKey.F5:
+ Console.Clear();
+ gui.ShowAll();
+ break;
+ case ConsoleKey.F6:
+ mainSocket.FSP_Download(new FSP_FileObject("share\\file.arc", "downloads\\file.arc"));
+ break;
+ case ConsoleKey.F7:
+ break;
+ /*case ConsoleKey.F8:
+ break;
+ case ConsoleKey.F9:
+ break;
+ case ConsoleKey.F10:
+ break;
+ case ConsoleKey.F11:
+ break;
+ case ConsoleKey.F12:
+ break;
+ case ConsoleKey.UpArrow:
+ break;
+ case ConsoleKey.DownArrow:
+ break;
+ case ConsoleKey.LeftArrow:
+ break;
+ case ConsoleKey.RightArrow:
+ break;
+ case ConsoleKey.PageUp:
+ break;
+ case ConsoleKey.PageDown:
+ break;
+ case ConsoleKey.Home:
+ break;
+ case ConsoleKey.End:
+ break;
+ case ConsoleKey.Escape:
+ break;
+ case ConsoleKey.Enter:
+ enter = true;
+ break;
+ case ConsoleKey.Backspace:
+ if (inputText.Length > 0)
+ inputText = inputText.Remove(inputText.Length - 1);
+ break;*/
+ default:
+ //inputText += readKeyResult.KeyChar;
+ break;
+ }
+ }
+ }
+ static void Log(string color, string msg)
+ {
+ ColoredText.WriteColored(color, msg);
+ FileWork.Log(logfile, msg);
+ }
+
+ static void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ ColoredText.WriteColored(input);
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ str += input[++i];
+ }
+ FileWork.Log(logfile, str);
+ }
+ else
+ {
+ throw new Exception("error in Log(): every text string must have color string before");
+ }
+ }
+ }
+}
diff --git a/.old 1/dtlauncher-client/Properties/AssemblyInfo.cs b/.old 1/dtlauncher-client/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..a46c9ad
--- /dev/null
+++ b/.old 1/dtlauncher-client/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные с этой сборкой.
+[assembly: AssemblyTitle("dtlauncher-client")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-client")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM задайте для атрибута ComVisible этого типа значение true.
+[assembly: ComVisible(false)]
+
+// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
+[assembly: Guid("eab95dec-0d9b-4e17-8875-0159358ac240")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 1/dtlauncher-client/bin.rar b/.old 1/dtlauncher-client/bin.rar
new file mode 100644
index 0000000..80669e7
Binary files /dev/null and b/.old 1/dtlauncher-client/bin.rar differ
diff --git a/.old 1/dtlauncher-client/dtlauncher-client.csproj b/.old 1/dtlauncher-client/dtlauncher-client.csproj
new file mode 100644
index 0000000..541ab01
--- /dev/null
+++ b/.old 1/dtlauncher-client/dtlauncher-client.csproj
@@ -0,0 +1,52 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {EAB95DEC-0D9B-4E17-8875-0159358AC240}
+ Exe
+ dtlauncher_client
+ dtlauncher-client
+ v4.8
+ 512
+ true
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+ del /f /q dtlauncher-client.exe.config
+
+
\ No newline at end of file
diff --git a/.old 1/dtlauncher-client/dtlauncher/DTLib.dll b/.old 1/dtlauncher-client/dtlauncher/DTLib.dll
new file mode 100644
index 0000000..9dcb486
Binary files /dev/null and b/.old 1/dtlauncher-client/dtlauncher/DTLib.dll differ
diff --git a/.old 1/dtlauncher-client/dtlauncher/client.cfg b/.old 1/dtlauncher-client/dtlauncher/client.cfg
new file mode 100644
index 0000000..4248c8f
--- /dev/null
+++ b/.old 1/dtlauncher-client/dtlauncher/client.cfg
@@ -0,0 +1,2 @@
+central server ip: m1net.keenetic.pro
+central server port: 20000
\ No newline at end of file
diff --git a/.old 1/dtlauncher-client/dtlauncher/dtlauncher-client.exe b/.old 1/dtlauncher-client/dtlauncher/dtlauncher-client.exe
new file mode 100644
index 0000000..11715bb
Binary files /dev/null and b/.old 1/dtlauncher-client/dtlauncher/dtlauncher-client.exe differ
diff --git a/.old 1/dtlauncher-client/dtlauncher/gui/files_tab.gui b/.old 1/dtlauncher-client/dtlauncher/gui/files_tab.gui
new file mode 100644
index 0000000..b04b4b6
--- /dev/null
+++ b/.old 1/dtlauncher-client/dtlauncher/gui/files_tab.gui
@@ -0,0 +1,61 @@
+┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
+┃ [F1] files ┃ [F2] servers ┃ [F3] settings ┃ [F4] exit ┃ [F5] refresh ┃
+┣━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━┫
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┃ │ ┃
+┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┷━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
+
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
diff --git a/.old 1/dtlauncher-client/dtlauncher/gui/servers_tab.gui b/.old 1/dtlauncher-client/dtlauncher/gui/servers_tab.gui
new file mode 100644
index 0000000..fa90ecc
--- /dev/null
+++ b/.old 1/dtlauncher-client/dtlauncher/gui/servers_tab.gui
@@ -0,0 +1,61 @@
+┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
+┃ [F1] files ┃ [F2] servers ┃ [F3] settings ┃ [F4] exit ┃ [F5] refresh ┃
+┣━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━┫
+┃ name ping ┃
+┠────────────────────────────────────────────────────────────────────────────────────────┨
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
+
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
diff --git a/.old 1/dtlauncher-client/dtlauncher/gui/settings_tab.gui b/.old 1/dtlauncher-client/dtlauncher/gui/settings_tab.gui
new file mode 100644
index 0000000..1730a22
--- /dev/null
+++ b/.old 1/dtlauncher-client/dtlauncher/gui/settings_tab.gui
@@ -0,0 +1,61 @@
+┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
+┃ [F1] files ┃ [F2] servers ┃ [F3] settings ┃ [F4] exit ┃ [F5] refresh ┃
+┣━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━┫
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
+
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
diff --git a/.old 1/dtlauncher-client/dtlauncher/gui/start_tab.gui b/.old 1/dtlauncher-client/dtlauncher/gui/start_tab.gui
new file mode 100644
index 0000000..1730a22
--- /dev/null
+++ b/.old 1/dtlauncher-client/dtlauncher/gui/start_tab.gui
@@ -0,0 +1,61 @@
+┏━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━┓
+┃ [F1] files ┃ [F2] servers ┃ [F3] settings ┃ [F4] exit ┃ [F5] refresh ┃
+┣━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━┻━━━━━━━━━━━━━━━━━━━┫
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┃ ┃
+┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
+
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
+wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww
diff --git a/.old 1/dtlauncher-server/App.config b/.old 1/dtlauncher-server/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 1/dtlauncher-server/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 1/dtlauncher-server/Program.cs b/.old 1/dtlauncher-server/Program.cs
new file mode 100644
index 0000000..ea60a46
--- /dev/null
+++ b/.old 1/dtlauncher-server/Program.cs
@@ -0,0 +1,151 @@
+using DTLib;
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using static DTLib.NetWork;
+
+namespace dtlauncher_server
+{
+ class Program
+ {
+ //static ConsoleGUI gui = new ConsoleGUI(90, 30);
+ static string logfile = $"logs\\server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+ static Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ //static Dictionary users = new Dictionary();
+
+ static void Main(string[] args)
+ {
+ while (true)
+ {
+ try
+ {
+ Console.Title = "dtlauncher server";
+ //gui.ReadFromFile("gui\\main.gui");
+ //gui.ShowAll();
+ NetWork.Log += Log;
+ Log("b", $"<{FileWork.ReadFromConfig("server.cfg", "server ip")}> : <{Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))}>\n");
+ mainSocket.Bind(new IPEndPoint(IPAddress.Parse(
+ FileWork.ReadFromConfig("server.cfg", "server ip")),
+ Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))));
+ Log("g", "server started succesfully\n");
+ //Thread userCheckThread = new Thread(CloseUnusedUserThreads);
+ //userCheckThread.Start();
+ try
+ {
+ mainSocket.Listen(200);
+ while (true)
+ {
+ var userSocket = mainSocket.Accept();
+ var userThread = new Thread(new ParameterizedThreadStart(UserStart));
+ //users.Add(userSocket, userThread);
+ userThread.Start(userSocket);
+ }
+ }
+ catch (Exception ex)
+ {
+ Log("r", $"handler error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ }
+ catch (ThreadAbortException)
+ {
+
+ }
+ catch (Exception ex)
+ {
+ if (mainSocket.IsBound) mainSocket.CloseSocket();
+ Log("r", $"Main() error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ Thread.Sleep(1500);
+ }
+ }
+
+ static void Log(string color, string msg)
+ {
+ ColoredText.WriteColored(color, "[" + DateTime.Now.ToString() + "]: " + msg);
+ FileWork.Log(logfile, msg);
+ }
+
+ static void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ input[1] = "[" + DateTime.Now.ToString() + "]: " + input[1];
+ ColoredText.WriteColored(input);
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ str += input[++i];
+ }
+ FileWork.Log(logfile, str);
+ }
+ else
+ {
+ throw new Exception("error in Log(): every text string must have color string before");
+ }
+ }
+
+ static void UserStart(dynamic _handlerSocket)
+ {
+ Socket handlerSocket = (Socket)_handlerSocket;
+ Log("g", "user connected\n");
+ try
+ {
+ string recieved = handlerSocket.GetData().ToStr();
+ if (recieved == "new user connection try")
+ {
+ handlerSocket.Send("new user connection created".ToBytes());
+ while (true)
+ {
+ recieved = handlerSocket.GetData().ToStr();
+ switch (recieved)
+ {
+ // ответ на NetWork.Ping()
+ case "ping":
+ handlerSocket.Send("pong".ToBytes());
+ break;
+ // отправка списка активных серверов
+ case "requesting servers list":
+
+ break;
+ case "requesting file download":
+ handlerSocket.FSP_Upload();
+ break;
+ default:
+ throw new Exception("unknown request: " + recieved);
+ }
+ }
+ }
+
+ else
+ {
+ throw new Exception("incorrect connection try");
+ }
+
+ }
+ catch (Exception ex)
+ {
+ Log("y", $"UserStart() error:\n message:\n {ex.Message}\n{ex.StackTrace}\n");
+ handlerSocket.CloseSocket();
+ Thread.CurrentThread.Abort();
+ }
+ }
+
+ /*static void CloseUnusedUserThreads()
+ {
+ while (true)
+ {
+ foreach (Socket s in users.Keys)
+ {
+ if (!NetWork.Ping(s))
+ {
+ Log("y", "closing unused user thread\n");
+ users[s].Abort();
+ users.Remove(s);
+ }
+ }
+ Thread.Sleep(300000);
+ }
+ }*/
+ }
+}
diff --git a/.old 1/dtlauncher-server/Properties/AssemblyInfo.cs b/.old 1/dtlauncher-server/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..13ba653
--- /dev/null
+++ b/.old 1/dtlauncher-server/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные с этой сборкой.
+[assembly: AssemblyTitle("dtlauncher-server")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-server")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM задайте для атрибута ComVisible этого типа значение true.
+[assembly: ComVisible(false)]
+
+// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
+[assembly: Guid("4f183e7c-a23d-4f5f-933c-f9f32bdc403a")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 1/dtlauncher-server/dtlauncher-server.csproj b/.old 1/dtlauncher-server/dtlauncher-server.csproj
new file mode 100644
index 0000000..38fca35
--- /dev/null
+++ b/.old 1/dtlauncher-server/dtlauncher-server.csproj
@@ -0,0 +1,56 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {4F183E7C-A23D-4F5F-933C-F9F32BDC403A}
+ Exe
+ dtlauncher_server
+ dtlauncher-server
+ v4.8
+ 512
+ true
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ DEBUG;TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+
+
+
+
+ del /f /q dtlauncher-server.exe.config
+
+
\ No newline at end of file
diff --git a/.old 1/dtlauncher.sln b/.old 1/dtlauncher.sln
new file mode 100644
index 0000000..85d73f0
--- /dev/null
+++ b/.old 1/dtlauncher.sln
@@ -0,0 +1,36 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30907.101
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-client", "dtlauncher-client\dtlauncher-client.csproj", "{EAB95DEC-0D9B-4E17-8875-0159358AC240}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-server", "dtlauncher-server\dtlauncher-server.csproj", "{4F183E7C-A23D-4F5F-933C-F9F32BDC403A}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Build|Any CPU = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {EAB95DEC-0D9B-4E17-8875-0159358AC240}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {EAB95DEC-0D9B-4E17-8875-0159358AC240}.Build|Any CPU.Build.0 = Build|Any CPU
+ {4F183E7C-A23D-4F5F-933C-F9F32BDC403A}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {4F183E7C-A23D-4F5F-933C-F9F32BDC403A}.Build|Any CPU.Build.0 = Build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.Build.0 = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {E6569C0C-DD32-4F7D-AD4C-DBC5434D2F8C}
+ EndGlobalSection
+EndGlobal
diff --git a/.old 2/DTLib/ColoredText.cs b/.old 2/DTLib/ColoredText.cs
new file mode 100644
index 0000000..a8147cd
--- /dev/null
+++ b/.old 2/DTLib/ColoredText.cs
@@ -0,0 +1,122 @@
+using System;
+
+namespace DTLib
+{
+ //
+ // изменение цвета текста в консоли
+ //
+ static public class ColoredText
+ {
+ // присвоение цвета тексту
+ static public ConsoleColor ParseColor(string color)
+ {
+ switch (color)
+ {
+ //case "magneta":
+ case "m":
+ return ConsoleColor.Magenta;
+ //case "green":
+ case "g":
+ return ConsoleColor.Green;
+ //case "red":
+ case "r":
+ return ConsoleColor.Red;
+ //case "yellow":
+ case "y":
+ return ConsoleColor.Yellow;
+ //case "white":
+ case "w":
+ return ConsoleColor.White;
+ //case "blue":
+ case "b":
+ return ConsoleColor.Blue;
+ //case "cyan":
+ case "c":
+ return ConsoleColor.Cyan;
+ //case "gray":
+ case "a":
+ return ConsoleColor.Gray;
+ //case "black":
+ case "t":
+ return ConsoleColor.Black;
+ default:
+ throw new Exception("incorrect color: " + color);
+ }
+ }
+
+ // вывод цветного текста
+ static public void WriteColored(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ var c = ParseColor(input[i]);
+ if (Console.ForegroundColor != c)
+ {
+ Console.Write(str);
+ Console.ForegroundColor = c;
+ str = "";
+ }
+ str += input[++i];
+ }
+ if (str != "")
+ Console.Write(str);
+ }
+ else
+ {
+ throw new Exception("error in WriteColored(): every text string must have color string before");
+ }
+ }
+
+ /*static public void WriteColoredB(string[] input)
+ {
+ if (input.Length % 3 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ var f = ParseColor(input[i]);
+ var b = ParseColor(input[++i]);
+ if (Console.ForegroundColor != f || Console.BackgroundColor != b)
+ {
+ Console.Write(str);
+ Console.ForegroundColor = f;
+ Console.BackgroundColor = b;
+ str = "";
+ }
+ str += input[++i];
+ }
+ if (str != "")
+ Console.Write(str);
+ }
+ else
+ {
+ throw new Exception("error in WriteColored(): every text string must have color string before");
+ }
+ }*/
+
+ static public void WriteColored(string color, string text)
+ {
+ var c = ParseColor(color);
+ if (Console.ForegroundColor != c)
+ {
+ Console.ForegroundColor = c;
+ }
+ Console.Write(text);
+ }
+
+ // ввод цветного текста
+ static public string ReadColored(string color)
+ {
+ var c = ParseColor(color);
+ if (Console.ForegroundColor != c)
+ {
+ Console.ForegroundColor = c;
+ }
+ string text = Console.ReadLine();
+ return text;
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 2/DTLib/ConsoleGUI.cs b/.old 2/DTLib/ConsoleGUI.cs
new file mode 100644
index 0000000..7e4351d
--- /dev/null
+++ b/.old 2/DTLib/ConsoleGUI.cs
@@ -0,0 +1,257 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Threading.Tasks;
+
+namespace DTLib.ConsoleGUI
+{
+ //
+ // создание gui из текста в консоли
+ //
+ public class Window
+ {
+ public int WindowWidth { get; private set; }
+ public int WindowHeight { get; private set; }
+ public char[,] Text;
+ public char[,] nowText;
+ public char[,] TextColors;
+ public char[,] nowTextColors;
+
+ public Window(int windowWidth, int windowHeight)
+ {
+ WindowWidth = windowWidth;
+ WindowHeight = windowHeight;
+ Text = new char[windowWidth, windowHeight];
+ TextColors = new char[windowWidth, windowHeight];
+ nowText = new char[windowWidth, windowHeight];
+ nowTextColors = new char[windowWidth, windowHeight];
+ Console.WindowWidth = WindowWidth + 1;
+ Console.WindowHeight = WindowHeight + 1;
+ Console.BufferWidth = WindowWidth + 1;
+ Console.BufferHeight = WindowHeight + 1;
+ Console.OutputEncoding = SimpleConverter.UTF8;
+ Console.InputEncoding = SimpleConverter.UTF8;
+ Console.CursorVisible = false;
+ // заполнение массивов
+ for (sbyte y = 0; y < WindowHeight; y++)
+ {
+ for (sbyte x = 0; x < WindowWidth; x++)
+ {
+ Text[x, y] = ' ';
+ nowText[x, y] = ' ';
+ TextColors[x, y] = 'w';
+ nowTextColors[x, y] = 'w';
+ }
+ }
+ }
+
+ // считывает массив символов из файла
+ // ширина и высота текста должны быть как указанные при инициализации объекта этого класса
+ public void ReadFromFile(string path)
+ {
+ var r = new StreamReader(path, SimpleConverter.UTF8);
+ char[] s = new char[1];
+ // считывание текста
+ sbyte y = 0, x = 0;
+ r.Read(s, 0, 1);
+ while (!r.EndOfStream && y < WindowHeight)
+ {
+ if (x == WindowWidth)
+ {
+ r.Read(s, 0, 1);
+ x = 0;
+ y++;
+ }
+ else
+ {
+ Text[x, y] = s[0];
+ x++;
+ }
+ r.Read(s, 0, 1);
+ }
+ r.Read(s, 0, 1);
+ // считывание цвета
+ // если не находит цвет в файле, оставляет старый
+ if (s[0] == '\n')
+ {
+ r.Read(s, 0, 1);
+ y = 0;
+ x = 0;
+ while (!r.EndOfStream && y < WindowHeight)
+ {
+ if (x == WindowWidth)
+ {
+ r.Read(s, 0, 1);
+ x = 0;
+ y++;
+ }
+ else
+ {
+ TextColors[x, y] = s[0];
+ x++;
+ }
+ r.Read(s, 0, 1);
+ }
+ }
+ r.Close();
+ }
+
+ public void ResetCursor()
+ {
+ Console.SetCursorPosition(0, WindowHeight);
+ }
+
+ // заменяет символ выведенный, использовать после ShowAll()
+ public void ChangeChar(sbyte x, sbyte y, char ch)
+ {
+ Text[x, y] = ch;
+ nowText[x, y] = ch;
+ Console.SetCursorPosition(x, y);
+ ColoredText.WriteColored(TextColors[x, y].ToString(), ch.ToString());
+ }
+
+ public void ChangeColor(sbyte x, sbyte y, char color)
+ {
+ TextColors[x, y] = color;
+ nowTextColors[x, y] = color;
+ Console.SetCursorPosition(x, y);
+ ColoredText.WriteColored(color.ToString(), Text[x, y].ToString());
+ }
+
+ public void ChangeCharAndColor(sbyte x, sbyte y, char color, char ch)
+ {
+ Text[x, y] = ch;
+ nowText[x, y] = ch;
+ TextColors[x, y] = color;
+ nowTextColors[x, y] = color;
+ Console.SetCursorPosition(x, y);
+ ColoredText.WriteColored(color.ToString(), ch.ToString());
+ }
+
+ public void ChangeLine(sbyte x, sbyte y, char color, string line)
+ {
+ Console.SetCursorPosition(x, y);
+ for (sbyte i = 0; i < line.Length; i++)
+ {
+ Text[x + i, y] = line[i];
+ nowText[x + i, y] = line[i];
+ TextColors[x + i, y] = color;
+ nowTextColors[x + i, y] = color;
+ }
+ ColoredText.WriteColored(color.ToString(), line);
+ }
+
+ // выводит все символы
+ public void ShowAll()
+ {
+ var l = new List();
+ for (sbyte y = 0; y < WindowHeight; y++)
+ {
+ for (sbyte x = 0; x < WindowWidth; x++)
+ {
+ l.Add(TextColors[x, y].ToString());
+ l.Add(Text[x, y].ToString());
+ nowText[x, y] = Text[x, y];
+ nowTextColors[x, y] = TextColors[x, y];
+ }
+ l.Add("w");
+ l.Add("\n");
+ }
+ ColoredText.WriteColored(l.ToArray());
+ //Console.WriteLine();
+ }
+
+ public void UpdateAll()
+ {
+ for (sbyte y = 0; y < WindowHeight; y++)
+ {
+ for (sbyte x = 0; x < WindowWidth; x++)
+ {
+ Console.SetCursorPosition(x, y);
+ if (TextColors[x, y] != nowTextColors[x, y] || Text[x, y] != nowText[x, y])
+ {
+ ColoredText.WriteColored(TextColors[x, y].ToString(), Text[x, y].ToString());
+ nowText[x, y] = Text[x, y];
+ nowTextColors[x, y] = TextColors[x, y];
+ }
+ }
+ Console.Write('\n');
+ }
+ }
+
+
+
+ public async void ChangeCharAsync(sbyte x, sbyte y, char ch)
+ {
+ await Task.Run(() =>
+ {
+ ChangeChar(x, y, ch);
+ });
+ }
+
+ public async void ChangeColorAsync(sbyte x, sbyte y, char color)
+ {
+ await Task.Run(() =>
+ {
+ ChangeColor(x, y, color);
+ });
+ }
+
+ public async void ChangeCharAndColorAsync(sbyte x, sbyte y, char color, char ch)
+ {
+ await Task.Run(() =>
+ {
+ ChangeCharAndColor(x, y, color, ch);
+ });
+ }
+
+ public async void ChangeLineAsync(sbyte x, sbyte y, char color, string line)
+ {
+ await Task.Run(() =>
+ {
+ ChangeLine(x, y, color, line);
+ });
+ }
+
+ public async void ShowAllAsync()
+ {
+ await Task.Run(() =>
+ {
+ ShowAll();
+ });
+ }
+
+ public async void UpdateAllAsync()
+ {
+ await Task.Run(() =>
+ {
+ UpdateAll();
+ });
+ }
+ }
+
+ public class Tab
+ {
+ public Window Window;
+ public string Name;
+
+ public Tab(Window window)
+ {
+ Window = window;
+ }
+ }
+
+ public class Box
+ {
+ public Tab Tab;
+ public int LeftTopCorner, Width, Heigth;
+
+ public Box(Tab tab, int leftTopCorner, int width, int heigth)
+ {
+ Tab = tab;
+ LeftTopCorner = leftTopCorner;
+ Width = width;
+ Heigth = heigth;
+ }
+ }
+}
diff --git a/.old 2/DTLib/DTLib.csproj b/.old 2/DTLib/DTLib.csproj
new file mode 100644
index 0000000..99fb4aa
--- /dev/null
+++ b/.old 2/DTLib/DTLib.csproj
@@ -0,0 +1,49 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ Library
+ Properties
+ DTLib
+ DTLib
+ v4.8
+ 512
+ true
+
+
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 2/DTLib/FileWork.cs b/.old 2/DTLib/FileWork.cs
new file mode 100644
index 0000000..8758afd
--- /dev/null
+++ b/.old 2/DTLib/FileWork.cs
@@ -0,0 +1,43 @@
+using System;
+using System.IO;
+
+namespace DTLib
+{
+ public static class FileWork
+ {
+ public static void Log(string logfile, string msg)
+ {
+ lock (new object())
+ {
+ var st = File.Open(logfile, FileMode.Append);
+ var writer = new StreamWriter(st, SimpleConverter.UTF8);
+ string logMsg = $"[{DateTime.Now}]: {msg}";
+ writer.Write(logMsg);
+ writer.Close();
+ st.Close();
+ }
+ }
+
+ public static void DirExistenceCheck(string dir)
+ {
+ if (!Directory.Exists(dir))
+ Directory.CreateDirectory(dir);
+ }
+
+ static public string ReadFromConfig(string configfile, string key)
+ {
+ var reader = new StreamReader(configfile);
+ while (!reader.EndOfStream)
+ {
+ string st = reader.ReadLine();
+ if (!st.StartsWith("#") && st.Contains(key + ": "))
+ {
+ reader.Close();
+ return st.Remove(0, st.IndexOf(key + ": ") + key.Length + 2);
+ }
+ }
+ reader.Close();
+ return null;
+ }
+ }
+}
diff --git a/.old 2/DTLib/NetWork.cs b/.old 2/DTLib/NetWork.cs
new file mode 100644
index 0000000..de6fd21
--- /dev/null
+++ b/.old 2/DTLib/NetWork.cs
@@ -0,0 +1,370 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+
+namespace DTLib
+{
+ //
+ // некоторые полезные методы для работы с TCP сокетами (Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ //
+ static public class NetWork
+ {
+ public delegate void LogDelegate(string[] msg);
+ // можно присвоить методы этому делегату чтоб выводить логи
+ static public LogDelegate Log;
+ static void LogSimple(string color, string msg)
+ {
+ Log(new string[] { color, msg });
+ }
+
+ // правильно закрывает сокет
+ static public void CloseSocket(this Socket socket)
+ {
+ socket.Shutdown(SocketShutdown.Both);
+ socket.Close();
+ }
+ // получение информации (сокет должен быть в режиме Listen)
+ static public byte[] GetData(this Socket socket)
+ {
+ List output = new List();
+ byte[] data = new byte[256];
+ do
+ {
+ int amount = socket.Receive(data, data.Length, 0);
+ for (int i = 0; i < amount; i++)
+ output.Add(data[i]);
+ }
+ while (socket.Available > 0);
+ return output.ToArray();
+ }
+
+ // отправка запроса и получение ответа на него (сокет должен быть в режиме Listen)
+ static public byte[] Request(this Socket socket, string request)
+ {
+ socket.Send(request.ToBytes());
+ return GetData(socket);
+ }
+
+ static public byte[] Request(this Socket socket, byte[] request)
+ {
+ socket.Send(request);
+ return GetData(socket);
+ }
+
+ /*static public MessageObject SplitMessage(byte[] recieved)
+ {
+ if (recieved.Length != 2284) throw new Exception("incorrect message length: " + recieved.Length);
+ var msg = new MessageObject();
+ msg.Number = recieved[2];
+ for (byte i = 3; i < 9; i++)
+ {
+ msg.Number = msg.Number * 10 + recieved[i];
+ }
+ msg.Datetime = new DateTime(recieved[9] * 100 + recieved[10], recieved[11], recieved[12],
+ recieved[13], recieved[14], recieved[15]);
+ for (byte i = 16; i < 22; i++)
+ {
+ msg.Sender = msg.Sender * 10 + recieved[i];
+ }
+ for (byte i = 22; i < 28; i++)
+ {
+ msg.Channel = msg.Channel * 10 + recieved[i];
+ }
+ List text = new List();
+ for (short i = 28; i < 2028; i++)
+ {
+ text.Add(recieved[i]);
+ }
+ msg.Text = text.ToStr();
+ Log($"message <{msg.Number}> is had recieved");
+ return msg;
+ }*/
+
+ static public void FtpDownload(string address, string login, string password, string outfile)
+ {
+ try
+ {
+ // debug
+ Log(new string[] {
+ "y", "file on server: <", "c",address, "y",">\nfile on client: <",
+ "c",outfile,"y", ">\n"});
+ // создание запроса
+ // "ftp://m1net.keenetic.pro:20000/" + @infile
+ FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
+ request.Credentials = new NetworkCredential(login, password);
+ request.Method = WebRequestMethods.Ftp.DownloadFile;
+ // получение ответа на запрос
+ FtpWebResponse response = (FtpWebResponse)request.GetResponse();
+ Stream responseStream = response.GetResponseStream();
+ FileStream fs = new FileStream(@Directory.GetCurrentDirectory() + '\\' + @outfile, FileMode.Create);
+ byte[] buffer = new byte[64];
+ int size = 0;
+
+ while ((size = responseStream.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ fs.Write(buffer, 0, size);
+ }
+ fs.Close();
+ response.Close();
+ }
+ catch (WebException e)
+ {
+ throw new Exception("ftp error:\n" + ((FtpWebResponse)e.Response).StatusDescription + '\n');
+ }
+ }
+
+ static public ServerObject[] RequestServersList(Socket centralServer)
+ {
+ List servers = new List();
+ string[] lines = Request(centralServer, "a356a4257dbf9d87c77cf87c3c694b30160b6ddfd3db82e7f62320207109e352").ToStr().Split('\n');
+ for (int i = 0; i < lines.Length; i++)
+ {
+ string[] properties = lines[i].Split(',');
+ servers.Add(new ServerObject(properties[0], properties[1], properties[2]));
+ }
+ return servers.ToArray();
+ }
+
+ static public string PingIP(string address)
+ {
+ Process proc = new Process();
+ proc.StartInfo.FileName = "cmd.exe";
+ proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address;
+ proc.StartInfo.CreateNoWindow = true;
+ proc.StartInfo.UseShellExecute = false;
+ proc.StartInfo.RedirectStandardOutput = true;
+ proc.Start();
+ var outStream = proc.StandardOutput;
+ var rezult = outStream.ReadToEnd();
+ rezult = rezult.Remove(0, rezult.LastIndexOf('=') + 2);
+ return rezult.Remove(rezult.Length - 4);
+ }
+
+ static public bool Ping(this Socket socket)
+ {
+ var rec = Request(socket, "ab53bf045004875fb17086f7f992b0514fb96c038f336e0bfc21609b20303f07");
+ if (rec.ToStr() == "91b5c0383b75fb1708f00486f7f9b96c038ab3bfc21059b20176f603692b05e0")
+ {
+ return true;
+ }
+ else return false;
+ }
+
+ static public void FSP_Download(this Socket mainSocket, FSP_FileObject file)
+ {
+ Log(new string[] { "c", $"remote socket accepted download request: {file.ClientFilePath}\n" });
+ mainSocket.Send("requesting file download".ToBytes());
+ string answ = mainSocket.GetPackageClear(64, "<", ">").ToStr();
+ if (answ != "download request accepted")
+ throw new Exception($"FSP_Download() error: a download socket recieved an incorrect message: {answ}\n");
+ mainSocket.SendPackage(276, file.ServerFilePath.ToBytes(), "", "");
+ file.Size = Convert.ToUInt32(mainSocket.GetPackageClear(64, "", "").ToStr());
+ file.Hash = mainSocket.GetPackageClear(64, "", "");
+ mainSocket.SendPackage(64, "ready".ToBytes(), "<", ">");
+ file.Stream = File.Open(file.ClientFilePath, FileMode.Create, FileAccess.Write);
+ int packagesCount = 0;
+ byte[] buffer = new byte[5120];
+ var hashstr = file.Hash.HashToString();
+ int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
+ // рассчёт скорости
+ int seconds = 0;
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ LogSimple("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // получение файла
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ string header = $"<{packagesCount}>";
+ buffer = mainSocket.GetPackageRaw(buffer.Length + 2 + header.Length, header, "<>");
+ file.Stream.Write(buffer, 0, buffer.Length);
+ file.Stream.Flush();
+ }
+ Log(new string[] { "y", " full packages recieved\n" });
+ speedCounter.Stop();
+ // получение остатка
+ mainSocket.SendPackage(64, "remain request".ToBytes(), "<", ">");
+ buffer = mainSocket.GetPackageRaw(Convert.ToInt32(file.Size - fullPackagesCount * 5120) + 16, "", "");
+ file.Stream.Write(buffer, 0, buffer.Length);
+ file.Stream.Flush();
+ file.Stream.Close();
+ Log(new string[] { "g", $" file {file.ClientFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) downloaded.\n" });
+ }
+
+ static public void FSP_Upload(this Socket mainSocket)
+ {
+ mainSocket.SendPackage(64, "download request accepted".ToBytes(), "<", ">");
+ var file = new FSP_FileObject();
+ file.ServerFilePath = mainSocket.GetPackageClear(276, "", "").ToStr();
+ file.Size = new FileInfo(file.ServerFilePath).Length;
+ file.Hash = new SecureHasher(256).HashFile(file.ServerFilePath);
+ mainSocket.SendPackage(64, file.Size.ToString().ToBytes(), "", "");
+ mainSocket.SendPackage(64, file.Hash, "", "");
+ if (mainSocket.GetPackageClear(64, "<", ">").ToStr() != "ready")
+ throw new Exception("user socket isn't ready");
+ Log(new string[] { "c", $"local socket accepted file download request: {file.ServerFilePath}\n" });
+ file.Stream = new FileStream(file.ServerFilePath, FileMode.Open, FileAccess.Read);
+ byte[] buffer = new byte[5120];
+ var hashstr = file.Hash.HashToString();
+ int packagesCount = 0;
+ int seconds = 0;
+ // рассчёт скорости
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ LogSimple("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // отправка файла
+ int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ string header = $"<{packagesCount}>";
+ file.Stream.Read(buffer, 0, buffer.Length);
+ try { mainSocket.SendPackage(buffer.Length + 2 + header.Length, buffer, header, "<>"); }
+ catch (Exception ex) { Log(new string[] { "r", "FSP_Upload() error: " + ex.Message + "\n" + ex.StackTrace + '\n' }); }
+ }
+ Log(new string[] { "y", " full packages send\n" });
+ speedCounter.Stop();
+ // досылка остатка
+ var req = mainSocket.GetPackageClear(64, "<", ">");
+ if (req.ToStr() != "remain request")
+ {
+ throw new Exception("FSP_Upload() error: didn't get remain request");
+ }
+ buffer = new byte[Convert.ToInt32(file.Size - file.Stream.Position)];
+ file.Stream.Read(buffer, 0, buffer.Length);
+ mainSocket.SendPackage(buffer.Length + 16, buffer, "", "");
+ file.Stream.Close();
+ Log(new string[] { "g", $" file {file.ServerFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) uploaded.\n" });
+ }
+
+ // убирает пустые байты в конце пакета
+ static public byte[] GetPackageClear(this Socket socket, int packageSize, string startsWith, string endsWith)
+ {
+ byte[] data = socket.GetPackageRaw(packageSize, startsWith, endsWith);
+ bool clean = false;
+ for (int i = 0; !clean; i++)
+ {
+ if (data[i] != 00)
+ {
+ if (i != 0) data = data.Remove(0, i);
+ clean = true;
+ }
+ else clean = i == data.Length - 1;
+ }
+ return data;
+ }
+ //не убирает пустые байты в конце пакета
+ static public byte[] GetPackageRaw(this Socket socket, int packageSize, string startsWith, string endsWith)
+ {
+ byte[] data = new byte[packageSize];
+ //Log(new string[] { "y", $"GetPackage() packegesize=<","c",packageSize.ToString(),
+ // "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" });
+ for (short s = 0; s < 2000; s += 10)
+ {
+ if (socket.Available >= packageSize)
+ {
+ socket.Receive(data, packageSize, 0);
+ if (data.StartsWith(startsWith) & data.EndsWith(endsWith))
+ {
+ data = data.Remove(0, startsWith.ToBytes().Length);
+ data = data.Remove(data.Length - endsWith.ToBytes().Length, endsWith.ToBytes().Length);
+ return data;
+ }
+ else throw new Exception($"GetPackage() error: has got incorrect package\n");
+ }
+ else Thread.Sleep(10);
+ }
+ throw new Exception($"GetPackage() error: timeout\n");
+ }
+
+ static public void SendPackage(this Socket socket, int length, byte[] data, string startsWith, string endsWith)
+ {
+ var list = new List();
+ list.AddRange(startsWith.ToBytes());
+ int i = startsWith.ToBytes().Length + endsWith.ToBytes().Length + data.Length;
+ //Log(new string[] { "y", $"SendPackage() length=<","c",length.ToString(),"y", "> packegesize=<","c",i.ToString(),
+ // "y", "> data.Length=<","c",data.Length.ToString(), "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" });
+ if (i > length) throw new Exception("SendPackage() error: int length is too small\n");
+ for (; i < length; i++)
+ list.Add(0);
+ list.AddRange(data);
+ list.AddRange(endsWith.ToBytes());
+ socket.Send(list.ToArray());
+ }
+ }
+
+ public class FSP_FileObject
+ {
+ public string ServerFilePath;
+ public string ClientFilePath;
+ public long Size;
+ public byte[] Hash;
+ public Stream Stream;
+
+ public FSP_FileObject(string serverFile, string clientFile)
+ {
+ ServerFilePath = serverFile;
+ ClientFilePath = clientFile;
+ }
+
+ public FSP_FileObject() { }
+ }
+
+ public class ServerObject
+ {
+ public string Address;
+ public string Name;
+ public string Speed;
+
+ public ServerObject(string address, string name, string speed)
+ {
+ Address = address;
+ Name = name;
+ Speed = speed;
+ }
+ }
+
+ public class MessageObject
+ {
+ public uint Number;
+ public DateTime Datetime;
+ public int Sender;
+ public int Channel;
+ public string Text;
+
+ public MessageObject() { }
+
+ public MessageObject(byte[] recieved)
+ {
+ if (recieved.Length != 2284) throw new Exception("incorrect message length: " + recieved.Length);
+ Number = recieved[2];
+ for (byte i = 3; i < 9; i++)
+ {
+ Number = Number * 10 + recieved[i];
+ }
+ Datetime = new DateTime(recieved[9] * 100 + recieved[10], recieved[11], recieved[12],
+ recieved[13], recieved[14], recieved[15]);
+ for (byte i = 16; i < 22; i++)
+ {
+ Sender = Sender * 10 + recieved[i];
+ }
+ for (byte i = 22; i < 28; i++)
+ {
+ Channel = Channel * 10 + recieved[i];
+ }
+ List text = new List();
+ for (short i = 28; i < 2028; i++)
+ {
+ text.Add(recieved[i]);
+ }
+ Text = text.ToStr();
+ //Log($"message <{Number}> is had recieved");
+ }
+ }
+}
diff --git a/.old 2/DTLib/Properties/AssemblyInfo.cs b/.old 2/DTLib/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..c0201c5
--- /dev/null
+++ b/.old 2/DTLib/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные со сборкой.
+[assembly: AssemblyTitle("DTLib")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DTLib")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
+[assembly: ComVisible(false)]
+
+// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
+[assembly: Guid("ce793497-2d5c-42d8-b311-e9b32af9cdfb")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Редакция
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 2/DTLib/SecureHasher.cs b/.old 2/DTLib/SecureHasher.cs
new file mode 100644
index 0000000..691664d
--- /dev/null
+++ b/.old 2/DTLib/SecureHasher.cs
@@ -0,0 +1,97 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace DTLib
+{
+ //
+ // создаёт хеши из массива байт, двух массивов байт, стрима
+ //
+ public class SecureHasher
+ {
+ private dynamic hasher;
+
+ // можно указать размер хеша (по умолчанию 256 байт)
+ public SecureHasher(short type)
+ {
+ switch (type)
+ {
+ case 256:
+ hasher = SHA256.Create();
+ break;
+ case 384:
+ hasher = SHA384.Create();
+ break;
+ case 512:
+ hasher = SHA512.Create();
+ break;
+ default:
+ throw new Exception("unknown hash algorithm type: " + type + "\nin shouid be 256, 384 or 512\n");
+ }
+ }
+ public SecureHasher()
+ {
+ hasher = SHA256.Create();
+ }
+
+ // просто хеш
+ public byte[] Hash(byte[] input)
+ {
+ return hasher.ComputeHash(input);
+ }
+
+ // хеш из двух массивов
+ public byte[] HashSalt(byte[] input, byte[] salt)
+ {
+ List rez = new List();
+ rez.AddRange(input);
+ rez.AddRange(salt);
+ return hasher.ComputeHash(rez.ToArray());
+ }
+
+ // читает стрим и вычисляет хеш всей инфы в нём
+ public byte[] HashStream(Stream st)
+ {
+ byte[] data = new byte[1024];
+ List rez = new List();
+ int offset = 0;
+ while (offset < st.Length)
+ {
+ offset += st.Read(data, offset, 1024);
+ rez.AddRange(hasher.ComputeHash(data));
+ }
+ return hasher.ComputeHash(rez.ToArray());
+ }
+
+ // Хеш двух массивов в цикле.
+ // Работает быстро, так что вполне можно использовать количество циклов до 8к
+
+ public byte[] HashSaltCycled(byte[] input, byte[] salt, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = HashSalt(input, salt);
+ }
+ return input;
+ }
+
+ public byte[] HashCycled(byte[] input, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = Hash(input);
+ }
+ return input;
+ }
+
+ public byte[] HashFile(string filename)
+ {
+ var md5 = MD5.Create();
+ var stream = File.OpenRead(filename);
+ var hash = HashSaltCycled(md5.ComputeHash(stream), filename.ToBytes(), 512);
+ stream.Close();
+ return hash;
+ }
+ }
+}
diff --git a/.old 2/DTLib/SecureRandom.cs b/.old 2/DTLib/SecureRandom.cs
new file mode 100644
index 0000000..98217cf
--- /dev/null
+++ b/.old 2/DTLib/SecureRandom.cs
@@ -0,0 +1,37 @@
+using System.Security.Cryptography;
+
+namespace DTLib
+{
+ //
+ // Вычисление псевдослучайного числа из множества параметров.
+ // Работает медленнее чем класс System.Random, но производит более случайные значения
+ //
+ public class SecureRandom
+ {
+ private RNGCryptoServiceProvider crypt = new RNGCryptoServiceProvider();
+
+ // получение массива случайных байтов
+ public byte[] NextBytes(uint length)
+ {
+ byte[] output = new byte[length];
+ crypt.GetNonZeroBytes(output);
+ return output;
+ }
+
+ // получение случайного числа от 0 до 2147483647
+ /*public int NextInt(uint from, int to)
+ {
+ int output = 0;
+ int rez = 0;
+ while (true)
+ {
+ rez = output * 10 + NextBytes(1)[0];
+ if (rez < to && rez > from)
+ {
+ output = rez;
+ return output;
+ }
+ }
+ }*/
+ }
+}
diff --git a/.old 2/DTLib/SimpleConverter.cs b/.old 2/DTLib/SimpleConverter.cs
new file mode 100644
index 0000000..9f6c1a3
--- /dev/null
+++ b/.old 2/DTLib/SimpleConverter.cs
@@ -0,0 +1,82 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace DTLib
+{
+ //
+ // содержит методы расширения для конвертации байт в строку и наоборот
+ //
+ public static class SimpleConverter
+ {
+ static public Encoding UTF8 = new UTF8Encoding(false);
+ // байты в кодировке UTF8 в строку
+ static public string ToStr(this byte[] bytes)
+ {
+ return UTF8.GetString(bytes);
+ }
+ static public string ToStr(this List bytes)
+ {
+ return UTF8.GetString(bytes.ToArray());
+ }
+
+ static public List ToList(this byte[] input)
+ {
+ var list = new List();
+ list.AddRange(input);
+ return list;
+ }
+
+ static public byte[] Remove(this byte[] input, int startIndex, int count)
+ {
+ List list = input.ToList();
+ list.RemoveRange(startIndex, count);
+ return list.ToArray();
+ }
+
+ // строку в байты
+ static public byte[] ToBytes(this string str)
+ {
+ return UTF8.GetBytes(str);
+ }
+
+ // хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
+ static public string HashToString(this byte[] hash)
+ {
+ var builder = new StringBuilder();
+ for (int i = 0; i < hash.Length; i++)
+ {
+ builder.Append(hash[i].ToString("x2"));
+ }
+ return builder.ToString();
+ }
+
+ static public bool StartsWith(this byte[] source, byte[] startsWith)
+ {
+ for (int i = 0; i < startsWith.Length; i++)
+ {
+ if (source[i] != startsWith[i])
+ return false;
+ }
+ return true;
+ }
+
+ static public bool StartsWith(this byte[] source, string startsWith)
+ => StartsWith(source, startsWith.ToBytes());
+
+ static public bool EndsWith(this byte[] source, byte[] endsWith)
+ {
+ for (int i = 0; i < endsWith.Length; i++)
+ {
+ if (source[source.Length - endsWith.Length + i] != endsWith[i])
+ return false;
+ }
+ return true;
+ }
+ static public bool EndsWith(this byte[] source, string endsWith)
+ => EndsWith(source, endsWith.ToBytes());
+
+ static public int Truncate(decimal number)
+ => Convert.ToInt32(Math.Truncate(number));
+ }
+}
diff --git a/.old 2/DTLib/TImer.cs b/.old 2/DTLib/TImer.cs
new file mode 100644
index 0000000..2383078
--- /dev/null
+++ b/.old 2/DTLib/TImer.cs
@@ -0,0 +1,31 @@
+using System;
+using System.Threading;
+
+namespace DTLib
+{
+ public class Timer
+ {
+ public Thread TimerThread;
+ bool Repeat;
+ public Timer(bool repeat, int delay, Action method)
+ {
+ Repeat = repeat;
+ TimerThread = new Thread(() =>
+ {
+ do
+ {
+ Thread.Sleep(delay);
+ method();
+ } while (Repeat);
+ });
+ TimerThread.Start();
+ }
+
+ public void Stop()
+ {
+ Repeat = false;
+ //throw new Exception("thread stop\n");
+ TimerThread.Abort();
+ }
+ }
+}
diff --git a/.old 2/dtlauncher-client-win/App.config b/.old 2/dtlauncher-client-win/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 2/dtlauncher-client-win/App.xaml b/.old 2/dtlauncher-client-win/App.xaml
new file mode 100644
index 0000000..87bbcc3
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/App.xaml
@@ -0,0 +1,9 @@
+
+
+
+
+
diff --git a/.old 2/dtlauncher-client-win/App.xaml.cs b/.old 2/dtlauncher-client-win/App.xaml.cs
new file mode 100644
index 0000000..4aa3d80
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/App.xaml.cs
@@ -0,0 +1,11 @@
+using System.Windows;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для App.xaml
+ ///
+ public partial class App : Application
+ {
+ }
+}
diff --git a/.old 2/dtlauncher-client-win/LauncherWindow.xaml b/.old 2/dtlauncher-client-win/LauncherWindow.xaml
new file mode 100644
index 0000000..7b406c3
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/LauncherWindow.xaml
@@ -0,0 +1,12 @@
+
+
+
+
+
diff --git a/.old 2/dtlauncher-client-win/LauncherWindow.xaml.cs b/.old 2/dtlauncher-client-win/LauncherWindow.xaml.cs
new file mode 100644
index 0000000..f920ce1
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/LauncherWindow.xaml.cs
@@ -0,0 +1,46 @@
+using DTLib;
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Windows;
+using static DTLib.NetWork;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для LauncherWindow.xaml
+ ///
+ public partial class LauncherWindow : Window
+ {
+ Socket socket;
+ string logfile;
+
+ public LauncherWindow(Socket _socket, string _logfile)
+ {
+ InitializeComponent();
+ socket = _socket;
+ logfile = _logfile;
+ NetWork.Log += Log;
+ //mainSocket.FSP_Download(new FSP_FileObject("share\\file.arc", "downloads\\file.arc"));
+ }
+
+ void Log(string msg)
+ {
+ msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ //LogBox.Text += msg;
+ }
+
+ void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+ }
+}
diff --git a/.old 2/dtlauncher-client-win/LoginWindow.xaml b/.old 2/dtlauncher-client-win/LoginWindow.xaml
new file mode 100644
index 0000000..c5b0e39
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/LoginWindow.xaml
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 2/dtlauncher-client-win/LoginWindow.xaml.cs b/.old 2/dtlauncher-client-win/LoginWindow.xaml.cs
new file mode 100644
index 0000000..4769d2b
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/LoginWindow.xaml.cs
@@ -0,0 +1,143 @@
+using DTLib;
+using System;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Windows;
+using static DTLib.NetWork;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для LoginWindow.xaml
+ ///
+ public partial class LoginWindow : Window
+ {
+ public Socket mainSocket { private set; get; } = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ public string logfile { private set; get; } = $"logs\\client-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+
+ public LoginWindow()
+ {
+ InitializeComponent();
+ try
+ {
+ FileWork.DirExistenceCheck("logs");
+ FileWork.DirExistenceCheck("downloads");
+ NetWork.Log += Log;
+ LoginButton.Click += Login;
+ RegisterButton.Click += Register;
+ Closed += CloseWindow;
+ Log("launcher is starting\n");
+ // подключение к серверу
+ mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(
+ FileWork.ReadFromConfig("client.cfg", "central server ip"))[0],
+ Convert.ToInt32(FileWork.ReadFromConfig("client.cfg", "central server port"))));
+ mainSocket.ReceiveTimeout = 2000;
+ Log("connecting to the main server...");
+ string recieved = mainSocket.Request("new user connection try").ToStr();
+ if (recieved != "new user connection created")
+ throw new Exception("can't connect to the main server");
+ Log("connected to the main server");
+ //NetWork.RequestServersList(mainSocket);
+ }
+ catch (Exception e)
+ {
+ Log("\nerror:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ }
+ }
+
+ void Log(string msg)
+ {
+ msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ LogBox.Text += msg;
+ }
+
+ void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+
+ void Register(object sender, EventArgs e)
+ {
+ try
+ {
+ string login = LoginBox.Text;
+ string password = PasswBox.Password;
+ string filename = $"register-{login}.req";
+
+ var hasher = new SecureHasher(256);
+ if (File.Exists(filename)) File.Delete(filename);
+ var writer = File.CreateText(filename);
+ writer.Write(login + " $" +
+ hasher.HashSaltCycled(password.ToBytes(), login.ToBytes(), 4096)
+ .HashToString());
+ writer.Close();
+ Log($"request file created:{Directory.GetCurrentDirectory()}\\{filename}");
+ }
+ catch (Exception ex)
+ {
+ Log("registration error: " + ex.Message);
+ }
+ }
+
+ void Login(object sender, EventArgs e)
+ {
+ try
+ {
+ // пересоздание сокета
+ if (mainSocket.IsBound)
+ {
+ mainSocket.Shutdown(SocketShutdown.Both);
+ mainSocket.Close();
+ mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ }
+
+ var hasher = new SecureHasher(256);
+ // подключение к серверу
+ mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses("m1net.keenetic.pro")[0], 20008));
+ mainSocket.ReceiveTimeout = 5000;
+
+ // авторизация
+ string login = LoginBox.Text;
+ string password = PasswBox.Password;
+
+ string recievedString = NetWork.Request(mainSocket, login).ToStr();
+ if (recievedString != "2e9b7473ce473cdbb9b9e68aa444f5146b1b415a05917aceecd3861804cc2fd8")
+ {
+ throw new Exception("incorrect login\n");
+ }
+
+ recievedString = NetWork.Request(mainSocket,hasher.HashSaltCycled(password.ToBytes(), login.ToBytes(), 4096)).ToStr();
+ if (recievedString != "82c8e541601e0883ea189a285e514adfa6c2da05c83285359bbcf73bd3a8518b")
+ {
+ throw new Exception("incorrect password");
+ }
+
+ Log("succesfully login\n");
+ var lauWin = new LauncherWindow(mainSocket, logfile);
+ //CloseSocket(null, null);
+ lauWin.Show();
+ Hide();
+ lauWin.Closed += CloseWindow;
+ }
+ catch (Exception ex)
+ {
+ Log("login error: " + ex.Message);
+ }
+ }
+
+ void CloseWindow(object sender, EventArgs e)
+ {
+ Log("DTchat was closed");
+ Close();
+ }
+ }
+}
diff --git a/.old 2/dtlauncher-client-win/Properties/AssemblyInfo.cs b/.old 2/dtlauncher-client-win/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..bbd57be
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/Properties/AssemblyInfo.cs
@@ -0,0 +1,53 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("dtlauncher-client-win")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-client-win")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM, установите атрибут ComVisible для этого типа в значение true.
+[assembly: ComVisible(false)]
+
+//Чтобы начать создание локализуемых приложений, задайте
+//CultureYouAreCodingWith в файле .csproj
+//в . Например, при использовании английского (США)
+//в своих исходных файлах установите в en-US. Затем отмените преобразование в комментарий
+//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
+//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+ ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
+ //(используется, если ресурс не найден на странице,
+ // или в словарях ресурсов приложения)
+ ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
+ //(используется, если ресурс не найден на странице,
+ // в приложении или в каких-либо словарях ресурсов для конкретной темы)
+)]
+
+
+// Сведения о версии для сборки включают четыре следующих значения:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 2/dtlauncher-client-win/Properties/Resources.Designer.cs b/.old 2/dtlauncher-client-win/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..615ca67
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/Properties/Resources.Designer.cs
@@ -0,0 +1,70 @@
+//------------------------------------------------------------------------------
+//
+// Этот код был создан программным средством.
+// Версия среды выполнения: 4.0.30319.42000
+//
+// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
+// код создан повторно.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_client_win.Properties
+{
+ ///
+ /// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
+ ///
+ // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
+ // класс с помощью таких средств, как ResGen или Visual Studio.
+ // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
+ // с параметром /str или заново постройте свой VS-проект.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_client_win.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Переопределяет свойство CurrentUICulture текущего потока для всех
+ /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/.old 2/dtlauncher-client-win/Properties/Resources.resx b/.old 2/dtlauncher-client-win/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/.old 2/dtlauncher-client-win/Properties/Settings.Designer.cs b/.old 2/dtlauncher-client-win/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..1c4561e
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/Properties/Settings.Designer.cs
@@ -0,0 +1,29 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_client_win.Properties
+{
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/.old 2/dtlauncher-client-win/Properties/Settings.settings b/.old 2/dtlauncher-client-win/Properties/Settings.settings
new file mode 100644
index 0000000..033d7a5
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 2/dtlauncher-client-win/dtlauncher-client-win.csproj b/.old 2/dtlauncher-client-win/dtlauncher-client-win.csproj
new file mode 100644
index 0000000..f7f6d4e
--- /dev/null
+++ b/.old 2/dtlauncher-client-win/dtlauncher-client-win.csproj
@@ -0,0 +1,104 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}
+ WinExe
+ dtlauncher_client_win
+ dtlauncher-client-win
+ v4.8
+ 512
+ {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ 4
+ true
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+ 4.0
+
+
+
+
+
+
+
+ MSBuild:Compile
+ Designer
+
+
+ Designer
+ MSBuild:Compile
+
+
+ MSBuild:Compile
+ Designer
+
+
+ App.xaml
+ Code
+
+
+ LauncherWindow.xaml
+
+
+ LoginWindow.xaml
+ Code
+
+
+
+
+ Code
+
+
+ True
+ True
+ Resources.resx
+
+
+ True
+ Settings.settings
+ True
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+ del /f /q dtlauncher-client-win.exe.config
+
+
\ No newline at end of file
diff --git a/.old 2/dtlauncher-server-win/App.config b/.old 2/dtlauncher-server-win/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 2/dtlauncher-server-win/App.xaml b/.old 2/dtlauncher-server-win/App.xaml
new file mode 100644
index 0000000..c4116b7
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/App.xaml
@@ -0,0 +1,96 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 2/dtlauncher-server-win/App.xaml.cs b/.old 2/dtlauncher-server-win/App.xaml.cs
new file mode 100644
index 0000000..bacff7e
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/App.xaml.cs
@@ -0,0 +1,11 @@
+using System.Windows;
+
+namespace dtlauncher_server_win
+{
+ ///
+ /// Логика взаимодействия для App.xaml
+ ///
+ public partial class App : Application
+ {
+ }
+}
diff --git a/.old 2/dtlauncher-server-win/Properties/AssemblyInfo.cs b/.old 2/dtlauncher-server-win/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..340af78
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/Properties/AssemblyInfo.cs
@@ -0,0 +1,53 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("dtlauncher-server-win")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-server-win")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM, установите атрибут ComVisible для этого типа в значение true.
+[assembly: ComVisible(false)]
+
+//Чтобы начать создание локализуемых приложений, задайте
+//CultureYouAreCodingWith в файле .csproj
+//в . Например, при использовании английского (США)
+//в своих исходных файлах установите в en-US. Затем отмените преобразование в комментарий
+//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
+//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+ ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
+ //(используется, если ресурс не найден на странице,
+ // или в словарях ресурсов приложения)
+ ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
+ //(используется, если ресурс не найден на странице,
+ // в приложении или в каких-либо словарях ресурсов для конкретной темы)
+)]
+
+
+// Сведения о версии для сборки включают четыре следующих значения:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 2/dtlauncher-server-win/Properties/Resources.Designer.cs b/.old 2/dtlauncher-server-win/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..9d42357
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/Properties/Resources.Designer.cs
@@ -0,0 +1,70 @@
+//------------------------------------------------------------------------------
+//
+// Этот код был создан программным средством.
+// Версия среды выполнения: 4.0.30319.42000
+//
+// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
+// код создан повторно.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_server_win.Properties
+{
+ ///
+ /// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
+ ///
+ // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
+ // класс с помощью таких средств, как ResGen или Visual Studio.
+ // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
+ // с параметром /str или заново постройте свой VS-проект.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_server_win.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Переопределяет свойство CurrentUICulture текущего потока для всех
+ /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/.old 2/dtlauncher-server-win/Properties/Resources.resx b/.old 2/dtlauncher-server-win/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/.old 2/dtlauncher-server-win/Properties/Settings.Designer.cs b/.old 2/dtlauncher-server-win/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..cb2dff3
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/Properties/Settings.Designer.cs
@@ -0,0 +1,29 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_server_win.Properties
+{
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/.old 2/dtlauncher-server-win/Properties/Settings.settings b/.old 2/dtlauncher-server-win/Properties/Settings.settings
new file mode 100644
index 0000000..033d7a5
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 2/dtlauncher-server-win/ServerWindow.xaml b/.old 2/dtlauncher-server-win/ServerWindow.xaml
new file mode 100644
index 0000000..5988e2d
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/ServerWindow.xaml
@@ -0,0 +1,12 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 2/dtlauncher-server-win/ServerWindow.xaml.cs b/.old 2/dtlauncher-server-win/ServerWindow.xaml.cs
new file mode 100644
index 0000000..d5746e6
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/ServerWindow.xaml.cs
@@ -0,0 +1,117 @@
+using DTLib;
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using System.Windows;
+using static DTLib.NetWork;
+
+namespace dtlauncher_server_win
+{
+ ///
+ /// Логика взаимодействия для ServerWindow.xaml
+ ///
+ public partial class ServerWindow : Window
+ {
+ static string logfile = $"logs\\server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+ static Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+
+ public ServerWindow()
+ {
+ InitializeComponent();
+ while (true)
+ {
+ try
+ {
+ FileWork.DirExistenceCheck("logs");
+ FileWork.DirExistenceCheck("share");
+ NetWork.Log += Log;
+ Log($"<{FileWork.ReadFromConfig("server.cfg", "server ip")}> : <{Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))}>\n");
+ mainSocket.Bind(new IPEndPoint(IPAddress.Parse(FileWork.ReadFromConfig("server.cfg", "server ip")), Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))));
+ Log("server started succesfully\n");
+ try
+ {
+ mainSocket.Listen(200);
+ while (true)
+ {
+ var userSocket = mainSocket.Accept();
+ var userThread = new Thread(new ParameterizedThreadStart(UserStart));
+ userThread.Start(userSocket);
+ }
+ }
+ catch (Exception ex)
+ {
+ Log($"handler error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ }
+ catch (Exception ex)
+ {
+ if (mainSocket.IsBound) mainSocket.CloseSocket();
+ Log($"Main() error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ Thread.Sleep(1500);
+ }
+ }
+
+ void Log(string msg)
+ {
+ msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ //LogBox.Text += msg;
+ }
+
+ void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+
+ void UserStart(dynamic _handlerSocket)
+ {
+ Socket handlerSocket = (Socket)_handlerSocket;
+ Log("user connected\n");
+ try
+ {
+ string recieved = handlerSocket.GetData().ToStr();
+ if (recieved == "new user connection try")
+ {
+ handlerSocket.Send("new user connection created".ToBytes());
+ while (true)
+ {
+ recieved = handlerSocket.GetData().ToStr();
+ switch (recieved)
+ {
+ // ответ на NetWork.Ping()
+ case "ping":
+ handlerSocket.Send("pong".ToBytes());
+ break;
+ // отправка списка активных серверов
+ case "requesting servers list":
+
+ break;
+ // отправка файла
+ case "requesting file download":
+ handlerSocket.FSP_Upload();
+ break;
+ default:
+ throw new Exception("unknown request: " + recieved);
+ }
+ }
+ }
+ else throw new Exception("incorrect connection try");
+ }
+ catch (Exception ex)
+ {
+ Log($"UserStart() error:\n message:\n {ex.Message}\n{ex.StackTrace}\n");
+ handlerSocket.CloseSocket();
+ Thread.CurrentThread.Abort();
+ }
+ }
+ }
+}
diff --git a/.old 2/dtlauncher-server-win/dtlauncher-server-win.csproj b/.old 2/dtlauncher-server-win/dtlauncher-server-win.csproj
new file mode 100644
index 0000000..efc5cf1
--- /dev/null
+++ b/.old 2/dtlauncher-server-win/dtlauncher-server-win.csproj
@@ -0,0 +1,124 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}
+ WinExe
+ dtlauncher_server_win
+ dtlauncher-server-win
+ v4.8
+ 512
+ {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ 4
+ true
+ true
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+ 4.0
+
+
+
+
+
+
+
+ MSBuild:Compile
+ Designer
+
+
+ MSBuild:Compile
+ Designer
+
+
+ App.xaml
+ Code
+
+
+ ServerWindow.xaml
+ Code
+
+
+
+
+ Code
+
+
+ True
+ True
+ Resources.resx
+
+
+ True
+ Settings.settings
+ True
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+ False
+ Microsoft .NET Framework 4.8 %28x86 и x64%29
+ true
+
+
+ False
+ .NET Framework 3.5 SP1
+ false
+
+
+
+
+ del /f /q dtlauncher-server-win.exe.config
+
+
\ No newline at end of file
diff --git a/.old 2/dtlauncher.sln b/.old 2/dtlauncher.sln
new file mode 100644
index 0000000..a8c29fa
--- /dev/null
+++ b/.old 2/dtlauncher.sln
@@ -0,0 +1,36 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30907.101
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-client-win", "dtlauncher-client-win\dtlauncher-client-win.csproj", "{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-server-win", "dtlauncher-server-win\dtlauncher-server-win.csproj", "{8B9889A7-93DC-4914-92D1-8209BD3BA71A}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Build|Any CPU = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.Build.0 = Build|Any CPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.Build.0 = Build|Any CPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.Build.0 = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {E6569C0C-DD32-4F7D-AD4C-DBC5434D2F8C}
+ EndGlobalSection
+EndGlobal
diff --git a/.old 3/DTLib/ColoredText.cs b/.old 3/DTLib/ColoredText.cs
new file mode 100644
index 0000000..a8147cd
--- /dev/null
+++ b/.old 3/DTLib/ColoredText.cs
@@ -0,0 +1,122 @@
+using System;
+
+namespace DTLib
+{
+ //
+ // изменение цвета текста в консоли
+ //
+ static public class ColoredText
+ {
+ // присвоение цвета тексту
+ static public ConsoleColor ParseColor(string color)
+ {
+ switch (color)
+ {
+ //case "magneta":
+ case "m":
+ return ConsoleColor.Magenta;
+ //case "green":
+ case "g":
+ return ConsoleColor.Green;
+ //case "red":
+ case "r":
+ return ConsoleColor.Red;
+ //case "yellow":
+ case "y":
+ return ConsoleColor.Yellow;
+ //case "white":
+ case "w":
+ return ConsoleColor.White;
+ //case "blue":
+ case "b":
+ return ConsoleColor.Blue;
+ //case "cyan":
+ case "c":
+ return ConsoleColor.Cyan;
+ //case "gray":
+ case "a":
+ return ConsoleColor.Gray;
+ //case "black":
+ case "t":
+ return ConsoleColor.Black;
+ default:
+ throw new Exception("incorrect color: " + color);
+ }
+ }
+
+ // вывод цветного текста
+ static public void WriteColored(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ var c = ParseColor(input[i]);
+ if (Console.ForegroundColor != c)
+ {
+ Console.Write(str);
+ Console.ForegroundColor = c;
+ str = "";
+ }
+ str += input[++i];
+ }
+ if (str != "")
+ Console.Write(str);
+ }
+ else
+ {
+ throw new Exception("error in WriteColored(): every text string must have color string before");
+ }
+ }
+
+ /*static public void WriteColoredB(string[] input)
+ {
+ if (input.Length % 3 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ var f = ParseColor(input[i]);
+ var b = ParseColor(input[++i]);
+ if (Console.ForegroundColor != f || Console.BackgroundColor != b)
+ {
+ Console.Write(str);
+ Console.ForegroundColor = f;
+ Console.BackgroundColor = b;
+ str = "";
+ }
+ str += input[++i];
+ }
+ if (str != "")
+ Console.Write(str);
+ }
+ else
+ {
+ throw new Exception("error in WriteColored(): every text string must have color string before");
+ }
+ }*/
+
+ static public void WriteColored(string color, string text)
+ {
+ var c = ParseColor(color);
+ if (Console.ForegroundColor != c)
+ {
+ Console.ForegroundColor = c;
+ }
+ Console.Write(text);
+ }
+
+ // ввод цветного текста
+ static public string ReadColored(string color)
+ {
+ var c = ParseColor(color);
+ if (Console.ForegroundColor != c)
+ {
+ Console.ForegroundColor = c;
+ }
+ string text = Console.ReadLine();
+ return text;
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 3/DTLib/ConsoleGUI.cs b/.old 3/DTLib/ConsoleGUI.cs
new file mode 100644
index 0000000..7e4351d
--- /dev/null
+++ b/.old 3/DTLib/ConsoleGUI.cs
@@ -0,0 +1,257 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Threading.Tasks;
+
+namespace DTLib.ConsoleGUI
+{
+ //
+ // создание gui из текста в консоли
+ //
+ public class Window
+ {
+ public int WindowWidth { get; private set; }
+ public int WindowHeight { get; private set; }
+ public char[,] Text;
+ public char[,] nowText;
+ public char[,] TextColors;
+ public char[,] nowTextColors;
+
+ public Window(int windowWidth, int windowHeight)
+ {
+ WindowWidth = windowWidth;
+ WindowHeight = windowHeight;
+ Text = new char[windowWidth, windowHeight];
+ TextColors = new char[windowWidth, windowHeight];
+ nowText = new char[windowWidth, windowHeight];
+ nowTextColors = new char[windowWidth, windowHeight];
+ Console.WindowWidth = WindowWidth + 1;
+ Console.WindowHeight = WindowHeight + 1;
+ Console.BufferWidth = WindowWidth + 1;
+ Console.BufferHeight = WindowHeight + 1;
+ Console.OutputEncoding = SimpleConverter.UTF8;
+ Console.InputEncoding = SimpleConverter.UTF8;
+ Console.CursorVisible = false;
+ // заполнение массивов
+ for (sbyte y = 0; y < WindowHeight; y++)
+ {
+ for (sbyte x = 0; x < WindowWidth; x++)
+ {
+ Text[x, y] = ' ';
+ nowText[x, y] = ' ';
+ TextColors[x, y] = 'w';
+ nowTextColors[x, y] = 'w';
+ }
+ }
+ }
+
+ // считывает массив символов из файла
+ // ширина и высота текста должны быть как указанные при инициализации объекта этого класса
+ public void ReadFromFile(string path)
+ {
+ var r = new StreamReader(path, SimpleConverter.UTF8);
+ char[] s = new char[1];
+ // считывание текста
+ sbyte y = 0, x = 0;
+ r.Read(s, 0, 1);
+ while (!r.EndOfStream && y < WindowHeight)
+ {
+ if (x == WindowWidth)
+ {
+ r.Read(s, 0, 1);
+ x = 0;
+ y++;
+ }
+ else
+ {
+ Text[x, y] = s[0];
+ x++;
+ }
+ r.Read(s, 0, 1);
+ }
+ r.Read(s, 0, 1);
+ // считывание цвета
+ // если не находит цвет в файле, оставляет старый
+ if (s[0] == '\n')
+ {
+ r.Read(s, 0, 1);
+ y = 0;
+ x = 0;
+ while (!r.EndOfStream && y < WindowHeight)
+ {
+ if (x == WindowWidth)
+ {
+ r.Read(s, 0, 1);
+ x = 0;
+ y++;
+ }
+ else
+ {
+ TextColors[x, y] = s[0];
+ x++;
+ }
+ r.Read(s, 0, 1);
+ }
+ }
+ r.Close();
+ }
+
+ public void ResetCursor()
+ {
+ Console.SetCursorPosition(0, WindowHeight);
+ }
+
+ // заменяет символ выведенный, использовать после ShowAll()
+ public void ChangeChar(sbyte x, sbyte y, char ch)
+ {
+ Text[x, y] = ch;
+ nowText[x, y] = ch;
+ Console.SetCursorPosition(x, y);
+ ColoredText.WriteColored(TextColors[x, y].ToString(), ch.ToString());
+ }
+
+ public void ChangeColor(sbyte x, sbyte y, char color)
+ {
+ TextColors[x, y] = color;
+ nowTextColors[x, y] = color;
+ Console.SetCursorPosition(x, y);
+ ColoredText.WriteColored(color.ToString(), Text[x, y].ToString());
+ }
+
+ public void ChangeCharAndColor(sbyte x, sbyte y, char color, char ch)
+ {
+ Text[x, y] = ch;
+ nowText[x, y] = ch;
+ TextColors[x, y] = color;
+ nowTextColors[x, y] = color;
+ Console.SetCursorPosition(x, y);
+ ColoredText.WriteColored(color.ToString(), ch.ToString());
+ }
+
+ public void ChangeLine(sbyte x, sbyte y, char color, string line)
+ {
+ Console.SetCursorPosition(x, y);
+ for (sbyte i = 0; i < line.Length; i++)
+ {
+ Text[x + i, y] = line[i];
+ nowText[x + i, y] = line[i];
+ TextColors[x + i, y] = color;
+ nowTextColors[x + i, y] = color;
+ }
+ ColoredText.WriteColored(color.ToString(), line);
+ }
+
+ // выводит все символы
+ public void ShowAll()
+ {
+ var l = new List();
+ for (sbyte y = 0; y < WindowHeight; y++)
+ {
+ for (sbyte x = 0; x < WindowWidth; x++)
+ {
+ l.Add(TextColors[x, y].ToString());
+ l.Add(Text[x, y].ToString());
+ nowText[x, y] = Text[x, y];
+ nowTextColors[x, y] = TextColors[x, y];
+ }
+ l.Add("w");
+ l.Add("\n");
+ }
+ ColoredText.WriteColored(l.ToArray());
+ //Console.WriteLine();
+ }
+
+ public void UpdateAll()
+ {
+ for (sbyte y = 0; y < WindowHeight; y++)
+ {
+ for (sbyte x = 0; x < WindowWidth; x++)
+ {
+ Console.SetCursorPosition(x, y);
+ if (TextColors[x, y] != nowTextColors[x, y] || Text[x, y] != nowText[x, y])
+ {
+ ColoredText.WriteColored(TextColors[x, y].ToString(), Text[x, y].ToString());
+ nowText[x, y] = Text[x, y];
+ nowTextColors[x, y] = TextColors[x, y];
+ }
+ }
+ Console.Write('\n');
+ }
+ }
+
+
+
+ public async void ChangeCharAsync(sbyte x, sbyte y, char ch)
+ {
+ await Task.Run(() =>
+ {
+ ChangeChar(x, y, ch);
+ });
+ }
+
+ public async void ChangeColorAsync(sbyte x, sbyte y, char color)
+ {
+ await Task.Run(() =>
+ {
+ ChangeColor(x, y, color);
+ });
+ }
+
+ public async void ChangeCharAndColorAsync(sbyte x, sbyte y, char color, char ch)
+ {
+ await Task.Run(() =>
+ {
+ ChangeCharAndColor(x, y, color, ch);
+ });
+ }
+
+ public async void ChangeLineAsync(sbyte x, sbyte y, char color, string line)
+ {
+ await Task.Run(() =>
+ {
+ ChangeLine(x, y, color, line);
+ });
+ }
+
+ public async void ShowAllAsync()
+ {
+ await Task.Run(() =>
+ {
+ ShowAll();
+ });
+ }
+
+ public async void UpdateAllAsync()
+ {
+ await Task.Run(() =>
+ {
+ UpdateAll();
+ });
+ }
+ }
+
+ public class Tab
+ {
+ public Window Window;
+ public string Name;
+
+ public Tab(Window window)
+ {
+ Window = window;
+ }
+ }
+
+ public class Box
+ {
+ public Tab Tab;
+ public int LeftTopCorner, Width, Heigth;
+
+ public Box(Tab tab, int leftTopCorner, int width, int heigth)
+ {
+ Tab = tab;
+ LeftTopCorner = leftTopCorner;
+ Width = width;
+ Heigth = heigth;
+ }
+ }
+}
diff --git a/.old 3/DTLib/DTLib.csproj b/.old 3/DTLib/DTLib.csproj
new file mode 100644
index 0000000..99fb4aa
--- /dev/null
+++ b/.old 3/DTLib/DTLib.csproj
@@ -0,0 +1,49 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ Library
+ Properties
+ DTLib
+ DTLib
+ v4.8
+ 512
+ true
+
+
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 3/DTLib/FileWork.cs b/.old 3/DTLib/FileWork.cs
new file mode 100644
index 0000000..8758afd
--- /dev/null
+++ b/.old 3/DTLib/FileWork.cs
@@ -0,0 +1,43 @@
+using System;
+using System.IO;
+
+namespace DTLib
+{
+ public static class FileWork
+ {
+ public static void Log(string logfile, string msg)
+ {
+ lock (new object())
+ {
+ var st = File.Open(logfile, FileMode.Append);
+ var writer = new StreamWriter(st, SimpleConverter.UTF8);
+ string logMsg = $"[{DateTime.Now}]: {msg}";
+ writer.Write(logMsg);
+ writer.Close();
+ st.Close();
+ }
+ }
+
+ public static void DirExistenceCheck(string dir)
+ {
+ if (!Directory.Exists(dir))
+ Directory.CreateDirectory(dir);
+ }
+
+ static public string ReadFromConfig(string configfile, string key)
+ {
+ var reader = new StreamReader(configfile);
+ while (!reader.EndOfStream)
+ {
+ string st = reader.ReadLine();
+ if (!st.StartsWith("#") && st.Contains(key + ": "))
+ {
+ reader.Close();
+ return st.Remove(0, st.IndexOf(key + ": ") + key.Length + 2);
+ }
+ }
+ reader.Close();
+ return null;
+ }
+ }
+}
diff --git a/.old 3/DTLib/NetWork.cs b/.old 3/DTLib/NetWork.cs
new file mode 100644
index 0000000..de6fd21
--- /dev/null
+++ b/.old 3/DTLib/NetWork.cs
@@ -0,0 +1,370 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+
+namespace DTLib
+{
+ //
+ // некоторые полезные методы для работы с TCP сокетами (Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ //
+ static public class NetWork
+ {
+ public delegate void LogDelegate(string[] msg);
+ // можно присвоить методы этому делегату чтоб выводить логи
+ static public LogDelegate Log;
+ static void LogSimple(string color, string msg)
+ {
+ Log(new string[] { color, msg });
+ }
+
+ // правильно закрывает сокет
+ static public void CloseSocket(this Socket socket)
+ {
+ socket.Shutdown(SocketShutdown.Both);
+ socket.Close();
+ }
+ // получение информации (сокет должен быть в режиме Listen)
+ static public byte[] GetData(this Socket socket)
+ {
+ List output = new List();
+ byte[] data = new byte[256];
+ do
+ {
+ int amount = socket.Receive(data, data.Length, 0);
+ for (int i = 0; i < amount; i++)
+ output.Add(data[i]);
+ }
+ while (socket.Available > 0);
+ return output.ToArray();
+ }
+
+ // отправка запроса и получение ответа на него (сокет должен быть в режиме Listen)
+ static public byte[] Request(this Socket socket, string request)
+ {
+ socket.Send(request.ToBytes());
+ return GetData(socket);
+ }
+
+ static public byte[] Request(this Socket socket, byte[] request)
+ {
+ socket.Send(request);
+ return GetData(socket);
+ }
+
+ /*static public MessageObject SplitMessage(byte[] recieved)
+ {
+ if (recieved.Length != 2284) throw new Exception("incorrect message length: " + recieved.Length);
+ var msg = new MessageObject();
+ msg.Number = recieved[2];
+ for (byte i = 3; i < 9; i++)
+ {
+ msg.Number = msg.Number * 10 + recieved[i];
+ }
+ msg.Datetime = new DateTime(recieved[9] * 100 + recieved[10], recieved[11], recieved[12],
+ recieved[13], recieved[14], recieved[15]);
+ for (byte i = 16; i < 22; i++)
+ {
+ msg.Sender = msg.Sender * 10 + recieved[i];
+ }
+ for (byte i = 22; i < 28; i++)
+ {
+ msg.Channel = msg.Channel * 10 + recieved[i];
+ }
+ List text = new List();
+ for (short i = 28; i < 2028; i++)
+ {
+ text.Add(recieved[i]);
+ }
+ msg.Text = text.ToStr();
+ Log($"message <{msg.Number}> is had recieved");
+ return msg;
+ }*/
+
+ static public void FtpDownload(string address, string login, string password, string outfile)
+ {
+ try
+ {
+ // debug
+ Log(new string[] {
+ "y", "file on server: <", "c",address, "y",">\nfile on client: <",
+ "c",outfile,"y", ">\n"});
+ // создание запроса
+ // "ftp://m1net.keenetic.pro:20000/" + @infile
+ FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
+ request.Credentials = new NetworkCredential(login, password);
+ request.Method = WebRequestMethods.Ftp.DownloadFile;
+ // получение ответа на запрос
+ FtpWebResponse response = (FtpWebResponse)request.GetResponse();
+ Stream responseStream = response.GetResponseStream();
+ FileStream fs = new FileStream(@Directory.GetCurrentDirectory() + '\\' + @outfile, FileMode.Create);
+ byte[] buffer = new byte[64];
+ int size = 0;
+
+ while ((size = responseStream.Read(buffer, 0, buffer.Length)) > 0)
+ {
+ fs.Write(buffer, 0, size);
+ }
+ fs.Close();
+ response.Close();
+ }
+ catch (WebException e)
+ {
+ throw new Exception("ftp error:\n" + ((FtpWebResponse)e.Response).StatusDescription + '\n');
+ }
+ }
+
+ static public ServerObject[] RequestServersList(Socket centralServer)
+ {
+ List servers = new List();
+ string[] lines = Request(centralServer, "a356a4257dbf9d87c77cf87c3c694b30160b6ddfd3db82e7f62320207109e352").ToStr().Split('\n');
+ for (int i = 0; i < lines.Length; i++)
+ {
+ string[] properties = lines[i].Split(',');
+ servers.Add(new ServerObject(properties[0], properties[1], properties[2]));
+ }
+ return servers.ToArray();
+ }
+
+ static public string PingIP(string address)
+ {
+ Process proc = new Process();
+ proc.StartInfo.FileName = "cmd.exe";
+ proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address;
+ proc.StartInfo.CreateNoWindow = true;
+ proc.StartInfo.UseShellExecute = false;
+ proc.StartInfo.RedirectStandardOutput = true;
+ proc.Start();
+ var outStream = proc.StandardOutput;
+ var rezult = outStream.ReadToEnd();
+ rezult = rezult.Remove(0, rezult.LastIndexOf('=') + 2);
+ return rezult.Remove(rezult.Length - 4);
+ }
+
+ static public bool Ping(this Socket socket)
+ {
+ var rec = Request(socket, "ab53bf045004875fb17086f7f992b0514fb96c038f336e0bfc21609b20303f07");
+ if (rec.ToStr() == "91b5c0383b75fb1708f00486f7f9b96c038ab3bfc21059b20176f603692b05e0")
+ {
+ return true;
+ }
+ else return false;
+ }
+
+ static public void FSP_Download(this Socket mainSocket, FSP_FileObject file)
+ {
+ Log(new string[] { "c", $"remote socket accepted download request: {file.ClientFilePath}\n" });
+ mainSocket.Send("requesting file download".ToBytes());
+ string answ = mainSocket.GetPackageClear(64, "<", ">").ToStr();
+ if (answ != "download request accepted")
+ throw new Exception($"FSP_Download() error: a download socket recieved an incorrect message: {answ}\n");
+ mainSocket.SendPackage(276, file.ServerFilePath.ToBytes(), "", "");
+ file.Size = Convert.ToUInt32(mainSocket.GetPackageClear(64, "", "").ToStr());
+ file.Hash = mainSocket.GetPackageClear(64, "", "");
+ mainSocket.SendPackage(64, "ready".ToBytes(), "<", ">");
+ file.Stream = File.Open(file.ClientFilePath, FileMode.Create, FileAccess.Write);
+ int packagesCount = 0;
+ byte[] buffer = new byte[5120];
+ var hashstr = file.Hash.HashToString();
+ int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
+ // рассчёт скорости
+ int seconds = 0;
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ LogSimple("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // получение файла
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ string header = $"<{packagesCount}>";
+ buffer = mainSocket.GetPackageRaw(buffer.Length + 2 + header.Length, header, "<>");
+ file.Stream.Write(buffer, 0, buffer.Length);
+ file.Stream.Flush();
+ }
+ Log(new string[] { "y", " full packages recieved\n" });
+ speedCounter.Stop();
+ // получение остатка
+ mainSocket.SendPackage(64, "remain request".ToBytes(), "<", ">");
+ buffer = mainSocket.GetPackageRaw(Convert.ToInt32(file.Size - fullPackagesCount * 5120) + 16, "", "");
+ file.Stream.Write(buffer, 0, buffer.Length);
+ file.Stream.Flush();
+ file.Stream.Close();
+ Log(new string[] { "g", $" file {file.ClientFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) downloaded.\n" });
+ }
+
+ static public void FSP_Upload(this Socket mainSocket)
+ {
+ mainSocket.SendPackage(64, "download request accepted".ToBytes(), "<", ">");
+ var file = new FSP_FileObject();
+ file.ServerFilePath = mainSocket.GetPackageClear(276, "", "").ToStr();
+ file.Size = new FileInfo(file.ServerFilePath).Length;
+ file.Hash = new SecureHasher(256).HashFile(file.ServerFilePath);
+ mainSocket.SendPackage(64, file.Size.ToString().ToBytes(), "", "");
+ mainSocket.SendPackage(64, file.Hash, "", "");
+ if (mainSocket.GetPackageClear(64, "<", ">").ToStr() != "ready")
+ throw new Exception("user socket isn't ready");
+ Log(new string[] { "c", $"local socket accepted file download request: {file.ServerFilePath}\n" });
+ file.Stream = new FileStream(file.ServerFilePath, FileMode.Open, FileAccess.Read);
+ byte[] buffer = new byte[5120];
+ var hashstr = file.Hash.HashToString();
+ int packagesCount = 0;
+ int seconds = 0;
+ // рассчёт скорости
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ LogSimple("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // отправка файла
+ int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ string header = $"<{packagesCount}>";
+ file.Stream.Read(buffer, 0, buffer.Length);
+ try { mainSocket.SendPackage(buffer.Length + 2 + header.Length, buffer, header, "<>"); }
+ catch (Exception ex) { Log(new string[] { "r", "FSP_Upload() error: " + ex.Message + "\n" + ex.StackTrace + '\n' }); }
+ }
+ Log(new string[] { "y", " full packages send\n" });
+ speedCounter.Stop();
+ // досылка остатка
+ var req = mainSocket.GetPackageClear(64, "<", ">");
+ if (req.ToStr() != "remain request")
+ {
+ throw new Exception("FSP_Upload() error: didn't get remain request");
+ }
+ buffer = new byte[Convert.ToInt32(file.Size - file.Stream.Position)];
+ file.Stream.Read(buffer, 0, buffer.Length);
+ mainSocket.SendPackage(buffer.Length + 16, buffer, "", "");
+ file.Stream.Close();
+ Log(new string[] { "g", $" file {file.ServerFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) uploaded.\n" });
+ }
+
+ // убирает пустые байты в конце пакета
+ static public byte[] GetPackageClear(this Socket socket, int packageSize, string startsWith, string endsWith)
+ {
+ byte[] data = socket.GetPackageRaw(packageSize, startsWith, endsWith);
+ bool clean = false;
+ for (int i = 0; !clean; i++)
+ {
+ if (data[i] != 00)
+ {
+ if (i != 0) data = data.Remove(0, i);
+ clean = true;
+ }
+ else clean = i == data.Length - 1;
+ }
+ return data;
+ }
+ //не убирает пустые байты в конце пакета
+ static public byte[] GetPackageRaw(this Socket socket, int packageSize, string startsWith, string endsWith)
+ {
+ byte[] data = new byte[packageSize];
+ //Log(new string[] { "y", $"GetPackage() packegesize=<","c",packageSize.ToString(),
+ // "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" });
+ for (short s = 0; s < 2000; s += 10)
+ {
+ if (socket.Available >= packageSize)
+ {
+ socket.Receive(data, packageSize, 0);
+ if (data.StartsWith(startsWith) & data.EndsWith(endsWith))
+ {
+ data = data.Remove(0, startsWith.ToBytes().Length);
+ data = data.Remove(data.Length - endsWith.ToBytes().Length, endsWith.ToBytes().Length);
+ return data;
+ }
+ else throw new Exception($"GetPackage() error: has got incorrect package\n");
+ }
+ else Thread.Sleep(10);
+ }
+ throw new Exception($"GetPackage() error: timeout\n");
+ }
+
+ static public void SendPackage(this Socket socket, int length, byte[] data, string startsWith, string endsWith)
+ {
+ var list = new List();
+ list.AddRange(startsWith.ToBytes());
+ int i = startsWith.ToBytes().Length + endsWith.ToBytes().Length + data.Length;
+ //Log(new string[] { "y", $"SendPackage() length=<","c",length.ToString(),"y", "> packegesize=<","c",i.ToString(),
+ // "y", "> data.Length=<","c",data.Length.ToString(), "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" });
+ if (i > length) throw new Exception("SendPackage() error: int length is too small\n");
+ for (; i < length; i++)
+ list.Add(0);
+ list.AddRange(data);
+ list.AddRange(endsWith.ToBytes());
+ socket.Send(list.ToArray());
+ }
+ }
+
+ public class FSP_FileObject
+ {
+ public string ServerFilePath;
+ public string ClientFilePath;
+ public long Size;
+ public byte[] Hash;
+ public Stream Stream;
+
+ public FSP_FileObject(string serverFile, string clientFile)
+ {
+ ServerFilePath = serverFile;
+ ClientFilePath = clientFile;
+ }
+
+ public FSP_FileObject() { }
+ }
+
+ public class ServerObject
+ {
+ public string Address;
+ public string Name;
+ public string Speed;
+
+ public ServerObject(string address, string name, string speed)
+ {
+ Address = address;
+ Name = name;
+ Speed = speed;
+ }
+ }
+
+ public class MessageObject
+ {
+ public uint Number;
+ public DateTime Datetime;
+ public int Sender;
+ public int Channel;
+ public string Text;
+
+ public MessageObject() { }
+
+ public MessageObject(byte[] recieved)
+ {
+ if (recieved.Length != 2284) throw new Exception("incorrect message length: " + recieved.Length);
+ Number = recieved[2];
+ for (byte i = 3; i < 9; i++)
+ {
+ Number = Number * 10 + recieved[i];
+ }
+ Datetime = new DateTime(recieved[9] * 100 + recieved[10], recieved[11], recieved[12],
+ recieved[13], recieved[14], recieved[15]);
+ for (byte i = 16; i < 22; i++)
+ {
+ Sender = Sender * 10 + recieved[i];
+ }
+ for (byte i = 22; i < 28; i++)
+ {
+ Channel = Channel * 10 + recieved[i];
+ }
+ List text = new List();
+ for (short i = 28; i < 2028; i++)
+ {
+ text.Add(recieved[i]);
+ }
+ Text = text.ToStr();
+ //Log($"message <{Number}> is had recieved");
+ }
+ }
+}
diff --git a/.old 3/DTLib/Properties/AssemblyInfo.cs b/.old 3/DTLib/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..c0201c5
--- /dev/null
+++ b/.old 3/DTLib/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные со сборкой.
+[assembly: AssemblyTitle("DTLib")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DTLib")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
+[assembly: ComVisible(false)]
+
+// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
+[assembly: Guid("ce793497-2d5c-42d8-b311-e9b32af9cdfb")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Редакция
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 3/DTLib/SecureHasher.cs b/.old 3/DTLib/SecureHasher.cs
new file mode 100644
index 0000000..691664d
--- /dev/null
+++ b/.old 3/DTLib/SecureHasher.cs
@@ -0,0 +1,97 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace DTLib
+{
+ //
+ // создаёт хеши из массива байт, двух массивов байт, стрима
+ //
+ public class SecureHasher
+ {
+ private dynamic hasher;
+
+ // можно указать размер хеша (по умолчанию 256 байт)
+ public SecureHasher(short type)
+ {
+ switch (type)
+ {
+ case 256:
+ hasher = SHA256.Create();
+ break;
+ case 384:
+ hasher = SHA384.Create();
+ break;
+ case 512:
+ hasher = SHA512.Create();
+ break;
+ default:
+ throw new Exception("unknown hash algorithm type: " + type + "\nin shouid be 256, 384 or 512\n");
+ }
+ }
+ public SecureHasher()
+ {
+ hasher = SHA256.Create();
+ }
+
+ // просто хеш
+ public byte[] Hash(byte[] input)
+ {
+ return hasher.ComputeHash(input);
+ }
+
+ // хеш из двух массивов
+ public byte[] HashSalt(byte[] input, byte[] salt)
+ {
+ List rez = new List();
+ rez.AddRange(input);
+ rez.AddRange(salt);
+ return hasher.ComputeHash(rez.ToArray());
+ }
+
+ // читает стрим и вычисляет хеш всей инфы в нём
+ public byte[] HashStream(Stream st)
+ {
+ byte[] data = new byte[1024];
+ List rez = new List();
+ int offset = 0;
+ while (offset < st.Length)
+ {
+ offset += st.Read(data, offset, 1024);
+ rez.AddRange(hasher.ComputeHash(data));
+ }
+ return hasher.ComputeHash(rez.ToArray());
+ }
+
+ // Хеш двух массивов в цикле.
+ // Работает быстро, так что вполне можно использовать количество циклов до 8к
+
+ public byte[] HashSaltCycled(byte[] input, byte[] salt, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = HashSalt(input, salt);
+ }
+ return input;
+ }
+
+ public byte[] HashCycled(byte[] input, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = Hash(input);
+ }
+ return input;
+ }
+
+ public byte[] HashFile(string filename)
+ {
+ var md5 = MD5.Create();
+ var stream = File.OpenRead(filename);
+ var hash = HashSaltCycled(md5.ComputeHash(stream), filename.ToBytes(), 512);
+ stream.Close();
+ return hash;
+ }
+ }
+}
diff --git a/.old 3/DTLib/SecureRandom.cs b/.old 3/DTLib/SecureRandom.cs
new file mode 100644
index 0000000..98217cf
--- /dev/null
+++ b/.old 3/DTLib/SecureRandom.cs
@@ -0,0 +1,37 @@
+using System.Security.Cryptography;
+
+namespace DTLib
+{
+ //
+ // Вычисление псевдослучайного числа из множества параметров.
+ // Работает медленнее чем класс System.Random, но производит более случайные значения
+ //
+ public class SecureRandom
+ {
+ private RNGCryptoServiceProvider crypt = new RNGCryptoServiceProvider();
+
+ // получение массива случайных байтов
+ public byte[] NextBytes(uint length)
+ {
+ byte[] output = new byte[length];
+ crypt.GetNonZeroBytes(output);
+ return output;
+ }
+
+ // получение случайного числа от 0 до 2147483647
+ /*public int NextInt(uint from, int to)
+ {
+ int output = 0;
+ int rez = 0;
+ while (true)
+ {
+ rez = output * 10 + NextBytes(1)[0];
+ if (rez < to && rez > from)
+ {
+ output = rez;
+ return output;
+ }
+ }
+ }*/
+ }
+}
diff --git a/.old 3/DTLib/SimpleConverter.cs b/.old 3/DTLib/SimpleConverter.cs
new file mode 100644
index 0000000..9f6c1a3
--- /dev/null
+++ b/.old 3/DTLib/SimpleConverter.cs
@@ -0,0 +1,82 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace DTLib
+{
+ //
+ // содержит методы расширения для конвертации байт в строку и наоборот
+ //
+ public static class SimpleConverter
+ {
+ static public Encoding UTF8 = new UTF8Encoding(false);
+ // байты в кодировке UTF8 в строку
+ static public string ToStr(this byte[] bytes)
+ {
+ return UTF8.GetString(bytes);
+ }
+ static public string ToStr(this List bytes)
+ {
+ return UTF8.GetString(bytes.ToArray());
+ }
+
+ static public List ToList(this byte[] input)
+ {
+ var list = new List();
+ list.AddRange(input);
+ return list;
+ }
+
+ static public byte[] Remove(this byte[] input, int startIndex, int count)
+ {
+ List list = input.ToList();
+ list.RemoveRange(startIndex, count);
+ return list.ToArray();
+ }
+
+ // строку в байты
+ static public byte[] ToBytes(this string str)
+ {
+ return UTF8.GetBytes(str);
+ }
+
+ // хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
+ static public string HashToString(this byte[] hash)
+ {
+ var builder = new StringBuilder();
+ for (int i = 0; i < hash.Length; i++)
+ {
+ builder.Append(hash[i].ToString("x2"));
+ }
+ return builder.ToString();
+ }
+
+ static public bool StartsWith(this byte[] source, byte[] startsWith)
+ {
+ for (int i = 0; i < startsWith.Length; i++)
+ {
+ if (source[i] != startsWith[i])
+ return false;
+ }
+ return true;
+ }
+
+ static public bool StartsWith(this byte[] source, string startsWith)
+ => StartsWith(source, startsWith.ToBytes());
+
+ static public bool EndsWith(this byte[] source, byte[] endsWith)
+ {
+ for (int i = 0; i < endsWith.Length; i++)
+ {
+ if (source[source.Length - endsWith.Length + i] != endsWith[i])
+ return false;
+ }
+ return true;
+ }
+ static public bool EndsWith(this byte[] source, string endsWith)
+ => EndsWith(source, endsWith.ToBytes());
+
+ static public int Truncate(decimal number)
+ => Convert.ToInt32(Math.Truncate(number));
+ }
+}
diff --git a/.old 3/DTLib/TImer.cs b/.old 3/DTLib/TImer.cs
new file mode 100644
index 0000000..2383078
--- /dev/null
+++ b/.old 3/DTLib/TImer.cs
@@ -0,0 +1,31 @@
+using System;
+using System.Threading;
+
+namespace DTLib
+{
+ public class Timer
+ {
+ public Thread TimerThread;
+ bool Repeat;
+ public Timer(bool repeat, int delay, Action method)
+ {
+ Repeat = repeat;
+ TimerThread = new Thread(() =>
+ {
+ do
+ {
+ Thread.Sleep(delay);
+ method();
+ } while (Repeat);
+ });
+ TimerThread.Start();
+ }
+
+ public void Stop()
+ {
+ Repeat = false;
+ //throw new Exception("thread stop\n");
+ TimerThread.Abort();
+ }
+ }
+}
diff --git a/.old 3/dtlauncher-client-win/App.config b/.old 3/dtlauncher-client-win/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 3/dtlauncher-client-win/App.xaml b/.old 3/dtlauncher-client-win/App.xaml
new file mode 100644
index 0000000..56be4b8
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/App.xaml
@@ -0,0 +1,166 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 3/dtlauncher-client-win/App.xaml.cs b/.old 3/dtlauncher-client-win/App.xaml.cs
new file mode 100644
index 0000000..4aa3d80
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/App.xaml.cs
@@ -0,0 +1,11 @@
+using System.Windows;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для App.xaml
+ ///
+ public partial class App : Application
+ {
+ }
+}
diff --git a/.old 3/dtlauncher-client-win/LauncherWindow.xaml b/.old 3/dtlauncher-client-win/LauncherWindow.xaml
new file mode 100644
index 0000000..081bf83
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/LauncherWindow.xaml
@@ -0,0 +1,91 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 3/dtlauncher-client-win/LauncherWindow.xaml.cs b/.old 3/dtlauncher-client-win/LauncherWindow.xaml.cs
new file mode 100644
index 0000000..3608bf5
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/LauncherWindow.xaml.cs
@@ -0,0 +1,91 @@
+using DTLib;
+using System;
+using System.IO;
+using System.Net.Sockets;
+using System.Windows;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для LauncherWindow.xaml
+ ///
+ public partial class LauncherWindow : Window
+ {
+ Socket socket;
+ string logfile;
+ public delegate void LaunchDel();
+ public LaunchDel Launch;
+ public ProgramLabel[] programsArray;
+ public int PreviousProgramNum = 0;
+
+ public LauncherWindow(Socket _socket, string _logfile)
+ {
+ InitializeComponent();
+ socket = _socket;
+ logfile = _logfile;
+ NetWork.Log += Log;
+ // переключение вкладок кнопками
+ var green = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(44, 220, 17));
+ var white = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
+ HomeButton.Click += (s, e) =>
+ {
+ LogGrid.Visibility = Visibility.Hidden;
+ SettingsGrid.Visibility = Visibility.Hidden;
+ HomeGrid.Visibility = Visibility.Visible;
+ LogButton.Foreground = white;
+ SettingsButton.Foreground = white;
+ HomeButton.Foreground = green;
+ };
+ LogButton.Click += (s, e) =>
+ {
+ HomeGrid.Visibility = Visibility.Hidden;
+ SettingsGrid.Visibility = Visibility.Hidden;
+ LogGrid.Visibility = Visibility.Visible;
+ HomeButton.Foreground = white;
+ SettingsButton.Foreground = white;
+ LogButton.Foreground = green;
+ };
+ SettingsButton.Click += (s, e) =>
+ {
+ HomeGrid.Visibility = Visibility.Hidden;
+ LogGrid.Visibility = Visibility.Hidden;
+ SettingsGrid.Visibility = Visibility.Visible;
+ HomeButton.Foreground = white;
+ LogButton.Foreground = white;
+ SettingsButton.Foreground = green;
+ };
+ // считывание дескрипторов программ
+ var descriptors = Directory.GetFiles("programs", "*.desc");
+ programsArray = new ProgramLabel[descriptors.Length];
+ Log(descriptors.Length + " descriptors found\n");
+ for (int i = 0; i < descriptors.Length; i++)
+ {
+ Log(descriptors[i] + '\n');
+ //programsArray[i] = new ProgramLabel(descriptors[i], i, this);
+ //ProgramsPanel.Children.Add(programsArray[i]);
+ //Log(programsArray[i].Text + " added to ProgramsPanel\n");
+ }
+ LaunchButton.Click += (s, e) => Launch();
+ //mainSocket.FSP_Download(new FSP_FileObject("share\\file.arc", "downloads\\file.arc"));
+ }
+
+ public void Log(string msg)
+ {
+ msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ LogBox.Text += msg;
+ }
+
+ public void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 3/dtlauncher-client-win/LoginWindow.xaml b/.old 3/dtlauncher-client-win/LoginWindow.xaml
new file mode 100644
index 0000000..c5ba562
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/LoginWindow.xaml
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 3/dtlauncher-client-win/LoginWindow.xaml.cs b/.old 3/dtlauncher-client-win/LoginWindow.xaml.cs
new file mode 100644
index 0000000..3d1a128
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/LoginWindow.xaml.cs
@@ -0,0 +1,144 @@
+using DTLib;
+using System;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Windows;
+using static DTLib.NetWork;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для LoginWindow.xaml
+ ///
+ public partial class LoginWindow : Window
+ {
+ public Socket mainSocket { private set; get; } = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ public string logfile { private set; get; } = $"logs\\client-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+
+ public LoginWindow()
+ {
+ InitializeComponent();
+ try
+ {
+ FileWork.DirExistenceCheck("logs");
+ FileWork.DirExistenceCheck("downloads");
+ NetWork.Log += Log;
+ LoginButton.Click += Login;
+ RegisterButton.Click += Register;
+ Closed += CloseWindow;
+ Log("launcher is starting\n");
+ // подключение к серверу
+ mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(
+ FileWork.ReadFromConfig("client.cfg", "central server ip"))[0],
+ Convert.ToInt32(FileWork.ReadFromConfig("client.cfg", "central server port"))));
+ mainSocket.ReceiveTimeout = 2000;
+ Log("connecting to the main server...");
+ string recieved = mainSocket.Request("new user connection try").ToStr();
+ if (recieved != "new user connection created")
+ throw new Exception("can't connect to the main server");
+ Log("connected to the main server");
+ //NetWork.RequestServersList(mainSocket);
+ }
+ catch (Exception e)
+ {
+ Log("\nerror:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ }
+ }
+
+ void Log(string msg)
+ {
+ msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ LogBox.Text += msg;
+ }
+
+ void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+
+ void Register(object sender, EventArgs e)
+ {
+ try
+ {
+ string login = LoginBox.Text;
+ string password = PasswBox.Password;
+ string filename = $"register-{login}.req";
+
+ var hasher = new SecureHasher(256);
+ if (File.Exists(filename)) File.Delete(filename);
+ var writer = File.CreateText(filename);
+ writer.Write(login + " $" +
+ hasher.HashSaltCycled(password.ToBytes(), login.ToBytes(), 4096)
+ .HashToString());
+ writer.Close();
+ Log($"request file created:{Directory.GetCurrentDirectory()}\\{filename}");
+ }
+ catch (Exception ex)
+ {
+ Log("registration error: " + ex.Message);
+ }
+ }
+
+ void Login(object sender, EventArgs e)
+ {
+ try
+ {
+ /*// пересоздание сокета
+ if (mainSocket.IsBound)
+ {
+ mainSocket.Shutdown(SocketShutdown.Both);
+ mainSocket.Close();
+ mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ }
+
+ var hasher = new SecureHasher(256);
+ // подключение к серверу
+ mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses("m1net.keenetic.pro")[0], 20008));
+ mainSocket.ReceiveTimeout = 5000;
+
+ // авторизация
+ string login = LoginBox.Text;
+ string password = PasswBox.Password;
+
+ string recievedString = NetWork.Request(mainSocket, login).ToStr();
+ if (recievedString != "2e9b7473ce473cdbb9b9e68aa444f5146b1b415a05917aceecd3861804cc2fd8")
+ {
+ throw new Exception("incorrect login\n");
+ }
+
+ recievedString = NetWork.Request(mainSocket,hasher.HashSaltCycled(password.ToBytes(), login.ToBytes(), 4096)).ToStr();
+ if (recievedString != "82c8e541601e0883ea189a285e514adfa6c2da05c83285359bbcf73bd3a8518b")
+ {
+ throw new Exception("incorrect password");
+ }*/
+
+ Log("succesfully login\n");
+ var lauWin = new LauncherWindow(mainSocket, logfile);
+ //CloseSocket(null, null);
+ lauWin.Show();
+ Hide();
+ lauWin.Closed += CloseWindow;
+ }
+ catch (Exception ex)
+ {
+ Log("login error: " + ex.Message + '\n' + ex.StackTrace);
+ }
+ }
+
+ void CloseWindow(object sender, EventArgs e)
+ {
+ Log("DTchat closed");
+ Close();
+ App.Current.Shutdown();
+ }
+ }
+}
diff --git a/.old 3/dtlauncher-client-win/ProgramLabel.xaml b/.old 3/dtlauncher-client-win/ProgramLabel.xaml
new file mode 100644
index 0000000..f193b11
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/ProgramLabel.xaml
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 3/dtlauncher-client-win/ProgramLabel.xaml.cs b/.old 3/dtlauncher-client-win/ProgramLabel.xaml.cs
new file mode 100644
index 0000000..35fc884
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/ProgramLabel.xaml.cs
@@ -0,0 +1,75 @@
+using System.Windows.Controls;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для ProgramLabel.xaml
+ ///
+ public partial class ProgramLabel : UserControl
+ {
+ /*static public DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(ProgramLabel));
+ public string Text
+ {
+ get { return (string)GetValue(TextProperty); }
+ set { SetValue(TextProperty, value); }
+ }
+
+ static public DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(System.Windows.Media.Imaging.BitmapImage), typeof(ProgramLabel));
+ public System.Windows.Media.Imaging.BitmapImage Icon
+ {
+ get { return (System.Windows.Media.Imaging.BitmapImage)GetValue(IconProperty); }
+ set { SetValue(IconProperty, value); }
+ }
+
+ static public DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(ProgramLabel));
+ public CornerRadius CornerRadius
+ {
+ get { return (CornerRadius)GetValue(CornerRadiusProperty); }
+ set { SetValue(CornerRadiusProperty, value); }
+ }*/
+
+ public string BackgroundImage;
+ public string ScriptServerPath;
+ public string InstallDir;
+ public string LaunchFile;
+ public string Arguments;
+ public string Description;
+ public int Number;
+ LauncherWindow Window;
+
+ public ProgramLabel() { }
+
+ /*public ProgramLabel(string descriptorPath, int number, LauncherWindow window)
+ {
+ Window = window;
+ Number = number;
+ //grid.MouseLeftButtonDown += (s, e) => ProgramShow();
+ Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
+ var text = FileWork.ReadFromConfig(descriptorPath, "name");
+ Window.Log(text + '\n');
+ Text = text;
+ //Text = (string)NameLabel.Content;
+ //IconImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\programs\\" + FileWork.ReadFromConfig(descriptorPath, "icon"), UriKind.Absolute));
+ //BackgroundImage = Directory.GetCurrentDirectory() + "\\programs\\" + FileWork.ReadFromConfig(descriptorPath, "background");
+ //ScriptServerPath = FileWork.ReadFromConfig(descriptorPath, "scriptserverpath");
+ //InstallDir = FileWork.ReadFromConfig(descriptorPath, "installdir");
+ //LaunchFile = FileWork.ReadFromConfig(descriptorPath, "launchfile");
+ //if (LaunchFile.Contains("%installdir%")) LaunchFile = LaunchFile.Replace("%installdir%", InstallDir);
+ //Arguments = FileWork.ReadFromConfig(descriptorPath, "arguments");
+ //Description = FileWork.ReadFromConfig(descriptorPath, "description").Replace("\\n", "\r\n");
+ //Window.Log(Text + " " + Icon + " " + Number);
+ }
+
+ void ProgramShow()
+ {
+ Window.programsArray[Window.PreviousProgramNum].Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
+ Window.PreviousProgramNum = Number;
+ Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(170, 170, 240));
+ Window.Log(Directory.GetCurrentDirectory() + '\\' + BackgroundImage + '\n');
+ Window.BackgroundImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(BackgroundImage, UriKind.Absolute));
+ Window.Launch = () => {
+ Process.Start(LaunchFile, Arguments);
+ };
+ }*/
+ }
+}
diff --git a/.old 3/dtlauncher-client-win/ProgramName.xaml b/.old 3/dtlauncher-client-win/ProgramName.xaml
new file mode 100644
index 0000000..34fe69b
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/ProgramName.xaml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
diff --git a/.old 3/dtlauncher-client-win/ProgramName.xaml.cs b/.old 3/dtlauncher-client-win/ProgramName.xaml.cs
new file mode 100644
index 0000000..2cab7b1
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/ProgramName.xaml.cs
@@ -0,0 +1,15 @@
+using System.Windows.Controls;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для ProgramName.xaml
+ ///
+ public partial class ProgramName : UserControl
+ {
+ public ProgramName()
+ {
+ InitializeComponent();
+ }
+ }
+}
diff --git a/.old 3/dtlauncher-client-win/Properties/AssemblyInfo.cs b/.old 3/dtlauncher-client-win/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..bbd57be
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/Properties/AssemblyInfo.cs
@@ -0,0 +1,53 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("dtlauncher-client-win")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-client-win")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM, установите атрибут ComVisible для этого типа в значение true.
+[assembly: ComVisible(false)]
+
+//Чтобы начать создание локализуемых приложений, задайте
+//CultureYouAreCodingWith в файле .csproj
+//в . Например, при использовании английского (США)
+//в своих исходных файлах установите в en-US. Затем отмените преобразование в комментарий
+//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
+//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+ ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
+ //(используется, если ресурс не найден на странице,
+ // или в словарях ресурсов приложения)
+ ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
+ //(используется, если ресурс не найден на странице,
+ // в приложении или в каких-либо словарях ресурсов для конкретной темы)
+)]
+
+
+// Сведения о версии для сборки включают четыре следующих значения:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 3/dtlauncher-client-win/Properties/Resources.Designer.cs b/.old 3/dtlauncher-client-win/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..615ca67
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/Properties/Resources.Designer.cs
@@ -0,0 +1,70 @@
+//------------------------------------------------------------------------------
+//
+// Этот код был создан программным средством.
+// Версия среды выполнения: 4.0.30319.42000
+//
+// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
+// код создан повторно.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_client_win.Properties
+{
+ ///
+ /// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
+ ///
+ // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
+ // класс с помощью таких средств, как ResGen или Visual Studio.
+ // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
+ // с параметром /str или заново постройте свой VS-проект.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_client_win.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Переопределяет свойство CurrentUICulture текущего потока для всех
+ /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/.old 3/dtlauncher-client-win/Properties/Resources.resx b/.old 3/dtlauncher-client-win/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/.old 3/dtlauncher-client-win/Properties/Settings.Designer.cs b/.old 3/dtlauncher-client-win/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..1c4561e
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/Properties/Settings.Designer.cs
@@ -0,0 +1,29 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_client_win.Properties
+{
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/.old 3/dtlauncher-client-win/Properties/Settings.settings b/.old 3/dtlauncher-client-win/Properties/Settings.settings
new file mode 100644
index 0000000..033d7a5
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 3/dtlauncher-client-win/divinity2devcut_background.jpg b/.old 3/dtlauncher-client-win/divinity2devcut_background.jpg
new file mode 100644
index 0000000..545c9e9
Binary files /dev/null and b/.old 3/dtlauncher-client-win/divinity2devcut_background.jpg differ
diff --git a/.old 3/dtlauncher-client-win/dtlauncher-client-win.csproj b/.old 3/dtlauncher-client-win/dtlauncher-client-win.csproj
new file mode 100644
index 0000000..468c870
--- /dev/null
+++ b/.old 3/dtlauncher-client-win/dtlauncher-client-win.csproj
@@ -0,0 +1,124 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}
+ WinExe
+ dtlauncher_client_win
+ dtlauncher-client-win
+ v4.8
+ 512
+ {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ 4
+ true
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+ dtlauncher_client_win.App
+
+
+
+
+
+
+
+
+
+
+
+ 4.0
+
+
+
+
+
+
+
+ MSBuild:Compile
+ Designer
+
+
+ Designer
+ MSBuild:Compile
+
+
+ MSBuild:Compile
+ Designer
+
+
+ App.xaml
+ Code
+
+
+ LauncherWindow.xaml
+
+
+ LoginWindow.xaml
+ Code
+
+
+ Designer
+ MSBuild:Compile
+
+
+ Designer
+ MSBuild:Compile
+
+
+
+
+ ProgramLabel.xaml
+
+
+ ProgramName.xaml
+
+
+ Code
+
+
+ True
+ True
+ Resources.resx
+
+
+ True
+ Settings.settings
+ True
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+
+
+
+ del /f /q dtlauncher-client-win.exe.config
+
+
\ No newline at end of file
diff --git a/.old 3/dtlauncher-server-win/App.config b/.old 3/dtlauncher-server-win/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 3/dtlauncher-server-win/App.xaml b/.old 3/dtlauncher-server-win/App.xaml
new file mode 100644
index 0000000..2963033
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/App.xaml
@@ -0,0 +1,94 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 3/dtlauncher-server-win/App.xaml.cs b/.old 3/dtlauncher-server-win/App.xaml.cs
new file mode 100644
index 0000000..bacff7e
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/App.xaml.cs
@@ -0,0 +1,11 @@
+using System.Windows;
+
+namespace dtlauncher_server_win
+{
+ ///
+ /// Логика взаимодействия для App.xaml
+ ///
+ public partial class App : Application
+ {
+ }
+}
diff --git a/.old 3/dtlauncher-server-win/Properties/AssemblyInfo.cs b/.old 3/dtlauncher-server-win/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..340af78
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/Properties/AssemblyInfo.cs
@@ -0,0 +1,53 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("dtlauncher-server-win")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-server-win")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM, установите атрибут ComVisible для этого типа в значение true.
+[assembly: ComVisible(false)]
+
+//Чтобы начать создание локализуемых приложений, задайте
+//CultureYouAreCodingWith в файле .csproj
+//в . Например, при использовании английского (США)
+//в своих исходных файлах установите в en-US. Затем отмените преобразование в комментарий
+//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
+//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+ ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
+ //(используется, если ресурс не найден на странице,
+ // или в словарях ресурсов приложения)
+ ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
+ //(используется, если ресурс не найден на странице,
+ // в приложении или в каких-либо словарях ресурсов для конкретной темы)
+)]
+
+
+// Сведения о версии для сборки включают четыре следующих значения:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 3/dtlauncher-server-win/Properties/Resources.Designer.cs b/.old 3/dtlauncher-server-win/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..9d42357
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/Properties/Resources.Designer.cs
@@ -0,0 +1,70 @@
+//------------------------------------------------------------------------------
+//
+// Этот код был создан программным средством.
+// Версия среды выполнения: 4.0.30319.42000
+//
+// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
+// код создан повторно.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_server_win.Properties
+{
+ ///
+ /// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
+ ///
+ // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
+ // класс с помощью таких средств, как ResGen или Visual Studio.
+ // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
+ // с параметром /str или заново постройте свой VS-проект.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_server_win.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Переопределяет свойство CurrentUICulture текущего потока для всех
+ /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/.old 3/dtlauncher-server-win/Properties/Resources.resx b/.old 3/dtlauncher-server-win/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/.old 3/dtlauncher-server-win/Properties/Settings.Designer.cs b/.old 3/dtlauncher-server-win/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..cb2dff3
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/Properties/Settings.Designer.cs
@@ -0,0 +1,29 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_server_win.Properties
+{
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/.old 3/dtlauncher-server-win/Properties/Settings.settings b/.old 3/dtlauncher-server-win/Properties/Settings.settings
new file mode 100644
index 0000000..033d7a5
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 3/dtlauncher-server-win/ServerWindow.xaml b/.old 3/dtlauncher-server-win/ServerWindow.xaml
new file mode 100644
index 0000000..5988e2d
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/ServerWindow.xaml
@@ -0,0 +1,12 @@
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 3/dtlauncher-server-win/ServerWindow.xaml.cs b/.old 3/dtlauncher-server-win/ServerWindow.xaml.cs
new file mode 100644
index 0000000..2c4f25c
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/ServerWindow.xaml.cs
@@ -0,0 +1,116 @@
+using DTLib;
+using System;
+using System.Net.Sockets;
+using System.Threading;
+using System.Windows;
+using static DTLib.NetWork;
+
+namespace dtlauncher_server_win
+{
+ ///
+ /// Логика взаимодействия для ServerWindow.xaml
+ ///
+ public partial class ServerWindow : Window
+ {
+ static string logfile = $"logs\\server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+ static Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+
+ public ServerWindow()
+ {
+ InitializeComponent();
+ /*while (true)
+ {
+ try
+ {
+ FileWork.DirExistenceCheck("logs");
+ FileWork.DirExistenceCheck("share");
+ NetWork.Log += Log;
+ Log($"<{FileWork.ReadFromConfig("server.cfg", "server ip")}> : <{Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))}>\n");
+ mainSocket.Bind(new IPEndPoint(IPAddress.Parse(FileWork.ReadFromConfig("server.cfg", "server ip")), Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))));
+ Log("server started succesfully\n");
+ try
+ {
+ mainSocket.Listen(200);
+ while (true)
+ {
+ var userSocket = mainSocket.Accept();
+ var userThread = new Thread(new ParameterizedThreadStart(UserStart));
+ userThread.Start(userSocket);
+ }
+ }
+ catch (Exception ex)
+ {
+ Log($"handler error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ }
+ catch (Exception ex)
+ {
+ if (mainSocket.IsBound) mainSocket.CloseSocket();
+ Log($"Main() error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ Thread.Sleep(1500);
+ }*/
+ }
+
+ void Log(string msg)
+ {
+ msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ //LogBox.Text += msg;
+ }
+
+ void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+
+ void UserStart(dynamic _handlerSocket)
+ {
+ Socket handlerSocket = (Socket)_handlerSocket;
+ Log("user connected\n");
+ try
+ {
+ string recieved = handlerSocket.GetData().ToStr();
+ if (recieved == "new user connection try")
+ {
+ handlerSocket.Send("new user connection created".ToBytes());
+ while (true)
+ {
+ recieved = handlerSocket.GetData().ToStr();
+ switch (recieved)
+ {
+ // ответ на NetWork.Ping()
+ case "ping":
+ handlerSocket.Send("pong".ToBytes());
+ break;
+ // отправка списка активных серверов
+ case "requesting servers list":
+
+ break;
+ // отправка файла
+ case "requesting file download":
+ handlerSocket.FSP_Upload();
+ break;
+ default:
+ throw new Exception("unknown request: " + recieved);
+ }
+ }
+ }
+ else throw new Exception("incorrect connection try");
+ }
+ catch (Exception ex)
+ {
+ Log($"UserStart() error:\n message:\n {ex.Message}\n{ex.StackTrace}\n");
+ handlerSocket.CloseSocket();
+ Thread.CurrentThread.Abort();
+ }
+ }
+ }
+}
diff --git a/.old 3/dtlauncher-server-win/dtlauncher-server-win.csproj b/.old 3/dtlauncher-server-win/dtlauncher-server-win.csproj
new file mode 100644
index 0000000..0ce2cf8
--- /dev/null
+++ b/.old 3/dtlauncher-server-win/dtlauncher-server-win.csproj
@@ -0,0 +1,127 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}
+ WinExe
+ dtlauncher_server_win
+ dtlauncher-server-win
+ v4.8
+ 512
+ {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ 4
+ true
+ true
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+ dtlauncher_server_win.App
+
+
+
+
+
+
+
+
+
+
+
+ 4.0
+
+
+
+
+
+
+
+ MSBuild:Compile
+ Designer
+
+
+ MSBuild:Compile
+ Designer
+
+
+ App.xaml
+ Code
+
+
+ ServerWindow.xaml
+ Code
+
+
+
+
+ Code
+
+
+ True
+ True
+ Resources.resx
+
+
+ True
+ Settings.settings
+ True
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+ False
+ Microsoft .NET Framework 4.8 %28x86 и x64%29
+ true
+
+
+ False
+ .NET Framework 3.5 SP1
+ false
+
+
+
+
+ del /f /q dtlauncher-server-win.exe.config
+
+
\ No newline at end of file
diff --git a/.old 3/dtlauncher.sln b/.old 3/dtlauncher.sln
new file mode 100644
index 0000000..a8c29fa
--- /dev/null
+++ b/.old 3/dtlauncher.sln
@@ -0,0 +1,36 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30907.101
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-client-win", "dtlauncher-client-win\dtlauncher-client-win.csproj", "{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-server-win", "dtlauncher-server-win\dtlauncher-server-win.csproj", "{8B9889A7-93DC-4914-92D1-8209BD3BA71A}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Build|Any CPU = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.Build.0 = Build|Any CPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.Build.0 = Build|Any CPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.Build.0 = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {E6569C0C-DD32-4F7D-AD4C-DBC5434D2F8C}
+ EndGlobalSection
+EndGlobal
diff --git a/.old 4/DTLib/Color.cs b/.old 4/DTLib/Color.cs
new file mode 100644
index 0000000..dbc8a69
--- /dev/null
+++ b/.old 4/DTLib/Color.cs
@@ -0,0 +1,57 @@
+using System;
+
+namespace DTLib
+{
+ public class Color
+ {
+ public class RGBA
+ {
+ public byte R;
+ public byte G;
+ public byte B;
+ public byte A;
+
+ public RGBA() { }
+
+ public RGBA(byte R, byte G, byte B, byte A)
+ {
+ this.R = R;
+ this.G = G;
+ this.B = B;
+ this.A = A;
+ }
+
+ public RGBA(byte[] arrayRGBA)
+ {
+ if (arrayRGBA.Length != 4) throw new Exception("Color.RGBA(byte[] arrayRGBA) error: arrayRGBA.Length != 4\n");
+ R = arrayRGBA[0];
+ G = arrayRGBA[1];
+ B = arrayRGBA[2];
+ A = arrayRGBA[3];
+ }
+ }
+ public class RGB
+ {
+ public byte R;
+ public byte G;
+ public byte B;
+
+ public RGB() { }
+
+ public RGB(byte R, byte G, byte B)
+ {
+ this.R = R;
+ this.G = G;
+ this.B = B;
+ }
+
+ public RGB(byte[] arrayRGB)
+ {
+ if (arrayRGB.Length != 4) throw new Exception("Color.RGB(byte[] arrayRGB) error: arrayRGB.Length != 4\n");
+ R = arrayRGB[0];
+ G = arrayRGB[1];
+ B = arrayRGB[2];
+ }
+ }
+ }
+}
diff --git a/.old 4/DTLib/ColoredConsole.cs b/.old 4/DTLib/ColoredConsole.cs
new file mode 100644
index 0000000..2ae162d
--- /dev/null
+++ b/.old 4/DTLib/ColoredConsole.cs
@@ -0,0 +1,83 @@
+using System;
+
+namespace DTLib
+{
+ //
+ // вывод и ввод цветного текста в консоли
+ // работает медленнее чем хотелось бы
+ //
+ public static class ColoredConsole
+ {
+ // парсит название цвета в ConsoleColor
+ public static ConsoleColor ParseColor(string color)
+ {
+ switch (color)
+ {
+ //case "magneta":
+ case "m":
+ return ConsoleColor.Magenta;
+ //case "green":
+ case "g":
+ return ConsoleColor.Green;
+ //case "red":
+ case "r":
+ return ConsoleColor.Red;
+ //case "yellow":
+ case "y":
+ return ConsoleColor.Yellow;
+ //case "white":
+ case "w":
+ return ConsoleColor.White;
+ //case "blue":
+ case "b":
+ return ConsoleColor.Blue;
+ //case "cyan":
+ case "c":
+ return ConsoleColor.Cyan;
+ //case "gray":
+ case "gray":
+ return ConsoleColor.Gray;
+ //case "black":
+ case "black":
+ return ConsoleColor.Black;
+ default:
+ throw new Exception("incorrect color: " + color);
+ }
+ }
+
+ // вывод цветного текста
+ public static void Write(params string[] input)
+ {
+ if (input.Length == 1)
+ {
+ if (Console.ForegroundColor != ConsoleColor.Green) Console.ForegroundColor = ConsoleColor.Gray;
+ Console.Write(input[0]);
+ }
+ else if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ var c = ParseColor(input[i]);
+ if (Console.ForegroundColor != c)
+ {
+ Console.Write(str);
+ Console.ForegroundColor = c;
+ str = "";
+ }
+ str += input[++i];
+ }
+ if (str != "") Console.Write(str);
+ }
+ else throw new Exception("error in Write(): every text string must have color string before");
+ }
+
+ // ввод цветного текста
+ public static string Read(string color)
+ {
+ var c = ParseColor(color);
+ if (Console.ForegroundColor != c) Console.ForegroundColor = c;
+ return Console.ReadLine();
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 4/DTLib/CompressedArray.cs b/.old 4/DTLib/CompressedArray.cs
new file mode 100644
index 0000000..bb09edc
--- /dev/null
+++ b/.old 4/DTLib/CompressedArray.cs
@@ -0,0 +1,72 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace DTLib
+{
+ public class CompressedArray
+ {
+ public class Array1D where T : IComparable
+ {
+ byte[] Description;
+ T[] Memory;
+
+ public Array1D() { }
+ public Array1D(T[] sourceArray)
+ {
+ CompressArray(sourceArray);
+ }
+
+ public void CompressArray(T[] sourceArray)
+ {
+ var listMem = new List();
+ var listDesc = new List();
+ T prevElement = sourceArray[0];
+ listMem.Add(sourceArray[0]);
+ listDesc.Add(1);
+ byte repeats = 1;
+ for (int i = 1; i < sourceArray.Length; i++)
+ {
+ if (prevElement.CompareTo(sourceArray[i]) == 0) repeats++;
+ else
+ {
+ listMem.Add(sourceArray[i]);
+ listDesc.Add(1);
+ if (repeats > 1)
+ {
+ listDesc[listDesc.Count - 2] = repeats;
+ repeats = 1;
+ }
+ }
+ prevElement = sourceArray[i];
+ }
+ Memory = listMem.ToArray();
+ Description = listDesc.ToArray();
+ ColoredConsole.Write("b", "listMem.Count: ", "c", listMem.Count.ToString(), "b", " listDesc.Count: ", "c", listDesc.Count + "\n");
+ for (short i = 0; i < listDesc.Count; i++)
+ {
+ ColoredConsole.Write("y", $"{Description[i]}:{Memory[i]}\n");
+ }
+ }
+
+ // блокирует обращение к памяти из нескольких потоков
+ Mutex storageUsing = new Mutex();
+
+ // возвращает элемент по индексу так, как если бы шло обращение к обычном массиву
+ public T GetElement(int index)
+ {
+ storageUsing.WaitOne();
+ T output = default;
+ int sum = 0;
+ for (int i = 0; i < Description.Length; i++)
+ {
+ if (sum < index) sum += Description[i];
+ else if (sum == index) output = Memory[i];
+ else output = Memory[i - 1];
+ }
+ storageUsing.ReleaseMutex();
+ return output;
+ }
+ }
+ }
+}
diff --git a/.old 4/DTLib/DTLib.csproj b/.old 4/DTLib/DTLib.csproj
new file mode 100644
index 0000000..a785bed
--- /dev/null
+++ b/.old 4/DTLib/DTLib.csproj
@@ -0,0 +1,52 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ Library
+ Properties
+ DTLib
+ DTLib
+ v4.8
+ 512
+ true
+
+
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 4/DTLib/FileWork.cs b/.old 4/DTLib/FileWork.cs
new file mode 100644
index 0000000..34457f6
--- /dev/null
+++ b/.old 4/DTLib/FileWork.cs
@@ -0,0 +1,167 @@
+using System.Collections.Generic;
+using System.IO;
+
+namespace DTLib
+{
+ //
+ // методы для работы с файловой системой
+ //
+ public static class FileWork
+ {
+ // записывает текст в файл и закрывает файл
+ public static void Log(string logfile, string msg)
+ {
+ lock (new object())
+ {
+ var st = File.Open(logfile, FileMode.Append);
+ var writer = new StreamWriter(st, SimpleConverter.UTF8);
+ writer.Write(msg);
+ writer.Close();
+ st.Close();
+ }
+ }
+
+ // создает папку если её не существует
+ public static void DirCreate(string dir)
+ {
+ if (!Directory.Exists(dir))
+ {
+ // проверяет существование папки, в которой нужно создать dir
+ if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
+ DirCreate(dir.Remove(dir.LastIndexOf('\\')));
+ Directory.CreateDirectory(dir);
+ }
+ }
+
+ // чтение параметров из конфига
+ public static string ReadFromConfig(string configfile, string key)
+ {
+ key += ": ";
+ var reader = new StreamReader(configfile);
+ while (!reader.EndOfStream)
+ {
+ string st = reader.ReadLine();
+ if (st.StartsWith(key))
+ {
+ string value = "";
+ for (int i = key.Length; i < st.Length; i++)
+ {
+ if (st[i] == '#') return value;
+ if (st[i] == '%')
+ {
+ bool stop = false;
+ string placeholder = "";
+ i++;
+ while (!stop)
+ {
+ if (st[i] == '%')
+ {
+ stop = true;
+ value += ReadFromConfig(configfile, placeholder);
+ }
+ else
+ {
+ placeholder += st[i];
+ i++;
+ }
+ }
+ }
+ else value += st[i];
+ }
+ return value;
+ }
+ }
+ reader.Close();
+ return null;
+ }
+
+ // копирует все файли и папки
+ public static void DirCopy(string source_dir, string new_dir, bool Override)
+ {
+ DirCreate(new_dir);
+ List subdirs = new List();
+ List files = GetAllFiles(source_dir, ref subdirs);
+ for (int i = 0; i < subdirs.Count; i++)
+ {
+ DirCreate(subdirs[i].Replace(source_dir, new_dir));
+ }
+ for (int i = 0; i < files.Count; i++)
+ {
+ string f = files[i].Replace(source_dir, new_dir);
+ File.Copy(files[i], f, Override);
+ //PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
+ }
+ }
+
+ // копирует все файли и папки и выдаёт список конфликтующих файлов
+ public static void DirCopy(string source_dir, string new_dir, bool owerwrite, out List conflicts)
+ {
+ conflicts = new List();
+ var subdirs = new List();
+ var files = GetAllFiles(source_dir, ref subdirs);
+ DirCreate(new_dir);
+ for (int i = 0; i < subdirs.Count; i++)
+ {
+ DirCreate(subdirs[i].Replace(source_dir, new_dir));
+ }
+ for (int i = 0; i < files.Count; i++)
+ {
+ string newfile = files[i].Replace(source_dir, new_dir);
+ if (File.Exists(newfile)) conflicts.Add(newfile);
+ File.Copy(files[i], newfile, owerwrite);
+ //PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
+ }
+ }
+
+ // выдает список всех файлов
+ public static List GetAllFiles(string dir)
+ {
+ List all_files = new List();
+ string[] cur_files = Directory.GetFiles(dir);
+ for (int i = 0; i < cur_files.Length; i++)
+ {
+ all_files.Add(cur_files[i]);
+ //PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
+ }
+ string[] cur_subdirs = Directory.GetDirectories(dir);
+ for (int i = 0; i < cur_subdirs.Length; i++)
+ {
+ //PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
+ all_files.AddRange(GetAllFiles(cur_subdirs[i]));
+ }
+ return all_files;
+ }
+
+ // выдает список всех файлов и подпапок в папке
+ public static List GetAllFiles(string dir, ref List all_subdirs)
+ {
+ List all_files = new List();
+ string[] cur_files = Directory.GetFiles(dir);
+ for (int i = 0; i < cur_files.Length; i++)
+ {
+ all_files.Add(cur_files[i]);
+ //PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
+ }
+ string[] cur_subdirs = Directory.GetDirectories(dir);
+ for (int i = 0; i < cur_subdirs.Length; i++)
+ {
+ all_subdirs.Add(cur_subdirs[i]);
+ //PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
+ all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs));
+ }
+ return all_files;
+ }
+
+ // удаляет папку со всеми подпапками и файлами
+ public static void DirDelete(string dir)
+ {
+ var subdirs = new List();
+ var files = GetAllFiles(dir, ref subdirs);
+ for (int i = 0; i < files.Count; i++)
+ File.Delete(files[i]);
+ for (int i = subdirs.Count - 1; i >= 0; i--)
+ Directory.Delete(subdirs[i]);
+ Directory.Delete(dir);
+ }
+ }
+}
diff --git a/.old 4/DTLib/Hasher.cs b/.old 4/DTLib/Hasher.cs
new file mode 100644
index 0000000..c1c8843
--- /dev/null
+++ b/.old 4/DTLib/Hasher.cs
@@ -0,0 +1,59 @@
+using System.Collections.Generic;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace DTLib
+{
+ //
+ // хеширует массивы байтов алшоритмом SHA256 и файлы алгоримом XXHash32
+ //
+ public class Hasher
+ {
+ readonly HashAlgorithm sha256 = SHA256.Create();
+ readonly HashAlgorithm xxh32 = XXHash32.Create();
+
+ public Hasher() { }
+
+ // хеш массива
+ public byte[] Hash(byte[] input)
+ => sha256.ComputeHash(input);
+
+ // хеш из двух массивов
+ public byte[] Hash(byte[] input, byte[] salt)
+ {
+ List rez = new List();
+ rez.AddRange(input);
+ rez.AddRange(salt);
+ return sha256.ComputeHash(rez.ToArray());
+ }
+
+ // хеш двух массивов зацикленный
+ public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = Hash(input, salt);
+ }
+ return input;
+ }
+ // хеш зацикленный
+ public byte[] HashCycled(byte[] input, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = Hash(input);
+ }
+ return input;
+ }
+
+ // хеш файла
+ public byte[] HashFile(string filename)
+ {
+ //var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
+ var hash = xxh32.ComputeHash(File.OpenRead(filename));
+ //var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
+ //PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}\n");
+ return hash;
+ }
+ }
+}
diff --git a/.old 4/DTLib/NetWork.cs b/.old 4/DTLib/NetWork.cs
new file mode 100644
index 0000000..c14b578
--- /dev/null
+++ b/.old 4/DTLib/NetWork.cs
@@ -0,0 +1,290 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using static DTLib.PublicLog;
+
+namespace DTLib
+{
+ //
+ // весь униврсальный неткод тут
+ // большинство методов предназначены для работы с TCP сокетами (Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ //
+ public static class NetWork
+ {
+ // получение информации (сокет должен быть в режиме Listen)
+ public static byte[] GetData(this Socket socket)
+ {
+ List output = new List();
+ byte[] data = new byte[256];
+ do
+ {
+ int amount = socket.Receive(data, data.Length, 0);
+ for (int i = 0; i < amount; i++)
+ {
+ output.Add(data[i]);
+ }
+ }
+ while (socket.Available > 0);
+ return output.ToArray();
+ }
+
+ // отправка запроса и получение ответа на него (сокет должен быть в режиме Listen)
+ public static byte[] Request(this Socket socket, string request)
+ {
+ socket.Send(request.ToBytes());
+ return GetData(socket);
+ }
+ public static byte[] Request(this Socket socket, byte[] request)
+ {
+ socket.Send(request);
+ return GetData(socket);
+ }
+
+ // скачивание файла с фтп сервера
+ public static void FtpDownload(string address, string login, string password, string outfile)
+ {
+ try
+ {
+ // debug
+ Log(new string[] { "y", "file on server: <", "c", address, "y", ">\nfile on client: <", "c", outfile, "y", ">\n" });
+ // создание запроса
+ // "ftp://m1net.keenetic.pro:20000/" + @infile
+ FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
+ request.Credentials = new NetworkCredential(login, password);
+ request.Method = WebRequestMethods.Ftp.DownloadFile;
+ // получение ответа на запрос
+ FtpWebResponse response = (FtpWebResponse)request.GetResponse();
+ Stream responseStream = response.GetResponseStream();
+ FileStream fs = new FileStream(@Directory.GetCurrentDirectory() + '\\' + @outfile, FileMode.Create);
+ byte[] buffer = new byte[64];
+ int size = 0;
+
+ while ((size = responseStream.Read(buffer, 0, buffer.Length)) > 0)
+ fs.Write(buffer, 0, size);
+ fs.Close();
+ response.Close();
+ }
+ catch (WebException e) { throw new Exception("ftp error:\n" + ((FtpWebResponse)e.Response).StatusDescription + '\n'); }
+ }
+
+ // запрашивает список серверов с главного сервера
+ public static ServerObject[] RequestServersList(Socket centralServer)
+ {
+ List servers = new List();
+ string[] lines = Request(centralServer, "a356a4257dbf9d87c77cf87c3c694b30160b6ddfd3db82e7f62320207109e352").ToStr().Split('\n');
+ for (int i = 0; i < lines.Length; i++)
+ {
+ string[] properties = lines[i].Split(',');
+ servers.Add(new ServerObject(properties[0], properties[1], properties[2]));
+ }
+ return servers.ToArray();
+ }
+
+ // пингует айпи с помощью встроенной в винду проги, возвращает задержку
+ public static string PingIP(string address)
+ {
+ Process proc = new Process();
+ proc.StartInfo.FileName = "cmd.exe";
+ proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address;
+ proc.StartInfo.CreateNoWindow = true;
+ proc.StartInfo.UseShellExecute = false;
+ proc.StartInfo.RedirectStandardOutput = true;
+ proc.Start();
+ var outStream = proc.StandardOutput;
+ var rezult = outStream.ReadToEnd();
+ rezult = rezult.Remove(0, rezult.LastIndexOf('=') + 2);
+ return rezult.Remove(rezult.Length - 4);
+ }
+
+ // пингует сервер (сервер должен уметь принимать такой запрос от клиента), возвращает true если сервер правильно ответил
+ public static bool Ping(this Socket socket)
+ {
+ if (Request(socket, "ab53bf045004875fb17086f7f992b0514fb96c038f336e0bfc21609b20303f07").ToStr() == "91b5c0383b75fb1708f00486f7f9b96c038ab3bfc21059b20176f603692b05e0") return true;
+ else return false;
+ }
+
+ // скачивает файл с помощью моего собственного протокола
+ public static void FSP_Download(this Socket mainSocket, FSP_FileObject file)
+ {
+ Log(new string[] { "c", $"remote socket accepted download request: {file.ClientFilePath}\n" });
+ mainSocket.Send("requesting file download".ToBytes());
+ string answ = mainSocket.GetPackageClear(64, "<", ">").ToStr();
+ if (answ != "download request accepted")
+ throw new Exception($"FSP_Download() error: a download socket recieved an incorrect message: {answ}\n");
+
+ mainSocket.SendPackage(276, file.ServerFilePath.ToBytes(), "", "");
+ file.Size = Convert.ToUInt32(mainSocket.GetPackageClear(64, "", "").ToStr());
+ file.Hash = mainSocket.GetPackageClear(64, "", "");
+ mainSocket.SendPackage(64, "ready".ToBytes(), "<", ">");
+ file.Stream = File.Open(file.ClientFilePath, FileMode.Create, FileAccess.Write);
+ int packagesCount = 0;
+ byte[] buffer = new byte[5120];
+ var hashstr = file.Hash.HashToString();
+ int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
+ // рассчёт скорости
+ int seconds = 0;
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // получение файла
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ string header = $"<{packagesCount}>";
+ buffer = mainSocket.GetPackageRaw(buffer.Length + 2 + header.Length, header, "<>");
+ file.Stream.Write(buffer, 0, buffer.Length);
+ file.Stream.Flush();
+ }
+ Log(new string[] { "y", " full packages recieved\n" });
+ speedCounter.Stop();
+ // получение остатка
+ mainSocket.SendPackage(64, "remain request".ToBytes(), "<", ">");
+ buffer = mainSocket.GetPackageRaw(Convert.ToInt32(file.Size - fullPackagesCount * 5120) + 16, "", "");
+ file.Stream.Write(buffer, 0, buffer.Length);
+ file.Stream.Flush();
+ file.Stream.Close();
+ Log(new string[] { "g", $" file {file.ClientFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) downloaded.\n" });
+ }
+
+ // отдаёт файл с помощью моего протокола
+ public static void FSP_Upload(this Socket mainSocket)
+ {
+ mainSocket.SendPackage(64, "download request accepted".ToBytes(), "<", ">");
+ var file = new FSP_FileObject
+ {
+ ServerFilePath = mainSocket.GetPackageClear(276, "", "").ToStr()
+ };
+ file.Size = new FileInfo(file.ServerFilePath).Length;
+ file.Hash = new Hasher().HashFile(file.ServerFilePath);
+ mainSocket.SendPackage(64, file.Size.ToString().ToBytes(), "", "");
+ mainSocket.SendPackage(64, file.Hash, "", "");
+ if (mainSocket.GetPackageClear(64, "<", ">").ToStr() != "ready")
+ throw new Exception("user socket isn't ready");
+ Log(new string[] { "c", $"local socket accepted file download request: {file.ServerFilePath}\n" });
+ file.Stream = new FileStream(file.ServerFilePath, FileMode.Open, FileAccess.Read);
+ byte[] buffer = new byte[5120];
+ var hashstr = file.Hash.HashToString();
+ int packagesCount = 0;
+ int seconds = 0;
+ // рассчёт скорости
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // отправка файла
+ int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ string header = $"<{packagesCount}>";
+ file.Stream.Read(buffer, 0, buffer.Length);
+ try { mainSocket.SendPackage(buffer.Length + 2 + header.Length, buffer, header, "<>"); }
+ catch (Exception ex) { Log(new string[] { "r", "FSP_Upload() error: " + ex.Message + "\n" + ex.StackTrace + '\n' }); }
+ }
+ Log(new string[] { "y", " full packages send\n" });
+ speedCounter.Stop();
+ // досылка остатка
+ var req = mainSocket.GetPackageClear(64, "<", ">");
+ if (req.ToStr() != "remain request")
+ throw new Exception("FSP_Upload() error: didn't get remain request");
+ buffer = new byte[Convert.ToInt32(file.Size - file.Stream.Position)];
+ file.Stream.Read(buffer, 0, buffer.Length);
+ mainSocket.SendPackage(buffer.Length + 16, buffer, "", "");
+ file.Stream.Close();
+ Log(new string[] { "g", $" file {file.ServerFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) uploaded.\n" });
+ }
+
+ // ждёт пакет заданного размера с заданным началом и концом
+ // убирает пустые байты в конце пакета
+ public static byte[] GetPackageClear(this Socket socket, int packageSize, string startsWith, string endsWith)
+ {
+ byte[] data = socket.GetPackageRaw(packageSize, startsWith, endsWith);
+ bool clean = false;
+ for (int i = 0; !clean; i++)
+ {
+ if (data[i] != 00)
+ {
+ if (i != 0) data = data.RemoveRange(0, i);
+ clean = true;
+ }
+ else clean = i == data.Length - 1;
+ }
+ return data;
+ }
+ //не убирает пустые байты в конце пакета
+ public static byte[] GetPackageRaw(this Socket socket, int packageSize, string startsWith, string endsWith)
+ {
+ byte[] data = new byte[packageSize];
+ //Log(new string[] { "y", $"GetPackage() packegesize=<","c",packageSize.ToString(),
+ // "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" });
+ for (short s = 0; s < 2000; s += 10)
+ {
+ if (socket.Available >= packageSize)
+ {
+ socket.Receive(data, packageSize, 0);
+ if (data.StartsWith(startsWith.ToBytes()) & data.EndsWith(endsWith.ToBytes()))
+ {
+ data = data.RemoveRange(0, startsWith.ToBytes().Length);
+ data = data.RemoveRange(data.Length - endsWith.ToBytes().Length, endsWith.ToBytes().Length);
+ return data;
+ }
+ else throw new Exception($"GetPackage() error: has got incorrect package\n");
+ }
+ else Thread.Sleep(10);
+ }
+ throw new Exception($"GetPackage() error: timeout\n");
+ }
+
+ // отправляет пакет заданного размера, добавля в начало и конец заданные значения
+ public static void SendPackage(this Socket socket, int length, byte[] data, string startsWith, string endsWith)
+ {
+ var list = new List();
+ list.AddRange(startsWith.ToBytes());
+ int i = startsWith.ToBytes().Length + endsWith.ToBytes().Length + data.Length;
+ //Log(new string[] { "y", $"SendPackage() length=<","c",length.ToString(),"y", "> packegesize=<","c",i.ToString(),
+ // "y", "> data.Length=<","c",data.Length.ToString(), "y", "> startsWith=<", "c", startsWith, "y", "> endsWith=<", "c", endsWith, "y", ">\n" });
+ if (i > length) throw new Exception("SendPackage() error: int length is too small\n");
+
+ for (; i < length; i++) list.Add(0);
+ list.AddRange(data);
+ list.AddRange(endsWith.ToBytes());
+ socket.Send(list.ToArray());
+ }
+
+
+
+ // хранит свойства файла, передаваемого с помощью моего протокола
+ public class FSP_FileObject
+ {
+ public string ServerFilePath;
+ public string ClientFilePath;
+ public long Size;
+ public byte[] Hash;
+ public Stream Stream;
+
+ public FSP_FileObject() { }
+ }
+
+ // хранит свойства сервера, полученные с помощью RequestServersList()
+ public class ServerObject
+ {
+ public string Address;
+ public string Name;
+ public string Speed;
+
+ public ServerObject(string address, string name, string speed)
+ {
+ Address = address;
+ Name = name;
+ Speed = speed;
+ }
+
+ public ServerObject() { }
+ }
+ }
+}
diff --git a/.old 4/DTLib/Properties/AssemblyInfo.cs b/.old 4/DTLib/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..c0201c5
--- /dev/null
+++ b/.old 4/DTLib/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные со сборкой.
+[assembly: AssemblyTitle("DTLib")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DTLib")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
+[assembly: ComVisible(false)]
+
+// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
+[assembly: Guid("ce793497-2d5c-42d8-b311-e9b32af9cdfb")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Редакция
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 4/DTLib/PublicLog.cs b/.old 4/DTLib/PublicLog.cs
new file mode 100644
index 0000000..5b38768
--- /dev/null
+++ b/.old 4/DTLib/PublicLog.cs
@@ -0,0 +1,16 @@
+namespace DTLib
+{
+ //
+ // вывод логов со всех классов в библиотеке
+ //
+ public static class PublicLog
+ {
+ public delegate void LogDelegate(string[] msg);
+ // вот к этому объекту подключайте методы для вывода логов
+ public static LogDelegate LogDel;
+
+ // этот метод вызывается в библиотеке
+ public static void Log(params string[] msg)
+ => LogDel(msg);
+ }
+}
diff --git a/.old 4/DTLib/SecureRandom.cs b/.old 4/DTLib/SecureRandom.cs
new file mode 100644
index 0000000..5b5e965
--- /dev/null
+++ b/.old 4/DTLib/SecureRandom.cs
@@ -0,0 +1,37 @@
+using System.Security.Cryptography;
+
+namespace DTLib
+{
+ //
+ // Вычисление псевдослучайного числа из множества параметров.
+ // Работает медленнее чем класс System.Random, но выдаёт более случайные значения
+ //
+ public class SecureRandom
+ {
+ private RNGCryptoServiceProvider crypt = new RNGCryptoServiceProvider();
+
+ // получение массива случайных байтов
+ public byte[] GenBytes(uint length)
+ {
+ byte[] output = new byte[length];
+ crypt.GetNonZeroBytes(output);
+ return output;
+ }
+
+ // получение случайного числа от 0 до 2147483647
+ /*public int NextInt(uint from, int to)
+ {
+ int output = 0;
+ int rez = 0;
+ while (true)
+ {
+ rez = output * 10 + NextBytes(1)[0];
+ if (rez < to && rez > from)
+ {
+ output = rez;
+ return output;
+ }
+ }
+ }*/
+ }
+}
diff --git a/.old 4/DTLib/SimpleConverter.cs b/.old 4/DTLib/SimpleConverter.cs
new file mode 100644
index 0000000..3b0c1f2
--- /dev/null
+++ b/.old 4/DTLib/SimpleConverter.cs
@@ -0,0 +1,88 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace DTLib
+{
+ //
+ // содержит методы расширения для различных операций и преобразований
+ //
+ public static class SimpleConverter
+ {
+ public static Encoding UTF8 = new UTF8Encoding(false);
+ // байты в кодировке UTF8 в строку
+ public static string ToStr(this byte[] bytes)
+ => UTF8.GetString(bytes);
+ public static string ToStr(this List bytes)
+ => UTF8.GetString(bytes.ToArray());
+
+ // хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
+ public static string HashToString(this byte[] hash)
+ {
+ var builder = new StringBuilder();
+ for (int i = 0; i < hash.Length; i++)
+ {
+ builder.Append(hash[i].ToString("x2"));
+ }
+ return builder.ToString();
+ }
+
+ // строку в байты
+ public static byte[] ToBytes(this string str)
+ => UTF8.GetBytes(str);
+
+ // эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
+ public static bool StartsWith(this byte[] source, byte[] startsWith)
+ {
+ for (int i = 0; i < startsWith.Length; i++)
+ {
+ if (source[i] != startsWith[i]) return false;
+ }
+ return true;
+ }
+
+ public static bool EndsWith(this byte[] source, byte[] endsWith)
+ {
+ for (int i = 0; i < endsWith.Length; i++)
+ {
+ if (source[source.Length - endsWith.Length + i] != endsWith[i]) return false;
+ }
+ return true;
+ }
+
+ // Math.Truncate принимает как decimal, так и doublе,
+ // из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов"
+ public static int Truncate(decimal number)
+ => Convert.ToInt32(Math.Truncate(number));
+
+ // сортирует в порядке возрастания элементы если это возможно, используя стандартный метод list.Sort();
+ public static T[] Sort(this T[] array)
+ {
+ var list = array.ToList();
+ list.Sort();
+ return list.ToArray();
+ }
+
+ // массив в лист
+ public static List ToList(this T[] input)
+ {
+ var list = new List();
+ list.AddRange(input);
+ return list;
+ }
+
+ // удаление нескольких элементов массива
+ public static T[] RemoveRange(this T[] input, int startIndex, int count)
+ {
+ List list = input.ToList();
+ list.RemoveRange(startIndex, count);
+ return list.ToArray();
+ }
+ public static T[] RemoveRange(this T[] input, int startIndex)
+ => input.RemoveRange(startIndex, input.Length - startIndex);
+
+ //
+ public static int ToInt(this T input)
+ => Convert.ToInt32(input);
+ }
+}
\ No newline at end of file
diff --git a/.old 4/DTLib/TImer.cs b/.old 4/DTLib/TImer.cs
new file mode 100644
index 0000000..cb154ec
--- /dev/null
+++ b/.old 4/DTLib/TImer.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Threading;
+
+namespace DTLib
+{
+ //
+ // простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
+ //
+ public class Timer
+ {
+ Thread TimerThread;
+ bool Repeat;
+
+ // таймер сразу запускается
+ public Timer(bool repeat, int delay, Action method)
+ {
+ Repeat = repeat;
+ TimerThread = new Thread(() =>
+ {
+ do
+ {
+ Thread.Sleep(delay);
+ method();
+ } while (Repeat);
+ });
+ TimerThread.Start();
+ }
+
+ // завершение потока
+ public void Stop()
+ {
+ Repeat = false;
+ TimerThread.Abort();
+ }
+ }
+}
diff --git a/.old 4/DTLib/XXHash.cs b/.old 4/DTLib/XXHash.cs
new file mode 100644
index 0000000..08c7c24
--- /dev/null
+++ b/.old 4/DTLib/XXHash.cs
@@ -0,0 +1,180 @@
+using System;
+using System.Security.Cryptography;
+namespace DTLib
+{
+ //
+ // честно взятый с гитхаба алгоритм хеширования
+ // выдаёт хеш в виде массива четырёх байтов
+ //
+ sealed class XXHash32 : HashAlgorithm
+ {
+ private const uint PRIME32_1 = 2654435761U;
+ private const uint PRIME32_2 = 2246822519U;
+ private const uint PRIME32_3 = 3266489917U;
+ private const uint PRIME32_4 = 668265263U;
+ private const uint PRIME32_5 = 374761393U;
+ private static readonly Func FuncGetLittleEndianUInt32;
+ private static readonly Func FuncGetFinalHashUInt32;
+ private uint _Seed32;
+ private uint _ACC32_1;
+ private uint _ACC32_2;
+ private uint _ACC32_3;
+ private uint _ACC32_4;
+ private uint _Hash32;
+ private int _RemainingLength;
+ private long _TotalLength = 0;
+ private int _CurrentIndex;
+ private byte[] _CurrentArray;
+
+ static XXHash32()
+ {
+ if (BitConverter.IsLittleEndian)
+ {
+ FuncGetLittleEndianUInt32 = new Func((x, i) =>
+ {
+ unsafe
+ {
+ fixed (byte* array = x)
+ {
+ return *(uint*)(array + i);
+ }
+ }
+ });
+ FuncGetFinalHashUInt32 = new Func(i => (i & 0x000000FFU) << 24 | (i & 0x0000FF00U) << 8 | (i & 0x00FF0000U) >> 8 | (i & 0xFF000000U) >> 24);
+ }
+ else
+ {
+ FuncGetLittleEndianUInt32 = new Func((x, i) =>
+ {
+ unsafe
+ {
+ fixed (byte* array = x)
+ {
+ return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
+ }
+ }
+ });
+ FuncGetFinalHashUInt32 = new Func(i => i);
+ }
+ }
+
+ // Creates an instance of class by default seed(0).
+ //
+ public static new XXHash32 Create() => new XXHash32();
+
+ // Initializes a new instance of the class by default seed(0).
+ public XXHash32() => Initialize(0);
+
+ // Initializes a new instance of the class, and sets the to the specified value.
+ // Represent the seed to be used for xxHash32 computing.
+ public XXHash32(uint seed) => Initialize(seed);
+
+ // Gets the value of the computed hash code.
+ // Hash computation has not yet completed.
+ public uint HashUInt32 => State == 0 ? _Hash32 : throw new InvalidOperationException("Hash computation has not yet completed.");
+
+ // Gets or sets the value of seed used by xxHash32 algorithm.
+ // Hash computation has not yet completed.
+ public uint Seed
+ {
+ get => _Seed32;
+ set
+ {
+ if (value != _Seed32)
+ {
+ if (State != 0) throw new InvalidOperationException("Hash computation has not yet completed.");
+ _Seed32 = value;
+ Initialize();
+ }
+ }
+ }
+
+ // Initializes this instance for new hash computing.
+ public override void Initialize()
+ {
+ _ACC32_1 = _Seed32 + PRIME32_1 + PRIME32_2;
+ _ACC32_2 = _Seed32 + PRIME32_2;
+ _ACC32_3 = _Seed32 + 0;
+ _ACC32_4 = _Seed32 - PRIME32_1;
+ }
+
+ // Routes data written to the object into the hash algorithm for computing the hash.
+ // The input to compute the hash code for.
+ // The offset into the byte array from which to begin using data.
+ // The number of bytes in the byte array to use as data.
+ protected override void HashCore(byte[] array, int ibStart, int cbSize)
+ {
+ if (State != 1) State = 1;
+ var size = cbSize - ibStart;
+ _RemainingLength = size & 15;
+ if (cbSize >= 16)
+ {
+ var limit = size - _RemainingLength;
+ do
+ {
+ _ACC32_1 = Round32(_ACC32_1, FuncGetLittleEndianUInt32(array, ibStart));
+ ibStart += 4;
+ _ACC32_2 = Round32(_ACC32_2, FuncGetLittleEndianUInt32(array, ibStart));
+ ibStart += 4;
+ _ACC32_3 = Round32(_ACC32_3, FuncGetLittleEndianUInt32(array, ibStart));
+ ibStart += 4;
+ _ACC32_4 = Round32(_ACC32_4, FuncGetLittleEndianUInt32(array, ibStart));
+ ibStart += 4;
+ } while (ibStart < limit);
+ }
+ _TotalLength += cbSize;
+ if (_RemainingLength != 0)
+ {
+ _CurrentArray = array;
+ _CurrentIndex = ibStart;
+ }
+ }
+
+ // Finalizes the hash computation after the last data is processed by the cryptographic stream object.
+ // The computed hash code.
+ protected override byte[] HashFinal()
+ {
+ if (_TotalLength >= 16)
+ {
+ _Hash32 = RotateLeft32(_ACC32_1, 1) + RotateLeft32(_ACC32_2, 7) + RotateLeft32(_ACC32_3, 12) + RotateLeft32(_ACC32_4, 18);
+ }
+ else
+ {
+ _Hash32 = _Seed32 + PRIME32_5;
+ }
+ _Hash32 += (uint)_TotalLength;
+ while (_RemainingLength >= 4)
+ {
+ _Hash32 = RotateLeft32(_Hash32 + FuncGetLittleEndianUInt32(_CurrentArray, _CurrentIndex) * PRIME32_3, 17) * PRIME32_4;
+ _CurrentIndex += 4;
+ _RemainingLength -= 4;
+ }
+ unsafe
+ {
+ fixed (byte* arrayPtr = _CurrentArray)
+ {
+ while (_RemainingLength-- >= 1)
+ {
+ _Hash32 = RotateLeft32(_Hash32 + arrayPtr[_CurrentIndex++] * PRIME32_5, 11) * PRIME32_1;
+ }
+ }
+ }
+ _Hash32 = (_Hash32 ^ (_Hash32 >> 15)) * PRIME32_2;
+ _Hash32 = (_Hash32 ^ (_Hash32 >> 13)) * PRIME32_3;
+ _Hash32 ^= _Hash32 >> 16;
+ _TotalLength = State = 0;
+ return BitConverter.GetBytes(FuncGetFinalHashUInt32(_Hash32));
+ }
+
+ private static uint Round32(uint input, uint value) => RotateLeft32(input + (value * PRIME32_2), 13) * PRIME32_1;
+
+ private static uint RotateLeft32(uint value, int count) => (value << count) | (value >> (32 - count));
+
+ private void Initialize(uint seed)
+ {
+ HashSizeValue = 32;
+ _Seed32 = seed;
+ Initialize();
+ }
+ }
+}
diff --git a/.old 4/dtlauncher-client-win/App.config b/.old 4/dtlauncher-client-win/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 4/dtlauncher-client-win/App.xaml b/.old 4/dtlauncher-client-win/App.xaml
new file mode 100644
index 0000000..56be4b8
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/App.xaml
@@ -0,0 +1,166 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 4/dtlauncher-client-win/App.xaml.cs b/.old 4/dtlauncher-client-win/App.xaml.cs
new file mode 100644
index 0000000..4aa3d80
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/App.xaml.cs
@@ -0,0 +1,11 @@
+using System.Windows;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для App.xaml
+ ///
+ public partial class App : Application
+ {
+ }
+}
diff --git a/.old 4/dtlauncher-client-win/LauncherWindow.xaml b/.old 4/dtlauncher-client-win/LauncherWindow.xaml
new file mode 100644
index 0000000..f639199
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/LauncherWindow.xaml
@@ -0,0 +1,98 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 4/dtlauncher-client-win/LauncherWindow.xaml.cs b/.old 4/dtlauncher-client-win/LauncherWindow.xaml.cs
new file mode 100644
index 0000000..7c54642
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/LauncherWindow.xaml.cs
@@ -0,0 +1,102 @@
+using DTLib;
+using System;
+using System.IO;
+using System.Net.Sockets;
+using System.Windows;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для LauncherWindow.xaml
+ ///
+ public partial class LauncherWindow : Window
+ {
+ public Socket mainSocket;
+ string logfile;
+ public delegate void LaunchDel();
+ public LaunchDel Launch = () => { };
+ public delegate void InstallDel();
+ public LaunchDel Install = () => { };
+ public ProgramLabel[] programsArray;
+ public int PreviousProgramNum = 0;
+
+ public LauncherWindow(Socket _socket, string _logfile, string _log)
+ {
+ InitializeComponent();
+ try
+ {
+ mainSocket = _socket;
+ logfile = _logfile;
+ LogBox.Text += _log;
+ PublicLog.LogDel += Log;
+ // переключение вкладок кнопками
+ var green = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(44, 220, 17));
+ var white = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
+ HomeButton.Click += (s, e) =>
+ {
+ LogGrid.Visibility = Visibility.Hidden;
+ SettingsGrid.Visibility = Visibility.Hidden;
+ HomeGrid.Visibility = Visibility.Visible;
+ LogButton.Foreground = white;
+ SettingsButton.Foreground = white;
+ HomeButton.Foreground = green;
+ };
+ LogButton.Click += (s, e) =>
+ {
+ HomeGrid.Visibility = Visibility.Hidden;
+ SettingsGrid.Visibility = Visibility.Hidden;
+ LogGrid.Visibility = Visibility.Visible;
+ HomeButton.Foreground = white;
+ SettingsButton.Foreground = white;
+ LogButton.Foreground = green;
+ };
+ SettingsButton.Click += (s, e) =>
+ {
+ HomeGrid.Visibility = Visibility.Hidden;
+ LogGrid.Visibility = Visibility.Hidden;
+ SettingsGrid.Visibility = Visibility.Visible;
+ HomeButton.Foreground = white;
+ LogButton.Foreground = white;
+ SettingsButton.Foreground = green;
+ };
+ // считывание дескрипторов программ
+ var descriptors = Directory.GetFiles("descroptors", "*.desc");
+ programsArray = new ProgramLabel[descriptors.Length];
+ Log(descriptors.Length + " descriptors found\n");
+ for (int i = 0; i < descriptors.Length; i++)
+ {
+ programsArray[i] = new ProgramLabel(descriptors[i], i, this);
+ ProgramsPanel.Children.Add(programsArray[i]);
+ Log(programsArray[i].Text + " added to ProgramsPanel\n");
+ }
+ LaunchButton.Click += (s, e) => Launch();
+ InstallButton.Click += (s, e) => Install();
+ //mainSocket.FSP_Download(new FSP_FileObject("share\\file.arc", "downloads\\file.arc"));
+ }
+ catch (Exception e)
+ {
+ Log("error:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ }
+ }
+
+ public void Log(string msg)
+ {
+
+ if (LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ LogBox.Text += msg;
+ }
+
+ public void Log(params string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 4/dtlauncher-client-win/LoginWindow.xaml b/.old 4/dtlauncher-client-win/LoginWindow.xaml
new file mode 100644
index 0000000..d8d9662
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/LoginWindow.xaml
@@ -0,0 +1,45 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 4/dtlauncher-client-win/LoginWindow.xaml.cs b/.old 4/dtlauncher-client-win/LoginWindow.xaml.cs
new file mode 100644
index 0000000..806a7a8
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/LoginWindow.xaml.cs
@@ -0,0 +1,142 @@
+using DTLib;
+using System;
+using System.IO;
+using System.Net.Sockets;
+using System.Windows;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для LoginWindow.xaml
+ ///
+ public partial class LoginWindow : Window
+ {
+ public Socket mainSocket { private set; get; } = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ public string logfile { private set; get; } = $"logs\\client-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+
+ public LoginWindow()
+ {
+ try
+ {
+ InitializeComponent();
+ FileWork.DirCreate("logs");
+ FileWork.DirCreate("downloads");
+ PublicLog.LogDel += Log;
+ LoginButton.Click += Login;
+ RegisterButton.Click += Register;
+ Closed += CloseWindow;
+ Log("[" + DateTime.Now.ToString() + "]: launcher is starting\n");
+ }
+ catch (Exception e)
+ {
+ Log("error:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ }
+ }
+
+ void Log(string msg)
+ {
+ lock (new object())
+ {
+ if (LogBox.Text.Length - 1 >= 0 && LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ LogBox.Text += msg;
+ }
+ }
+
+ void Log(params string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+
+ void Register(object sender, EventArgs e)
+ {
+ try
+ {
+ string login = LoginBox.Text;
+ string password = PasswBox.Password;
+ string filename = $"register-{login}.req";
+ var hasher = new Hasher();
+ if (File.Exists(filename)) File.Delete(filename);
+ var writer = File.CreateText(filename);
+ writer.Write(login + " $" +
+ hasher.HashCycled(password.ToBytes(), login.ToBytes(), 4096)
+ .HashToString());
+ writer.Close();
+ Log($"request file created:{Directory.GetCurrentDirectory()}\\{filename}");
+ }
+ catch (Exception ex)
+ {
+ Log("registration error: " + ex.Message);
+ }
+ }
+
+ void Login(object sender, EventArgs e)
+ {
+ try
+ {
+ ConnectingLabel.Visibility = Visibility.Visible;
+ /*// пересоздание сокета
+ if (mainSocket.Connected)
+ {
+ mainSocket.Shutdown(SocketShutdown.Both);
+ mainSocket.Close();
+ mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ }
+ // подключение к серверу
+ Log("connecting to the main server...");
+ mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(
+ FileWork.ReadFromConfig("client.cfg", "central server ip"))[0],
+ Convert.ToInt32(FileWork.ReadFromConfig("client.cfg", "central server port"))));
+ mainSocket.ReceiveTimeout = 2000;
+ string recieved = mainSocket.Request("new user connection try").ToStr();
+ if (recieved != "new user connection created")
+ throw new Exception("can't connect to the main server");
+ Log("connected to the main server");
+ //NetWork.RequestServersList(mainSocket);
+ var hasher = new SecureHasher(256);
+ // подключение к серверу
+ mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses("m1net.keenetic.pro")[0], 20008));
+ mainSocket.ReceiveTimeout = 5000;
+ // авторизация
+ string login = LoginBox.Text;
+ string password = PasswBox.Password;
+ string recievedString = NetWork.Request(mainSocket, login).ToStr();
+ if (recievedString != "2e9b7473ce473cdbb9b9e68aa444f5146b1b415a05917aceecd3861804cc2fd8")
+ throw new Exception("incorrect login\n");recievedString = NetWork.Request(mainSocket,hasher.HashSaltCycled(password.ToBytes(), login.ToBytes(), 4096)).ToStr();
+ if (recievedString != "82c8e541601e0883ea189a285e514adfa6c2da05c83285359bbcf73bd3a8518b")
+ throw new Exception("incorrect password");*/
+ ConnectingLabel.Visibility = Visibility.Hidden;
+ Log("succesfully login\n");
+ // вызов нового окна
+ var lauWin = new LauncherWindow(mainSocket, logfile, LogBox.Text);
+ lauWin.Show();
+ Hide();
+ PublicLog.LogDel -= Log;
+ lauWin.Closed += CloseWindow;
+ }
+ catch (Exception ex)
+ {
+ Log("login error: " + ex.Message + '\n' + ex.StackTrace);
+ }
+ }
+
+ void CloseWindow(object sender, EventArgs e)
+ {
+ if (mainSocket.Connected)
+ {
+ mainSocket.Shutdown(SocketShutdown.Both);
+ mainSocket.Close();
+ }
+ Log("DTchat closed");
+ Close();
+ App.Current.Shutdown();
+ }
+ }
+}
diff --git a/.old 4/dtlauncher-client-win/ProgramLabel.xaml b/.old 4/dtlauncher-client-win/ProgramLabel.xaml
new file mode 100644
index 0000000..f6a6073
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/ProgramLabel.xaml
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 4/dtlauncher-client-win/ProgramLabel.xaml.cs b/.old 4/dtlauncher-client-win/ProgramLabel.xaml.cs
new file mode 100644
index 0000000..29a0f8d
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/ProgramLabel.xaml.cs
@@ -0,0 +1,115 @@
+using DTLib;
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Windows;
+using System.Windows.Controls;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для ProgramLabel.xaml
+ ///
+ public partial class ProgramLabel : UserControl
+ {
+ public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(ProgramLabel));
+ public string Text
+ {
+ get { return (string)GetValue(TextProperty); }
+ set { SetValue(TextProperty, value); }
+ }
+
+ public static DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(System.Windows.Media.Imaging.BitmapImage), typeof(ProgramLabel));
+ public System.Windows.Media.Imaging.BitmapImage Icon
+ {
+ get { return (System.Windows.Media.Imaging.BitmapImage)GetValue(IconProperty); }
+ set { SetValue(IconProperty, value); }
+ }
+
+ public static DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(ProgramLabel));
+ public CornerRadius CornerRadius
+ {
+ get { return (CornerRadius)GetValue(CornerRadiusProperty); }
+ set { SetValue(CornerRadiusProperty, value); }
+ }
+
+ public string BackgroundImage;
+ public string Script;
+ public string InstallDir;
+ public string LaunchFile;
+ public string Arguments;
+ public string Description;
+ public int Number;
+ LauncherWindow Window;
+
+ public ProgramLabel()
+ {
+ InitializeComponent();
+ }
+
+ public ProgramLabel(string descriptorPath, int number, LauncherWindow window)
+ {
+ try
+ {
+ InitializeComponent();
+ Window = window;
+ Number = number;
+ FontSize = 14;
+ Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
+ Text = FileWork.ReadFromConfig(descriptorPath, "name");
+ NameLabel.Content = FileWork.ReadFromConfig(descriptorPath, "name");
+ IconImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\descroptors\\" + FileWork.ReadFromConfig(descriptorPath, "icon"), UriKind.Absolute));
+ BackgroundImage = Directory.GetCurrentDirectory() + "\\descroptors\\" + FileWork.ReadFromConfig(descriptorPath, "background");
+ Script = FileWork.ReadFromConfig(descriptorPath, "script");
+ InstallDir = FileWork.ReadFromConfig(descriptorPath, "installdir");
+ LaunchFile = FileWork.ReadFromConfig(descriptorPath, "launchfile");
+ Arguments = FileWork.ReadFromConfig(descriptorPath, "arguments");
+ Description = FileWork.ReadFromConfig(descriptorPath, "description").Replace("\\n", "\n");
+ //Window.Log(Text + " " + Icon + " " + Number);
+ }
+ catch (Exception e)
+ {
+ Window.Log("error:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ }
+ }
+
+ void ProgramShow(object sender, System.Windows.Input.MouseButtonEventArgs e)
+ {
+ try
+ {
+ Window.programsArray[Window.PreviousProgramNum].Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
+ Window.programsArray[Window.PreviousProgramNum].FontWeight = FontWeights.Normal;
+ Window.programsArray[Window.PreviousProgramNum].FontSize = 14;
+ Window.PreviousProgramNum = Number;
+ Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(170, 170, 240));
+ FontWeight = FontWeights.Bold;
+ FontSize = 13;
+ Window.NameLabel.Content = Text;
+ Window.DescriptionBox.Text = Description;
+ Window.BackgroundImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(BackgroundImage, UriKind.Absolute));
+ Window.Launch = () =>
+ {
+ var startInfo = new ProcessStartInfo()
+ {
+ FileName = LaunchFile,
+ Arguments = Arguments,
+ };
+ Process.Start(startInfo);
+ };
+ Window.Install = () =>
+ {
+ var scriptrunner = new DTScript.ScriptRunner
+ {
+ debug = false,
+ mainSocket = Window.mainSocket
+ };
+ scriptrunner.RunScriptFile(Directory.GetCurrentDirectory() + "\\scripts\\" + Script);
+ };
+ }
+ catch (Exception ex)
+ {
+ Window.Log("error:\n" + ex.Message + "\n" + ex.StackTrace + '\n');
+ }
+ }
+ }
+}
diff --git a/.old 4/dtlauncher-client-win/Properties/AssemblyInfo.cs b/.old 4/dtlauncher-client-win/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..bbd57be
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/Properties/AssemblyInfo.cs
@@ -0,0 +1,53 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("dtlauncher-client-win")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-client-win")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM, установите атрибут ComVisible для этого типа в значение true.
+[assembly: ComVisible(false)]
+
+//Чтобы начать создание локализуемых приложений, задайте
+//CultureYouAreCodingWith в файле .csproj
+//в . Например, при использовании английского (США)
+//в своих исходных файлах установите в en-US. Затем отмените преобразование в комментарий
+//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
+//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+ ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
+ //(используется, если ресурс не найден на странице,
+ // или в словарях ресурсов приложения)
+ ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
+ //(используется, если ресурс не найден на странице,
+ // в приложении или в каких-либо словарях ресурсов для конкретной темы)
+)]
+
+
+// Сведения о версии для сборки включают четыре следующих значения:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 4/dtlauncher-client-win/Properties/Resources.Designer.cs b/.old 4/dtlauncher-client-win/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..615ca67
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/Properties/Resources.Designer.cs
@@ -0,0 +1,70 @@
+//------------------------------------------------------------------------------
+//
+// Этот код был создан программным средством.
+// Версия среды выполнения: 4.0.30319.42000
+//
+// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
+// код создан повторно.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_client_win.Properties
+{
+ ///
+ /// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
+ ///
+ // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
+ // класс с помощью таких средств, как ResGen или Visual Studio.
+ // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
+ // с параметром /str или заново постройте свой VS-проект.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_client_win.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Переопределяет свойство CurrentUICulture текущего потока для всех
+ /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/.old 4/dtlauncher-client-win/Properties/Resources.resx b/.old 4/dtlauncher-client-win/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/.old 4/dtlauncher-client-win/Properties/Settings.Designer.cs b/.old 4/dtlauncher-client-win/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..1c4561e
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/Properties/Settings.Designer.cs
@@ -0,0 +1,29 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_client_win.Properties
+{
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/.old 4/dtlauncher-client-win/Properties/Settings.settings b/.old 4/dtlauncher-client-win/Properties/Settings.settings
new file mode 100644
index 0000000..033d7a5
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 4/dtlauncher-client-win/dtlauncher-client-win.csproj b/.old 4/dtlauncher-client-win/dtlauncher-client-win.csproj
new file mode 100644
index 0000000..2bb81e5
--- /dev/null
+++ b/.old 4/dtlauncher-client-win/dtlauncher-client-win.csproj
@@ -0,0 +1,125 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}
+ WinExe
+ dtlauncher_client_win
+ dtlauncher-client-win
+ v4.8
+ 512
+ {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ 4
+ true
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+ true
+
+
+ dtlauncher_client_win.App
+
+
+ dtscript.ico
+
+
+
+
+
+
+
+
+
+
+
+ 4.0
+
+
+
+
+
+
+
+ MSBuild:Compile
+ Designer
+
+
+ Designer
+ MSBuild:Compile
+
+
+ MSBuild:Compile
+ Designer
+
+
+ App.xaml
+ Code
+
+
+ LauncherWindow.xaml
+
+
+ LoginWindow.xaml
+ Code
+
+
+ Designer
+ MSBuild:Compile
+
+
+
+
+ ProgramLabel.xaml
+
+
+ Code
+
+
+ True
+ True
+ Resources.resx
+
+
+ True
+ Settings.settings
+ True
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+ {e02ea967-fd29-47d2-b25b-ba684b784aee}
+ dtscript
+
+
+
+
+
+
+
+ del /f /q dtlauncher-client-win.exe.config
+
+
\ No newline at end of file
diff --git a/.old 4/dtlauncher-client-win/dtscript.ico b/.old 4/dtlauncher-client-win/dtscript.ico
new file mode 100644
index 0000000..df420bb
Binary files /dev/null and b/.old 4/dtlauncher-client-win/dtscript.ico differ
diff --git a/.old 4/dtlauncher-server-win/App.config b/.old 4/dtlauncher-server-win/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 4/dtlauncher-server-win/App.xaml b/.old 4/dtlauncher-server-win/App.xaml
new file mode 100644
index 0000000..97bb104
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/App.xaml
@@ -0,0 +1,166 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 4/dtlauncher-server-win/App.xaml.cs b/.old 4/dtlauncher-server-win/App.xaml.cs
new file mode 100644
index 0000000..bacff7e
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/App.xaml.cs
@@ -0,0 +1,11 @@
+using System.Windows;
+
+namespace dtlauncher_server_win
+{
+ ///
+ /// Логика взаимодействия для App.xaml
+ ///
+ public partial class App : Application
+ {
+ }
+}
diff --git a/.old 4/dtlauncher-server-win/Properties/AssemblyInfo.cs b/.old 4/dtlauncher-server-win/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..340af78
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/Properties/AssemblyInfo.cs
@@ -0,0 +1,53 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("dtlauncher-server-win")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-server-win")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM, установите атрибут ComVisible для этого типа в значение true.
+[assembly: ComVisible(false)]
+
+//Чтобы начать создание локализуемых приложений, задайте
+//CultureYouAreCodingWith в файле .csproj
+//в . Например, при использовании английского (США)
+//в своих исходных файлах установите в en-US. Затем отмените преобразование в комментарий
+//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
+//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+ ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
+ //(используется, если ресурс не найден на странице,
+ // или в словарях ресурсов приложения)
+ ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
+ //(используется, если ресурс не найден на странице,
+ // в приложении или в каких-либо словарях ресурсов для конкретной темы)
+)]
+
+
+// Сведения о версии для сборки включают четыре следующих значения:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 4/dtlauncher-server-win/Properties/Resources.Designer.cs b/.old 4/dtlauncher-server-win/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..9d42357
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/Properties/Resources.Designer.cs
@@ -0,0 +1,70 @@
+//------------------------------------------------------------------------------
+//
+// Этот код был создан программным средством.
+// Версия среды выполнения: 4.0.30319.42000
+//
+// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
+// код создан повторно.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_server_win.Properties
+{
+ ///
+ /// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
+ ///
+ // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
+ // класс с помощью таких средств, как ResGen или Visual Studio.
+ // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
+ // с параметром /str или заново постройте свой VS-проект.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_server_win.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Переопределяет свойство CurrentUICulture текущего потока для всех
+ /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/.old 4/dtlauncher-server-win/Properties/Resources.resx b/.old 4/dtlauncher-server-win/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/.old 4/dtlauncher-server-win/Properties/Settings.Designer.cs b/.old 4/dtlauncher-server-win/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..cb2dff3
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/Properties/Settings.Designer.cs
@@ -0,0 +1,29 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_server_win.Properties
+{
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/.old 4/dtlauncher-server-win/Properties/Settings.settings b/.old 4/dtlauncher-server-win/Properties/Settings.settings
new file mode 100644
index 0000000..033d7a5
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 4/dtlauncher-server-win/ServerWindow.xaml b/.old 4/dtlauncher-server-win/ServerWindow.xaml
new file mode 100644
index 0000000..8785194
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/ServerWindow.xaml
@@ -0,0 +1,37 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 4/dtlauncher-server-win/ServerWindow.xaml.cs b/.old 4/dtlauncher-server-win/ServerWindow.xaml.cs
new file mode 100644
index 0000000..ed0e7a5
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/ServerWindow.xaml.cs
@@ -0,0 +1,117 @@
+using DTLib;
+using System;
+using System.Net.Sockets;
+using System.Threading;
+using System.Windows;
+using static DTLib.NetWork;
+
+namespace dtlauncher_server_win
+{
+ ///
+ /// Логика взаимодействия для ServerWindow.xaml
+ ///
+ public partial class ServerWindow : Window
+ {
+ static string logfile = $"logs\\server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+ static Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+
+ public ServerWindow()
+ {
+ InitializeComponent();
+ /*while (true)
+ {
+ try
+ {
+ FileWork.DirExistenceCheck("logs");
+ FileWork.DirExistenceCheck("share");
+ NetWork.Log += Log;
+ Log($"<{FileWork.ReadFromConfig("server.cfg", "server ip")}> : <{Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))}>\n");
+ mainSocket.Bind(new IPEndPoint(IPAddress.Parse(FileWork.ReadFromConfig("server.cfg", "server ip")), Convert.ToInt32(FileWork.ReadFromConfig("server.cfg", "server port"))));
+ Log("server started succesfully\n");
+ try
+ {
+ mainSocket.Listen(200);
+ while (true)
+ {
+ var userSocket = mainSocket.Accept();
+ var userThread = new Thread(new ParameterizedThreadStart(UserStart));
+ userThread.Start(userSocket);
+ }
+ }
+ catch (Exception ex)
+ {
+ Log($"handler error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ }
+ catch (Exception ex)
+ {
+ if (mainSocket.IsBound) mainSocket.CloseSocket();
+ Log($"Main() error:\n message:\n {ex.Message}\nmethod:\n {ex.TargetSite}\n");
+ }
+ Thread.Sleep(1500);
+ }*/
+ }
+
+ void Log(string msg)
+ {
+ msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ //LogBox.Text += msg;
+ }
+
+ void Log(string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+
+ void UserStart(dynamic _handlerSocket)
+ {
+ Socket handlerSocket = (Socket)_handlerSocket;
+ Log("user connected\n");
+ try
+ {
+ string recieved = handlerSocket.GetData().ToStr();
+ if (recieved == "new user connection try")
+ {
+ handlerSocket.Send("new user connection created".ToBytes());
+ while (true)
+ {
+ recieved = handlerSocket.GetData().ToStr();
+ switch (recieved)
+ {
+ // ответ на NetWork.Ping()
+ case "ping":
+ handlerSocket.Send("pong".ToBytes());
+ break;
+ // отправка списка активных серверов
+ case "requesting servers list":
+
+ break;
+ // отправка файла
+ case "requesting file download":
+ handlerSocket.FSP_Upload();
+ break;
+ default:
+ throw new Exception("unknown request: " + recieved);
+ }
+ }
+ }
+ else throw new Exception("incorrect connection try");
+ }
+ catch (Exception ex)
+ {
+ Log($"UserStart() error:\n message:\n {ex.Message}\n{ex.StackTrace}\n");
+ mainSocket.Shutdown(SocketShutdown.Both);
+ mainSocket.Close();
+ Thread.CurrentThread.Abort();
+ }
+ }
+ }
+}
diff --git a/.old 4/dtlauncher-server-win/dtlauncher-server-win.csproj b/.old 4/dtlauncher-server-win/dtlauncher-server-win.csproj
new file mode 100644
index 0000000..0ce2cf8
--- /dev/null
+++ b/.old 4/dtlauncher-server-win/dtlauncher-server-win.csproj
@@ -0,0 +1,127 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}
+ WinExe
+ dtlauncher_server_win
+ dtlauncher-server-win
+ v4.8
+ 512
+ {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ 4
+ true
+ true
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+ dtlauncher_server_win.App
+
+
+
+
+
+
+
+
+
+
+
+ 4.0
+
+
+
+
+
+
+
+ MSBuild:Compile
+ Designer
+
+
+ MSBuild:Compile
+ Designer
+
+
+ App.xaml
+ Code
+
+
+ ServerWindow.xaml
+ Code
+
+
+
+
+ Code
+
+
+ True
+ True
+ Resources.resx
+
+
+ True
+ Settings.settings
+ True
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+ False
+ Microsoft .NET Framework 4.8 %28x86 и x64%29
+ true
+
+
+ False
+ .NET Framework 3.5 SP1
+ false
+
+
+
+
+ del /f /q dtlauncher-server-win.exe.config
+
+
\ No newline at end of file
diff --git a/.old 4/dtlauncher.sln b/.old 4/dtlauncher.sln
new file mode 100644
index 0000000..ec344cc
--- /dev/null
+++ b/.old 4/dtlauncher.sln
@@ -0,0 +1,40 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30907.101
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-client-win", "dtlauncher-client-win\dtlauncher-client-win.csproj", "{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-server-win", "dtlauncher-server-win\dtlauncher-server-win.csproj", "{8B9889A7-93DC-4914-92D1-8209BD3BA71A}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtscript", "..\dtscript\dtscript.csproj", "{E02EA967-FD29-47D2-B25B-BA684B784AEE}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Build|Any CPU = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.Build.0 = Build|Any CPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.Build.0 = Build|Any CPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.Build.0 = Build|Any CPU
+ {E02EA967-FD29-47D2-B25B-BA684B784AEE}.Build|Any CPU.ActiveCfg = build|Any CPU
+ {E02EA967-FD29-47D2-B25B-BA684B784AEE}.Build|Any CPU.Build.0 = build|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {E6569C0C-DD32-4F7D-AD4C-DBC5434D2F8C}
+ EndGlobalSection
+EndGlobal
diff --git a/.old 4/dtscript/App.config b/.old 4/dtscript/App.config
new file mode 100644
index 0000000..4bfa005
--- /dev/null
+++ b/.old 4/dtscript/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/.old 4/dtscript/MainClass.cs b/.old 4/dtscript/MainClass.cs
new file mode 100644
index 0000000..922e714
--- /dev/null
+++ b/.old 4/dtscript/MainClass.cs
@@ -0,0 +1,48 @@
+using DTLib;
+using System;
+
+namespace DTScript
+{
+ public class MainClass
+ {
+ static void Main(string[] args)
+ {
+ try
+ {
+ FileWork.DirCreate("dtscript-logs");
+ PublicLog.LogDel += Log;
+ var scripter = new ScriptRunner();
+ if (args.Length == 0 || args.Length > 2) throw new Exception("enter script file path\n");
+ else if (args.Length == 1) scripter.RunScriptFile(args[0]);
+ else if (args.Length == 2 && args[0] == "-debug")
+ {
+ scripter.debug = true;
+ scripter.Debug("y", "debug is enabled\n");
+ scripter.RunScriptFile(args[1]);
+ }
+ else throw new Exception("unknown args\n");
+ }
+ catch (Exception e)
+ {
+ Log("r", $"dtscript Main() error:\n{e.Message}\n{e.StackTrace}\n");
+ }
+ Log("gray", " \n");
+ }
+
+ // вывод лога в консоль и файл
+ static readonly string logfile = $"dtscript-logs\\dtscript-log-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+
+ static void Log(params string[] msg)
+ {
+ if (msg.Length != 1 && msg.Length % 2 != 0) throw new Exception("ыыы нечётное количество элементов выводимого массива");
+ ColoredConsole.Write(msg);
+ if (msg.Length == 1) FileWork.Log(logfile, msg[0]);
+ else
+ {
+ var mergmsg = "";
+ for (int i = 0; i < msg.Length; i++) mergmsg += msg[++i];
+ FileWork.Log(logfile, mergmsg);
+ }
+ }
+ }
+}
diff --git a/.old 4/dtscript/Properties/AssemblyInfo.cs b/.old 4/dtscript/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..2f86bb2
--- /dev/null
+++ b/.old 4/dtscript/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные с этой сборкой.
+[assembly: AssemblyTitle("dtscript")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtscript")]
+[assembly: AssemblyCopyright("Copyright © 2020")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM задайте для атрибута ComVisible этого типа значение true.
+[assembly: ComVisible(false)]
+
+// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
+[assembly: Guid("e02ea967-fd29-47d2-b25b-ba684b784aee")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 4/dtscript/ScriptRunner.cs b/.old 4/dtscript/ScriptRunner.cs
new file mode 100644
index 0000000..a3e3176
--- /dev/null
+++ b/.old 4/dtscript/ScriptRunner.cs
@@ -0,0 +1,441 @@
+using DTLib;
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+
+namespace DTScript
+{
+ //
+ // основной класс скриптового интерпретатора
+ //
+ public class ScriptRunner
+ {
+ // выводит текст через DTLib если дебаг включен
+ public bool debug = false;
+ public System.Net.Sockets.Socket mainSocket;
+ internal void Debug(params string[] msg)
+ {
+ if (debug) PublicLog.Log(msg);
+ }
+
+ // cчитывание текста из файла и запуск выполнения
+ public void RunScriptFile(string scriptfile)
+ {
+ Debug("g", @"----\ " + scriptfile + " /----\n");
+ try { Execute(SplitScript(File.ReadAllText(scriptfile))); }
+ catch (Exception e) { PublicLog.Log("r", $"dtscript RunScriptFile() error:\n{e.Message}\n{e.StackTrace}\n", "gray", " \n"); }
+ }
+
+ int globalindex = -1;
+ List> Storage = new();
+
+ object GetValue(string key)
+ {
+ Debug("m", "GetValue(", "c", "<", "b", key, "c", ">", "m", ")\n");
+ for (int i = 0; i <= globalindex; i++)
+ if (Storage[i].ContainsKey(key)) return Storage[i][key];
+ throw new Exception($"GetValue() exception: storage doesn't contain key<{key}>");
+ }
+
+ void SetValue(string key, object value)
+ {
+ Debug("m", "SetValue(", "c", "<", "b", key, "c", "> ", "c", "<", "b", value.ToString(), "c", ">", "m", ")\n");
+ for (int i = 0; i <= globalindex; i++)
+ if (Storage[i].ContainsKey(key))
+ {
+ Storage[i][key] = value;
+ Debug(Storage[i][key].ToString());
+ return;
+ }//throw new Exception($"SetValue() exception: storage alredy contains key<{key}>");
+ Storage[globalindex].Add(key, value);
+ }
+
+ dynamic Execute(List script)
+ {
+ Debug("y", " executing...\n");
+ // создание локального
+ globalindex++;
+ Storage.Add(new Dictionary());
+ // запуск цикла
+ for (int index = 0; index < script.Count; index++)
+ {
+ if (debug)
+ {
+ PublicLog.Log(new string[] {
+ "y","\noperator: ", "m",script[index].Operator, "y"," options: ", "c", "<", "b", script[index].Options[0], "c", ">"});
+ for (ushort n = 1; n < script[index].Options.Length; n++)
+ PublicLog.Log("w", ", ", "c", "<", "b", script[index].Options[n], "c", ">");
+ PublicLog.Log("\n");
+ }
+ switch (script[index].Operator)
+ {
+ case "return":
+ Debug("g", "script ended");
+ return GetValue(script[index].Options[0]);
+ case "Run":
+ var proc = new Process();
+ proc.StartInfo.FileName = script[index].Options[0].Replace("\"", "");
+ proc.StartInfo.Arguments = script[index].Options[1].Replace("\"", "");
+ if (script[index].Options.Length == 3 && script[index].Options[2] == "true")
+ {
+ proc.StartInfo.CreateNoWindow = true;
+ Debug("g", $"process {script[index].Operator} started in hidden mode\n");
+ }
+ else if (script[index].Options.Length == 3 && script[index].Options[2] == "false")
+ {
+ proc.StartInfo.CreateNoWindow = false;
+ Debug("g", $"process {script[index].Operator} started in not hidden mode\n");
+ }
+ else throw new Exception("invalid arguments in Run().\n it must be: Run(string exe_file, string arguments, true/false nowindow)\n");
+ proc.StartInfo.UseShellExecute = false;
+ proc.Start();
+ proc.WaitForExit();
+ proc.Close();
+ break;
+ case "Log":
+ Debug("y", $"Log() has {script[index].Options.Length} args\n");
+ PublicLog.Log(CalcString(script[index].Options.ToList()));
+ break;
+ case "ShowFiles":
+ Debug("y", $"Log() has {script[index].Options.Length} args\n");
+ foreach (string file in Directory.GetFiles(CalcString(script[index].Options.ToList())))
+ PublicLog.Log(file + '\n');
+ break;
+ case "bool":
+ if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
+ {
+ List expr = new();
+ for (ushort n = 2; n < script[index].Options.Length; n++)
+ expr.Add(script[index].Options[n]);
+ // сравнение и добавление результата в storage[globalindex]
+ SetValue(script[index].Options[0], Compare(expr));
+ Debug(new string[] {"y"," bool ","b", script[index].Options[0],
+ "w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
+ }
+ else throw new Exception("error: incorrect bool defination\n");
+ break;
+ case "num":
+ if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
+ {
+ List expr = new();
+ for (ushort n = 2; n < script[index].Options.Length; n++)
+ {
+ expr.Add(script[index].Options[n]);
+ }
+ SetValue(script[index].Options[0], (double)Calc(expr));
+ Debug(new string[] {"y"," num ","b", script[index].Options[0],
+ "w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
+ }
+ else throw new Exception("Execute() error: incorrect double defination\n");
+ break;
+ case "string":
+ if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
+ {
+ List expr = new();
+ for (ushort n = 2; n < script[index].Options.Length; n++)
+ {
+ expr.Add(script[index].Options[n]);
+ }
+ SetValue(script[index].Options[0], CalcString(expr));
+ Debug(new string[] {"y"," string ","b", script[index].Options[0],
+ "w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
+ }
+ break;
+ case "while":
+ if (script[index + 1].Operator != "{") throw new Exception("Execute() error: expect { after for()");
+ var subscript = SplitScript(script[index + 1].Options[0]);
+ while (Compare(script[index].Options.ToList()))
+ {
+ Execute(subscript);
+ }
+ index++;
+ break;
+ case "FSP_Download":
+ mainSocket.FSP_Download(new NetWork.FSP_FileObject()
+ {
+ ClientFilePath = script[index].Options[0],
+ ServerFilePath = script[index].Options[1]
+ });
+ break;
+ default:
+ throw new Exception($"Execute() error: invalid construct: {script[index].Operator}\n");
+ }
+ }
+ Storage.RemoveAt(globalindex);
+ globalindex--;
+ return null;
+
+ // операции со строками
+ string CalcString(List expr)
+ {
+ Debug("m", "CalcString(");
+ foreach (string part in expr)
+ Debug("c", "<", "b", part, "c", ">");
+ Debug("m", ")", "y", " started\n");
+ // извлечение значений переменных
+ for (ushort n = 0; n < expr.Count; n++)
+ {
+ switch (expr[n][0])
+ {
+ case '+':
+ break;
+ case '"':
+ if (!expr[n].EndsWith("\"")) throw new Exception("Calc() error: invalid value <" + expr[n] + ">\n");
+ break;
+ default:
+ expr[n] = GetValue(expr[n]).ToString();
+ break;
+ }
+ }
+ // вычисление
+ string rezult = "";
+ for (ushort i = 0; i < expr.Count; i++)
+ {
+
+ if (expr[i] == "+")
+ {
+ i++;
+ rezult += expr[i];
+ }
+ else if (i == 0) rezult = expr[0];
+ else throw new Exception($"error in Calc(): arg {expr[i]}\n");
+ }
+ if (rezult.Contains("\\n")) rezult = rezult.Replace("\\n", "\n");
+ if (rezult.Contains("\"")) rezult = rezult.Replace("\"", "");
+ Debug("y", " returns <", "b", $"{rezult}", "y", ">\n");
+ return rezult;
+ }
+ // операции с числами
+ double Calc(List expr)
+ {
+ Debug("m", "Calc(");
+ foreach (string part in expr)
+ Debug("c", "<", "b", part, "c", ">");
+ Debug("m", ")", "y", " started\n");
+ // извлечение значений переменных
+ for (ushort n = 0; n < expr.Count; n++)
+ {
+ switch (expr[n][0])
+ {
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ case '+':
+ case '-':
+ case '*':
+ case '/':
+ break;
+ default:
+ expr[n] = GetValue(expr[n]).ToString();
+ break;
+ }
+ }
+ // вычисление
+ double rezult = new();
+ for (ushort i = 0; i < expr.Count; i++)
+ switch (expr[i][0])
+ {
+ case '+':
+ i++;
+ rezult += Convert.ToDouble(expr[i]);
+ break;
+ case '-':
+ i++;
+ rezult -= Convert.ToDouble(expr[i]);
+ break;
+ case '*':
+ i++;
+ rezult *= Convert.ToDouble(expr[i]);
+ break;
+ case '/':
+ i++;
+ rezult /= Convert.ToDouble(expr[i]);
+ break;
+ default:
+ if (i == 0) rezult += Convert.ToDouble(expr[i]);
+ else throw new Exception($"error in Calc(): arg {expr[i]}\n");
+ break;
+ }
+ Debug("y", " returns <", "b", $"{rezult}", "y", ">\n");
+ return rezult;
+ }
+ // сравнение
+ bool Compare(List expr)
+ {
+ Debug("m", "Compare(");
+ foreach (string part in expr)
+ Debug("c", "<", "b", part, "c", ">");
+ Debug("m", ")", "y", " started\n");
+ // вычисление значений правой и левой части неравенства
+ char act = '\0';
+ double rezult_0 = new double(), rezult_1;
+ List _expr = new List();
+ for (ushort n = 0; n < expr.Count; n++)
+ {
+ Debug("m", $" <{expr[n]}>\n");
+ switch (expr[n][0])
+ {
+ case '<':
+ case '>':
+ act = expr[n][0];
+ rezult_0 = Calc(_expr);
+ _expr.Clear();
+ break;
+ case '!':
+ case '=':
+ act = expr[n][0];
+ rezult_0 = Calc(_expr);
+ _expr.Clear();
+ n++;
+ break;
+ default:
+ _expr.Add(expr[n]);
+ break;
+ }
+ }
+ Debug("y", " rezult_0 = <", "b", rezult_0.ToString(), "y", ">\n");
+ rezult_1 = Calc(_expr);
+ Debug("y", " rezult_1 = <", "b", rezult_1.ToString(), "y", ">\n");
+ Debug("y", " act = <", "b", act.ToString(), "y", ">\n");
+ bool output = act switch
+ {
+ '<' => rezult_0 < rezult_1,
+ '>' => rezult_0 > rezult_1,
+ '!' => rezult_0 != rezult_1,
+ '=' => rezult_0 == rezult_1,
+ _ => throw new Exception($"error: incorrect comparsion symbol: <{act}>\n"),
+ };
+ Debug("y", " return <", "c", $"{output}", "y", ">\n");
+ return output;
+ }
+ }
+
+ List SplitScript(string text)
+ {
+ // лист для хранения обработанного текста
+ List script = new();
+ string construct = "";
+ string option = "";
+ List options = new();
+ for (int index = 0; index < text.Length; index++)
+ {
+ switch (text[index])
+ {
+ // конец распознания конструкта
+ case ';':
+ Debug(text[index].ToString() + '\n');
+ // добавление конструкта и его параметров в лист
+ if (construct != "") script.Add(new Construction(construct, options));
+ construct = "";
+ option = "";
+ options.Clear();
+ break;
+ // распознание параметров конструкта
+ case '(':
+ Debug(text[index].ToString());
+ while (text[index] != ')')
+ {
+ index++;
+ switch (text[index])
+ {
+ case '"':
+ Debug("g", text[index].ToString());
+ do
+ {
+ option += text[index];
+ index++;
+ Debug("g", text[index].ToString());
+ } while (text[index] != '"');
+ option += text[index];
+ break;
+ case ' ':
+ case '\t':
+ case '\r':
+ case '\n':
+ break;
+ case ')':
+ case ',':
+ Debug(text[index].ToString());
+ options.Add(option);
+ option = "";
+ break;
+ // математика
+ case '+':
+ case '-':
+ case '*':
+ case '/':
+ case '!':
+ case '=':
+ Debug(text[index].ToString());
+ if (option != "") options.Add(option);
+ option = "";
+ options.Add(text[index].ToString());
+ break;
+ default:
+ option += text[index];
+ Debug("c", text[index].ToString());
+ break;
+ }
+ }
+ if (debug && text[index + 1] == ';') PublicLog.Log("y", "\n " + options.Count + " options have read\n");
+ break;
+ // очистка конструкта от лишних символов
+ case ' ':
+ case '\t':
+ case '\r':
+ case '\n':
+ break;
+ //
+ case '{':
+ Debug("SplitScript() found <{>");
+ // добавление конструкта и его параметров в лист
+ if (construct != "") script.Add(new Construction(construct, options));
+ options.Clear();
+ option = "";
+ construct = "";
+ index++;
+ short bracketBalance = 1;
+ while (bracketBalance != 0)
+ {
+ if (text[index] == '{') bracketBalance++;
+ if (text[index] == '}') bracketBalance--;
+ option += text[index];
+ index++;
+ }
+ option.Remove(option.Length - 1);
+ script.Add(new Construction("{", new List { option }));
+ option = "";
+ break;
+ case '}':
+ //throw new Exception($"SplitScript() error: unexpected '}}' on line {line}\n");
+ break;
+ default:
+ construct += text[index];
+ Debug("m", text[index].ToString());
+ break;
+ }
+ }
+ // возврат листа
+ return script;
+ }
+
+ class Construction
+ {
+ public string Operator { get; private set; }
+ public string[] Options { get; private set; }
+ public Construction(string oper, List opts)
+ {
+ Operator = oper;
+ Options = opts.ToArray();
+ }
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 4/dtscript/dtscript.csproj b/.old 4/dtscript/dtscript.csproj
new file mode 100644
index 0000000..e165cc4
--- /dev/null
+++ b/.old 4/dtscript/dtscript.csproj
@@ -0,0 +1,96 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {E02EA967-FD29-47D2-B25B-BA684B784AEE}
+ Exe
+ dtscript
+ dtscript
+ v4.8
+ 512
+ true
+ true
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
+
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+ true
+ preview
+
+
+ DTScript.MainClass
+
+
+ dtscript.ico
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ False
+ Microsoft .NET Framework 4.7.2 %28x86 и x64%29
+ true
+
+
+ False
+ .NET Framework 3.5 SP1
+ false
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+ del /q /f dtscript.exe.config
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 4/dtscript/dtscript.ico b/.old 4/dtscript/dtscript.ico
new file mode 100644
index 0000000..df420bb
Binary files /dev/null and b/.old 4/dtscript/dtscript.ico differ
diff --git a/.old 4/dtscript/dtscript.sln b/.old 4/dtscript/dtscript.sln
new file mode 100644
index 0000000..0f54d92
--- /dev/null
+++ b/.old 4/dtscript/dtscript.sln
@@ -0,0 +1,26 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30611.23
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtscript", "dtscript.csproj", "{E02EA967-FD29-47D2-B25B-BA684B784AEE}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ build|Any CPU = build|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {E02EA967-FD29-47D2-B25B-BA684B784AEE}.build|Any CPU.ActiveCfg = build|Any CPU
+ {E02EA967-FD29-47D2-B25B-BA684B784AEE}.build|Any CPU.Build.0 = build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.build|Any CPU.ActiveCfg = Build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.build|Any CPU.Build.0 = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {A1D642E1-876E-4187-91D5-526827AE36A2}
+ EndGlobalSection
+EndGlobal
diff --git a/.old 5/dtlauncher-client-win/App.config b/.old 5/dtlauncher-client-win/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 5/dtlauncher-client-win/App.xaml b/.old 5/dtlauncher-client-win/App.xaml
new file mode 100644
index 0000000..56be4b8
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/App.xaml
@@ -0,0 +1,166 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 5/dtlauncher-client-win/App.xaml.cs b/.old 5/dtlauncher-client-win/App.xaml.cs
new file mode 100644
index 0000000..4aa3d80
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/App.xaml.cs
@@ -0,0 +1,11 @@
+using System.Windows;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для App.xaml
+ ///
+ public partial class App : Application
+ {
+ }
+}
diff --git a/.old 5/dtlauncher-client-win/LauncherWindow.xaml b/.old 5/dtlauncher-client-win/LauncherWindow.xaml
new file mode 100644
index 0000000..f639199
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/LauncherWindow.xaml
@@ -0,0 +1,98 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 5/dtlauncher-client-win/LauncherWindow.xaml.cs b/.old 5/dtlauncher-client-win/LauncherWindow.xaml.cs
new file mode 100644
index 0000000..7c54642
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/LauncherWindow.xaml.cs
@@ -0,0 +1,102 @@
+using DTLib;
+using System;
+using System.IO;
+using System.Net.Sockets;
+using System.Windows;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для LauncherWindow.xaml
+ ///
+ public partial class LauncherWindow : Window
+ {
+ public Socket mainSocket;
+ string logfile;
+ public delegate void LaunchDel();
+ public LaunchDel Launch = () => { };
+ public delegate void InstallDel();
+ public LaunchDel Install = () => { };
+ public ProgramLabel[] programsArray;
+ public int PreviousProgramNum = 0;
+
+ public LauncherWindow(Socket _socket, string _logfile, string _log)
+ {
+ InitializeComponent();
+ try
+ {
+ mainSocket = _socket;
+ logfile = _logfile;
+ LogBox.Text += _log;
+ PublicLog.LogDel += Log;
+ // переключение вкладок кнопками
+ var green = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(44, 220, 17));
+ var white = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
+ HomeButton.Click += (s, e) =>
+ {
+ LogGrid.Visibility = Visibility.Hidden;
+ SettingsGrid.Visibility = Visibility.Hidden;
+ HomeGrid.Visibility = Visibility.Visible;
+ LogButton.Foreground = white;
+ SettingsButton.Foreground = white;
+ HomeButton.Foreground = green;
+ };
+ LogButton.Click += (s, e) =>
+ {
+ HomeGrid.Visibility = Visibility.Hidden;
+ SettingsGrid.Visibility = Visibility.Hidden;
+ LogGrid.Visibility = Visibility.Visible;
+ HomeButton.Foreground = white;
+ SettingsButton.Foreground = white;
+ LogButton.Foreground = green;
+ };
+ SettingsButton.Click += (s, e) =>
+ {
+ HomeGrid.Visibility = Visibility.Hidden;
+ LogGrid.Visibility = Visibility.Hidden;
+ SettingsGrid.Visibility = Visibility.Visible;
+ HomeButton.Foreground = white;
+ LogButton.Foreground = white;
+ SettingsButton.Foreground = green;
+ };
+ // считывание дескрипторов программ
+ var descriptors = Directory.GetFiles("descroptors", "*.desc");
+ programsArray = new ProgramLabel[descriptors.Length];
+ Log(descriptors.Length + " descriptors found\n");
+ for (int i = 0; i < descriptors.Length; i++)
+ {
+ programsArray[i] = new ProgramLabel(descriptors[i], i, this);
+ ProgramsPanel.Children.Add(programsArray[i]);
+ Log(programsArray[i].Text + " added to ProgramsPanel\n");
+ }
+ LaunchButton.Click += (s, e) => Launch();
+ InstallButton.Click += (s, e) => Install();
+ //mainSocket.FSP_Download(new FSP_FileObject("share\\file.arc", "downloads\\file.arc"));
+ }
+ catch (Exception e)
+ {
+ Log("error:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ }
+ }
+
+ public void Log(string msg)
+ {
+
+ if (LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ LogBox.Text += msg;
+ }
+
+ public void Log(params string[] input)
+ {
+ if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ str += input[++i];
+ Log(str);
+ }
+ else throw new Exception("error in Log(): every text string must have color string before");
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 5/dtlauncher-client-win/LoginWindow.xaml b/.old 5/dtlauncher-client-win/LoginWindow.xaml
new file mode 100644
index 0000000..c5ba562
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/LoginWindow.xaml
@@ -0,0 +1,42 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 5/dtlauncher-client-win/LoginWindow.xaml.cs b/.old 5/dtlauncher-client-win/LoginWindow.xaml.cs
new file mode 100644
index 0000000..7233c33
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/LoginWindow.xaml.cs
@@ -0,0 +1,122 @@
+using DTLib;
+using System;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Windows;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для LoginWindow.xaml
+ ///
+ public partial class LoginWindow : Window
+ {
+ public Socket mainSocket { private set; get; } = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ public string logfile { private set; get; } = $"logs\\client-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+
+ public LoginWindow()
+ {
+ try
+ {
+ InitializeComponent();
+ FileWork.DirCreate("logs");
+ FileWork.DirCreate("downloads");
+ PublicLog.LogDel += Log;
+ LoginButton.Click += Login;
+ RegisterButton.Click += Register;
+ Closed += CloseWindow;
+ Log("[" + DateTime.Now.ToString() + "]: launcher is starting\n");
+ }
+ catch (Exception e)
+ {
+ Log("error:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ }
+ }
+
+ void Log(string msg)
+ {
+ lock (new object())
+ {
+ if (LogBox.Text.Length - 1 >= 0 && LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg;
+ FileWork.Log(logfile, msg);
+ LogBox.Text += msg;
+ }
+ }
+
+ void Log(params string[] input)
+ {
+ var str = new System.Text.StringBuilder();
+ if (input.Length == 1) str.Append(input[0]);
+ else if (input.Length % 2 == 0) for (ushort i = 0; i < input.Length; i++) str.Append(input[++i]);
+ else throw new Exception("error in Log(): every text string must have color string before");
+ lock (new object())
+ {
+ FileWork.Log(logfile, str.ToString());
+ LogBox.Text += str.ToString();
+ }
+ }
+
+ void Register(object sender, EventArgs e)
+ {
+ try
+ {
+ var hasher = new Hasher();
+ File.WriteAllText($"register-{LoginBox.Text}.req",
+ hasher.HashCycled(hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()), 512).HashToString()
+ + ": " + LoginBox.Text);
+ Log($"request file created:{Directory.GetCurrentDirectory()}\\register-{LoginBox.Text}.req {hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()).Length}");
+ }
+ catch (Exception ex)
+ {
+ Log("registration error: " + ex.Message);
+ }
+ }
+
+ void Login(object sender, EventArgs e)
+ {
+ try
+ {
+ if (mainSocket.Connected)
+ {
+ mainSocket.Shutdown(SocketShutdown.Both);
+ mainSocket.Close();
+ mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+ }
+ mainSocket.Connect(new IPEndPoint(
+ Dns.GetHostAddresses(FileWork.ReadFromConfig("client.cfg", "central server ip"))[0],
+ FileWork.ReadFromConfig("client.cfg", "central server port").ToInt()));
+ mainSocket.ReceiveTimeout = 2000;
+ string request = mainSocket.GetPackageClear(16).ToStr();
+ if (request != "requesting hash") throw new Exception($"Login() error: invalid request <{request}> <{request.Length}>");
+ var hasher = new Hasher();
+ mainSocket.SendPackage(32, hasher.HashCycled(hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()), 512));
+ request = mainSocket.GetPackageClear(16).ToStr();
+ if (request != "success") throw new Exception($"Login() error: invalid success message <{request}>");
+ Log("succesfully logined\n");
+ // вызов нового окна
+ var lauWin = new LauncherWindow(mainSocket, logfile, LogBox.Text);
+ lauWin.Show();
+ Hide();
+ PublicLog.LogDel -= Log;
+ lauWin.Closed += CloseWindow;
+ }
+ catch (Exception ex)
+ {
+ Log("login error: " + ex.Message + '\n' + ex.StackTrace);
+ }
+ }
+
+ void CloseWindow(object sender, EventArgs e)
+ {
+ if (mainSocket.Connected)
+ {
+ mainSocket.Shutdown(SocketShutdown.Both);
+ mainSocket.Close();
+ }
+ Log("DTchat closed");
+ Close();
+ App.Current.Shutdown();
+ }
+ }
+}
diff --git a/.old 5/dtlauncher-client-win/ProgramLabel.xaml b/.old 5/dtlauncher-client-win/ProgramLabel.xaml
new file mode 100644
index 0000000..f6a6073
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/ProgramLabel.xaml
@@ -0,0 +1,33 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/.old 5/dtlauncher-client-win/ProgramLabel.xaml.cs b/.old 5/dtlauncher-client-win/ProgramLabel.xaml.cs
new file mode 100644
index 0000000..29a0f8d
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/ProgramLabel.xaml.cs
@@ -0,0 +1,115 @@
+using DTLib;
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Windows;
+using System.Windows.Controls;
+
+namespace dtlauncher_client_win
+{
+ ///
+ /// Логика взаимодействия для ProgramLabel.xaml
+ ///
+ public partial class ProgramLabel : UserControl
+ {
+ public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(ProgramLabel));
+ public string Text
+ {
+ get { return (string)GetValue(TextProperty); }
+ set { SetValue(TextProperty, value); }
+ }
+
+ public static DependencyProperty IconProperty = DependencyProperty.Register("Icon", typeof(System.Windows.Media.Imaging.BitmapImage), typeof(ProgramLabel));
+ public System.Windows.Media.Imaging.BitmapImage Icon
+ {
+ get { return (System.Windows.Media.Imaging.BitmapImage)GetValue(IconProperty); }
+ set { SetValue(IconProperty, value); }
+ }
+
+ public static DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(ProgramLabel));
+ public CornerRadius CornerRadius
+ {
+ get { return (CornerRadius)GetValue(CornerRadiusProperty); }
+ set { SetValue(CornerRadiusProperty, value); }
+ }
+
+ public string BackgroundImage;
+ public string Script;
+ public string InstallDir;
+ public string LaunchFile;
+ public string Arguments;
+ public string Description;
+ public int Number;
+ LauncherWindow Window;
+
+ public ProgramLabel()
+ {
+ InitializeComponent();
+ }
+
+ public ProgramLabel(string descriptorPath, int number, LauncherWindow window)
+ {
+ try
+ {
+ InitializeComponent();
+ Window = window;
+ Number = number;
+ FontSize = 14;
+ Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
+ Text = FileWork.ReadFromConfig(descriptorPath, "name");
+ NameLabel.Content = FileWork.ReadFromConfig(descriptorPath, "name");
+ IconImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\descroptors\\" + FileWork.ReadFromConfig(descriptorPath, "icon"), UriKind.Absolute));
+ BackgroundImage = Directory.GetCurrentDirectory() + "\\descroptors\\" + FileWork.ReadFromConfig(descriptorPath, "background");
+ Script = FileWork.ReadFromConfig(descriptorPath, "script");
+ InstallDir = FileWork.ReadFromConfig(descriptorPath, "installdir");
+ LaunchFile = FileWork.ReadFromConfig(descriptorPath, "launchfile");
+ Arguments = FileWork.ReadFromConfig(descriptorPath, "arguments");
+ Description = FileWork.ReadFromConfig(descriptorPath, "description").Replace("\\n", "\n");
+ //Window.Log(Text + " " + Icon + " " + Number);
+ }
+ catch (Exception e)
+ {
+ Window.Log("error:\n" + e.Message + "\n" + e.StackTrace + '\n');
+ }
+ }
+
+ void ProgramShow(object sender, System.Windows.Input.MouseButtonEventArgs e)
+ {
+ try
+ {
+ Window.programsArray[Window.PreviousProgramNum].Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
+ Window.programsArray[Window.PreviousProgramNum].FontWeight = FontWeights.Normal;
+ Window.programsArray[Window.PreviousProgramNum].FontSize = 14;
+ Window.PreviousProgramNum = Number;
+ Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(170, 170, 240));
+ FontWeight = FontWeights.Bold;
+ FontSize = 13;
+ Window.NameLabel.Content = Text;
+ Window.DescriptionBox.Text = Description;
+ Window.BackgroundImage.Source = new System.Windows.Media.Imaging.BitmapImage(new Uri(BackgroundImage, UriKind.Absolute));
+ Window.Launch = () =>
+ {
+ var startInfo = new ProcessStartInfo()
+ {
+ FileName = LaunchFile,
+ Arguments = Arguments,
+ };
+ Process.Start(startInfo);
+ };
+ Window.Install = () =>
+ {
+ var scriptrunner = new DTScript.ScriptRunner
+ {
+ debug = false,
+ mainSocket = Window.mainSocket
+ };
+ scriptrunner.RunScriptFile(Directory.GetCurrentDirectory() + "\\scripts\\" + Script);
+ };
+ }
+ catch (Exception ex)
+ {
+ Window.Log("error:\n" + ex.Message + "\n" + ex.StackTrace + '\n');
+ }
+ }
+ }
+}
diff --git a/.old 5/dtlauncher-client-win/Properties/AssemblyInfo.cs b/.old 5/dtlauncher-client-win/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..bbd57be
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/Properties/AssemblyInfo.cs
@@ -0,0 +1,53 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("dtlauncher-client-win")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-client-win")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM, установите атрибут ComVisible для этого типа в значение true.
+[assembly: ComVisible(false)]
+
+//Чтобы начать создание локализуемых приложений, задайте
+//CultureYouAreCodingWith в файле .csproj
+//в . Например, при использовании английского (США)
+//в своих исходных файлах установите в en-US. Затем отмените преобразование в комментарий
+//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
+//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+ ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
+ //(используется, если ресурс не найден на странице,
+ // или в словарях ресурсов приложения)
+ ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
+ //(используется, если ресурс не найден на странице,
+ // в приложении или в каких-либо словарях ресурсов для конкретной темы)
+)]
+
+
+// Сведения о версии для сборки включают четыре следующих значения:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 5/dtlauncher-client-win/Properties/Resources.Designer.cs b/.old 5/dtlauncher-client-win/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..615ca67
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/Properties/Resources.Designer.cs
@@ -0,0 +1,70 @@
+//------------------------------------------------------------------------------
+//
+// Этот код был создан программным средством.
+// Версия среды выполнения: 4.0.30319.42000
+//
+// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
+// код создан повторно.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_client_win.Properties
+{
+ ///
+ /// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
+ ///
+ // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
+ // класс с помощью таких средств, как ResGen или Visual Studio.
+ // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
+ // с параметром /str или заново постройте свой VS-проект.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_client_win.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Переопределяет свойство CurrentUICulture текущего потока для всех
+ /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/.old 5/dtlauncher-client-win/Properties/Resources.resx b/.old 5/dtlauncher-client-win/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/.old 5/dtlauncher-client-win/Properties/Settings.Designer.cs b/.old 5/dtlauncher-client-win/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..1c4561e
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/Properties/Settings.Designer.cs
@@ -0,0 +1,29 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_client_win.Properties
+{
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/.old 5/dtlauncher-client-win/Properties/Settings.settings b/.old 5/dtlauncher-client-win/Properties/Settings.settings
new file mode 100644
index 0000000..033d7a5
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 5/dtlauncher-client-win/dtlauncher-client-win.csproj b/.old 5/dtlauncher-client-win/dtlauncher-client-win.csproj
new file mode 100644
index 0000000..2bb81e5
--- /dev/null
+++ b/.old 5/dtlauncher-client-win/dtlauncher-client-win.csproj
@@ -0,0 +1,125 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}
+ WinExe
+ dtlauncher_client_win
+ dtlauncher-client-win
+ v4.8
+ 512
+ {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ 4
+ true
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+ true
+
+
+ dtlauncher_client_win.App
+
+
+ dtscript.ico
+
+
+
+
+
+
+
+
+
+
+
+ 4.0
+
+
+
+
+
+
+
+ MSBuild:Compile
+ Designer
+
+
+ Designer
+ MSBuild:Compile
+
+
+ MSBuild:Compile
+ Designer
+
+
+ App.xaml
+ Code
+
+
+ LauncherWindow.xaml
+
+
+ LoginWindow.xaml
+ Code
+
+
+ Designer
+ MSBuild:Compile
+
+
+
+
+ ProgramLabel.xaml
+
+
+ Code
+
+
+ True
+ True
+ Resources.resx
+
+
+ True
+ Settings.settings
+ True
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+ {e02ea967-fd29-47d2-b25b-ba684b784aee}
+ dtscript
+
+
+
+
+
+
+
+ del /f /q dtlauncher-client-win.exe.config
+
+
\ No newline at end of file
diff --git a/.old 5/dtlauncher-client-win/dtscript.ico b/.old 5/dtlauncher-client-win/dtscript.ico
new file mode 100644
index 0000000..df420bb
Binary files /dev/null and b/.old 5/dtlauncher-client-win/dtscript.ico differ
diff --git a/.old 5/dtlauncher-server-win/App.config b/.old 5/dtlauncher-server-win/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 5/dtlauncher-server-win/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 5/dtlauncher-server-win/Program.cs b/.old 5/dtlauncher-server-win/Program.cs
new file mode 100644
index 0000000..8479647
--- /dev/null
+++ b/.old 5/dtlauncher-server-win/Program.cs
@@ -0,0 +1,121 @@
+using DTLib;
+using System;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using static DTLib.NetWork;
+
+namespace dtlauncher_server
+{
+ class Program
+ {
+ static Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
+
+ static void Main(string[] args)
+ {
+ while (true)
+ {
+ try
+ {
+ Console.Title = "dtlauncher server";
+ PublicLog.LogDel += Log;
+ Log("b", $"<{FileWork.ReadFromConfig("server.cfg", "server ip")}:{FileWork.ReadFromConfig("server.cfg", "server port")}>\n");
+ mainSocket.Bind(new IPEndPoint(IPAddress.Parse(
+ FileWork.ReadFromConfig("server.cfg", "server ip")),
+ FileWork.ReadFromConfig("server.cfg", "server port").ToInt()));
+ Log("g", "server started succesfully\n");
+ mainSocket.Listen(1000);
+ while (true)
+ {
+ var userSocket = mainSocket.Accept();
+ var userThread = new Thread(new ParameterizedThreadStart(UserHandle));
+ //users.Add(userSocket, userThread);
+ userThread.Start(userSocket);
+ }
+ }
+ catch (Exception ex)
+ {
+ if (mainSocket.IsBound)
+ {
+ mainSocket.Shutdown(SocketShutdown.Both);
+ mainSocket.Close();
+ }
+ Log("r", $"dtlauncher_server.Main() error:\n{ex.Message}\n{ex.StackTrace}\n");
+ }
+ Log("gray", "\n");
+ }
+ }
+
+ // лог в консоль и файл
+ static readonly string logfile = $"logs\\dtlauncher-server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+ static void Log(params string[] msg)
+ {
+ lock (new object())
+ {
+ if (msg.Length == 1)
+ {
+ msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
+ FileWork.Log(logfile, msg[0]);
+ }
+ else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
+ else
+ {
+ msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
+ var str = new System.Text.StringBuilder();
+ for (int i = 0; i < msg.Length; i++) str.Append(msg[++i]);
+ FileWork.Log(logfile, str.ToString());
+ }
+ ColoredConsole.Write(msg);
+ }
+ }
+
+ // запускается для каждого юзера в отдельном потоке
+ static void UserHandle(object _handlerSocket)
+ {
+ Log("g", "user connecting\n");
+ Socket handlerSocket = (Socket)_handlerSocket;
+ try
+ {
+ handlerSocket.SendPackage(16, "requesting hash".ToBytes());
+ string login;
+ lock (new object())
+ {
+ login = FileWork.ReadFromConfig("users.db", handlerSocket.GetPackageRaw(32).HashToString());
+ }
+ handlerSocket.SendPackage(16, "success".ToBytes());
+ Log("g", $"user <{login}> succesfully logged\n");
+ while (true)
+ {
+ if (handlerSocket.Available >= 64)
+ {
+ var request = handlerSocket.GetPackageClear(64).ToStr();
+ switch (request)
+ {
+ // ответ на NetWork.Ping()
+ /*case "ping":
+ handlerSocket.Send("pong".ToBytes());
+ break;*/
+ // отправка списка активных серверов
+ /*case "requesting servers list":
+
+ break;*/
+ case "requesting file download":
+ handlerSocket.FSP_Upload();
+ break;
+ default:
+ throw new Exception("unknown request: " + request);
+ }
+ }
+ else Thread.Sleep(10);
+ }
+ }
+ catch (Exception ex)
+ {
+ Log("y", $"UserStart() error:\n message:\n {ex.Message}\n{ex.StackTrace}\n");
+ handlerSocket.Shutdown(SocketShutdown.Both);
+ handlerSocket.Close();
+ Thread.CurrentThread.Abort();
+ }
+ }
+ }
+}
diff --git a/.old 5/dtlauncher-server-win/Properties/AssemblyInfo.cs b/.old 5/dtlauncher-server-win/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..340af78
--- /dev/null
+++ b/.old 5/dtlauncher-server-win/Properties/AssemblyInfo.cs
@@ -0,0 +1,53 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Windows;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набор атрибутов. Измените значения этих атрибутов, чтобы изменить сведения,
+// связанные со сборкой.
+[assembly: AssemblyTitle("dtlauncher-server-win")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("dtlauncher-server-win")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM, установите атрибут ComVisible для этого типа в значение true.
+[assembly: ComVisible(false)]
+
+//Чтобы начать создание локализуемых приложений, задайте
+//CultureYouAreCodingWith в файле .csproj
+//в . Например, при использовании английского (США)
+//в своих исходных файлах установите в en-US. Затем отмените преобразование в комментарий
+//атрибута NeutralResourceLanguage ниже. Обновите "en-US" в
+//строка внизу для обеспечения соответствия настройки UICulture в файле проекта.
+
+//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
+
+
+[assembly: ThemeInfo(
+ ResourceDictionaryLocation.None, //где расположены словари ресурсов по конкретным тематикам
+ //(используется, если ресурс не найден на странице,
+ // или в словарях ресурсов приложения)
+ ResourceDictionaryLocation.SourceAssembly //где расположен словарь универсальных ресурсов
+ //(используется, если ресурс не найден на странице,
+ // в приложении или в каких-либо словарях ресурсов для конкретной темы)
+)]
+
+
+// Сведения о версии для сборки включают четыре следующих значения:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 5/dtlauncher-server-win/Properties/Resources.Designer.cs b/.old 5/dtlauncher-server-win/Properties/Resources.Designer.cs
new file mode 100644
index 0000000..9d42357
--- /dev/null
+++ b/.old 5/dtlauncher-server-win/Properties/Resources.Designer.cs
@@ -0,0 +1,70 @@
+//------------------------------------------------------------------------------
+//
+// Этот код был создан программным средством.
+// Версия среды выполнения: 4.0.30319.42000
+//
+// Изменения в этом файле могут привести к неправильному поведению и будут утрачены, если
+// код создан повторно.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_server_win.Properties
+{
+ ///
+ /// Класс ресурсов со строгим типом для поиска локализованных строк и пр.
+ ///
+ // Этот класс был автоматически создан при помощи StronglyTypedResourceBuilder
+ // класс с помощью таких средств, как ResGen или Visual Studio.
+ // Для добавления или удаления члена измените файл .ResX, а затем перезапустите ResGen
+ // с параметром /str или заново постройте свой VS-проект.
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ internal class Resources
+ {
+
+ private static global::System.Resources.ResourceManager resourceMan;
+
+ private static global::System.Globalization.CultureInfo resourceCulture;
+
+ [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
+ internal Resources()
+ {
+ }
+
+ ///
+ /// Возврат кэшированного экземпляра ResourceManager, используемого этим классом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Resources.ResourceManager ResourceManager
+ {
+ get
+ {
+ if ((resourceMan == null))
+ {
+ global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("dtlauncher_server_win.Properties.Resources", typeof(Resources).Assembly);
+ resourceMan = temp;
+ }
+ return resourceMan;
+ }
+ }
+
+ ///
+ /// Переопределяет свойство CurrentUICulture текущего потока для всех
+ /// подстановки ресурсов с помощью этого класса ресурсов со строгим типом.
+ ///
+ [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
+ internal static global::System.Globalization.CultureInfo Culture
+ {
+ get
+ {
+ return resourceCulture;
+ }
+ set
+ {
+ resourceCulture = value;
+ }
+ }
+ }
+}
diff --git a/.old 5/dtlauncher-server-win/Properties/Resources.resx b/.old 5/dtlauncher-server-win/Properties/Resources.resx
new file mode 100644
index 0000000..af7dbeb
--- /dev/null
+++ b/.old 5/dtlauncher-server-win/Properties/Resources.resx
@@ -0,0 +1,117 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ text/microsoft-resx
+
+
+ 2.0
+
+
+ System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
+ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
+
+
\ No newline at end of file
diff --git a/.old 5/dtlauncher-server-win/Properties/Settings.Designer.cs b/.old 5/dtlauncher-server-win/Properties/Settings.Designer.cs
new file mode 100644
index 0000000..cb2dff3
--- /dev/null
+++ b/.old 5/dtlauncher-server-win/Properties/Settings.Designer.cs
@@ -0,0 +1,29 @@
+//------------------------------------------------------------------------------
+//
+// This code was generated by a tool.
+// Runtime Version:4.0.30319.42000
+//
+// Changes to this file may cause incorrect behavior and will be lost if
+// the code is regenerated.
+//
+//------------------------------------------------------------------------------
+
+
+namespace dtlauncher_server_win.Properties
+{
+ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
+ {
+
+ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
+
+ public static Settings Default
+ {
+ get
+ {
+ return defaultInstance;
+ }
+ }
+ }
+}
diff --git a/.old 5/dtlauncher-server-win/Properties/Settings.settings b/.old 5/dtlauncher-server-win/Properties/Settings.settings
new file mode 100644
index 0000000..033d7a5
--- /dev/null
+++ b/.old 5/dtlauncher-server-win/Properties/Settings.settings
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 5/dtlauncher-server-win/dtlauncher-server-win.csproj b/.old 5/dtlauncher-server-win/dtlauncher-server-win.csproj
new file mode 100644
index 0000000..9c05b3a
--- /dev/null
+++ b/.old 5/dtlauncher-server-win/dtlauncher-server-win.csproj
@@ -0,0 +1,111 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}
+ Exe
+ dtlauncher_server_win
+ dtlauncher-server-win
+ v4.8
+ 512
+ {60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
+ 4
+ true
+ true
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
+
+
+ AnyCPU
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 4.0
+
+
+
+
+
+
+
+
+ Code
+
+
+ True
+ True
+ Resources.resx
+
+
+ True
+ Settings.settings
+ True
+
+
+ ResXFileCodeGenerator
+ Resources.Designer.cs
+
+
+ SettingsSingleFileGenerator
+ Settings.Designer.cs
+
+
+
+
+
+
+
+ {ce793497-2d5c-42d8-b311-e9b32af9cdfb}
+ DTLib
+
+
+
+
+ False
+ Microsoft .NET Framework 4.8 %28x86 и x64%29
+ true
+
+
+ False
+ .NET Framework 3.5 SP1
+ false
+
+
+
+
+ del /f /q dtlauncher-server-win.exe.config
+
+
\ No newline at end of file
diff --git a/.old 5/dtlauncher.sln b/.old 5/dtlauncher.sln
new file mode 100644
index 0000000..0d389f2
--- /dev/null
+++ b/.old 5/dtlauncher.sln
@@ -0,0 +1,45 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 16
+VisualStudioVersion = 16.0.30907.101
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-client-win", "dtlauncher-client-win\dtlauncher-client-win.csproj", "{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}"
+ ProjectSection(ProjectDependencies) = postProject
+ {4784D974-A342-4202-9430-90FE5AC00FC7} = {4784D974-A342-4202-9430-90FE5AC00FC7}
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-server-win", "dtlauncher-server-win\dtlauncher-server-win.csproj", "{8B9889A7-93DC-4914-92D1-8209BD3BA71A}"
+ ProjectSection(ProjectDependencies) = postProject
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} = {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ EndProjectSection
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtscript", "..\dtscript\dtscript.csproj", "{E02EA967-FD29-47D2-B25B-BA684B784AEE}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "updater", "updater\updater.csproj", "{4784D974-A342-4202-9430-90FE5AC00FC7}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Build|Any CPU = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.Build.0 = Build|Any CPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {367793EE-4757-4ADD-BF7E-960DC9EB6DF9}.Build|Any CPU.Build.0 = Build|Any CPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.Build.0 = Build|Any CPU
+ {E02EA967-FD29-47D2-B25B-BA684B784AEE}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {E02EA967-FD29-47D2-B25B-BA684B784AEE}.Build|Any CPU.Build.0 = Build|Any CPU
+ {4784D974-A342-4202-9430-90FE5AC00FC7}.Build|Any CPU.ActiveCfg = Build|Any CPU
+ {4784D974-A342-4202-9430-90FE5AC00FC7}.Build|Any CPU.Build.0 = Build|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {E6569C0C-DD32-4F7D-AD4C-DBC5434D2F8C}
+ EndGlobalSection
+EndGlobal
diff --git a/.old 5/updater/App.config b/.old 5/updater/App.config
new file mode 100644
index 0000000..193aecc
--- /dev/null
+++ b/.old 5/updater/App.config
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 5/updater/Program.cs b/.old 5/updater/Program.cs
new file mode 100644
index 0000000..ac35391
--- /dev/null
+++ b/.old 5/updater/Program.cs
@@ -0,0 +1,39 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+
+namespace updater
+{
+ class Program
+ {
+ static void Main(string[] args)
+ {
+
+ }
+
+ // вывод лога в консоль и файл
+ static readonly string logfile = $"logs-updater\\updater-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
+
+ static public void Log(params string[] msg)
+ {
+ if (msg.Length == 1)
+ {
+ msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
+ FileWork.Log(logfile, msg[0]);
+ }
+ else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
+ else
+ {
+ msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
+ var str = new System.Text.StringBuilder();
+ for (int i = 0; i < msg.Length; i++) str.Append(msg[++i]);
+ FileWork.Log(logfile, str.ToString());
+ }
+ ColoredConsole.Write(msg);
+ }
+ }
+}
diff --git a/.old 5/updater/Properties/AssemblyInfo.cs b/.old 5/updater/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..3f58293
--- /dev/null
+++ b/.old 5/updater/Properties/AssemblyInfo.cs
@@ -0,0 +1,36 @@
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные с этой сборкой.
+[assembly: AssemblyTitle("updater")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("updater")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// из модели COM задайте для атрибута ComVisible этого типа значение true.
+[assembly: ComVisible(false)]
+
+// Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM
+[assembly: Guid("4784d974-a342-4202-9430-90fe5ac00fc7")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Номер редакции
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 5/updater/dtlib/ColoredConsole.cs b/.old 5/updater/dtlib/ColoredConsole.cs
new file mode 100644
index 0000000..09e6ac8
--- /dev/null
+++ b/.old 5/updater/dtlib/ColoredConsole.cs
@@ -0,0 +1,83 @@
+using System;
+
+namespace updater
+{
+ //
+ // вывод и ввод цветного текста в консоли
+ // работает медленнее чем хотелось бы
+ //
+ public static class ColoredConsole
+ {
+ // парсит название цвета в ConsoleColor
+ public static ConsoleColor ParseColor(string color)
+ {
+ switch (color)
+ {
+ //case "magneta":
+ case "m":
+ return ConsoleColor.Magenta;
+ //case "green":
+ case "g":
+ return ConsoleColor.Green;
+ //case "red":
+ case "r":
+ return ConsoleColor.Red;
+ //case "yellow":
+ case "y":
+ return ConsoleColor.Yellow;
+ //case "white":
+ case "w":
+ return ConsoleColor.White;
+ //case "blue":
+ case "b":
+ return ConsoleColor.Blue;
+ //case "cyan":
+ case "c":
+ return ConsoleColor.Cyan;
+ //case "gray":
+ case "gray":
+ return ConsoleColor.Gray;
+ //case "black":
+ case "black":
+ return ConsoleColor.Black;
+ default:
+ throw new Exception("incorrect color: " + color);
+ }
+ }
+
+ // вывод цветного текста
+ public static void Write(params string[] input)
+ {
+ if (input.Length == 1)
+ {
+ if (Console.ForegroundColor != ConsoleColor.Green) Console.ForegroundColor = ConsoleColor.Gray;
+ Console.Write(input[0]);
+ }
+ else if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ var c = ParseColor(input[i]);
+ if (Console.ForegroundColor != c)
+ {
+ Console.Write(str);
+ Console.ForegroundColor = c;
+ str = "";
+ }
+ str += input[++i];
+ }
+ if (str != "") Console.Write(str);
+ }
+ else throw new Exception("error in Write(): every text string must have color string before");
+ }
+
+ // ввод цветного текста
+ public static string Read(string color)
+ {
+ var c = ParseColor(color);
+ if (Console.ForegroundColor != c) Console.ForegroundColor = c;
+ return Console.ReadLine();
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 5/updater/dtlib/FileWork.cs b/.old 5/updater/dtlib/FileWork.cs
new file mode 100644
index 0000000..9838fe0
--- /dev/null
+++ b/.old 5/updater/dtlib/FileWork.cs
@@ -0,0 +1,168 @@
+using System.Collections.Generic;
+using System.IO;
+
+namespace updater
+{
+ //
+ // методы для работы с файловой системой
+ //
+ public static class FileWork
+ {
+ // записывает текст в файл и закрывает файл
+ public static void Log(string logfile, string msg)
+ {
+ lock (new object())
+ {
+ if (logfile.Contains("\\")) DirCreate(logfile.Remove(logfile.LastIndexOf('\\')));
+ var st = File.Open(logfile, FileMode.Append);
+ var writer = new StreamWriter(st, SimpleConverter.UTF8);
+ writer.Write(msg);
+ writer.Close();
+ st.Close();
+ }
+ }
+
+ // создает папку если её не существует
+ public static void DirCreate(string dir)
+ {
+ if (!Directory.Exists(dir))
+ {
+ // проверяет существование папки, в которой нужно создать dir
+ if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
+ DirCreate(dir.Remove(dir.LastIndexOf('\\')));
+ Directory.CreateDirectory(dir);
+ }
+ }
+
+ // чтение параметров из конфига
+ public static string ReadFromConfig(string configfile, string key)
+ {
+ key += ": ";
+ var reader = new StreamReader(configfile);
+ while (!reader.EndOfStream)
+ {
+ string st = reader.ReadLine();
+ if (st.StartsWith(key))
+ {
+ string value = "";
+ for (int i = key.Length; i < st.Length; i++)
+ {
+ if (st[i] == '#') return value;
+ if (st[i] == '%')
+ {
+ bool stop = false;
+ string placeholder = "";
+ i++;
+ while (!stop)
+ {
+ if (st[i] == '%')
+ {
+ stop = true;
+ value += ReadFromConfig(configfile, placeholder);
+ }
+ else
+ {
+ placeholder += st[i];
+ i++;
+ }
+ }
+ }
+ else value += st[i];
+ }
+ return value;
+ }
+ }
+ reader.Close();
+ return null;
+ }
+
+ // копирует все файли и папки
+ public static void DirCopy(string source_dir, string new_dir, bool Override)
+ {
+ DirCreate(new_dir);
+ List subdirs = new List();
+ List files = GetAllFiles(source_dir, ref subdirs);
+ for (int i = 0; i < subdirs.Count; i++)
+ {
+ DirCreate(subdirs[i].Replace(source_dir, new_dir));
+ }
+ for (int i = 0; i < files.Count; i++)
+ {
+ string f = files[i].Replace(source_dir, new_dir);
+ File.Copy(files[i], f, Override);
+ //PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
+ }
+ }
+
+ // копирует все файли и папки и выдаёт список конфликтующих файлов
+ public static void DirCopy(string source_dir, string new_dir, bool owerwrite, out List conflicts)
+ {
+ conflicts = new List();
+ var subdirs = new List();
+ var files = GetAllFiles(source_dir, ref subdirs);
+ DirCreate(new_dir);
+ for (int i = 0; i < subdirs.Count; i++)
+ {
+ DirCreate(subdirs[i].Replace(source_dir, new_dir));
+ }
+ for (int i = 0; i < files.Count; i++)
+ {
+ string newfile = files[i].Replace(source_dir, new_dir);
+ if (File.Exists(newfile)) conflicts.Add(newfile);
+ File.Copy(files[i], newfile, owerwrite);
+ //PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
+ }
+ }
+
+ // выдает список всех файлов
+ public static List GetAllFiles(string dir)
+ {
+ List all_files = new List();
+ string[] cur_files = Directory.GetFiles(dir);
+ for (int i = 0; i < cur_files.Length; i++)
+ {
+ all_files.Add(cur_files[i]);
+ //PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
+ }
+ string[] cur_subdirs = Directory.GetDirectories(dir);
+ for (int i = 0; i < cur_subdirs.Length; i++)
+ {
+ //PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
+ all_files.AddRange(GetAllFiles(cur_subdirs[i]));
+ }
+ return all_files;
+ }
+
+ // выдает список всех файлов и подпапок в папке
+ public static List GetAllFiles(string dir, ref List all_subdirs)
+ {
+ List all_files = new List();
+ string[] cur_files = Directory.GetFiles(dir);
+ for (int i = 0; i < cur_files.Length; i++)
+ {
+ all_files.Add(cur_files[i]);
+ //PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
+ }
+ string[] cur_subdirs = Directory.GetDirectories(dir);
+ for (int i = 0; i < cur_subdirs.Length; i++)
+ {
+ all_subdirs.Add(cur_subdirs[i]);
+ //PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
+ all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs));
+ }
+ return all_files;
+ }
+
+ // удаляет папку со всеми подпапками и файлами
+ public static void DirDelete(string dir)
+ {
+ var subdirs = new List();
+ var files = GetAllFiles(dir, ref subdirs);
+ for (int i = 0; i < files.Count; i++)
+ File.Delete(files[i]);
+ for (int i = subdirs.Count - 1; i >= 0; i--)
+ Directory.Delete(subdirs[i]);
+ Directory.Delete(dir);
+ }
+ }
+}
diff --git a/.old 5/updater/dtlib/Hasher.cs b/.old 5/updater/dtlib/Hasher.cs
new file mode 100644
index 0000000..a4403ed
--- /dev/null
+++ b/.old 5/updater/dtlib/Hasher.cs
@@ -0,0 +1,59 @@
+using System.Collections.Generic;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace updater
+{
+ //
+ // хеширует массивы байтов алшоритмом SHA256 и файлы алгоримом XXHash32
+ //
+ public class Hasher
+ {
+ readonly HashAlgorithm sha256 = SHA256.Create();
+ readonly HashAlgorithm xxh32 = XXHash32.Create();
+
+ public Hasher() { }
+
+ // хеш массива
+ public byte[] Hash(byte[] input)
+ => sha256.ComputeHash(input);
+
+ // хеш из двух массивов
+ public byte[] Hash(byte[] input, byte[] salt)
+ {
+ List rez = new List();
+ rez.AddRange(input);
+ rez.AddRange(salt);
+ return sha256.ComputeHash(rez.ToArray());
+ }
+
+ // хеш двух массивов зацикленный
+ public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = Hash(input, salt);
+ }
+ return input;
+ }
+ // хеш зацикленный
+ public byte[] HashCycled(byte[] input, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = Hash(input);
+ }
+ return input;
+ }
+
+ // хеш файла
+ public byte[] HashFile(string filename)
+ {
+ //var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
+ var hash = xxh32.ComputeHash(File.OpenRead(filename));
+ //var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
+ //PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}\n");
+ return hash;
+ }
+ }
+}
diff --git a/.old 5/updater/dtlib/NetWork.cs b/.old 5/updater/dtlib/NetWork.cs
new file mode 100644
index 0000000..c44029b
--- /dev/null
+++ b/.old 5/updater/dtlib/NetWork.cs
@@ -0,0 +1,277 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using static updater.Program;
+
+namespace updater
+{
+ //
+ // весь униврсальный неткод тут
+ // большинство методов предназначены для работы с TCP сокетами (Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ //
+ public static class NetWork
+ {
+ /*
+ // получение информации (сокет должен быть в режиме Listen)
+ public static byte[] GetData(this Socket socket)
+ {
+ List output = new List();
+ byte[] data = new byte[256];
+ do
+ {
+ int amount = socket.Receive(data, data.Length, 0);
+ for (int i = 0; i < amount; i++)
+ {
+ output.Add(data[i]);
+ }
+ }
+ while (socket.Available > 0);
+ return output.ToArray();
+ }
+
+ // отправка запроса и получение ответа на него (сокет должен быть в режиме Listen)
+ public static byte[] Request(this Socket socket, string request)
+ {
+ socket.Send(request.ToBytes());
+ return GetData(socket);
+ }
+ public static byte[] Request(this Socket socket, byte[] request)
+ {
+ socket.Send(request);
+ return GetData(socket);
+ }
+ */
+
+ // скачивание файла с фтп сервера
+ public static void FtpDownload(string address, string login, string password, string outfile)
+ {
+ try
+ {
+ // debug
+ Log("y", "file on server: <", "c", address, "y", ">\nfile on client: <", "c", outfile, "y", ">\n" );
+ // создание запроса
+ // "ftp://m1net.keenetic.pro:20000/" + @infile
+ FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
+ request.Credentials = new NetworkCredential(login, password);
+ request.Method = WebRequestMethods.Ftp.DownloadFile;
+ // получение ответа на запрос
+ FtpWebResponse response = (FtpWebResponse)request.GetResponse();
+ Stream responseStream = response.GetResponseStream();
+ FileStream fs = new FileStream(@Directory.GetCurrentDirectory() + '\\' + @outfile, FileMode.Create);
+ byte[] buffer = new byte[64];
+ int size = 0;
+
+ while ((size = responseStream.Read(buffer, 0, buffer.Length)) > 0)
+ fs.Write(buffer, 0, size);
+ fs.Close();
+ response.Close();
+ }
+ catch (WebException e) { throw new Exception("ftp error:\n" + ((FtpWebResponse)e.Response).StatusDescription + '\n'); }
+ }
+
+ // запрашивает список серверов с главного сервера
+ /*public static ServerObject[] RequestServersList(Socket centralServer)
+ {
+ List servers = new List();
+ string[] lines = Request(centralServer, "a356a4257dbf9d87c77cf87c3c694b30160b6ddfd3db82e7f62320207109e352").ToStr().Split('\n');
+ for (int i = 0; i < lines.Length; i++)
+ {
+ string[] properties = lines[i].Split(',');
+ servers.Add(new ServerObject(properties[0], properties[1], properties[2]));
+ }
+ return servers.ToArray();
+ }*/
+
+ // пингует айпи с помощью встроенной в винду проги, возвращает задержку
+ public static string PingIP(string address)
+ {
+ Process proc = new Process();
+ proc.StartInfo.FileName = "cmd.exe";
+ proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address;
+ proc.StartInfo.CreateNoWindow = true;
+ proc.StartInfo.UseShellExecute = false;
+ proc.StartInfo.RedirectStandardOutput = true;
+ proc.Start();
+ var outStream = proc.StandardOutput;
+ var rezult = outStream.ReadToEnd();
+ rezult = rezult.Remove(0, rezult.LastIndexOf('=') + 2);
+ return rezult.Remove(rezult.Length - 4);
+ }
+
+ // пингует сервер (сервер должен уметь принимать такой запрос от клиента), возвращает true если сервер правильно ответил
+ /*public static bool Ping(this Socket socket)
+ {
+ if (Request(socket, "ab53bf045004875fb17086f7f992b0514fb96c038f336e0bfc21609b20303f07").ToStr() == "91b5c0383b75fb1708f00486f7f9b96c038ab3bfc21059b20176f603692b05e0") return true;
+ else return false;
+ } */
+
+ // скачивает файл с помощью FSP протокола
+ public static void FSP_Download(this Socket mainSocket, FSP_FileObject file)
+ {
+ Log(new string[] { "c", $"remote socket accepted download request: {file.ClientFilePath}\n" });
+ mainSocket.Send("requesting file download".ToBytes());
+ string answ = mainSocket.GetPackageClear(64).ToStr();
+ if (answ != "download request accepted")
+ throw new Exception($"FSP_Download() error: a download socket recieved an incorrect message: {answ}\n");
+
+ mainSocket.SendPackage(256, file.ServerFilePath.ToBytes());
+ file.Size = Convert.ToUInt32(mainSocket.GetPackageClear(64).ToStr());
+ file.Hash = mainSocket.GetPackageClear(64);
+ mainSocket.SendPackage(64, "ready".ToBytes());
+ file.Stream = File.Open(file.ClientFilePath, FileMode.Create, FileAccess.Write);
+ int packagesCount = 0;
+ byte[] buffer = new byte[5120];
+ var hashstr = file.Hash.HashToString();
+ int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
+ // рассчёт скорости
+ int seconds = 0;
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // получение файла
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ buffer = mainSocket.GetPackageRaw(buffer.Length);
+ file.Stream.Write(buffer, 0, buffer.Length);
+ file.Stream.Flush();
+ }
+ Log(new string[] { "y", " full packages recieved\n" });
+ speedCounter.Stop();
+ // получение остатка
+ mainSocket.SendPackage(64, "remain request".ToBytes());
+ buffer = mainSocket.GetPackageRaw((file.Size - fullPackagesCount * 5120).ToInt());
+ file.Stream.Write(buffer, 0, buffer.Length);
+ file.Stream.Flush();
+ file.Stream.Close();
+ Log(new string[] { "g", $" file {file.ClientFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) downloaded.\n" });
+ }
+
+ // отдаёт файл с помощью FSP протокола
+ public static void FSP_Upload(this Socket mainSocket)
+ {
+ mainSocket.SendPackage(64, "download request accepted".ToBytes());
+ var file = new FSP_FileObject
+ {
+ ServerFilePath = mainSocket.GetPackageClear(256).ToStr()
+ };
+ file.Size = new FileInfo(file.ServerFilePath).Length;
+ file.Hash = new Hasher().HashFile(file.ServerFilePath);
+ mainSocket.SendPackage(64, file.Size.ToString().ToBytes());
+ mainSocket.SendPackage(64, file.Hash);
+ if (mainSocket.GetPackageClear(64).ToStr() != "ready") throw new Exception("user socket isn't ready");
+ Log(new string[] { "c", $"local socket accepted file download request: {file.ServerFilePath}\n" });
+ file.Stream = new FileStream(file.ServerFilePath, FileMode.Open, FileAccess.Read);
+ byte[] buffer = new byte[5120];
+ var hashstr = file.Hash.HashToString();
+ int packagesCount = 0;
+ int seconds = 0;
+ // рассчёт скорости
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // отправка файла
+ int fullPackagesCount = SimpleConverter.Truncate(file.Size / buffer.Length);
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ file.Stream.Read(buffer, 0, buffer.Length);
+ mainSocket.SendPackage(buffer.Length, buffer);
+ }
+ Log(new string[] { "y", " full packages send\n" });
+ speedCounter.Stop();
+ // досылка остатка
+ if (mainSocket.GetPackageClear(64).ToStr() != "remain request")
+ throw new Exception("FSP_Upload() error: didn't get remain request");
+ buffer = new byte[Convert.ToInt32(file.Size - file.Stream.Position)];
+ file.Stream.Read(buffer, 0, buffer.Length);
+ mainSocket.SendPackage(buffer.Length, buffer);
+ file.Stream.Close();
+ Log(new string[] { "g", $" file {file.ServerFilePath} ({packagesCount * 5120 + buffer.Length} of {file.Size} bytes) uploaded.\n" });
+ }
+
+ // ждёт пакет заданного размера с заданным началом и концом
+ // убирает пустые байты в конце пакета
+ public static byte[] GetPackageClear(this Socket socket, int packageSize)
+ {
+ byte[] data = socket.GetPackageRaw(packageSize);
+ bool clear = false;
+ int toClean = packageSize;
+ for (int i = packageSize - 1; !clear; i--)
+ {
+ if (data[i] == 00) toClean--;
+ else clear = true;
+ }
+ if (toClean != packageSize) data = data.RemoveRange(toClean);
+ return data;
+ }
+ //не убирает пустые байты в конце пакета
+ public static byte[] GetPackageRaw(this Socket socket, int packageSize)
+ {
+ var startsWith = ("<" + packageSize.ToString() + ">").ToBytes();
+ packageSize += startsWith.Length;
+ byte[] data = new byte[packageSize];
+ // цикл выполняется пока не пройдёт 1000 мс
+ for (short s = 0; s < 1000; s += 10)
+ {
+ if (socket.Available >= packageSize)
+ {
+ socket.Receive(data, packageSize, 0);
+ if (data.StartsWith(startsWith)) return data.RemoveRange(0, startsWith.Length);
+ else throw new Exception($"GetPackage() error: has got incorrect package\n");
+ }
+ else Thread.Sleep(10);
+ }
+ throw new Exception($"GetPackage() error: timeout\n");
+ }
+
+ // отправляет пакет заданного размера, добавля в конец нули если длина data меньше чем packageSize
+ public static void SendPackage(this Socket socket, int packageSize, byte[] data)
+ {
+ if (data.Length > packageSize) throw new Exception("SendPackage() error: data.Length > packageSize\n");
+ var startsWith = ("<" + packageSize.ToString() + ">").ToBytes();
+ packageSize += startsWith.Length;
+ var list = new List();
+ list.AddRange(startsWith);
+ list.AddRange(data);
+ for (int i = startsWith.Length + data.Length; i < packageSize; i++) list.Add(0);
+ socket.Send(list.ToArray());
+ }
+
+
+ // хранит свойства файла, передаваемого с помощью моего протокола
+ public class FSP_FileObject
+ {
+ public string ServerFilePath;
+ public string ClientFilePath;
+ public long Size;
+ public byte[] Hash;
+ public Stream Stream;
+
+ public FSP_FileObject() { }
+ }
+
+ // хранит свойства сервера, полученные с помощью RequestServersList()
+ public class ServerObject
+ {
+ public string Address;
+ public string Name;
+ public string Speed;
+
+ public ServerObject(string address, string name, string speed)
+ {
+ Address = address;
+ Name = name;
+ Speed = speed;
+ }
+
+ public ServerObject() { }
+ }
+ }
+}
diff --git a/.old 5/updater/dtlib/SimpleConverter.cs b/.old 5/updater/dtlib/SimpleConverter.cs
new file mode 100644
index 0000000..d1a0877
--- /dev/null
+++ b/.old 5/updater/dtlib/SimpleConverter.cs
@@ -0,0 +1,88 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace updater
+{
+ //
+ // содержит методы расширения для различных операций и преобразований
+ //
+ public static class SimpleConverter
+ {
+ public static Encoding UTF8 = new UTF8Encoding(false);
+ // байты в кодировке UTF8 в строку
+ public static string ToStr(this byte[] bytes)
+ => UTF8.GetString(bytes);
+ public static string ToStr(this List bytes)
+ => UTF8.GetString(bytes.ToArray());
+
+ // хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
+ public static string HashToString(this byte[] hash)
+ {
+ var builder = new StringBuilder();
+ for (int i = 0; i < hash.Length; i++)
+ {
+ builder.Append(hash[i].ToString("x2"));
+ }
+ return builder.ToString();
+ }
+
+ // строку в байты
+ public static byte[] ToBytes(this string str)
+ => UTF8.GetBytes(str);
+
+ // эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
+ public static bool StartsWith(this byte[] source, byte[] startsWith)
+ {
+ for (int i = 0; i < startsWith.Length; i++)
+ {
+ if (source[i] != startsWith[i]) return false;
+ }
+ return true;
+ }
+
+ public static bool EndsWith(this byte[] source, byte[] endsWith)
+ {
+ for (int i = 0; i < endsWith.Length; i++)
+ {
+ if (source[source.Length - endsWith.Length + i] != endsWith[i]) return false;
+ }
+ return true;
+ }
+
+ // Math.Truncate принимает как decimal, так и doublе,
+ // из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов"
+ public static int Truncate(decimal number)
+ => Convert.ToInt32(Math.Truncate(number));
+
+ // сортирует в порядке возрастания элементы если это возможно, используя стандартный метод list.Sort();
+ public static T[] Sort(this T[] array)
+ {
+ var list = array.ToList();
+ list.Sort();
+ return list.ToArray();
+ }
+
+ // массив в лист
+ public static List ToList(this T[] input)
+ {
+ var list = new List();
+ list.AddRange(input);
+ return list;
+ }
+
+ // удаление нескольких элементов массива
+ public static T[] RemoveRange(this T[] input, int startIndex, int count)
+ {
+ List list = input.ToList();
+ list.RemoveRange(startIndex, count);
+ return list.ToArray();
+ }
+ public static T[] RemoveRange(this T[] input, int startIndex)
+ => input.RemoveRange(startIndex, input.Length - startIndex);
+
+ //
+ public static int ToInt(this T input)
+ => Convert.ToInt32(input);
+ }
+}
\ No newline at end of file
diff --git a/.old 5/updater/dtlib/TImer.cs b/.old 5/updater/dtlib/TImer.cs
new file mode 100644
index 0000000..6a571e4
--- /dev/null
+++ b/.old 5/updater/dtlib/TImer.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Threading;
+
+namespace updater
+{
+ //
+ // простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
+ //
+ public class Timer
+ {
+ Thread TimerThread;
+ bool Repeat;
+
+ // таймер сразу запускается
+ public Timer(bool repeat, int delay, Action method)
+ {
+ Repeat = repeat;
+ TimerThread = new Thread(() =>
+ {
+ do
+ {
+ Thread.Sleep(delay);
+ method();
+ } while (Repeat);
+ });
+ TimerThread.Start();
+ }
+
+ // завершение потока
+ public void Stop()
+ {
+ Repeat = false;
+ TimerThread.Abort();
+ }
+ }
+}
diff --git a/.old 5/updater/dtlib/XXHash.cs b/.old 5/updater/dtlib/XXHash.cs
new file mode 100644
index 0000000..7d92d5a
--- /dev/null
+++ b/.old 5/updater/dtlib/XXHash.cs
@@ -0,0 +1,180 @@
+using System;
+using System.Security.Cryptography;
+namespace updater
+{
+ //
+ // честно взятый с гитхаба алгоритм хеширования
+ // выдаёт хеш в виде массива четырёх байтов
+ //
+ sealed class XXHash32 : HashAlgorithm
+ {
+ private const uint PRIME32_1 = 2654435761U;
+ private const uint PRIME32_2 = 2246822519U;
+ private const uint PRIME32_3 = 3266489917U;
+ private const uint PRIME32_4 = 668265263U;
+ private const uint PRIME32_5 = 374761393U;
+ private static readonly Func FuncGetLittleEndianUInt32;
+ private static readonly Func FuncGetFinalHashUInt32;
+ private uint _Seed32;
+ private uint _ACC32_1;
+ private uint _ACC32_2;
+ private uint _ACC32_3;
+ private uint _ACC32_4;
+ private uint _Hash32;
+ private int _RemainingLength;
+ private long _TotalLength = 0;
+ private int _CurrentIndex;
+ private byte[] _CurrentArray;
+
+ static XXHash32()
+ {
+ if (BitConverter.IsLittleEndian)
+ {
+ FuncGetLittleEndianUInt32 = new Func((x, i) =>
+ {
+ unsafe
+ {
+ fixed (byte* array = x)
+ {
+ return *(uint*)(array + i);
+ }
+ }
+ });
+ FuncGetFinalHashUInt32 = new Func(i => (i & 0x000000FFU) << 24 | (i & 0x0000FF00U) << 8 | (i & 0x00FF0000U) >> 8 | (i & 0xFF000000U) >> 24);
+ }
+ else
+ {
+ FuncGetLittleEndianUInt32 = new Func((x, i) =>
+ {
+ unsafe
+ {
+ fixed (byte* array = x)
+ {
+ return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
+ }
+ }
+ });
+ FuncGetFinalHashUInt32 = new Func(i => i);
+ }
+ }
+
+ // Creates an instance of class by default seed(0).
+ //
+ public static new XXHash32 Create() => new XXHash32();
+
+ // Initializes a new instance of the class by default seed(0).
+ public XXHash32() => Initialize(0);
+
+ // Initializes a new instance of the class, and sets the to the specified value.
+ // Represent the seed to be used for xxHash32 computing.
+ public XXHash32(uint seed) => Initialize(seed);
+
+ // Gets the value of the computed hash code.
+ // Hash computation has not yet completed.
+ public uint HashUInt32 => State == 0 ? _Hash32 : throw new InvalidOperationException("Hash computation has not yet completed.");
+
+ // Gets or sets the value of seed used by xxHash32 algorithm.
+ // Hash computation has not yet completed.
+ public uint Seed
+ {
+ get => _Seed32;
+ set
+ {
+ if (value != _Seed32)
+ {
+ if (State != 0) throw new InvalidOperationException("Hash computation has not yet completed.");
+ _Seed32 = value;
+ Initialize();
+ }
+ }
+ }
+
+ // Initializes this instance for new hash computing.
+ public override void Initialize()
+ {
+ _ACC32_1 = _Seed32 + PRIME32_1 + PRIME32_2;
+ _ACC32_2 = _Seed32 + PRIME32_2;
+ _ACC32_3 = _Seed32 + 0;
+ _ACC32_4 = _Seed32 - PRIME32_1;
+ }
+
+ // Routes data written to the object into the hash algorithm for computing the hash.
+ // The input to compute the hash code for.
+ // The offset into the byte array from which to begin using data.
+ // The number of bytes in the byte array to use as data.
+ protected override void HashCore(byte[] array, int ibStart, int cbSize)
+ {
+ if (State != 1) State = 1;
+ var size = cbSize - ibStart;
+ _RemainingLength = size & 15;
+ if (cbSize >= 16)
+ {
+ var limit = size - _RemainingLength;
+ do
+ {
+ _ACC32_1 = Round32(_ACC32_1, FuncGetLittleEndianUInt32(array, ibStart));
+ ibStart += 4;
+ _ACC32_2 = Round32(_ACC32_2, FuncGetLittleEndianUInt32(array, ibStart));
+ ibStart += 4;
+ _ACC32_3 = Round32(_ACC32_3, FuncGetLittleEndianUInt32(array, ibStart));
+ ibStart += 4;
+ _ACC32_4 = Round32(_ACC32_4, FuncGetLittleEndianUInt32(array, ibStart));
+ ibStart += 4;
+ } while (ibStart < limit);
+ }
+ _TotalLength += cbSize;
+ if (_RemainingLength != 0)
+ {
+ _CurrentArray = array;
+ _CurrentIndex = ibStart;
+ }
+ }
+
+ // Finalizes the hash computation after the last data is processed by the cryptographic stream object.
+ // The computed hash code.
+ protected override byte[] HashFinal()
+ {
+ if (_TotalLength >= 16)
+ {
+ _Hash32 = RotateLeft32(_ACC32_1, 1) + RotateLeft32(_ACC32_2, 7) + RotateLeft32(_ACC32_3, 12) + RotateLeft32(_ACC32_4, 18);
+ }
+ else
+ {
+ _Hash32 = _Seed32 + PRIME32_5;
+ }
+ _Hash32 += (uint)_TotalLength;
+ while (_RemainingLength >= 4)
+ {
+ _Hash32 = RotateLeft32(_Hash32 + FuncGetLittleEndianUInt32(_CurrentArray, _CurrentIndex) * PRIME32_3, 17) * PRIME32_4;
+ _CurrentIndex += 4;
+ _RemainingLength -= 4;
+ }
+ unsafe
+ {
+ fixed (byte* arrayPtr = _CurrentArray)
+ {
+ while (_RemainingLength-- >= 1)
+ {
+ _Hash32 = RotateLeft32(_Hash32 + arrayPtr[_CurrentIndex++] * PRIME32_5, 11) * PRIME32_1;
+ }
+ }
+ }
+ _Hash32 = (_Hash32 ^ (_Hash32 >> 15)) * PRIME32_2;
+ _Hash32 = (_Hash32 ^ (_Hash32 >> 13)) * PRIME32_3;
+ _Hash32 ^= _Hash32 >> 16;
+ _TotalLength = State = 0;
+ return BitConverter.GetBytes(FuncGetFinalHashUInt32(_Hash32));
+ }
+
+ private static uint Round32(uint input, uint value) => RotateLeft32(input + (value * PRIME32_2), 13) * PRIME32_1;
+
+ private static uint RotateLeft32(uint value, int count) => (value << count) | (value >> (32 - count));
+
+ private void Initialize(uint seed)
+ {
+ HashSizeValue = 32;
+ _Seed32 = seed;
+ Initialize();
+ }
+ }
+}
diff --git a/.old 5/updater/updater.csproj b/.old 5/updater/updater.csproj
new file mode 100644
index 0000000..301f0c6
--- /dev/null
+++ b/.old 5/updater/updater.csproj
@@ -0,0 +1,82 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {4784D974-A342-4202-9430-90FE5AC00FC7}
+ Exe
+ updater
+ updater
+ v4.8
+ 512
+ true
+ true
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
+
+
+ AnyCPU
+ false
+ none
+ true
+ bin\
+ DEBUG;TRACE
+ prompt
+ 4
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ False
+ Microsoft .NET Framework 4.8 %28x86 и x64%29
+ true
+
+
+ False
+ .NET Framework 3.5 SP1
+ false
+
+
+
+
+ del /f /q updater.exe.config
+
+
\ No newline at end of file
diff --git a/.old 6/DTLib/Color.cs b/.old 6/DTLib/Color.cs
new file mode 100644
index 0000000..e451099
--- /dev/null
+++ b/.old 6/DTLib/Color.cs
@@ -0,0 +1,23 @@
+using System;
+
+namespace DTLib
+{
+ public class Color
+ {
+ public record RGBA(byte R, byte G, byte B, byte A)
+ {
+ public RGBA(byte[] arrayRGBA) : this(arrayRGBA[0], arrayRGBA[1], arrayRGBA[2], arrayRGBA[3])
+ {
+ if (arrayRGBA.Length != 4) throw new Exception("Color.RGBA(byte[] arrayRGBA) error: arrayRGBA.Length != 4\n");
+ }
+ }
+
+ public record RGB(byte R, byte G, byte B)
+ {
+ public RGB(byte[] arrayRGB) : this(arrayRGB[0], arrayRGB[1], arrayRGB[2])
+ {
+ if (arrayRGB.Length != 3) throw new Exception("Color.RGB(byte[] arrayRGB) error: arrayRGB.Length != 3\n");
+ }
+ }
+ }
+}
diff --git a/.old 6/DTLib/ColoredConsole.cs b/.old 6/DTLib/ColoredConsole.cs
new file mode 100644
index 0000000..d0f9a17
--- /dev/null
+++ b/.old 6/DTLib/ColoredConsole.cs
@@ -0,0 +1,73 @@
+using System;
+
+namespace DTLib
+{
+ //
+ // вывод и ввод цветного текста в консоли
+ // работает медленнее чем хотелось бы
+ //
+ public static class ColoredConsole
+ {
+ // парсит название цвета в ConsoleColor
+ public static ConsoleColor ParseColor(string color)
+ {
+ return color switch
+ {
+ //case "magneta":
+ "m" => ConsoleColor.Magenta,
+ //case "green":
+ "g" => ConsoleColor.Green,
+ //case "red":
+ "r" => ConsoleColor.Red,
+ //case "yellow":
+ "y" => ConsoleColor.Yellow,
+ //case "white":
+ "w" => ConsoleColor.White,
+ //case "blue":
+ "b" => ConsoleColor.Blue,
+ //case "cyan":
+ "c" => ConsoleColor.Cyan,
+ //case "gray":
+ "gray" => ConsoleColor.Gray,
+ //case "black":
+ "black" => ConsoleColor.Black,
+ _ => throw new Exception($"ColoredConsole.ParseColor({color}) error: incorrect color"),
+ };
+ }
+
+ // вывод цветного текста
+ public static void Write(params string[] input)
+ {
+ if (input.Length == 1)
+ {
+ if (Console.ForegroundColor != ConsoleColor.Gray) Console.ForegroundColor = ConsoleColor.Gray;
+ Console.Write(input[0]);
+ }
+ else if (input.Length % 2 == 0)
+ {
+ string str = "";
+ for (ushort i = 0; i < input.Length; i++)
+ {
+ var c = ParseColor(input[i]);
+ if (Console.ForegroundColor != c)
+ {
+ Console.Write(str);
+ Console.ForegroundColor = c;
+ str = "";
+ }
+ str += input[++i];
+ }
+ if (str != "") Console.Write(str);
+ }
+ else throw new Exception("ColoredConsole.Write() error: every text string must have color string before");
+ }
+
+ // ввод цветного текста
+ public static string Read(string color)
+ {
+ var c = ParseColor(color);
+ if (Console.ForegroundColor != c) Console.ForegroundColor = c;
+ return Console.ReadLine();
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 6/DTLib/CompressedArray.cs b/.old 6/DTLib/CompressedArray.cs
new file mode 100644
index 0000000..8b6b69e
--- /dev/null
+++ b/.old 6/DTLib/CompressedArray.cs
@@ -0,0 +1,72 @@
+using System;
+using System.Collections.Generic;
+using System.Threading;
+
+namespace DTLib
+{
+ public class CompressedArray
+ {
+ public class Array1D where T : IComparable
+ {
+ byte[] Description;
+ T[] Memory;
+
+ public Array1D() { }
+ public Array1D(T[] sourceArray)
+ {
+ CompressArray(sourceArray);
+ }
+
+ public void CompressArray(T[] sourceArray)
+ {
+ var listMem = new List();
+ var listDesc = new List();
+ T prevElement = sourceArray[0];
+ listMem.Add(sourceArray[0]);
+ listDesc.Add(1);
+ byte repeats = 1;
+ for (int i = 1; i < sourceArray.Length; i++)
+ {
+ if (prevElement.CompareTo(sourceArray[i]) == 0) repeats++;
+ else
+ {
+ listMem.Add(sourceArray[i]);
+ listDesc.Add(1);
+ if (repeats > 1)
+ {
+ listDesc[listDesc.Count - 2] = repeats;
+ repeats = 1;
+ }
+ }
+ prevElement = sourceArray[i];
+ }
+ Memory = listMem.ToArray();
+ Description = listDesc.ToArray();
+ ColoredConsole.Write("b", "listMem.Count: ", "c", listMem.Count.ToString(), "b", " listDesc.Count: ", "c", listDesc.Count + "\n");
+ for (short i = 0; i < listDesc.Count; i++)
+ {
+ ColoredConsole.Write("y", $"{Description[i]}:{Memory[i]}\n");
+ }
+ }
+
+ // блокирует обращение к памяти из нескольких потоков
+ Mutex storageUsing = new();
+
+ // возвращает элемент по индексу так, как если бы шло обращение к обычном массиву
+ public T GetElement(int index)
+ {
+ storageUsing.WaitOne();
+ T output = default;
+ int sum = 0;
+ for (int i = 0; i < Description.Length; i++)
+ {
+ if (sum < index) sum += Description[i];
+ else if (sum == index) output = Memory[i];
+ else output = Memory[i - 1];
+ }
+ storageUsing.ReleaseMutex();
+ return output;
+ }
+ }
+ }
+}
diff --git a/.old 6/DTLib/DTLib.csproj b/.old 6/DTLib/DTLib.csproj
new file mode 100644
index 0000000..e38372d
--- /dev/null
+++ b/.old 6/DTLib/DTLib.csproj
@@ -0,0 +1,55 @@
+
+
+
+
+ Debug
+ AnyCPU
+ {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}
+ Library
+ Properties
+ DTLib
+ DTLib
+ v4.8
+ 9.0
+ 512
+ true
+
+
+ none
+ true
+ bin\
+ TRACE
+ prompt
+ 4
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.old 6/DTLib/Dtsod.cs b/.old 6/DTLib/Dtsod.cs
new file mode 100644
index 0000000..8a3f66d
--- /dev/null
+++ b/.old 6/DTLib/Dtsod.cs
@@ -0,0 +1,174 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace DTLib
+{
+ //
+ // это как json но не совсем
+ //
+ public class Dtsod
+ {
+ string Text;
+ public Dictionary Values { get; }
+ public Dtsod(string text)
+ {
+ Text = text;
+ Values = Parse(text);
+ }
+
+ // выдаёт Exception
+ public dynamic this[string key]
+ {
+ get
+ {
+ if (TryGet(key, out dynamic value)) return value;
+ else throw new Exception($"Dtsod[{key}] key not found");
+ }
+ }
+
+ // не выдаёт KeyNotFoundException
+ public bool TryGet(string key, out dynamic value)
+ {
+ try
+ {
+ value = Values[key];
+ return true;
+ }
+ catch (KeyNotFoundException)
+ {
+ //PublicLog.Log("y", $"key {key} not found\n");
+ value = null;
+ return false;
+ }
+ }
+
+ public override string ToString() => Text;
+
+
+ Dictionary Parse(string text)
+ {
+ Dictionary output = new();
+ StringBuilder nameStrB = new();
+ StringBuilder valStrB = new();
+ dynamic value = null;
+ bool readValue = false;
+ bool readString = false;
+ bool readListElem = false;
+ bool isList = false;
+
+ dynamic StringToElse(string str)
+ {
+ if (readString) return str;
+ //PublicLog.Log("m", $"value: <{value}>\n");
+ // bool
+ if (str == "true") return true;
+ else if (str == "false") return false;
+ // double
+ else if (str.Contains(".")) return SimpleConverter.ToDouble(str);
+ // ushort, uint, ulong
+ else if (str.Length > 2 && str[str.Length - 2] == 'u')
+ return str[str.Length - 1] switch
+ {
+ 's' => SimpleConverter.ToUShort(str.Remove(str.Length - 2)),
+ 'i' => SimpleConverter.ToUInt(str.Remove(str.Length - 2)),
+ 'l' => SimpleConverter.ToULong(str.Remove(str.Length - 2)),
+ _ => throw new Exception($"ParseConfig() error: unknown data type "),
+ };
+ // short, int, long
+ else return str[str.Length - 1] switch
+ {
+ 's' => SimpleConverter.ToShort(str.Remove(str.Length - 1)),
+ 'l' => SimpleConverter.ToLong(str.Remove(str.Length - 1)),
+ _ => SimpleConverter.ToInt(str),
+ };
+ }
+
+ for (int i = 0; i < text.Length; i++)
+ {
+ switch (text[i])
+ {
+ case '{':
+ i++;
+ for (; text[i] != '}'; i++) valStrB.Append(text[i]);
+ value = Parse(valStrB.ToString());
+ valStrB.Clear();
+ break;
+ case '}':
+ throw new Exception("ParseConfig() error: unexpected '}' at " + i + "char");
+ case '<':
+ readString = true;
+ short balance = 1;
+ while (balance != 0)
+ {
+ i++;
+ if (text[i] == '>') balance--;
+ else if (text[i] == '<') balance++;
+ valStrB.Append(text[i]);
+ }
+ valStrB.Remove(valStrB.Length - 1, 1);
+ break;
+ case '"':
+ readString = true;
+ while (text[i] != '"' && text[i--] != '\\')
+ {
+ i++;
+ valStrB.Append(text[i]);
+ }
+ break;
+ case ':':
+ readValue = true;
+ break;
+ case ' ':
+ case '\t':
+ case '\r':
+ case '\n':
+ break;
+ case '[':
+ isList = true;
+ value = new List();
+ break;
+ case ',':
+ case ']':
+ if (isList) value.Add(StringToElse(valStrB.ToString()));
+ else throw new Exception($"unexpected {text[i]}");
+ valStrB.Clear();
+ break;
+ case ';':
+ // конвертация value в нужный тип данных
+ if (!isList) value = StringToElse(valStrB.ToString());
+ if (readListElem)
+ {
+ if (!output.ContainsKey(nameStrB.ToString())) output.Add(nameStrB.ToString(), new List());
+ output[nameStrB.ToString()].Add(value);
+ }
+ else output.Add(nameStrB.ToString(), value);
+ nameStrB.Clear();
+ valStrB.Clear();
+ value = null;
+ readValue = false;
+ readString = false;
+ readListElem = false;
+ isList = false;
+ break;
+ // коммент
+ case '#':
+ for (; i < text.Length && text[i] != '\n'; i++) ;
+ break;
+ // если $ перед названием параметра поставить, значение (value) добавится в лист с таким названием (nameStrB.ToString())
+ case '$':
+ if (nameStrB.ToString().Length != 0) throw new Exception("unexpected usage of '$' at char " + i.ToString());
+ readListElem = true;
+ break;
+ default:
+ if (readValue) valStrB.Append(text[i]);
+ else nameStrB.Append(text[i]);
+ break;
+ };
+ }
+ return output;
+ }
+
+
+ }
+}
diff --git a/.old 6/DTLib/FileWork.cs b/.old 6/DTLib/FileWork.cs
new file mode 100644
index 0000000..efdaa67
--- /dev/null
+++ b/.old 6/DTLib/FileWork.cs
@@ -0,0 +1,202 @@
+using System.Collections.Generic;
+using System.IO;
+
+namespace DTLib
+{
+ //
+ // методы для работы с файловой системой
+ //
+ public static class FileWork
+ {
+ // записывает текст в файл и закрывает файл
+ public static void Log(string logfile, string msg)
+ {
+ lock (new object())
+ {
+ if (logfile.Contains("\\")) DirCreate(logfile.Remove(logfile.LastIndexOf('\\')));
+ var st = File.Open(logfile, FileMode.Append);
+ var writer = new StreamWriter(st, SimpleConverter.UTF8);
+ writer.Write(msg);
+ writer.Close();
+ st.Close();
+ }
+ }
+
+ // создает папку если её не существует
+ public static void DirCreate(string dir)
+ {
+ if (!Directory.Exists(dir))
+ {
+ // проверяет существование папки, в которой нужно создать dir
+ if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
+ DirCreate(dir.Remove(dir.LastIndexOf('\\')));
+ Directory.CreateDirectory(dir);
+ }
+ }
+
+ // создаёт файл, сохдаёт папки из его пути
+ public static void FileCreate(string path)
+ {
+ if (!File.Exists(path))
+ {
+ if (path.Contains("\\")) DirCreate(path.Remove(path.LastIndexOf('\\')));
+ using var s = File.Create(path);
+ s.Close();
+ }
+ }
+
+ // чтение параметров из конфига
+ public static string ReadFromConfig(string configfile, string key)
+ {
+ lock (new object())
+ {
+ key += ": ";
+ using var reader = new StreamReader(configfile);
+ while (!reader.EndOfStream)
+ {
+ string st = reader.ReadLine();
+ if (st.StartsWith(key))
+ {
+ string value = "";
+ for (int i = key.Length; i < st.Length; i++)
+ {
+ if (st[i] == '#') return value;
+ if (st[i] == '%')
+ {
+ bool stop = false;
+ string placeholder = "";
+ i++;
+ while (!stop)
+ {
+ if (st[i] == '%')
+ {
+ stop = true;
+ value += ReadFromConfig(configfile, placeholder);
+ }
+ else
+ {
+ placeholder += st[i];
+ i++;
+ }
+ }
+ }
+ else value += st[i];
+ }
+ reader.Close();
+ //if (value == "") throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
+ return value;
+ }
+ }
+ reader.Close();
+ throw new System.Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
+ }
+ }
+
+ // копирует все файли и папки
+ public static void DirCopy(string source_dir, string new_dir, bool Override)
+ {
+ DirCreate(new_dir);
+ List subdirs = new List();
+ List files = GetAllFiles(source_dir, ref subdirs);
+ for (int i = 0; i < subdirs.Count; i++)
+ {
+ DirCreate(subdirs[i].Replace(source_dir, new_dir));
+ }
+ for (int i = 0; i < files.Count; i++)
+ {
+ string f = files[i].Replace(source_dir, new_dir);
+ File.Copy(files[i], f, Override);
+ //PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
+ }
+ }
+
+ // копирует все файли и папки и выдаёт список конфликтующих файлов
+ public static void DirCopy(string source_dir, string new_dir, bool owerwrite, out List conflicts)
+ {
+ conflicts = new List();
+ var subdirs = new List();
+ var files = GetAllFiles(source_dir, ref subdirs);
+ DirCreate(new_dir);
+ for (int i = 0; i < subdirs.Count; i++)
+ {
+ DirCreate(subdirs[i].Replace(source_dir, new_dir));
+ }
+ for (int i = 0; i < files.Count; i++)
+ {
+ string newfile = files[i].Replace(source_dir, new_dir);
+ if (File.Exists(newfile)) conflicts.Add(newfile);
+ File.Copy(files[i], newfile, owerwrite);
+ //PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
+ }
+ }
+
+ // выдает список всех файлов
+ public static List GetAllFiles(string dir)
+ {
+ List all_files = new List();
+ string[] cur_files = Directory.GetFiles(dir);
+ for (int i = 0; i < cur_files.Length; i++)
+ {
+ all_files.Add(cur_files[i]);
+ //PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
+ }
+ string[] cur_subdirs = Directory.GetDirectories(dir);
+ for (int i = 0; i < cur_subdirs.Length; i++)
+ {
+ //PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
+ all_files.AddRange(GetAllFiles(cur_subdirs[i]));
+ }
+ return all_files;
+ }
+
+ // выдает список всех файлов и подпапок в папке
+ public static List GetAllFiles(string dir, ref List all_subdirs)
+ {
+ List all_files = new List();
+ string[] cur_files = Directory.GetFiles(dir);
+ for (int i = 0; i < cur_files.Length; i++)
+ {
+ all_files.Add(cur_files[i]);
+ //PublicLog.Log(new string[] { "b", "file found: <", "c", cur_files[i], "b", ">\n" });
+ }
+ string[] cur_subdirs = Directory.GetDirectories(dir);
+ for (int i = 0; i < cur_subdirs.Length; i++)
+ {
+ all_subdirs.Add(cur_subdirs[i]);
+ //PublicLog.Log(new string[] { "b", "subdir found: <", "c", cur_subdirs[i], "b", ">\n" });
+ all_files.AddRange(GetAllFiles(cur_subdirs[i], ref all_subdirs));
+ }
+ return all_files;
+ }
+
+ // удаляет папку со всеми подпапками и файлами
+ public static void DirDelete(string dir)
+ {
+ var subdirs = new List();
+ var files = GetAllFiles(dir, ref subdirs);
+ for (int i = 0; i < files.Count; i++)
+ File.Delete(files[i]);
+ for (int i = subdirs.Count - 1; i >= 0; i--)
+ Directory.Delete(subdirs[i]);
+ Directory.Delete(dir);
+ }
+
+ // вычисляет и записывает в manifest.dtsod хеши файлов из files_list.dtsod
+ public static void CreateManifest(string dir)
+ {
+ if (!dir.EndsWith("\\")) dir += "\\";
+ var dtsod = new Dtsod(File.ReadAllText(dir + "files_list.dtsod"));
+ System.Text.StringBuilder manifestBuilder = new();
+ Hasher hasher = new();
+ for (int i = 0; i < dtsod["files"].Count; i++)
+ {
+ manifestBuilder.Append(dtsod["files"][i]);
+ manifestBuilder.Append(": \"");
+ byte[] hash = hasher.HashFile(dir + dtsod["files"][i]);
+ manifestBuilder.Append(hash.HashToString());
+ manifestBuilder.Append("\";\n");
+ }
+ File.WriteAllText(dir + "manifest.dtsod", manifestBuilder.ToString());
+ }
+ }
+}
diff --git a/.old 6/DTLib/Hasher.cs b/.old 6/DTLib/Hasher.cs
new file mode 100644
index 0000000..05b3c87
--- /dev/null
+++ b/.old 6/DTLib/Hasher.cs
@@ -0,0 +1,61 @@
+using System.Collections.Generic;
+using System.IO;
+using System.Security.Cryptography;
+
+namespace DTLib
+{
+ //
+ // хеширует массивы байтов алшоритмом SHA256 и файлы алгоримом XXHash32
+ //
+ public class Hasher
+ {
+ readonly HashAlgorithm sha256 = SHA256.Create();
+ readonly HashAlgorithm xxh32 = XXHash32.Create();
+
+ public Hasher() { }
+
+ // хеш массива
+ public byte[] Hash(byte[] input)
+ => sha256.ComputeHash(input);
+
+ // хеш из двух массивов
+ public byte[] Hash(byte[] input, byte[] salt)
+ {
+ List rez = new List();
+ rez.AddRange(input);
+ rez.AddRange(salt);
+ return sha256.ComputeHash(rez.ToArray());
+ }
+
+ // хеш двух массивов зацикленный
+ public byte[] HashCycled(byte[] input, byte[] salt, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = Hash(input, salt);
+ }
+ return input;
+ }
+ // хеш зацикленный
+ public byte[] HashCycled(byte[] input, ushort cycles)
+ {
+ for (uint i = 0; i < cycles; i++)
+ {
+ input = Hash(input);
+ }
+ return input;
+ }
+
+ // хеш файла
+ public byte[] HashFile(string filename)
+ {
+ using var fileStream = File.OpenRead(filename);
+ //var then = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
+ var hash = xxh32.ComputeHash(fileStream);
+ //var now = DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second;
+ //PublicLog.Log($"xxh32 hash: {hash.HashToString()} time: {now - then}\n");
+ fileStream.Close();
+ return hash;
+ }
+ }
+}
diff --git a/.old 6/DTLib/NetWork.cs b/.old 6/DTLib/NetWork.cs
new file mode 100644
index 0000000..5da9ee8
--- /dev/null
+++ b/.old 6/DTLib/NetWork.cs
@@ -0,0 +1,180 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+using static DTLib.PublicLog;
+
+namespace DTLib
+{
+ //
+ // весь униврсальный неткод тут
+ // большинство методов предназначены для работы с TCP сокетами (Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
+ //
+ public static class NetWork
+ {
+ // скачивание файла с фтп сервера
+ public static void FtpDownload(string address, string login, string password, string outfile)
+ {
+ try
+ {
+ // debug
+ Log(new string[] { "y", "file on server: <", "c", address, "y", ">\nfile on client: <", "c", outfile, "y", ">\n" });
+ // создание запроса
+ // "ftp://m1net.keenetic.pro:20000/" + @infile
+ FtpWebRequest request = (FtpWebRequest)WebRequest.Create(address);
+ request.Credentials = new NetworkCredential(login, password);
+ request.Method = WebRequestMethods.Ftp.DownloadFile;
+ // получение ответа на запрос
+ FtpWebResponse response = (FtpWebResponse)request.GetResponse();
+ Stream responseStream = response.GetResponseStream();
+ FileStream fs = new FileStream(@Directory.GetCurrentDirectory() + '\\' + @outfile, FileMode.Create);
+ byte[] buffer = new byte[64];
+ int size = 0;
+
+ while ((size = responseStream.Read(buffer, 0, buffer.Length)) > 0)
+ fs.Write(buffer, 0, size);
+ fs.Close();
+ response.Close();
+ }
+ catch (WebException e) { throw new Exception("ftp error:\n" + ((FtpWebResponse)e.Response).StatusDescription + '\n'); }
+ }
+
+ // пингует айпи с помощью встроенной в винду проги, возвращает задержку
+ public static string PingIP(string address)
+ {
+ Process proc = new Process();
+ proc.StartInfo.FileName = "cmd.exe";
+ proc.StartInfo.Arguments = "/c @echo off & chcp 65001 >nul & ping -n 5 " + address;
+ proc.StartInfo.CreateNoWindow = true;
+ proc.StartInfo.UseShellExecute = false;
+ proc.StartInfo.RedirectStandardOutput = true;
+ proc.Start();
+ var outStream = proc.StandardOutput;
+ var rezult = outStream.ReadToEnd();
+ rezult = rezult.Remove(0, rezult.LastIndexOf('=') + 2);
+ return rezult.Remove(rezult.Length - 4);
+ }
+
+ // скачивает файл с помощью FSP протокола
+ public static void FSP_Download(this Socket mainSocket, string filePath_server, string filePath_client)
+ {
+ FileWork.FileCreate(filePath_client);
+ using var fileStream = File.OpenWrite(filePath_client);
+ mainSocket.SendPackage("requesting file download".ToBytes());
+ Log("c", $"requesting file download: {filePath_server}\n");
+ mainSocket.SendPackage(filePath_server.ToBytes());
+ var fileSize = Convert.ToUInt32(mainSocket.GetPackage().ToStr());
+ var hashstr = mainSocket.GetPackage().HashToString();
+ mainSocket.SendPackage("ready".ToBytes());
+ int packagesCount = 0;
+ byte[] buffer = new byte[5120];
+ int fullPackagesCount = SimpleConverter.Truncate(fileSize / buffer.Length);
+ // рассчёт скорости
+ int seconds = 0;
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // получение файла
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ buffer = mainSocket.GetPackage();
+ fileStream.Write(buffer, 0, buffer.Length);
+ fileStream.Flush();
+ }
+ speedCounter.Stop();
+ // получение остатка
+ mainSocket.SendPackage("remain request".ToBytes());
+ buffer = mainSocket.GetPackage();
+ fileStream.Write(buffer, 0, buffer.Length);
+ fileStream.Flush();
+ fileStream.Close();
+ Log(new string[] { "g", $" downloaded {packagesCount * 5120 + buffer.Length} of {fileSize} bytes\n" });
+
+ }
+
+ // отдаёт файл с помощью FSP протокола
+ public static void FSP_Upload(this Socket mainSocket, string filePath)
+ {
+ using var fileStream = File.OpenRead(filePath);
+ Log("b", $"uploading file {filePath}\n");
+ var fileSize = new FileInfo(filePath).Length;
+ var fileHash = new Hasher().HashFile(filePath);
+ mainSocket.SendPackage(fileSize.ToString().ToBytes());
+ mainSocket.SendPackage(fileHash);
+ if (mainSocket.GetPackage().ToStr() != "ready") throw new Exception("user socket isn't ready");
+ byte[] buffer = new byte[5120];
+ var hashstr = fileHash.HashToString();
+ int packagesCount = 0;
+ int seconds = 0;
+ // рассчёт скорости
+ var speedCounter = new Timer(true, 1000, () =>
+ {
+ seconds++;
+ Log("c", $"speed= {packagesCount * buffer.Length / (seconds * 1000)} kb/s\n");
+ });
+ // отправка файла
+ int fullPackagesCount = SimpleConverter.Truncate(fileSize / buffer.Length);
+ for (; packagesCount < fullPackagesCount; packagesCount++)
+ {
+ fileStream.Read(buffer, 0, buffer.Length);
+ mainSocket.SendPackage(buffer);
+ }
+ speedCounter.Stop();
+ // досылка остатка
+ if (mainSocket.GetPackage().ToStr() != "remain request")
+ throw new Exception("FSP_Upload() error: didn't get remain request");
+ buffer = new byte[Convert.ToInt32(fileSize - fileStream.Position)];
+ fileStream.Read(buffer, 0, buffer.Length);
+ mainSocket.SendPackage(buffer);
+ fileStream.Close();
+ Log(new string[] { "g", $" uploaded {packagesCount * 5120 + buffer.Length} of {fileSize} bytes\n" });
+
+ }
+
+ // ждёт пакет заданного размера с заданным началом и концом
+ public static byte[] GetPackage(this Socket socket)
+ {
+ int packageSize = 0;
+ byte[] data = new byte[2];
+ // цикл выполняется пока не пройдёт 1000 мс
+ for (ushort s = 0; s < 200; s += 1)
+ {
+ if (packageSize == 0 && socket.Available >= 2)
+ {
+ socket.Receive(data, data.Length, 0);
+ packageSize = data.BytesToInt();
+
+ }
+ if (packageSize != 0 && socket.Available >= packageSize)
+ {
+ data = new byte[packageSize];
+ socket.Receive(data, data.Length, 0);
+ return data;
+ }
+ else Thread.Sleep(5);
+ }
+ throw new Exception($"GetPackage() error: timeout. socket.Available={socket.Available}\n");
+ }
+
+ // отправляет пакет заданного размера, добавля в конец нули если длина data меньше чем packageSize
+ public static void SendPackage(this Socket socket, byte[] data)
+ {
+ if (data.Length > 65536) throw new Exception($"SendPackage() error: package is too big ({data.Length} bytes)");
+ if (data.Length == 0) throw new Exception($"SendPackage() error: package has zero size");
+ var list = new List();
+ byte[] packageSize = data.Length.IntToBytes();
+ if (packageSize.Length == 1) list.Add(0);
+ list.AddRange(packageSize);
+ list.AddRange(data);
+ socket.Send(list.ToArray());
+ }
+
+ // получает с сайта публичный ip
+ public static string GetPublicIP() => new WebClient().DownloadString("https://ipv4bot.whatismyipaddress.com/");
+ }
+}
diff --git a/.old 6/DTLib/Properties/AssemblyInfo.cs b/.old 6/DTLib/Properties/AssemblyInfo.cs
new file mode 100644
index 0000000..c0201c5
--- /dev/null
+++ b/.old 6/DTLib/Properties/AssemblyInfo.cs
@@ -0,0 +1,35 @@
+using System.Reflection;
+using System.Runtime.InteropServices;
+
+// Общие сведения об этой сборке предоставляются следующим набором
+// набора атрибутов. Измените значения этих атрибутов для изменения сведений,
+// связанные со сборкой.
+[assembly: AssemblyTitle("DTLib")]
+[assembly: AssemblyDescription("")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("DTLib")]
+[assembly: AssemblyCopyright("Copyright © 2021")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми
+// для компонентов COM. Если необходимо обратиться к типу в этой сборке через
+// COM, задайте атрибуту ComVisible значение TRUE для этого типа.
+[assembly: ComVisible(false)]
+
+// Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM
+[assembly: Guid("ce793497-2d5c-42d8-b311-e9b32af9cdfb")]
+
+// Сведения о версии сборки состоят из указанных ниже четырех значений:
+//
+// Основной номер версии
+// Дополнительный номер версии
+// Номер сборки
+// Редакция
+//
+// Можно задать все значения или принять номера сборки и редакции по умолчанию
+// используя "*", как показано ниже:
+// [assembly: AssemblyVersion("1.0.*")]
+[assembly: AssemblyVersion("1.0.0.0")]
+[assembly: AssemblyFileVersion("1.0.0.0")]
diff --git a/.old 6/DTLib/PublicLog.cs b/.old 6/DTLib/PublicLog.cs
new file mode 100644
index 0000000..5b38768
--- /dev/null
+++ b/.old 6/DTLib/PublicLog.cs
@@ -0,0 +1,16 @@
+namespace DTLib
+{
+ //
+ // вывод логов со всех классов в библиотеке
+ //
+ public static class PublicLog
+ {
+ public delegate void LogDelegate(string[] msg);
+ // вот к этому объекту подключайте методы для вывода логов
+ public static LogDelegate LogDel;
+
+ // этот метод вызывается в библиотеке
+ public static void Log(params string[] msg)
+ => LogDel(msg);
+ }
+}
diff --git a/.old 6/DTLib/SecureRandom.cs b/.old 6/DTLib/SecureRandom.cs
new file mode 100644
index 0000000..f00bac9
--- /dev/null
+++ b/.old 6/DTLib/SecureRandom.cs
@@ -0,0 +1,37 @@
+using System.Security.Cryptography;
+
+namespace DTLib
+{
+ //
+ // Вычисление псевдослучайного числа из множества параметров.
+ // Работает медленнее чем класс System.Random, но выдаёт более случайные значения
+ //
+ public class SecureRandom
+ {
+ private RNGCryptoServiceProvider crypt = new();
+
+ // получение массива случайных байтов
+ public byte[] GenBytes(uint length)
+ {
+ byte[] output = new byte[length];
+ crypt.GetNonZeroBytes(output);
+ return output;
+ }
+
+ // получение случайного числа от 0 до 2147483647
+ /*public int NextInt(uint from, int to)
+ {
+ int output = 0;
+ int rez = 0;
+ while (true)
+ {
+ rez = output * 10 + NextBytes(1)[0];
+ if (rez < to && rez > from)
+ {
+ output = rez;
+ return output;
+ }
+ }
+ }*/
+ }
+}
diff --git a/.old 6/DTLib/SimpleConverter.cs b/.old 6/DTLib/SimpleConverter.cs
new file mode 100644
index 0000000..7184635
--- /dev/null
+++ b/.old 6/DTLib/SimpleConverter.cs
@@ -0,0 +1,161 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+
+namespace DTLib
+{
+ //
+ // содержит методы расширения для различных операций и преобразований
+ //
+ public static class SimpleConverter
+ {
+ public static Encoding UTF8 = new UTF8Encoding(false);
+ // байты в кодировке UTF8 в строку
+ public static string ToStr(this byte[] bytes) => UTF8.GetString(bytes);
+ public static string ToStr(this List bytes) => UTF8.GetString(bytes.ToArray());
+
+ // хеш в виде массива байт в строку (хеш изначально не в кодировке UTF8, так что метод выше не работает с ним)
+ public static string HashToString(this byte[] hash)
+ {
+ var builder = new StringBuilder();
+ for (int i = 0; i < hash.Length; i++)
+ {
+ builder.Append(hash[i].ToString("x2"));
+ }
+ return builder.ToString();
+ }
+
+ // строку в байты
+ public static byte[] ToBytes(this string str) => UTF8.GetBytes(str);
+
+ // эти методы работают как надо, в отличии от стандартных, которые иногда дуркуют
+ public static bool StartsWith(this byte[] source, byte[] startsWith)
+ {
+ for (int i = 0; i < startsWith.Length; i++)
+ {
+ if (source[i] != startsWith[i]) return false;
+ }
+ return true;
+ }
+
+ public static bool EndsWith(this byte[] source, byte[] endsWith)
+ {
+ for (int i = 0; i < endsWith.Length; i++)
+ {
+ if (source[source.Length - endsWith.Length + i] != endsWith[i]) return false;
+ }
+ return true;
+ }
+
+ // Math.Truncate принимает как decimal, так и doublе,
+ // из-за чего вызов метода так: Math.Truncate(10/3) выдаст ошибку "неоднозначный вызов"
+ public static int Truncate(this double number) => Convert.ToInt32(Math.Truncate(number));
+
+ // сортирует в порядке возрастания элементы если это возможно, используя стандартный метод list.Sort();
+ public static T[] Sort(this T[] array)
+ {
+ var list = array.ToList();
+ list.Sort();
+ return list.ToArray();
+ }
+
+ // массив в лист
+ public static List ToList(this T[] input)
+ {
+ var list = new List();
+ list.AddRange(input);
+ return list;
+ }
+
+ // удаление нескольких элементов массива
+ public static T[] RemoveRange(this T[] input, int startIndex, int count)
+ {
+ List list = input.ToList();
+ list.RemoveRange(startIndex, count);
+ return list.ToArray();
+ }
+ public static T[] RemoveRange(this T[] input, int startIndex) => input.RemoveRange(startIndex, input.Length - startIndex);
+
+ // метод как у листов
+ public static bool Contains(this T[] array, T value)
+ {
+ for (int i = 0; i < array.Length; i++)
+ if (array[i].Equals(value)) return true;
+ return false;
+ }
+
+ // конвертирует массив в строку
+ public static string MergeToString(this T[] array, string separator)
+ {
+ var b = new StringBuilder();
+ for (int i = 0; i < array.Length; i++)
+ {
+ b.Append(array[i].ToString());
+ b.Append(separator);
+ }
+ return b.ToString();
+ }
+ public static string MergeToString(this List list, string separator)
+ {
+ var b = new StringBuilder();
+ b.Append(list[0].ToString());
+ for (int i = 1; i < list.Count; i++)
+ {
+ b.Append(separator);
+ b.Append(list[i].ToString());
+ }
+ return b.ToString();
+ }
+
+ // сокращение конвертации
+ public static int ToInt(this T input) => Convert.ToInt32(input);
+ public static uint ToUInt(this T input) => Convert.ToUInt32(input);
+ public static long ToLong(this T input) => Convert.ToInt64(input);
+ public static ulong ToULong(this T input) => Convert.ToUInt64(input);
+ public static short ToShort(this T input) => Convert.ToInt16(input);
+ public static ushort ToUShort(this T input) => Convert.ToUInt16(input);
+ public static double ToDouble(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture);
+ public static byte ToByte(this T input) => Convert.ToByte(input);
+ public static sbyte ToSByte(this T input) => Convert.ToSByte(input);
+ public static bool ToBool(this T input) => Convert.ToBoolean(input);
+
+ public static string AutoBuild(params object[] parts)
+ {
+ var builder = new StringBuilder();
+ for (int i = 0; i < parts.Length; i++)
+ builder.Append(parts[i]);
+ return builder.ToString();
+ }
+
+ public static int BytesToInt(this byte[] bytes)
+ {
+ int output = 0;
+ for (ushort i = 0; i < bytes.Length; i++) output = output * 256 + bytes[i];
+ return output;
+ }
+
+ public static byte[] IntToBytes(this int num)
+ {
+ List output = new();
+ while (num != 0)
+ {
+ output.Add(ToByte(num % 256));
+ num = Truncate(num / 256);
+ }
+ output.Reverse();
+ return output.ToArray();
+ }
+
+ public static string ToString(this IEnumerable collection, string separator)
+ {
+ StringBuilder builder = new();
+ foreach (T elem in collection)
+ {
+ builder.Append(elem.ToString());
+ builder.Append(separator);
+ }
+ builder.Remove(builder.Length - separator.Length, separator.Length);
+ return builder.ToString();
+ }
+ }
+}
\ No newline at end of file
diff --git a/.old 6/DTLib/TImer.cs b/.old 6/DTLib/TImer.cs
new file mode 100644
index 0000000..cb154ec
--- /dev/null
+++ b/.old 6/DTLib/TImer.cs
@@ -0,0 +1,36 @@
+using System;
+using System.Threading;
+
+namespace DTLib
+{
+ //
+ // простой и понятный класс для выполнения каких-либо действий в отдельном потоке раз в некоторое время
+ //
+ public class Timer
+ {
+ Thread TimerThread;
+ bool Repeat;
+
+ // таймер сразу запускается
+ public Timer(bool repeat, int delay, Action method)
+ {
+ Repeat = repeat;
+ TimerThread = new Thread(() =>
+ {
+ do
+ {
+ Thread.Sleep(delay);
+ method();
+ } while (Repeat);
+ });
+ TimerThread.Start();
+ }
+
+ // завершение потока
+ public void Stop()
+ {
+ Repeat = false;
+ TimerThread.Abort();
+ }
+ }
+}
diff --git a/.old 6/DTLib/XXHash.cs b/.old 6/DTLib/XXHash.cs
new file mode 100644
index 0000000..08c7c24
--- /dev/null
+++ b/.old 6/DTLib/XXHash.cs
@@ -0,0 +1,180 @@
+using System;
+using System.Security.Cryptography;
+namespace DTLib
+{
+ //
+ // честно взятый с гитхаба алгоритм хеширования
+ // выдаёт хеш в виде массива четырёх байтов
+ //
+ sealed class XXHash32 : HashAlgorithm
+ {
+ private const uint PRIME32_1 = 2654435761U;
+ private const uint PRIME32_2 = 2246822519U;
+ private const uint PRIME32_3 = 3266489917U;
+ private const uint PRIME32_4 = 668265263U;
+ private const uint PRIME32_5 = 374761393U;
+ private static readonly Func FuncGetLittleEndianUInt32;
+ private static readonly Func FuncGetFinalHashUInt32;
+ private uint _Seed32;
+ private uint _ACC32_1;
+ private uint _ACC32_2;
+ private uint _ACC32_3;
+ private uint _ACC32_4;
+ private uint _Hash32;
+ private int _RemainingLength;
+ private long _TotalLength = 0;
+ private int _CurrentIndex;
+ private byte[] _CurrentArray;
+
+ static XXHash32()
+ {
+ if (BitConverter.IsLittleEndian)
+ {
+ FuncGetLittleEndianUInt32 = new Func((x, i) =>
+ {
+ unsafe
+ {
+ fixed (byte* array = x)
+ {
+ return *(uint*)(array + i);
+ }
+ }
+ });
+ FuncGetFinalHashUInt32 = new Func(i => (i & 0x000000FFU) << 24 | (i & 0x0000FF00U) << 8 | (i & 0x00FF0000U) >> 8 | (i & 0xFF000000U) >> 24);
+ }
+ else
+ {
+ FuncGetLittleEndianUInt32 = new Func((x, i) =>
+ {
+ unsafe
+ {
+ fixed (byte* array = x)
+ {
+ return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
+ }
+ }
+ });
+ FuncGetFinalHashUInt32 = new Func(i => i);
+ }
+ }
+
+ // Creates an instance of