Framework/UI/Menu/MenuData.cs

Static cache that the main menu reads from. Loads s&box platform news once per game start and fetches map title and thumbnail for a package ident in the background, bumping a Version counter so the menu can rebuild.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using RoleplayFramework.Diagnostics;

namespace RoleplayFramework.UI;

/// <summary>Data the main menu loads in the background: s&amp;box news and map thumbnails.</summary>
public static class MenuData
{
	/// <summary>Bumped whenever something new arrived (for the menu's rebuild hash).</summary>
	public static int Version { get; private set; }

	// ------------------------------------------------------------------ news

	public static IReadOnlyList<Sandbox.Services.News> News { get; private set; } = Array.Empty<Sandbox.Services.News>();
	public static bool NewsLoading { get; private set; }
	public static string NewsError { get; private set; }
	static bool _newsRequested;

	/// <summary>The latest s&amp;box platform news (like Garry's Mod shows its own news). Loaded once per game start.</summary>
	public static async Task LoadNews()
	{
		if ( _newsRequested ) return;
		_newsRequested = true;
		NewsLoading = true;
		Version++;
		try
		{
			News = (await Sandbox.Services.News.GetPlatformNews( 0, 8 )) ?? Array.Empty<Sandbox.Services.News>();
		}
		catch ( Exception e )
		{
			NewsError = "News could not be loaded.";
			RpLog.Warn( "ui", $"News: {e.Message}" );
		}
		finally
		{
			NewsLoading = false;
			Version++;
		}
	}

	public static string Age( DateTimeOffset when )
	{
		var d = DateTimeOffset.UtcNow - when;
		if ( d.TotalHours < 1 ) return "just now";
		if ( d.TotalDays < 1 ) return $"{(int)d.TotalHours}h ago";
		if ( d.TotalDays < 30 ) return $"{(int)d.TotalDays}d ago";
		return when.ToString( "MMM d, yyyy" );
	}

	// ------------------------------------------------------------------ map info

	public sealed record MapInfo( string Title, string Thumb );

	static readonly Dictionary<string, MapInfo> _maps = new();
	static readonly HashSet<string> _requested = new();

	/// <summary>Title + thumbnail of a map (sbox.game package), fetched once in the background; null until known.</summary>
	public static MapInfo Map( string ident )
	{
		if ( string.IsNullOrEmpty( ident ) ) return null;
		if ( _maps.TryGetValue( ident, out var info ) ) return info;
		if ( Core.MapCatalog.IsBuiltIn( ident ) ) return _maps[ident] = new MapInfo( ident, null );
		if ( _requested.Add( ident ) ) _ = FetchMap( ident );
		return null;
	}

	static async Task FetchMap( string ident )
	{
		try
		{
			var p = await Package.FetchAsync( ident, true );
			_maps[ident] = new MapInfo( p?.Title ?? ident, p?.Thumb );
		}
		catch ( Exception )
		{
			_maps[ident] = new MapInfo( ident, null );
		}
		Version++;
	}
}