fixed dependencies

This commit is contained in:
Timerix22 2022-03-13 13:47:40 +03:00
parent 538db682f3
commit c201f11ce1
13 changed files with 867 additions and 959 deletions

63
.gitattributes vendored
View File

@ -1,63 +0,0 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain

730
.gitignore vendored
View File

@ -1,365 +1,365 @@
## Ignore Visual Studio temporary files, build results, and ## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons. ## files generated by popular Visual Studio add-ons.
## ##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files # User-specific files
*.rsuser *.rsuser
*.suo *.suo
*.user *.user
*.userosscache *.userosscache
*.sln.docstates *.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio) # User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs *.userprefs
# Mono auto generated files # Mono auto generated files
mono_crash.* mono_crash.*
# Build results # Build results
[Dd]ebug/ [Dd]ebug/
[Dd]ebugPublic/ [Dd]ebugPublic/
[Rr]elease/ [Rr]elease/
[Rr]eleases/ [Rr]eleases/
x64/ x64/
x86/ x86/
[Ww][Ii][Nn]32/ [Ww][Ii][Nn]32/
[Aa][Rr][Mm]/ [Aa][Rr][Mm]/
[Aa][Rr][Mm]64/ [Aa][Rr][Mm]64/
bld/ bld/
[Bb]in/ [Bb]in/
[Oo]bj/ [Oo]bj/
[Oo]ut/ [Oo]ut/
[Ll]og/ [Ll]og/
[Ll]ogs/ [Ll]ogs/
# Visual Studio 2015/2017 cache/options directory # Visual Studio 2015/2017 cache/options directory
.vs/ .vs/
.vshistory/ .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/
# Visual Studio 2017 auto generated files # Visual Studio 2017 auto generated files
Generated\ Files/ Generated\ Files/
# MSTest test Results # MSTest test Results
[Tt]est[Rr]esult*/ [Tt]est[Rr]esult*/
[Bb]uild[Ll]og.* [Bb]uild[Ll]og.*
# NUnit # NUnit
*.VisualState.xml *.VisualState.xml
TestResult.xml TestResult.xml
nunit-*.xml nunit-*.xml
# Build Results of an ATL Project # Build Results of an ATL Project
[Dd]ebugPS/ [Dd]ebugPS/
[Rr]eleasePS/ [Rr]eleasePS/
dlldata.c dlldata.c
# Benchmark Results # Benchmark Results
BenchmarkDotNet.Artifacts/ BenchmarkDotNet.Artifacts/
# .NET Core # .NET Core
project.lock.json project.lock.json
project.fragment.lock.json project.fragment.lock.json
artifacts/ artifacts/
# ASP.NET Scaffolding # ASP.NET Scaffolding
ScaffoldingReadMe.txt ScaffoldingReadMe.txt
# StyleCop # StyleCop
StyleCopReport.xml StyleCopReport.xml
# Files built by Visual Studio # Files built by Visual Studio
*_i.c *_i.c
*_p.c *_p.c
*_h.h *_h.h
*.ilk *.ilk
*.meta *.meta
*.obj *.obj
*.iobj *.iobj
*.pch *.pch
*.pdb *.pdb
*.ipdb *.ipdb
*.pgc *.pgc
*.pgd *.pgd
*.rsp *.rsp
*.sbr *.sbr
*.tlb *.tlb
*.tli *.tli
*.tlh *.tlh
*.tmp *.tmp
*.tmp_proj *.tmp_proj
*_wpftmp.csproj *_wpftmp.csproj
*.log *.log
*.vspscc *.vspscc
*.vssscc *.vssscc
.builds .builds
*.pidb *.pidb
*.svclog *.svclog
*.scc *.scc
*.editorconfig *.editorconfig
# Chutzpah Test files # Chutzpah Test files
_Chutzpah* _Chutzpah*
# Visual C++ cache files # Visual C++ cache files
ipch/ ipch/
*.aps *.aps
*.ncb *.ncb
*.opendb *.opendb
*.opensdf *.opensdf
*.sdf *.sdf
*.cachefile *.cachefile
*.VC.db *.VC.db
*.VC.VC.opendb *.VC.VC.opendb
# Visual Studio profiler # Visual Studio profiler
*.psess *.psess
*.vsp *.vsp
*.vspx *.vspx
*.sap *.sap
# Visual Studio Trace Files # Visual Studio Trace Files
*.e2e *.e2e
# TFS 2012 Local Workspace # TFS 2012 Local Workspace
$tf/ $tf/
# Guidance Automation Toolkit # Guidance Automation Toolkit
*.gpState *.gpState
# ReSharper is a .NET coding add-in # ReSharper is a .NET coding add-in
_ReSharper*/ _ReSharper*/
*.[Rr]e[Ss]harper *.[Rr]e[Ss]harper
*.DotSettings.user *.DotSettings.user
# TeamCity is a build add-in # TeamCity is a build add-in
_TeamCity* _TeamCity*
# DotCover is a Code Coverage Tool # DotCover is a Code Coverage Tool
*.dotCover *.dotCover
# AxoCover is a Code Coverage Tool # AxoCover is a Code Coverage Tool
.axoCover/* .axoCover/*
!.axoCover/settings.json !.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool # Coverlet is a free, cross platform Code Coverage Tool
coverage*.json coverage*.json
coverage*.xml coverage*.xml
coverage*.info coverage*.info
# Visual Studio code coverage results # Visual Studio code coverage results
*.coverage *.coverage
*.coveragexml *.coveragexml
# NCrunch # NCrunch
_NCrunch_* _NCrunch_*
.*crunch*.local.xml .*crunch*.local.xml
nCrunchTemp_* nCrunchTemp_*
# MightyMoose # MightyMoose
*.mm.* *.mm.*
AutoTest.Net/ AutoTest.Net/
# Web workbench (sass) # Web workbench (sass)
.sass-cache/ .sass-cache/
# Installshield output folder # Installshield output folder
[Ee]xpress/ [Ee]xpress/
# DocProject is a documentation generator add-in # DocProject is a documentation generator add-in
DocProject/buildhelp/ DocProject/buildhelp/
DocProject/Help/*.HxT DocProject/Help/*.HxT
DocProject/Help/*.HxC DocProject/Help/*.HxC
DocProject/Help/*.hhc DocProject/Help/*.hhc
DocProject/Help/*.hhk DocProject/Help/*.hhk
DocProject/Help/*.hhp DocProject/Help/*.hhp
DocProject/Help/Html2 DocProject/Help/Html2
DocProject/Help/html DocProject/Help/html
# Click-Once directory # Click-Once directory
publish/ publish/
# Publish Web Output # Publish Web Output
*.[Pp]ublish.xml *.[Pp]ublish.xml
*.azurePubxml *.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings, # Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted # but database connection strings (with potential passwords) will be unencrypted
*.pubxml *.pubxml
*.publishproj *.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to # Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained # checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted # in these scripts will be unencrypted
PublishScripts/ PublishScripts/
# NuGet Packages # NuGet Packages
*.nupkg *.nupkg
# NuGet Symbol Packages # NuGet Symbol Packages
*.snupkg *.snupkg
# The packages folder can be ignored because of Package Restore # The packages folder can be ignored because of Package Restore
**/[Pp]ackages/* **/[Pp]ackages/*
# except build/, which is used as an MSBuild target. # except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/ !**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed # Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config #!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files # NuGet v3's project.json files produces more ignorable files
*.nuget.props *.nuget.props
*.nuget.targets *.nuget.targets
# Microsoft Azure Build Output # Microsoft Azure Build Output
csx/ csx/
*.build.csdef *.build.csdef
# Microsoft Azure Emulator # Microsoft Azure Emulator
ecf/ ecf/
rcf/ rcf/
# Windows Store app package directories and files # Windows Store app package directories and files
AppPackages/ AppPackages/
BundleArtifacts/ BundleArtifacts/
Package.StoreAssociation.xml Package.StoreAssociation.xml
_pkginfo.txt _pkginfo.txt
*.appx *.appx
*.appxbundle *.appxbundle
*.appxupload *.appxupload
# Visual Studio cache files # Visual Studio cache files
# files ending in .cache can be ignored # files ending in .cache can be ignored
*.[Cc]ache *.[Cc]ache
# but keep track of directories ending in .cache # but keep track of directories ending in .cache
!?*.[Cc]ache/ !?*.[Cc]ache/
# Others # Others
ClientBin/ ClientBin/
~$* ~$*
*~ *~
*.dbmdl *.dbmdl
*.dbproj.schemaview *.dbproj.schemaview
*.jfm *.jfm
*.pfx *.pfx
*.publishsettings *.publishsettings
orleans.codegen.cs orleans.codegen.cs
# Including strong name files can present a security risk # Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424) # (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk #*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components # Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/ #bower_components/
# RIA/Silverlight projects # RIA/Silverlight projects
Generated_Code/ Generated_Code/
# Backup & report files from converting an old project file # Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed, # to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-) # because we have git ;-)
_UpgradeReport_Files/ _UpgradeReport_Files/
Backup*/ Backup*/
UpgradeLog*.XML UpgradeLog*.XML
UpgradeLog*.htm UpgradeLog*.htm
ServiceFabricBackup/ ServiceFabricBackup/
*.rptproj.bak *.rptproj.bak
# SQL Server files # SQL Server files
*.mdf *.mdf
*.ldf *.ldf
*.ndf *.ndf
# Business Intelligence projects # Business Intelligence projects
*.rdl.data *.rdl.data
*.bim.layout *.bim.layout
*.bim_*.settings *.bim_*.settings
*.rptproj.rsuser *.rptproj.rsuser
*- [Bb]ackup.rdl *- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl *- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl *- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes # Microsoft Fakes
FakesAssemblies/ FakesAssemblies/
# GhostDoc plugin setting file # GhostDoc plugin setting file
*.GhostDoc.xml *.GhostDoc.xml
# Node.js Tools for Visual Studio # Node.js Tools for Visual Studio
.ntvs_analysis.dat .ntvs_analysis.dat
node_modules/ node_modules/
# Visual Studio 6 build log # Visual Studio 6 build log
*.plg *.plg
# Visual Studio 6 workspace options file # Visual Studio 6 workspace options file
*.opt *.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw *.vbw
# Visual Studio LightSwitch build output # Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts **/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml **/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts **/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml **/*.Server/ModelManifest.xml
_Pvt_Extensions _Pvt_Extensions
# Paket dependency manager # Paket dependency manager
.paket/paket.exe .paket/paket.exe
paket-files/ paket-files/
# FAKE - F# Make # FAKE - F# Make
.fake/ .fake/
# CodeRush personal settings # CodeRush personal settings
.cr/personal .cr/personal
# Python Tools for Visual Studio (PTVS) # Python Tools for Visual Studio (PTVS)
__pycache__/ __pycache__/
*.pyc *.pyc
# Cake - Uncomment if you are using it # Cake - Uncomment if you are using it
# tools/** # tools/**
# !tools/packages.config # !tools/packages.config
# Tabs Studio # Tabs Studio
*.tss *.tss
# Telerik's JustMock configuration file # Telerik's JustMock configuration file
*.jmconfig *.jmconfig
# BizTalk build output # BizTalk build output
*.btp.cs *.btp.cs
*.btm.cs *.btm.cs
*.odx.cs *.odx.cs
*.xsd.cs *.xsd.cs
# OpenCover UI analysis results # OpenCover UI analysis results
OpenCover/ OpenCover/
# Azure Stream Analytics local run output # Azure Stream Analytics local run output
ASALocalRun/ ASALocalRun/
# MSBuild Binary and Structured Log # MSBuild Binary and Structured Log
*.binlog *.binlog
# NVidia Nsight GPU debugger configuration file # NVidia Nsight GPU debugger configuration file
*.nvuser *.nvuser
# MFractors (Xamarin productivity tool) working folder # MFractors (Xamarin productivity tool) working folder
.mfractor/ .mfractor/
# Local History for Visual Studio # Local History for Visual Studio
.localhistory/ .localhistory/
# BeatPulse healthcheck temp database # BeatPulse healthcheck temp database
healthchecksdb healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017 # Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/ MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder # Ionide (cross platform F# VS Code tools) working folder
.ionide/ .ionide/
# Fody - auto-generated XML schema # Fody - auto-generated XML schema
FodyWeavers.xsd FodyWeavers.xsd

View File

@ -87,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;
OldFilework.LogToFile(logfile, msg); File.AppendAllText(logfile, msg);
LogBox.Text += msg; LogBox.Text += msg;
} }

View File

@ -7,6 +7,7 @@ using DTLib;
using DTLib.Dtsod; using DTLib.Dtsod;
using DTLib.Filesystem; using DTLib.Filesystem;
using DTLib.Network; using DTLib.Network;
using DTLib.Extensions;
namespace dtlauncher_client_win namespace dtlauncher_client_win
{ {
@ -126,7 +127,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;
OldFilework.LogToFile(logfile, msg); File.AppendAllText(logfile, msg);
LogBox.Text += msg; LogBox.Text += msg;
} }

View File

@ -98,6 +98,9 @@
<Generator>ResXFileCodeGenerator</Generator> <Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput> <LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource> </EmbeddedResource>
<None Include="client.dtsod">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="Properties\Settings.settings"> <None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator> <Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput> <LastGenOutput>Settings.Designer.cs</LastGenOutput>
@ -107,7 +110,7 @@
<None Include="App.config" /> <None Include="App.config" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\DTLib\DTLib.csproj"> <ProjectReference Include="..\..\DTLib\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>
@ -122,8 +125,7 @@
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup> <PropertyGroup>
<PostBuildEvent>del /f /q dtlauncher-client-win.exe.config <PostBuildEvent>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 dtlauncher-client-win.exe ..\..\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 ..\..\dtlauncher-server-win\bin\share\client\client.dtsod</PostBuildEvent>
copy client.dtsod C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\client.dtsod</PostBuildEvent>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View File

@ -8,6 +8,7 @@ using DTLib;
using DTLib.Dtsod; using DTLib.Dtsod;
using DTLib.Filesystem; using DTLib.Filesystem;
using DTLib.Network; using DTLib.Network;
using DTLib.Extensions;
namespace dtlauncher_server namespace dtlauncher_server
{ {
@ -16,6 +17,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 DtsodV21 config; static DtsodV21 config;
static DTLib.Loggers.DefaultLogger Info = new("logs", "dtlaunchet_server");
//static readonly Dictionary<Socket, Thread> users = new(); //static readonly Dictionary<Socket, Thread> users = new();
@ -26,8 +28,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.LogEvent += Log; PublicLog.LogEvent += Info.Log;
PublicLog.LogNoTimeEvent += Log; PublicLog.LogNoTimeEvent += Info.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"))
@ -47,15 +49,15 @@ namespace dtlauncher_server
outBuilder.Append(file); outBuilder.Append(file);
outBuilder.Append("\");\n"); outBuilder.Append("\");\n");
} }
Log("c", "\n\n" + outBuilder.ToString() + "\n\n");*/ Info.Log("c", "\n\n" + outBuilder.ToString() + "\n\n");*/
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", Info.Log("b", "local address: <", "c", config["server_ip"], "b",
">\npublic address: <", "c", OldNetwork.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);
Log("g", "server started succesfully\n"); Info.Log("g", "server started succesfully\n");
// //
/*DTLib.Timer userCkeckTimer = new(true, 3000, () => /*DTLib.Timer userCkeckTimer = new(true, 3000, () =>
{ {
@ -63,7 +65,7 @@ namespace dtlauncher_server
{ {
if (usr.) if (usr.)
{ {
Log("y", $"closing unused user <{usr.RemoteEndPoint.Serialize()[0]}> thread\n"); Info.Log("y", $"closing unused user <{usr.RemoteEndPoint.Serialize()[0]}> thread\n");
users[usr].Abort(); users[usr].Abort();
users.Remove(usr); users.Remove(usr);
} }
@ -80,36 +82,18 @@ namespace dtlauncher_server
} }
catch (Exception ex) catch (Exception ex)
{ {
Log("r", $"dtlauncher_server.Main() error:\n{ex.Message}\n{ex.StackTrace}\n"); Info.Log("r", $"dtlauncher_server.Main() error:\n{ex.Message}\n{ex.StackTrace}\n");
mainSocket.Close(); mainSocket.Close();
} }
Log("press any key to close... "); Info.Log("press any key to close... ");
Console.ReadKey(); Console.ReadKey();
Log("gray", "\n"); Info.Log("gray", "\n");
}
// вывод лога в консоль и файл
public static void Log(params string[] msg)
{
if (msg.Length == 1) msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
else msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
LogNoTime(msg);
}
public static void LogNoTime(params string[] msg)
{
lock (new object())
{
if (msg.Length == 1) OldFilework.LogToFile(logfile, msg[0]);
else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
else OldFilework.LogToFile(logfile, msg.MergeToString());
ColoredConsole.Write(msg);
}
} }
// запускается для каждого юзера в отдельном потоке // запускается для каждого юзера в отдельном потоке
static void UserHandle(Socket handlerSocket) static void UserHandle(Socket handlerSocket)
{ {
Log("b", "user connecting... "); Info.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); FSP fsp = new(handlerSocket);
@ -120,9 +104,9 @@ namespace dtlauncher_server
// запрос от апдейтера // запрос от апдейтера
if (hash.HashToString() == "ffffffffffffffff") if (hash.HashToString() == "ffffffffffffffff")
{ {
LogNoTime("c", "client is updater\n"); Info.LogNoTime("c", "client is updater\n");
CreateManifest("share\\client\\"); CreateManifest("share\\client\\");
Log("g", "client files manifest created\n"); Info.Log("g", "client files manifest created\n");
handlerSocket.SendPackage("updater".ToBytes()); handlerSocket.SendPackage("updater".ToBytes());
while (true) while (true)
{ {
@ -137,16 +121,16 @@ namespace dtlauncher_server
fsp.UploadFile(filepath); fsp.UploadFile(filepath);
break; break;
case "register new user": case "register new user":
Log("b", "new user registration requested\n"); Info.Log("b", "new user registration requested\n");
handlerSocket.SendPackage("ok".ToBytes()); handlerSocket.SendPackage("ok".ToBytes());
//filepath = handlerSocket.GetPackage().BytesToString(); //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"); //Info.Log("b", $"downloading file registration_requests\\{filepath}\n");
//handlerSocket.FSP_Download($"registration_requests\\{filepath}"); //handlerSocket.FSP_Download($"registration_requests\\{filepath}");
recieved = handlerSocket.GetPackage().BytesToString(); 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"); Info.Log("b", $"text wrote to file <", "c", "registration_requests\\{filepath}", "b", ">\n");
break; break;
default: default:
throw new Exception("unknown request: " + request); throw new Exception("unknown request: " + request);
@ -158,14 +142,14 @@ namespace dtlauncher_server
// запрос от лаунчера // запрос от лаунчера
else else
{ {
LogNoTime("c", "client is launcher\n"); Info.LogNoTime("c", "client is launcher\n");
string login; string login;
lock (new object()) lock (new object())
{ {
login = OldFilework.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"); Info.Log("g", "user <", "c", login, "g", "> succesfully logined\n");
while (true) while (true)
{ {
if (handlerSocket.Available >= 64) if (handlerSocket.Available >= 64)
@ -194,7 +178,7 @@ namespace dtlauncher_server
} }
catch (Exception ex) catch (Exception ex)
{ {
Log("y", $"UserStart() error:\n message:\n {ex.Message}\n{ex.StackTrace}\n"); Info.Log("y", $"UserStart() error:\n message:\n {ex.Message}\n{ex.StackTrace}\n");
handlerSocket.Shutdown(SocketShutdown.Both); handlerSocket.Shutdown(SocketShutdown.Both);
handlerSocket.Close(); handlerSocket.Close();
Thread.CurrentThread.Abort(); Thread.CurrentThread.Abort();

View File

@ -83,7 +83,9 @@
<Generator>SettingsSingleFileGenerator</Generator> <Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput> <LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None> </None>
<None Include="server.dtsod" /> <None Include="server.dtsod">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<None Include="App.config" /> <None Include="App.config" />
@ -101,14 +103,13 @@
</BootstrapperPackage> </BootstrapperPackage>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\DTLib\DTLib.csproj"> <ProjectReference Include="..\..\DTLib\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>
</ItemGroup> </ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup> <PropertyGroup>
<PostBuildEvent>del /f /q dtlauncher-server-win.exe.config <PostBuildEvent>del /f /q dtlauncher-server-win.exe.config</PostBuildEvent>
copy C:\projects\c#\dtlauncher\dtlauncher-server-win\server.dtsod server.dtsod</PostBuildEvent>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

View File

@ -17,7 +17,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "updater", "updater\updater.
EndProject 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}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DTLib", "..\DTLib\DTLib\DTLib.csproj", "{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Sulution Files", "Sulution Files", "{09AA971D-CD70-4D93-BBA9-810C842830D8}"
ProjectSection(SolutionItems) = preProject
.gitignore = .gitignore
EndProjectSection
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
@ -32,8 +37,8 @@ Global
{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
{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.ActiveCfg = Release-net48|Any CPU
{CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.Build.0 = Build|Any CPU {CE793497-2D5C-42D8-B311-E9B32AF9CDFB}.Build|Any CPU.Build.0 = Release-net48|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE

View File

@ -2,54 +2,32 @@
using DTLib; using DTLib;
using DTLib.Filesystem; using DTLib.Filesystem;
namespace DTScript namespace DTScript;
public class MainClass
{ {
public class MainClass static DTLib.Loggers.DefaultLogger Info = new("logs", "dtlaunchet_server");
static void Main(string[] args)
{ {
static void Main(string[] args) try
{ {
try Directory.Create("dtscript-logs");
PublicLog.LogEvent += Info.Log;
PublicLog.LogNoTimeEvent += Info.Log;
var scripter = new ScriptRunner();
if (args.Length == 0 || args.Length > 2) throw new Exception("enter script file path\n");
else if (args.Length == 1) scripter.RunScriptFile(args[0]);
else if (args.Length == 2 && args[0] == "-debug")
{ {
Directory.Create("dtscript-logs"); scripter.debug = true;
PublicLog.LogEvent += Log; scripter.Debug("y", "debug is enabled\n");
PublicLog.LogNoTimeEvent += Log; scripter.RunScriptFile(args[1]);
var scripter = new ScriptRunner();
if (args.Length == 0 || args.Length > 2) throw new Exception("enter script file path\n");
else if (args.Length == 1) scripter.RunScriptFile(args[0]);
else if (args.Length == 2 && args[0] == "-debug")
{
scripter.debug = true;
scripter.Debug("y", "debug is enabled\n");
scripter.RunScriptFile(args[1]);
}
else throw new Exception("unknown args\n");
} }
catch (Exception ex) else throw new Exception("unknown args\n");
{
Log("r", $"dtscript.Main() error:\n{ex.Message}\n{ex.StackTrace}\n");
}
Log("gray", " \n");
}
// вывод лога в консоль и файл
static readonly string logfile = $"dtscript-logs\\dtscript-{DateTime.Now}.log".Replace(':', '-').Replace(' ', '_');
static void Log(params string[] msg)
{
if (msg.Length == 1)
{
msg[0] = "[" + DateTime.Now.ToString() + "]: " + msg[0];
OldFilework.LogToFile(logfile, msg[0]);
}
else if (msg.Length % 2 != 0) throw new Exception("incorrect array to log\n");
else
{
msg[1] = "[" + DateTime.Now.ToString() + "]: " + msg[1];
var str = new System.Text.StringBuilder();
for (int i = 0; i < msg.Length; i++) str.Append(msg[++i]);
OldFilework.LogToFile(logfile, str.ToString());
}
ColoredConsole.Write(msg);
} }
catch (Exception ex)
{ Info.Log("r", $"dtscript.Main() error:\n{ex.Message}\n{ex.StackTrace}\n"); }
Info.Log("gray", " \n");
} }
} }

View File

@ -2,465 +2,464 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Net.Sockets; using System.Net.Sockets;
using System.Linq;
using DTLib; using DTLib;
using DTLib.Filesystem; using DTLib.Filesystem;
using DTLib.Network; using DTLib.Network;
namespace DTScript namespace DTScript;
//
// основной класс скриптового интерпретатора
//
public class ScriptRunner
{ {
// // выводит текст через DTLib если дебаг включен
// основной класс скриптового интерпретатора public bool debug = false;
// public Socket mainSocket;
public class ScriptRunner public FSP fsp;
internal void Debug(params string[] msg)
{ {
// выводит текст через DTLib если дебаг включен if (debug) PublicLog.Log(msg);
public bool debug = false; }
public Socket mainSocket;
public FSP fsp;
internal void Debug(params string[] msg) // cчитывание текста из файла и запуск выполнения
{ public void RunScriptFile(string scriptfile)
if (debug) PublicLog.Log(msg); {
} Debug("g", @"----\ " + scriptfile + " /----\n");
try { Execute(SplitScript(File.ReadAllText(scriptfile))); }
catch (Exception e) { PublicLog.Log("r", $"dtscript RunScriptFile() error:\n{e.Message}\n{e.StackTrace}\n", "gray", " \n"); }
}
// cчитывание текста из файла и запуск выполнения int globalindex = -1;
public void RunScriptFile(string scriptfile) List<Dictionary<string, object>> Storage = new();
{
Debug("g", @"----\ " + scriptfile + " /----\n");
try { Execute(SplitScript(File.ReadAllText(scriptfile))); }
catch (Exception e) { PublicLog.Log("r", $"dtscript RunScriptFile() error:\n{e.Message}\n{e.StackTrace}\n", "gray", " \n"); }
}
int globalindex = -1; object GetValue(string key)
List<Dictionary<string, object>> Storage = new(); {
Debug("m", "GetValue(", "c", "<", "b", key, "c", ">", "m", ")\n");
for (int i = 0; i <= globalindex; i++)
if (Storage[i].ContainsKey(key)) return Storage[i][key];
throw new Exception($"GetValue() exception: storage doesn't contain key<{key}>");
}
object GetValue(string key) void SetValue(string key, object value)
{ {
Debug("m", "GetValue(", "c", "<", "b", key, "c", ">", "m", ")\n"); Debug("m", "SetValue(", "c", "<", "b", key, "c", "> ", "c", "<", "b", value.ToString(), "c", ">", "m", ")\n");
for (int i = 0; i <= globalindex; i++) for (int i = 0; i <= globalindex; i++)
if (Storage[i].ContainsKey(key)) return Storage[i][key]; if (Storage[i].ContainsKey(key))
throw new Exception($"GetValue() exception: storage doesn't contain key<{key}>");
}
void SetValue(string key, object value)
{
Debug("m", "SetValue(", "c", "<", "b", key, "c", "> ", "c", "<", "b", value.ToString(), "c", ">", "m", ")\n");
for (int i = 0; i <= globalindex; i++)
if (Storage[i].ContainsKey(key))
{
Storage[i][key] = value;
Debug(Storage[i][key].ToString());
return;
}//throw new Exception($"SetValue() exception: storage alredy contains key<{key}>");
Storage[globalindex].Add(key, value);
}
dynamic Execute(List<Construction> script)
{
Debug("y", " executing...\n");
// создание локального
globalindex++;
List<Construction> subscript;
Storage.Add(new Dictionary<string, object>());
// запуск цикла
for (int index = 0; index < script.Count; index++)
{ {
if (debug) Storage[i][key] = value;
{ Debug(Storage[i][key].ToString());
PublicLog.Log(new string[] { return;
}//throw new Exception($"SetValue() exception: storage alredy contains key<{key}>");
Storage[globalindex].Add(key, value);
}
dynamic Execute(List<Construction> script)
{
Debug("y", " executing...\n");
// создание локального
globalindex++;
List<Construction> subscript;
Storage.Add(new Dictionary<string, object>());
// запуск цикла
for (int index = 0; index < script.Count; index++)
{
if (debug)
{
PublicLog.Log(new string[] {
"y","\noperator: ", "m",script[index].Operator, "y"," options: ", "c", "<", "b", script[index].Options[0], "c", ">"}); "y","\noperator: ", "m",script[index].Operator, "y"," options: ", "c", "<", "b", script[index].Options[0], "c", ">"});
for (ushort n = 1; n < script[index].Options.Length; n++) for (ushort n = 1; n < script[index].Options.Length; n++)
PublicLog.Log("w", ", ", "c", "<", "b", script[index].Options[n], "c", ">"); PublicLog.Log("w", ", ", "c", "<", "b", script[index].Options[n], "c", ">");
PublicLog.Log("\n"); PublicLog.Log("\n");
} }
switch (script[index].Operator) switch (script[index].Operator)
{
case "return":
Debug("g", "script ended");
return GetValue(script[index].Options[0]);
case "Run":
var proc = new Process();
proc.StartInfo.FileName = script[index].Options[0].Replace("\"", "");
proc.StartInfo.Arguments = script[index].Options[1].Replace("\"", "");
/*if (script[index].Options.Length == 3 && script[index].Options[2] == "true")
{
proc.StartInfo.CreateNoWindow = true;
Debug("g", $"process {script[index].Operator} started in hidden mode\n");
}
else if (script[index].Options.Length == 3 && script[index].Options[2] == "false")
{
proc.StartInfo.CreateNoWindow = false;
Debug("g", $"process {script[index].Operator} started in not hidden mode\n");
}
else throw new Exception("invalid arguments in Run().\n it must be: Run(string exe_file, string arguments, true/false nowindow)\n");
proc.StartInfo.UseShellExecute = false;*/
proc.Start();
proc.WaitForExit();
proc.Close();
break;
case "Log":
Debug("y", $"Log() has {script[index].Options.Length} args\n");
PublicLog.Log(CalcString(script[index].Options.ToList()));
break;
case "ShowFiles":
Debug("y", $"Log() has {script[index].Options.Length} args\n");
foreach (string file in Directory.GetFiles(CalcString(script[index].Options.ToList())))
PublicLog.Log(file + '\n');
break;
case "bool":
if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
{
List<string> expr = new();
for (ushort n = 2; n < script[index].Options.Length; n++)
expr.Add(script[index].Options[n]);
// сравнение и добавление результата в storage[globalindex]
SetValue(script[index].Options[0], Compare(expr));
Debug(new string[] {"y"," bool ","b", script[index].Options[0],
"w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
}
else throw new Exception("error: incorrect bool defination\n");
break;
case "num":
if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
{
List<string> expr = new();
for (ushort n = 2; n < script[index].Options.Length; n++)
{
expr.Add(script[index].Options[n]);
}
SetValue(script[index].Options[0], (double)Calc(expr));
Debug(new string[] {"y"," num ","b", script[index].Options[0],
"w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
}
else throw new Exception("Execute() error: incorrect double defination\n");
break;
case "string":
if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
{
List<string> expr = new();
for (ushort n = 2; n < script[index].Options.Length; n++)
{
expr.Add(script[index].Options[n]);
}
SetValue(script[index].Options[0], CalcString(expr));
Debug(new string[] {"y"," string ","b", script[index].Options[0],
"w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
}
break;
case "while":
if (script[index + 1].Operator != "{") throw new Exception("Execute() error: expect { after for()");
subscript = SplitScript(script[index + 1].Options[0]);
while (Compare(script[index].Options.ToList()))
{
Execute(subscript);
}
index++;
break;
case "if":
if (script[index + 1].Operator != "{") throw new Exception("Execute() error: expect { after for()");
subscript = SplitScript(script[index + 1].Options[0]);
if (Compare(script[index].Options.ToList()))
{
Execute(subscript);
}
index++;
break;
case "Download":
if (fsp is null) fsp = new(mainSocket);
fsp.DownloadFile(script[index].Options[0], script[index].Options[1]);
break;
case "DirDelete":
Directory.Delete(script[index].Options[0]);
break;
case "FileDelete":
File.Delete(script[index].Options[0]);
break;
case "FileWrite":
File.Create(script[index].Options[0]);
File.WriteAllText(script[index].Options[0], script[index].Options[1]);
break;
case "FileAppend":
File.Create(script[index].Options[0]);
File.AppendAllText(script[index].Options[0], script[index].Options[1]);
break;
default:
throw new Exception($"Execute() error: invalid construct: {script[index].Operator}\n");
}
}
Storage.RemoveAt(globalindex);
globalindex--;
return null;
// операции со строками
string CalcString(List<string> expr)
{
Debug("m", "CalcString(");
foreach (string part in expr)
Debug("c", "<", "b", part, "c", ">");
Debug("m", ")", "y", " started\n");
// извлечение значений переменных
for (ushort n = 0; n < expr.Count; n++)
{
switch (expr[n][0])
{ {
case "return": case '+':
Debug("g", "script ended");
return GetValue(script[index].Options[0]);
case "Run":
var proc = new Process();
proc.StartInfo.FileName = script[index].Options[0].Replace("\"", "");
proc.StartInfo.Arguments = script[index].Options[1].Replace("\"", "");
/*if (script[index].Options.Length == 3 && script[index].Options[2] == "true")
{
proc.StartInfo.CreateNoWindow = true;
Debug("g", $"process {script[index].Operator} started in hidden mode\n");
}
else if (script[index].Options.Length == 3 && script[index].Options[2] == "false")
{
proc.StartInfo.CreateNoWindow = false;
Debug("g", $"process {script[index].Operator} started in not hidden mode\n");
}
else throw new Exception("invalid arguments in Run().\n it must be: Run(string exe_file, string arguments, true/false nowindow)\n");
proc.StartInfo.UseShellExecute = false;*/
proc.Start();
proc.WaitForExit();
proc.Close();
break; break;
case "Log": case '"':
Debug("y", $"Log() has {script[index].Options.Length} args\n"); if (!expr[n].EndsWith("\"")) throw new Exception("Calc() error: invalid value <" + expr[n] + ">\n");
PublicLog.Log(CalcString(script[index].Options.ToList()));
break;
case "ShowFiles":
Debug("y", $"Log() has {script[index].Options.Length} args\n");
foreach (string file in Directory.GetFiles(CalcString(script[index].Options.ToList())))
PublicLog.Log(file + '\n');
break;
case "bool":
if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
{
List<string> expr = new();
for (ushort n = 2; n < script[index].Options.Length; n++)
expr.Add(script[index].Options[n]);
// сравнение и добавление результата в storage[globalindex]
SetValue(script[index].Options[0], Compare(expr));
Debug(new string[] {"y"," bool ","b", script[index].Options[0],
"w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
}
else throw new Exception("error: incorrect bool defination\n");
break;
case "num":
if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
{
List<string> expr = new();
for (ushort n = 2; n < script[index].Options.Length; n++)
{
expr.Add(script[index].Options[n]);
}
SetValue(script[index].Options[0], (double)Calc(expr));
Debug(new string[] {"y"," num ","b", script[index].Options[0],
"w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
}
else throw new Exception("Execute() error: incorrect double defination\n");
break;
case "string":
if (script[index].Options.Length > 2 && script[index].Options[1] == "=")
{
List<string> expr = new();
for (ushort n = 2; n < script[index].Options.Length; n++)
{
expr.Add(script[index].Options[n]);
}
SetValue(script[index].Options[0], CalcString(expr));
Debug(new string[] {"y"," string ","b", script[index].Options[0],
"w", " = ", "c", GetValue(script[index].Options[0]).ToString() + '\n'});
}
break;
case "while":
if (script[index + 1].Operator != "{") throw new Exception("Execute() error: expect { after for()");
subscript = SplitScript(script[index + 1].Options[0]);
while (Compare(script[index].Options.ToList()))
{
Execute(subscript);
}
index++;
break;
case "if":
if (script[index + 1].Operator != "{") throw new Exception("Execute() error: expect { after for()");
subscript = SplitScript(script[index + 1].Options[0]);
if (Compare(script[index].Options.ToList()))
{
Execute(subscript);
}
index++;
break;
case "Download":
if (fsp is null) fsp = new(mainSocket);
fsp.DownloadFile(script[index].Options[0], script[index].Options[1]);
break;
case "DirDelete":
Directory.Delete(script[index].Options[0]);
break;
case "FileDelete":
File.Delete(script[index].Options[0]);
break;
case "FileWrite":
File.Create(script[index].Options[0]);
File.WriteAllText(script[index].Options[0], script[index].Options[1]);
break;
case "FileAppend":
File.Create(script[index].Options[0]);
File.AppendAllText(script[index].Options[0], script[index].Options[1]);
break; break;
default: default:
throw new Exception($"Execute() error: invalid construct: {script[index].Operator}\n"); expr[n] = GetValue(expr[n]).ToString();
break;
} }
} }
Storage.RemoveAt(globalindex); // вычисление
globalindex--; string rezult = "";
return null; for (ushort i = 0; i < expr.Count; i++)
// операции со строками
string CalcString(List<string> expr)
{ {
Debug("m", "CalcString(");
foreach (string part in expr)
Debug("c", "<", "b", part, "c", ">");
Debug("m", ")", "y", " started\n");
// извлечение значений переменных
for (ushort n = 0; n < expr.Count; n++)
{
switch (expr[n][0])
{
case '+':
break;
case '"':
if (!expr[n].EndsWith("\"")) throw new Exception("Calc() error: invalid value <" + expr[n] + ">\n");
break;
default:
expr[n] = GetValue(expr[n]).ToString();
break;
}
}
// вычисление
string rezult = "";
for (ushort i = 0; i < expr.Count; i++)
{
if (expr[i] == "+") if (expr[i] == "+")
{ {
i++;
rezult += expr[i];
}
else rezult = i == 0 ? expr[0] : throw new Exception($"error in Calc(): arg {expr[i]}\n");
}
if (rezult.Contains("\\n")) rezult = rezult.Replace("\\n", "\n");
if (rezult.Contains("\"")) rezult = rezult.Replace("\"", "");
Debug("y", " returns <", "b", $"{rezult}", "y", ">\n");
return rezult;
}
// операции с числами
double Calc(List<string> expr)
{
Debug("m", "Calc(");
foreach (string part in expr)
Debug("c", "<", "b", part, "c", ">");
Debug("m", ")", "y", " started\n");
// извлечение значений переменных
for (ushort n = 0; n < expr.Count; n++)
{
switch (expr[n][0])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '+':
case '-':
case '*':
case '/':
break;
default:
expr[n] = GetValue(expr[n]).ToString();
break;
}
}
// вычисление
double rezult = new();
for (ushort i = 0; i < expr.Count; i++)
switch (expr[i][0])
{
case '+':
i++; i++;
rezult += expr[i]; rezult += Convert.ToDouble(expr[i]);
}
else if (i == 0) rezult = expr[0];
else throw new Exception($"error in Calc(): arg {expr[i]}\n");
}
if (rezult.Contains("\\n")) rezult = rezult.Replace("\\n", "\n");
if (rezult.Contains("\"")) rezult = rezult.Replace("\"", "");
Debug("y", " returns <", "b", $"{rezult}", "y", ">\n");
return rezult;
}
// операции с числами
double Calc(List<string> expr)
{
Debug("m", "Calc(");
foreach (string part in expr)
Debug("c", "<", "b", part, "c", ">");
Debug("m", ")", "y", " started\n");
// извлечение значений переменных
for (ushort n = 0; n < expr.Count; n++)
{
switch (expr[n][0])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '+':
case '-':
case '*':
case '/':
break;
default:
expr[n] = GetValue(expr[n]).ToString();
break;
}
}
// вычисление
double rezult = new();
for (ushort i = 0; i < expr.Count; i++)
switch (expr[i][0])
{
case '+':
i++;
rezult += Convert.ToDouble(expr[i]);
break;
case '-':
i++;
rezult -= Convert.ToDouble(expr[i]);
break;
case '*':
i++;
rezult *= Convert.ToDouble(expr[i]);
break;
case '/':
i++;
rezult /= Convert.ToDouble(expr[i]);
break;
default:
if (i == 0) rezult += Convert.ToDouble(expr[i]);
else throw new Exception($"error in Calc(): arg {expr[i]}\n");
break;
}
Debug("y", " returns <", "b", $"{rezult}", "y", ">\n");
return rezult;
}
// сравнение
bool Compare(List<string> expr)
{
Debug("m", "Compare(");
foreach (string part in expr)
Debug("c", "<", "b", part, "c", ">");
Debug("m", ")", "y", " started\n");
// вычисление значений правой и левой части неравенства
char act = '\0';
double rezult_0 = new(), rezult_1;
var _expr = new List<string>();
for (ushort n = 0; n < expr.Count; n++)
{
Debug("m", $" <{expr[n]}>\n");
switch (expr[n][0])
{
case '<':
case '>':
act = expr[n][0];
rezult_0 = Calc(_expr);
_expr.Clear();
break;
case '!':
case '=':
act = expr[n][0];
rezult_0 = Calc(_expr);
_expr.Clear();
n++;
break;
default:
_expr.Add(expr[n]);
break;
}
}
Debug("y", " rezult_0 = <", "b", rezult_0.ToString(), "y", ">\n");
rezult_1 = Calc(_expr);
Debug("y", " rezult_1 = <", "b", rezult_1.ToString(), "y", ">\n");
Debug("y", " act = <", "b", act.ToString(), "y", ">\n");
bool output = act switch
{
'<' => rezult_0 < rezult_1,
'>' => rezult_0 > rezult_1,
'!' => rezult_0 != rezult_1,
'=' => rezult_0 == rezult_1,
_ => throw new Exception($"error: incorrect comparsion symbol: <{act}>\n"),
};
Debug("y", " return <", "c", $"{output}", "y", ">\n");
return output;
}
}
List<Construction> SplitScript(string text)
{
// лист для хранения обработанного текста
List<Construction> script = new();
string construct = "";
string option = "";
List<string> options = new();
for (int index = 0; index < text.Length; index++)
{
switch (text[index])
{
// конец распознания конструкта
case ';':
Debug(text[index].ToString() + '\n');
// добавление конструкта и его параметров в лист
if (construct != "") script.Add(new Construction(construct, options));
construct = "";
option = "";
options.Clear();
break; break;
// распознание параметров конструкта case '-':
case '(': i++;
Debug(text[index].ToString()); rezult -= Convert.ToDouble(expr[i]);
while (text[index] != ')')
{
index++;
switch (text[index])
{
case '"':
Debug("g", text[index].ToString());
do
{
option += text[index];
index++;
Debug("g", text[index].ToString());
} while (text[index] != '"');
option += text[index];
break;
case ' ':
case '\t':
case '\r':
case '\n':
break;
case ')':
case ',':
Debug(text[index].ToString());
options.Add(option);
option = "";
break;
// математика
case '+':
case '-':
case '*':
case '/':
case '!':
case '=':
Debug(text[index].ToString());
if (option != "") options.Add(option);
option = "";
options.Add(text[index].ToString());
break;
default:
option += text[index];
Debug("c", text[index].ToString());
break;
}
}
if (debug && text[index + 1] == ';') PublicLog.Log("y", "\n " + options.Count + " options have read\n");
break; break;
// очистка конструкта от лишних символов case '*':
case ' ': i++;
case '\t': rezult *= Convert.ToDouble(expr[i]);
case '\r':
case '\n':
break; break;
// case '/':
case '{': i++;
Debug("SplitScript() found <{>"); rezult /= Convert.ToDouble(expr[i]);
// добавление конструкта и его параметров в лист
if (construct != "") script.Add(new Construction(construct, options));
options.Clear();
option = "";
construct = "";
index++;
short bracketBalance = 1;
while (bracketBalance != 0)
{
if (text[index] == '{') bracketBalance++;
if (text[index] == '}') bracketBalance--;
option += text[index];
index++;
}
option.Remove(option.Length - 1);
script.Add(new Construction("{", new List<string> { option }));
option = "";
break;
case '}':
//throw new Exception($"SplitScript() error: unexpected '}}' on line {line}\n");
break; break;
default: default:
construct += text[index]; if (i == 0) rezult += Convert.ToDouble(expr[i]);
Debug("m", text[index].ToString()); else throw new Exception($"error in Calc(): arg {expr[i]}\n");
break;
}
Debug("y", " returns <", "b", $"{rezult}", "y", ">\n");
return rezult;
}
// сравнение
bool Compare(List<string> expr)
{
Debug("m", "Compare(");
foreach (string part in expr)
Debug("c", "<", "b", part, "c", ">");
Debug("m", ")", "y", " started\n");
// вычисление значений правой и левой части неравенства
char act = '\0';
double rezult_0 = new(), rezult_1;
var _expr = new List<string>();
for (ushort n = 0; n < expr.Count; n++)
{
Debug("m", $" <{expr[n]}>\n");
switch (expr[n][0])
{
case '<':
case '>':
act = expr[n][0];
rezult_0 = Calc(_expr);
_expr.Clear();
break;
case '!':
case '=':
act = expr[n][0];
rezult_0 = Calc(_expr);
_expr.Clear();
n++;
break;
default:
_expr.Add(expr[n]);
break; break;
} }
} }
// возврат листа Debug("y", " rezult_0 = <", "b", rezult_0.ToString(), "y", ">\n");
return script; rezult_1 = Calc(_expr);
} Debug("y", " rezult_1 = <", "b", rezult_1.ToString(), "y", ">\n");
Debug("y", " act = <", "b", act.ToString(), "y", ">\n");
class Construction bool output = act switch
{
public string Operator { get; private set; }
public string[] Options { get; private set; }
public Construction(string oper, List<string> opts)
{ {
Operator = oper; '<' => rezult_0 < rezult_1,
Options = opts.ToArray(); '>' => rezult_0 > rezult_1,
} '!' => rezult_0 != rezult_1,
'=' => rezult_0 == rezult_1,
_ => throw new Exception($"error: incorrect comparsion symbol: <{act}>\n"),
};
Debug("y", " return <", "c", $"{output}", "y", ">\n");
return output;
} }
} }
}
List<Construction> SplitScript(string text)
{
// лист для хранения обработанного текста
List<Construction> script = new();
string construct = "";
string option = "";
List<string> options = new();
for (int index = 0; index < text.Length; index++)
{
switch (text[index])
{
// конец распознания конструкта
case ';':
Debug(text[index].ToString() + '\n');
// добавление конструкта и его параметров в лист
if (construct != "") script.Add(new Construction(construct, options));
construct = "";
option = "";
options.Clear();
break;
// распознание параметров конструкта
case '(':
Debug(text[index].ToString());
while (text[index] != ')')
{
index++;
switch (text[index])
{
case '"':
Debug("g", text[index].ToString());
do
{
option += text[index];
index++;
Debug("g", text[index].ToString());
} while (text[index] != '"');
option += text[index];
break;
case ' ':
case '\t':
case '\r':
case '\n':
break;
case ')':
case ',':
Debug(text[index].ToString());
options.Add(option);
option = "";
break;
// математика
case '+':
case '-':
case '*':
case '/':
case '!':
case '=':
Debug(text[index].ToString());
if (option != "") options.Add(option);
option = "";
options.Add(text[index].ToString());
break;
default:
option += text[index];
Debug("c", text[index].ToString());
break;
}
}
if (debug && text[index + 1] == ';') PublicLog.Log("y", "\n " + options.Count + " options have read\n");
break;
// очистка конструкта от лишних символов
case ' ':
case '\t':
case '\r':
case '\n':
break;
//
case '{':
Debug("SplitScript() found <{>");
// добавление конструкта и его параметров в лист
if (construct != "") script.Add(new Construction(construct, options));
options.Clear();
option = "";
construct = "";
index++;
short bracketBalance = 1;
while (bracketBalance != 0)
{
if (text[index] == '{') bracketBalance++;
if (text[index] == '}') bracketBalance--;
option += text[index];
index++;
}
option.Remove(option.Length - 1);
script.Add(new Construction("{", new List<string> { option }));
option = "";
break;
case '}':
//throw new Exception($"SplitScript() error: unexpected '}}' on line {line}\n");
break;
default:
construct += text[index];
Debug("m", text[index].ToString());
break;
}
}
// возврат листа
return script;
}
class Construction
{
public string Operator { get; private set; }
public string[] Options { get; private set; }
public Construction(string oper, List<string> opts)
{
Operator = oper;
Options = opts.ToArray();
}
}
}

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\DTLib.csproj">
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project> <Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
<Name>DTLib</Name> <Name>DTLib</Name>
</ProjectReference> </ProjectReference>
@ -89,7 +89,7 @@
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup> <PropertyGroup>
<PostBuildEvent>del /q /f dtscript.exe.config <PostBuildEvent>del /q /f dtscript.exe.config
copy dtscript.exe C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\dtscript.exe</PostBuildEvent> copy dtscript.exe ..\..\dtlauncher-server-win\bin\share\client\dtscript.exe</PostBuildEvent>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<PreBuildEvent> <PreBuildEvent>

View File

@ -6,6 +6,7 @@ using System.Text;
using DTLib; using DTLib;
using DTLib.Filesystem; using DTLib.Filesystem;
using DTLib.Network; using DTLib.Network;
using DTLib.Extensions;
namespace updater namespace updater
{ {
@ -87,9 +88,9 @@ namespace updater
{ {
lock (new object()) lock (new object())
{ {
if (msg.Length == 1) OldFilework.LogToFile(logfile, msg[0]); if (msg.Length == 1) File.AppendAllText(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 OldFilework.LogToFile(logfile, msg.MergeToString()); else File.AppendAllText(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\DTLib.csproj">
<Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project> <Project>{ce793497-2d5c-42d8-b311-e9b32af9cdfb}</Project>
<Name>DTLib</Name> <Name>DTLib</Name>
</ProjectReference> </ProjectReference>
@ -84,10 +84,10 @@
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" /> <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup> <PropertyGroup>
<PostBuildEvent>del /f /q dtlauncher.exe.config <PostBuildEvent>del /f /q dtlauncher.exe.config
copy dtlauncher.exe C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\dtlauncher.exe copy dtlauncher.exe ..\..\dtlauncher-server-win\bin\share\client\dtlauncher.exe
copy DTLib.dll C:\projects\c#\dtlauncher\dtlauncher-server-win\bin\share\client\DTLib.dll copy DTLib.dll ..\..\dtlauncher-server-win\bin\share\client\DTLib.dll
copy dtlauncher.exe C:\projects\c#\dtlauncher\release\dtlauncher.exe copy dtlauncher.exe ..\..\release\dtlauncher.exe
copy DTLib.dll C:\projects\c#\dtlauncher\release\DTLib.dll copy DTLib.dll ..\..\release\DTLib.dll
</PostBuildEvent> </PostBuildEvent>
</PropertyGroup> </PropertyGroup>