Framework/Scripting/Api/LuaConCommand.cs

A static bridge that exposes GMod-style concommand.Add/Remove/GetTable/RunConsoleCommand to the framework's Lua realms. Since s&box has no runtime console command registration, all Lua commands run through a single ConCmd 'rp', and client commands are forwarded to the host via an Rpc with rate limiting.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using RoleplayFramework.Diagnostics;
using RoleplayFramework.Lua;
using RoleplayFramework.Players;

namespace RoleplayFramework.Scripting;

/// <summary>
/// GMod's <c>concommand</c> for Lua. s&amp;box can't add console commands at runtime, so all Lua commands run through one
/// framework command: <c>rp &lt;command&gt; [args...]</c> (<c>rp</c> alone lists them).
///
///   concommand.Add(name, function(ply, cmd, args, argStr) end [, autoComplete, helpText])
///   concommand.Remove(name)   concommand.GetTable()   RunConsoleCommand(name, ...)
///
/// Like GMod: a command the client realm defines runs there (ply = the local player); otherwise a client sends it to the
/// server (rate-limited), where it runs with ply = that player. In the server console (dedicated) ply is nil.
/// </summary>
public static class LuaConCommand
{
	public const int MaxCommands = 256;
	static readonly Regex NamePattern = new( @"^[A-Za-z0-9_.\-]{1,48}$" );

	sealed class Command { public LuaValue Fn; public string Help; }

	static readonly Dictionary<LuaRealm, Dictionary<string, Command>> _byRealm = new();

	static Dictionary<string, Command> For( LuaRealm realm )
	{
		if ( !_byRealm.TryGetValue( realm, out var d ) ) _byRealm[realm] = d = new( StringComparer.OrdinalIgnoreCase );
		// Forget realms that were replaced (reload, world change).
		foreach ( var old in _byRealm.Keys.Where( r => r != LuaRuntime.Server && r != LuaRuntime.Client && r != realm ).ToList() ) _byRealm.Remove( old );
		return d;
	}

	public static void Register( LuaRealm realm )
	{
		var t = realm.State.GetOrCreateLibrary( "concommand" );
		LuaState.Register( t, "Add", ( s, a ) =>
		{
			var name = LuaState.CheckString( a, 0, "concommand.Add" );
			if ( !NamePattern.IsMatch( name ) ) throw LuaState.ArgError( 0, "concommand.Add", "name: 1-48 characters of letters, digits, _ . -" );
			var fn = LuaState.Arg( a, 1 );
			if ( !fn.IsFunction ) throw LuaState.ArgError( 1, "concommand.Add", "function expected" );
			var cmds = For( realm );
			if ( !cmds.ContainsKey( name ) && cmds.Count >= MaxCommands ) throw new LuaRuntimeException( $"too many console commands (limit {MaxCommands})" );
			var help = LuaState.Arg( a, 3 ).IsString ? LuaState.Arg( a, 3 ).AsString : "";
			cmds[name] = new Command { Fn = fn, Help = help.Length > 200 ? help.Substring( 0, 200 ) : help };
			return null;
		} );
		LuaState.Register( t, "Remove", ( s, a ) => { For( realm ).Remove( LuaState.CheckString( a, 0, "concommand.Remove" ) ); return null; } );
		LuaState.Register( t, "GetTable", ( s, a ) =>
		{
			var list = new LuaTable();
			foreach ( var (name, c) in For( realm ) ) list.Set( name, c.Fn );
			return new LuaValue[] { list };
		} );

		// RunConsoleCommand(name, ...): GMod runs any console command; here it runs Lua commands the same way `rp` does.
		realm.State.Register( "RunConsoleCommand", ( s, a ) =>
		{
			var name = LuaState.CheckString( a, 0, "RunConsoleCommand" );
			var args = a.Skip( 1 ).Select( v => s.ToStringMeta( v ) ).ToList();
			Dispatch( name, string.Join( " ", args.Select( Quote ) ), fromRealm: realm );
			return null;
		} );
	}

	static string Quote( string s ) => s.Contains( ' ' ) || s.Length == 0 ? "\"" + s.Replace( "\"", "'" ) + "\"" : s;

	/// <summary>Splits like the console: spaces separate, "double quotes" group.</summary>
	public static List<string> SplitArgs( string text )
	{
		var list = new List<string>();
		foreach ( Match m in Regex.Matches( text ?? "", "\"([^\"]*)\"|(\\S+)" ) )
			list.Add( m.Groups[1].Success ? m.Groups[1].Value : m.Groups[2].Value );
		return list;
	}

	static bool Run( LuaRealm realm, string name, string argStr, LuaValue ply )
	{
		if ( realm is null || !For( realm ).TryGetValue( name, out var c ) ) return false;
		var args = new LuaTable();
		foreach ( var x in SplitArgs( argStr ) ) args.Append( x );
		try { realm.Call( c.Fn, ply, name, args, argStr ?? "" ); }
		catch ( LuaException e ) { realm.Report( $"concommand '{name}': {e.Message}", null ); }
		return true;
	}

	static void Dispatch( string name, string argStr, LuaRealm fromRealm = null )
	{
		// The client realm first (local player), then the server: locally if we are the host, otherwise by RPC.
		var client = LuaRuntime.Client;
		if ( client is not null && fromRealm != LuaRuntime.Server )
		{
			var local = LuaPlayers.LocalPlayerValue( client );
			if ( Run( client, name, argStr, local ) ) return;
		}

		if ( LuaRuntime.Server is { } server )
		{
			// Host: from the console of a listen server the caller is the host's player; on a dedicated server nobody.
			LuaValue ply = Application.IsDedicatedServer || fromRealm == server ? LuaValue.Nil : LuaPlayers.LocalPlayerValue( server );
			if ( Run( server, name, argStr, ply ) ) return;
		}
		else if ( Networking.IsActive && !Networking.IsHost )
		{
			ServerCommand( name, argStr ?? "" );
			return;
		}

		RpLog.Warn( "lua", $"Unknown command '{name}'. Type rp to list the commands of this gamemode." );
	}

	/// <summary>Client → host: run a server-side Lua console command as this player.</summary>
	[Rpc.Host]
	public static void ServerCommand( string name, string argStr )
	{
		var caller = Rpc.Caller;
		if ( !PlayerSessions.Guard( caller, "Lua.ConCommand", 5, 2, out _ ) ) return;
		if ( name is null || !NamePattern.IsMatch( name ) || (argStr?.Length ?? 0) > 1024 ) return;
		var server = LuaRuntime.Server;
		if ( server is null ) return;
		if ( !Run( server, name, argStr, LuaPlayers.Wrap( server, caller.Id ) ) )
			RpLog.Info( "lua", $"{caller.DisplayName} ran unknown command '{name}'" );
	}

	[ConCmd( "rp", Help = "Run a Lua console command of the gamemode: rp <command> [args]. Without arguments: list them." )]
	public static void ConsoleCommand( string name = "", string a1 = "", string a2 = "", string a3 = "", string a4 = "",
		string a5 = "", string a6 = "", string a7 = "", string a8 = "" )
	{
		if ( string.IsNullOrWhiteSpace( name ) )
		{
			foreach ( var (realm, label) in new[] { (LuaRuntime.Client, "client"), (LuaRuntime.Server, "server") } )
			{
				if ( realm is null ) continue;
				foreach ( var (n, c) in For( realm ).OrderBy( x => x.Key ) )
					RpLog.Info( "lua", $"rp {n}  ({label}){(string.IsNullOrEmpty( c.Help ) ? "" : " - " + c.Help)}" );
			}
			return;
		}
		var args = new[] { a1, a2, a3, a4, a5, a6, a7, a8 }.Where( x => !string.IsNullOrEmpty( x ) ).Select( Quote );
		Dispatch( name, string.Join( " ", args ) );
	}
}