diff --git a/NexVerse/RegionModules/ViewerAdvisor/OGLViewerAdvisorModule.cs b/NexVerse/RegionModules/ViewerAdvisor/OGLViewerAdvisorModule.cs new file mode 100644 index 00000000..35d76a99 --- /dev/null +++ b/NexVerse/RegionModules/ViewerAdvisor/OGLViewerAdvisorModule.cs @@ -0,0 +1,275 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.Collections.Generic; +using System.Threading; +using log4net; +using Mono.Addins; +using Nini.Config; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; + +namespace NexVerse.RegionModules.ViewerAdvisor +{ + /// + /// Opt-in, private chat recommendation for non-OGL viewers. + /// The cooldown is per avatar and per simulator process. Region crossings + /// on the same simulator do not reset it. + /// + [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "OGLViewerAdvisorModule")] + public sealed class OGLViewerAdvisorModule : ISharedRegionModule + { + private static readonly ILog m_Log = + LogManager.GetLogger(typeof(OGLViewerAdvisorModule)); + + private readonly object m_Sync = new object(); + private readonly List m_Scenes = new List(); + private readonly Dictionary m_LastSentUtc = + new Dictionary(); + + private volatile bool m_Enabled; + private TimeSpan m_Interval = TimeSpan.FromMinutes(60); + private string[] m_OfficialPrefixes = { "OpenGenesisLINK", "OGL Viewer" }; + private string m_Message = + "Um das volle Erlebnis von OpenGenesisLINK geniessen zu koennen, " + + "steigen Sie auf den offiziellen OGL Viewer um: https://opengenesislink.de"; + private Timer m_Timer; + private int m_CheckRunning; + + public string Name => "OGL Viewer Advisor"; + public Type ReplaceableInterface => null; + + public void Initialise(IConfigSource config) + { + IConfig section = config?.Configs["OGLViewerAdvisor"]; + // Explicit opt-in: absent sections and bare installations remain silent. + m_Enabled = section?.GetBoolean("Enabled", false) ?? false; + if (!m_Enabled) + return; + + int minutes = Math.Clamp(section.GetInt("IntervalMinutes", 60), 1, 1440); + m_Interval = TimeSpan.FromMinutes(minutes); + m_OfficialPrefixes = ParsePrefixes( + section.GetString("OfficialViewerPrefixes", "OpenGenesisLINK;OGL Viewer")); + + string message = section.GetString("Message", m_Message)?.Trim(); + if (!string.IsNullOrEmpty(message)) + m_Message = message.Length > 900 ? message.Substring(0, 900) : message; + + m_Log.InfoFormat( + "[OGL-VIEWER-ADVISOR]: Enabled; interval={0} minute(s); known official viewer prefixes={1}.", + minutes, m_OfficialPrefixes.Length); + } + + public void PostInitialise() + { + if (!m_Enabled) + return; + + // A periodic sweep handles users who remain connected for hours. + // One timer is shared by all regions in this simulator process. + m_Timer = new Timer(CheckOnlineAvatars, null, + TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(15)); + } + + public void AddRegion(Scene scene) + { + if (!m_Enabled || scene == null) + return; + + lock (m_Sync) + { + if (m_Scenes.Contains(scene)) + return; + m_Scenes.Add(scene); + } + + scene.EventManager.OnMakeRootAgent += OnMakeRootAgent; + } + + public void RegionLoaded(Scene scene) { } + + public void RemoveRegion(Scene scene) + { + if (scene == null) + return; + + scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent; + lock (m_Sync) + m_Scenes.Remove(scene); + } + + public void Close() + { + m_Enabled = false; + m_Timer?.Dispose(); + m_Timer = null; + + lock (m_Sync) + { + foreach (Scene scene in m_Scenes) + scene.EventManager.OnMakeRootAgent -= OnMakeRootAgent; + + m_Scenes.Clear(); + m_LastSentUtc.Clear(); + } + } + + private static string[] ParsePrefixes(string input) + { + if (string.IsNullOrWhiteSpace(input)) + return Array.Empty(); + + string[] parts = input.Split(';', StringSplitOptions.RemoveEmptyEntries); + var unique = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (string part in parts) + { + string cleaned = part.Trim(); + if (cleaned.Length != 0) + unique.Add(cleaned); + } + + var result = new string[unique.Count]; + unique.CopyTo(result); + return result; + } + + internal static bool MatchesOfficialViewer(string value, string[] prefixes) + { + if (string.IsNullOrWhiteSpace(value)) + return false; + + string candidate = value.Trim(); + foreach (string prefix in prefixes) + { + if (!candidate.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + continue; + if (candidate.Length == prefix.Length) + return true; + + // Require a separator after the reported product name. + // Viewer-supplied names are not authenticated identities. + char delimiter = candidate[prefix.Length]; + if (char.IsWhiteSpace(delimiter) || delimiter == '-' || + delimiter == '_' || delimiter == '/' || delimiter == '(' || + delimiter == ':' || delimiter == '.') + return true; + } + + return false; + } + + private void OnMakeRootAgent(ScenePresence presence) + { + CheckAndNotify(presence); + } + + private void CheckOnlineAvatars(object state) + { + if (!m_Enabled || + Interlocked.CompareExchange(ref m_CheckRunning, 1, 0) != 0) + return; + + try + { + Scene[] scenes; + lock (m_Sync) + { + scenes = m_Scenes.ToArray(); + DateTime staleBefore = DateTime.UtcNow - m_Interval - m_Interval; + var stale = new List(); + foreach (KeyValuePair entry in m_LastSentUtc) + { + if (entry.Value < staleBefore) + stale.Add(entry.Key); + } + foreach (UUID id in stale) + m_LastSentUtc.Remove(id); + } + + foreach (Scene scene in scenes) + { + try + { + scene.ForEachRootScenePresence(CheckAndNotify); + } + catch (Exception error) + { + m_Log.Warn("[OGL-VIEWER-ADVISOR]: Periodic avatar scan failed.", error); + } + } + } + finally + { + Volatile.Write(ref m_CheckRunning, 0); + } + } + + private void CheckAndNotify(ScenePresence presence) + { + if (!m_Enabled || presence == null || presence.IsDeleted || + presence.IsNPC || presence.IsChildAgent) + return; + + IClientAPI client = presence.ControllingClient; + if (client == null) + return; + + AgentCircuitData circuit; + try + { + circuit = presence.Scene.AuthenticateHandler.GetAgentCircuitData( + client.CircuitCode); + } + catch (Exception error) + { + m_Log.Debug("[OGL-VIEWER-ADVISOR]: Could not inspect viewer circuit.", error); + return; + } + + // A missing circuit is not a reason to send an unsolicited advert. + if (circuit == null || + MatchesOfficialViewer(circuit.Channel, m_OfficialPrefixes) || + MatchesOfficialViewer(circuit.Viewer, m_OfficialPrefixes)) + return; + + DateTime now = DateTime.UtcNow; + lock (m_Sync) + { + if (m_LastSentUtc.TryGetValue(presence.UUID, out DateTime last) && + now - last < m_Interval) + return; + + // Reserve the slot before sending to avoid timer/login races. + m_LastSentUtc[presence.UUID] = now; + } + + try + { + // Owner-only chat: never broadcast the recommendation to a region. + client.SendChatMessage( + m_Message, + (byte)ChatTypeEnum.Owner, + presence.AbsolutePosition, + "OpenGenesisLINK System", + UUID.Zero, + UUID.Zero, + (byte)ChatSourceType.Object, + (byte)ChatAudibleLevel.Fully); + } + catch (Exception error) + { + lock (m_Sync) + { + if (m_LastSentUtc.TryGetValue(presence.UUID, out DateTime last) && + last == now) + m_LastSentUtc.Remove(presence.UUID); + } + + m_Log.Warn("[OGL-VIEWER-ADVISOR]: Sending viewer recommendation failed.", error); + } + } + } +} diff --git a/bin/OpenSim.ini b/bin/OpenSim.ini index 4c9b8d53..8d0f30fb 100644 --- a/bin/OpenSim.ini +++ b/bin/OpenSim.ini @@ -135,6 +135,14 @@ [Economy] economymodule = NexVerseMoneyModule +; OGL Viewer Advisor: opt-in recommendation for users of other viewers. +; The module is intentionally disabled until explicitly enabled. +[OGLViewerAdvisor] + Enabled = false + IntervalMinutes = 60 + OfficialViewerPrefixes = "OpenGenesisLINK;OGL Viewer" + Message = "Um das volle Erlebnis von OpenGenesisLINK geniessen zu koennen, steigen Sie auf den offiziellen OGL Viewer um: https://opengenesislink.de" + [NexDiscoveryViewer] Enabled = true LegacyFirestormCompatibility = true diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index 1226b886..c1d61249 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -135,6 +135,14 @@ [Economy] economymodule = NexVerseMoneyModule +; OGL Viewer Advisor: opt-in recommendation for users of other viewers. +; The module is intentionally disabled until explicitly enabled. +[OGLViewerAdvisor] + Enabled = false + IntervalMinutes = 60 + OfficialViewerPrefixes = "OpenGenesisLINK;OGL Viewer" + Message = "Um das volle Erlebnis von OpenGenesisLINK geniessen zu koennen, steigen Sie auf den offiziellen OGL Viewer um: https://opengenesislink.de" + [NexDiscoveryViewer] Enabled = true LegacyFirestormCompatibility = true diff --git a/doc/NexVerse/OGL_VIEWER_ADVISOR.md b/doc/NexVerse/OGL_VIEWER_ADVISOR.md new file mode 100644 index 00000000..426ddd1c --- /dev/null +++ b/doc/NexVerse/OGL_VIEWER_ADVISOR.md @@ -0,0 +1,70 @@ +# OGL Viewer Advisor (opt-in) + +OpenGenesisLINK contains a small server-side region module that recommends the +OGL Viewer in **private owner chat** to avatars using other viewer channels. + +**Release state:** Not activated. Both `bin/OpenSim.ini` and +`bin/OpenSim.ini.example` explicitly set `Enabled = false`. The module also +defaults to disabled when its section is absent. No resident will receive a +message until a server operator opts in and restarts the simulator. + +## Configuration + +```ini +[OGLViewerAdvisor] + Enabled = false + IntervalMinutes = 60 + OfficialViewerPrefixes = "OpenGenesisLINK;OGL Viewer" + Message = "Um das volle Erlebnis von OpenGenesisLINK geniessen zu koennen, steigen Sie auf den offiziellen OGL Viewer um: https://opengenesislink.de" +``` + +To activate later, change `Enabled = true` on **each simulator** where this +feature should run, then restart that simulator. Do not enable until the +shipping OGL Viewer reports a matching channel at login. Check the channel +in the actual viewer build, not merely the product title. + +- `IntervalMinutes`: whole minutes from 1 to 1440 (default 60). The active + root avatar is checked at rootification and every 15 seconds thereafter. +- `OfficialViewerPrefixes`: semicolon-separated, case-insensitive prefixes + for the client-supplied viewer channel/version. Empty prefixes match nothing. + Only an exact name or a name followed by a separator is exempt. +- `Message`: personalized plaintext (up to 900 characters), delivered using + `ChatTypeEnum.Owner` only to the affected client. It is not region chat. +- Avatars with missing circuit information, NPCs and child agents receive + no messages. Repeated rootification events on the same simulator process + do not cause another notice before the interval expires. + +## Important boundaries + +The per-avatar cooldown is **in memory in one simulator process**. It works +across regions hosted by that same process; restart or a teleport to a +*different simulator process* can reset that process's cooldown. A strict +grid-wide one-per-hour limit across multiple hosts requires a shared, +atomic coordinator (for example, a small authenticated ROBUST/API endpoint +with persisted timestamps). Do not treat the in-process limiter as a +cross-host guarantee. This is especially important if multiple simulator +instances are active. + +Viewer channel strings are self-reported and can be spoofed. This filter +must not be used as a security, access-control or entitlement decision. + +## Manual acceptance checks (in an isolated simulator) + +1. Without the section and with `Enabled=false`, log in using Firestorm: + no advisor chat. +2. Set `Enabled=true` in a test instance, then restart. Firestorm receives + one private chat notice after becoming a root agent. +3. Rootify again/teleport to another region on that same simulator within + 60 minutes: no additional notice. +4. Remain online for an hour: a second private notice arrives no earlier + than 60 minutes after the first (up to 15-second polling delay). +5. OGL Viewer's actual channel begins with a configured official prefix: + zero notices, even after one hour. +6. Another viewer and an unidentified-but-valid non-OGL channel receive + the same hourly reminder. +7. Repeat with the module disabled to verify no events or timer are active. +8. For multi-host deployments, test the known cross-process limitation or + integrate a central limiter **before** promising global hourly behavior. + +The module is compiled automatically by the recursive `NexVerse.RegionModules` +file inclusion in `prebuild.xml`; no separate project or LSL script is needed. diff --git a/tools/ci/verify_ogl_viewer_advisor.py b/tools/ci/verify_ogl_viewer_advisor.py new file mode 100644 index 00000000..f905efcf --- /dev/null +++ b/tools/ci/verify_ogl_viewer_advisor.py @@ -0,0 +1,41 @@ +#!/usr/bin/env python3 +"""Structural regression guard for the disabled-by-default OGL Viewer Advisor. + +This verifies source/config wiring, not the runtime C# behavior: run manual +simulator tests described in doc/NexVerse/OGL_VIEWER_ADVISOR.md as well. +""" +from pathlib import Path +import re + +root = Path(__file__).resolve().parents[2] +src = (root / "NexVerse/RegionModules/ViewerAdvisor/OGLViewerAdvisorModule.cs").read_text() +prebuild = (root / "prebuild.xml").read_text() +assert 'Project name="NexVerse.RegionModules"' in prebuild +assert '' in prebuild +for token in ( + 'ISharedRegionModule', + 'Id = "OGLViewerAdvisorModule"', + 'Configs["OGLViewerAdvisor"]', + 'GetBoolean("Enabled", false)', + 'TimeSpan.FromMinutes(60)', + 'OnMakeRootAgent += OnMakeRootAgent', + 'OnMakeRootAgent -= OnMakeRootAgent', + 'ForEachRootScenePresence(CheckAndNotify)', + 'GetAgentCircuitData(', + 'MatchesOfficialViewer(circuit.Channel, m_OfficialPrefixes)', + 'MatchesOfficialViewer(circuit.Viewer, m_OfficialPrefixes)', + 'ChatTypeEnum.Owner', + 'm_LastSentUtc.TryGetValue', + 'now - last < m_Interval', +): + assert token in src, token + +for rel in ("bin/OpenSim.ini", "bin/OpenSim.ini.example"): + ini = (root / rel).read_text() + assert ini.count("[OGLViewerAdvisor]") == 1, rel + section = ini.split("[OGLViewerAdvisor]", 1)[1].split("\n[", 1)[0] + assert re.search(r"(?m)^\s*Enabled\s*=\s*false\s*$", section), rel + assert re.search(r"(?m)^\s*IntervalMinutes\s*=\s*60\s*$", section), rel + assert "OfficialViewerPrefixes" in section, rel + +print("OK: OGL viewer advisor wired in, disabled in both simulator INIs")