commit bc4546410e0aa70c110e008c71f62ad9fafec7cb
Author: zznty <94796179+zznty@users.noreply.github.com>
Date: Thu Jul 21 21:57:27 2022 +0700
first
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8afdcb6
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,454 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Ww][Ii][Nn]32/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# Tye
+.tye/
+
+# ASP.NET Scaffolding
+ScaffoldingReadMe.txt
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Coverlet is a free, cross platform Code Coverage Tool
+coverage*.json
+coverage*.xml
+coverage*.info
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# 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
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+# Fody - auto-generated XML schema
+FodyWeavers.xsd
+
+##
+## Visual studio for Mac
+##
+
+
+# globs
+Makefile.in
+*.userprefs
+*.usertasks
+config.make
+config.status
+aclocal.m4
+install-sh
+autom4te.cache/
+*.tar.gz
+tarballs/
+test-results/
+
+# Mac bundle stuff
+*.dmg
+*.app
+
+# content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore
+# General
+.DS_Store
+.AppleDouble
+.LSOverride
+
+# Icon must end with two \r
+Icon
+
+
+# Thumbnails
+._*
+
+# Files that might appear in the root of a volume
+.DocumentRevisions-V100
+.fseventsd
+.Spotlight-V100
+.TemporaryItems
+.Trashes
+.VolumeIcon.icns
+.com.apple.timemachine.donotpresent
+
+# Directories potentially created on remote AFP share
+.AppleDB
+.AppleDesktop
+Network Trash Folder
+Temporary Items
+.apdisk
+
+# content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore
+# Windows thumbnail cache files
+Thumbs.db
+ehthumbs.db
+ehthumbs_vista.db
+
+# Dump file
+*.stackdump
+
+# Folder config file
+[Dd]esktop.ini
+
+# Recycle Bin used on file shares
+$RECYCLE.BIN/
+
+# Windows Installer files
+*.cab
+*.msi
+*.msix
+*.msm
+*.msp
+
+# Windows shortcuts
+*.lnk
+
+# JetBrains Rider
+.idea/
+*.sln.iml
+
+##
+## Visual Studio Code
+##
+.vscode/*
+!.vscode/settings.json
+!.vscode/tasks.json
+!.vscode/launch.json
+!.vscode/extensions.json
diff --git a/.idea/.idea.TorchRemote/.idea/.gitignore b/.idea/.idea.TorchRemote/.idea/.gitignore
new file mode 100644
index 0000000..5fa4bc4
--- /dev/null
+++ b/.idea/.idea.TorchRemote/.idea/.gitignore
@@ -0,0 +1,13 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Rider ignored files
+/modules.xml
+/projectSettingsUpdater.xml
+/.idea.TorchRemote.iml
+/contentModel.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml
diff --git a/.idea/.idea.TorchRemote/.idea/avalonia.xml b/.idea/.idea.TorchRemote/.idea/avalonia.xml
new file mode 100644
index 0000000..f9472c9
--- /dev/null
+++ b/.idea/.idea.TorchRemote/.idea/avalonia.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/.idea.TorchRemote/.idea/encodings.xml b/.idea/.idea.TorchRemote/.idea/encodings.xml
new file mode 100644
index 0000000..df87cf9
--- /dev/null
+++ b/.idea/.idea.TorchRemote/.idea/encodings.xml
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/.idea/.idea.TorchRemote/.idea/indexLayout.xml b/.idea/.idea.TorchRemote/.idea/indexLayout.xml
new file mode 100644
index 0000000..7b08163
--- /dev/null
+++ b/.idea/.idea.TorchRemote/.idea/indexLayout.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/.idea.TorchRemote/.idea/misc.xml b/.idea/.idea.TorchRemote/.idea/misc.xml
new file mode 100644
index 0000000..1d8c84d
--- /dev/null
+++ b/.idea/.idea.TorchRemote/.idea/misc.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/.idea.TorchRemote/.idea/vcs.xml b/.idea/.idea.TorchRemote/.idea/vcs.xml
new file mode 100644
index 0000000..94a25f7
--- /dev/null
+++ b/.idea/.idea.TorchRemote/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/TorchRemote.Models/Requests/ChatCommandRequest.cs b/TorchRemote.Models/Requests/ChatCommandRequest.cs
new file mode 100644
index 0000000..743b333
--- /dev/null
+++ b/TorchRemote.Models/Requests/ChatCommandRequest.cs
@@ -0,0 +1,3 @@
+namespace TorchRemote.Models.Requests;
+
+public record ChatCommandRequest(string Command);
\ No newline at end of file
diff --git a/TorchRemote.Models/Requests/ChatMessageRequest.cs b/TorchRemote.Models/Requests/ChatMessageRequest.cs
new file mode 100644
index 0000000..c8c8a3e
--- /dev/null
+++ b/TorchRemote.Models/Requests/ChatMessageRequest.cs
@@ -0,0 +1,4 @@
+using TorchRemote.Models.Shared;
+namespace TorchRemote.Models.Requests;
+
+public record ChatMessageRequest(string Author, string Message, ChatChannel Channel, long? TargetId = null);
\ No newline at end of file
diff --git a/TorchRemote.Models/Requests/StopServerRequest.cs b/TorchRemote.Models/Requests/StopServerRequest.cs
new file mode 100644
index 0000000..31a6f26
--- /dev/null
+++ b/TorchRemote.Models/Requests/StopServerRequest.cs
@@ -0,0 +1,3 @@
+namespace TorchRemote.Models.Requests;
+
+public record StopServerRequest(bool Save = true);
diff --git a/TorchRemote.Models/Responses/ChatCommandResponse.cs b/TorchRemote.Models/Responses/ChatCommandResponse.cs
new file mode 100644
index 0000000..512f1ac
--- /dev/null
+++ b/TorchRemote.Models/Responses/ChatCommandResponse.cs
@@ -0,0 +1,3 @@
+namespace TorchRemote.Models.Responses;
+
+public record ChatCommandResponse(Guid Id, string Author, string Message) : ChatResponseBase;
diff --git a/TorchRemote.Models/Responses/ChatMessageResponse.cs b/TorchRemote.Models/Responses/ChatMessageResponse.cs
new file mode 100644
index 0000000..226a569
--- /dev/null
+++ b/TorchRemote.Models/Responses/ChatMessageResponse.cs
@@ -0,0 +1,4 @@
+using TorchRemote.Models.Shared;
+namespace TorchRemote.Models.Responses;
+
+public record ChatMessageResponse(string AuthorName, ulong? Author, ChatChannel Channel, string Message) : ChatResponseBase;
diff --git a/TorchRemote.Models/Responses/ChatResponseBase.cs b/TorchRemote.Models/Responses/ChatResponseBase.cs
new file mode 100644
index 0000000..570e127
--- /dev/null
+++ b/TorchRemote.Models/Responses/ChatResponseBase.cs
@@ -0,0 +1,6 @@
+using System.Text.Json.Serialization;
+namespace TorchRemote.Models.Responses;
+
+[JsonDerivedType(typeof(ChatCommandResponse), "command")]
+[JsonDerivedType(typeof(ChatMessageResponse), "message")]
+public record ChatResponseBase();
diff --git a/TorchRemote.Models/Responses/LogLineResponse.cs b/TorchRemote.Models/Responses/LogLineResponse.cs
new file mode 100644
index 0000000..e7e5505
--- /dev/null
+++ b/TorchRemote.Models/Responses/LogLineResponse.cs
@@ -0,0 +1,13 @@
+namespace TorchRemote.Models.Responses;
+
+public record struct LogLineResponse(DateTime Time, LogLineLevel Level, string Logger, string Message);
+
+public enum LogLineLevel
+{
+ Trace,
+ Debug,
+ Info,
+ Warning,
+ Error,
+ Fatal
+}
diff --git a/TorchRemote.Models/Responses/ServerStatusResponse.cs b/TorchRemote.Models/Responses/ServerStatusResponse.cs
new file mode 100644
index 0000000..080e046
--- /dev/null
+++ b/TorchRemote.Models/Responses/ServerStatusResponse.cs
@@ -0,0 +1,15 @@
+namespace TorchRemote.Models.Responses;
+
+public record ServerStatusResponse(double SimSpeed, int MemberCount, TimeSpan Uptime, ServerStatus Status);
+
+public enum ServerStatus
+{
+ /// The server is not running.
+ Stopped,
+ /// The server is starting/loading the session.
+ Starting,
+ /// The server is running.
+ Running,
+ /// The server encountered an error.
+ Error,
+}
diff --git a/TorchRemote.Models/Responses/SettingInfoResponse.cs b/TorchRemote.Models/Responses/SettingInfoResponse.cs
new file mode 100644
index 0000000..870dfe4
--- /dev/null
+++ b/TorchRemote.Models/Responses/SettingInfoResponse.cs
@@ -0,0 +1,15 @@
+namespace TorchRemote.Models.Responses;
+
+public record SettingInfoResponse(string Name, ICollection Properties);
+public record SettingPropertyInfo(string Name, string? Description, int? Order, Guid Type);
+
+public struct SettingPropertyTypeEnum
+{
+ public static readonly Guid Integer = new("95c0d25b-e44d-4505-9549-48ee9c14bce8");
+ public static readonly Guid Boolean = new("028ef347-1fc3-486a-b70b-3d3b1dcdb538");
+ public static readonly Guid Number = new("009ced71-4a69-4af0-abb9-ec3339fffce0");
+ public static readonly Guid String = new("22dbed1b-b976-44b4-98c9-d1b742a93f0c");
+ public static readonly Guid DateTime = new("f0978b29-9da9-4289-85c9-41d5b92056e8");
+ public static readonly Guid TimeSpan = new("7a2bebf1-78f5-4e4e-8d83-18914dbee55c");
+ public static readonly Guid Color = new("99c74632-0fa9-469b-ba05-825ba21a017b");
+}
\ No newline at end of file
diff --git a/TorchRemote.Models/Responses/WorldResponse.cs b/TorchRemote.Models/Responses/WorldResponse.cs
new file mode 100644
index 0000000..8305fd9
--- /dev/null
+++ b/TorchRemote.Models/Responses/WorldResponse.cs
@@ -0,0 +1,3 @@
+namespace TorchRemote.Models.Responses;
+
+public record WorldResponse(string Name, long SizeKb);
diff --git a/TorchRemote.Models/Shared/ChatChannel.cs b/TorchRemote.Models/Shared/ChatChannel.cs
new file mode 100644
index 0000000..ccd3814
--- /dev/null
+++ b/TorchRemote.Models/Shared/ChatChannel.cs
@@ -0,0 +1,9 @@
+namespace TorchRemote.Models.Shared;
+
+public enum ChatChannel
+{
+ Global,
+ GlobalScripted,
+ Faction,
+ Private
+}
diff --git a/TorchRemote.Models/Shared/IpAddress.cs b/TorchRemote.Models/Shared/IpAddress.cs
new file mode 100644
index 0000000..c1ca9be
--- /dev/null
+++ b/TorchRemote.Models/Shared/IpAddress.cs
@@ -0,0 +1,3 @@
+namespace TorchRemote.Models.Shared;
+
+public record IpAddress(string Ip, int Port);
diff --git a/TorchRemote.Models/Shared/ServerSettings.cs b/TorchRemote.Models/Shared/ServerSettings.cs
new file mode 100644
index 0000000..482b879
--- /dev/null
+++ b/TorchRemote.Models/Shared/ServerSettings.cs
@@ -0,0 +1,9 @@
+namespace TorchRemote.Models.Shared;
+
+public record ServerSettings(
+ string ServerName,
+ string MapName,
+ string ServerDescription,
+ short MemberLimit,
+ IpAddress ListenEndPoint
+);
diff --git a/TorchRemote.Models/TorchRemote.Models.csproj b/TorchRemote.Models/TorchRemote.Models.csproj
new file mode 100644
index 0000000..d28ab0c
--- /dev/null
+++ b/TorchRemote.Models/TorchRemote.Models.csproj
@@ -0,0 +1,13 @@
+
+
+
+ netstandard2.0
+ enable
+ enable
+ 10
+
+
+
+
+
+
diff --git a/TorchRemote.Models/Trash/IsExternalInit.cs b/TorchRemote.Models/Trash/IsExternalInit.cs
new file mode 100644
index 0000000..1b4fd00
--- /dev/null
+++ b/TorchRemote.Models/Trash/IsExternalInit.cs
@@ -0,0 +1,5 @@
+using System.Runtime.CompilerServices;
+[assembly: InternalsVisibleTo("TorchRemote.Plugin")]
+// ReSharper disable once CheckNamespace
+namespace System.Runtime.CompilerServices;
+internal class IsExternalInit { }
\ No newline at end of file
diff --git a/TorchRemote.Plugin/Config.cs b/TorchRemote.Plugin/Config.cs
new file mode 100644
index 0000000..ccad03f
--- /dev/null
+++ b/TorchRemote.Plugin/Config.cs
@@ -0,0 +1,17 @@
+using Torch;
+using Torch.Views;
+
+namespace TorchRemote.Plugin;
+
+public class Config : ViewModel
+{
+ [Display(Name = "Web Server Config", Description = "Basic configuration for serving web api.")]
+ public ListenerConfig Listener { get; set; } = new();
+ public string SecurityKey { get; set; } = string.Empty;
+}
+
+public class ListenerConfig : ViewModel
+{
+ [Display(Name = "Url Prefix", Description = "Root url for all requests. If you want access server from remote replace + with your public ip or domain.")]
+ public string UrlPrefix { get; set; } = "http://+:80/";
+}
diff --git a/TorchRemote.Plugin/Controllers/ChatController.cs b/TorchRemote.Plugin/Controllers/ChatController.cs
new file mode 100644
index 0000000..84b90bd
--- /dev/null
+++ b/TorchRemote.Plugin/Controllers/ChatController.cs
@@ -0,0 +1,118 @@
+using System.Net;
+using System.Reflection;
+using System.Text.RegularExpressions;
+using EmbedIO;
+using EmbedIO.Routing;
+using EmbedIO.WebApi;
+using EmbedIO.WebSockets;
+using Sandbox.Engine.Multiplayer;
+using Sandbox.Game.Multiplayer;
+using Sandbox.Game.World;
+using Torch.API;
+using Torch.API.Managers;
+using Torch.API.Plugins;
+using Torch.Commands;
+using Torch.Managers;
+using Torch.Utils;
+using TorchRemote.Models.Requests;
+using TorchRemote.Models.Responses;
+using TorchRemote.Models.Shared;
+using TorchRemote.Plugin.Modules;
+using TorchRemote.Plugin.Utils;
+using VRage.Network;
+namespace TorchRemote.Plugin.Controllers;
+
+public class ChatController : WebApiController
+{
+ private const string RootPath = "/chat";
+
+ [ReflectedMethodInfo(typeof(MyMultiplayerBase), "OnChatMessageReceived_BroadcastExcept")]
+ private static readonly MethodInfo BroadcastExceptMethod = null!;
+ [ReflectedMethodInfo(typeof(MyMultiplayerBase), "OnChatMessageReceived_SingleTarget")]
+ private static readonly MethodInfo SingleTargetMethod = null!;
+
+ [Route(HttpVerbs.Post, $"{RootPath}/message")]
+ public void SendMessage([JsonData] ChatMessageRequest request)
+ {
+ if (MyMultiplayer.Static is null)
+ throw new HttpException(HttpStatusCode.ServiceUnavailable);
+
+ var msg = new ChatMsg
+ {
+ CustomAuthorName = request.Author,
+ Text = request.Message,
+ Channel = (byte)request.Channel,
+ TargetId = request.TargetId.GetValueOrDefault()
+ };
+
+ switch (request.Channel)
+ {
+ case ChatChannel.Global:
+ case ChatChannel.GlobalScripted when request.TargetId is null:
+ NetworkManager.RaiseStaticEvent(BroadcastExceptMethod, msg);
+ break;
+
+ case ChatChannel.Private when request.TargetId is not null:
+ case ChatChannel.GlobalScripted:
+ var steamId = Sync.Players.TryGetSteamId(request.TargetId.Value);
+ if (steamId == 0)
+ throw HttpException.NotFound($"Unable to find player with identity id {request.TargetId.Value}", request.TargetId.Value);
+
+ NetworkManager.RaiseStaticEvent(SingleTargetMethod, msg, new(steamId));
+ break;
+
+ case ChatChannel.Faction when request.TargetId is not null:
+ var faction = MySession.Static.Factions.TryGetFactionById(request.TargetId.Value);
+ if (faction is null)
+ throw HttpException.NotFound($"Unable to find faction with id {request.TargetId.Value}", request.TargetId.Value);
+
+ foreach (var playerId in faction.Members.Keys.Where(Sync.Players.IsPlayerOnline))
+ {
+ NetworkManager.RaiseStaticEvent(SingleTargetMethod, msg, new(Sync.Players.TryGetSteamId(playerId)));
+ }
+ break;
+
+ default:
+ throw HttpException.BadRequest("Invalid channel and targetId combination");
+ }
+
+ if (Statics.Torch.CurrentSession?.Managers.GetManager() is { } manager)
+ manager.DisplayMessageOnSelf(request.Author, request.Message);
+ }
+
+ [Route(HttpVerbs.Post, $"{RootPath}/command")]
+ public async Task InvokeCommand([JsonData] ChatCommandRequest request)
+ {
+ if (Statics.CommandManager is null)
+ throw new HttpException(HttpStatusCode.ServiceUnavailable);
+
+ if (Statics.CommandManager.Commands.GetCommand(request.Command, out var argText) is not { } command)
+ throw HttpException.NotFound($"Unable to find command {request.Command}", request.Command);
+
+ var argsList = Regex.Matches(argText, "(\"[^\"]+\"|\\S+)").Cast().Select(x => x.ToString().Replace("\"", "")).ToList();
+
+ var id = new Guid();
+ var context = new WebSocketCommandContext(Statics.Torch, command.Plugin, argText, argsList, Statics.ChatModule, id);
+
+ if (await Statics.Torch.InvokeAsync(() => command.TryInvoke(context)))
+ return id;
+
+ throw HttpException.BadRequest("Invalid syntax", request.Command);
+ }
+}
+
+internal class WebSocketCommandContext : CommandContext
+{
+ private readonly ChatModule _module;
+ private readonly Guid _id;
+ public WebSocketCommandContext(ITorchBase torch, ITorchPlugin plugin, string rawArgs, List args, ChatModule module, Guid id) : base(torch, plugin, Sync.MyId, rawArgs, args)
+ {
+ _module = module;
+ _id = id;
+ }
+
+ public override void Respond(string message, string? sender = null, string? font = null)
+ {
+ _module.SendChatResponse(new ChatCommandResponse(_id, sender ?? Torch.Config.ChatName, message));
+ }
+}
\ No newline at end of file
diff --git a/TorchRemote.Plugin/Controllers/ServerController.cs b/TorchRemote.Plugin/Controllers/ServerController.cs
new file mode 100644
index 0000000..177544b
--- /dev/null
+++ b/TorchRemote.Plugin/Controllers/ServerController.cs
@@ -0,0 +1,76 @@
+using EmbedIO;
+using EmbedIO.Routing;
+using EmbedIO.WebApi;
+using Sandbox.Game.Multiplayer;
+using Sandbox.Game.World;
+using Torch.API.Session;
+using TorchRemote.Models.Requests;
+using TorchRemote.Models.Responses;
+using TorchRemote.Models.Shared;
+using TorchRemote.Plugin.Utils;
+
+namespace TorchRemote.Plugin.Controllers;
+
+public class ServerController : WebApiController
+{
+ private const string RootPath = "/server";
+
+ [Route(HttpVerbs.Get, $"{RootPath}/status")]
+ public ServerStatusResponse GetStatus()
+ {
+ return new(Math.Round(Sync.ServerSimulationRatio, 2),
+ MySession.Static?.Players?.GetOnlinePlayerCount() ?? 0,
+ Statics.Torch.ElapsedPlayTime,
+ (ServerStatus)Statics.Torch.State);
+ }
+
+ [Route(HttpVerbs.Post, $"{RootPath}/start")]
+ public void Start()
+ {
+ if (!Statics.Torch.CanRun)
+ throw HttpException.BadRequest($"Server can't start in state {Statics.Torch.State}", Statics.Torch.State);
+
+ Statics.Torch.Start();
+ }
+
+ [Route(HttpVerbs.Post, $"{RootPath}/stop")]
+ public async Task Stop(StopServerRequest request)
+ {
+ if (!Statics.Torch.IsRunning)
+ throw HttpException.BadRequest($"Server can't stop in state {Statics.Torch.State}", Statics.Torch.State);
+
+ var saveResult = await Statics.Torch.Save(exclusive: true);
+ if (saveResult is not GameSaveResult.Success)
+ throw HttpException.InternalServerError($"Save resulted in {saveResult}", saveResult);
+
+ Statics.Torch.Stop();
+ }
+
+ [Route(HttpVerbs.Get, $"{RootPath}/settings")]
+ public ServerSettings GetSettings()
+ {
+ var settings = Statics.Torch.DedicatedInstance.DedicatedConfig;
+
+ return new(settings.ServerName ?? "unamed",
+ settings.WorldName ?? "unamed",
+ settings.ServerDescription ?? string.Empty,
+ settings.SessionSettings.MaxPlayers,
+ new(settings.IP, settings.Port));
+ }
+
+ [Route(HttpVerbs.Post, $"{RootPath}/settings")]
+ public async Task SetSettings([JsonData] ServerSettings request)
+ {
+ var settings = Statics.Torch.DedicatedInstance.DedicatedConfig;
+
+ settings.ServerName = request.ServerName;
+ settings.WorldName = request.MapName;
+ settings.ServerDescription = request.ServerDescription;
+ settings.SessionSettings.MaxPlayers = request.MemberLimit;
+ settings.IP = request.ListenEndPoint.Ip;
+ settings.Port = request.ListenEndPoint.Port;
+
+ if (Statics.Torch.IsRunning)
+ await Statics.Torch.InvokeAsync(request.ApplyDynamically);
+ }
+}
diff --git a/TorchRemote.Plugin/Controllers/SettingsController.cs b/TorchRemote.Plugin/Controllers/SettingsController.cs
new file mode 100644
index 0000000..9884cb0
--- /dev/null
+++ b/TorchRemote.Plugin/Controllers/SettingsController.cs
@@ -0,0 +1,24 @@
+using EmbedIO;
+using EmbedIO.Routing;
+using EmbedIO.WebApi;
+using Swan;
+using TorchRemote.Models.Responses;
+using TorchRemote.Plugin.Utils;
+namespace TorchRemote.Plugin.Controllers;
+
+public class SettingsController : WebApiController
+{
+ private const string RootPath = "/settings";
+
+ [Route(HttpVerbs.Get, $"{RootPath}/{{id}}")]
+ public SettingInfoResponse Get(Guid id)
+ {
+ if (!Statics.SettingManager.Settings.TryGetValue(id, out var setting))
+ throw HttpException.NotFound($"Setting with id {id} not found", id);
+
+ return new(setting.Name.Humanize(), setting.Properties.Select(b =>
+ new SettingPropertyInfo(b.DisplayInfo?.Name ?? b.Name.Humanize(),
+ b.DisplayInfo?.Description, b.DisplayInfo?.Order, b.TypeId))
+ .ToArray());
+ }
+}
diff --git a/TorchRemote.Plugin/Controllers/WorldsController.cs b/TorchRemote.Plugin/Controllers/WorldsController.cs
new file mode 100644
index 0000000..166a750
--- /dev/null
+++ b/TorchRemote.Plugin/Controllers/WorldsController.cs
@@ -0,0 +1,62 @@
+using System.Net;
+using EmbedIO;
+using EmbedIO.Routing;
+using EmbedIO.WebApi;
+using TorchRemote.Models.Responses;
+using TorchRemote.Plugin.Utils;
+namespace TorchRemote.Plugin.Controllers;
+
+public class WorldsController : WebApiController
+{
+ private const string RootPath = "/worlds";
+
+ [Route(HttpVerbs.Get, RootPath)]
+ public IEnumerable Get()
+ {
+ var config = Statics.InstanceManager.DedicatedConfig;
+
+ if (config is null)
+ throw new HttpException(HttpStatusCode.ServiceUnavailable);
+
+ return config.Worlds.Select(b => b.FolderName.ToGuid());
+ }
+
+ [Route(HttpVerbs.Get, $"{RootPath}/selected")]
+ public Guid GetSelected()
+ {
+ if (Statics.InstanceManager.DedicatedConfig?.SelectedWorld is not { } world)
+ throw new HttpException(HttpStatusCode.ServiceUnavailable);
+
+ return world.FolderName.ToGuid();
+ }
+
+ [Route(HttpVerbs.Get, $"{RootPath}/{{id}}")]
+ public WorldResponse GetWorld(Guid id)
+ {
+ var config = Statics.InstanceManager.DedicatedConfig;
+
+ if (config is null)
+ throw new HttpException(HttpStatusCode.ServiceUnavailable);
+
+ if (config.Worlds.FirstOrDefault(b => b.FolderName.ToGuid() == id) is not { } world)
+ throw HttpException.NotFound($"World not found by given id {id}", id);
+
+ return new(world.FolderName, world.WorldSizeKB);
+ }
+
+ [Route(HttpVerbs.Post, $"{RootPath}/{{id}}/select")]
+ public void Select(Guid id)
+ {
+ var config = Statics.InstanceManager.DedicatedConfig;
+
+ if (config is null)
+ throw new HttpException(HttpStatusCode.ServiceUnavailable);
+
+ if (config.Worlds.FirstOrDefault(b => b.FolderName.ToGuid() == id) is not { } world)
+ throw HttpException.NotFound($"World not found by given id {id}", id);
+
+ config.Model.IgnoreLastSession = true;
+ config.SelectedWorld = world;
+ config.Save();
+ }
+}
diff --git a/TorchRemote.Plugin/FodyWeavers.xml b/TorchRemote.Plugin/FodyWeavers.xml
new file mode 100644
index 0000000..d5abfed
--- /dev/null
+++ b/TorchRemote.Plugin/FodyWeavers.xml
@@ -0,0 +1,3 @@
+
+
+
\ No newline at end of file
diff --git a/TorchRemote.Plugin/FodyWeavers.xsd b/TorchRemote.Plugin/FodyWeavers.xsd
new file mode 100644
index 0000000..69dbe48
--- /dev/null
+++ b/TorchRemote.Plugin/FodyWeavers.xsd
@@ -0,0 +1,74 @@
+
+
+
+
+
+
+
+
+
+
+ Used to control if the On_PropertyName_Changed feature is enabled.
+
+
+
+
+ Used to control if the Dependent properties feature is enabled.
+
+
+
+
+ Used to control if the IsChanged property feature is enabled.
+
+
+
+
+ Used to change the name of the method that fires the notify event. This is a string that accepts multiple values in a comma separated form.
+
+
+
+
+ Used to control if equality checks should be inserted. If false, equality checking will be disabled for the project.
+
+
+
+
+ Used to control if equality checks should use the Equals method resolved from the base class.
+
+
+
+
+ Used to control if equality checks should use the static Equals method resolved from the base class.
+
+
+
+
+ Used to turn off build warnings from this weaver.
+
+
+
+
+ Used to turn off build warnings about mismatched On_PropertyName_Changed methods.
+
+
+
+
+
+
+
+ 'true' to run assembly verification (PEVerify) on the target assembly after all weavers have been executed.
+
+
+
+
+ A comma-separated list of error codes that can be safely ignored in assembly verification.
+
+
+
+
+ 'false' to turn off automatic generation of the XML Schema file.
+
+
+
+
+
\ No newline at end of file
diff --git a/TorchRemote.Plugin/Managers/ApiServerManager.cs b/TorchRemote.Plugin/Managers/ApiServerManager.cs
new file mode 100644
index 0000000..52a9731
--- /dev/null
+++ b/TorchRemote.Plugin/Managers/ApiServerManager.cs
@@ -0,0 +1,95 @@
+using System.Security.Cryptography;
+using System.Text.Json;
+using EmbedIO;
+using EmbedIO.BearerToken;
+using EmbedIO.WebApi;
+using Microsoft.IdentityModel.Tokens;
+using NLog;
+using Torch.API;
+using Torch.API.Managers;
+using Torch.Managers;
+using Torch.Server.Managers;
+using TorchRemote.Plugin.Controllers;
+using TorchRemote.Plugin.Modules;
+using TorchRemote.Plugin.Utils;
+using VRage.Game.ModAPI;
+namespace TorchRemote.Plugin.Managers;
+
+public class ApiServerManager : Manager
+{
+ private static readonly ILogger Log = LogManager.GetCurrentClassLogger();
+
+ private readonly Config _config;
+ private readonly IWebServer _server;
+ [Dependency]
+ private readonly SettingManager _settingManager = null!;
+ [Dependency]
+ private readonly InstanceManager _instanceManager = null!;
+ public ApiServerManager(ITorchBase torchInstance, Config config) : base(torchInstance)
+ {
+ _config = config;
+
+ if (string.IsNullOrEmpty(_config.SecurityKey))
+ _config.SecurityKey = CreateSecurityKey();
+
+ var apiModule = new WebApiModule("/api/v1", async (context, data) =>
+ {
+ try
+ {
+ context.Response.ContentType = "application/json";
+ using var stream = context.OpenResponseStream();
+ await JsonSerializer.SerializeAsync(stream, data, Statics.SerializerOptions);
+ }
+ catch (Exception e)
+ {
+ Log.Error(e);
+ throw HttpException.InternalServerError(e.Message, e.Message);
+ }
+ });
+
+ var chatModule = new ChatModule("/api/live/chat", true);
+ Statics.ChatModule = chatModule;
+
+ _server = new WebServer(o => o
+ .WithUrlPrefix(_config.Listener.UrlPrefix)
+ .WithMicrosoftHttpListener())
+ .WithLocalSessionManager()
+ .WithModule(apiModule
+ .WithController()
+ .WithController()
+ .WithController()
+ .WithController())
+ .WithModule(new LogsModule("/api/live/logs", true))
+ .WithModule(chatModule)
+ .WithBearerToken("/api", new SymmetricSecurityKey(Convert.FromBase64String(_config.SecurityKey)), new BasicAuthorizationServerProvider());
+ }
+
+ public override void Attach()
+ {
+ base.Attach();
+
+ Starter();
+ Log.Info("Listening on {0}", _config.Listener.UrlPrefix);
+
+ //_instanceManager.InstanceLoaded += model => _settingManager.RegisterSetting(model.Model, typeof(IMyConfigDedicated), false);
+ }
+ public override void Detach()
+ {
+ base.Detach();
+ _server.Dispose();
+ }
+
+ private async void Starter()
+ {
+ await _server.RunAsync();
+ }
+
+ private static string CreateSecurityKey()
+ {
+ var aes = Aes.Create();
+ aes.GenerateIV();
+ aes.GenerateKey();
+
+ return Convert.ToBase64String(aes.Key);
+ }
+}
diff --git a/TorchRemote.Plugin/Managers/ChatMonitorManager.cs b/TorchRemote.Plugin/Managers/ChatMonitorManager.cs
new file mode 100644
index 0000000..72090fb
--- /dev/null
+++ b/TorchRemote.Plugin/Managers/ChatMonitorManager.cs
@@ -0,0 +1,28 @@
+using Sandbox.Engine.Multiplayer;
+using Torch.API;
+using Torch.API.Managers;
+using Torch.Managers;
+using TorchRemote.Models.Responses;
+using TorchRemote.Models.Shared;
+using TorchRemote.Plugin.Utils;
+namespace TorchRemote.Plugin.Managers;
+
+public class ChatMonitorManager : Manager
+{
+ [Dependency]
+ private readonly IChatManagerServer _chatManager = null!;
+ public ChatMonitorManager(ITorchBase torchInstance) : base(torchInstance)
+ {
+ }
+
+ public override void Attach()
+ {
+ base.Attach();
+ _chatManager.MessageRecieved += ChatManagerOnMessageReceived;
+ }
+ private void ChatManagerOnMessageReceived(TorchChatMessage msg, ref bool consumed)
+ {
+ Statics.ChatModule.SendChatResponse(new ChatMessageResponse(msg.Author ?? (msg.AuthorSteamId is null ? Torch.Config.ChatName : MyMultiplayer.Static.GetMemberName(msg.AuthorSteamId.Value)),
+ msg.AuthorSteamId, (ChatChannel)msg.Channel, msg.Message));
+ }
+}
diff --git a/TorchRemote.Plugin/Managers/SettingManager.cs b/TorchRemote.Plugin/Managers/SettingManager.cs
new file mode 100644
index 0000000..20c71ef
--- /dev/null
+++ b/TorchRemote.Plugin/Managers/SettingManager.cs
@@ -0,0 +1,77 @@
+using System.Collections.Concurrent;
+using System.Reflection;
+using System.Text.Json.Serialization;
+using System.Xml.Serialization;
+using NLog;
+using Torch.API;
+using Torch.Managers;
+using Torch.Views;
+using TorchRemote.Models.Responses;
+using TorchRemote.Plugin.Utils;
+using VRage;
+namespace TorchRemote.Plugin.Managers;
+
+public class SettingManager : Manager
+{
+ private static readonly ILogger Log = LogManager.GetCurrentClassLogger();
+
+ public SettingManager(ITorchBase torchInstance) : base(torchInstance)
+ {
+ }
+
+ public Guid RegisterSetting(object value, Type type, bool includeOnlyDisplay = true)
+ {
+ var properties = type.IsInterface ? type.GetProperties() : type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
+ var settingProperties = properties
+ .Where(b => !b.HasAttribute() &&
+ !b.HasAttribute() &&
+ (!includeOnlyDisplay ||
+ b.HasAttribute()))
+ .Select(property => new SettingProperty(property.Name,
+ GetTypeId(property.PropertyType, property.GetValue(value), includeOnlyDisplay),
+ property.PropertyType, property.GetMethod, property.SetMethod,
+ property.GetCustomAttribute() is { } attr ?
+ new(attr.Name, attr.Description, attr.GroupName, attr.Order, attr.ReadOnly, attr.Enabled) :
+ null))
+ .ToArray();
+
+ var setting = new Setting(type.Name, type, settingProperties, value);
+
+ var id = (type.FullName! + value.GetHashCode()).ToGuid();
+ Settings.Add(id, setting);
+ Log.Debug("Registered type {0} with id {1}", type, id);
+ return id;
+ }
+
+ private Guid GetTypeId(Type type, object value, bool includeOnlyDisplay)
+ {
+ if (type == typeof(int) || type == typeof(uint))
+ return SettingPropertyTypeEnum.Integer;
+ if (type == typeof(bool))
+ return SettingPropertyTypeEnum.Boolean;
+ if (type == typeof(short) ||
+ type == typeof(ushort) ||
+ type == typeof(byte) ||
+ type == typeof(ulong) ||
+ type == typeof(long) ||
+ type == typeof(float) ||
+ type == typeof(double) ||
+ type == typeof(MyFixedPoint))
+ return SettingPropertyTypeEnum.Number;
+ if (type == typeof(string))
+ return SettingPropertyTypeEnum.String;
+ if (type == typeof(DateTime))
+ return SettingPropertyTypeEnum.DateTime;
+ if (type == typeof(TimeSpan))
+ return SettingPropertyTypeEnum.TimeSpan;
+ if (type == typeof(System.Drawing.Color) || type == typeof(VRageMath.Color))
+ return SettingPropertyTypeEnum.Color;
+ return RegisterSetting(value, type, includeOnlyDisplay);
+ }
+
+ public IDictionary Settings { get; } = new ConcurrentDictionary();
+}
+
+public record Setting(string Name, Type Type, IEnumerable Properties, object? Value = null);
+public record SettingProperty(string Name, Guid TypeId, Type Type, MethodInfo Getter, MethodInfo? Setter, SettingPropertyDisplayInfo? DisplayInfo);
+public record SettingPropertyDisplayInfo(string? Name, string? Description, string? GroupName, int? Order, bool? IsReadOnly, bool? IsEnabled);
diff --git a/TorchRemote.Plugin/Modules/ChatModule.cs b/TorchRemote.Plugin/Modules/ChatModule.cs
new file mode 100644
index 0000000..8ff9b54
--- /dev/null
+++ b/TorchRemote.Plugin/Modules/ChatModule.cs
@@ -0,0 +1,28 @@
+using System.Net.WebSockets;
+using System.Text.Json;
+using EmbedIO.WebSockets;
+using TorchRemote.Models.Responses;
+using TorchRemote.Plugin.Utils;
+namespace TorchRemote.Plugin.Modules;
+
+public class ChatModule : WebSocketModule
+{
+ public ChatModule(string urlPath, bool enableConnectionWatchdog) : base(urlPath, enableConnectionWatchdog)
+ {
+ }
+
+ public async void SendChatResponse(ChatResponseBase response)
+ {
+ if (ActiveContexts.Count == 0)
+ return;
+
+ var buffer = JsonSerializer.SerializeToUtf8Bytes(response, Statics.SerializerOptions);
+ await Task.WhenAll(ActiveContexts
+ .Where(b => b.WebSocket.State is WebSocketState.Open)
+ .Select(context => context.WebSocket.SendAsync(buffer, true)));
+ }
+
+ protected override async Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result)
+ {
+ }
+}
diff --git a/TorchRemote.Plugin/Modules/LogsModule.cs b/TorchRemote.Plugin/Modules/LogsModule.cs
new file mode 100644
index 0000000..de30a76
--- /dev/null
+++ b/TorchRemote.Plugin/Modules/LogsModule.cs
@@ -0,0 +1,85 @@
+using System.Net.WebSockets;
+using System.Text;
+using System.Text.Json;
+using EmbedIO.WebSockets;
+using NLog;
+using NLog.Targets;
+using NLog.Targets.Wrappers;
+using Torch.Server;
+using TorchRemote.Models.Responses;
+using TorchRemote.Plugin.Utils;
+namespace TorchRemote.Plugin.Modules;
+
+public class LogsModule : WebSocketModule
+{
+
+ public LogsModule(string urlPath, bool enableConnectionWatchdog) : base(urlPath, enableConnectionWatchdog)
+ {
+ ConfigureLogging();
+ }
+ protected override async Task OnMessageReceivedAsync(IWebSocketContext context, byte[] buffer, IWebSocketReceiveResult result)
+ {
+ }
+
+ public async void OnLogMessageReceived(DateTime time, LogLevel level, string logger, string message)
+ {
+ if (ActiveContexts.Count == 0)
+ return;
+
+ var response = new LogLineResponse(time, (LogLineLevel)level.Ordinal, logger, message);
+ var buffer = JsonSerializer.SerializeToUtf8Bytes(response, Statics.SerializerOptions);
+
+ await Task.WhenAll(ActiveContexts
+ .Where(b => b.WebSocket.State is WebSocketState.Open)
+ .Select(context => context.WebSocket.SendAsync(buffer, true)));
+ }
+
+ private void ConfigureLogging()
+ {
+ var cfg = LogManager.Configuration;
+ var flowDocumentTarget = cfg.FindTargetByName("wpf");
+
+ if (flowDocumentTarget is null or SplitGroupTarget)
+ return;
+
+ flowDocumentTarget.Name = "wpf-old";
+
+ var target = new SplitGroupTarget
+ {
+ Name = "wpf",
+ Targets =
+ {
+ flowDocumentTarget,
+ new StupidTarget(this)
+ }
+ };
+
+ cfg.RemoveTarget("wpf");
+ cfg.AddTarget(target);
+ foreach (var rule in cfg.LoggingRules)
+ {
+ if (rule.Targets.Remove(flowDocumentTarget))
+ rule.Targets.Add(target);
+ }
+ LogManager.Configuration = cfg;
+ LogManager.GetCurrentClassLogger().Info("Reconfigured logging");
+ }
+
+ private class StupidTarget : Target
+ {
+ private readonly LogsModule _module;
+ public StupidTarget(LogsModule module)
+ {
+ _module = module;
+ }
+
+ protected override void Write(LogEventInfo logEvent)
+ {
+ var message = logEvent.FormattedMessage;
+ if (logEvent.Exception is not null)
+ message += $"\n{logEvent.Exception}";
+
+ _module.OnLogMessageReceived(logEvent.TimeStamp, logEvent.Level, logEvent.LoggerName, message);
+ }
+ }
+}
diff --git a/TorchRemote.Plugin/Plugin.cs b/TorchRemote.Plugin/Plugin.cs
new file mode 100644
index 0000000..b76e23b
--- /dev/null
+++ b/TorchRemote.Plugin/Plugin.cs
@@ -0,0 +1,33 @@
+using System.IO;
+using System.Windows.Controls;
+using Torch;
+using Torch.API;
+using Torch.API.Managers;
+using Torch.API.Plugins;
+using Torch.API.Session;
+using Torch.Views;
+using TorchRemote.Plugin.Managers;
+
+namespace TorchRemote.Plugin;
+
+public class Plugin : TorchPluginBase, IWpfPlugin
+{
+ private Persistent _config = null!;
+
+ public override void Init(ITorchBase torch)
+ {
+ base.Init(torch);
+ _config = Persistent.Load(Path.Combine(StoragePath, "TorchRemote.cfg"));
+
+ Torch.Managers.AddManager(new ApiServerManager(Torch, _config.Data));
+ Torch.Managers.AddManager(new SettingManager(Torch));
+ Torch.Managers.GetManager()
+ .AddFactory(s => new ChatMonitorManager(s.Torch));
+ }
+
+ public UserControl GetControl() => new PropertyGrid
+ {
+ Margin = new(3),
+ DataContext = _config.Data
+ };
+}
diff --git a/TorchRemote.Plugin/TorchRemote.Plugin.csproj b/TorchRemote.Plugin/TorchRemote.Plugin.csproj
new file mode 100644
index 0000000..b45d623
--- /dev/null
+++ b/TorchRemote.Plugin/TorchRemote.Plugin.csproj
@@ -0,0 +1,99 @@
+
+
+
+ net48
+ enable
+ enable
+ x64
+ 10
+ true
+ $(SolutionDir)TorchBinaries\
+
+
+
+ none
+
+
+
+
+ $(TorchDir)NLog.dll
+ False
+
+
+ $(TorchDir)DedicatedServer64\Sandbox.Common.dll
+ False
+
+
+ $(TorchDir)DedicatedServer64\Sandbox.Game.dll
+ False
+
+
+ $(TorchDir)DedicatedServer64\Sandbox.Graphics.dll
+ False
+
+
+ $(TorchDir)DedicatedServer64\System.Memory.dll
+ False
+
+
+
+ $(TorchDir)Torch.dll
+ False
+
+
+ $(TorchDir)Torch.API.dll
+ False
+
+
+ $(TorchDir)Torch.Server.exe
+ False
+
+
+ $(TorchDir)DedicatedServer64\VRage.dll
+ False
+
+
+ $(TorchDir)DedicatedServer64\VRage.Game.dll
+ False
+
+
+ $(TorchDir)DedicatedServer64\VRage.Input.dll
+ False
+
+
+ $(TorchDir)DedicatedServer64\VRage.Library.dll
+ False
+
+
+ $(TorchDir)DedicatedServer64\VRage.Math.dll
+ False
+
+
+ $(TorchDir)DedicatedServer64\VRage.Network.dll
+ False
+
+
+
+
+
+
+
+
+
+
+
+
+
+ PreserveNewest
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/TorchRemote.Plugin/Utils/Extensions.cs b/TorchRemote.Plugin/Utils/Extensions.cs
new file mode 100644
index 0000000..253d845
--- /dev/null
+++ b/TorchRemote.Plugin/Utils/Extensions.cs
@@ -0,0 +1,29 @@
+using System.Security.Cryptography;
+using System.Text;
+using Sandbox.Engine.Multiplayer;
+using Sandbox.Engine.Networking;
+using Sandbox.Game;
+using Sandbox.Game.World;
+using TorchRemote.Models.Shared;
+namespace TorchRemote.Plugin.Utils;
+
+public static class Extensions
+{
+ public static void ApplyDynamically(this ServerSettings settings)
+ {
+ MyGameService.GameServer.SetServerName(settings.ServerName);
+
+ MyMultiplayer.Static.HostName = settings.ServerName;
+ MyMultiplayer.Static.WorldName = settings.MapName;
+ MySession.Static.Name = settings.MapName;
+ MyMultiplayer.Static.MemberLimit = settings.MemberLimit;
+
+ MyCachedServerItem.SendSettingsToSteam();
+ }
+
+ public static Guid ToGuid(this string s)
+ {
+ using var md5 = MD5.Create();
+ return new(md5.ComputeHash(Encoding.UTF8.GetBytes(s)));
+ }
+}
diff --git a/TorchRemote.Plugin/Utils/JsonDataAttribute.cs b/TorchRemote.Plugin/Utils/JsonDataAttribute.cs
new file mode 100644
index 0000000..a1bce52
--- /dev/null
+++ b/TorchRemote.Plugin/Utils/JsonDataAttribute.cs
@@ -0,0 +1,34 @@
+using System.Text.Json;
+using EmbedIO;
+using EmbedIO.WebApi;
+namespace TorchRemote.Plugin.Utils;
+
+///
+/// Specifies that a parameter of a controller method will receive
+/// an object obtained by deserializing the request body as JSON.
+/// The received object will be
+/// only if the deserialized object is null.
+/// If the request body is not valid JSON,
+/// or if it cannot be deserialized to the type of the parameter,
+/// a 400 Bad Request response will be sent to the client.
+/// This class cannot be inherited.
+///
+///
+///
+[AttributeUsage(AttributeTargets.Parameter)]
+public class JsonDataAttribute : Attribute, IRequestDataAttribute
+{
+ ///
+ public async Task