diff --git a/.gitignore b/.gitignore index 9491a2f..8d8b248 100644 --- a/.gitignore +++ b/.gitignore @@ -97,6 +97,7 @@ StyleCopReport.xml *.pidb *.svclog *.scc +*.editorconfig # Chutzpah Test files _Chutzpah* diff --git a/DTLib/Color.cs b/DTLib/Color.cs new file mode 100644 index 0000000..db09e38 --- /dev/null +++ b/DTLib/Color.cs @@ -0,0 +1,24 @@ +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/DTLib/ColoredConsole.cs b/DTLib/ColoredConsole.cs new file mode 100644 index 0000000..d0f9a17 --- /dev/null +++ b/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/DTLib/CompressedArray.cs b/DTLib/CompressedArray.cs new file mode 100644 index 0000000..8b6b69e --- /dev/null +++ b/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/DTLib/DTLib.csproj b/DTLib/DTLib.csproj new file mode 100644 index 0000000..043db00 --- /dev/null +++ b/DTLib/DTLib.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {CE793497-2D5C-42D8-B311-E9B32AF9CDFB} + Library + Properties + DTLib + DTLib + v4.8 + 9.0 + 512 + true + + + none + true + bin\ + TRACE + prompt + 4 + true + + + + + + + + + + + + + + + + + + + + + + + + + + + xcopy C:\projects\c#\dtlauncher\DTLib C:\projects\c#\DTLib /E /H | echo All + + \ No newline at end of file diff --git a/DTLib/Dtsod.cs b/DTLib/Dtsod.cs new file mode 100644 index 0000000..1539fec --- /dev/null +++ b/DTLib/Dtsod.cs @@ -0,0 +1,175 @@ +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) + { + //PublicLog.Log("m", $"StringToElse({str})\n"); + if (readString) return str; + // 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; + i++; + while (text[i] != '"' || text[i - 1] == '\\') + { + valStrB.Append(text[i]); + 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]}> at text[{i}]"); + valStrB.Clear(); + break; + case ';': + // конвертация value в нужный тип данных + if (!isList && valStrB.Length > 0) 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/DTLib/FileWork.cs b/DTLib/FileWork.cs new file mode 100644 index 0000000..65b3228 --- /dev/null +++ b/DTLib/FileWork.cs @@ -0,0 +1,184 @@ +using System.Collections.Generic; +using System.IO; + +namespace DTLib +{ + // + // методы для работы с файловой системой + // + public static class FileWork + { + // записывает текст в файл и закрывает файл + public static void Log(string logfile, string msg) + { + lock (new object()) + { + FileCreate(logfile); + 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); + } + } +} diff --git a/DTLib/Hasher.cs b/DTLib/Hasher.cs new file mode 100644 index 0000000..05b3c87 --- /dev/null +++ b/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/DTLib/NetWork.cs b/DTLib/NetWork.cs new file mode 100644 index 0000000..b560f96 --- /dev/null +++ b/DTLib/NetWork.cs @@ -0,0 +1,190 @@ +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) + { + Log("g", $"requesting file download: {filePath_server}\n"); + mainSocket.SendPackage("requesting file download".ToBytes()); + mainSocket.SendPackage(filePath_server.ToBytes()); + FSP_Download(mainSocket, filePath_client); + } + + public static void FSP_Download(this Socket mainSocket, string filePath_client) + { + FileWork.FileCreate(filePath_client); + using var fileStream = File.OpenWrite(filePath_client); + 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(); + // получение остатка + if ((fileSize - fileStream.Position) > 0) + { + 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) + { + Log("b", $"uploading file {filePath}\n"); + using var fileStream = File.OpenRead(filePath); + 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 ((fileSize - fileStream.Position) > 0) + { + if (mainSocket.GetPackage().ToStr() != "remain request") throw new Exception("FSP_Upload() error: didn't get remain request"); + buffer = new byte[(fileSize - fileStream.Position).ToInt()]; + 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/DTLib/Properties/AssemblyInfo.cs b/DTLib/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..c0201c5 --- /dev/null +++ b/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/DTLib/PublicLog.cs b/DTLib/PublicLog.cs new file mode 100644 index 0000000..5b38768 --- /dev/null +++ b/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/DTLib/SecureRandom.cs b/DTLib/SecureRandom.cs new file mode 100644 index 0000000..f00bac9 --- /dev/null +++ b/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/DTLib/SimpleConverter.cs b/DTLib/SimpleConverter.cs new file mode 100644 index 0000000..4aacf9c --- /dev/null +++ b/DTLib/SimpleConverter.cs @@ -0,0 +1,162 @@ +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 T number) => Math.Truncate(number.ToDouble()).ToInt(); + + // сортирует в порядке возрастания элементы если это возможно, используя стандартный метод 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/DTLib/TImer.cs b/DTLib/TImer.cs new file mode 100644 index 0000000..cb154ec --- /dev/null +++ b/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/DTLib/XXHash.cs b/DTLib/XXHash.cs new file mode 100644 index 0000000..08c7c24 --- /dev/null +++ b/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/DTLib/cs9somefix.cs b/DTLib/cs9somefix.cs new file mode 100644 index 0000000..b5c71f9 --- /dev/null +++ b/DTLib/cs9somefix.cs @@ -0,0 +1,8 @@ +// включает init и record из c# 9.0 +using System.ComponentModel; + +namespace System.Runtime.CompilerServices +{ + [EditorBrowsable(EditorBrowsableState.Never)] + public class IsExternalInit { } +} diff --git a/dtlauncher-client-win/ProgramLabel.xaml.cs b/dtlauncher-client-win/ProgramLabel.xaml.cs index 42cdd16..d5e8263 100644 --- a/dtlauncher-client-win/ProgramLabel.xaml.cs +++ b/dtlauncher-client-win/ProgramLabel.xaml.cs @@ -56,12 +56,12 @@ namespace dtlauncher_client_win Window = window; Number = number; descriptor = new(File.ReadAllText(descriptorFile)); - launchinfo = new(File.ReadAllText("launchinfo\\" + descriptor["launchinfo"])); + launchinfo = new(File.ReadAllText("launchinfo\\" + descriptor["id"])); FontSize = 14; Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240)); Text = descriptor["name"]; NameLabel.Content = descriptor["name"]; - IconImage.Source = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\icons\\" + descriptor["icon"], UriKind.Absolute)); + IconImage.Source = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\icons\\" + descriptor["id"], UriKind.Absolute)); //background = Directory.GetCurrentDirectory() + "\\descriptors\\" + descriptor["background"]; //installScript = descriptor["script"]; //installDir = descriptor["installdir"]; @@ -90,21 +90,29 @@ namespace dtlauncher_client_win FontSize = 13; Window.NameLabel.Content = Text; Window.DescriptionBox.Text = descriptor["description"]; - Window.BackgroundImage.Source = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\backgrounds\\" + descriptor["background"], UriKind.Absolute)); + Window.BackgroundImage.Source = new BitmapImage(new Uri(Directory.GetCurrentDirectory() + "\\backgrounds\\" + descriptor["id"], UriKind.Absolute)); Window.Launch = () => { - Window.Log($"launching file <{launchinfo["launchfile"]}>\n"); - Process.Start(launchinfo["launchfile"]); + switch (descriptor["id"]) + { + case "anarx_1.12": + + break; + default: + Window.Log($"launching file <{launchinfo["launchfile"]}>\n"); + Process.Start(launchinfo["launchfile"]); + break; + } }; Window.Install = () => { - Window.Log($"launching installation script <{descriptor["installscript"]}>\n"); + Window.Log($"launching installation script <{descriptor["id"]}>\n"); var scriptrunner = new DTScript.ScriptRunner { debug = false, mainSocket = Window.mainSocket }; - scriptrunner.RunScriptFile("installscripts\\" + descriptor["installscript"]); + scriptrunner.RunScriptFile("installscripts\\" + descriptor["id"]); }; } catch (Exception ex) diff --git a/dtlauncher-client-win/client.dtsod b/dtlauncher-client-win/client.dtsod new file mode 100644 index 0000000..d58641c --- /dev/null +++ b/dtlauncher-client-win/client.dtsod @@ -0,0 +1,2 @@ +server_domain: "timerix.cf"; +server_port: 4000; \ No newline at end of file diff --git a/dtlauncher-client-win/dtlauncher-client-win.csproj b/dtlauncher-client-win/dtlauncher-client-win.csproj index 794939d..fb191dd 100644 --- a/dtlauncher-client-win/dtlauncher-client-win.csproj +++ b/dtlauncher-client-win/dtlauncher-client-win.csproj @@ -107,14 +107,14 @@ - - {ce793497-2d5c-42d8-b311-e9b32af9cdfb} - DTLib - {e02ea967-fd29-47d2-b25b-ba684b784aee} dtscript + + {ce793497-2d5c-42d8-b311-e9b32af9cdfb} + DTLib + @@ -123,6 +123,7 @@ del /f /q dtlauncher-client-win.exe.config copy dtlauncher-client-win.exe C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\dtlauncher-client-win.exe +copy C:\projects\c#\dtlauncher\dtlauncher-client-win\client.dtsod client.dtsod copy client.dtsod C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\client.dtsod \ No newline at end of file diff --git a/dtlauncher-server-win/DtlauncherServer.cs b/dtlauncher-server-win/DtlauncherServer.cs index 5d7f554..0b1a927 100644 --- a/dtlauncher-server-win/DtlauncherServer.cs +++ b/dtlauncher-server-win/DtlauncherServer.cs @@ -15,6 +15,7 @@ namespace dtlauncher_server static readonly string logfile = $"logs\\dtlauncher-server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_'); static readonly Socket mainSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); static Dtsod config; + //static readonly Dictionary users = new(); static void Main() diff --git a/dtlauncher-server-win/dtlauncher-server-win.csproj b/dtlauncher-server-win/dtlauncher-server-win.csproj index 5bf6e1f..767f904 100644 --- a/dtlauncher-server-win/dtlauncher-server-win.csproj +++ b/dtlauncher-server-win/dtlauncher-server-win.csproj @@ -83,16 +83,11 @@ SettingsSingleFileGenerator Settings.Designer.cs + - - - {ce793497-2d5c-42d8-b311-e9b32af9cdfb} - DTLib - - False @@ -105,8 +100,15 @@ false + + + {ce793497-2d5c-42d8-b311-e9b32af9cdfb} + DTLib + + - del /f /q dtlauncher-server-win.exe.config + del /f /q dtlauncher-server-win.exe.config +copy C:\projects\c#\dtlauncher\dtlauncher-server-win\server.dtsod server.dtsod \ No newline at end of file diff --git a/dtlauncher-server-win/server.dtsod b/dtlauncher-server-win/server.dtsod new file mode 100644 index 0000000..472de2d --- /dev/null +++ b/dtlauncher-server-win/server.dtsod @@ -0,0 +1,2 @@ +server_ip: "10.1.10.44"; +server_port: 4000; \ No newline at end of file diff --git a/dtlauncher.sln b/dtlauncher.sln index 4c4cf21..56f8864 100644 --- a/dtlauncher.sln +++ b/dtlauncher.sln @@ -3,8 +3,6 @@ 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} @@ -24,18 +22,13 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution .editorconfig = .editorconfig EndProjectSection EndProject -Project("{54435603-DBB4-11D2-8724-00A0C9A8B90C}") = "installer", "installer\installer.vdproj", "{D3B717FC-F9D5-4C8F-8957-1BB964819EF1}" - ProjectSection(ProjectDependencies) = postProject - {4784D974-A342-4202-9430-90FE5AC00FC7} = {4784D974-A342-4202-9430-90FE5AC00FC7} - EndProjectSection +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 - {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 @@ -44,7 +37,8 @@ Global {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 - {D3B717FC-F9D5-4C8F-8957-1BB964819EF1}.Build|Any CPU.ActiveCfg = Build + {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 diff --git a/updater/Updater.cs b/updater/Updater.cs index 5db8c37..65edffd 100644 --- a/updater/Updater.cs +++ b/updater/Updater.cs @@ -12,7 +12,8 @@ namespace updater { static readonly string logfile = $"logs\\updater-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_'); static Socket mainSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); - static Dtsod config; + static readonly string server_domain = "timerix.cf"; + static readonly int server_port = 4000; static void Main(string[] args) { @@ -22,15 +23,14 @@ namespace updater Console.InputEncoding = Encoding.Unicode; Console.OutputEncoding = Encoding.Unicode; PublicLog.LogDel += Log; - config = config = new(File.ReadAllText("updater.dtsod")); // подключение к центральному серверу while (true) { try { - Log("b", "server address: <", "c", config["server_domain"], "b", - ">\nserver port: <", "c", config["server_port"].ToString(), "b", ">\n"); - mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(config["server_domain"])[0], (int)config["server_port"])); + Log("b", "server address: <", "c", server_domain, "b", + ">\nserver port: <", "c", server_port.ToString(), "b", ">\n"); + mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(server_domain)[0], server_port)); Log("g", "connected to server\n"); break; } diff --git a/updater/updater.csproj b/updater/updater.csproj index f3e3c3b..c6d74f9 100644 --- a/updater/updater.csproj +++ b/updater/updater.csproj @@ -73,22 +73,21 @@ - + + + + {ce793497-2d5c-42d8-b311-e9b32af9cdfb} DTLib - - - del /f /q dtlauncher.exe.config copy dtlauncher.exe C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\dtlauncher.exe copy DTLib.dll C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\DTLib.dll -copy dtlauncher.exe C:\projects\c#\dtlauncher\installer\dtlauncher\dtlauncher.exe -copy DTLib.dll C:\projects\c#\dtlauncher\installer\dtlauncher\DTLib.dll -copy updater.dtsod C:\projects\c#\dtlauncher\installer\dtlauncher\updater.dtsod +copy dtlauncher.exe C:\projects\c#\dtlauncher\release\dtlauncher.exe +copy DTLib.dll C:\projects\c#\dtlauncher\release\DTLib.dll