RynthServers as of 2026-11-10 (internal 5a8f64b): release 2026.11.10.1
This commit is contained in:
parent
3dd7e983c3
commit
8547236e48
27 changed files with 2961 additions and 16 deletions
|
|
@ -46,12 +46,22 @@ internal static class ServerPackCommands
|
|||
/// <summary>"/rserver [show|hide|toggle]": the window after it.</summary>
|
||||
public static string Window(string serverName, bool shown) => CommandReply.Shown($"The {serverName} window", shown);
|
||||
|
||||
/// <summary>The usage, two lines.</summary>
|
||||
public static string[] Usage(string serverName) => new[]
|
||||
/// <summary>
|
||||
/// The usage: two lines, then the server's own (ServerUsageLines), if any. With none, the two lines are
|
||||
/// exactly what every server plugin has always printed.
|
||||
/// </summary>
|
||||
public static string[] Usage(string serverName, IReadOnlyList<string>? serverLines = null)
|
||||
{
|
||||
$"/rserver [show|hide|toggle] - the {serverName} server card (also in the Mini Remote's Char section).",
|
||||
$"/rserver info - what is known about {serverName}; /rserver auto|on|off - this character's override.",
|
||||
};
|
||||
var lines = new List<string>
|
||||
{
|
||||
$"/rserver [show|hide|toggle] - the {serverName} server card (also in the Mini Remote's Char section).",
|
||||
$"/rserver info - what is known about {serverName}; /rserver auto|on|off - this character's override.",
|
||||
};
|
||||
if (serverLines != null)
|
||||
foreach (string l in serverLines)
|
||||
if (!string.IsNullOrWhiteSpace(l)) lines.Add(l.Trim());
|
||||
return lines.ToArray();
|
||||
}
|
||||
|
||||
public static string Unknown(string word) => $"Unknown '/rserver {word}'.";
|
||||
}
|
||||
|
|
|
|||
|
|
@ -21,6 +21,9 @@ namespace RynthCore.Plugin.ServerPack;
|
|||
/// <summary>RynthCore's verdict for this plugin's server.</summary>
|
||||
internal sealed record ServerVerdictView(string Name, bool Active, string Force, bool Detected, string Reason);
|
||||
|
||||
/// <summary>One entry of the server window's bar-icon dropdown: a click runs <paramref name="Command"/> as a chat command. <paramref name="Icon"/> is one Phosphor glyph.</summary>
|
||||
internal sealed record ServerBarMenuItem(string Id, string Tooltip, string Icon, string Command);
|
||||
|
||||
internal sealed class ServerPackModel
|
||||
{
|
||||
/// <summary>Payloads longer than this are not ours (a push is a few hundred bytes).</summary>
|
||||
|
|
@ -170,7 +173,7 @@ internal sealed class ServerPackModel
|
|||
/// shared "Server" section of the Mini Remote.
|
||||
/// </summary>
|
||||
public static string BuildSectionsJson(ServerPackInfo info, string pluginName, IReadOnlyList<ServerPage>? pages = null,
|
||||
IReadOnlyList<ServerWindow>? windows = null, bool frameless = false)
|
||||
IReadOnlyList<ServerWindow>? windows = null, bool frameless = false, IReadOnlyList<ServerBarMenuItem>? barMenu = null)
|
||||
{
|
||||
var sb = new StringBuilder(512);
|
||||
sb.Append("{\"version\":1,\"servers\":[{\"id\":").Append(Q(info.Id)).Append(",\"name\":").Append(Q(info.Name));
|
||||
|
|
@ -185,6 +188,20 @@ internal sealed class ServerPackModel
|
|||
sb.Append(",\"icon\":").Append(Q(WindowIcon));
|
||||
sb.Append(",\"width\":").Append(tabs ? ServerPackPages.Width : 460).Append(",\"height\":").Append(ServerPackPages.Height);
|
||||
sb.Append(",\"minWidth\":320,\"minHeight\":200,\"bar\":true,\"server\":").Append(Q(info.Id));
|
||||
// The bar icon's hover dropdown (RynthCore API 95); an older engine ignores the key.
|
||||
if (barMenu != null && barMenu.Count > 0)
|
||||
{
|
||||
sb.Append(",\"barMenu\":[");
|
||||
for (int i = 0; i < barMenu.Count; i++)
|
||||
{
|
||||
ServerBarMenuItem item = barMenu[i];
|
||||
sb.Append(i == 0 ? "" : ",").Append("{\"id\":").Append(Q(item.Id));
|
||||
sb.Append(",\"tooltip\":").Append(Q(item.Tooltip));
|
||||
sb.Append(",\"icon\":").Append(Q(item.Icon));
|
||||
sb.Append(",\"command\":").Append(Q(item.Command)).Append('}');
|
||||
}
|
||||
sb.Append(']');
|
||||
}
|
||||
sb.Append('}');
|
||||
// The server's own windows (ServerWindows, ServerPackWindows.cs, 2026-11-07).
|
||||
if (windows != null) sb.Append(ServerPackWindows.Json(windows, info.Id, frameless));
|
||||
|
|
|
|||
|
|
@ -32,7 +32,10 @@
|
|||
// SetProfileValue(key, n) a live number in its "RynthServer.Profile" ("values"), for other
|
||||
// plugins that apply a server rule without knowing the server.
|
||||
// ServerCommandVerbs(list) its own "/rserver <verb>" words, handled in ServerChatCommand.
|
||||
// ServerUsageLines(add) the usage lines for those words, after the shared two (help, unknown word).
|
||||
// RunOnTick(action) work for the next tick (a page's button, on the render thread).
|
||||
// ServerCardActions() the server's own buttons at the top of its card, under RynthCore's verdict
|
||||
// (render thread: ImGui calls only; queue work with RunOnTick).
|
||||
// Send(command) a chat command as if typed (pump thread, logged in only);
|
||||
// LogTagged(text) the engine log, "[RynthConquest] ..."; ChatLine(text) the chat window.
|
||||
// Resources\quests.<id>.csv (no code) the server's own quest list: embedded by ServerPlugin.props and
|
||||
|
|
@ -74,6 +77,8 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
|
|||
private readonly List<ServerPage> _pages;
|
||||
// The server's own windows (ServerWindows), validated the same way.
|
||||
private readonly List<ServerWindow> _windows;
|
||||
// The server window's bar-icon dropdown (ServerBarMenu), for the sections manifest.
|
||||
private readonly List<ServerBarMenuItem> _barMenu = new();
|
||||
private readonly List<string> _pageNotes = new();
|
||||
private readonly ServerPackSettings _settings = new(ServerPackSettings.DefaultPath(RynthPluginInfo.Name));
|
||||
private readonly ServerProfileValues _profileValues = new();
|
||||
|
|
@ -85,6 +90,8 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
|
|||
private readonly ConcurrentQueue<Action> _tickActions = new();
|
||||
// The server's own "/rserver" verbs (ServerCommandVerbs).
|
||||
private readonly HashSet<string> _serverVerbs = new(StringComparer.OrdinalIgnoreCase);
|
||||
// The server's own "/rserver" usage lines (ServerUsageLines), after the shared two.
|
||||
private readonly List<string> _usageLines = new();
|
||||
private volatile bool _loginComplete;
|
||||
private volatile string? _world;
|
||||
private bool _wasActive;
|
||||
|
|
@ -102,7 +109,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
|
|||
var verbs = new List<string>();
|
||||
ServerCommandVerbs(verbs);
|
||||
foreach (string v in verbs) if (!string.IsNullOrWhiteSpace(v)) _serverVerbs.Add(v.Trim());
|
||||
_ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages);
|
||||
ServerUsageLines(_usageLines.Add);
|
||||
_ui = new ServerPackUi(_model, RynthPluginInfo.Name + " " + Marshal.PtrToStringAnsi(VersionPointer), () => _world, _pages, DrawCardActions);
|
||||
ServerBarMenu(_barMenu);
|
||||
}
|
||||
|
||||
internal ServerPackInfo Info => _model.Info;
|
||||
|
|
@ -133,6 +142,11 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
|
|||
/// instead of being read as another server's id. Called once, from the constructor.
|
||||
/// </summary>
|
||||
partial void ServerCommandVerbs(List<string> verbs);
|
||||
/// <summary>
|
||||
/// Usage lines for the server's own verbs, printed after the shared two by "/rserver help" and an
|
||||
/// unknown word. Called once, from the constructor (no Host yet).
|
||||
/// </summary>
|
||||
partial void ServerUsageLines(Action<string> add);
|
||||
/// <summary>Extra lines for "/rserver info".</summary>
|
||||
partial void ServerInfoLines(Action<string> line);
|
||||
/// <summary>The server's own pages (ServerPackPages.cs). Called once, from the constructor (no Host yet).</summary>
|
||||
|
|
@ -147,6 +161,15 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
|
|||
/// <summary>Every frame while logged in (render thread, AC's main thread; the engine's ImGui context current).</summary>
|
||||
partial void ServerRender();
|
||||
/// <summary>
|
||||
/// Items for a hover dropdown on the server window's bar icon (RynthCore API 95; an older engine
|
||||
/// ignores it). Called once, from the constructor (no Host yet).
|
||||
/// </summary>
|
||||
partial void ServerBarMenu(List<ServerBarMenuItem> items);
|
||||
/// <summary>
|
||||
/// Drawn at the top of the server card, under RynthCore's verdict; render thread; queue work with RunOnTick.
|
||||
/// </summary>
|
||||
partial void ServerCardActions();
|
||||
/// <summary>
|
||||
/// An incoming chat line (pump thread, logged in only): set <paramref name="eat"/> to keep it out of
|
||||
/// the chat window (it comes in true when an earlier plugin already ate it).
|
||||
/// </summary>
|
||||
|
|
@ -165,6 +188,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
|
|||
/// <summary>The live numbers of the profile ("values"). Any thread.</summary>
|
||||
internal ServerProfileValues ProfileValues => _profileValues;
|
||||
|
||||
// A delegate cannot bind an unimplemented partial method (CS0762), so the card gets this wrapper.
|
||||
private void DrawCardActions() => ServerCardActions();
|
||||
|
||||
/// <summary>The pages this plugin draws.</summary>
|
||||
internal IReadOnlyList<ServerPage> Pages => _pages;
|
||||
|
||||
|
|
@ -250,6 +276,9 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
|
|||
catch (Exception ex) { LogTagged($"A queued action failed: {ex.GetType().Name}: {ex.Message}"); }
|
||||
}
|
||||
|
||||
// A queued web-panel open is answered from here (ServerPackWeb.cs).
|
||||
PollWeb();
|
||||
|
||||
bool active = Active;
|
||||
if (active && !_wasActive && Info.Botting == BottingPolicy.Forbidden)
|
||||
ChatLine($"[{RynthPluginInfo.Name}] {Info.Name} forbids bots: don't run RynthAi's combat, navigation or looting here.");
|
||||
|
|
@ -280,7 +309,7 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
|
|||
/// </summary>
|
||||
internal string? BuildSectionsJson()
|
||||
=> _sectionsJson ??= ServerPackModel.BuildSectionsJson(Info, RynthPluginInfo.Name, _pages, _windows,
|
||||
frameless: _windows.Count > 0 && Host.HasFramelessWindows);
|
||||
frameless: _windows.Count > 0 && Host.HasFramelessWindows, barMenu: _barMenu);
|
||||
|
||||
/// <summary>
|
||||
/// RynthPluginRenderEmbed "window:<id>": one of the server's own windows (ServerWindows), into the
|
||||
|
|
@ -466,9 +495,10 @@ public sealed partial class ServerPackPlugin : RynthPluginBase
|
|||
bool handled = false;
|
||||
ServerChatCommand(parts, ref handled);
|
||||
if (handled) return;
|
||||
if (verb == ServerVerb.Unknown) Reply.Fail(ServerPackCommands.Unknown(parts[1]) + " " + ServerPackCommands.Usage(Info.Name)[0]);
|
||||
else ChatLine(ServerPackCommands.Usage(Info.Name)[0]);
|
||||
ChatLine(ServerPackCommands.Usage(Info.Name)[1]);
|
||||
string[] usage = ServerPackCommands.Usage(Info.Name, _usageLines);
|
||||
if (verb == ServerVerb.Unknown) Reply.Fail(ServerPackCommands.Unknown(parts[1]) + " " + usage[0]);
|
||||
else ChatLine(usage[0]);
|
||||
for (int i = 1; i < usage.Length; i++) ChatLine(usage[i]);
|
||||
}
|
||||
|
||||
private void PrintInfo()
|
||||
|
|
|
|||
|
|
@ -26,6 +26,7 @@ internal sealed class ServerPackUi
|
|||
private readonly Func<string?> _world;
|
||||
private readonly string _windowTitle;
|
||||
private readonly IReadOnlyList<ServerPage> _pages;
|
||||
private readonly Action? _cardActions;
|
||||
private string _status = string.Empty;
|
||||
|
||||
/// <summary>The standalone window is open ("/rserver").</summary>
|
||||
|
|
@ -34,12 +35,14 @@ internal sealed class ServerPackUi
|
|||
/// <param name="pluginLabel">"RynthColdeve 0.1.0", for the title and the card.</param>
|
||||
/// <param name="world">The world name the client reports now (null when unknown).</param>
|
||||
/// <param name="pages">The server's own pages: tabs of the window after the card.</param>
|
||||
public ServerPackUi(ServerPackModel model, string pluginLabel, Func<string?> world, IReadOnlyList<ServerPage>? pages = null)
|
||||
/// <param name="cardActions">The server's own buttons, drawn under the verdict (render thread); null when it has none.</param>
|
||||
public ServerPackUi(ServerPackModel model, string pluginLabel, Func<string?> world, IReadOnlyList<ServerPage>? pages = null, Action? cardActions = null)
|
||||
{
|
||||
_model = model;
|
||||
_pluginLabel = pluginLabel;
|
||||
_world = world;
|
||||
_pages = pages ?? Array.Empty<ServerPage>();
|
||||
_cardActions = cardActions;
|
||||
_windowTitle = model.Info.Name + " server (" + pluginLabel + ")##server_" + model.Info.Id;
|
||||
}
|
||||
|
||||
|
|
@ -82,6 +85,7 @@ internal sealed class ServerPackUi
|
|||
{
|
||||
ServerPackInfo info = _model.Info;
|
||||
RenderVerdict(info);
|
||||
_cardActions?.Invoke();
|
||||
ImGui.Separator();
|
||||
RenderFacts(info);
|
||||
if (info.Commands.Length > 0)
|
||||
|
|
|
|||
232
Plugins/Shared/ServerPack/ServerPackWeb.cs
Normal file
232
Plugins/Shared/ServerPack/ServerPackWeb.cs
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
// ServerPackWeb.cs - the host side of ServerWebOpen: open a server's web page in the engine's web
|
||||
// panel when it has one, else in the system browser. A server's own code calls OpenWeb on the pump
|
||||
// (ServerChatCommand, a RunOnTick action); the answer goes to `done` exactly once, and it may run on
|
||||
// the pump (a refusal, or the tick's poll of a queued open) or on a worker thread (the browser). Reply
|
||||
// is any-thread. The answer never contains the URL, and nothing here logs it.
|
||||
//
|
||||
// The panel (RynthCore plugin API v94, docs\WEB_PANEL.md): ServerWebPanel.cs reads the engine's codes
|
||||
// and states and holds the one open the tick waits on (OnTick -> PollWeb). The engine calls are the
|
||||
// four NoInlining helpers at the bottom, the only code that names an SDK web-panel member, each called
|
||||
// inside catch (MissingMethodException) and catch (TypeLoadException): on a core whose
|
||||
// Runtime\PluginShared SDK predates the panel they fail that call, not the plugin's load.
|
||||
//
|
||||
// Never Process.Start inside acclient: the browser opens with ShellExecuteW, as the engine does
|
||||
// (ProblemReport.cs), on its own short-lived STA thread so the shell call never blocks the pump.
|
||||
using System;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
using RynthCore.PluginSdk;
|
||||
|
||||
namespace RynthCore.Plugin.ServerPack;
|
||||
|
||||
public sealed partial class ServerPackPlugin
|
||||
{
|
||||
[DllImport("shell32.dll", CharSet = CharSet.Unicode, EntryPoint = "ShellExecuteW")]
|
||||
private static extern IntPtr ShellExecuteW(IntPtr hwnd, string? operation, string file, string? parameters, string? directory, int showCmd);
|
||||
|
||||
private ServerWebPanel? _webPanel;
|
||||
|
||||
private ServerWebPanel WebPanel
|
||||
=> Volatile.Read(ref _webPanel)
|
||||
?? Interlocked.CompareExchange(ref _webPanel, new ServerWebPanel(new EngineWebPanel(this)), null)
|
||||
?? _webPanel!;
|
||||
|
||||
/// <summary>The engine has a web panel (HasWebPanel; false on an older core or SDK). Any thread.</summary>
|
||||
private bool PanelAvailable => WebPanel.Available;
|
||||
|
||||
private static void Finish(Action<WebOpenOutcome> done, WebOpenOutcome outcome)
|
||||
{
|
||||
try { done(outcome); } catch { }
|
||||
}
|
||||
|
||||
/// <summary>Opens the page (pump thread). `done` gets the route taken and a message without the URL, once.</summary>
|
||||
internal void OpenWeb(WebOpenRequest r, Action<WebOpenOutcome> done)
|
||||
{
|
||||
WebOpenRoute route = ServerWebOpen.Route(r, PanelAvailable);
|
||||
if (route == WebOpenRoute.Refused)
|
||||
{
|
||||
Finish(done, new WebOpenOutcome(route, false, "That page is not on this server's list of pages, so it was not opened."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (route == WebOpenRoute.Panel)
|
||||
{
|
||||
try
|
||||
{
|
||||
WebPanel.Open(r, Environment.TickCount64, result => AfterPanel(r, result, done));
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
AfterPanel(r, PanelResult.RefusedBeforeNavigate, done);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
OpenInBrowser(r, done);
|
||||
}
|
||||
|
||||
/// <summary>The panel's answer (pump thread: at once, or from the tick's poll). Exactly one Finish or browser open.</summary>
|
||||
private void AfterPanel(WebOpenRequest r, PanelResult result, Action<WebOpenOutcome> done)
|
||||
{
|
||||
try
|
||||
{
|
||||
// The one browser decision after the panel (ServerWebOpen.FallbackToBrowser: a refusal before
|
||||
// navigating only). Every other answer below ends without the browser: the code may be spent.
|
||||
if (ServerWebOpen.FallbackToBrowser(result))
|
||||
{
|
||||
LogTagged("web panel: " + result + ", using the browser");
|
||||
OpenInBrowser(r, done);
|
||||
return;
|
||||
}
|
||||
switch (result)
|
||||
{
|
||||
case PanelResult.Opened:
|
||||
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, true, "Opened in the web panel."));
|
||||
return;
|
||||
case PanelResult.OpenedInBrowserByEngine:
|
||||
// RynthCore opened the browser itself (and said so in chat): never a second time.
|
||||
LogTagged("web panel: OpenedInBrowserByEngine");
|
||||
Finish(done, new WebOpenOutcome(WebOpenRoute.Browser, true, "Opened in your browser."));
|
||||
return;
|
||||
case PanelResult.UrlNotAllowed:
|
||||
case PanelResult.BadArgs:
|
||||
// A plugin bug: the request did not pass the engine's checks. The browser would hide it.
|
||||
LogTagged("web panel: " + result + " (a plugin bug: the engine refused the request; not sent to the browser)");
|
||||
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel refused that page (a plugin bug, logged)."));
|
||||
return;
|
||||
case PanelResult.FailedAfterNavigate:
|
||||
LogTagged("web panel: FailedAfterNavigate");
|
||||
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel stopped while loading the page; open it again."));
|
||||
return;
|
||||
case PanelResult.Closed:
|
||||
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel was closed before the page loaded."));
|
||||
return;
|
||||
default:
|
||||
// NoAnswer (the poll timed out or the state could not be read), or Pending, which
|
||||
// ServerWebPanel never answers with. Neutral: the panel may still show; no browser.
|
||||
LogTagged("web panel: " + result);
|
||||
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel hasn't shown the page yet; it may still appear."));
|
||||
return;
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
Finish(done, new WebOpenOutcome(WebOpenRoute.Panel, false, "The web panel couldn't open that page."));
|
||||
}
|
||||
}
|
||||
|
||||
private void OpenInBrowser(WebOpenRequest r, Action<WebOpenOutcome> done)
|
||||
{
|
||||
if (!ServerWebOpen.TryGetAllowedUri(r.Url, r.AllowedHosts, out string url))
|
||||
{
|
||||
Finish(done, new WebOpenOutcome(WebOpenRoute.Refused, false, "That page is not on this server's list of pages, so it was not opened."));
|
||||
return;
|
||||
}
|
||||
var thread = new Thread(() =>
|
||||
{
|
||||
string message;
|
||||
bool ok;
|
||||
try
|
||||
{
|
||||
long code = ShellExecuteW(IntPtr.Zero, "open", url, null, null, 1).ToInt64();
|
||||
ok = code > 32;
|
||||
message = ok ? "Opened in your browser." : $"Couldn't open your browser (Windows error {code}).";
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
ok = false;
|
||||
message = "Couldn't open your browser (Windows error 0).";
|
||||
}
|
||||
Finish(done, new WebOpenOutcome(WebOpenRoute.Browser, ok, message));
|
||||
})
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "ServerPack web open",
|
||||
};
|
||||
thread.SetApartmentState(ApartmentState.STA);
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
/// <summary>The tick's poll of a queued open (OnTick, pump thread).</summary>
|
||||
private void PollWeb()
|
||||
{
|
||||
try { _webPanel?.Poll(Environment.TickCount64); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
/// <summary>Closes the engine's web panel only if this plugin opened it; answers a waiting open. Pump thread.</summary>
|
||||
internal void CloseWeb()
|
||||
{
|
||||
try { _webPanel?.Close(); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
// -- The engine calls. Each helper is the only code naming its SDK members, and each wrapper catches
|
||||
// the two exceptions an older Runtime\PluginShared SDK raises when it JITs the helper. --
|
||||
|
||||
private sealed class EngineWebPanel : IWebPanelEngine
|
||||
{
|
||||
private readonly ServerPackPlugin _plugin;
|
||||
|
||||
public EngineWebPanel(ServerPackPlugin plugin) => _plugin = plugin;
|
||||
|
||||
public bool HasPanel()
|
||||
{
|
||||
try { return _plugin.WebPanelHasCore(); }
|
||||
catch (MissingMethodException) { return false; }
|
||||
catch (TypeLoadException) { return false; }
|
||||
}
|
||||
|
||||
public int Open(string url, string[] allowlist, string profileKey, string title)
|
||||
{
|
||||
try { return _plugin.WebPanelOpenCore(url, allowlist, profileKey, title); }
|
||||
catch (MissingMethodException) { return WebPanelCodes.Unavailable; }
|
||||
catch (TypeLoadException) { return WebPanelCodes.Unavailable; }
|
||||
}
|
||||
|
||||
public int GetState(int handle, out int flags, out int error, out uint navigationCount)
|
||||
{
|
||||
flags = 0;
|
||||
error = 0;
|
||||
navigationCount = 0;
|
||||
try { return _plugin.WebPanelStateCore(handle, out flags, out error, out navigationCount); }
|
||||
catch (MissingMethodException) { return WebPanelCodes.StatusNone; }
|
||||
catch (TypeLoadException) { return WebPanelCodes.StatusNone; }
|
||||
}
|
||||
|
||||
public int Close(int handle)
|
||||
{
|
||||
try { return _plugin.WebPanelCloseCore(handle); }
|
||||
catch (MissingMethodException) { return WebPanelCodes.Unavailable; }
|
||||
catch (TypeLoadException) { return WebPanelCodes.Unavailable; }
|
||||
}
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private bool WebPanelHasCore() => Host.HasWebPanel;
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private int WebPanelOpenCore(string url, string[] allowlist, string profileKey, string title)
|
||||
=> Host.OpenWebPanel(new WebPanelOptions
|
||||
{
|
||||
Url = url,
|
||||
Allowlist = allowlist,
|
||||
ProfileKey = profileKey,
|
||||
Title = title,
|
||||
Flags = WebPanelFlags.FallbackToBrowser,
|
||||
});
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private int WebPanelStateCore(int handle, out int flags, out int error, out uint navigationCount)
|
||||
{
|
||||
WebPanelStatus status = Host.GetWebPanelState(handle, out WebPanelState state);
|
||||
flags = (int)state.Flags;
|
||||
error = (int)state.Error;
|
||||
navigationCount = state.NavigationCount;
|
||||
return (int)status;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private int WebPanelCloseCore(int handle) => Host.CloseWebPanel(handle);
|
||||
}
|
||||
|
|
@ -67,6 +67,10 @@
|
|||
<Compile Include="$(RynthSuiteRoot)Plugins\Shared\RynthServerQuestPackApi.cs" Link="Shared\RynthServerQuestPackApi.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ServerPackQuestPack.cs" Link="ServerPack\ServerPackQuestPack.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ServerPackInterface.cs" Link="ServerPack\ServerPackInterface.cs" />
|
||||
<!-- Open a web page in the engine's panel, else the browser (allowlisted https only). -->
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ServerWebOpen.cs" Link="ServerPack\ServerWebOpen.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ServerWebPanel.cs" Link="ServerPack\ServerWebPanel.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)ServerPackWeb.cs" Link="ServerPack\ServerPackWeb.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
|
|
|||
110
Plugins/Shared/ServerPack/ServerWebOpen.cs
Normal file
110
Plugins/Shared/ServerPack/ServerWebOpen.cs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
// ServerWebOpen.cs - the rules for opening a server's web page from a server plugin: which URLs are
|
||||
// allowed and where the page goes (the engine's web panel when it has one, else the system browser).
|
||||
// Pure (no engine, no threads): RynthServerPack.Tests covers it. The host side is ServerPackWeb.cs.
|
||||
// No Regex: the plugins are NativeAOT and Regex costs size, so the key is parsed by hand.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace RynthCore.Plugin.ServerPack;
|
||||
|
||||
/// <summary>
|
||||
/// A page to open. The URL comes from constants in the plugin, never from chat, but it may carry a
|
||||
/// one-time code, so ToString names the title only (a record's generated ToString would print the URL).
|
||||
/// </summary>
|
||||
internal sealed record WebOpenRequest(string Url, IReadOnlyList<string> AllowedHosts, string ProfileKey, string Title)
|
||||
{
|
||||
public override string ToString() => "WebOpenRequest(" + Title + ")";
|
||||
}
|
||||
|
||||
internal enum WebOpenRoute { Panel, Browser, Refused }
|
||||
|
||||
/// <summary>What the engine's panel did. Only a refusal before navigating may fall back to the browser.</summary>
|
||||
/// <remarks>
|
||||
/// OpenedInBrowserByEngine: the engine's own fallback opened the system browser (do nothing more).
|
||||
/// BadArgs and UrlNotAllowed: plugin bugs, never sent to the browser. Pending: the engine queued the
|
||||
/// open and the tick polls its state (ServerWebPanel). Closed: closed or replaced before it loaded.
|
||||
/// NoAnswer: the state never settled before the poll timeout (or could not be read); neutral, no fallback.
|
||||
/// </remarks>
|
||||
internal enum PanelResult { Opened, RefusedBeforeNavigate, UrlNotAllowed, FailedAfterNavigate, OpenedInBrowserByEngine, BadArgs, Pending, Closed, NoAnswer }
|
||||
|
||||
/// <summary>What happened. The message never contains the URL.</summary>
|
||||
internal sealed record WebOpenOutcome(WebOpenRoute Route, bool Ok, string Message);
|
||||
|
||||
internal static class ServerWebOpen
|
||||
{
|
||||
/// <summary>
|
||||
/// Absolute https, no userinfo, the default port, and a host equal to an allowed entry
|
||||
/// (OrdinalIgnoreCase). An entry "*.x" matches subdomains of x only, never x itself.
|
||||
/// </summary>
|
||||
public static bool IsAllowedUrl(string? url, IReadOnlyList<string> allowedHosts)
|
||||
=> TryGetAllowedUri(url, allowedHosts, out _);
|
||||
|
||||
/// <summary>The same check, giving the validated absolute URI (what the browser should be handed).</summary>
|
||||
public static bool TryGetAllowedUri(string? url, IReadOnlyList<string> allowedHosts, out string absoluteUri)
|
||||
{
|
||||
absoluteUri = string.Empty;
|
||||
if (string.IsNullOrEmpty(url) || allowedHosts == null) return false;
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)) return false;
|
||||
if (!string.Equals(uri.Scheme, "https", StringComparison.Ordinal)) return false;
|
||||
if (uri.UserInfo.Length != 0 || !uri.IsDefaultPort) return false;
|
||||
string host = uri.Host;
|
||||
if (host.Length == 0) return false;
|
||||
if (!HostAllowed(host, allowedHosts)) return false;
|
||||
absoluteUri = uri.AbsoluteUri;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool HostAllowed(string host, IReadOnlyList<string> allowedHosts)
|
||||
{
|
||||
|
||||
foreach (string entry in allowedHosts)
|
||||
{
|
||||
if (string.IsNullOrEmpty(entry)) continue;
|
||||
if (entry.StartsWith("*.", StringComparison.Ordinal))
|
||||
{
|
||||
string suffix = entry.Substring(1); // ".x"
|
||||
if (suffix.Length > 1
|
||||
&& host.Length > suffix.Length
|
||||
&& host.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
|
||||
return true;
|
||||
}
|
||||
else if (string.Equals(host, entry, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>Fall back to the browser only when the panel refused before navigating. After a
|
||||
/// navigate the one-time code is spent (a dead link), and UrlNotAllowed must not bypass the engine's list.</summary>
|
||||
public static bool FallbackToBrowser(PanelResult r) => r == PanelResult.RefusedBeforeNavigate;
|
||||
|
||||
/// <summary>^[a-z0-9-]{1,32}/[0-9a-f]{32}$ - the engine's panel profile key (server/token).</summary>
|
||||
public static bool IsValidProfileKey(string? key)
|
||||
{
|
||||
if (key == null) return false;
|
||||
int slash = key.IndexOf('/');
|
||||
if (slash < 1 || slash > 32) return false;
|
||||
if (key.Length - slash - 1 != 32) return false;
|
||||
for (int i = 0; i < slash; i++)
|
||||
{
|
||||
char c = key[i];
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '-')) return false;
|
||||
}
|
||||
for (int i = slash + 1; i < key.Length; i++)
|
||||
{
|
||||
char c = key[i];
|
||||
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Refused if the URL is not allowed; Browser if there is no panel or no valid key; else Panel.</summary>
|
||||
public static WebOpenRoute Route(WebOpenRequest r, bool panelAvailable)
|
||||
{
|
||||
if (!IsAllowedUrl(r.Url, r.AllowedHosts)) return WebOpenRoute.Refused;
|
||||
if (!panelAvailable || !IsValidProfileKey(r.ProfileKey)) return WebOpenRoute.Browser;
|
||||
return WebOpenRoute.Panel;
|
||||
}
|
||||
}
|
||||
202
Plugins/Shared/ServerPack/ServerWebPanel.cs
Normal file
202
Plugins/Shared/ServerPack/ServerWebPanel.cs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
// ServerWebPanel.cs - the engine's web panel (RynthCore plugin API v94, docs\WEB_PANEL.md) as the
|
||||
// ServerPack sees it: the engine's codes and states read as a PanelResult, and the one open the tick
|
||||
// waits on. Pure (no SDK types, no engine): the calls go through IWebPanelEngine, which ServerPackWeb.cs
|
||||
// implements with NoInlining helpers and RynthServerPack.Tests fakes.
|
||||
//
|
||||
// An open that returns a handle (> 0) is only queued, so its answer comes later: the plugin's OnTick
|
||||
// calls Poll, and the first state that decides (WEB_PANEL.md: Failed, its error and OpenedInBrowser
|
||||
// appear together, so one poll is enough) answers it. `then` runs exactly once per Open: at once for a
|
||||
// refusal, else from Poll (a state, or the timeout), from Close, or from a newer Open. No locks: the
|
||||
// waiting open and the handle move by Interlocked only, and `then` never runs under anything.
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
|
||||
namespace RynthCore.Plugin.ServerPack;
|
||||
|
||||
/// <summary>The engine's web-panel calls, in primitives and strings only (WEB_PANEL.md's values as ints).</summary>
|
||||
internal interface IWebPanelEngine
|
||||
{
|
||||
bool HasPanel();
|
||||
/// <summary>A handle (> 0), or a negative WebPanelResult.</summary>
|
||||
int Open(string url, string[] allowlist, string profileKey, string title);
|
||||
/// <summary>The WebPanelStatus; fills the WebPanelStateFlags, the error and the navigation count.</summary>
|
||||
int GetState(int handle, out int flags, out int error, out uint navigationCount);
|
||||
int Close(int handle);
|
||||
}
|
||||
|
||||
/// <summary>WEB_PANEL.md's numbers (RynthCore.PluginSdk WebPanelResult, WebPanelStatus, WebPanelStateFlags).</summary>
|
||||
internal static class WebPanelCodes
|
||||
{
|
||||
public const int BadArgs = -1, UrlNotAllowed = -2, NoGameWindow = -3, Unavailable = -4, ShuttingDown = -5;
|
||||
public const int StaleHandle = -6, RuntimeMissing = -7, CreateFailed = -8, ProcessFailed = -9;
|
||||
public const int StatusNone = 0, StatusStarting = 1, StatusLoading = 2, StatusReady = 3;
|
||||
public const int StatusClosed = 4, StatusFailed = 5, StatusSuperseded = 6;
|
||||
public const int FlagOpenedInBrowser = 4;
|
||||
}
|
||||
|
||||
internal sealed class ServerWebPanel
|
||||
{
|
||||
/// <summary>
|
||||
/// How long a queued open may stay Starting before it is answered NoAnswer (neutral, no browser).
|
||||
/// 20 s covers a cold WebView2 start (creating the environment and the browser process) with room
|
||||
/// to spare; past it something is wrong, and opening the browser too could spend the code twice.
|
||||
/// The handle is kept, so logout still closes the panel if it shows up late.
|
||||
/// </summary>
|
||||
public const long PollTimeoutMs = 20_000;
|
||||
|
||||
private sealed class WaitingOpen
|
||||
{
|
||||
public WaitingOpen(int handle, long deadlineMs, Action<PanelResult> then)
|
||||
{
|
||||
Handle = handle;
|
||||
DeadlineMs = deadlineMs;
|
||||
Then = then;
|
||||
}
|
||||
|
||||
public int Handle { get; }
|
||||
public long DeadlineMs { get; }
|
||||
public Action<PanelResult> Then { get; }
|
||||
}
|
||||
|
||||
private readonly IWebPanelEngine _engine;
|
||||
private WaitingOpen? _waiting;
|
||||
// The handle this plugin opened last (0 = none); the only one Close ever closes.
|
||||
private int _handle;
|
||||
|
||||
public ServerWebPanel(IWebPanelEngine engine) => _engine = engine;
|
||||
|
||||
/// <summary>The engine has a web panel. False when the call throws.</summary>
|
||||
public bool Available
|
||||
{
|
||||
get
|
||||
{
|
||||
try { return _engine.HasPanel(); }
|
||||
catch (Exception) { return false; }
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>An open is queued and not yet answered.</summary>
|
||||
public bool Waiting => Volatile.Read(ref _waiting) != null;
|
||||
|
||||
/// <summary>OpenWebPanel's return: a handle is Pending (queued, not opened); else the refusal.</summary>
|
||||
public static PanelResult FromOpenCode(int code)
|
||||
{
|
||||
if (code > 0) return PanelResult.Pending;
|
||||
switch (code)
|
||||
{
|
||||
case WebPanelCodes.BadArgs: return PanelResult.BadArgs;
|
||||
case WebPanelCodes.UrlNotAllowed: return PanelResult.UrlNotAllowed;
|
||||
case WebPanelCodes.NoGameWindow:
|
||||
case WebPanelCodes.Unavailable:
|
||||
case WebPanelCodes.ShuttingDown:
|
||||
return PanelResult.RefusedBeforeNavigate;
|
||||
default:
|
||||
// Not a documented Open return. No handle was issued, so nothing navigated: a refusal.
|
||||
return PanelResult.RefusedBeforeNavigate;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A polled state. Loading/Ready: Opened. Failed with OpenedInBrowser: the engine opened the browser.
|
||||
/// Failed with RuntimeMissing/CreateFailed, no browser and no navigation: RefusedBeforeNavigate (we
|
||||
/// try the browser; with FallbackToBrowser set this means the engine's own ShellExecute failed).
|
||||
/// Any other Failed (ProcessFailed, or an error after a navigation): FailedAfterNavigate, the code is
|
||||
/// spent. Closed/Superseded: Closed. Starting: Pending. None or anything else: NoAnswer.
|
||||
/// </summary>
|
||||
public static PanelResult FromState(int status, int flags, int error, uint navigationCount)
|
||||
{
|
||||
switch (status)
|
||||
{
|
||||
case WebPanelCodes.StatusStarting:
|
||||
return PanelResult.Pending;
|
||||
case WebPanelCodes.StatusLoading:
|
||||
case WebPanelCodes.StatusReady:
|
||||
return PanelResult.Opened;
|
||||
case WebPanelCodes.StatusFailed:
|
||||
if ((flags & WebPanelCodes.FlagOpenedInBrowser) != 0) return PanelResult.OpenedInBrowserByEngine;
|
||||
if ((error == WebPanelCodes.RuntimeMissing || error == WebPanelCodes.CreateFailed) && navigationCount == 0)
|
||||
return PanelResult.RefusedBeforeNavigate;
|
||||
return PanelResult.FailedAfterNavigate;
|
||||
case WebPanelCodes.StatusClosed:
|
||||
case WebPanelCodes.StatusSuperseded:
|
||||
return PanelResult.Closed;
|
||||
default:
|
||||
return PanelResult.NoAnswer;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opens <paramref name="r"/> in the panel. <paramref name="then"/> gets the answer exactly once: now
|
||||
/// for a refusal, else later from Poll, Close or a newer Open. A newer Open that the engine queued
|
||||
/// answers the older one Closed (the engine superseded it); a refused one leaves the older one waiting.
|
||||
/// </summary>
|
||||
public void Open(WebOpenRequest r, long nowMs, Action<PanelResult> then)
|
||||
{
|
||||
int code;
|
||||
try
|
||||
{
|
||||
var hosts = new List<string>(r.AllowedHosts);
|
||||
code = _engine.Open(r.Url, hosts.ToArray(), r.ProfileKey, r.Title);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
code = WebPanelCodes.Unavailable;
|
||||
}
|
||||
|
||||
PanelResult result = FromOpenCode(code);
|
||||
if (result != PanelResult.Pending)
|
||||
{
|
||||
Run(then, result);
|
||||
return;
|
||||
}
|
||||
Interlocked.Exchange(ref _handle, code);
|
||||
Answer(Interlocked.Exchange(ref _waiting, new WaitingOpen(code, nowMs + PollTimeoutMs, then)), PanelResult.Closed);
|
||||
}
|
||||
|
||||
/// <summary>The tick: answers the waiting open once its state decides, or at the timeout.</summary>
|
||||
public void Poll(long nowMs)
|
||||
{
|
||||
WaitingOpen? w = Volatile.Read(ref _waiting);
|
||||
if (w == null) return;
|
||||
|
||||
PanelResult result;
|
||||
try
|
||||
{
|
||||
int status = _engine.GetState(w.Handle, out int flags, out int error, out uint navigationCount);
|
||||
result = FromState(status, flags, error, navigationCount);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// The handle was issued, so the engine may still navigate: never the browser from here.
|
||||
result = PanelResult.NoAnswer;
|
||||
}
|
||||
if (result == PanelResult.Pending)
|
||||
{
|
||||
if (nowMs < w.DeadlineMs) return;
|
||||
result = PanelResult.NoAnswer;
|
||||
}
|
||||
if (Interlocked.CompareExchange(ref _waiting, null, w) == w) Run(w.Then, result);
|
||||
}
|
||||
|
||||
/// <summary>Closes the panel only if this plugin opened it, and answers a waiting open Closed.</summary>
|
||||
public void Close()
|
||||
{
|
||||
Answer(Interlocked.Exchange(ref _waiting, null), PanelResult.Closed);
|
||||
int handle = Interlocked.Exchange(ref _handle, 0);
|
||||
if (handle <= 0) return;
|
||||
try { _engine.Close(handle); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
|
||||
private static void Answer(WaitingOpen? w, PanelResult result)
|
||||
{
|
||||
if (w != null) Run(w.Then, result);
|
||||
}
|
||||
|
||||
private static void Run(Action<PanelResult> then, PanelResult result)
|
||||
{
|
||||
try { then(result); }
|
||||
catch (Exception) { }
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue