Framework/ServerBrowser/ServerBrowser.cs

Server browser and connect logic for a roleplay framework. Lists public Steam lobbies through Networking.QueryLobbies with metadata from SessionService, filters and sorts them, and handles joining a lobby id, Steam id or local server with timeout and editor guards.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using RoleplayFramework.Core;
using RoleplayFramework.Diagnostics;
using RoleplayFramework.Net;
using Sandbox.Network;

namespace RoleplayFramework.ServerBrowser;

/// <summary>One server as shown in the browser, built from a Steam lobby plus the framework's lobby metadata.</summary>
public sealed record ServerEntry(
	ulong LobbyId,
	string Name,
	string Gamemode,
	string FrameworkVersion,
	int Protocol,
	string Map,
	int Players,
	int MaxPlayers,
	int Ping,
	bool PingEstimated,
	bool Password,
	bool Full,
	bool Friends = false,
	bool Outdated = false )
{
	/// <summary>False when the server runs a different framework protocol: joining would be rejected at the handshake.</summary>
	public bool Compatible => Protocol == FrameworkInfo.ProtocolVersion && !Outdated;
	public bool Empty => Players == 0;
}

public enum BrowserState { Idle, Loading, Loaded, Failed }

public enum SortMode { Players, Ping, Name, Map }

/// <summary>
/// Server discovery through the platform lobby system (<see cref="Networking.QueryLobbies(CancellationToken)"/>), the
/// same mechanism the s&amp;box menu uses. This is not a separate master server: it lists public lobbies of this game
/// that Steam returns. Editor play sessions are always private and never appear.
/// </summary>
public static class ServerBrowserService
{
	public static BrowserState State { get; private set; } = BrowserState.Idle;
	public static string Error { get; private set; }
	public static DateTime? LastRefreshUtc { get; private set; }
	public static IReadOnlyList<ServerEntry> Servers { get; private set; } = Array.Empty<ServerEntry>();

	/// <summary>Incremented whenever results or state change (for UI rebuild hashing).</summary>
	public static int Version { get; private set; }

	static CancellationTokenSource _cts;

	public static async Task Refresh()
	{
		_cts?.Cancel();
		var cts = _cts = new CancellationTokenSource( TimeSpan.FromSeconds( 15 ) );

		State = BrowserState.Loading;
		Error = null;
		Version++;

		try
		{
			var lobbies = await Networking.QueryLobbies( cts.Token ) ?? new List<LobbyInformation>();
			if ( cts != _cts ) return; // superseded by a newer refresh

			Servers = lobbies.Select( ToEntry ).ToList();
			State = BrowserState.Loaded;
			LastRefreshUtc = DateTime.UtcNow;
			RpLog.Info( "browser", $"Found {Servers.Count} server(s)" );
		}
		catch ( OperationCanceledException )
		{
			if ( cts != _cts ) return;
			State = BrowserState.Failed;
			Error = "The server list took too long to load. Check your connection and refresh.";
		}
		catch ( Exception e )
		{
			if ( cts != _cts ) return;
			State = BrowserState.Failed;
			Error = $"Could not load servers: {e.Message}";
			RpLog.Warn( "browser", Error );
		}
		finally
		{
			Version++;
		}
	}

	static ServerEntry ToEntry( LobbyInformation l )
	{
		var meta = SessionService.UnpackMetadata( l.Get( SessionService.DataKey, "" ) );
		return new ServerEntry(
			l.LobbyId,
			string.IsNullOrWhiteSpace( l.Name ) ? "Unnamed server" : l.Name,
			meta.Gamemode,
			meta.Version,
			meta.Protocol,
			!string.IsNullOrWhiteSpace( l.Map ) ? l.Map : meta.Map,
			l.Members,
			l.MaxMembers,
			l.Ping,
			l.IsPingEstimated,
			l.IsPasswordProtected,
			l.IsFull,
			l.OwnerId != 0 && new Friend( l.OwnerId ).IsFriend, // hosted by a Steam friend
			l.IsOutdated );
	}

	/// <summary>Search + filters + sort over the last results.</summary>
	public static List<ServerEntry> View( string search, string gamemode, bool hideFull, bool hideEmpty, bool hidePassword, SortMode sort,
		bool friendsOnly = false, bool descending = false )
	{
		IEnumerable<ServerEntry> q = Servers;
		if ( friendsOnly ) q = q.Where( x => x.Friends );
		if ( !string.IsNullOrWhiteSpace( search ) )
		{
			var s = search.Trim();
			q = q.Where( x => x.Name.Contains( s, StringComparison.OrdinalIgnoreCase ) || x.Map.Contains( s, StringComparison.OrdinalIgnoreCase ) );
		}
		if ( !string.IsNullOrEmpty( gamemode ) ) q = q.Where( x => x.Gamemode == gamemode );
		if ( hideFull ) q = q.Where( x => !x.Full );
		if ( hideEmpty ) q = q.Where( x => !x.Empty );
		if ( hidePassword ) q = q.Where( x => !x.Password );

		q = sort switch
		{
			SortMode.Ping => q.OrderBy( x => x.Ping ),
			SortMode.Name => q.OrderBy( x => x.Name, StringComparer.OrdinalIgnoreCase ),
			SortMode.Map => q.OrderBy( x => x.Map, StringComparer.OrdinalIgnoreCase ),
			_ => q.OrderByDescending( x => x.Players ).ThenBy( x => x.Ping ),
		};
		var list = q.ToList();
		if ( descending ) list.Reverse();
		return list;
	}

	/// <summary>Per gamemode: server count and players, for the browser's gamemode list (GMod style).</summary>
	public static List<(string Gamemode, int Servers, int Players)> GamemodeSummary( bool friendsOnly ) =>
		Servers.Where( s => !friendsOnly || s.Friends )
			.GroupBy( s => string.IsNullOrEmpty( s.Gamemode ) ? "unknown" : s.Gamemode )
			.Select( g => (g.Key, g.Count(), g.Sum( s => s.Players )) )
			.OrderByDescending( g => g.Item3 ).ThenByDescending( g => g.Item2 ).ThenBy( g => g.Key )
			.ToList();

	public static IEnumerable<string> Gamemodes => Servers.Select( s => s.Gamemode ).Distinct().OrderBy( x => x );
}

public enum ConnectState { Idle, Connecting, Failed }

/// <summary>
/// Joining a server. The engine performs the connection, asks for a password through the s&amp;box platform
/// dialog when the lobby needs one, and loads the host's scene on success.
/// </summary>
public static class ConnectService
{
	public static ConnectState State { get; private set; }
	public static string Target { get; private set; }
	public static string Error { get; private set; }
	public static int Version { get; private set; }

	static RealTimeSince _since;
	const float TimeoutSeconds = 30;

	/// <summary>Validates a direct-connect address: a lobby id, a Steam id, or "local" (same-machine dedicated server).</summary>
	public static string ValidateAddress( string address )
	{
		address = address?.Trim() ?? "";
		if ( address.Length == 0 ) return "Enter a lobby id, Steam id or \"local\".";
		if ( address == "local" ) return null;
		if ( address.Length > 20 || !address.All( char.IsAsciiDigit ) ) return "Use the numeric lobby id from the server's 'status' command, a Steam id, or \"local\".";
		return null;
	}

	public static bool Connect( string address, string label )
	{
		var err = ValidateAddress( address );
		if ( err is not null ) { Fail( err ); return false; }
		if ( Networking.IsActive ) { Fail( "Leave your current session first." ); return false; }

		// Tested: joining another server from editor play mode fails ("GameInstance load failed") and unloads the
		// project's game code from the editor until it is restarted. Only the real game client can join servers.
		if ( Application.IsEditor )
		{
			Fail( "Joining servers isn't possible from the editor's play mode. Run the game outside the editor to join." );
			return false;
		}

		address = address.Trim();
		Target = label ?? address;
		State = ConnectState.Connecting;
		Error = null;
		_since = 0;
		Version++;
		RpLog.Info( "connect", $"Connecting to {Target} ({address})" );

		try
		{
			if ( ulong.TryParse( address, out var id ) ) Networking.Connect( id );
			else Networking.Connect( address );
		}
		catch ( Exception e )
		{
			Fail( $"Could not start connecting: {e.Message}" );
			return false;
		}
		return true;
	}

	/// <summary>Called every frame by the menu while visible: detects timeouts and silent failures.</summary>
	public static void Tick()
	{
		if ( State != ConnectState.Connecting ) return;
		if ( Networking.IsActive && !Networking.IsConnecting ) return; // connected; the host's scene is loading
		if ( _since > 3 && !Networking.IsConnecting && !Networking.IsActive )
		{
			Fail( "The connection was refused or the server could not be reached (wrong id, password cancelled, or the server is gone)." );
			return;
		}
		if ( _since > TimeoutSeconds ) Fail( $"Timed out after {TimeoutSeconds:F0} seconds." );
	}

	public static void Cancel()
	{
		if ( State == ConnectState.Connecting && (Networking.IsConnecting || Networking.IsActive) ) Networking.Disconnect();
		State = ConnectState.Idle;
		Version++;
	}

	static void Fail( string message )
	{
		State = ConnectState.Failed;
		Error = message;
		Version++;
		RpLog.Warn( "connect", message );
	}

	[ConCmd( "rp_connect", Help = "Connect to a server: rp_connect <lobbyId|steamId|local>" )]
	public static void ConnectCommand( string address ) => Connect( address, address );
}