Code/SboxlistService.cs

Host-only component for a server-list integration. Reads the site config, builds a SiteClient per configured site, ticks them each frame for heartbeats and vote polling, and reports player joins through INetworkListener.OnActive. Also resolves a vote's player identity to a live Connection by SteamID64 or display name.

using System;
using System.Collections.Generic;
using System.Linq;
using Sandbox;
using static Sandbox.Internal.GlobalGameNamespace;

namespace Sboxlist;

/// <summary>
/// Put one of these in the scene the server loads (next to the NetworkHelper). It runs only on
/// the host: it reads the config, sends heartbeats, polls for votes and asks for rewards when a
/// player joins. Clients do nothing.
/// </summary>
public sealed class SboxlistService : Component, Component.INetworkListener
{
	public const string Version = "1.0.0";

	public static SboxlistService Instance { get; private set; }

	public IReadOnlyList<SiteClient> Sites => sites;

	readonly List<SiteClient> sites = new();
	double startedAt;
	bool loaded;

	protected override void OnStart()
	{
		Instance = this;
		startedAt = RealTime.NowDouble;
	}

	protected override void OnUpdate()
	{
		if ( !Networking.IsHost ) return;

		if ( !loaded )
		{
			loaded = true;
			Reload();
		}

		foreach ( var site in sites )
			site.Tick();
	}

	protected override void OnDestroy()
	{
		if ( Instance == this ) Instance = null;
	}

	public void Reload()
	{
		var previous = new List<SiteClient>( sites );
		sites.Clear();
		var configs = SboxlistConfig.Load( out var source );
		Log.Info( $"[sboxlist] {Version} config: {source}" );
		Log.Info( $"[sboxlist] config file path: {SboxlistConfig.FullPath()}" );

		foreach ( var config in configs )
		{
			// A running site with the same identity keeps its state (pending acks and, through its server id, what it
			// has seen). Only the rewards setting can change in place. A stopped site starts again.
			var kept = previous.FirstOrDefault( s => !s.Disabled && SameSite( s.Config, config ) );
			if ( kept is not null )
			{
				kept.Config.Rewards = config.Rewards;
				sites.Add( kept );
				continue;
			}

			var site = new SiteClient( config, this );
			sites.Add( site );
			Log.Info( $"[sboxlist] site {config.SiteId}: {config.BaseUrl} as {config.ServerId}, auth {config.Auth}, rewards {(config.Rewards ? "on" : "off")}" );
			_ = site.InfoAsync();
		}

		if ( sites.Count == 0 )
			Log.Warning( "[sboxlist] no site configured; nothing will be sent" );
	}

	static bool SameSite( SiteConfig a, SiteConfig b ) =>
		a.SiteId == b.SiteId && a.BaseUrl == b.BaseUrl && a.ServerId == b.ServerId && a.Token == b.Token && a.Auth == b.Auth;

	/// <summary>Called on the host when a player is fully in the game.</summary>
	public void OnActive( Connection channel )
	{
		if ( !Networking.IsHost || channel is null ) return;
		if ( Application.IsDedicatedServer && channel.IsHost ) return;
		foreach ( var site in sites )
			site.QueueJoin( channel, "join" );
	}

	internal int PlayerCount()
	{
		var all = Connection.All;
		if ( all is null ) return 0;
		return Application.IsDedicatedServer ? all.Count( c => !c.IsHost ) : all.Count;
	}

	internal string MapName => Scene?.Name ?? "";

	internal long UptimeSeconds => (long)Math.Max( 0, RealTime.NowDouble - startedAt );

	/// <summary>The connected player a vote belongs to, by SteamID64 or by exact name.</summary>
	internal Connection FindPlayer( string identityKind, string identityKey )
	{
		var all = Connection.All;
		if ( all is null || string.IsNullOrEmpty( identityKey ) ) return null;

		foreach ( var c in all )
		{
			if ( Application.IsDedicatedServer && c.IsHost ) continue;
			if ( identityKind == "steam" && c.SteamId.ValueUnsigned.ToString( System.Globalization.CultureInfo.InvariantCulture ) == identityKey ) return c;
			if ( identityKind == "name" && c.DisplayName == identityKey ) return c;
		}

		return null;
	}
}