Framework/Scripting/Api/LuaContentLib.cs

Lua library binding named `content`, letting gamemode Lua queue cloud packages and collections, query mounted packages and search sbox.game. Also fires a `ContentMounted` hook and broadcasts runtime server adds to connected clients.

Http CallsNetworking
🌐 https://sbox.game
using System;
using System.Collections.Generic;
using System.Linq;
using RoleplayFramework.Core;
using RoleplayFramework.Diagnostics;
using RoleplayFramework.Lua;

namespace RoleplayFramework.Scripting;

/// <summary>
/// Lua library <c>content</c>: gamemodes import cloud content (sbox.game packages) themselves.
///
///   content.AddPackage("org.name")          queue a package; also accepts "https://sbox.game/org/name"
///   content.AddCollection("content.json")   server: a collection file (gamemode folder, then its bases, then data/roleplay/)
///   content.AddCollection("https://…")      server: a collection on any web server
///   content.IsMounted(id)  content.GetTitle(id)  content.GetModel(id)  content.GetPackages()  content.IsBusy()
///   hook "ContentMounted"(mounted, failed)   fired in both realms when a batch finished mounting
///
/// Server adds become part of the world's required content: players joining later get them before their scripts run,
/// players already connected are sent them right away. Adds while the gamemode loads are mounted before the server
/// opens. A client add mounts on that client only.
/// </summary>
public static class LuaContentLib
{
	static bool _subscribed;

	public static void Register( LuaRealm realm )
	{
		if ( !_subscribed )
		{
			_subscribed = true;
			ContentPackages.BatchMounted += OnBatchMounted;
		}

		var t = realm.State.GetOrCreateLibrary( "content" );
		bool server = realm.Kind == LuaRealmKind.Server;

		LuaState.Register( t, "AddPackage", ( L, a ) =>
		{
			var raw = LuaState.CheckString( a, 0, "content.AddPackage" );
			var id = ContentPackages.Normalize( raw );
			if ( !ContentPackages.IsValidIdent( id ) )
				throw LuaState.ArgError( 0, "content.AddPackage", $"'{raw}' is not an org.name package ident" );
			ContentPackages.Enqueue( new[] { id }, share: server );
			return new LuaValue[] { true };
		} );

		LuaState.Register( t, "AddCollection", ( L, a ) =>
		{
			var source = LuaState.CheckString( a, 0, "content.AddCollection" );
			if ( !server ) throw new LuaRuntimeException( "content.AddCollection is server-only; clients get the server's content automatically" );
			if ( ContentPackages.CheckCollectionSource( source ) is { } bad ) throw LuaState.ArgError( 0, "content.AddCollection", bad );

			_ = ContentPackages.EnqueueCollectionAsync( source, BasesFor( realm ), share: true,
				error => realm.Report( $"content.AddCollection('{source}'): {error}", null ) );
			return new LuaValue[] { true };
		} );

		LuaState.Register( t, "IsMounted", ( L, a ) =>
			new LuaValue[] { ContentPackages.Mounted.ContainsKey( ContentPackages.Normalize( LuaState.CheckString( a, 0, "content.IsMounted" ) ) ) } );

		LuaState.Register( t, "GetTitle", ( L, a ) =>
		{
			var id = ContentPackages.Normalize( LuaState.CheckString( a, 0, "content.GetTitle" ) );
			return new[] { ContentPackages.Mounted.TryGetValue( id, out var title ) ? LuaValue.FromString( title ) : LuaValue.Nil };
		} );

		LuaState.Register( t, "GetModel", ( L, a ) =>
			new[] { LuaValue.FromString( ContentPackages.PrimaryAssetOf( ContentPackages.Normalize( LuaState.CheckString( a, 0, "content.GetModel" ) ) ) ) } );

		LuaState.Register( t, "GetPackages", ( L, a ) =>
		{
			// Server: the world's required list. Client: everything mounted on this machine.
			var ids = server ? ContentPackages.Required.ToList() : ContentPackages.Mounted.Keys.ToList();
			return new[] { LuaValue.FromTable( ToTable( ids ) ) };
		} );

		LuaState.Register( t, "IsBusy", ( L, a ) => new LuaValue[] { ContentPackages.Busy } );

		// content.Search(query, function(results) end [, type]) - client: searches sbox.game (type "model" by default).
		// results = { { ident, title, thumb, author }, ... } (max 60), or nil and an error message.
		if ( !server )
		{
			LuaState.Register( t, "Search", ( L, a ) =>
			{
				var query = LuaState.CheckString( a, 0, "content.Search" ).Trim();
				if ( query.Length > 64 ) throw LuaState.ArgError( 0, "content.Search", "query longer than 64 characters" );
				var cb = LuaState.Arg( a, 1 );
				if ( !cb.IsFunction ) throw LuaState.ArgError( 1, "content.Search", "callback function expected" );
				var type = LuaState.Arg( a, 2 ).IsString ? LuaState.Arg( a, 2 ).AsString : "model";
				if ( !System.Text.RegularExpressions.Regex.IsMatch( type, "^[a-z]{1,16}$" ) ) throw LuaState.ArgError( 2, "content.Search", "type must be a word like \"model\"" );
				if ( _searching ) throw new LuaRuntimeException( "content.Search: a search is already running" );
				if ( _sinceSearch < 0.5f ) throw new LuaRuntimeException( "content.Search: too fast, wait a moment" );
				_ = SearchAsync( realm, $"type:{type} {StripFilters( query )}".Trim(), cb );
				return new LuaValue[] { true };
			} );
		}
	}

	static bool _searching;
	static RealTimeSince _sinceSearch = 10;

	// Users type words; filters ("type:", "sort:") are set by the framework.
	static string StripFilters( string q ) => string.Join( " ", q.Split( ' ', StringSplitOptions.RemoveEmptyEntries ).Where( w => !w.Contains( ':' ) ) );

	static async System.Threading.Tasks.Task SearchAsync( LuaRealm realm, string query, LuaValue cb )
	{
		_searching = true;
		_sinceSearch = 0;
		LuaTable list = null;
		string error = null;
		try
		{
			var result = await Package.FindAsync( query, 60, 0 );
			list = new LuaTable();
			foreach ( var p in result?.Packages ?? Array.Empty<Package>() )
			{
				var row = new LuaTable();
				row.Set( "ident", p.FullIdent );
				row.Set( "title", p.Title ?? p.FullIdent );
				row.Set( "thumb", p.Thumb ?? "" );
				row.Set( "author", p.Org?.Title ?? "" );
				list.Append( LuaValue.FromTable( row ) );
			}
		}
		catch ( Exception e ) { error = e.Message; }
		finally { _searching = false; }

		if ( LuaRuntime.Client != realm ) return; // realm reloaded meanwhile
		var r = realm.State.PCall( cb, list is null ? LuaValue.Nil : LuaValue.FromTable( list ), error is null ? LuaValue.Nil : LuaValue.FromString( error ) );
		if ( !r.Success ) realm.Report( $"content.Search callback: {r.Error}", r.Traceback );
	}

	/// <summary>Where a relative collection path is looked up: the running gamemode's folder, its bases, then data/roleplay/.</summary>
	static List<(BaseFileSystem, string)> BasesFor( LuaRealm realm )
	{
		var list = new List<(BaseFileSystem, string)>();
		var gm = realm.Gamemode;
		if ( gm is not null )
		{
			var chain = GamemodeRegistry.Current?.LoadOrder( gm.Id ) ?? new List<GamemodeManifest> { gm };
			foreach ( var m in Enumerable.Reverse( chain ) )
				if ( !string.IsNullOrEmpty( m.Root ) ) list.Add( (realm.Files, m.Root) );
		}
		list.Add( (FileSystem.Data, ContentPackages.DataBase) );
		return list;
	}

	static LuaTable ToTable( List<string> ids )
	{
		var t = new LuaTable();
		foreach ( var id in ids ) t.Append( LuaValue.FromString( id ) );
		return t;
	}

	static void OnBatchMounted( List<string> mounted, List<string> failed, bool shared )
	{
		// Server batches go to every connected client (joining clients get them with the manifest instead).
		if ( shared && Networking.IsActive && Networking.IsHost && mounted.Count > 0 )
			PushToClients( string.Join( ",", mounted ) );

		if ( mounted.Count > 0 )
			RpLog.Info( "content", $"Added at runtime: {string.Join( ", ", mounted )}" );

		LuaRuntime.Server?.RunHook( "ContentMounted", LuaValue.FromTable( ToTable( mounted ) ), LuaValue.FromTable( ToTable( failed ) ) );
		LuaRuntime.Client?.RunHook( "ContentMounted", LuaValue.FromTable( ToTable( mounted ) ), LuaValue.FromTable( ToTable( failed ) ) );
	}

	/// <summary>Host → clients: packages the server added while running. Mounted locally, then ContentMounted runs.</summary>
	[Rpc.Broadcast( NetFlags.HostOnly )]
	public static void PushToClients( string packed )
	{
		if ( Networking.IsHost ) return; // the host mounted them already
		var ids = ContentPackages.ParseFromServer( packed );
		if ( ids.Count == 0 ) return;
		RpLog.Info( "content", $"Server added {ids.Count} package(s): {string.Join( ", ", ids )}" );
		ContentPackages.Enqueue( ids, share: false );
	}
}