it can be compiled, but doesn't work

This commit is contained in:
Timerix22 2021-10-30 13:46:48 +03:00
parent 17915621f3
commit 538db682f3
32 changed files with 108 additions and 1984 deletions

1
.gitignore vendored
View File

@ -35,6 +35,7 @@ bld/
# Visual Studio 2015/2017 cache/options directory # Visual Studio 2015/2017 cache/options directory
.vs/ .vs/
.vshistory/
# Uncomment if you have tasks that create the project's static files in wwwroot # Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/ #wwwroot/

View File

@ -1,24 +0,0 @@
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");
}
}
}
}

View File

@ -1,73 +0,0 @@
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();
}
}
}

View File

@ -1,72 +0,0 @@
using System;
using System.Collections.Generic;
using System.Threading;
namespace DTLib
{
public class CompressedArray
{
public class Array1D<T> where T : IComparable<T>
{
byte[] Description;
T[] Memory;
public Array1D() { }
public Array1D(T[] sourceArray)
{
CompressArray(sourceArray);
}
public void CompressArray(T[] sourceArray)
{
var listMem = new List<T>();
var listDesc = new List<byte>();
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;
}
}
}
}

View File

@ -1,54 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>DTLib</RootNamespace>
<AssemblyName>DTLib</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<LangVersion>9.0</LangVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Build|AnyCPU' ">
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
</ItemGroup>
<ItemGroup>
<Compile Include="Color.cs" />
<Compile Include="CompressedArray.cs" />
<Compile Include="Dtsod.cs" />
<Compile Include="cs9somefix.cs" />
<Compile Include="DtsodParser2.cs" />
<Compile Include="Filework.cs" />
<Compile Include="ColoredConsole.cs" />
<Compile Include="PublicLog.cs" />
<Compile Include="Network.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Hasher.cs" />
<Compile Include="SecureRandom.cs" />
<Compile Include="SimpleConverter.cs" />
<Compile Include="TImer.cs" />
<Compile Include="XXHash.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>xcopy C:\projects\c#\dtlauncher\DTLib C:\projects\c#\DTLib /E /H | echo All</PostBuildEvent>
</PropertyGroup>
</Project>

View File

@ -1,418 +0,0 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using static DTLib.PublicLog;
namespace DTLib
{
//
// это как json но не совсем
//
public class Dtsod : Dictionary<string, dynamic>
{
static readonly bool debug = false;
public string Text { get; }
//public Dictionary<string, dynamic> Values { get; set; }
public Dtsod(string text)
{
Text = text;
foreach (KeyValuePair<string, dynamic> pair in ParseNew(text))
Add(pair.Key, pair.Value);
}
/*// выдаёт Exception
public dynamic this[string key]
{
get
{
if (TryGet(key, out dynamic value)) return value;
else throw new Exception($"Dtsod[{key}] key not found");
}
set
{
if (TrySet(key, value)) return;
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)
{
value = null;
return false;
}
}
public bool TrySet(string key, dynamic value)
{
try
{
Values[key] = value;
return true;
}
catch (KeyNotFoundException)
{
return false;
}
}*/
public override string ToString() => Text;
enum ValueType
{
List,
Complex,
String,
/*Double,
Long,
Ulong,
Short,
Ushort,
Int,
Uint,
Null,
Boolean,*/
Default
}
Dictionary<string, dynamic> ParseNew(string text)
{
Dictionary<string, dynamic> parsed = new();
int i = 0;
for (; i < text.Length; i++) ReadName();
return parsed;
void ReadName()
{
void ReadCommentLine()
{
for (; i < text.Length && text[i] != '\n'; i++) ;
}
bool isListElem = false;
dynamic value = null;
StringBuilder defaultNameBuilder = new();
if (debug) LogNoTime("m", "ReadName");
for (; i < text.Length; i++)
{
if (debug) LogNoTime("w", text[i].ToString());
switch (text[i])
{
case ' ':
case '\t':
case '\r':
case '\n':
break;
case ':':
i++;
value = ReadValue();
string name = defaultNameBuilder.ToString();
if (debug) LogNoTime("c", $"parsed.Add({name}, {value})\n");
if (isListElem)
{
if (!parsed.ContainsKey(name)) parsed.Add(name, new List<dynamic>());
parsed[name].Add(value);
}
else parsed.Add(name, value);
if (debug) LogNoTime("g", "ReadName return\n");
return;
// строка, начинающаяся с # будет считаться комментом
case '#':
ReadCommentLine();
break;
case '}':
throw new Exception("Parse.ReadName() error: unexpected '}' at " + i + "char");
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
case '$':
if (defaultNameBuilder.ToString().Length != 0) throw new Exception("unexpected usage of '$' at char " + i.ToString());
isListElem = true;
break;
case ';':
throw new Exception("Parse.ReadName() error: unexpected ';' at " + i + "char");
default:
defaultNameBuilder.Append(text[i]);
break;
}
}
}
dynamic ReadValue()
{
ValueType type = ValueType.Default;
string ReadString()
{
i++;
StringBuilder valueBuilder = new();
valueBuilder.Append('"');
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
{
if (debug) LogNoTime("gray", text[i].ToString());
valueBuilder.Append(text[i]);
}
valueBuilder.Append('"');
if (debug) LogNoTime("gray", text[i].ToString());
type = ValueType.String;
return valueBuilder.ToString();
}
List<dynamic> ReadList()
{
i++;
List<dynamic> output = new();
StringBuilder valueBuilder = new();
for (; text[i] != ']'; i++)
{
if (debug) LogNoTime("c", text[i].ToString());
switch (text[i])
{
case ' ':
case '\t':
case '\r':
case '\n':
break;
case ',':
output.Add(ParseValueToRightType(valueBuilder.ToString()));
valueBuilder.Clear();
break;
default:
valueBuilder.Append(text[i]);
break;
}
}
output.Add(ParseValueToRightType(valueBuilder.ToString()));
if (debug) LogNoTime("c", text[i].ToString());
type = ValueType.List;
return output;
}
Dictionary<string, dynamic> ReadComplex()
{
i++;
StringBuilder valueBuilder = new();
for (; text[i] != '}'; i++)
{
if (debug) LogNoTime("y", text[i].ToString());
if (text[i] == '"')
{
valueBuilder.Append(ReadString());
}
else valueBuilder.Append(text[i]);
}
if (debug) LogNoTime("y", text[i].ToString());
type = ValueType.Complex;
if (debug) LogNoTime("g", valueBuilder.ToString());
return ParseNew(valueBuilder.ToString());
}
dynamic ParseValueToRightType(string stringValue)
{
if (debug) LogNoTime("g", $"\nParseValueToRightType({stringValue})");
return stringValue switch
{
_ when stringValue.Contains('"') => stringValue.Remove(stringValue.Length - 1).Remove(0, 1),
// bool
"true" or "false" => stringValue.ToBool(),
// null
"null" => null,
// double
_ when stringValue.Contains('.') => stringValue.ToDouble(),
// ushort, ulong, uint
_ when (stringValue.Length > 2 && stringValue[stringValue.Length - 2] == 'u') => stringValue[stringValue.Length - 1] switch
{
's' => stringValue.Remove(stringValue.Length - 2).ToUShort(),
'i' => stringValue.Remove(stringValue.Length - 2).ToUInt(),
'l' => stringValue.Remove(stringValue.Length - 2).ToULong(),
_ => throw new Exception($"Dtsod.Parse.ReadValue() error: wrong type <u{stringValue[stringValue.Length - 1]}>")
},
// short, long, int
_ => stringValue[stringValue.Length - 1] switch
{
's' => stringValue.Remove(stringValue.Length - 1).ToShort(),
'l' => stringValue.Remove(stringValue.Length - 1).ToLong(),
_ => stringValue.ToInt()
}
};
}
dynamic value = null;
StringBuilder defaultValueBuilder = new();
if (debug) LogNoTime("m", "\nReadValue\n");
for (; i < text.Length; i++)
{
if (debug) LogNoTime("b", text[i].ToString());
switch (text[i])
{
case ' ':
case '\t':
case '\r':
case '\n':
break;
case '"':
value = ReadString();
break;
case ';':
if (debug) LogNoTime("g", $"\nReadValue returns type {type} value <{value}>\n");
return type switch
{
ValueType.List or ValueType.Complex => value,
ValueType.String => ParseValueToRightType(value),
ValueType.Default => ParseValueToRightType(defaultValueBuilder.ToString()),
_ => throw new Exception($"Dtlib.Parse.ReadValue() error: can't convert value to type <{type}>")
};
case '[':
value = ReadList();
break;
case '{':
value = ReadComplex();
break;
default:
defaultValueBuilder.Append(text[i]);
break;
}
}
throw new Exception("Dtsod.Parse.ReadValue error: end of text");
}
}
Dictionary<string, dynamic> ParseOld(string text)
{
Dictionary<string, dynamic> 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;
// bool
switch (str)
{
// предустановленные значения
case "true": return true;
case "false": return false;
case "null": return null;
default:
// double
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 <u{str[str.Length - 1]}>"),
};
// 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++)
{
if (debug) LogNoTime(text[i].ToString());
void ReadString()
{
i++;
while (text[i] != '"' || text[i - 1] == '\\')
{
if (debug) LogNoTime(text[i].ToString());
valStrB.Append(text[i]);
i++;
}
}
switch (text[i])
{
case '{':
i++;
for (; text[i] != '}'; i++)
{
if (text[i] == '"') ReadString();
else valStrB.Append(text[i]);
}
value = ParseOld(valStrB.ToString());
valStrB.Clear();
break;
case '}':
throw new Exception("ParseConfig() error: unexpected '}' at " + i + "char");
case '"':
readString = true;
ReadString();
break;
case ':':
readValue = true;
break;
case ' ':
case '\t':
case '\r':
case '\n':
break;
case '[':
isList = true;
value = new List<dynamic>();
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<dynamic>());
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;
}
}
}

View File

@ -1,207 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DTLib
{
class DtsodParser2
{
enum ValueType
{
List,
Complex,
String,
Double,
Long,
Ulong,
Short,
Ushort,
Int,
Uint,
Null,
Boolean,
Default
}
Dictionary<string, dynamic> ParseNew(string text)
{
Dictionary<string, dynamic> parsed = new();
int i = 0;
for (; i < text.Length; i++) ReadName();
return parsed;
void ReadName()
{
bool isListElem = false;
void ReadCommentLine()
{
for (; i < text.Length && text[i] != '\n'; i++) ;
}
dynamic value = null;
StringBuilder defaultNameBuilder = new();
for (; i < text.Length; i++)
{
switch (text[i])
{
case ' ':
case '\t':
case '\r':
case '\n':
break;
case ':':
value = ReadValue();
break;
// строка, начинающаяся с # будет считаться комментом
case '#':
ReadCommentLine();
break;
case '}':
throw new Exception("ParseConfig() error: unexpected '}' at " + i + "char");
// если $ перед названием параметра поставить, значение value добавится в лист с названием name
case '$':
if (defaultNameBuilder.ToString().Length != 0) throw new Exception("unexpected usage of '$' at char " + i.ToString());
isListElem = true;
break;
case ';':
string name = defaultNameBuilder.ToString();
if (isListElem)
{
if (!parsed.ContainsKey(name)) parsed.Add(name, new List<dynamic>());
parsed[name].Add(value);
}
else parsed.Add(name, value);
return;
default:
defaultNameBuilder.Append(text[i]);
break;
}
}
}
dynamic ReadValue()
{
ValueType type = ValueType.Default;
string ReadString()
{
i++;
StringBuilder valueBuilder = new();
for (; text[i] != '"' || text[i - 1] == '\\'; i++)
valueBuilder.Append(text[i]);
type = ValueType.String;
return valueBuilder.ToString();
}
List<string> ReadList()
{
List<string> output = new();
StringBuilder valueBuilder = new();
for (; text[i] != ']'; i++)
{
switch (text[i])
{
case ' ':
case '\t':
case '\r':
case '\n':
break;
case ',':
output.Add(valueBuilder.ToString());
break;
default:
valueBuilder.Append(text[i]);
break;
}
}
type = ValueType.List;
return output;
}
Dictionary<string, dynamic> ReadComplex()
{
i++;
StringBuilder valueBuilder = new();
for (; text[i] != '}'; i++)
{
if (text[i] == '"') valueBuilder.Append(ReadString());
else valueBuilder.Append(text[i]);
}
type = ValueType.Complex;
return ParseNew(valueBuilder.ToString());
}
dynamic value = null;
StringBuilder defaultValueBuilder = new();
for (; i < text.Length; i++)
{
switch (text[i])
{
case ' ':
case '\t':
case '\r':
case '\n':
break;
case '"':
value = ReadString();
break;
case ';':
if (type == ValueType.Default)
{
string valueString = defaultValueBuilder.ToString();
type = valueString switch
{
"true" or "false" => ValueType.Boolean,
"null" => ValueType.Null,
_ when valueString.Contains('.') => ValueType.Null,
_ when (valueString.Length > 2 && valueString[valueString.Length - 2] == 'u') => valueString[valueString.Length - 1] switch
{
's' => ValueType.Ushort,
'i' => ValueType.Uint,
'l' => ValueType.Ulong,
_ => throw new Exception($"Dtsod.Parse.ReadValue() error: wrong type <u{valueString[valueString.Length - 1]}>")
},
_ => valueString[valueString.Length - 1] switch
{
's' => ValueType.Short,
'l' => ValueType.Long,
_ => ValueType.Int
}
};
}
return type switch
{
ValueType.String or ValueType.List or ValueType.Complex => value,
ValueType.Double => SimpleConverter.ToDouble(value),
ValueType.Long => SimpleConverter.ToLong(value.Remove(value.Length - 1)),
ValueType.Ulong => SimpleConverter.ToULong(value.Remove(value.Length - 2)),
ValueType.Short => SimpleConverter.ToShort(value.Remove(value.Length - 1)),
ValueType.Ushort => SimpleConverter.ToUShort(value.Remove(value.Length - 2)),
ValueType.Int => SimpleConverter.ToInt(value),
ValueType.Uint => SimpleConverter.ToUInt(value),
ValueType.Boolean => SimpleConverter.ToBool(value),
ValueType.Null => null,
_ => throw new Exception($"Dtlib.Parse.ReadValue() error: can't convert value to type <{type}>")
};
case '[':
value = ReadList();
break;
case '{':
value = ReadComplex();
break;
default:
defaultValueBuilder.Append(text[i]);
break;
}
}
throw new Exception("Dtsod.Parse.ReadValue error: end of text");
}
}
}
}

View File

@ -1,251 +0,0 @@
using System;
using System.Collections.Generic;
namespace DTLib
{
//
// методы для работы с файловой системой
//
public static class Filework
{
// записывает текст в файл и закрывает файл
public static void LogToFile(string logfile, string msg)
{
lock (new object())
{
File.WriteAllText(logfile, msg);
}
}
// чтение параметров из конфига
public static string ReadFromConfig(string configfile, string key)
{
lock (new object())
{
key += ": ";
using var reader = new System.IO.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 Exception($"ReadFromConfig({configfile}, {key}) error: key not found");
}
}
public static class Directory
{
public static bool Exists(string dir) => System.IO.Directory.Exists(dir);
// создает папку, если её не существует
public static void Create(string dir)
{
if (!Directory.Exists(dir))
{
// проверяет существование папки, в которой нужно создать dir
if (dir.Contains("\\") && !Directory.Exists(dir.Remove(dir.LastIndexOf('\\'))))
Create(dir.Remove(dir.LastIndexOf('\\')));
System.IO.Directory.CreateDirectory(dir);
}
}
// копирует все файлы и папки
public static void Copy(string source_dir, string new_dir, bool owerwrite = false)
{
Create(new_dir);
List<string> subdirs = new List<string>();
List<string> files = GetAllFiles(source_dir, ref subdirs);
for (int i = 0; i < subdirs.Count; i++)
{
Create(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, owerwrite);
//PublicLog.Log(new string[] {"g", $"file <", "c", files[i], "b", "> have copied to <", "c", newfile, "b", ">\n'" });
}
}
// копирует все файлы и папки и выдаёт список конфликтующих файлов
public static void Copy(string source_dir, string new_dir, out List<string> conflicts, bool owerwrite = false)
{
conflicts = new List<string>();
var subdirs = new List<string>();
var files = GetAllFiles(source_dir, ref subdirs);
Create(new_dir);
for (int i = 0; i < subdirs.Count; i++)
{
Create(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 void Delete(string dir)
{
var subdirs = new List<string>();
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--)
System.IO.Directory.Delete(subdirs[i]);
System.IO.Directory.Delete(dir);
}
public static string[] GetFiles(string dir) => System.IO.Directory.GetFiles(dir);
public static string[] GetFiles(string dir, string searchPattern) => System.IO.Directory.GetFiles(dir, searchPattern);
public static string[] GetDirectories(string dir) => System.IO.Directory.GetDirectories(dir);
// выдает список всех файлов
public static List<string> GetAllFiles(string dir)
{
List<string> all_files = new List<string>();
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<string> GetAllFiles(string dir, ref List<string> all_subdirs)
{
List<string> all_files = new List<string>();
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 class File
{
public static int GetSize(string file) => new System.IO.FileInfo(file).Length.ToInt();
public static bool Exists(string file) => System.IO.File.Exists(file);
// если файл не существует, создаёт файл, создаёт папки из его пути
public static void Create(string file)
{
if (!File.Exists(file))
{
if (file.Contains("\\")) Directory.Create(file.Remove(file.LastIndexOf('\\')));
using var stream = System.IO.File.Create(file);
stream.Close();
}
}
public static void Copy(string srcPath, string newPath, bool replace = false)
{
if (!replace && Exists(newPath)) throw new Exception($"file <{newPath}> alredy exists");
Create(newPath);
WriteAllBytes(newPath, ReadAllBytes(srcPath));
}
public static void Delete(string file) => System.IO.File.Delete(file);
public static byte[] ReadAllBytes(string file)
{
using var stream = File.OpenRead(file);
int size = GetSize(file);
byte[] output = new byte[size];
stream.Read(output, 0, size);
stream.Close();
return output;
}
public static string ReadAllText(string file) => ReadAllBytes(file).ToStr();
public static void WriteAllBytes(string file, byte[] content)
{
using var stream = File.OpenWrite(file);
stream.Write(content, 0, content.Length);
stream.Close();
}
public static void WriteAllText(string file, string content) => WriteAllBytes(file, content.ToBytes());
public static void AppendAllBytes(string file, byte[] content)
{
using var stream = File.OpenAppend(file);
stream.Write(content, 0, content.Length);
stream.Close();
}
public static void AppendAllText(string file, string content) => AppendAllBytes(file, content.ToBytes());
public static System.IO.FileStream OpenRead(string file)
{
if (!Exists(file)) throw new Exception($"file not found: <{file}>");
return System.IO.File.OpenRead(file);
}
public static System.IO.FileStream OpenWrite(string file)
{
File.Create(file);
return System.IO.File.OpenWrite(file);
}
public static System.IO.FileStream OpenAppend(string file)
{
File.Create(file);
return System.IO.File.Open(file, System.IO.FileMode.Append);
}
}
}
}

View File

@ -1,61 +0,0 @@
using System.Collections.Generic;
using System.Security.Cryptography;
using static DTLib.Filework;
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<byte> rez = new List<byte>();
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;
}
}
}

View File

@ -1,271 +0,0 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using static DTLib.Filework;
using static DTLib.PublicLog;
namespace DTLib
{
//
// весь униврсальный неткод тут
// большинство методов предназначены для работы с TCP сокетами (Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
//
public static class Network
{
// ждёт пакет заданного размера с заданным началом и концом
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>();
byte[] packageSize = data.Length.IntToBytes();
if (packageSize.Length == 1) list.Add(0);
list.AddRange(packageSize);
list.AddRange(data);
socket.Send(list.ToArray());
}
// скачивает файл с помощью 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)
{
File.Create(filePath_client);
using var fileStream = File.OpenWrite(filePath_client);
var fileSize = mainSocket.GetPackage().ToStr().ToUInt();
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 = File.GetSize(filePath);
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" });
}
// получает с сайта публичный ip
public static string GetPublicIP() => new WebClient().DownloadString("https://ipv4bot.whatismyipaddress.com/");
// пингует айпи с помощью встроенной в винду проги, возвращает задержку
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);
}
public class FSP
{
Socket mainSocket;
FSP(Socket _mainSocket) => mainSocket = _mainSocket;
//public delegate void FSP_LogDelegate(uint bytes);
public uint BytesDownloaded = 0;
public uint BytesUploaded = 0;
public uint Filesize = 0;
// скачивает файл с помощью FSP протокола
public void DownloadFile(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());
DownloadFile(filePath_client);
}
public void DownloadFile(string filePath_client)
{
File.Create(filePath_client);
using var fileStream = File.OpenWrite(filePath_client);
Filesize = mainSocket.GetPackage().ToStr().ToUInt();
var hashstr = mainSocket.GetPackage().HashToString();
mainSocket.SendPackage("ready".ToBytes());
int packagesCount = 0;
byte[] buffer = new byte[5120];
int fullPackagesCount = SimpleConverter.Truncate(Filesize / buffer.Length);
// получение файла
for (; packagesCount < fullPackagesCount; packagesCount++)
{
buffer = mainSocket.GetPackage();
fileStream.Write(buffer, 0, buffer.Length);
fileStream.Flush();
}
// получение остатка
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 void UploadFile(string filePath)
{
Log("b", $"uploading file {filePath}\n");
using var fileStream = File.OpenRead(filePath);
Filesize = File.GetSize(filePath).ToUInt();
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 fullPackagesCount = SimpleConverter.Truncate(Filesize / buffer.Length);
for (; packagesCount < fullPackagesCount; packagesCount++)
{
fileStream.Read(buffer, 0, buffer.Length);
mainSocket.SendPackage(buffer);
}
// досылка остатка
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 void DownloadByManifest(string manifestOnServer, string dirOnClient)
{
Log("b", "downloading manifest <", "c", manifestOnServer, "b", ">\n");
DownloadFile(manifestOnServer, "TEMP\\manifestOnServer");
var manifest = new Dtsod(File.ReadAllText("TEMP\\manifest.dtsod"));
Log("g", $"found {manifest.Values.Count} files in manifest\n");
var hasher = new Hasher();
foreach (string fileOnServer in manifest.Keys)
{
string fileOnClient = $"{dirOnClient}\\{fileOnServer}";
Log("b", "file <", "c", fileOnClient, "b", ">... ");
if (!File.Exists(fileOnClient))
{
LogNoTime("y", "doesn't exist\n");
DownloadFile(fileOnServer, fileOnClient);
}
else if (hasher.HashFile(fileOnClient).HashToString() != manifest[fileOnServer])
{
LogNoTime("y", "outdated\n");
DownloadFile(fileOnServer, fileOnClient);
}
else LogNoTime("g", "without changes\n");
}
Directory.Delete("TEMP");
}
}
}
}

View File

@ -1,35 +0,0 @@
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")]

View File

@ -1,14 +0,0 @@
namespace DTLib
{
//
// вывод логов со всех классов в библиотеке
//
public static class PublicLog
{
public delegate void LogDelegate(params string[] msg);
// вот к этому объекту подключайте методы для вывода логов
public static LogDelegate Log;
public static LogDelegate LogNoTime;
public static LogDelegate FSP_DownloadSpeed;
}
}

View File

@ -1,37 +0,0 @@
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;
}
}
}*/
}
}

View File

@ -1,151 +0,0 @@
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<byte> 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<T>(this T number) => Math.Truncate(number.ToDouble()).ToInt();
// сортирует в порядке возрастания элементы если это возможно, используя стандартный метод list.Sort();
public static T[] Sort<T>(this T[] array)
{
var list = array.ToList();
list.Sort();
return list.ToArray();
}
// массив в лист
public static List<T> ToList<T>(this T[] input)
{
var list = new List<T>();
list.AddRange(input);
return list;
}
// удаление нескольких элементов массива
public static T[] RemoveRange<T>(this T[] input, int startIndex, int count)
{
List<T> list = input.ToList();
list.RemoveRange(startIndex, count);
return list.ToArray();
}
public static T[] RemoveRange<T>(this T[] input, int startIndex) => input.RemoveRange(startIndex, input.Length - startIndex);
// метод как у листов
public static bool Contains<T>(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<T>(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 int ToInt<T>(this T input) => Convert.ToInt32(input);
public static uint ToUInt<T>(this T input) => Convert.ToUInt32(input);
public static long ToLong<T>(this T input) => Convert.ToInt64(input);
public static ulong ToULong<T>(this T input) => Convert.ToUInt64(input);
public static short ToShort<T>(this T input) => Convert.ToInt16(input);
public static ushort ToUShort<T>(this T input) => Convert.ToUInt16(input);
public static double ToDouble<T>(this T input) => Convert.ToDouble(input, System.Globalization.CultureInfo.InvariantCulture);
public static byte ToByte<T>(this T input) => Convert.ToByte(input);
public static sbyte ToSByte<T>(this T input) => Convert.ToSByte(input);
public static bool ToBool<T>(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<byte> output = new();
while (num != 0)
{
output.Add(ToByte(num % 256));
num = Truncate(num / 256);
}
output.Reverse();
return output.ToArray();
}
public static string ToString<T>(this IEnumerable<T> 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();
}
}
}

View File

@ -1,36 +0,0 @@
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();
}
}
}

View File

@ -1,180 +0,0 @@
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<byte[], int, uint> FuncGetLittleEndianUInt32;
private static readonly Func<uint, uint> 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<byte[], int, uint>((x, i) =>
{
unsafe
{
fixed (byte* array = x)
{
return *(uint*)(array + i);
}
}
});
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => (i & 0x000000FFU) << 24 | (i & 0x0000FF00U) << 8 | (i & 0x00FF0000U) >> 8 | (i & 0xFF000000U) >> 24);
}
else
{
FuncGetLittleEndianUInt32 = new Func<byte[], int, uint>((x, i) =>
{
unsafe
{
fixed (byte* array = x)
{
return (uint)(array[i++] | (array[i++] << 8) | (array[i++] << 16) | (array[i] << 24));
}
}
});
FuncGetFinalHashUInt32 = new Func<uint, uint>(i => i);
}
}
// Creates an instance of <see cref="XXHash32"/> class by default seed(0).
// <returns></returns>
public static new XXHash32 Create() => new XXHash32();
// Initializes a new instance of the <see cref="XXHash32"/> class by default seed(0).
public XXHash32() => Initialize(0);
// Initializes a new instance of the <see cref="XXHash32"/> class, and sets the <see cref="Seed"/> to the specified value.
// <param name="seed">Represent the seed to be used for xxHash32 computing.</param>
public XXHash32(uint seed) => Initialize(seed);
// Gets the <see cref="uint"/> value of the computed hash code.
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
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.
// <exception cref="InvalidOperationException">Hash computation has not yet completed.</exception>
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.
// <param name="array">The input to compute the hash code for.</param>
// <param name="ibStart">The offset into the byte array from which to begin using data.</param>
// <param name="cbSize">The number of bytes in the byte array to use as data.</param>
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.
// <returns>The computed hash code.</returns>
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();
}
}
}

View File

@ -1,8 +0,0 @@
// включает init и record из c# 9.0
using System.ComponentModel;
namespace System.Runtime.CompilerServices
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class IsExternalInit { }
}

View File

@ -1,6 +1,5 @@
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Net.Sockets;
using System.Windows; using System.Windows;
namespace dtlauncher_client_win namespace dtlauncher_client_win

View File

@ -1,9 +1,9 @@
using DTLib; using System;
using System;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Windows; using System.Windows;
using static DTLib.Filework; using DTLib;
using DTLib.Filesystem;
namespace dtlauncher_client_win namespace dtlauncher_client_win
{ {
@ -29,8 +29,9 @@ namespace dtlauncher_client_win
mainSocket = _socket; mainSocket = _socket;
logfile = _logfile; logfile = _logfile;
LogBox.Text += _log; LogBox.Text += _log;
PublicLog.Log += Log; PublicLog.LogEvent += Log;
this.Closed += AppClose; PublicLog.LogNoTimeEvent += Log;
Closed += AppClose;
// переключение вкладок кнопками // переключение вкладок кнопками
var green = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(44, 220, 17)); 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)); var white = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240));
@ -62,7 +63,7 @@ namespace dtlauncher_client_win
SettingsButton.Foreground = green; SettingsButton.Foreground = green;
}; };
// считывание дескрипторов программ // считывание дескрипторов программ
var descriptors = Directory.GetFiles("descriptors", "*.desc"); string[] descriptors = Directory.GetFiles("descriptors", "*.desc");
programsArray = new ProgramLabel[descriptors.Length]; programsArray = new ProgramLabel[descriptors.Length];
Log(descriptors.Length + " descriptors found\n"); Log(descriptors.Length + " descriptors found\n");
for (int i = 0; i < descriptors.Length; i++) for (int i = 0; i < descriptors.Length; i++)
@ -86,7 +87,7 @@ namespace dtlauncher_client_win
public void Log(string msg) public void Log(string msg)
{ {
if (LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg; if (LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg;
Filework.LogToFile(logfile, msg); OldFilework.LogToFile(logfile, msg);
LogBox.Text += msg; LogBox.Text += msg;
} }

View File

@ -1,10 +1,12 @@
using DTLib; using System;
using System;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Windows; using System.Windows;
using static DTLib.Filework; using DTLib;
using DTLib.Dtsod;
using DTLib.Filesystem;
using DTLib.Network;
namespace dtlauncher_client_win namespace dtlauncher_client_win
{ {
@ -15,7 +17,7 @@ namespace dtlauncher_client_win
{ {
public Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public Socket mainSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public string logfile = $"logs\\client-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_'); public string logfile = $"logs\\client-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
Dtsod config; DtsodV21 config;
public LoginWindow() public LoginWindow()
{ {
@ -28,12 +30,13 @@ namespace dtlauncher_client_win
Directory.Create("installed"); Directory.Create("installed");
Directory.Create("installscripts"); Directory.Create("installscripts");
Directory.Create("launchinfo"); Directory.Create("launchinfo");
PublicLog.Log += Log; PublicLog.LogEvent += Log;
PublicLog.LogNoTimeEvent += Log;
LoginButton.Click += Login; LoginButton.Click += Login;
RegisterButton.Click += Register; RegisterButton.Click += Register;
Log("[" + DateTime.Now.ToString() + "]: launcher is starting\n"); Log("[" + DateTime.Now.ToString() + "]: launcher is starting\n");
config = new(File.ReadAllText("client.dtsod")); config = new(File.ReadAllText("client.dtsod"));
this.Closed += AppClose; Closed += AppClose;
} }
catch (Exception e) catch (Exception e)
{ {
@ -46,7 +49,7 @@ namespace dtlauncher_client_win
try try
{ {
var hasher = new Hasher(); var hasher = new Hasher();
var filename = $"register-{LoginBox.Text}.req"; string filename = $"register-{LoginBox.Text}.req";
string content = hasher.HashCycled(hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()), 512).HashToString() + ": " + LoginBox.Text; string content = hasher.HashCycled(hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()), 512).HashToString() + ": " + LoginBox.Text;
//File.WriteAllText(filename, hasher.HashCycled(hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()), 512).HashToString() + ": " + LoginBox.Text); //File.WriteAllText(filename, 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}"); //Log($"request file created:{Directory.GetCurrentDirectory()}\\register-{LoginBox.Text}.req {hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()).Length}");
@ -60,13 +63,13 @@ namespace dtlauncher_client_win
mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(config["server_domain"])[0], (int)config["server_port"])); mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(config["server_domain"])[0], (int)config["server_port"]));
Log("g", "connecting to server...\n"); Log("g", "connecting to server...\n");
mainSocket.ReceiveTimeout = 2000; mainSocket.ReceiveTimeout = 2000;
var recieved = mainSocket.GetPackage().ToStr(); string recieved = mainSocket.GetPackage().BytesToString();
if (recieved != "requesting hash") throw new Exception($"Login() error: invalid request <{recieved}> <{recieved.Length}>"); if (recieved != "requesting hash") throw new Exception($"Login() error: invalid request <{recieved}> <{recieved.Length}>");
mainSocket.SendPackage(new byte[] { 255, 255, 255, 255, 255, 255, 255, 255 }); mainSocket.SendPackage(new byte[] { 255, 255, 255, 255, 255, 255, 255, 255 });
recieved = mainSocket.GetPackage().ToStr(); recieved = mainSocket.GetPackage().BytesToString();
if (recieved != "updater") throw new Exception($"invalid central server answer <{recieved}>"); if (recieved != "updater") throw new Exception($"invalid central server answer <{recieved}>");
mainSocket.SendPackage("register new user".ToBytes()); mainSocket.SendPackage("register new user".ToBytes());
recieved = mainSocket.GetPackage().ToStr(); recieved = mainSocket.GetPackage().BytesToString();
if (recieved != "ok") throw new Exception($"invalid central server answer <{recieved}>"); if (recieved != "ok") throw new Exception($"invalid central server answer <{recieved}>");
mainSocket.SendPackage(content.ToBytes()); mainSocket.SendPackage(content.ToBytes());
Log("g", "registration request sent\n"); Log("g", "registration request sent\n");
@ -97,19 +100,20 @@ namespace dtlauncher_client_win
mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(config["server_domain"])[0], (int)config["server_port"])); mainSocket.Connect(new IPEndPoint(Dns.GetHostAddresses(config["server_domain"])[0], (int)config["server_port"]));
Log("g", "connecting to server...\n"); Log("g", "connecting to server...\n");
mainSocket.ReceiveTimeout = 2000; mainSocket.ReceiveTimeout = 2000;
string recieved = mainSocket.GetPackage().ToStr(); string recieved = mainSocket.GetPackage().BytesToString();
if (recieved != "requesting hash") throw new Exception($"Login() error: invalid request <{recieved}> <{recieved.Length}>"); if (recieved != "requesting hash") throw new Exception($"Login() error: invalid request <{recieved}> <{recieved.Length}>");
var hasher = new Hasher(); var hasher = new Hasher();
mainSocket.SendPackage(hasher.HashCycled(hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()), 512)); mainSocket.SendPackage(hasher.HashCycled(hasher.Hash(LoginBox.Text.ToBytes(), PasswBox.Password.ToBytes()), 512));
recieved = mainSocket.GetPackage().ToStr(); recieved = mainSocket.GetPackage().BytesToString();
if (recieved != "success") throw new Exception($"Login() error: invalid server answer <{recieved}>"); if (recieved != "success") throw new Exception($"Login() error: invalid server answer <{recieved}>");
Log("succesfully connected\n"); Log("succesfully connected\n");
// вызов нового окна // вызов нового окна
PublicLog.Log -= Log; PublicLog.LogEvent -= Log;
PublicLog.LogNoTimeEvent -= Log;
var lauWin = new LauncherWindow(mainSocket, logfile, LogBox.Text); var lauWin = new LauncherWindow(mainSocket, logfile, LogBox.Text);
lauWin.Show(); lauWin.Show();
this.Closed -= AppClose; Closed -= AppClose;
this.Close(); Close();
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -122,7 +126,7 @@ namespace dtlauncher_client_win
public void Log(string msg) public void Log(string msg)
{ {
if (LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg; if (LogBox.Text[LogBox.Text.Length - 1] == '\n') msg = "[" + DateTime.Now.ToString() + "]: " + msg;
LogToFile(logfile, msg); OldFilework.LogToFile(logfile, msg);
LogBox.Text += msg; LogBox.Text += msg;
} }

View File

@ -1,10 +1,10 @@
using DTLib; using System;
using System;
using System.Diagnostics; using System.Diagnostics;
using System.IO; using System.IO;
using System.Windows; using System.Windows;
using System.Windows.Controls; using System.Windows.Controls;
using System.Windows.Media.Imaging; using System.Windows.Media.Imaging;
using DTLib.Dtsod;
namespace dtlauncher_client_win namespace dtlauncher_client_win
{ {
@ -40,13 +40,10 @@ namespace dtlauncher_client_win
//public string description; //public string description;
//public string installScript; //public string installScript;
//public string installDir; //public string installDir;
Dtsod descriptor; DtsodV21 descriptor;
Dtsod launchinfo; DtsodV21 launchinfo;
public ProgramLabel() public ProgramLabel() => InitializeComponent();
{
InitializeComponent();
}
public ProgramLabel(string descriptorFile, int number, LauncherWindow window) public ProgramLabel(string descriptorFile, int number, LauncherWindow window)
{ {

View File

@ -1,2 +1,2 @@
server_domain: "timerix.cf"; server_domain: "m1net.keenetic.pro";
server_port: 4000; server_port: 25001;

View File

@ -107,7 +107,7 @@
<None Include="App.config" /> <None Include="App.config" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DTLib\DTLib.csproj"> <ProjectReference Include="..\..\DTLib\DTLib.csproj">
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project> <Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
<Name>DTLib</Name> <Name>DTLib</Name>
</ProjectReference> </ProjectReference>

View File

@ -1,11 +1,13 @@
using DTLib; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using System.Threading; using System.Threading;
using static DTLib.Filework; using DTLib;
using DTLib.Dtsod;
using DTLib.Filesystem;
using DTLib.Network;
namespace dtlauncher_server namespace dtlauncher_server
{ {
@ -13,7 +15,7 @@ namespace dtlauncher_server
{ {
static readonly string logfile = $"logs\\dtlauncher-server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_'); static readonly string logfile = $"logs\\dtlauncher-server-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
static readonly Socket mainSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); static readonly Socket mainSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static Dtsod config; static DtsodV21 config;
//static readonly Dictionary<Socket, Thread> users = new(); //static readonly Dictionary<Socket, Thread> users = new();
@ -24,7 +26,8 @@ namespace dtlauncher_server
Console.Title = "dtlauncher server"; Console.Title = "dtlauncher server";
Console.InputEncoding = Encoding.Unicode; Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode; Console.OutputEncoding = Encoding.Unicode;
PublicLog.Log += Log; PublicLog.LogEvent += Log;
PublicLog.LogNoTimeEvent += Log;
/*var outBuilder = new StringBuilder(); /*var outBuilder = new StringBuilder();
string time = DateTime.Now.ToString().Replace(':', '-').Replace(' ', '_'); string time = DateTime.Now.ToString().Replace(':', '-').Replace(' ', '_');
foreach (var _file in Directory.GetFiles(@"D:\!dtlauncher-server\share\public\Conan_Exiles")) foreach (var _file in Directory.GetFiles(@"D:\!dtlauncher-server\share\public\Conan_Exiles"))
@ -48,7 +51,7 @@ namespace dtlauncher_server
config = config = new(File.ReadAllText("server.dtsod")); config = config = new(File.ReadAllText("server.dtsod"));
int f = (int)config["server_port"]; int f = (int)config["server_port"];
Log("b", "local address: <", "c", config["server_ip"], "b", Log("b", "local address: <", "c", config["server_ip"], "b",
">\npublic address: <", "c", Network.GetPublicIP(), "b", ">\npublic address: <", "c", OldNetwork.GetPublicIP(), "b",
">\nport: <", "c", config["server_port"].ToString(), "b", ">\n"); ">\nport: <", "c", config["server_port"].ToString(), "b", ">\n");
mainSocket.Bind(new IPEndPoint(IPAddress.Parse(config["server_ip"]), (int)config["server_port"])); mainSocket.Bind(new IPEndPoint(IPAddress.Parse(config["server_ip"]), (int)config["server_port"]));
mainSocket.Listen(1000); mainSocket.Listen(1000);
@ -69,7 +72,7 @@ namespace dtlauncher_server
// запуск отдельного потока для каждого юзера // запуск отдельного потока для каждого юзера
while (true) while (true)
{ {
var userSocket = mainSocket.Accept(); Socket userSocket = mainSocket.Accept();
var userThread = new Thread(new ParameterizedThreadStart((obj) => UserHandle((Socket)obj))); var userThread = new Thread(new ParameterizedThreadStart((obj) => UserHandle((Socket)obj)));
//users.Add(userSocket, userThread); //users.Add(userSocket, userThread);
userThread.Start(userSocket); userThread.Start(userSocket);
@ -96,9 +99,9 @@ namespace dtlauncher_server
{ {
lock (new object()) lock (new object())
{ {
if (msg.Length == 1) Filework.LogToFile(logfile, msg[0]); if (msg.Length == 1) OldFilework.LogToFile(logfile, msg[0]);
else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n"); else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
else Filework.LogToFile(logfile, SimpleConverter.AutoBuild(msg)); else OldFilework.LogToFile(logfile, msg.MergeToString());
ColoredConsole.Write(msg); ColoredConsole.Write(msg);
} }
} }
@ -109,10 +112,11 @@ namespace dtlauncher_server
Log("b", "user connecting... "); Log("b", "user connecting... ");
//Socket fspSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //Socket fspSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//fspSocket.Bind() //fspSocket.Bind()
FSP fsp = new(handlerSocket);
try try
{ {
handlerSocket.SendPackage("requesting hash".ToBytes()); handlerSocket.SendPackage("requesting hash".ToBytes());
var hash = handlerSocket.GetPackage(); byte[] hash = handlerSocket.GetPackage();
// запрос от апдейтера // запрос от апдейтера
if (hash.HashToString() == "ffffffffffffffff") if (hash.HashToString() == "ffffffffffffffff")
{ {
@ -124,22 +128,22 @@ namespace dtlauncher_server
{ {
if (handlerSocket.Available >= 2) if (handlerSocket.Available >= 2)
{ {
var request = handlerSocket.GetPackage().ToStr(); string request = handlerSocket.GetPackage().BytesToString();
string recieved, filepath; string recieved, filepath;
switch (request) switch (request)
{ {
case "requesting file download": case "requesting file download":
filepath = "share\\client\\" + handlerSocket.GetPackage().ToStr(); filepath = "share\\client\\" + handlerSocket.GetPackage().BytesToString();
handlerSocket.FSP_Upload(filepath); fsp.UploadFile(filepath);
break; break;
case "register new user": case "register new user":
Log("b", "new user registration requested\n"); Log("b", "new user registration requested\n");
handlerSocket.SendPackage("ok".ToBytes()); handlerSocket.SendPackage("ok".ToBytes());
//filepath = handlerSocket.GetPackage().ToStr(); //filepath = handlerSocket.GetPackage().BytesToString();
//if (!filePath.EndsWith(".req")) throw new Exception($"wrong registration request file: <{filepath}>"); //if (!filePath.EndsWith(".req")) throw new Exception($"wrong registration request file: <{filepath}>");
//Log("b", $"downloading file registration_requests\\{filepath}\n"); //Log("b", $"downloading file registration_requests\\{filepath}\n");
//handlerSocket.FSP_Download($"registration_requests\\{filepath}"); //handlerSocket.FSP_Download($"registration_requests\\{filepath}");
recieved = handlerSocket.GetPackage().ToStr(); recieved = handlerSocket.GetPackage().BytesToString();
filepath = $"registration_requests\\{recieved.Remove(0, recieved.IndexOf(':') + 2)}.req"; filepath = $"registration_requests\\{recieved.Remove(0, recieved.IndexOf(':') + 2)}.req";
File.WriteAllText(filepath, recieved); File.WriteAllText(filepath, recieved);
Log("b", $"text wrote to file <", "c", "registration_requests\\{filepath}", "b", ">\n"); Log("b", $"text wrote to file <", "c", "registration_requests\\{filepath}", "b", ">\n");
@ -158,7 +162,7 @@ namespace dtlauncher_server
string login; string login;
lock (new object()) lock (new object())
{ {
login = Filework.ReadFromConfig("users.db", hash.HashToString()); login = OldFilework.ReadFromConfig("users.db", hash.HashToString());
} }
handlerSocket.SendPackage("success".ToBytes()); handlerSocket.SendPackage("success".ToBytes());
Log("g", "user <", "c", login, "g", "> succesfully logined\n"); Log("g", "user <", "c", login, "g", "> succesfully logined\n");
@ -166,7 +170,7 @@ namespace dtlauncher_server
{ {
if (handlerSocket.Available >= 64) if (handlerSocket.Available >= 64)
{ {
var request = handlerSocket.GetPackage().ToStr(); string request = handlerSocket.GetPackage().BytesToString();
switch (request) switch (request)
{ {
// ответ на NetWork.Ping() // ответ на NetWork.Ping()
@ -178,7 +182,7 @@ namespace dtlauncher_server
break;*/ break;*/
case "requesting file download": case "requesting file download":
handlerSocket.FSP_Upload("share\\public\\" + handlerSocket.GetPackage().ToStr()); fsp.UploadFile("share\\public\\" + handlerSocket.GetPackage().BytesToString());
break; break;
default: default:
throw new Exception("unknown request: " + request); throw new Exception("unknown request: " + request);
@ -197,12 +201,11 @@ namespace dtlauncher_server
} }
} }
// вычисляет и записывает в manifest.dtsod хеши файлов из files_list.dtsod // вычисляет и записывает в manifest.dtsod хеши файлов из files_list.dtsod
public static void CreateManifest(string dir) public static void CreateManifest(string dir)
{ {
if (!dir.EndsWith("\\")) dir += "\\"; if (!dir.EndsWith("\\")) dir += "\\";
var files = Filework.Directory.GetAllFiles(dir); List<string> files = Directory.GetAllFiles(dir);
if (files.Contains(dir + "manifest.dtsod")) files.Remove(dir + "manifest.dtsod"); if (files.Contains(dir + "manifest.dtsod")) files.Remove(dir + "manifest.dtsod");
StringBuilder manifestBuilder = new(); StringBuilder manifestBuilder = new();
Hasher hasher = new(); Hasher hasher = new();

View File

@ -101,7 +101,7 @@
</BootstrapperPackage> </BootstrapperPackage>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DTLib\DTLib.csproj"> <ProjectReference Include="..\..\DTLib\DTLib.csproj">
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project> <Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
<Name>DTLib</Name> <Name>DTLib</Name>
</ProjectReference> </ProjectReference>

View File

@ -1,2 +1,2 @@
server_ip: "10.1.10.44"; server_ip: "10.1.10.44";
server_port: 4000; server_port: 25001;

View File

@ -1,7 +1,7 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16 # Visual Studio Version 17
VisualStudioVersion = 16.0.30907.101 VisualStudioVersion = 17.0.31815.197
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-client-win", "dtlauncher-client-win\dtlauncher-client-win.csproj", "{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-client-win", "dtlauncher-client-win\dtlauncher-client-win.csproj", "{367793EE-4757-4ADD-BF7E-960DC9EB6DF9}"
ProjectSection(ProjectDependencies) = postProject ProjectSection(ProjectDependencies) = postProject
@ -15,10 +15,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtlauncher-server-win", "dt
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "updater", "updater\updater.csproj", "{4784D974-A342-4202-9430-90FE5AC00FC7}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "updater", "updater\updater.csproj", "{4784D974-A342-4202-9430-90FE5AC00FC7}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtscript", "dtscript\dtscript.csproj", "{E02EA967-FD29-47D2-B25B-BA684B784AEE}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "dtscript", "dtscript\dtscript.csproj", "{E02EA967-FD29-47D2-B25B-BA684B784AEE}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DTLib", "..\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Build|Any CPU = Build|Any CPU Build|Any CPU = Build|Any CPU
@ -30,10 +30,10 @@ Global
{8B9889A7-93DC-4914-92D1-8209BD3BA71A}.Build|Any CPU.Build.0 = Build|Any CPU {8B9889A7-93DC-4914-92D1-8209BD3BA71A}.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.ActiveCfg = Build|Any CPU
{4784D974-A342-4202-9430-90FE5AC00FC7}.Build|Any CPU.Build.0 = Build|Any CPU {4784D974-A342-4202-9430-90FE5AC00FC7}.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
{E02EA967-FD29-47D2-B25B-BA684B784AEE}.Build|Any CPU.ActiveCfg = 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 {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 EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -1,5 +1,6 @@
using DTLib; using System;
using System; using DTLib;
using DTLib.Filesystem;
namespace DTScript namespace DTScript
{ {
@ -9,8 +10,9 @@ namespace DTScript
{ {
try try
{ {
Filework.Directory.Create("dtscript-logs"); Directory.Create("dtscript-logs");
PublicLog.Log += Log; PublicLog.LogEvent += Log;
PublicLog.LogNoTimeEvent += Log;
var scripter = new ScriptRunner(); var scripter = new ScriptRunner();
if (args.Length == 0 || args.Length > 2) throw new Exception("enter script file path\n"); 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 == 1) scripter.RunScriptFile(args[0]);
@ -37,7 +39,7 @@ namespace DTScript
if (msg.Length == 1) if (msg.Length == 1)
{ {
msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0]; msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
Filework.LogToFile(logfile, msg[0]); OldFilework.LogToFile(logfile, msg[0]);
} }
else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n"); else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
else else
@ -45,7 +47,7 @@ namespace DTScript
msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1]; msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
var str = new System.Text.StringBuilder(); var str = new System.Text.StringBuilder();
for (int i = 0; i < msg.Length; i++) str.Append(msg[++i]); for (int i = 0; i < msg.Length; i++) str.Append(msg[++i]);
Filework.LogToFile(logfile, str.ToString()); OldFilework.LogToFile(logfile, str.ToString());
} }
ColoredConsole.Write(msg); ColoredConsole.Write(msg);
} }

View File

@ -1,9 +1,10 @@
using DTLib; using System;
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Net.Sockets; using System.Net.Sockets;
using static DTLib.Filework; using DTLib;
using DTLib.Filesystem;
using DTLib.Network;
namespace DTScript namespace DTScript
{ {
@ -15,6 +16,8 @@ namespace DTScript
// выводит текст через DTLib если дебаг включен // выводит текст через DTLib если дебаг включен
public bool debug = false; public bool debug = false;
public Socket mainSocket; public Socket mainSocket;
public FSP fsp;
internal void Debug(params string[] msg) internal void Debug(params string[] msg)
{ {
if (debug) PublicLog.Log(msg); if (debug) PublicLog.Log(msg);
@ -163,20 +166,21 @@ namespace DTScript
index++; index++;
break; break;
case "Download": case "Download":
mainSocket.FSP_Download(script[index].Options[0], script[index].Options[1]); if (fsp is null) fsp = new(mainSocket);
fsp.DownloadFile(script[index].Options[0], script[index].Options[1]);
break; break;
case "DirDelete": case "DirDelete":
Filework.Directory.Delete(script[index].Options[0]); Directory.Delete(script[index].Options[0]);
break; break;
case "FileDelete": case "FileDelete":
File.Delete(script[index].Options[0]); File.Delete(script[index].Options[0]);
break; break;
case "FileWrite": case "FileWrite":
Filework.File.Create(script[index].Options[0]); File.Create(script[index].Options[0]);
File.WriteAllText(script[index].Options[0], script[index].Options[1]); File.WriteAllText(script[index].Options[0], script[index].Options[1]);
break; break;
case "FileAppend": case "FileAppend":
Filework.File.Create(script[index].Options[0]); File.Create(script[index].Options[0]);
File.AppendAllText(script[index].Options[0], script[index].Options[1]); File.AppendAllText(script[index].Options[0], script[index].Options[1]);
break; break;
default: default:
@ -298,7 +302,7 @@ namespace DTScript
// вычисление значений правой и левой части неравенства // вычисление значений правой и левой части неравенства
char act = '\0'; char act = '\0';
double rezult_0 = new(), rezult_1; double rezult_0 = new(), rezult_1;
List<string> _expr = new List<string>(); var _expr = new List<string>();
for (ushort n = 0; n < expr.Count; n++) for (ushort n = 0; n < expr.Count; n++)
{ {
Debug("m", $" <{expr[n]}>\n"); Debug("m", $" <{expr[n]}>\n");

View File

@ -81,7 +81,7 @@
<Content Include="dtscript_doc.txt" /> <Content Include="dtscript_doc.txt" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DTLib\DTLib.csproj"> <ProjectReference Include="..\..\DTLib\DTLib.csproj">
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project> <Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
<Name>DTLib</Name> <Name>DTLib</Name>
</ProjectReference> </ProjectReference>

View File

@ -1,9 +1,11 @@
using DTLib; using System;
using System;
using System.Diagnostics; using System.Diagnostics;
using System.Net; using System.Net;
using System.Net.Sockets; using System.Net.Sockets;
using System.Text; using System.Text;
using DTLib;
using DTLib.Filesystem;
using DTLib.Network;
namespace updater namespace updater
{ {
@ -11,8 +13,8 @@ namespace updater
{ {
static readonly string logfile = $"logs\\updater-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_'); static readonly string logfile = $"logs\\updater-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
static Socket mainSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); static Socket mainSocket = new(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static readonly string server_domain = "timerix.cf"; static readonly string server_domain = "m1net.keenetic.pro";
static readonly int server_port = 4000; static readonly int server_port = 25001;
static void Main(string[] args) static void Main(string[] args)
{ {
@ -21,7 +23,8 @@ namespace updater
Console.Title = "dtlauncher updater"; Console.Title = "dtlauncher updater";
Console.InputEncoding = Encoding.Unicode; Console.InputEncoding = Encoding.Unicode;
Console.OutputEncoding = Encoding.Unicode; Console.OutputEncoding = Encoding.Unicode;
PublicLog.Log += Log; PublicLog.LogEvent += Log;
PublicLog.LogNoTimeEvent += Log;
// подключение к центральному серверу // подключение к центральному серверу
while (true) while (true)
{ {
@ -38,17 +41,18 @@ namespace updater
Log("r", $"updater.Main() error:\n{ex.Message}\n{ex.StackTrace}\n"); Log("r", $"updater.Main() error:\n{ex.Message}\n{ex.StackTrace}\n");
} }
} }
var recieved = mainSocket.GetPackage().ToStr(); var fsp = new FSP(mainSocket);
string recieved = mainSocket.GetPackage().BytesToString();
if (recieved != "requesting hash") throw new Exception("invalid server request"); if (recieved != "requesting hash") throw new Exception("invalid server request");
mainSocket.SendPackage(new byte[] { 255, 255, 255, 255, 255, 255, 255, 255 }); mainSocket.SendPackage(new byte[] { 255, 255, 255, 255, 255, 255, 255, 255 });
recieved = mainSocket.GetPackage().ToStr(); recieved = mainSocket.GetPackage().BytesToString();
if (recieved != "updater") throw new Exception($"invalid central server answer <{recieved}>"); if (recieved != "updater") throw new Exception($"invalid central server answer <{recieved}>");
// обновление апдейтера // обновление апдейтера
if (args.Length == 0 || args[0] != "updated") if (args.Length == 0 || args[0] != "updated")
{ {
mainSocket.FSP_Download("dtlauncher.exe", "TEMP\\dtlauncher.exe"); fsp.DownloadFile("dtlauncher.exe", "TEMP\\dtlauncher.exe");
Log("g", "dtlauncher.exe downloaded\n"); Log("g", "dtlauncher.exe downloaded\n");
mainSocket.FSP_Download("DTLib.dll", "TEMP\\DTLib.dll"); fsp.DownloadFile("DTLib.dll", "TEMP\\DTLib.dll");
Log("g", "DTLib.dll downloaded\n"); Log("g", "DTLib.dll downloaded\n");
Process.Start("cmd", "/c timeout 0 && copy TEMP\\dtlauncher.exe dtlauncher.exe && copy TEMP\\DTLib.dll DTLib.dll && start dtlauncher.exe updated"); Process.Start("cmd", "/c timeout 0 && copy TEMP\\dtlauncher.exe dtlauncher.exe && copy TEMP\\DTLib.dll DTLib.dll && start dtlauncher.exe updated");
} }
@ -56,10 +60,11 @@ namespace updater
{ {
// установка шрифтов // установка шрифтов
Log("installing fonts\n"); /*Log("installing fonts\n");
Process.Start("fonts\\fontinst.exe"); Process.Start("fonts\\fontinst.exe");
Filework.Directory.Delete("TEMP"); Directory.Delete("TEMP");*/
Log("deleted TEMP\n"); Log("deleted TEMP\n");
fsp.DownloadFile("dtlauncher-client-win.exe", "dtlauncher-client-win.exe");
Process.Start("dtlauncher-client-win.exe", "updated"); Process.Start("dtlauncher-client-win.exe", "updated");
} }
} }
@ -82,9 +87,9 @@ namespace updater
{ {
lock (new object()) lock (new object())
{ {
if (msg.Length == 1) Filework.LogToFile(logfile, msg[0]); if (msg.Length == 1) OldFilework.LogToFile(logfile, msg[0]);
else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n"); else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
else Filework.LogToFile(logfile, SimpleConverter.AutoBuild(msg)); else OldFilework.LogToFile(logfile, msg.MergeToString());
ColoredConsole.Write(msg); ColoredConsole.Write(msg);
} }
} }

View File

@ -76,7 +76,7 @@
<Content Include="logo-D.ico" /> <Content Include="logo-D.ico" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\DTLib\DTLib.csproj"> <ProjectReference Include="..\..\DTLib\DTLib.csproj">
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project> <Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
<Name>DTLib</Name> <Name>DTLib</Name>
</ProjectReference> </ProjectReference>