├── .gitattributes ├── .gitignore ├── README.md ├── SEWA.Mod ├── CubeBlocks.sbc ├── Properties │ └── AssemblyInfo.cs ├── SEWA.Mod.csproj ├── WebApiBlockComp.cs └── WebApiSessionComp.cs ├── SEWA.sln └── SEWA ├── Controllers ├── ActionController.cs ├── BlockController.cs ├── Controller.cs ├── GridController.cs └── PropertyController.cs ├── Extensions.cs ├── Properties └── AssemblyInfo.cs ├── Request.cs ├── Router.cs ├── SEWA.csproj ├── SewaServer.cs ├── SkipEmptyContractResolver.cs ├── ValueBag.cs ├── ViewModels ├── BlockProperty.cs ├── Grid.cs ├── Inventory.cs ├── InventoryItem.cs └── TerminalBlock.cs ├── WebApiPlugin.cs └── packages.config /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | 24 | # Visual Studio 2015 cache/options directory 25 | .vs/ 26 | # Uncomment if you have tasks that create the project's static files in wwwroot 27 | #wwwroot/ 28 | 29 | # MSTest test Results 30 | [Tt]est[Rr]esult*/ 31 | [Bb]uild[Ll]og.* 32 | 33 | # NUNIT 34 | *.VisualState.xml 35 | TestResult.xml 36 | 37 | # Build Results of an ATL Project 38 | [Dd]ebugPS/ 39 | [Rr]eleasePS/ 40 | dlldata.c 41 | 42 | # DNX 43 | project.lock.json 44 | artifacts/ 45 | 46 | *_i.c 47 | *_p.c 48 | *_i.h 49 | *.ilk 50 | *.meta 51 | *.obj 52 | *.pch 53 | *.pdb 54 | *.pgc 55 | *.pgd 56 | *.rsp 57 | *.sbr 58 | *.tlb 59 | *.tli 60 | *.tlh 61 | *.tmp 62 | *.tmp_proj 63 | *.log 64 | *.vspscc 65 | *.vssscc 66 | .builds 67 | *.pidb 68 | *.svclog 69 | *.scc 70 | 71 | # Chutzpah Test files 72 | _Chutzpah* 73 | 74 | # Visual C++ cache files 75 | ipch/ 76 | *.aps 77 | *.ncb 78 | *.opendb 79 | *.opensdf 80 | *.sdf 81 | *.cachefile 82 | 83 | # Visual Studio profiler 84 | *.psess 85 | *.vsp 86 | *.vspx 87 | *.sap 88 | 89 | # TFS 2012 Local Workspace 90 | $tf/ 91 | 92 | # Guidance Automation Toolkit 93 | *.gpState 94 | 95 | # ReSharper is a .NET coding add-in 96 | _ReSharper*/ 97 | *.[Rr]e[Ss]harper 98 | *.DotSettings.user 99 | 100 | # JustCode is a .NET coding add-in 101 | .JustCode 102 | 103 | # TeamCity is a build add-in 104 | _TeamCity* 105 | 106 | # DotCover is a Code Coverage Tool 107 | *.dotCover 108 | 109 | # NCrunch 110 | _NCrunch_* 111 | .*crunch*.local.xml 112 | nCrunchTemp_* 113 | 114 | # MightyMoose 115 | *.mm.* 116 | AutoTest.Net/ 117 | 118 | # Web workbench (sass) 119 | .sass-cache/ 120 | 121 | # Installshield output folder 122 | [Ee]xpress/ 123 | 124 | # DocProject is a documentation generator add-in 125 | DocProject/buildhelp/ 126 | DocProject/Help/*.HxT 127 | DocProject/Help/*.HxC 128 | DocProject/Help/*.hhc 129 | DocProject/Help/*.hhk 130 | DocProject/Help/*.hhp 131 | DocProject/Help/Html2 132 | DocProject/Help/html 133 | 134 | # Click-Once directory 135 | publish/ 136 | 137 | # Publish Web Output 138 | *.[Pp]ublish.xml 139 | *.azurePubxml 140 | # TODO: Comment the next line if you want to checkin your web deploy settings 141 | # but database connection strings (with potential passwords) will be unencrypted 142 | *.pubxml 143 | *.publishproj 144 | 145 | # NuGet Packages 146 | *.nupkg 147 | # The packages folder can be ignored because of Package Restore 148 | **/packages/* 149 | # except build/, which is used as an MSBuild target. 150 | !**/packages/build/ 151 | # Uncomment if necessary however generally it will be regenerated when needed 152 | #!**/packages/repositories.config 153 | # NuGet v3's project.json files produces more ignoreable files 154 | *.nuget.props 155 | *.nuget.targets 156 | 157 | # Microsoft Azure Build Output 158 | csx/ 159 | *.build.csdef 160 | 161 | # Microsoft Azure Emulator 162 | ecf/ 163 | rcf/ 164 | 165 | # Microsoft Azure ApplicationInsights config file 166 | ApplicationInsights.config 167 | 168 | # Windows Store app package directory 169 | AppPackages/ 170 | BundleArtifacts/ 171 | 172 | # Visual Studio cache files 173 | # files ending in .cache can be ignored 174 | *.[Cc]ache 175 | # but keep track of directories ending in .cache 176 | !*.[Cc]ache/ 177 | 178 | # Others 179 | ClientBin/ 180 | ~$* 181 | *~ 182 | *.dbmdl 183 | *.dbproj.schemaview 184 | *.pfx 185 | *.publishsettings 186 | node_modules/ 187 | orleans.codegen.cs 188 | 189 | # RIA/Silverlight projects 190 | Generated_Code/ 191 | 192 | # Backup & report files from converting an old project file 193 | # to a newer Visual Studio version. Backup files are not needed, 194 | # because we have git ;-) 195 | _UpgradeReport_Files/ 196 | Backup*/ 197 | UpgradeLog*.XML 198 | UpgradeLog*.htm 199 | 200 | # SQL Server files 201 | *.mdf 202 | *.ldf 203 | 204 | # Business Intelligence projects 205 | *.rdl.data 206 | *.bim.layout 207 | *.bim_*.settings 208 | 209 | # Microsoft Fakes 210 | FakesAssemblies/ 211 | 212 | # GhostDoc plugin setting file 213 | *.GhostDoc.xml 214 | 215 | # Node.js Tools for Visual Studio 216 | .ntvs_analysis.dat 217 | 218 | # Visual Studio 6 build log 219 | *.plg 220 | 221 | # Visual Studio 6 workspace options file 222 | *.opt 223 | 224 | # Visual Studio LightSwitch build output 225 | **/*.HTMLClient/GeneratedArtifacts 226 | **/*.DesktopClient/GeneratedArtifacts 227 | **/*.DesktopClient/ModelManifest.xml 228 | **/*.Server/GeneratedArtifacts 229 | **/*.Server/ModelManifest.xml 230 | _Pvt_Extensions 231 | 232 | # Paket dependency manager 233 | .paket/paket.exe 234 | 235 | # FAKE - F# Make 236 | .fake/ 237 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![SEWA](http://i.imgur.com/ujFVqjk.png) 2 | 3 | # Command your ships over the internet! 4 | This project is a plugin+mod pair for Space Engineers dedicated servers that allows players to interface with their grids over the internet via a RESTful HTTP interface. Using this API anyone could create a control or monitoring application for Space Engineers such as a control panel on a mobile app or a program that notifies you if your ship is under attack. 5 | 6 | This project will be considered feature complete once it exposes the same features accessible to the Programmable Block but may also add additional features such as a web API for server management. 7 | 8 | More information about the usage of this project will be available as it becomes more stable - it's still in very early development and not yet feature complete. 9 | 10 | ![SCREENSHOT](http://i.imgur.com/UEHSpwq.jpg) 11 | -------------------------------------------------------------------------------- /SEWA.Mod/CubeBlocks.sbc: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | TextPanel 7 | WebAPI 8 | 9 | WebAPI Block 10 | Textures\GUI\Icons\Fake.dds 11 | Large 12 | TriangleMesh 13 | 14 | 15 | Models\Cubes\Large\LCDPanel.mwm 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | WebAPI 33 | Y 34 | Light 35 | 3 36 | 214 37 | ParticleElectrical 38 | Utility 39 | 0.00002 40 | 41 | 42 | 43 | 44 | TextPanel 45 | SmallWebAPI 46 | 47 | WebAPI Block 48 | Textures\GUI\Icons\Fake.dds 49 | Small 50 | TriangleMesh 51 | 52 | 53 | Models\Cubes\Small\TextPanel.mwm 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | WebAPI 71 | Y 72 | Light 73 | 3 74 | 214 75 | ParticleElectrical 76 | Utility 77 | 0.00002 78 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /SEWA.Mod/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("SEWebAPI")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SEWebAPI")] 13 | [assembly: AssemblyCopyright("Copyright © 2016")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("9af96577-1525-412a-971c-b6780d10d23f")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /SEWA.Mod/SEWA.Mod.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {9AF96577-1525-412A-971C-B6780D10D23F} 8 | Library 9 | Properties 10 | SEWA.Mod 11 | SEWA.Mod 12 | v4.6.1 13 | 512 14 | 15 | 16 | 17 | true 18 | bin\x64\Debug\ 19 | DEBUG;TRACE 20 | full 21 | x64 22 | prompt 23 | MinimumRecommendedRules.ruleset 24 | 25 | 26 | bin\x64\Release\ 27 | TRACE 28 | true 29 | pdbonly 30 | x64 31 | prompt 32 | MinimumRecommendedRules.ruleset 33 | 34 | 35 | 36 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\HavokWrapper.dll 37 | False 38 | 39 | 40 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\Sandbox.Common.dll 41 | False 42 | 43 | 44 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\Sandbox.Game.dll 45 | False 46 | 47 | 48 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\Sandbox.Graphics.dll 49 | False 50 | 51 | 52 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\SpaceEngineers.Game.dll 53 | False 54 | 55 | 56 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\SpaceEngineers.ObjectBuilders.dll 57 | False 58 | 59 | 60 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\SpaceEngineers.ObjectBuilders.XmlSerializers.dll 61 | False 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.dll 73 | 74 | 75 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Audio.dll 76 | 77 | 78 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Game.dll 79 | 80 | 81 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Game.XmlSerializers.dll 82 | 83 | 84 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Input.dll 85 | 86 | 87 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Library.dll 88 | 89 | 90 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Math.dll 91 | 92 | 93 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Native.dll 94 | 95 | 96 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.OpenVRWrapper.dll 97 | 98 | 99 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Render.dll 100 | 101 | 102 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Render11.dll 103 | 104 | 105 | C:\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Scripting.dll 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 121 | -------------------------------------------------------------------------------- /SEWA.Mod/WebApiBlockComp.cs: -------------------------------------------------------------------------------- 1 | using Sandbox.Common.ObjectBuilders; 2 | using VRage.Game.Components; 3 | using VRage.ObjectBuilders; 4 | 5 | namespace SEWA.Mod 6 | { 7 | [MyEntityComponentDescriptor(typeof(MyObjectBuilder_TextPanel), true)] 8 | public class WebApiBlockComp : MyGameLogicComponent 9 | { 10 | private MyObjectBuilder_EntityBase _objectBuilder; 11 | public string LocalKey { get; set; } 12 | 13 | public override void Init(MyObjectBuilder_EntityBase objectBuilder) 14 | { 15 | _objectBuilder = objectBuilder; 16 | base.Init(objectBuilder); 17 | } 18 | 19 | public override MyObjectBuilder_EntityBase GetObjectBuilder(bool copy = false) 20 | { 21 | return copy ? (MyObjectBuilder_EntityBase)_objectBuilder.Clone() : _objectBuilder; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SEWA.Mod/WebApiSessionComp.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Text; 4 | using Sandbox.ModAPI; 5 | using Sandbox.ModAPI.Interfaces.Terminal; 6 | using VRage.Game.Components; 7 | using VRage.Game.GUI.TextPanel; 8 | using VRage.ModAPI; 9 | using VRage.Utils; 10 | 11 | namespace SEWA.Mod 12 | { 13 | [MySessionComponentDescriptor(MyUpdateOrder.AfterSimulation)] 14 | public class WebApiSessionComp : MySessionComponentBase 15 | { 16 | private IMyTerminalControlCheckbox _showQrControl; 17 | private IMyTerminalControlTextbox _keyControl; 18 | private IMyTerminalControlButton _genControl; 19 | private bool _init; 20 | 21 | public override void UpdateAfterSimulation() 22 | { 23 | if (_init || MyAPIGateway.TerminalControls == null || MyAPIGateway.Multiplayer == null) 24 | return; 25 | 26 | _init = true; 27 | 28 | //Don't do anything in this class on the server 29 | if (MyAPIGateway.Session.IsServer) 30 | return; 31 | 32 | MyAPIGateway.TerminalControls.CustomControlGetter += TerminalControlsOnCustomControlGetter; 33 | MyAPIGateway.Multiplayer.RegisterMessageHandler(7331, UpdateLocalKey); 34 | InitControls(); 35 | } 36 | 37 | private void UpdateLocalKey(byte[] bytes) 38 | { 39 | var id = BitConverter.ToInt64(bytes, 0); 40 | var key = BitConverter.ToString(bytes, 8); 41 | 42 | if (!MyAPIGateway.Entities.EntityExists(id)) 43 | return; 44 | 45 | var logic = MyAPIGateway.Entities.GetEntityById(id)?.GameLogic?.GetAs(); 46 | if (logic == null) 47 | return; 48 | logic.LocalKey = key; 49 | _keyControl.UpdateVisual(); 50 | } 51 | 52 | private static void RequestKey(IMyEntity entity, bool generateNew = false) 53 | { 54 | var data = new byte[9]; 55 | data[8] = generateNew ? (byte)1 : (byte)0; 56 | var id = BitConverter.GetBytes(entity.EntityId); 57 | Array.Copy(id, data, 8); 58 | 59 | MyAPIGateway.Multiplayer.SendMessageToServer(7331, data); 60 | } 61 | 62 | private void InitControls() 63 | { 64 | _showQrControl = MyAPIGateway.TerminalControls.CreateControl(""); 65 | _showQrControl.Title = MyStringId.GetOrCompute("Show QR Code"); 66 | _showQrControl.Getter = b => ((IMyTextPanel)b).ShowOnScreen == ShowTextOnScreenFlag.PUBLIC; 67 | _showQrControl.Setter = (b, v) => 68 | { 69 | ((IMyTextPanel)b).SetShowOnScreen(v ? ShowTextOnScreenFlag.PUBLIC : ShowTextOnScreenFlag.NONE); 70 | }; 71 | 72 | _keyControl = MyAPIGateway.TerminalControls.CreateControl(""); 73 | _keyControl.Title = MyStringId.GetOrCompute("API Key"); 74 | _keyControl.Getter = b => 75 | { 76 | var logic = b.GameLogic.GetAs(); 77 | if (string.IsNullOrEmpty(logic?.LocalKey)) 78 | RequestKey(b); 79 | 80 | return new StringBuilder(logic?.LocalKey ?? ""); 81 | }; 82 | _keyControl.Setter = (b, v) => { }; 83 | 84 | _genControl = MyAPIGateway.TerminalControls.CreateControl(""); 85 | _genControl.Title = MyStringId.GetOrCompute("Generate New Key"); 86 | _genControl.Action = b => RequestKey(b, true); 87 | } 88 | 89 | private void TerminalControlsOnCustomControlGetter(IMyTerminalBlock block, List controls) 90 | { 91 | if (!(block is IMyTextPanel) || !block.BlockDefinition.SubtypeId.Contains("WebAPI")) 92 | return; 93 | 94 | controls.RemoveAll(x => !(x is IMyTerminalControlOnOffSwitch)); 95 | controls.Add(_keyControl); 96 | controls.Add(_genControl); 97 | controls.Add(_showQrControl); 98 | } 99 | 100 | protected override void UnloadData() 101 | { 102 | MyAPIGateway.TerminalControls.CustomControlGetter -= TerminalControlsOnCustomControlGetter; 103 | MyAPIGateway.Multiplayer.UnregisterMessageHandler(7331, UpdateLocalKey); 104 | } 105 | } 106 | } -------------------------------------------------------------------------------- /SEWA.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26020.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SEWA", "SEWA\SEWA.csproj", "{E6CC47A8-7E77-4157-A369-F9602BB5DC22}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SEWA.Mod", "SEWA.Mod\SEWA.Mod.csproj", "{9AF96577-1525-412A-971C-B6780D10D23F}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|x64 = Debug|x64 13 | Release|x64 = Release|x64 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {E6CC47A8-7E77-4157-A369-F9602BB5DC22}.Debug|x64.ActiveCfg = Debug|x64 17 | {E6CC47A8-7E77-4157-A369-F9602BB5DC22}.Debug|x64.Build.0 = Debug|x64 18 | {E6CC47A8-7E77-4157-A369-F9602BB5DC22}.Release|x64.ActiveCfg = Release|x64 19 | {E6CC47A8-7E77-4157-A369-F9602BB5DC22}.Release|x64.Build.0 = Release|x64 20 | {9AF96577-1525-412A-971C-B6780D10D23F}.Debug|x64.ActiveCfg = Debug|x64 21 | {9AF96577-1525-412A-971C-B6780D10D23F}.Debug|x64.Build.0 = Debug|x64 22 | {9AF96577-1525-412A-971C-B6780D10D23F}.Release|x64.ActiveCfg = Release|x64 23 | {9AF96577-1525-412A-971C-B6780D10D23F}.Release|x64.Build.0 = Release|x64 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /SEWA/Controllers/ActionController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Sandbox.ModAPI; 8 | using Sandbox.ModAPI.Ingame; 9 | using SEWA.ViewModels; 10 | using Torch.API; 11 | using VRage.ModAPI; 12 | using IMyTerminalBlock = Sandbox.ModAPI.IMyTerminalBlock; 13 | 14 | namespace SEWA.Controllers 15 | { 16 | public class ActionController : Controller 17 | { 18 | /// 19 | public override async Task PostAsync() 20 | { 21 | long id; 22 | string actionName; 23 | if (!(ValueBag.TryGet("id", out id) && ValueBag.TryGet("action", out actionName))) 24 | { 25 | await Request.RespondAsync("Invalid parameters.", HttpStatusCode.BadRequest); 26 | return; 27 | } 28 | 29 | await Torch.InvokeAsync(() => 30 | { 31 | MyAPIGateway.Entities.TryGetEntityById(id, out IMyEntity entity); 32 | if (entity is IMyTerminalBlock terminalBlock && terminalBlock.HasAction(actionName)) 33 | terminalBlock.ApplyAction(actionName); 34 | }); 35 | 36 | await Request.RespondAsync(null, HttpStatusCode.OK); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /SEWA/Controllers/BlockController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Sandbox.Game.Entities.Cube; 8 | using Sandbox.ModAPI; 9 | using SEWA.ViewModels; 10 | using Torch.API; 11 | using VRage.ModAPI; 12 | 13 | namespace SEWA.Controllers 14 | { 15 | public class BlockController : Controller 16 | { 17 | /// 18 | public override async Task GetAsync() 19 | { 20 | long id = 0; 21 | //if (!long.TryParse(request.PathSegments.Last(), out id)) 22 | if (!ValueBag.TryGet("id", out id)) 23 | { 24 | await Request.RespondAsync("Invalid block ID", HttpStatusCode.BadRequest); 25 | return; 26 | } 27 | 28 | TerminalBlock block = null; 29 | await Torch.InvokeAsync(() => 30 | { 31 | MyAPIGateway.Entities.TryGetEntityById(id, out IMyEntity entity); 32 | if (entity is IMyTerminalBlock terminalBlock) 33 | block = new TerminalBlock(terminalBlock, false); 34 | }); 35 | 36 | if (block != null) 37 | { 38 | await Request.RespondAsync(block, HttpStatusCode.OK); 39 | return; 40 | } 41 | 42 | await Request.RespondAsync("Block not found", HttpStatusCode.NotFound); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /SEWA/Controllers/Controller.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using NLog; 9 | using Torch.API; 10 | 11 | namespace SEWA.Controllers 12 | { 13 | public abstract class Controller 14 | { 15 | public ITorchBase Torch { get; set; } 16 | public ValueBag ValueBag { get; set; } 17 | public Request Request { get; set; } 18 | 19 | protected static readonly Logger Log = LogManager.GetLogger("SEWA"); 20 | 21 | public async Task HandleRequestAsync() 22 | { 23 | try 24 | { 25 | switch (Request.Method.Method) 26 | { 27 | case "POST": 28 | await PostAsync(); 29 | break; 30 | case "PUT": 31 | await PutAsync(); 32 | break; 33 | case "GET": 34 | await GetAsync(); 35 | break; 36 | case "DELETE": 37 | await DeleteAsync(); 38 | break; 39 | } 40 | } 41 | catch (Exception e) 42 | { 43 | Log.Error("Error handling request."); 44 | Log.Error(e); 45 | await Request.RespondAsync("Internal error.", HttpStatusCode.InternalServerError); 46 | } 47 | } 48 | 49 | public virtual async Task GetAsync() 50 | { 51 | await Request.RespondAsync("", HttpStatusCode.NotImplemented); 52 | } 53 | 54 | public virtual async Task PutAsync() 55 | { 56 | await Request.RespondAsync("", HttpStatusCode.NotImplemented); 57 | } 58 | 59 | public virtual async Task PostAsync() 60 | { 61 | await Request.RespondAsync("", HttpStatusCode.NotImplemented); 62 | } 63 | 64 | public virtual async Task DeleteAsync() 65 | { 66 | await Request.RespondAsync("", HttpStatusCode.NotImplemented); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /SEWA/Controllers/GridController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Sandbox.Game.Entities.Cube; 8 | using Sandbox.ModAPI; 9 | using SEWA.ViewModels; 10 | using Torch.API; 11 | using VRage.Game.ModAPI; 12 | using VRage.ModAPI; 13 | 14 | namespace SEWA.Controllers 15 | { 16 | public class GridController : Controller 17 | { 18 | /// 19 | public override async Task GetAsync() 20 | { 21 | long id = 0; 22 | //if (!long.TryParse(request.PathSegments.Last(), out id)) 23 | if (!ValueBag.TryGet("id", out id)) 24 | { 25 | await Request.RespondAsync("Invalid grid ID", HttpStatusCode.BadRequest); 26 | return; 27 | } 28 | 29 | Grid grid = null; 30 | await Torch.InvokeAsync(() => 31 | { 32 | MyAPIGateway.Entities.TryGetEntityById(id, out IMyEntity entity); 33 | if (entity is IMyCubeGrid cubeGrid) 34 | grid = new Grid(cubeGrid); 35 | }); 36 | 37 | if (grid != null) 38 | { 39 | await Request.RespondAsync(grid, HttpStatusCode.OK); 40 | return; 41 | } 42 | 43 | await Request.RespondAsync("Grid not found", HttpStatusCode.NotFound); 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /SEWA/Controllers/PropertyController.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using Newtonsoft.Json; 8 | using Sandbox.ModAPI; 9 | using SEWA.ViewModels; 10 | using Torch.API; 11 | using VRage.Game.ModAPI; 12 | using VRage.ModAPI; 13 | 14 | namespace SEWA.Controllers 15 | { 16 | public class PropertyController : Controller 17 | { 18 | /// 19 | public override async Task GetAsync() 20 | { 21 | var values = GetValues(); 22 | 23 | BlockProperty property = null; 24 | await Torch.InvokeAsync(() => 25 | { 26 | MyAPIGateway.Entities.TryGetEntityById(values.Id, out IMyEntity entity); 27 | if (entity is IMyTerminalBlock block) 28 | { 29 | property = new BlockProperty(block.GetProperty(values.Property), block); 30 | } 31 | }); 32 | 33 | if (property != null) 34 | { 35 | await Request.RespondAsync(property, HttpStatusCode.OK); 36 | return; 37 | } 38 | 39 | await Request.RespondAsync("Block or property not found.", HttpStatusCode.NotFound); 40 | } 41 | 42 | /// 43 | public override async Task PutAsync() 44 | { 45 | if (!Request.QueryString.AllKeys.Contains("value")) 46 | { 47 | await Request.RespondAsync("No value supplied.", HttpStatusCode.BadRequest); 48 | } 49 | 50 | var input = Request.QueryString["value"]; 51 | Log.Debug($"Put input: {input}"); 52 | var values = GetValues(); 53 | 54 | bool success = false; 55 | await Torch.InvokeAsync(() => 56 | { 57 | MyAPIGateway.Entities.TryGetEntityById(values.Id, out IMyEntity entity); 58 | if (entity is IMyTerminalBlock block) 59 | { 60 | success = block.GetProperty(values.Property).TrySetValue(block, input); 61 | } 62 | }); 63 | 64 | if (success) 65 | await Request.RespondAsync("Property set.", HttpStatusCode.OK); 66 | else 67 | await Request.RespondAsync("Setting property failed.", HttpStatusCode.InternalServerError); 68 | } 69 | 70 | public (long Id, string Property) GetValues() 71 | { 72 | ValueBag.TryGet("property", out string prop); 73 | ValueBag.TryGet("id", out long id); 74 | 75 | return (id, prop); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /SEWA/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Sandbox.ModAPI; 7 | using Sandbox.ModAPI.Interfaces; 8 | using VRage.Game.ModAPI; 9 | using VRageMath; 10 | 11 | namespace SEWA 12 | { 13 | public static class Extensions 14 | { 15 | public static Type GetValueType(this ITerminalProperty prop) 16 | { 17 | if (!(prop is ITerminalProperty)) 18 | return null; 19 | 20 | var type = prop.GetType(); 21 | return type.GenericTypeArguments[0]; 22 | } 23 | 24 | public static bool TrySetValue(this ITerminalProperty prop, IMyTerminalBlock block, string value) 25 | { 26 | if (prop is ITerminalProperty pBool) 27 | { 28 | if (!bool.TryParse(value, out bool bVal)) 29 | return false; 30 | pBool.SetValue(block, bVal); 31 | } 32 | else if (prop is ITerminalProperty pFloat) 33 | { 34 | if (!float.TryParse(value, out float fVal)) 35 | return false; 36 | pFloat.SetValue(block, fVal); 37 | } 38 | else if (prop is ITerminalProperty pColor) 39 | { 40 | var bytes = StringToByteArray(value); 41 | if (bytes.Length != 4) 42 | return false; 43 | var c = new Color {R = bytes[0], G = bytes[1], B = bytes[2], A = bytes[3]}; 44 | pColor.SetValue(block, c); 45 | } 46 | else if (prop is ITerminalProperty pSb) 47 | { 48 | pSb.SetValue(block, new StringBuilder(value)); 49 | } 50 | 51 | return true; 52 | } 53 | 54 | public static byte[] StringToByteArray(string hex) 55 | { 56 | return Enumerable.Range(0, hex.Length) 57 | .Where(x => x % 2 == 0) 58 | .Select(x => Convert.ToByte(hex.Substring(x, 2), 16)) 59 | .ToArray(); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /SEWA/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("SEWA")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SEWA")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("e6cc47a8-7e77-4157-a369-f9602bb5dc22")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /SEWA/Request.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.Diagnostics; 5 | using System.Linq; 6 | using System.Net; 7 | using System.Net.Http; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | using Newtonsoft.Json; 11 | using NLog; 12 | using Sandbox; 13 | 14 | namespace SEWA 15 | { 16 | public class Request 17 | { 18 | private readonly HttpListenerContext _context; 19 | private static Logger _log = LogManager.GetLogger("Request"); 20 | 21 | public string[] PathSegments { get; } 22 | public NameValueCollection QueryString { get; } 23 | public HttpMethod Method { get; } 24 | public string ApiKey { get; } 25 | public string Content { get; } 26 | 27 | public Request(HttpListenerContext context) 28 | { 29 | _context = context; 30 | PathSegments = context.Request.Url.Segments; 31 | QueryString = context.Request.QueryString; 32 | Method = new HttpMethod(context.Request.HttpMethod); 33 | ApiKey = context.Request.Headers.Get("ApiKey") ?? ""; 34 | Content = context.Request.InputStream.ReadString(); 35 | } 36 | 37 | public async Task RespondAsync(object responseObject, HttpStatusCode statusCode) 38 | { 39 | var sw = Stopwatch.StartNew(); 40 | var response = _context.Response; 41 | if (!response.OutputStream.CanWrite) 42 | return; 43 | 44 | await Task.Run(() => 45 | { 46 | var jsonObj = JsonConvert.SerializeObject(responseObject, Formatting.Indented, new JsonSerializerSettings{ContractResolver = new SkipEmptyContractResolver()}); 47 | var jsonBytes = Encoding.Unicode.GetBytes(jsonObj); 48 | response.ContentType = "application/json"; 49 | response.StatusCode = (int)statusCode; 50 | response.ContentLength64 = jsonBytes.Length; 51 | response.OutputStream.Write(jsonBytes, 0, jsonBytes.Length); 52 | response.OutputStream.Close(); 53 | }); 54 | sw.Stop(); 55 | _log.Debug($"Serialization/response took {sw.Elapsed.TotalMilliseconds}ms"); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /SEWA/Router.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Net; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using NLog; 8 | using SEWA.Controllers; 9 | using Torch.API; 10 | 11 | namespace SEWA 12 | { 13 | public class Router 14 | { 15 | private ITorchBase _torch; 16 | private readonly Dictionary _routes = new Dictionary(); 17 | private static Logger _log = LogManager.GetLogger("SEWA"); 18 | 19 | public Router(ITorchBase torchBase) 20 | { 21 | _torch = torchBase; 22 | } 23 | 24 | public void AddRoute(string route, Type controllerType) 25 | { 26 | var splitRoute = route.Split('/'); 27 | if (_routes.ContainsKey(splitRoute)) 28 | throw new InvalidOperationException("Route is already regsistered."); 29 | 30 | _routes.Add(splitRoute, controllerType); 31 | } 32 | 33 | public async Task RouteRequest(Request request) 34 | { 35 | //hack for testing 36 | //if (string.IsNullOrEmpty(request.ApiKey)) 37 | //{ 38 | // request.Respond("No API key", HttpStatusCode.Forbidden); 39 | // return; 40 | //} 41 | 42 | _log.Debug($"Trying to match route '{string.Join("/", request.PathSegments)}'"); 43 | 44 | if (_routes.ContainsKey(request.PathSegments)) 45 | { 46 | var controller = (Controller)Activator.CreateInstance(_routes[request.PathSegments]); 47 | controller.Torch = _torch; 48 | controller.Request = request; 49 | await controller.HandleRequestAsync(); 50 | return; 51 | } 52 | 53 | var bestRank = 0; 54 | string[] bestRoute = null; 55 | Type bestType = null; 56 | foreach (var route in _routes) 57 | { 58 | var rank = RankRoute(route.Key, request.PathSegments); 59 | _log.Debug($"Route '{string.Join("/", route.Key)}': {rank}"); 60 | 61 | if (rank > bestRank) 62 | { 63 | bestRank = rank; 64 | bestRoute = route.Key; 65 | bestType = route.Value; 66 | } 67 | } 68 | 69 | if (bestType == null) 70 | { 71 | _log.Debug("No route for request."); 72 | await request.RespondAsync("No route found.", HttpStatusCode.NotFound); 73 | return; 74 | } 75 | 76 | _log.Info($"Using controller {bestType}"); 77 | var bestController = (Controller)Activator.CreateInstance(bestType); 78 | bestController.Torch = _torch; 79 | bestController.ValueBag = MakeBag(bestRoute, request.PathSegments); 80 | bestController.Request = request; 81 | await bestController.HandleRequestAsync(); 82 | } 83 | 84 | /// 85 | /// Returns a rank of how suitable the route is for the given path. 86 | /// 87 | /// 88 | /// 89 | /// 90 | private int RankRoute(string[] route, string[] pathSegments) 91 | { 92 | if (route.Length > pathSegments.Length - 1) 93 | return -1; 94 | 95 | var rank = 0; 96 | for (var i = 0; i < route.Length; i++) 97 | { 98 | var segment = pathSegments[i + 1].TrimEnd('/'); 99 | 100 | if (route[i].StartsWith("{") && route[i].EndsWith("}")) 101 | rank++; 102 | else if (route[i] == segment) 103 | rank += 2; 104 | else 105 | return -1; 106 | } 107 | 108 | return rank; 109 | } 110 | 111 | private ValueBag MakeBag(string[] route, string[] pathSegments) 112 | { 113 | var bag = new ValueBag(); 114 | 115 | for (var i = 0; i < route.Length; i++) 116 | { 117 | var part = route[i]; 118 | if (part.StartsWith("{") && part.EndsWith("}")) 119 | { 120 | var name = part.Substring(1, part.Length - 2); 121 | var segment = pathSegments[i + 1].TrimEnd('/'); 122 | bag.Add(name, segment); 123 | } 124 | } 125 | 126 | return bag; 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /SEWA/SEWA.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {E6CC47A8-7E77-4157-A369-F9602BB5DC22} 8 | Library 9 | Properties 10 | SEWA 11 | SEWA 12 | v4.6.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | true 34 | bin\x64\Debug\ 35 | DEBUG;TRACE 36 | full 37 | x64 38 | prompt 39 | MinimumRecommendedRules.ruleset 40 | 41 | 42 | bin\x64\Release\ 43 | TRACE 44 | true 45 | pdbonly 46 | x64 47 | prompt 48 | MinimumRecommendedRules.ruleset 49 | 50 | 51 | 52 | ..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll 53 | 54 | 55 | ..\packages\NLog.4.4.1\lib\net45\NLog.dll 56 | 57 | 58 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\Sandbox.Common.dll 59 | 60 | 61 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\Sandbox.Game.dll 62 | 63 | 64 | ..\..\SEServerExtender\GameLibraries\Sandbox.Graphics.dll 65 | 66 | 67 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\SpaceEngineers.Game.dll 68 | 69 | 70 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\SpaceEngineers.ObjectBuilders.dll 71 | 72 | 73 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\SpaceEngineers.ObjectBuilders.XmlSerializers.dll 74 | 75 | 76 | 77 | 78 | ..\packages\System.ValueTuple.4.3.0\lib\netstandard1.0\System.ValueTuple.dll 79 | True 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | ..\..\Torch\Torch\bin\x64\Release\Torch.dll 89 | 90 | 91 | ..\..\Torch\Torch\bin\x64\Release\Torch.API.dll 92 | 93 | 94 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.dll 95 | 96 | 97 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Audio.dll 98 | 99 | 100 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Game.dll 101 | 102 | 103 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Game.XmlSerializers.dll 104 | 105 | 106 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Input.dll 107 | 108 | 109 | ..\..\SEServerExtender\GameLibraries\VRage.Library.dll 110 | 111 | 112 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Math.dll 113 | 114 | 115 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Native.dll 116 | 117 | 118 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.OpenVRWrapper.dll 119 | 120 | 121 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Render.dll 122 | 123 | 124 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Render11.dll 125 | 126 | 127 | ..\..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\SpaceEngineers\Bin64\VRage.Scripting.dll 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | -------------------------------------------------------------------------------- /SEWA/SewaServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Net; 6 | using System.Reflection; 7 | using System.Text; 8 | using System.Threading; 9 | using System.Threading.Tasks; 10 | using NLog; 11 | using SEWA.Controllers; 12 | using Torch.API; 13 | 14 | namespace SEWA 15 | { 16 | public class SewaServer 17 | { 18 | private ITorchBase _torch; 19 | private HttpListener _listener; 20 | private CancellationToken _token; 21 | private CancellationTokenSource _tokenSource; 22 | private Router _router; 23 | private static Logger _log = LogManager.GetLogger("SEWA"); 24 | 25 | public SewaServer(ITorchBase torch) 26 | { 27 | _torch = torch; 28 | _listener = new HttpListener(); 29 | _listener.Prefixes.Add("http://+:8080/"); 30 | _tokenSource = new CancellationTokenSource(); 31 | _token = _tokenSource.Token; 32 | _router = new Router(torch); 33 | 34 | _router.AddRoute("block/{id}", typeof(BlockController)); 35 | _router.AddRoute("grid/{id}", typeof(GridController)); 36 | _router.AddRoute("block/{id}/{property}", typeof(PropertyController)); 37 | _router.AddRoute("block/{id}/{action}", typeof(ActionController)); 38 | } 39 | 40 | public async Task Run() 41 | { 42 | await Task.Run(() => 43 | { 44 | _log.Info("Starting HTTP listener"); 45 | try 46 | { 47 | _listener.Start(); 48 | while (!_token.IsCancellationRequested) 49 | { 50 | var context = _listener.GetContext(); 51 | _log.Info($"Handling request: {context.Request.RawUrl}"); 52 | HandleRequestAsync(context); 53 | } 54 | } 55 | catch (HttpListenerException e) 56 | { 57 | _log.Error("Error in HTTP listener."); 58 | _log.Error(e); 59 | } 60 | 61 | _log.Info("Listen loop cancelled."); 62 | }, _token); 63 | } 64 | 65 | public void Stop() 66 | { 67 | _log.Info("Stopping listener"); 68 | _tokenSource.Cancel(); 69 | _listener.Stop(); 70 | } 71 | 72 | public async Task HandleRequestAsync(HttpListenerContext context) 73 | { 74 | _log.Debug("Handling request."); 75 | var sw = Stopwatch.StartNew(); 76 | await _router.RouteRequest(new Request(context)); 77 | sw.Stop(); 78 | _log.Debug($"Handled request in {sw.Elapsed.TotalMilliseconds}ms"); 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /SEWA/SkipEmptyContractResolver.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | using Newtonsoft.Json; 9 | using Newtonsoft.Json.Serialization; 10 | 11 | namespace SEWA 12 | { 13 | public class SkipEmptyContractResolver : DefaultContractResolver 14 | { 15 | public SkipEmptyContractResolver(bool shareCache = false) : base(shareCache) { } 16 | 17 | protected override JsonProperty CreateProperty(MemberInfo member, 18 | MemberSerialization memberSerialization) 19 | { 20 | JsonProperty property = base.CreateProperty(member, memberSerialization); 21 | bool isDefaultValueIgnored = 22 | ((property.DefaultValueHandling ?? DefaultValueHandling.Ignore) 23 | & DefaultValueHandling.Ignore) != 0; 24 | if (isDefaultValueIgnored 25 | && !typeof(string).IsAssignableFrom(property.PropertyType) 26 | && typeof(IEnumerable).IsAssignableFrom(property.PropertyType)) 27 | { 28 | Predicate newShouldSerialize = obj => { 29 | var collection = property.ValueProvider.GetValue(obj) as ICollection; 30 | return collection == null || collection.Count != 0; 31 | }; 32 | Predicate oldShouldSerialize = property.ShouldSerialize; 33 | property.ShouldSerialize = oldShouldSerialize != null 34 | ? o => oldShouldSerialize(o) && newShouldSerialize(o) 35 | : newShouldSerialize; 36 | } 37 | return property; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /SEWA/ValueBag.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.ComponentModel; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace SEWA 9 | { 10 | public class ValueBag 11 | { 12 | private readonly Dictionary _bag = new Dictionary(); 13 | 14 | public void Add(string key, string value) 15 | { 16 | _bag.Add(key, value); 17 | } 18 | 19 | public string Get(string key) 20 | { 21 | return _bag.ContainsKey(key) ? _bag[key] : null; 22 | } 23 | 24 | public bool TryGet(string key, out T value) 25 | { 26 | if (!_bag.ContainsKey(key)) 27 | { 28 | value = default(T); 29 | return false; 30 | } 31 | 32 | try 33 | { 34 | var converter = TypeDescriptor.GetConverter(typeof(T)); 35 | value = (T)converter.ConvertFromString(_bag[key]); 36 | return true; 37 | } 38 | catch (NotSupportedException) 39 | { 40 | value = default(T); 41 | return false; 42 | } 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /SEWA/ViewModels/BlockProperty.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection.Emit; 2 | using System.Text; 3 | using NLog; 4 | using Sandbox.ModAPI; 5 | using Sandbox.ModAPI.Interfaces; 6 | using VRage.Game.ModAPI; 7 | using VRageMath; 8 | 9 | namespace SEWA.ViewModels 10 | { 11 | public class BlockProperty 12 | { 13 | private static readonly Logger Log = LogManager.GetLogger(nameof(BlockProperty)); 14 | 15 | public string Name { get; } 16 | public string Type { get; } 17 | public object Value { get; } 18 | public bool IsValid { get; } = true; 19 | 20 | public BlockProperty(ITerminalProperty property, IMyTerminalBlock block) 21 | { 22 | Name = property.Id; 23 | Type = property.TypeName; 24 | 25 | if (property is ITerminalProperty pBool) 26 | Value = pBool.GetValue(block); 27 | else if (property is ITerminalProperty pFloat) 28 | Value = pFloat.GetValue(block); 29 | else if (property is ITerminalProperty pColor) 30 | Value = pColor.GetValue(block); 31 | else if (property is ITerminalProperty pSb) 32 | Value = pSb.GetValue(block).ToString(); 33 | else 34 | { 35 | #if DEBUG 36 | Log.Warn($"Falling back to reflection for type `{Type}`"); 37 | var propType = property.GetType(); 38 | if (propType.IsGenericType) 39 | { 40 | var getValueMethod = propType.GetMethod("GetValue", new[] { typeof(IMyCubeBlock) }); 41 | Value = getValueMethod.Invoke(property, new object[] { block }); 42 | } 43 | #else 44 | IsValid = false; 45 | Log.Warn($"Property {Type} not supported"); 46 | #endif 47 | } 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /SEWA/ViewModels/Grid.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Sandbox.ModAPI; 7 | using VRage.Game; 8 | using VRage.Game.ModAPI; 9 | using VRageMath; 10 | 11 | namespace SEWA.ViewModels 12 | { 13 | public class Grid 14 | { 15 | public string Name { get; } 16 | public Vector3D Position { get; } 17 | public Quaternion Orientation { get; } 18 | public List Blocks { get; } = new List(); 19 | 20 | public Grid(IMyCubeGrid grid) 21 | { 22 | Name = grid.DisplayName; 23 | Position = grid.PositionComp.GetPosition(); 24 | Orientation = Quaternion.CreateFromRotationMatrix(grid.PositionComp.WorldMatrix.GetOrientation()); 25 | 26 | grid.GetBlocks(new List(), b => 27 | { 28 | if (b.FatBlock is IMyTerminalBlock block) 29 | { 30 | Blocks.Add(new TerminalBlock(block)); 31 | } 32 | return false; 33 | }); 34 | } 35 | 36 | /* 37 | public Grid(MyObjectBuilder_CubeGrid gridBuilder) 38 | { 39 | Name = gridBuilder.DisplayName; 40 | Position = gridBuilder.PositionAndOrientation.Value.Position; 41 | Orientation = gridBuilder.PositionAndOrientation.Value.Orientation; 42 | 43 | foreach (var block in gridBuilder.CubeBlocks) 44 | { 45 | block 46 | } 47 | }*/ 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /SEWA/ViewModels/Inventory.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using VRage.Game.Entity; 3 | using VRage.Game.ModAPI; 4 | 5 | namespace SEWA.ViewModels 6 | { 7 | public class Inventory 8 | { 9 | public float CurrentVolume { get; } 10 | public float MaxVolume { get; } 11 | public List Items { get; } = new List(); 12 | 13 | public Inventory(IMyInventory inventory) 14 | { 15 | CurrentVolume = (float)inventory.CurrentVolume; 16 | MaxVolume = (float)inventory.MaxVolume; 17 | 18 | foreach (var item in inventory.GetItems()) 19 | { 20 | Items.Add(new InventoryItem((IMyInventoryItem)item)); 21 | } 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /SEWA/ViewModels/InventoryItem.cs: -------------------------------------------------------------------------------- 1 | using Sandbox.Game.Entities.Inventory; 2 | using VRage.Game; 3 | using VRage.Game.Entity; 4 | using VRage.Game.ModAPI; 5 | 6 | namespace SEWA.ViewModels 7 | { 8 | public class InventoryItem 9 | { 10 | public string Type { get; } 11 | public float Amount { get; } 12 | public float Mass { get; } 13 | public float Volume { get; } 14 | 15 | public InventoryItem(IMyInventoryItem item) 16 | { 17 | var content = item.Content; 18 | var adapter = MyInventoryItemAdapter.Static; 19 | adapter.Adapt(content.GetId()); 20 | 21 | Amount = (float)item.Amount; 22 | Mass = adapter.Mass * Amount; 23 | Volume = adapter.Volume * Amount; 24 | Type = $"{content.TypeId}/{content.SubtypeName}"; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /SEWA/ViewModels/TerminalBlock.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Sandbox.Definitions; 7 | using Sandbox.Game.Entities.Cube; 8 | using Sandbox.Game.Gui; 9 | using Sandbox.ModAPI; 10 | using Sandbox.ModAPI.Interfaces; 11 | using VRage.Game; 12 | using VRage.Game.ModAPI; 13 | using VRage.Game.ObjectBuilders.ComponentSystem; 14 | using static Sandbox.ModAPI.Ingame.TerminalBlockExtentions; 15 | 16 | namespace SEWA.ViewModels 17 | { 18 | public class TerminalBlock 19 | { 20 | public string Type { get; } 21 | public string Name { get; } 22 | public long Id { get; } 23 | public List Inventories { get; } = new List(); 24 | public List Properties { get; } = new List(); 25 | public List Actions { get; } = new List(); 26 | 27 | public TerminalBlock(IMyTerminalBlock block, bool light = true) 28 | { 29 | Name = block.CustomName; 30 | var def = block.BlockDefinition; 31 | Type = $"{def.TypeId}/{def.SubtypeId}"; 32 | Id = block.EntityId; 33 | 34 | if (light) 35 | return; 36 | 37 | if (block.HasInventory) 38 | { 39 | var count = block.InventoryCount; 40 | for (var i = 0; i < count; i++) 41 | { 42 | Inventories.Add(new Inventory(block.GetInventory(i))); 43 | } 44 | } 45 | 46 | block.GetProperties(new List(), p => 47 | { 48 | var prop = new BlockProperty(p, block); 49 | if (prop.IsValid) 50 | Properties.Add(prop); 51 | return false; 52 | }); 53 | 54 | foreach (var action in MyTerminalControlFactory.GetActions(block.GetType())) 55 | { 56 | Actions.Add(action.Id); 57 | } 58 | } 59 | 60 | /* 61 | public TerminalBlock(MyObjectBuilder_TerminalBlock blockBuilder, bool light = true) 62 | { 63 | Name = blockBuilder.CustomName; 64 | Type = $"{blockBuilder.TypeId}/{blockBuilder.SubtypeId}"; 65 | Id = blockBuilder.EntityId; 66 | 67 | if (light) 68 | return; 69 | 70 | foreach (var comp in blockBuilder.ComponentContainer.Components) 71 | { 72 | if (comp.Component is MyObjectBuilder_InventoryBase inventory) 73 | { 74 | Inventories.Add(new Inventory(inventory)); 75 | } 76 | 77 | if (comp.Component is myobjectbuilder_proper) 78 | } 79 | }*/ 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /SEWA/WebApiPlugin.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using NLog; 7 | using Torch; 8 | using Torch.API; 9 | 10 | namespace SEWA 11 | { 12 | [Plugin("SE Web API", "0.0.0.1", "c3cf8255-18dd-455a-8565-6fad78837acb")] 13 | public class WebApiPlugin : TorchPluginBase 14 | { 15 | private SewaServer _server; 16 | /// 17 | public override void Init(ITorchBase torch) 18 | { 19 | base.Init(torch); 20 | LogManager.GetLogger("SEWA").Info("Init"); 21 | _server = new SewaServer(torch); 22 | _server.Run(); 23 | } 24 | 25 | /// 26 | public override void Dispose() 27 | { 28 | _server.Stop(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /SEWA/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | --------------------------------------------------------------------------------