diff --git a/.github/workflows/nexjast-ci.yml b/.github/workflows/nexjast-ci.yml index 1630fb88..0cbdf861 100644 --- a/.github/workflows/nexjast-ci.yml +++ b/.github/workflows/nexjast-ci.yml @@ -233,6 +233,14 @@ jobs: shell: bash run: dotnet run --configuration Release --project tools/ci/NexExperiencesRegression/NexExperiencesRegression.csproj + - name: Verify Roadmap 12 NexDiscovery + shell: bash + run: python3 tools/ci/verify_nexdiscovery.py + + - name: Regression-test NexDiscovery persistence and moderation + shell: bash + run: dotnet run --configuration Release --project tools/ci/NexDiscoveryRegression/NexDiscoveryRegression.csproj + - name: Verify NV dollar live database matrix contract shell: bash run: python3 tools/ci/verify_ledger_db_matrix.py @@ -406,10 +414,10 @@ jobs: shell: bash run: | grep -F 'public const string ProductName = "OpenGenesisLINK";' OpenSim/Framework/VersionInfo.cs - grep -F 'public const string VersionNumber = "0.9.3.7";' OpenSim/Framework/VersionInfo.cs - grep -F 'public const string AssemblyVersionNumber = "0.9.3.7";' OpenSim/Framework/VersionInfo.cs + grep -F 'public const string VersionNumber = "0.9.3.8";' OpenSim/Framework/VersionInfo.cs + grep -F 'public const string AssemblyVersionNumber = "0.9.3.8";' OpenSim/Framework/VersionInfo.cs grep -F 'public const Flavour VERSION_FLAVOUR = Flavour.Dev;' OpenSim/Framework/VersionInfo.cs - grep -F 'public const string MilestoneVersion = "0.9.3.7";' NexVerse/Core/NexVersePlatform.cs + grep -F 'public const string MilestoneVersion = "0.9.3.8";' NexVerse/Core/NexVersePlatform.cs grep -F 'Development checkpoint status: completed 3 October 2026' doc/NexVerse/CHECKPOINT_0.9.3.2.md grep -F '36/36 explicit checklist items completed' doc/NexVerse/CHECKPOINT_0.9.3.2.md @@ -459,7 +467,7 @@ jobs: grep -F '"status": "ok"' /tmp/nexverse-health.json curl --silent --fail --max-time 2 http://127.0.0.1:19090/api/v1/version > /tmp/nexverse-version.json - grep -F '"server_version": "OpenGenesisLINK 0.9.3.7 Dev"' /tmp/nexverse-version.json + grep -F '"server_version": "OpenGenesisLINK 0.9.3.8 Dev"' /tmp/nexverse-version.json grep -F '"api_version": "v1"' /tmp/nexverse-version.json grep -F '"language": "de-DE"' /tmp/nexverse-version.json @@ -670,6 +678,28 @@ jobs: ): assert inventory_path in doc["paths"], f"Inventory OpenAPI path missing: {inventory_path}" + for discovery_path in ( + "/api/v1/search", + "/api/v1/places", + "/api/v1/places/{placeId}", + "/api/v1/events", + "/api/v1/classifieds", + "/api/v1/land-portal", + "/api/v1/land-portal/owned", + "/api/v1/destinations", + "/api/v1/destinations/categories", + "/api/v1/destinations/{destinationId}", + "/api/v1/destinations/{destinationId}/visit", + "/api/v1/destinations/{destinationId}/moderation", + ): + assert discovery_path in doc["paths"], f"Discovery OpenAPI path missing: {discovery_path}" + + assert doc["paths"]["/api/v1/search"]["get"]["security"] == [] + assert doc["paths"]["/api/v1/places"]["get"]["security"] == [] + assert doc["paths"]["/api/v1/places"]["post"]["x-nexverse-scope"] == "discovery:manage" + assert doc["paths"]["/api/v1/destinations"]["post"]["x-nexverse-scope"] == "discovery:submit" + assert doc["paths"]["/api/v1/destinations/{destinationId}/moderation"]["post"]["x-nexverse-scope"] == "discovery:manage" + assert doc["components"]["securitySchemes"]["apiKeyAuth"]["name"] == "X-NexVerse-Api-Key" assert doc["x_nexverse_idempotency"]["protected_operations"] == [ "POST /api/v1/users", @@ -680,14 +710,16 @@ jobs: assert "/api/v1/docs" in doc["paths"] assert doc["x_nexverse_language"] == "de-DE" assert doc["x_nexverse_version_history"][0]["api_version"] == "v1" - assert doc["x_nexverse_version_history"][0]["server_line"] == "0.9.3.7" + assert doc["x_nexverse_version_history"][0]["server_line"] == "0.9.3.8" assert doc["x_nexverse_version_history"][0]["status"] == "development" - assert doc["x_nexverse_version_history"][1]["server_line"] == "0.9.3.6" + assert doc["x_nexverse_version_history"][1]["server_line"] == "0.9.3.7" assert doc["x_nexverse_version_history"][1]["status"] == "completed" - assert doc["x_nexverse_version_history"][2]["server_line"] == "0.9.3.5" + assert doc["x_nexverse_version_history"][2]["server_line"] == "0.9.3.6" assert doc["x_nexverse_version_history"][2]["status"] == "completed" - assert doc["x_nexverse_version_history"][3]["server_line"] == "0.9.3.4" - assert doc["x_nexverse_version_history"][3]["status"] == "release" + assert doc["x_nexverse_version_history"][3]["server_line"] == "0.9.3.5" + assert doc["x_nexverse_version_history"][3]["status"] == "completed" + assert doc["x_nexverse_version_history"][4]["server_line"] == "0.9.3.4" + assert doc["x_nexverse_version_history"][4]["status"] == "release" assert doc["x_nexverse_changelog"] assert doc["x_nexverse_changelog"][0]["version"] == "0.9.3.3" assert "0.9.3.1 Dev" not in json.dumps(doc, ensure_ascii=False) @@ -708,7 +740,7 @@ jobs: assert "/api/v1/estates/{estateId}/regions/{regionId}" in estate_change["endpoints"] roadmap = doc["x_nexverse_roadmap"] - assert roadmap["current_milestone"] == "0.9.3.7" + assert roadmap["current_milestone"] == "0.9.3.8" assert roadmap["current_codename"] == "" milestones = {item["version"]: item for item in roadmap["milestones"]} assert milestones["0.9.3.1"]["status"] == "released" @@ -720,6 +752,7 @@ jobs: assert milestones["0.9.3.5"]["checklist"] == {"completed": 83, "total": 83, "open": 0} assert milestones["0.9.3.6"]["status"] == "completed" assert milestones["0.9.3.7"]["status"] == "completed" + assert milestones["0.9.3.8"]["status"] == "completed" from pathlib import Path roadmap_text = Path("../doc/NexVerse/ROADMAP.md").read_text(encoding="utf-8") diff --git a/NexVerse/Core/Discovery/NexDiscoveryStore.cs b/NexVerse/Core/Discovery/NexDiscoveryStore.cs new file mode 100644 index 00000000..3cede1c5 --- /dev/null +++ b/NexVerse/Core/Discovery/NexDiscoveryStore.cs @@ -0,0 +1,692 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace NexVerse.Core.Discovery +{ + public enum NexDiscoveryMaturity + { + General = 0, + Moderate = 1, + Adult = 2 + } + + public enum NexDiscoveryPublicationState + { + Draft = 0, + Submitted = 1, + Approved = 2, + Rejected = 3 + } + + public enum NexLandUse + { + Other = 0, + Residential = 1, + Commercial = 2, + Mixed = 3 + } + + public sealed class NexPlaceRecord + { + public Guid PlaceId { get; set; } + public Guid RegionId { get; set; } + public string RegionName { get; set; } = string.Empty; + public Guid ParcelId { get; set; } + public int ParcelLocalId { get; set; } + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public NexDiscoveryMaturity Maturity { get; set; } = NexDiscoveryMaturity.General; + public List Images { get; set; } = new List(); + public Guid OwnerId { get; set; } + public int X { get; set; } = 128; + public int Y { get; set; } = 128; + public int Z { get; set; } = 25; + public string TeleportUri { get; set; } = string.Empty; + public string ParcelDetails { get; set; } = string.Empty; + public double Traffic { get; set; } + public List Tags { get; set; } = new List(); + public List EventIds { get; set; } = new List(); + public List RelatedDestinationIds { get; set; } = new List(); + public NexLandUse LandUse { get; set; } = NexLandUse.Other; + public string RegionType { get; set; } = string.Empty; + public bool Featured { get; set; } + public NexDiscoveryPublicationState State { get; set; } = NexDiscoveryPublicationState.Draft; + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; + } + + public sealed class NexEventRecord + { + public Guid EventId { get; set; } + public Guid PlaceId { get; set; } + public Guid OrganizerId { get; set; } + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string Image { get; set; } = string.Empty; + public NexDiscoveryMaturity Maturity { get; set; } = NexDiscoveryMaturity.General; + public DateTimeOffset StartsAt { get; set; } + public DateTimeOffset EndsAt { get; set; } + public long AdmissionPriceMinor { get; set; } + public List Tags { get; set; } = new List(); + public NexDiscoveryPublicationState State { get; set; } = NexDiscoveryPublicationState.Draft; + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; + } + + public sealed class NexClassifiedRecord + { + public Guid ClassifiedId { get; set; } + public Guid OwnerId { get; set; } + public Guid PlaceId { get; set; } + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string Category { get; set; } = string.Empty; + public string Image { get; set; } = string.Empty; + public NexDiscoveryMaturity Maturity { get; set; } = NexDiscoveryMaturity.General; + public List Tags { get; set; } = new List(); + public NexDiscoveryPublicationState State { get; set; } = NexDiscoveryPublicationState.Draft; + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; + } + + public sealed class NexDestinationRecord + { + public Guid DestinationId { get; set; } + public Guid PlaceId { get; set; } + public Guid SubmittedBy { get; set; } + public string Name { get; set; } = string.Empty; + public string Description { get; set; } = string.Empty; + public string Category { get; set; } = string.Empty; + public string Subcategory { get; set; } = string.Empty; + public string Collection { get; set; } = string.Empty; + public string Image { get; set; } = string.Empty; + public NexDiscoveryMaturity Maturity { get; set; } = NexDiscoveryMaturity.General; + public bool Featured { get; set; } + public bool EditorPick { get; set; } + public int Popularity { get; set; } + public List Tags { get; set; } = new List(); + public List EventIds { get; set; } = new List(); + public NexDiscoveryPublicationState State { get; set; } = NexDiscoveryPublicationState.Draft; + public string ModerationNote { get; set; } = string.Empty; + public string ModeratedBy { get; set; } = string.Empty; + public DateTimeOffset CreatedAt { get; set; } = DateTimeOffset.UtcNow; + public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.UtcNow; + } + + public sealed class NexDiscoverySnapshot + { + public int SchemaVersion { get; set; } = NexDiscoveryStore.CurrentSchemaVersion; + public List Places { get; set; } = new List(); + public List Events { get; set; } = new List(); + public List Classifieds { get; set; } = new List(); + public List Destinations { get; set; } = new List(); + } + + public sealed class NexDiscoveryStore + { + public const int CurrentSchemaVersion = 1; + + private readonly object m_Sync = new object(); + private readonly string m_Path; + private readonly JsonSerializerOptions m_Json; + private NexDiscoverySnapshot m_State; + + public NexDiscoveryStore(string path) + { + if (string.IsNullOrWhiteSpace(path)) + throw new ArgumentException("Discovery store path is required.", nameof(path)); + + m_Path = Path.GetFullPath(path); + m_Json = new JsonSerializerOptions + { + WriteIndented = true, + PropertyNameCaseInsensitive = true + }; + m_Json.Converters.Add(new JsonStringEnumConverter()); + m_State = Load(); + } + + public NexPlaceRecord GetPlace(Guid id) + { + lock (m_Sync) + return Clone(m_State.Places.FirstOrDefault(x => x.PlaceId == id)); + } + + public IReadOnlyList ListPlaces( + string query, + NexDiscoveryMaturity? maximumMaturity, + NexDiscoveryPublicationState? state, + int offset, + int limit) + { + ValidatePage(offset, limit); + string q = NormalizeQuery(query); + + lock (m_Sync) + { + IEnumerable source = m_State.Places; + + if (state.HasValue) + source = source.Where(x => x.State == state.Value); + if (maximumMaturity.HasValue) + source = source.Where(x => x.Maturity <= maximumMaturity.Value); + if (q.Length > 0) + source = source.Where(x => Matches(q, x.Name, x.RegionName, x.Description, x.ParcelDetails, string.Join(" ", x.Tags))); + + return source + .OrderByDescending(x => x.Featured) + .ThenByDescending(x => x.Traffic) + .ThenBy(x => x.Name, StringComparer.OrdinalIgnoreCase) + .Skip(offset) + .Take(limit) + .Select(Clone) + .ToArray(); + } + } + + public NexPlaceRecord UpsertPlace(NexPlaceRecord input) + { + if (input == null) + throw new ArgumentNullException(nameof(input)); + + NexPlaceRecord record = NormalizePlace(input); + + lock (m_Sync) + { + NexPlaceRecord existing = m_State.Places.FirstOrDefault(x => x.PlaceId == record.PlaceId); + if (existing != null) + { + record.CreatedAt = existing.CreatedAt; + m_State.Places.Remove(existing); + } + + record.UpdatedAt = DateTimeOffset.UtcNow; + m_State.Places.Add(record); + Save(); + return Clone(record); + } + } + + public bool DeletePlace(Guid id) + { + lock (m_Sync) + { + bool removed = m_State.Places.RemoveAll(x => x.PlaceId == id) > 0; + if (removed) + { + m_State.Destinations.RemoveAll(x => x.PlaceId == id); + m_State.Events.RemoveAll(x => x.PlaceId == id); + m_State.Classifieds.RemoveAll(x => x.PlaceId == id); + Save(); + } + return removed; + } + } + + public NexEventRecord GetEvent(Guid id) + { + lock (m_Sync) + return Clone(m_State.Events.FirstOrDefault(x => x.EventId == id)); + } + + public IReadOnlyList ListEvents( + string query, + NexDiscoveryMaturity? maximumMaturity, + NexDiscoveryPublicationState? state, + int offset, + int limit) + { + ValidatePage(offset, limit); + string q = NormalizeQuery(query); + + lock (m_Sync) + { + IEnumerable source = m_State.Events; + + if (state.HasValue) + source = source.Where(x => x.State == state.Value); + if (maximumMaturity.HasValue) + source = source.Where(x => x.Maturity <= maximumMaturity.Value); + if (q.Length > 0) + source = source.Where(x => Matches(q, x.Name, x.Description, string.Join(" ", x.Tags))); + + return source + .OrderBy(x => x.StartsAt) + .Skip(offset) + .Take(limit) + .Select(Clone) + .ToArray(); + } + } + + public NexEventRecord UpsertEvent(NexEventRecord input) + { + if (input == null) + throw new ArgumentNullException(nameof(input)); + if (input.EventId == Guid.Empty) + input.EventId = Guid.NewGuid(); + RequireName(input.Name, nameof(input.Name)); + if (input.PlaceId == Guid.Empty) + throw new ArgumentException("Event place is required."); + if (input.EndsAt <= input.StartsAt) + throw new ArgumentException("Event end must be after start."); + if (input.AdmissionPriceMinor < 0) + throw new ArgumentOutOfRangeException(nameof(input.AdmissionPriceMinor)); + + NexEventRecord record = Clone(input); + record.Name = record.Name.Trim(); + record.Description = TrimMax(record.Description, 8192); + record.Tags = NormalizeTags(record.Tags); + record.UpdatedAt = DateTimeOffset.UtcNow; + + lock (m_Sync) + { + if (!m_State.Places.Any(x => x.PlaceId == record.PlaceId)) + throw new InvalidOperationException("Event place was not found."); + + NexEventRecord existing = m_State.Events.FirstOrDefault(x => x.EventId == record.EventId); + if (existing != null) + { + record.CreatedAt = existing.CreatedAt; + m_State.Events.Remove(existing); + } + + m_State.Events.Add(record); + Save(); + return Clone(record); + } + } + + public bool DeleteEvent(Guid id) + { + lock (m_Sync) + { + bool removed = m_State.Events.RemoveAll(x => x.EventId == id) > 0; + foreach (NexPlaceRecord place in m_State.Places) + place.EventIds.RemoveAll(x => x == id); + foreach (NexDestinationRecord destination in m_State.Destinations) + destination.EventIds.RemoveAll(x => x == id); + if (removed) + Save(); + return removed; + } + } + + public NexClassifiedRecord GetClassified(Guid id) + { + lock (m_Sync) + return Clone(m_State.Classifieds.FirstOrDefault(x => x.ClassifiedId == id)); + } + + public IReadOnlyList ListClassifieds( + string query, + NexDiscoveryMaturity? maximumMaturity, + NexDiscoveryPublicationState? state, + int offset, + int limit) + { + ValidatePage(offset, limit); + string q = NormalizeQuery(query); + + lock (m_Sync) + { + IEnumerable source = m_State.Classifieds; + if (state.HasValue) + source = source.Where(x => x.State == state.Value); + if (maximumMaturity.HasValue) + source = source.Where(x => x.Maturity <= maximumMaturity.Value); + if (q.Length > 0) + source = source.Where(x => Matches(q, x.Name, x.Description, x.Category, string.Join(" ", x.Tags))); + + return source + .OrderByDescending(x => x.UpdatedAt) + .Skip(offset) + .Take(limit) + .Select(Clone) + .ToArray(); + } + } + + public NexClassifiedRecord UpsertClassified(NexClassifiedRecord input) + { + if (input == null) + throw new ArgumentNullException(nameof(input)); + if (input.ClassifiedId == Guid.Empty) + input.ClassifiedId = Guid.NewGuid(); + RequireName(input.Name, nameof(input.Name)); + + NexClassifiedRecord record = Clone(input); + record.Name = record.Name.Trim(); + record.Description = TrimMax(record.Description, 8192); + record.Category = TrimMax(record.Category, 128); + record.Tags = NormalizeTags(record.Tags); + record.UpdatedAt = DateTimeOffset.UtcNow; + + lock (m_Sync) + { + if (record.PlaceId != Guid.Empty && + !m_State.Places.Any(x => x.PlaceId == record.PlaceId)) + { + throw new InvalidOperationException("Classified place was not found."); + } + + NexClassifiedRecord existing = + m_State.Classifieds.FirstOrDefault(x => x.ClassifiedId == record.ClassifiedId); + + if (existing != null) + { + record.CreatedAt = existing.CreatedAt; + m_State.Classifieds.Remove(existing); + } + + m_State.Classifieds.Add(record); + Save(); + return Clone(record); + } + } + + public bool DeleteClassified(Guid id) + { + lock (m_Sync) + { + bool removed = m_State.Classifieds.RemoveAll(x => x.ClassifiedId == id) > 0; + if (removed) + Save(); + return removed; + } + } + + public NexDestinationRecord GetDestination(Guid id) + { + lock (m_Sync) + return Clone(m_State.Destinations.FirstOrDefault(x => x.DestinationId == id)); + } + + public IReadOnlyList ListDestinations( + string query, + NexDiscoveryMaturity? maximumMaturity, + NexDiscoveryPublicationState? state, + string category, + string collection, + bool? featured, + bool? editorPick, + string sort, + int offset, + int limit) + { + ValidatePage(offset, limit); + string q = NormalizeQuery(query); + string categoryKey = NormalizeQuery(category); + string collectionKey = NormalizeQuery(collection); + + lock (m_Sync) + { + IEnumerable source = m_State.Destinations; + + if (state.HasValue) + source = source.Where(x => x.State == state.Value); + if (maximumMaturity.HasValue) + source = source.Where(x => x.Maturity <= maximumMaturity.Value); + if (featured.HasValue) + source = source.Where(x => x.Featured == featured.Value); + if (editorPick.HasValue) + source = source.Where(x => x.EditorPick == editorPick.Value); + if (categoryKey.Length > 0) + source = source.Where(x => NormalizeQuery(x.Category) == categoryKey); + if (collectionKey.Length > 0) + source = source.Where(x => NormalizeQuery(x.Collection) == collectionKey); + if (q.Length > 0) + source = source.Where(x => Matches(q, x.Name, x.Description, x.Category, x.Subcategory, x.Collection, string.Join(" ", x.Tags))); + + source = (sort ?? string.Empty).Trim().ToLowerInvariant() switch + { + "recent" => source.OrderByDescending(x => x.CreatedAt), + "popular" => source.OrderByDescending(x => x.Popularity).ThenByDescending(x => x.UpdatedAt), + "hot" => source.OrderByDescending(x => x.Popularity).ThenByDescending(x => x.CreatedAt), + _ => source.OrderByDescending(x => x.EditorPick).ThenByDescending(x => x.Featured).ThenByDescending(x => x.Popularity) + }; + + return source + .Skip(offset) + .Take(limit) + .Select(Clone) + .ToArray(); + } + } + + public NexDestinationRecord UpsertDestination(NexDestinationRecord input) + { + if (input == null) + throw new ArgumentNullException(nameof(input)); + if (input.DestinationId == Guid.Empty) + input.DestinationId = Guid.NewGuid(); + if (input.PlaceId == Guid.Empty) + throw new ArgumentException("Destination place is required."); + RequireName(input.Name, nameof(input.Name)); + + NexDestinationRecord record = Clone(input); + record.Name = record.Name.Trim(); + record.Description = TrimMax(record.Description, 8192); + record.Category = TrimMax(record.Category, 128); + record.Subcategory = TrimMax(record.Subcategory, 128); + record.Collection = TrimMax(record.Collection, 128); + record.Tags = NormalizeTags(record.Tags); + record.UpdatedAt = DateTimeOffset.UtcNow; + + lock (m_Sync) + { + if (!m_State.Places.Any(x => x.PlaceId == record.PlaceId)) + throw new InvalidOperationException("Destination place was not found."); + + NexDestinationRecord existing = + m_State.Destinations.FirstOrDefault(x => x.DestinationId == record.DestinationId); + + if (existing != null) + { + record.CreatedAt = existing.CreatedAt; + record.Popularity = Math.Max(existing.Popularity, record.Popularity); + record.ModeratedBy = existing.ModeratedBy; + record.ModerationNote = existing.ModerationNote; + m_State.Destinations.Remove(existing); + } + + m_State.Destinations.Add(record); + Save(); + return Clone(record); + } + } + + public NexDestinationRecord ModerateDestination( + Guid destinationId, + NexDiscoveryPublicationState state, + string moderator, + string note) + { + if (state != NexDiscoveryPublicationState.Approved && + state != NexDiscoveryPublicationState.Rejected) + { + throw new ArgumentException("Moderation state must be Approved or Rejected."); + } + + lock (m_Sync) + { + NexDestinationRecord record = + m_State.Destinations.FirstOrDefault(x => x.DestinationId == destinationId) ?? + throw new KeyNotFoundException("Destination was not found."); + + record.State = state; + record.ModeratedBy = (moderator ?? string.Empty).Trim(); + record.ModerationNote = TrimMax(note, 2048); + record.UpdatedAt = DateTimeOffset.UtcNow; + Save(); + return Clone(record); + } + } + + public NexDestinationRecord RecordDestinationVisit(Guid destinationId) + { + lock (m_Sync) + { + NexDestinationRecord record = + m_State.Destinations.FirstOrDefault(x => x.DestinationId == destinationId) ?? + throw new KeyNotFoundException("Destination was not found."); + + if (record.State != NexDiscoveryPublicationState.Approved) + throw new InvalidOperationException("Only approved destinations can receive visits."); + + record.Popularity = checked(record.Popularity + 1); + record.UpdatedAt = DateTimeOffset.UtcNow; + Save(); + return Clone(record); + } + } + + public IReadOnlyList GetCategories() + { + lock (m_Sync) + { + return m_State.Destinations + .Where(x => x.State == NexDiscoveryPublicationState.Approved) + .GroupBy(x => x.Category ?? string.Empty, StringComparer.OrdinalIgnoreCase) + .Where(x => !string.IsNullOrWhiteSpace(x.Key)) + .OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase) + .Select(x => (object)new + { + category = x.Key, + subcategories = x + .Select(y => y.Subcategory) + .Where(y => !string.IsNullOrWhiteSpace(y)) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(y => y, StringComparer.OrdinalIgnoreCase) + .ToArray(), + count = x.Count() + }) + .ToArray(); + } + } + + private NexDiscoverySnapshot Load() + { + if (!File.Exists(m_Path)) + return new NexDiscoverySnapshot(); + + NexDiscoverySnapshot state = + JsonSerializer.Deserialize( + File.ReadAllText(m_Path), + m_Json) ?? + new NexDiscoverySnapshot(); + + if (state.SchemaVersion != CurrentSchemaVersion) + throw new InvalidOperationException("Unsupported NexDiscovery schema version."); + + state.Places ??= new List(); + state.Events ??= new List(); + state.Classifieds ??= new List(); + state.Destinations ??= new List(); + return state; + } + + private void Save() + { + string directory = Path.GetDirectoryName(m_Path); + if (!string.IsNullOrWhiteSpace(directory)) + Directory.CreateDirectory(directory); + + string temp = m_Path + ".tmp"; + File.WriteAllText(temp, JsonSerializer.Serialize(m_State, m_Json)); + File.Move(temp, m_Path, true); + } + + private NexPlaceRecord NormalizePlace(NexPlaceRecord input) + { + NexPlaceRecord record = Clone(input); + if (record.PlaceId == Guid.Empty) + record.PlaceId = Guid.NewGuid(); + if (record.RegionId == Guid.Empty) + throw new ArgumentException("Place region is required."); + RequireName(record.Name, nameof(record.Name)); + + record.Name = record.Name.Trim(); + record.RegionName = TrimMax(record.RegionName, 255); + record.Description = TrimMax(record.Description, 8192); + record.ParcelDetails = TrimMax(record.ParcelDetails, 8192); + record.RegionType = TrimMax(record.RegionType, 128); + record.TeleportUri = TrimMax(record.TeleportUri, 2048); + record.Images = NormalizeStrings(record.Images, 16, 2048); + record.Tags = NormalizeTags(record.Tags); + record.EventIds ??= new List(); + record.RelatedDestinationIds ??= new List(); + + if (record.X < 0 || record.Y < 0 || record.Z < 0) + throw new ArgumentOutOfRangeException("Place coordinates must be non-negative."); + if (record.Traffic < 0 || double.IsNaN(record.Traffic) || double.IsInfinity(record.Traffic)) + throw new ArgumentOutOfRangeException(nameof(record.Traffic)); + + return record; + } + + private static List NormalizeTags(IEnumerable values) => + NormalizeStrings(values, 32, 64) + .Select(x => x.ToLowerInvariant()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToList(); + + private static List NormalizeStrings( + IEnumerable values, + int maximumCount, + int maximumLength) + { + return (values ?? Array.Empty()) + .Select(x => TrimMax(x, maximumLength)) + .Where(x => x.Length > 0) + .Distinct(StringComparer.OrdinalIgnoreCase) + .Take(maximumCount) + .ToList(); + } + + private static string TrimMax(string value, int max) + { + string normalized = (value ?? string.Empty).Trim(); + return normalized.Length <= max + ? normalized + : normalized.Substring(0, max); + } + + private static void RequireName(string value, string parameter) + { + string normalized = (value ?? string.Empty).Trim(); + if (normalized.Length == 0 || normalized.Length > 255) + throw new ArgumentException("A name between 1 and 255 characters is required.", parameter); + } + + private static string NormalizeQuery(string value) => + (value ?? string.Empty).Trim().ToLowerInvariant(); + + private static bool Matches(string query, params string[] values) => + values.Any(x => NormalizeQuery(x).Contains(query, StringComparison.Ordinal)); + + private static void ValidatePage(int offset, int limit) + { + if (offset < 0) + throw new ArgumentOutOfRangeException(nameof(offset)); + if (limit < 1 || limit > 500) + throw new ArgumentOutOfRangeException(nameof(limit)); + } + + private T Clone(T value) + { + if (value == null) + return default; + + return JsonSerializer.Deserialize( + JsonSerializer.Serialize(value, m_Json), + m_Json); + } + } +} diff --git a/NexVerse/Core/NexVersePlatform.cs b/NexVerse/Core/NexVersePlatform.cs index acdd365b..a5cd4c6d 100644 --- a/NexVerse/Core/NexVersePlatform.cs +++ b/NexVerse/Core/NexVersePlatform.cs @@ -8,9 +8,9 @@ namespace NexVerse.Core public static class NexVersePlatform { public const string ProductName = "OpenGenesisLINK"; - public const string MilestoneVersion = "0.9.3.7"; + public const string MilestoneVersion = "0.9.3.8"; public const string MilestoneCodename = ""; - public const string MilestoneTitle = "NexGroups und NexExperiences"; + public const string MilestoneTitle = "NexSearch, Places, Land und Destination Guide"; public const string UiLanguage = "de-DE"; public const string ApiVersion = "v1"; public const string ProtocolVersion = "1"; @@ -27,6 +27,7 @@ namespace NexVerse.Core ["voice"] = "planned", ["economy"] = "native-nv-dollar", ["lsl"] = "experience-tools-integrated", + ["discovery"] = "native-v1", ["firestorm"] = "baseline-validation-pending" }; } diff --git a/NexVerse/Core/Security/NexSecurity.cs b/NexVerse/Core/Security/NexSecurity.cs index 64d08997..42c70e91 100644 --- a/NexVerse/Core/Security/NexSecurity.cs +++ b/NexVerse/Core/Security/NexSecurity.cs @@ -35,6 +35,9 @@ namespace NexVerse.Core.Security public const string ExperiencesRead = "experiences:read"; public const string ExperiencesManage = "experiences:manage"; public const string ExperiencesScript = "experiences:script"; + public const string DiscoveryRead = "discovery:read"; + public const string DiscoverySubmit = "discovery:submit"; + public const string DiscoveryManage = "discovery:manage"; } public sealed class NexPrincipal diff --git a/NexVerse/RegionModules/Discovery/NexDiscoveryViewerModule.cs b/NexVerse/RegionModules/Discovery/NexDiscoveryViewerModule.cs new file mode 100644 index 00000000..e55b29c2 --- /dev/null +++ b/NexVerse/RegionModules/Discovery/NexDiscoveryViewerModule.cs @@ -0,0 +1,273 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Http; +using log4net; +using Mono.Addins; +using Nini.Config; +using OpenMetaverse; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Region.Framework.Interfaces; +using OpenSim.Region.Framework.Scenes; +using Caps = OpenSim.Framework.Capabilities.Caps; + +namespace NexVerse.RegionModules.Discovery +{ + [Extension( + Path = "/OpenSim/RegionModules", + NodeName = "RegionModule", + Id = "NexDiscoveryViewerModule")] + public sealed class NexDiscoveryViewerModule : + ISharedRegionModule + { + private static readonly ILog m_Log = + LogManager.GetLogger( + typeof(NexDiscoveryViewerModule)); + + private readonly object m_Sync = new object(); + private readonly List m_Scenes = + new List(); + + private bool m_Enabled; + private string m_WorldApiBaseUrl = string.Empty; + private int m_RequestTimeoutMilliseconds = 3000; + private HttpClient m_Http; + + public string Name => "NexDiscoveryViewerModule"; + public Type ReplaceableInterface => null; + + public void Initialise(IConfigSource config) + { + IConfig section = + config?.Configs["NexDiscoveryViewer"]; + + if (section == null || + !section.GetBoolean("Enabled", false)) + { + m_Enabled = false; + return; + } + + m_WorldApiBaseUrl = + section.GetString( + "WorldApiBaseUrl", + string.Empty) + .Trim() + .TrimEnd('/'); + + m_RequestTimeoutMilliseconds = + Math.Clamp( + section.GetInt( + "RequestTimeoutMilliseconds", + 3000), + 500, + 30000); + + if (!Uri.TryCreate( + m_WorldApiBaseUrl, + UriKind.Absolute, + out Uri baseUri) || + (baseUri.Scheme != Uri.UriSchemeHttp && + baseUri.Scheme != Uri.UriSchemeHttps)) + { + throw new InvalidOperationException( + "[NEX-DISCOVERY]: WorldApiBaseUrl must be an absolute HTTP(S) URL."); + } + + m_Http = + new HttpClient + { + Timeout = + TimeSpan.FromMilliseconds( + m_RequestTimeoutMilliseconds) + }; + + m_Enabled = true; + + m_Log.InfoFormat( + "[NEX-DISCOVERY]: Viewer capability adapter enabled for {0}.", + m_WorldApiBaseUrl); + } + + public void PostInitialise() + { + } + + public void AddRegion(Scene scene) + { + if (!m_Enabled || scene == null) + return; + + lock (m_Sync) + m_Scenes.Add(scene); + + scene.EventManager.OnRegisterCaps += + OnRegisterCaps; + } + + public void RegionLoaded(Scene scene) + { + } + + public void RemoveRegion(Scene scene) + { + if (scene == null) + return; + + scene.EventManager.OnRegisterCaps -= + OnRegisterCaps; + + lock (m_Sync) + m_Scenes.Remove(scene); + } + + public void Close() + { + lock (m_Sync) + { + foreach (Scene scene in m_Scenes) + { + scene.EventManager.OnRegisterCaps -= + OnRegisterCaps; + } + + m_Scenes.Clear(); + } + + m_Http?.Dispose(); + m_Http = null; + } + + private void OnRegisterCaps( + UUID agentId, + Caps caps) + { + if (!m_Enabled || + caps == null) + { + return; + } + + Register( + caps, + "NexSearch", + "/api/v1/search"); + + Register( + caps, + "NexPlaces", + "/api/v1/places"); + + Register( + caps, + "NexLandPortal", + "/api/v1/land-portal"); + + Register( + caps, + "NexDestinationGuide", + "/api/v1/destinations"); + } + + private void Register( + Caps caps, + string capability, + string worldApiPath) + { + caps.RegisterSimpleHandler( + capability, + new SimpleStreamHandler( + "/" + UUID.Random(), + (request, response) => + Proxy( + request, + response, + worldApiPath))); + } + + private void Proxy( + IOSHttpRequest request, + IOSHttpResponse response, + string worldApiPath) + { + if (!string.Equals( + request?.HttpMethod, + "GET", + StringComparison.OrdinalIgnoreCase)) + { + response.StatusCode = + (int)HttpStatusCode.MethodNotAllowed; + response.ContentType = + "application/json; charset=utf-8"; + response.RawBuffer = + System.Text.Encoding.UTF8.GetBytes( + "{\"error\":\"method_not_allowed\",\"message\":\"GET is required.\"}"); + return; + } + + try + { + string query = + request?.Url?.Query ?? + string.Empty; + + using HttpRequestMessage outbound = + new HttpRequestMessage( + HttpMethod.Get, + m_WorldApiBaseUrl + + worldApiPath + + query); + + outbound.Headers.TryAddWithoutValidation( + "X-NexVerse-Viewer-Agent", + capsSafeAgent(request)); + + using HttpResponseMessage upstream = + m_Http.Send(outbound); + + response.StatusCode = + (int)upstream.StatusCode; + + response.ContentType = + upstream.Content.Headers.ContentType + ?.ToString() ?? + "application/json; charset=utf-8"; + + response.RawBuffer = + upstream.Content + .ReadAsByteArrayAsync() + .GetAwaiter() + .GetResult(); + } + catch (Exception e) + { + m_Log.WarnFormat( + "[NEX-DISCOVERY]: Viewer capability proxy {0} failed: {1}", + worldApiPath, + e.Message); + + response.StatusCode = + (int)HttpStatusCode.BadGateway; + response.ContentType = + "application/json; charset=utf-8"; + response.RawBuffer = + System.Text.Encoding.UTF8.GetBytes( + "{\"error\":\"discovery_upstream_unavailable\",\"message\":\"World API discovery service is unavailable.\"}"); + } + } + + private static string capsSafeAgent( + IOSHttpRequest request) + { + string agent = + request?.UserAgent ?? + string.Empty; + + return agent.Length <= 255 + ? agent + : agent.Substring(0, 255); + } + } +} diff --git a/NexVerse/Server/Api/NexDiscoveryApi.cs b/NexVerse/Server/Api/NexDiscoveryApi.cs new file mode 100644 index 00000000..03971f6a --- /dev/null +++ b/NexVerse/Server/Api/NexDiscoveryApi.cs @@ -0,0 +1,1184 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text.Json; +using System.Text.Json.Serialization; +using NexVerse.Core.Audit; +using NexVerse.Core.Discovery; +using NexVerse.Core.Economy; +using NexVerse.Core.Experiences; +using NexVerse.Core.Security; +using OpenMetaverse; +using OpenSim.Framework; +using OpenSim.Framework.Servers.HttpServer; +using OpenSim.Groups; +using OpenSim.Services.Interfaces; +using GridRegion = OpenSim.Services.Interfaces.GridRegion; + +namespace NexVerse.Server.Api +{ + internal sealed class NexDiscoveryApi + { + private static readonly JsonSerializerOptions s_Json = + CreateJsonOptions(); + + private readonly NexApiAuthenticator m_Authenticator; + private readonly IUserAccountService m_Users; + private readonly IGridService m_Grid; + private readonly GroupsService m_Groups; + private readonly NexExperienceStore m_Experiences; + private readonly NexDiscoveryStore m_Store; + private readonly Func m_Economy; + private readonly INexAuditSink m_Audit; + private readonly string m_TeleportBaseUri; + + public NexDiscoveryApi( + NexApiAuthenticator authenticator, + IUserAccountService users, + IGridService grid, + GroupsService groups, + NexExperienceStore experiences, + NexDiscoveryStore store, + Func economy, + INexAuditSink audit, + string teleportBaseUri) + { + m_Authenticator = authenticator ?? throw new ArgumentNullException(nameof(authenticator)); + m_Users = users; + m_Grid = grid; + m_Groups = groups; + m_Experiences = experiences ?? throw new ArgumentNullException(nameof(experiences)); + m_Store = store ?? throw new ArgumentNullException(nameof(store)); + m_Economy = economy ?? throw new ArgumentNullException(nameof(economy)); + m_Audit = audit ?? NullNexAuditSink.Instance; + m_TeleportBaseUri = (teleportBaseUri ?? string.Empty).Trim().TrimEnd('/'); + } + + public void HandleSearch(IOSHttpRequest request, IOSHttpResponse response) + { + if (!RequireMethod(request, response, "GET")) + return; + + try + { + string query = Query(request, "q"); + HashSet types = + ParseTypes(Query(request, "types")); + NexDiscoveryMaturity? maturity = + ParseOptionalMaturity(Query(request, "maturity")); + int limit = QueryInt(request, "limit", 50, 1, 100); + + List hits = new List(); + + if (Wants(types, "people") && query.Length > 0 && m_Users != null) + { + foreach (UserAccount user in + (m_Users.GetUserAccounts(UUID.Zero, query) ?? + new List()) + .Where(x => x != null && x.Active) + .Take(limit)) + { + hits.Add(new + { + type = "people", + id = user.PrincipalID.ToString(), + name = user.EffectiveDisplayName, + username = user.Username, + description = user.UserTitle ?? string.Empty + }); + } + } + + if (Wants(types, "groups") && query.Length > 0 && m_Groups != null) + { + foreach (DirGroupsReplyData group in + (m_Groups.FindGroups(UUID.Zero.ToString(), query) ?? + new List()) + .Take(limit)) + { + hits.Add(new + { + type = "groups", + id = group.groupID.ToString(), + name = group.groupName, + members = group.members + }); + } + } + + if (Wants(types, "regions") && query.Length > 0 && m_Grid != null) + { + foreach (GridRegion region in + (m_Grid.GetRegionsByName(UUID.Zero, query, limit) ?? + new List()) + .Take(limit)) + { + if (!AllowsMaturity(maturity, RegionMaturity(region))) + continue; + + hits.Add(new + { + type = "regions", + id = region.RegionID.ToString(), + name = region.RegionName, + maturity = RegionMaturity(region).ToString().ToLowerInvariant(), + x = region.RegionLocX, + y = region.RegionLocY, + size_x = region.RegionSizeX, + size_y = region.RegionSizeY, + teleport_uri = BuildTeleport(region.RegionName, 128, 128, 25) + }); + } + } + + if (Wants(types, "experiences")) + { + foreach (NexExperience experience in + m_Experiences.Search(query, 0, limit) + .Where(x => x.Enabled)) + { + NexDiscoveryMaturity experienceMaturity = + (NexDiscoveryMaturity)(int)experience.Maturity; + if (!AllowsMaturity(maturity, experienceMaturity)) + continue; + + hits.Add(new + { + type = "experiences", + id = experience.ExperienceId, + name = experience.Name, + description = experience.Description, + maturity = experienceMaturity.ToString().ToLowerInvariant(), + owner_id = experience.OwnerId, + group_id = experience.GroupId + }); + } + } + + AddContentHits(hits, query, types, maturity, limit); + AddLandHits(hits, query, types, maturity, limit); + + WriteJson(response, new + { + query, + types = types.Count == 0 ? new[] { "all" } : types.OrderBy(x => x).ToArray(), + count = Math.Min(hits.Count, limit), + results = hits.Take(limit).ToArray(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + } + + public void HandlePlaces(IOSHttpRequest request, IOSHttpResponse response) + { + string path = (request?.UriPath ?? string.Empty).TrimEnd('/'); + string method = request?.HttpMethod ?? string.Empty; + + if (path.Equals("/api/v1/places", StringComparison.OrdinalIgnoreCase)) + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + try + { + IReadOnlyList places = + m_Store.ListPlaces( + Query(request, "q"), + ParseOptionalMaturity(Query(request, "maturity")), + NexDiscoveryPublicationState.Approved, + QueryInt(request, "offset", 0, 0, int.MaxValue), + QueryInt(request, "limit", 50, 1, 200)); + + WriteJson(response, new + { + places = places.Select(PlacePayload).ToArray(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.DiscoveryManage, out NexPrincipal principal, out _)) + return; + + try + { + NexPlaceRecord input = ReadBody(request); + NexPlaceRecord saved = m_Store.UpsertPlace(input); + Audit(principal, "discovery.place.upserted", "place:" + saved.PlaceId, response); + WriteJson(response, new + { + place = PlacePayload(saved), + correlation_id = Correlation(response) + }, HttpStatusCode.Created); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + MethodNotAllowed(response, "GET or POST"); + return; + } + + if (TryResourceId(path, "/api/v1/places/", out Guid placeId)) + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + NexPlaceRecord place = m_Store.GetPlace(placeId); + if (place == null || place.State != NexDiscoveryPublicationState.Approved) + { + NotFound(response, "place_not_found", "Place was not found."); + return; + } + + WriteJson(response, new + { + place = PlacePayload(place), + events = place.EventIds + .Select(m_Store.GetEvent) + .Where(x => x != null && x.State == NexDiscoveryPublicationState.Approved) + .ToArray(), + related_destinations = place.RelatedDestinationIds + .Select(m_Store.GetDestination) + .Where(x => x != null && x.State == NexDiscoveryPublicationState.Approved) + .Select(DestinationPayload) + .ToArray(), + correlation_id = Correlation(response) + }); + return; + } + + if (method.Equals("PUT", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.DiscoveryManage, out NexPrincipal principal, out _)) + return; + + try + { + NexPlaceRecord input = ReadBody(request); + input.PlaceId = placeId; + NexPlaceRecord saved = m_Store.UpsertPlace(input); + Audit(principal, "discovery.place.upserted", "place:" + saved.PlaceId, response); + WriteJson(response, new { place = PlacePayload(saved), correlation_id = Correlation(response) }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + if (method.Equals("DELETE", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.DiscoveryManage, out NexPrincipal principal, out _)) + return; + + bool removed = m_Store.DeletePlace(placeId); + Audit(principal, "discovery.place.deleted", "place:" + placeId, response); + WriteJson(response, new { deleted = removed, correlation_id = Correlation(response) }); + return; + } + + MethodNotAllowed(response, "GET, PUT or DELETE"); + return; + } + + NotFound(response, "not_found", "Places endpoint was not found."); + } + + public void HandleContent(IOSHttpRequest request, IOSHttpResponse response) + { + string path = (request?.UriPath ?? string.Empty).TrimEnd('/'); + string method = request?.HttpMethod ?? string.Empty; + + if (path.Equals("/api/v1/events", StringComparison.OrdinalIgnoreCase)) + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + WriteJson(response, new + { + events = m_Store.ListEvents( + Query(request, "q"), + ParseOptionalMaturity(Query(request, "maturity")), + NexDiscoveryPublicationState.Approved, + QueryInt(request, "offset", 0, 0, int.MaxValue), + QueryInt(request, "limit", 50, 1, 200)), + correlation_id = Correlation(response) + }); + return; + } + + if (method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.DiscoveryManage, out NexPrincipal principal, out _)) + return; + + try + { + NexEventRecord saved = m_Store.UpsertEvent(ReadBody(request)); + Audit(principal, "discovery.event.upserted", "event:" + saved.EventId, response); + WriteJson(response, new { @event = saved, correlation_id = Correlation(response) }, HttpStatusCode.Created); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + } + + if (path.Equals("/api/v1/classifieds", StringComparison.OrdinalIgnoreCase)) + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + WriteJson(response, new + { + classifieds = m_Store.ListClassifieds( + Query(request, "q"), + ParseOptionalMaturity(Query(request, "maturity")), + NexDiscoveryPublicationState.Approved, + QueryInt(request, "offset", 0, 0, int.MaxValue), + QueryInt(request, "limit", 50, 1, 200)), + correlation_id = Correlation(response) + }); + return; + } + + if (method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.DiscoveryManage, out NexPrincipal principal, out _)) + return; + + try + { + NexClassifiedRecord saved = m_Store.UpsertClassified(ReadBody(request)); + Audit(principal, "discovery.classified.upserted", "classified:" + saved.ClassifiedId, response); + WriteJson(response, new { classified = saved, correlation_id = Correlation(response) }, HttpStatusCode.Created); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + } + + NotFound(response, "not_found", "Discovery content endpoint was not found."); + } + + public void HandleLandPortal(IOSHttpRequest request, IOSHttpResponse response) + { + if (!RequireMethod(request, response, "GET")) + return; + + try + { + NexEconomyService economy = + m_Economy() ?? + throw new InvalidOperationException("NV$ economy is unavailable."); + + string path = (request?.UriPath ?? string.Empty).TrimEnd('/'); + string query = Query(request, "q"); + NexLandListingType? listingType = + ParseLandListingType(Query(request, "type")); + int limit = QueryInt(request, "limit", 50, 1, 200); + int offset = QueryInt(request, "offset", 0, 0, int.MaxValue); + + IReadOnlyList listings = + economy.SearchLandListings(query, listingType, 0, 500); + + if (path.EndsWith("/owned", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.DiscoveryRead, out NexPrincipal _, out UserAccount account)) + return; + + Guid ownerId = + account != null + ? account.PrincipalID.Guid + : QueryGuid(request, "owner_id"); + + listings = + listings.Where(x => x.SellerAccountId == ownerId).ToArray(); + } + else + { + listings = + listings.Where(x => x.Active).ToArray(); + } + + string useFilter = Query(request, "land_use"); + string regionTypeFilter = Query(request, "region_type"); + bool? featured = QueryNullableBool(request, "featured"); + long minPrice = QueryLong(request, "min_price", 0, 0, long.MaxValue); + long maxPrice = QueryLong(request, "max_price", long.MaxValue, 0, long.MaxValue); + int minArea = QueryInt(request, "min_area", 0, 0, int.MaxValue); + NexDiscoveryMaturity? maturity = ParseOptionalMaturity(Query(request, "maturity")); + + List results = new List(); + foreach (NexLandListing listing in listings) + { + NexPlaceRecord place = FindPlace(listing); + + if (listing.PriceMinor < minPrice || listing.PriceMinor > maxPrice || listing.Area < minArea) + continue; + if (!string.IsNullOrWhiteSpace(useFilter) && + (place == null || !place.LandUse.ToString().Equals(useFilter, StringComparison.OrdinalIgnoreCase))) + continue; + if (!string.IsNullOrWhiteSpace(regionTypeFilter) && + (place == null || !place.RegionType.Equals(regionTypeFilter, StringComparison.OrdinalIgnoreCase))) + continue; + if (featured.HasValue && (place?.Featured ?? false) != featured.Value) + continue; + if (maturity.HasValue && + place != null && + place.Maturity > maturity.Value) + continue; + + results.Add(LandPayload(listing, place)); + } + + WriteJson(response, new + { + currency = NexLedgerCurrency.Code, + count = results.Skip(offset).Take(limit).Count(), + listings = results.Skip(offset).Take(limit).ToArray(), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + } + + public void HandleDestinations(IOSHttpRequest request, IOSHttpResponse response) + { + string path = (request?.UriPath ?? string.Empty).TrimEnd('/'); + string method = request?.HttpMethod ?? string.Empty; + + if (path.Equals("/api/v1/destinations/categories", StringComparison.OrdinalIgnoreCase)) + { + if (!RequireMethod(request, response, "GET")) + return; + + WriteJson(response, new + { + categories = m_Store.GetCategories(), + correlation_id = Correlation(response) + }); + return; + } + + if (path.Equals("/api/v1/destinations", StringComparison.OrdinalIgnoreCase)) + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + WriteJson(response, new + { + destinations = m_Store.ListDestinations( + Query(request, "q"), + ParseOptionalMaturity(Query(request, "maturity")), + NexDiscoveryPublicationState.Approved, + Query(request, "category"), + Query(request, "collection"), + QueryNullableBool(request, "featured"), + QueryNullableBool(request, "editor_pick"), + Query(request, "sort"), + QueryInt(request, "offset", 0, 0, int.MaxValue), + QueryInt(request, "limit", 50, 1, 200)) + .Select(DestinationPayload) + .ToArray(), + correlation_id = Correlation(response) + }); + return; + } + + if (method.Equals("POST", StringComparison.OrdinalIgnoreCase)) + { + if (!Authenticate(request, response, NexScopes.DiscoverySubmit, out NexPrincipal principal, out UserAccount account)) + return; + + try + { + NexDestinationRecord input = ReadBody(request); + input.State = NexDiscoveryPublicationState.Submitted; + if (account != null) + input.SubmittedBy = account.PrincipalID.Guid; + + NexDestinationRecord saved = m_Store.UpsertDestination(input); + Audit(principal, "discovery.destination.submitted", "destination:" + saved.DestinationId, response); + WriteJson(response, new + { + destination = DestinationPayload(saved), + correlation_id = Correlation(response) + }, HttpStatusCode.Created); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + + MethodNotAllowed(response, "GET or POST"); + return; + } + + string moderationMarker = "/moderation"; + if (path.EndsWith(moderationMarker, StringComparison.OrdinalIgnoreCase)) + { + string idPath = path.Substring(0, path.Length - moderationMarker.Length); + if (TryResourceId(idPath, "/api/v1/destinations/", out Guid destinationId)) + { + if (!RequireMethod(request, response, "POST")) + return; + if (!Authenticate(request, response, NexScopes.DiscoveryManage, out NexPrincipal principal, out _)) + return; + + try + { + using JsonDocument document = JsonDocument.Parse(request.InputStream); + JsonElement root = document.RootElement; + string stateText = StringProperty(root, "state"); + if (!Enum.TryParse(stateText, true, out NexDiscoveryPublicationState state)) + throw new ArgumentException("state must be approved or rejected."); + + NexDestinationRecord saved = + m_Store.ModerateDestination( + destinationId, + state, + principal.Subject, + StringProperty(root, "note")); + + Audit(principal, "discovery.destination.moderated", "destination:" + destinationId, response); + WriteJson(response, new + { + destination = DestinationPayload(saved), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + } + + string visitMarker = "/visit"; + if (path.EndsWith(visitMarker, StringComparison.OrdinalIgnoreCase)) + { + string idPath = path.Substring(0, path.Length - visitMarker.Length); + if (TryResourceId(idPath, "/api/v1/destinations/", out Guid destinationId)) + { + if (!RequireMethod(request, response, "POST")) + return; + + try + { + NexDestinationRecord saved = m_Store.RecordDestinationVisit(destinationId); + WriteJson(response, new + { + popularity = saved.Popularity, + teleport_uri = DestinationTeleport(saved), + correlation_id = Correlation(response) + }); + } + catch (Exception e) + { + WriteFailure(response, e); + } + return; + } + } + + if (TryResourceId(path, "/api/v1/destinations/", out Guid resourceId)) + { + if (method.Equals("GET", StringComparison.OrdinalIgnoreCase)) + { + NexDestinationRecord destination = m_Store.GetDestination(resourceId); + if (destination == null || + destination.State != NexDiscoveryPublicationState.Approved) + { + NotFound(response, "destination_not_found", "Destination was not found."); + return; + } + + WriteJson(response, new + { + destination = DestinationPayload(destination), + place = PlacePayload(m_Store.GetPlace(destination.PlaceId)), + events = destination.EventIds + .Select(m_Store.GetEvent) + .Where(x => x != null && x.State == NexDiscoveryPublicationState.Approved) + .ToArray(), + correlation_id = Correlation(response) + }); + return; + } + } + + NotFound(response, "not_found", "Destination endpoint was not found."); + } + + private void AddContentHits( + List hits, + string query, + HashSet types, + NexDiscoveryMaturity? maturity, + int limit) + { + if (Wants(types, "places") || Wants(types, "parcels")) + { + foreach (NexPlaceRecord place in + m_Store.ListPlaces( + query, + maturity, + NexDiscoveryPublicationState.Approved, + 0, + limit)) + { + if (Wants(types, "places")) + { + hits.Add(new + { + type = "places", + id = place.PlaceId, + name = place.Name, + description = place.Description, + region_name = place.RegionName, + maturity = place.Maturity.ToString().ToLowerInvariant(), + traffic = place.Traffic, + tags = place.Tags, + teleport_uri = ResolveTeleport(place) + }); + } + + if (Wants(types, "parcels") && place.ParcelId != Guid.Empty) + { + hits.Add(new + { + type = "parcels", + id = place.ParcelId, + place_id = place.PlaceId, + name = place.Name, + region_name = place.RegionName, + parcel_local_id = place.ParcelLocalId, + details = place.ParcelDetails, + teleport_uri = ResolveTeleport(place) + }); + } + } + } + + if (Wants(types, "events")) + { + foreach (NexEventRecord item in m_Store.ListEvents( + query, maturity, NexDiscoveryPublicationState.Approved, 0, limit)) + { + hits.Add(new + { + type = "events", + id = item.EventId, + name = item.Name, + description = item.Description, + starts_at = item.StartsAt, + ends_at = item.EndsAt, + place_id = item.PlaceId, + maturity = item.Maturity.ToString().ToLowerInvariant() + }); + } + } + + if (Wants(types, "classifieds")) + { + foreach (NexClassifiedRecord item in m_Store.ListClassifieds( + query, maturity, NexDiscoveryPublicationState.Approved, 0, limit)) + { + hits.Add(new + { + type = "classifieds", + id = item.ClassifiedId, + name = item.Name, + description = item.Description, + category = item.Category, + place_id = item.PlaceId + }); + } + } + + if (Wants(types, "destinations")) + { + foreach (NexDestinationRecord item in m_Store.ListDestinations( + query, maturity, NexDiscoveryPublicationState.Approved, + string.Empty, string.Empty, null, null, string.Empty, 0, limit)) + { + hits.Add(new + { + type = "destinations", + id = item.DestinationId, + name = item.Name, + description = item.Description, + category = item.Category, + subcategory = item.Subcategory, + featured = item.Featured, + editor_pick = item.EditorPick, + popularity = item.Popularity, + teleport_uri = DestinationTeleport(item) + }); + } + } + } + + private void AddLandHits( + List hits, + string query, + HashSet types, + NexDiscoveryMaturity? maturity, + int limit) + { + bool sale = Wants(types, "land_for_sale"); + bool rent = Wants(types, "land_for_rent"); + if (!sale && !rent) + return; + + NexEconomyService economy = m_Economy(); + if (economy == null) + return; + + foreach (NexLandListing listing in + economy.SearchLandListings(query, null, 0, limit * 2) + .Where(x => x.Active)) + { + if (listing.ListingType == NexLandListingType.Sale && !sale) + continue; + if (listing.ListingType == NexLandListingType.Rental && !rent) + continue; + + NexPlaceRecord place = FindPlace(listing); + if (maturity.HasValue && place != null && place.Maturity > maturity.Value) + continue; + + hits.Add(LandPayload(listing, place)); + } + } + + private object LandPayload(NexLandListing listing, NexPlaceRecord place) => + new + { + type = listing.ListingType == NexLandListingType.Sale + ? "land_for_sale" + : "land_for_rent", + listing_id = listing.ListingId, + region_id = listing.RegionId, + region_name = listing.RegionName, + parcel_id = listing.ParcelId, + parcel_local_id = listing.ParcelLocalId, + parcel_name = listing.ParcelName, + seller_account_id = listing.SellerAccountId, + estate_id = listing.EstateId, + area = listing.Area, + price = listing.PriceMinor, + currency = NexLedgerCurrency.Code, + rental_period_days = listing.RentalPeriodDays, + active = listing.Active, + created_at = listing.CreatedAt, + place_id = place?.PlaceId ?? Guid.Empty, + maturity = place?.Maturity.ToString().ToLowerInvariant() ?? string.Empty, + land_use = place?.LandUse.ToString().ToLowerInvariant() ?? string.Empty, + region_type = place?.RegionType ?? string.Empty, + featured = place?.Featured ?? false, + map_location = place == null + ? null + : new { x = place.X, y = place.Y, z = place.Z }, + teleport_uri = place == null + ? BuildTeleport(listing.RegionName, 128, 128, 25) + : ResolveTeleport(place) + }; + + private NexPlaceRecord FindPlace(NexLandListing listing) => + m_Store.ListPlaces( + string.Empty, + null, + null, + 0, + 500) + .FirstOrDefault(x => + (x.ParcelId != Guid.Empty && x.ParcelId == listing.ParcelId) || + (x.RegionId == listing.RegionId && + x.ParcelLocalId > 0 && + x.ParcelLocalId == listing.ParcelLocalId)); + + private object PlacePayload(NexPlaceRecord place) + { + if (place == null) + return null; + + return new + { + place_id = place.PlaceId, + region_id = place.RegionId, + region_name = place.RegionName, + parcel_id = place.ParcelId, + parcel_local_id = place.ParcelLocalId, + name = place.Name, + description = place.Description, + maturity = place.Maturity.ToString().ToLowerInvariant(), + images = place.Images, + owner_id = place.OwnerId, + coordinates = new { x = place.X, y = place.Y, z = place.Z }, + teleport_uri = ResolveTeleport(place), + parcel_details = place.ParcelDetails, + traffic = place.Traffic, + tags = place.Tags, + events = place.EventIds, + related_destinations = place.RelatedDestinationIds, + land_use = place.LandUse.ToString().ToLowerInvariant(), + region_type = place.RegionType, + featured = place.Featured, + state = place.State.ToString().ToLowerInvariant(), + created_at = place.CreatedAt, + updated_at = place.UpdatedAt + }; + } + + private object DestinationPayload(NexDestinationRecord destination) + { + if (destination == null) + return null; + + return new + { + destination_id = destination.DestinationId, + place_id = destination.PlaceId, + submitted_by = destination.SubmittedBy, + name = destination.Name, + description = destination.Description, + category = destination.Category, + subcategory = destination.Subcategory, + collection = destination.Collection, + image = destination.Image, + maturity = destination.Maturity.ToString().ToLowerInvariant(), + featured = destination.Featured, + editor_pick = destination.EditorPick, + popularity = destination.Popularity, + tags = destination.Tags, + events = destination.EventIds, + state = destination.State.ToString().ToLowerInvariant(), + moderation_note = destination.ModerationNote, + teleport_uri = DestinationTeleport(destination), + created_at = destination.CreatedAt, + updated_at = destination.UpdatedAt + }; + } + + private string DestinationTeleport(NexDestinationRecord destination) + { + NexPlaceRecord place = m_Store.GetPlace(destination.PlaceId); + return place == null ? string.Empty : ResolveTeleport(place); + } + + private string ResolveTeleport(NexPlaceRecord place) => + !string.IsNullOrWhiteSpace(place.TeleportUri) + ? place.TeleportUri + : BuildTeleport(place.RegionName, place.X, place.Y, place.Z); + + private string BuildTeleport(string regionName, int x, int y, int z) + { + if (string.IsNullOrWhiteSpace(m_TeleportBaseUri) || + string.IsNullOrWhiteSpace(regionName)) + { + return string.Empty; + } + + return m_TeleportBaseUri + + "/" + Uri.EscapeDataString(regionName.Trim()) + + "/" + x + + "/" + y + + "/" + z; + } + + private static NexDiscoveryMaturity RegionMaturity(GridRegion region) + { + int raw = region?.Maturity ?? 0; + if (raw >= 2) + return NexDiscoveryMaturity.Adult; + if (raw == 1) + return NexDiscoveryMaturity.Moderate; + return NexDiscoveryMaturity.General; + } + + private static bool AllowsMaturity( + NexDiscoveryMaturity? maximum, + NexDiscoveryMaturity actual) => + !maximum.HasValue || actual <= maximum.Value; + + private bool Authenticate( + IOSHttpRequest request, + IOSHttpResponse response, + string scope, + out NexPrincipal principal, + out UserAccount account) + { + if (m_Authenticator.TryAuthenticate( + request, + scope, + out principal, + out account, + out int statusCode, + out string error)) + { + return true; + } + + response.AddHeader("WWW-Authenticate", "Bearer"); + WriteError(response, (HttpStatusCode)statusCode, error, "Authentication or " + scope + " authorization is required."); + return false; + } + + private void Audit( + NexPrincipal principal, + string action, + string resource, + IOSHttpResponse response) + { + m_Audit.Record(new NexAuditEvent( + principal?.Subject ?? "unknown", + action, + resource, + Correlation(response), + new Dictionary())); + } + + private static T ReadBody(IOSHttpRequest request) + { + T value = + JsonSerializer.Deserialize( + request.InputStream, + s_Json); + + if (value == null) + throw new ArgumentException("A valid JSON body is required."); + + return value; + } + + private static string StringProperty(JsonElement root, string name) + { + if (!root.TryGetProperty(name, out JsonElement value) || + value.ValueKind != JsonValueKind.String) + { + return string.Empty; + } + return (value.GetString() ?? string.Empty).Trim(); + } + + private static string Query(IOSHttpRequest request, string key) => + (request?.QueryString?[key] ?? string.Empty).Trim(); + + private static int QueryInt( + IOSHttpRequest request, + string key, + int defaultValue, + int min, + int max) + { + string raw = Query(request, key); + if (raw.Length == 0) + return defaultValue; + if (!int.TryParse(raw, out int value) || value < min || value > max) + throw new ArgumentException(key + " is outside the allowed range."); + return value; + } + + private static long QueryLong( + IOSHttpRequest request, + string key, + long defaultValue, + long min, + long max) + { + string raw = Query(request, key); + if (raw.Length == 0) + return defaultValue; + if (!long.TryParse(raw, out long value) || value < min || value > max) + throw new ArgumentException(key + " is outside the allowed range."); + return value; + } + + private static Guid QueryGuid(IOSHttpRequest request, string key) + { + if (!Guid.TryParse(Query(request, key), out Guid value) || + value == Guid.Empty) + { + throw new ArgumentException(key + " must be a non-zero UUID."); + } + return value; + } + + private static bool? QueryNullableBool(IOSHttpRequest request, string key) + { + string raw = Query(request, key); + if (raw.Length == 0) + return null; + if (!bool.TryParse(raw, out bool value)) + throw new ArgumentException(key + " must be boolean."); + return value; + } + + private static NexDiscoveryMaturity? ParseOptionalMaturity(string raw) + { + if (string.IsNullOrWhiteSpace(raw)) + return null; + if (!Enum.TryParse(raw, true, out NexDiscoveryMaturity value)) + throw new ArgumentException("maturity must be general, moderate or adult."); + return value; + } + + private static NexLandListingType? ParseLandListingType(string raw) + { + if (string.IsNullOrWhiteSpace(raw) || + raw.Equals("all", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + if (raw.Equals("sale", StringComparison.OrdinalIgnoreCase)) + return NexLandListingType.Sale; + if (raw.Equals("rental", StringComparison.OrdinalIgnoreCase) || + raw.Equals("rent", StringComparison.OrdinalIgnoreCase)) + return NexLandListingType.Rental; + + throw new ArgumentException("type must be sale, rental or all."); + } + + private static HashSet ParseTypes(string raw) + { + return new HashSet( + (raw ?? string.Empty) + .Split(',', StringSplitOptions.RemoveEmptyEntries) + .Select(x => x.Trim().ToLowerInvariant()) + .Where(x => x.Length > 0), + StringComparer.OrdinalIgnoreCase); + } + + private static bool Wants(HashSet types, string value) => + types == null || + types.Count == 0 || + types.Contains("all") || + types.Contains(value); + + private static bool TryResourceId( + string path, + string prefix, + out Guid id) + { + id = Guid.Empty; + if (!path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + return false; + + string tail = path.Substring(prefix.Length); + return !tail.Contains('/') && + Guid.TryParse(tail, out id) && + id != Guid.Empty; + } + + private static bool RequireMethod( + IOSHttpRequest request, + IOSHttpResponse response, + string expected) + { + if (string.Equals(request?.HttpMethod, expected, StringComparison.OrdinalIgnoreCase)) + return true; + + MethodNotAllowed(response, expected); + return false; + } + + private static string Correlation(IOSHttpResponse response) => + NexApiRequestContext.Ensure(response); + + private static void WriteFailure(IOSHttpResponse response, Exception exception) + { + if (exception is KeyNotFoundException) + { + NotFound(response, "discovery_not_found", exception.Message); + return; + } + + if (exception is UnauthorizedAccessException) + { + WriteError(response, HttpStatusCode.Forbidden, "discovery_forbidden", exception.Message); + return; + } + + if (exception is ArgumentException || + exception is InvalidOperationException) + { + WriteError(response, HttpStatusCode.BadRequest, "discovery_validation_failed", exception.Message); + return; + } + + WriteError(response, HttpStatusCode.InternalServerError, "discovery_internal_error", "The discovery operation failed."); + } + + private static void MethodNotAllowed(IOSHttpResponse response, string expected) => + WriteError(response, HttpStatusCode.MethodNotAllowed, "method_not_allowed", expected + " is required."); + + private static void NotFound( + IOSHttpResponse response, + string error, + string message) => + WriteError(response, HttpStatusCode.NotFound, error, message); + + private static void WriteError( + IOSHttpResponse response, + HttpStatusCode status, + string error, + string message) => + WriteJson(response, new + { + error, + message, + correlation_id = Correlation(response) + }, status); + + private static void WriteJson( + IOSHttpResponse response, + object payload, + HttpStatusCode status = HttpStatusCode.OK) + { + response.KeepAlive = false; + response.StatusCode = (int)status; + response.ContentType = "application/json; charset=utf-8"; + response.RawBuffer = JsonSerializer.SerializeToUtf8Bytes(payload, s_Json); + } + + private static JsonSerializerOptions CreateJsonOptions() + { + JsonSerializerOptions options = new JsonSerializerOptions + { + WriteIndented = true, + PropertyNameCaseInsensitive = true, + PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower + }; + options.Converters.Add(new JsonStringEnumConverter(JsonNamingPolicy.CamelCase)); + return options; + } + } +} diff --git a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs index 95508aa1..6f5a335d 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiConnector.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiConnector.cs @@ -8,6 +8,7 @@ using NexVerse.Core.Audit; using NexVerse.Core.ControlPlane; using NexVerse.Core.Economy; using NexVerse.Core.Experiences; +using NexVerse.Core.Discovery; using NexVerse.Core.Messaging; using NexVerse.Core.Jobs; using NexVerse.Core.Observability; @@ -447,9 +448,11 @@ namespace NexVerse.Server.Api IConfig nexGroupsConfig = config.Configs["NexGroups"]; + GroupsService nexGroupsService = null; + if (nexGroupsConfig?.GetBoolean("Enabled", false) == true) { - GroupsService nexGroupsService = + nexGroupsService = new GroupsService( config); @@ -498,6 +501,82 @@ namespace NexVerse.Server.Api "OpenGenesisLINK NexExperiences API"), true); + IConfig discoveryConfig = + config.Configs["NexDiscovery"]; + + string discoveryStorePath = + discoveryConfig?.GetString( + "StorePath", + "data/opengenesislink-discovery.json") ?? + "data/opengenesislink-discovery.json"; + + string teleportBaseUri = + discoveryConfig?.GetString( + "TeleportBaseUri", + string.Empty) ?? + string.Empty; + + NexDiscoveryStore discoveryStore = + new NexDiscoveryStore( + discoveryStorePath); + + NexDiscoveryApi discoveryApi = + new NexDiscoveryApi( + authenticator, + userAccounts, + grid, + nexGroupsService, + experienceStore, + discoveryStore, + () => + NexEconomyConnector.Current?.Enabled == true + ? NexEconomyConnector.Current.Economy + : null, + auditSink, + teleportBaseUri); + + server.AddSimpleStreamHandler( + new SimpleStreamHandler( + "/api/v1/search", + apiGate.Wrap(discoveryApi.HandleSearch), + "OpenGenesisLINK NexSearch API"), + true); + + server.AddSimpleStreamHandler( + new SimpleStreamHandler( + "/api/v1/places", + apiGate.Wrap(discoveryApi.HandlePlaces), + "OpenGenesisLINK Places API"), + true); + + server.AddSimpleStreamHandler( + new SimpleStreamHandler( + "/api/v1/events", + apiGate.Wrap(discoveryApi.HandleContent), + "OpenGenesisLINK Discovery Events API"), + true); + + server.AddSimpleStreamHandler( + new SimpleStreamHandler( + "/api/v1/classifieds", + apiGate.Wrap(discoveryApi.HandleContent), + "OpenGenesisLINK Classifieds API"), + true); + + server.AddSimpleStreamHandler( + new SimpleStreamHandler( + "/api/v1/land-portal", + apiGate.Wrap(discoveryApi.HandleLandPortal), + "OpenGenesisLINK Land Portal API"), + true); + + server.AddSimpleStreamHandler( + new SimpleStreamHandler( + "/api/v1/destinations", + apiGate.Wrap(discoveryApi.HandleDestinations), + "OpenGenesisLINK Destination Guide API"), + true); + NexInventoryApi inventoryApi = new NexInventoryApi( inventory, diff --git a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs index 80b9f6d5..fb5d74d5 100644 --- a/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs +++ b/NexVerse/Server/Api/NexVerseWorldApiHandlers.cs @@ -190,6 +190,41 @@ namespace NexVerse.Server.Api ("post", "NV$-Konto sperren, freigeben oder schließen", "admin:*", "200")), ["/api/v1/economy/accounts/ensure"] = AuthenticatedOperations( ("post", "Vertrauenswürdiges Gruppen-, Business-, Estate- oder Objekt-Wallet provisionieren", "economy:transfer (service/admin)", "200")), + ["/api/v1/search"] = GetOperation( + "NexSearch über Personen, Gruppen, Regionen, Parcels, Places, Events, Land, Classifieds, Experiences und Destinations"), + ["/api/v1/places"] = MergeOperations( + GetOperation("Veröffentlichte Places durchsuchen"), + AuthenticatedOperations( + ("post", "Place anlegen oder aktualisieren", "discovery:manage", "201"))), + ["/api/v1/places/{placeId}"] = MergeOperations( + GetOperation("Veröffentlichtes Place-Profil lesen"), + AuthenticatedOperations( + ("put", "Place aktualisieren", "discovery:manage", "200"), + ("delete", "Place und abhängige Discovery-Einträge löschen", "discovery:manage", "200"))), + ["/api/v1/events"] = MergeOperations( + GetOperation("Veröffentlichte Discovery-Events durchsuchen"), + AuthenticatedOperations( + ("post", "Discovery-Event anlegen oder aktualisieren", "discovery:manage", "201"))), + ["/api/v1/classifieds"] = MergeOperations( + GetOperation("Veröffentlichte Classifieds durchsuchen"), + AuthenticatedOperations( + ("post", "Classified anlegen oder aktualisieren", "discovery:manage", "201"))), + ["/api/v1/land-portal"] = GetOperation( + "Aktive NV$-Landangebote als Landportal durchsuchen"), + ["/api/v1/land-portal/owned"] = AuthenticatedOperations( + ("get", "Eigene oder autorisierte Landangebote lesen", "discovery:read", "200")), + ["/api/v1/destinations"] = MergeOperations( + GetOperation("Freigegebene Destination-Guide-Einträge durchsuchen"), + AuthenticatedOperations( + ("post", "Destination zur Moderation einreichen", "discovery:submit", "201"))), + ["/api/v1/destinations/categories"] = GetOperation( + "Destination-Guide-Kategorien und Unterkategorien lesen"), + ["/api/v1/destinations/{destinationId}"] = GetOperation( + "Freigegebene Destination mit Place- und Event-Bezug lesen"), + ["/api/v1/destinations/{destinationId}/visit"] = PublicOperations( + ("post", "Destination-Aufruf für Popularitätsranking registrieren", "200")), + ["/api/v1/destinations/{destinationId}/moderation"] = AuthenticatedOperations( + ("post", "Destination freigeben oder ablehnen", "discovery:manage", "200")), ["/api/v1/groups"] = AuthenticatedOperations( ("get", "NexGroups durchsuchen", "groups:read", "200"), ("post", "NexGroup erstellen", "groups:manage", "201")), @@ -487,6 +522,23 @@ namespace NexVerse.Server.Api "EconomyAccountStateResponse", "200"); ApplyJsonContract(paths, "/api/v1/economy/accounts/ensure", "post", "EconomyWalletEnsureRequest", "EconomyBalanceResponse", "200"); + ApplyJsonContract(paths, "/api/v1/search", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/places", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/places", "post", "DiscoveryPlaceRequest", "DiscoveryObjectResponse", "201"); + ApplyJsonContract(paths, "/api/v1/places/{placeId}", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/places/{placeId}", "put", "DiscoveryPlaceRequest", "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/events", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/events", "post", "DiscoveryMutationRequest", "DiscoveryObjectResponse", "201"); + ApplyJsonContract(paths, "/api/v1/classifieds", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/classifieds", "post", "DiscoveryMutationRequest", "DiscoveryObjectResponse", "201"); + ApplyJsonContract(paths, "/api/v1/land-portal", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/land-portal/owned", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/destinations", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/destinations", "post", "DiscoveryDestinationRequest", "DiscoveryObjectResponse", "201"); + ApplyJsonContract(paths, "/api/v1/destinations/categories", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/destinations/{destinationId}", "get", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/destinations/{destinationId}/visit", "post", null, "DiscoveryObjectResponse", "200"); + ApplyJsonContract(paths, "/api/v1/destinations/{destinationId}/moderation", "post", "DiscoveryModerationRequest", "DiscoveryObjectResponse", "200"); ApplyJsonContract(paths, "/api/v1/groups", "get", null, "Chapter11ObjectResponse", "200"); ApplyJsonContract(paths, "/api/v1/groups", "post", "NexGroupCreateRequest", "Chapter11ObjectResponse", "201"); ApplyJsonContract(paths, "/api/v1/groups/{groupId}", "get", null, "Chapter11ObjectResponse", "200"); @@ -1210,10 +1262,25 @@ namespace NexVerse.Server.Api new { api_version = NexVersePlatform.ApiVersion, - server_line = "0.9.3.7", + server_line = "0.9.3.8", codename = NexVersePlatform.MilestoneCodename, status = "development", published = "2026-10-06", + compatibility = "OpenGenesisLINK v0.9.3.8 Dev — NexSearch, Places, Land Portal und Destination Guide", + highlights = new[] + { + "NexSearch aggregiert People, Groups, Regions, Parcels, Places, Events, Land, Classifieds, Experiences und Destinations", + "Places und Destination Guide mit persistenter Moderation, Kategorien, Collections, Events, Popularitaet und Teleport-Links", + "Land Portal projiziert die autoritative NV$-Land-Commerce-Datenbasis; optionale Viewer-CAPS ergaenzen Firestorm ohne Legacy-Suche zu ersetzen" + } + }, + new + { + api_version = NexVersePlatform.ApiVersion, + server_line = "0.9.3.7", + codename = NexVersePlatform.MilestoneCodename, + status = "completed", + published = "2026-10-06", compatibility = "OpenGenesisLINK v0.9.3.7 Dev — NexGroups, NexExperiences und Experience LSL", highlights = new[] { @@ -1627,7 +1694,7 @@ namespace NexVerse.Server.Api }, new { version = "0.9.3.6", codename = "", title = "NV$-Wirtschaft, Bankwesen, Handel und Land", status = "completed", checklist = (object)null, summary = "Natives Kontobuch, Bankwesen, Viewer-Wirtschaftskompatibilität und Landhandel abgeschlossen.", evidence = new[] { "Doppelte Buchfuehrung und persistente Konten", "NVBAN/Banking/Commerce/Landhandel", "Live-MariaDB/PostgreSQL- und Runtime-CI gruen" } }, new { version = "0.9.3.7", codename = "", title = "NexGroups und NexExperiences", status = "completed", checklist = (object)null, summary = "NexGroups-Paritaetsschicht, native NexExperiences und Experience-LSL abgeschlossen.", evidence = new[] { "NexGroups Management/Moderation/API plus NV$-Gruppenkonto", "Native Experience-Permissions, Policies, Script-Bindings und persistentes K/V", "Release-Build, Hypergrid, LLLogin, World API und Chapter-11-CI gruen" } }, - new { version = "0.9.3.8", codename = "", title = "Suche, Orte, Land und Reiseführer", status = "planned", checklist = (object)null, summary = "Suche, Orte, Landportal und Dienste zur Zielentdeckung.", evidence = Array.Empty() }, + new { version = "0.9.3.8", codename = "", title = "Suche, Orte, Land und Reiseführer", status = "completed", checklist = (object)null, summary = "NexSearch, Places, Land Portal und Destination Guide einschließlich optionaler Viewer-CAPS abgeschlossen.", evidence = new[] { "NexSearch aggregiert autoritative People-, Groups-, Grid-, Experience- und NV$-Landdaten", "Persistente Places, Events, Classifieds und moderierte Destinationen", "NexSearch/NexPlaces/NexLandPortal/NexDestinationGuide Viewer-CAPS sowie CI-Persistenz- und Moderationsregression" } }, new { version = "0.9.3.9", codename = "", title = "NexVoice", status = "planned", checklist = (object)null, summary = "WebRTC-/Janus-Sprachplattform als Ersatz für entfernte Legacy-Sprachsysteme.", evidence = Array.Empty() }, new { version = "0.9.3.10", codename = "", title = "Wegfindung", status = "planned", checklist = (object)null, summary = "Wegfindungsdienst, NavMesh-Verhalten und LSL-Integration.", evidence = Array.Empty() }, new { version = "0.9.3.11", codename = "", title = "LSL-Parität I — Kernkonformität", status = "planned", checklist = (object)null, summary = "Maschinenlesbare LSL-Matrix, Konformitätstests und Härtung der Script-Sandbox.", evidence = Array.Empty() }, @@ -1915,6 +1982,60 @@ namespace NexVerse.Server.Api }; } + private static object PublicOperations( + params (string method, string summary, string successCode)[] operations) + { + Dictionary result = + new Dictionary(); + + foreach ((string method, string summary, string successCode) operationSpec in operations) + { + result[operationSpec.method] = + new Dictionary + { + ["summary"] = operationSpec.summary, + ["security"] = Array.Empty(), + ["responses"] = new Dictionary + { + [operationSpec.successCode] = new { description = "Erfolgreiche Antwort" }, + ["400"] = JsonResponse("Ungültige Anfrage", "Error"), + ["404"] = JsonResponse("Ressource nicht gefunden", "Error"), + ["429"] = JsonResponse("Rate-Limit überschritten", "Error") + }, + ["x-nexverse-audience"] = new[] { "citizen", "admin", "service" }, + ["x-nexverse-purpose"] = operationSpec.summary, + ["x-nexverse-ai-instruction"] = + "Öffentliche Discovery-Operation. Keine zusätzlichen Rechte aus der Lesbarkeit oder Aufrufbarkeit ableiten.", + ["x-nexverse-security-constraints"] = + new[] + { + "Keine Zugangsdaten senden, sofern die Operation sie nicht ausdrücklich erfordert.", + "Rate-Limits und Korrelations-IDs beachten." + } + }; + } + + return result; + } + + private static object MergeOperations( + params object[] operationGroups) + { + Dictionary result = + new Dictionary(); + + foreach (object group in operationGroups) + { + if (group is Dictionary operations) + { + foreach (KeyValuePair pair in operations) + result[pair.Key] = pair.Value; + } + } + + return result; + } + private static object AuthenticatedOperations( params (string method, string summary, string scope, string successCode)[] operations) { @@ -2411,6 +2532,66 @@ namespace NexVerse.Server.Api ["correlation_id"] = new { type = "string" } } }, + ["DiscoveryObjectResponse"] = new + { + type = "object" + }, + ["DiscoveryMutationRequest"] = new + { + type = "object", + additionalProperties = true + }, + ["DiscoveryPlaceRequest"] = new + { + type = "object", + required = new[] { "region_id", "name" }, + properties = new Dictionary + { + ["place_id"] = new { type = "string", format = "uuid" }, + ["region_id"] = new { type = "string", format = "uuid" }, + ["region_name"] = new { type = "string", maxLength = 255 }, + ["parcel_id"] = new { type = "string", format = "uuid" }, + ["parcel_local_id"] = new { type = "integer", minimum = 0 }, + ["name"] = new { type = "string", minLength = 1, maxLength = 255 }, + ["description"] = new { type = "string", maxLength = 8192 }, + ["maturity"] = new { type = "string", @enum = new[] { "general", "moderate", "adult" } }, + ["owner_id"] = new { type = "string", format = "uuid" }, + ["teleport_uri"] = new { type = "string", maxLength = 2048 }, + ["traffic"] = new { type = "number", minimum = 0 }, + ["land_use"] = new { type = "string", @enum = new[] { "other", "residential", "commercial", "mixed" } }, + ["region_type"] = new { type = "string", maxLength = 128 }, + ["featured"] = new { type = "boolean" }, + ["state"] = new { type = "string", @enum = new[] { "draft", "submitted", "approved", "rejected" } } + } + }, + ["DiscoveryDestinationRequest"] = new + { + type = "object", + required = new[] { "place_id", "name" }, + properties = new Dictionary + { + ["destination_id"] = new { type = "string", format = "uuid" }, + ["place_id"] = new { type = "string", format = "uuid" }, + ["name"] = new { type = "string", minLength = 1, maxLength = 255 }, + ["description"] = new { type = "string", maxLength = 8192 }, + ["category"] = new { type = "string", maxLength = 128 }, + ["subcategory"] = new { type = "string", maxLength = 128 }, + ["collection"] = new { type = "string", maxLength = 128 }, + ["maturity"] = new { type = "string", @enum = new[] { "general", "moderate", "adult" } }, + ["featured"] = new { type = "boolean" }, + ["editor_pick"] = new { type = "boolean" } + } + }, + ["DiscoveryModerationRequest"] = new + { + type = "object", + required = new[] { "state" }, + properties = new Dictionary + { + ["state"] = new { type = "string", @enum = new[] { "approved", "rejected" } }, + ["note"] = new { type = "string", maxLength = 2048 } + } + }, ["Chapter11ObjectResponse"] = new { type = "object" diff --git a/OpenSim/Framework/VersionInfo.cs b/OpenSim/Framework/VersionInfo.cs index c67cb392..77cfadce 100644 --- a/OpenSim/Framework/VersionInfo.cs +++ b/OpenSim/Framework/VersionInfo.cs @@ -31,8 +31,8 @@ namespace OpenSim { // NexVerse maintains its own version line from the OpenSimulator 0.9.3.0 baseline. public const string ProductName = "OpenGenesisLINK"; - public const string VersionNumber = "0.9.3.7"; - public const string AssemblyVersionNumber = "0.9.3.7"; + public const string VersionNumber = "0.9.3.8"; + public const string AssemblyVersionNumber = "0.9.3.8"; public const Flavour VERSION_FLAVOUR = Flavour.Dev; diff --git a/README.md b/README.md index 072eaa10..1b0f3110 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # OpenGenesisLINK -**OpenGenesisLINK v0.9.3.7 Dev** is an independent virtual-world server platform developed by the OpenGenesisLINK project. +**OpenGenesisLINK v0.9.3.8 Dev** is an independent virtual-world server platform developed by the OpenGenesisLINK project. This repository starts from the published **OpenSimulator 0.9.3.0 ("Nessie") Release** source package. It is intentionally maintained as its own repository rather than as a GitHub fork. The long-term objective is an independent OpenGenesisLINK development line whose architecture, services, protocols, modules, tooling and branding may diverge substantially from OpenSimulator. @@ -21,7 +21,7 @@ Imported OpenSimulator files do **not** lose or replace their existing BSD/third ## Versioning -The active development version is **OpenGenesisLINK v0.9.3.7 Dev**. +The active development version is **OpenGenesisLINK v0.9.3.8 Dev**. OpenGenesisLINK continues the existing 0.9.3.x development line. OpenSimulator 0.9.3.0 remains the historical source baseline; upstream OpenSimulator version numbers do not automatically become OpenGenesisLINK version numbers. diff --git a/VERSIONING.md b/VERSIONING.md index 6fd0de50..c718db2a 100644 --- a/VERSIONING.md +++ b/VERSIONING.md @@ -1,8 +1,8 @@ # OpenGenesisLINK versioning Current stable release: **NexVerse 0.9.3.4** -Active development line: **OpenGenesisLINK v0.9.3.7 Dev** -Active milestone: **NexGroups and NexExperiences — Chapter 11 completed** +Active development line: **OpenGenesisLINK v0.9.3.8 Dev** +Active milestone: **Search, Places, Land and Destination Guide — Chapter 12 completed** Next architectural consolidation line: **OpenGenesisLINK v0.9.4.0** Completed milestone codename: **NEXJAST** @@ -30,7 +30,8 @@ OpenGenesisLINK continues from the OpenSimulator 0.9.3.0 source baseline and the - `NexVerse 0.9.3.4` — completed stable release for Simulator, Region and Estate Control Plane. - `OpenGenesisLINK v0.9.3.5 Dev` — completed development line for Inventory, OAR/IAR, persistent Job Engine and NexBus. - `OpenGenesisLINK v0.9.3.6 Dev` — completed development line for NV$ economy, banking, commerce and land flows. -- `OpenGenesisLINK v0.9.3.7 Dev` — current development line; NexGroups parity layer and native NexExperiences/Experience LSL are implemented and validated on `main`. +- `OpenGenesisLINK v0.9.3.7 Dev` — completed development line for NexGroups parity, native NexExperiences and Experience LSL. +- `OpenGenesisLINK v0.9.3.8 Dev` — current development line; NexSearch, Places, Land Portal and Destination Guide are implemented with optional viewer discovery capabilities. - `OpenGenesisLINK v0.9.3.5 RC1+` — future release-candidate phase after the 0.9.3.5 definition of done is satisfied. - `OpenGenesisLINK v0.9.3.5` — next stable release after validation of the active milestone. - `OpenGenesisLINK v0.9.4.0` — Generation 1 consolidation line for broader OGL branding, German administration surfaces and the native addon subsystem. diff --git a/bin/OpenSim.ini.example b/bin/OpenSim.ini.example index 5855b8ed..91e3626c 100644 --- a/bin/OpenSim.ini.example +++ b/bin/OpenSim.ini.example @@ -974,6 +974,13 @@ ;; Money Unit fee to create groups. Default is 0. ; PriceGroupCreate = 0 +[NexDiscoveryViewer] + ; Optional viewer-facing capabilities for OpenGenesisLINK-aware viewers. + ; Standard Firestorm/SL-compatible search remains untouched. + Enabled = false + WorldApiBaseUrl = "http://127.0.0.1:8002" + RequestTimeoutMilliseconds = 3000 + [NexExperiencesViewer] ; Central OpenGenesisLINK Experience adapter. ; Experience permissions and K/V state remain authoritative in Robust. diff --git a/bin/Robust.HG.ini.example b/bin/Robust.HG.ini.example index 670e3e43..73115d21 100644 --- a/bin/Robust.HG.ini.example +++ b/bin/Robust.HG.ini.example @@ -276,6 +276,16 @@ ; This file is server-owned and must be writable by the Robust process. StorePath = "data/nexverse-experiences.json" +[NexDiscovery] + ; Native OpenGenesisLINK discovery authority for Places, Events, + ; Classifieds and Destination Guide curation. + StorePath = "data/opengenesislink-discovery.json" + + ; Optional hop/teleport base used when a Place does not provide an + ; explicit TeleportUri, for example: + ; TeleportBaseUri = "hop://login.mynexverse.de" + TeleportBaseUri = "" + [NexEconomy] ; Native OpenGenesisLINK NV$ double-entry ledger bootstrap. ; Disabled until the durable database backend has been validated for this installation. diff --git a/bin/Robust.ini.example b/bin/Robust.ini.example index 1acbce0b..5b86411b 100644 --- a/bin/Robust.ini.example +++ b/bin/Robust.ini.example @@ -232,6 +232,16 @@ ; This file is server-owned and must be writable by the Robust process. StorePath = "data/nexverse-experiences.json" +[NexDiscovery] + ; Native OpenGenesisLINK discovery authority for Places, Events, + ; Classifieds and Destination Guide curation. + StorePath = "data/opengenesislink-discovery.json" + + ; Optional hop/teleport base used when a Place does not provide an + ; explicit TeleportUri, for example: + ; TeleportBaseUri = "hop://login.mynexverse.de" + TeleportBaseUri = "" + [NexEconomy] ; Native OpenGenesisLINK NV$ double-entry ledger bootstrap. ; Disabled until the durable database backend has been validated for this installation. diff --git a/doc/NexVerse/ROADMAP.md b/doc/NexVerse/ROADMAP.md index a493f8c6..feea0282 100644 --- a/doc/NexVerse/ROADMAP.md +++ b/doc/NexVerse/ROADMAP.md @@ -3,8 +3,8 @@ > Status: Active development roadmap > Current stable release: **NexVerse 0.9.3.4** > Completed release train: **0.9.3.2 → 0.9.3.3 → 0.9.3.4** -> Active development line: **OpenGenesisLINK v0.9.3.7 Dev** -> Active milestone: **0.9.3.7 — NexGroups and NexExperiences completed** +> Active development line: **OpenGenesisLINK v0.9.3.8 Dev** +> Active milestone: **0.9.3.8 — Search, Places, Land and Destination Guide completed** > Completed milestone codename: **NEXJAST** > Historical source baseline: OpenSimulator 0.9.3.0 ("Nessie") @@ -1097,74 +1097,75 @@ Support Firestorm-visible flows including: ## 12. Search, Places, Land and Destination Guide -Create NexVerse-native discovery services used by both web and viewer. +**Status: implemented on the 0.9.3.8 development line.** OpenGenesisLINK now exposes one discovery layer for web clients and optional viewer capabilities while preserving the existing Firestorm-compatible search stack. ### 12.1 NexSearch -Index and search: - -- people; -- groups; -- regions; -- parcels; -- places; -- events; -- land for sale; -- land for rent; -- classifieds; -- experiences; -- destinations. +- [x] people via the authoritative UserAccount service; +- [x] groups via the existing Groups V2/NexGroups authority when enabled; +- [x] regions via the authoritative Grid service; +- [x] parcels projected from published Places; +- [x] Places from the persistent NexDiscovery store; +- [x] Events from the persistent NexDiscovery store; +- [x] land for sale from the existing NV$ land-commerce authority; +- [x] land for rent from the existing NV$ land-commerce authority; +- [x] Classifieds from the persistent NexDiscovery store; +- [x] Experiences from the native NexExperiences authority; +- [x] Destinations from the moderated Destination Guide; +- [x] type, maturity and bounded-result filtering; +- [x] public `GET /api/v1/search` endpoint. ### 12.2 Places -Create web place pages containing: - -- region/place name; -- description; -- maturity; -- images; -- owner; -- coordinates; -- teleport link; -- parcel details; -- traffic; -- tags; -- events; -- related destinations. +- [x] region/place name; +- [x] description; +- [x] maturity; +- [x] image list; +- [x] owner; +- [x] coordinates; +- [x] explicit or generated teleport link; +- [x] parcel UUID/local ID and parcel details; +- [x] traffic; +- [x] tags; +- [x] linked events; +- [x] related destinations; +- [x] land-use and region-type metadata; +- [x] featured state; +- [x] persistent managed CRUD plus public read surface. ### 12.3 Land portal -Provide web/API views similar in purpose to modern virtual-world land marketplaces: - -- owned land; -- land for sale; -- rentals; -- residential; -- commercial; -- featured listings; -- price; -- area; -- maturity; -- region type; -- map location. +- [x] authenticated owned-land view; +- [x] active land-for-sale view; +- [x] active rental view; +- [x] residential/commercial/mixed metadata through Place enrichment; +- [x] featured listings; +- [x] NV$ price; +- [x] area; +- [x] maturity; +- [x] region type; +- [x] map coordinates; +- [x] teleport link; +- [x] reuses `NexEconomyService.SearchLandListings`; no duplicate commerce ledger or listing authority. ### 12.4 Destination Guide -The StadtPortal manages destination content that is also visible in compatible viewers. - -Features: - -- categories; -- subcategories; -- featured destinations; -- editor picks; -- recently added; -- popular/hot; -- events; -- maturity filtering; -- curated collections; -- teleport links; -- submission and moderation workflow. +- [x] categories; +- [x] subcategories; +- [x] featured destinations; +- [x] editor picks; +- [x] recently added sorting; +- [x] popular/hot sorting; +- [x] linked events; +- [x] maturity filtering; +- [x] curated collections; +- [x] teleport links through the linked Place; +- [x] submission workflow; +- [x] approve/reject moderation workflow; +- [x] popularity/visit counter; +- [x] public category and destination APIs; +- [x] optional viewer CAPS: `NexSearch`, `NexPlaces`, `NexLandPortal`, `NexDestinationGuide`; +- [x] standard Firestorm/SL-compatible search behavior remains untouched. --- diff --git a/doc/NexVerse/WORLD_API.md b/doc/NexVerse/WORLD_API.md index 9d31403b..cda56210 100644 --- a/doc/NexVerse/WORLD_API.md +++ b/doc/NexVerse/WORLD_API.md @@ -2,7 +2,7 @@ The NexVerse World API is the Robust-hosted control-plane API for the NexVerse grid deployment running on OpenGenesisLINK. -Active server development line: **OpenGenesisLINK v0.9.3.7 Dev — NexGroups, NexExperiences and Experience LSL** +Active server development line: **OpenGenesisLINK v0.9.3.8 Dev — NexSearch, Places, Land Portal and Destination Guide** World API v1 was completed as the 0.9.3.2 development checkpoint on 3 October 2026 and remains the control-plane API foundation for the active OpenGenesisLINK development line. NexVerse continues as the deployment/grid identity. @@ -721,3 +721,65 @@ Script routes provide Experience resolution/details, resident permission checks, The shared LSL API/YEngine now exposes the Experience permission and persistent-storage surface: `llRequestExperiencePermissions`, `experience_permissions`, `experience_permissions_denied`, `llGetExperienceDetails`, `llAgentInExperience`, CRUD K/V calls, K/V size/count/key enumeration and `llGetExperienceErrorMessage`. Experience permission decisions and K/V data are grid-authoritative through Robust. YEngine reserves event IDs 26 and 27 for the two Experience permission events. + + +## NexDiscovery — Roadmap 12 / OpenGenesisLINK 0.9.3.8 + +OpenGenesisLINK 0.9.3.8 introduces a shared discovery layer for web clients and compatible viewers. Existing Firestorm/Second-Life-compatible search behavior is deliberately preserved; NexDiscovery is an additional native service rather than a destructive replacement. + +### NexSearch + +`GET /api/v1/search` performs bounded cross-domain discovery. Supported result domains are: + +- `people` +- `groups` +- `regions` +- `parcels` +- `places` +- `events` +- `land_for_sale` +- `land_for_rent` +- `classifieds` +- `experiences` +- `destinations` + +NexSearch does not create duplicate authorities. People come from UserAccountService, groups from the configured Groups/NexGroups authority, regions from GridService, Experiences from NexExperiences, and sale/rental listings from the NV$ land-commerce workflow. Places, Discovery Events, Classifieds and Destination Guide curation are persisted in the NexDiscovery store. + +Public search supports query, type and maturity filtering. Result counts are bounded server-side. + +### Places + +`GET /api/v1/places` and `GET /api/v1/places/{placeId}` expose published Place data including region/parcel identity, description, maturity, images, owner, coordinates, teleport URI, parcel details, traffic, tags, linked events, related destinations, land-use metadata, region type and featured state. + +Managed Place mutations use `discovery:manage`. Removing a Place also removes its dependent Destination, Event and Classified discovery records so stale portal entries are not retained. + +When a Place does not define an explicit teleport URI, Robust may build one from `[NexDiscovery] TeleportBaseUri`, region name and local coordinates. + +### Land Portal + +`GET /api/v1/land-portal` projects the existing NV$ land-commerce listings into a discovery-oriented marketplace view. Filters include sale/rental type, query, price range, minimum area, maturity, land use, region type and featured state. + +The Land Portal does not maintain a second land-sale database. Price, seller, listing activity and rental period remain authoritative in `NexEconomyService`; NexDiscovery only enriches those listings with Place metadata such as maturity, residential/commercial classification, region type, map position and teleport link. + +`GET /api/v1/land-portal/owned` requires `discovery:read` and returns listings for the authenticated or otherwise authorized owner account. + +### Destination Guide + +`GET /api/v1/destinations` exposes approved Destination Guide entries. Supported views include featured/editor picks, recently added, popular/hot ordering, categories, subcategories, curated collections, maturity filtering and linked events. + +`GET /api/v1/destinations/categories` projects the public category/subcategory tree. + +Authenticated submissions use `discovery:submit`. Moderation uses `discovery:manage` through `POST /api/v1/destinations/{destinationId}/moderation` with `approved` or `rejected` state. Submitted entries are never returned by the public guide until explicitly approved. + +`POST /api/v1/destinations/{destinationId}/visit` records an approved destination visit for popularity ordering. It does not grant any additional grid permission. + +### Viewer capabilities + +When `[NexDiscoveryViewer] Enabled = true` is configured on a simulator, OpenGenesisLINK advertises four optional capabilities to compatible viewers: + +- `NexSearch` +- `NexPlaces` +- `NexLandPortal` +- `NexDestinationGuide` + +These capabilities proxy only public GET discovery operations to the central World API. They do not expose management scopes, API keys or database access to the simulator/viewer. Standard viewer search remains untouched. diff --git a/tools/ci/NexDiscoveryRegression/NexDiscoveryRegression.csproj b/tools/ci/NexDiscoveryRegression/NexDiscoveryRegression.csproj new file mode 100644 index 00000000..1f83820d --- /dev/null +++ b/tools/ci/NexDiscoveryRegression/NexDiscoveryRegression.csproj @@ -0,0 +1,11 @@ + + + Exe + net8.0 + disable + disable + + + + + diff --git a/tools/ci/NexDiscoveryRegression/Program.cs b/tools/ci/NexDiscoveryRegression/Program.cs new file mode 100644 index 00000000..22483575 --- /dev/null +++ b/tools/ci/NexDiscoveryRegression/Program.cs @@ -0,0 +1,199 @@ +// SPDX-License-Identifier: MPL-2.0 + +using System; +using System.IO; +using System.Linq; +using NexVerse.Core.Discovery; + +internal static class Program +{ + private static void Require(bool condition, string message) + { + if (!condition) + throw new InvalidOperationException(message); + } + + private static void Main() + { + string root = + Path.Combine( + Path.GetTempPath(), + "ogl-discovery-" + + Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(root); + + string path = + Path.Combine( + root, + "discovery.json"); + + NexDiscoveryStore store = + new NexDiscoveryStore(path); + + Guid regionId = Guid.NewGuid(); + Guid parcelId = Guid.NewGuid(); + Guid ownerId = Guid.NewGuid(); + + NexPlaceRecord place = + store.UpsertPlace( + new NexPlaceRecord + { + RegionId = regionId, + RegionName = "NexVerse Landing", + ParcelId = parcelId, + ParcelLocalId = 1, + OwnerId = ownerId, + Name = "NexVerse Landing Plaza", + Description = "Central destination for the grid", + Maturity = NexDiscoveryMaturity.General, + Images = { "https://example.invalid/place.jpg" }, + X = 171, + Y = 126, + Z = 25, + Traffic = 123.5, + Tags = { "city", "landing", "welcome" }, + LandUse = NexLandUse.Commercial, + RegionType = "city", + Featured = true, + State = NexDiscoveryPublicationState.Approved + }); + + Require( + place.PlaceId != Guid.Empty, + "place ID was not assigned"); + + Require( + store.ListPlaces( + "landing", + NexDiscoveryMaturity.General, + NexDiscoveryPublicationState.Approved, + 0, + 10).Count == 1, + "place search failed"); + + NexEventRecord eventRecord = + store.UpsertEvent( + new NexEventRecord + { + PlaceId = place.PlaceId, + OrganizerId = ownerId, + Name = "Welcome Night", + Description = "Opening event", + StartsAt = DateTimeOffset.UtcNow.AddHours(1), + EndsAt = DateTimeOffset.UtcNow.AddHours(3), + Tags = { "party", "welcome" }, + State = NexDiscoveryPublicationState.Approved + }); + + NexClassifiedRecord classified = + store.UpsertClassified( + new NexClassifiedRecord + { + OwnerId = ownerId, + PlaceId = place.PlaceId, + Name = "Shop Space", + Description = "Commercial parcel offer", + Category = "land", + Tags = { "shop", "commercial" }, + State = NexDiscoveryPublicationState.Approved + }); + + NexDestinationRecord destination = + store.UpsertDestination( + new NexDestinationRecord + { + PlaceId = place.PlaceId, + SubmittedBy = ownerId, + Name = "NexVerse City Start", + Description = "Editor destination", + Category = "city", + Subcategory = "welcome", + Collection = "stadt-nexverse", + Featured = true, + EditorPick = true, + Tags = { "city", "start" }, + EventIds = { eventRecord.EventId }, + State = NexDiscoveryPublicationState.Submitted + }); + + Require( + store.ListDestinations( + string.Empty, + null, + NexDiscoveryPublicationState.Approved, + string.Empty, + string.Empty, + null, + null, + string.Empty, + 0, + 10).Count == 0, + "submitted destination leaked into public results"); + + destination = + store.ModerateDestination( + destination.DestinationId, + NexDiscoveryPublicationState.Approved, + "ci-admin", + "approved"); + + Require( + destination.State == + NexDiscoveryPublicationState.Approved, + "destination moderation failed"); + + store.RecordDestinationVisit( + destination.DestinationId); + store.RecordDestinationVisit( + destination.DestinationId); + + Require( + store.GetDestination( + destination.DestinationId).Popularity == 2, + "destination popularity tracking failed"); + + Require( + store.GetCategories().Count == 1, + "destination category projection failed"); + + NexDiscoveryStore reopened = + new NexDiscoveryStore(path); + + Require( + reopened.GetPlace(place.PlaceId) != null && + reopened.GetEvent(eventRecord.EventId) != null && + reopened.GetClassified(classified.ClassifiedId) != null && + reopened.GetDestination(destination.DestinationId) != null, + "discovery persistence/reopen failed"); + + Require( + reopened.ListDestinations( + "nexverse", + NexDiscoveryMaturity.General, + NexDiscoveryPublicationState.Approved, + "city", + "stadt-nexverse", + true, + true, + "popular", + 0, + 10).Count == 1, + "destination filters failed"); + + Require( + reopened.DeletePlace(place.PlaceId), + "place deletion failed"); + + Require( + reopened.GetPlace(place.PlaceId) == null && + reopened.GetEvent(eventRecord.EventId) == null && + reopened.GetClassified(classified.ClassifiedId) == null && + reopened.GetDestination(destination.DestinationId) == null, + "place cascade cleanup failed"); + + Directory.Delete(root, true); + + Console.WriteLine( + "OpenGenesisLINK NexDiscovery persistence, moderation and cascade regression: OK"); + } +} diff --git a/tools/ci/verify_nexdiscovery.py b/tools/ci/verify_nexdiscovery.py new file mode 100644 index 00000000..697d5101 --- /dev/null +++ b/tools/ci/verify_nexdiscovery.py @@ -0,0 +1,131 @@ +#!/usr/bin/env python3 +from pathlib import Path + +store = Path("NexVerse/Core/Discovery/NexDiscoveryStore.cs").read_text(encoding="utf-8") +api = Path("NexVerse/Server/Api/NexDiscoveryApi.cs").read_text(encoding="utf-8") +connector = Path("NexVerse/Server/Api/NexVerseWorldApiConnector.cs").read_text(encoding="utf-8") +security = Path("NexVerse/Core/Security/NexSecurity.cs").read_text(encoding="utf-8") +roadmap = Path("doc/NexVerse/ROADMAP.md").read_text(encoding="utf-8") +robust = Path("bin/Robust.ini.example").read_text(encoding="utf-8") +robust_hg = Path("bin/Robust.HG.ini.example").read_text(encoding="utf-8") +opensim_config = Path("bin/OpenSim.ini.example").read_text(encoding="utf-8") +viewer = Path("NexVerse/RegionModules/Discovery/NexDiscoveryViewerModule.cs").read_text(encoding="utf-8") +openapi = Path("NexVerse/Server/Api/NexVerseWorldApiHandlers.cs").read_text(encoding="utf-8") +regression = Path("tools/ci/NexDiscoveryRegression/Program.cs").read_text(encoding="utf-8") + +for marker in ( + "### 12.1 NexSearch", + "### 12.2 Places", + "### 12.3 Land portal", + "### 12.4 Destination Guide", +): + assert marker in roadmap, f"missing Roadmap 12 marker: {marker}" + +for marker in ( + "NexPlaceRecord", + "NexEventRecord", + "NexClassifiedRecord", + "NexDestinationRecord", + "NexDiscoveryPublicationState", + "NexDiscoveryMaturity", + "NexLandUse", + "ListPlaces(", + "ListEvents(", + "ListClassifieds(", + "ListDestinations(", + "ModerateDestination(", + "RecordDestinationVisit(", + "GetCategories(", +): + assert marker in store, f"missing NexDiscovery store marker: {marker}" + +for marker in ( + "HandleSearch(", + "HandlePlaces(", + "HandleLandPortal(", + "HandleDestinations(", + "HandleContent(", + '"people"', + '"groups"', + '"regions"', + '"parcels"', + '"places"', + '"events"', + '"land_for_sale"', + '"land_for_rent"', + '"classifieds"', + '"experiences"', + '"destinations"', + "SearchLandListings(", + "FindGroups(", + "GetRegionsByName(", + "GetUserAccounts(", + "m_Experiences.Search(", + "DestinationTeleport(", +): + assert marker in api, f"missing NexDiscovery API marker: {marker}" + +for marker in ( + '"/api/v1/search"', + '"/api/v1/places"', + '"/api/v1/events"', + '"/api/v1/classifieds"', + '"/api/v1/land-portal"', + '"/api/v1/destinations"', + "new NexDiscoveryStore(", + "new NexDiscoveryApi(", +): + assert marker in connector, f"missing NexDiscovery connector marker: {marker}" + +for marker in ( + '["/api/v1/search"]', + '["/api/v1/places"]', + '["/api/v1/land-portal"]', + '["/api/v1/destinations"]', + '["/api/v1/destinations/{destinationId}/moderation"]', + '"DiscoveryPlaceRequest"', + '"DiscoveryDestinationRequest"', + '"DiscoveryModerationRequest"', + "PublicOperations(", + "MergeOperations(", +): + assert marker in openapi, f"missing NexDiscovery OpenAPI marker: {marker}" + +for marker in ( + 'DiscoveryRead = "discovery:read"', + 'DiscoverySubmit = "discovery:submit"', + 'DiscoveryManage = "discovery:manage"', +): + assert marker in security, f"missing discovery scope: {marker}" + +for config in (robust, robust_hg): + assert "[NexDiscovery]" in config + assert 'StorePath = "data/opengenesislink-discovery.json"' in config + assert 'TeleportBaseUri = ""' in config + +for marker in ( + "NexDiscoveryViewerModule", + '"NexSearch"', + '"NexPlaces"', + '"NexLandPortal"', + '"NexDestinationGuide"', + "/api/v1/search", + "/api/v1/places", + "/api/v1/land-portal", + "/api/v1/destinations", +): + assert marker in viewer, f"missing viewer discovery capability marker: {marker}" + +assert "[NexDiscoveryViewer]" in opensim_config +assert 'WorldApiBaseUrl = "http://127.0.0.1:8002"' in opensim_config + +for marker in ( + "submitted destination leaked into public results", + "destination moderation failed", + "destination popularity tracking failed", + "discovery persistence/reopen failed", + "place cascade cleanup failed", +): + assert marker in regression, f"missing discovery regression marker: {marker}" + +print("OpenGenesisLINK Roadmap 12 NexDiscovery contract: OK")