Essentials/src/PepperDash.Essentials.Core/Web/EssentialsWebApi.cs
jkdevito f0025ce56c Backport PR #1439: packageManifest CWS endpoint + v1/v2 config merge fix
Backports PepperDash/Essentials#1439 (merged to main at 6ceddcf5) onto
dev/v3-routing (v3.0.0-dev-v3-routing.40):

- New GET /packageManifest CWS route reporting Essentials/plugin/touchpanel
  UI package version info (GetPackageManifestRequestHandler).
- EssentialsConfig.Versions now round-trips via [JsonProperty("versions")].
- ConfigReader now detects v1 vs v2 config by presence of system/template
  nodes (previously any versions node caused the v1->v2 merge to be
  skipped), and re-applies the versions node after merge since
  PortalConfigReader.MergeConfigs does not carry it forward.
- Mobile control: track and validate UI client app versions
  (ConnectedClientVersionInfo, MobileControlSystemController changes merged
  cleanly from the PR).
- Directory.Build.props: adds PackageId AssemblyMetadata item (kept this
  branch's 3.0.0-local version).

Conflict resolution notes:
- This branch had already introduced its own AppVersion type (Version +
  RepoUrl only) for TouchpanelWrapperApp/UserInterfaces. Replaced it with
  the PR's unified NugetVersion (adds PackageId/RepoUrl/Name, all
  NullValueHandling.Ignore) to match main's schema, since AppVersion had
  no other references in the codebase.
- ConfigReader.LoadConfig on this branch had already fixed a double
  Stream.ReadToEnd() bug (reading fileContents once); kept that fix and
  layered the PR's v1/v2 detection fix + versions-node preservation on
  top of it, plus this branch's null-ConfigObject-after-merge guard.
- EssentialsWebApi.SetupRoutes: inserted the new packageManifest route
  into this branch's existing (longer) route list, which already
  includes routing-specific endpoints not present on main.

Builds clean (dotnet build on the full solution, 0 errors).

Not pushed - pending local hardware/config testing before push.
2026-07-10 09:37:29 -05:00

329 lines
11 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Crestron.SimplSharp;
using Crestron.SimplSharp.WebScripting;
using PepperDash.Core;
using PepperDash.Core.Web;
using PepperDash.Essentials.Core.Web.RequestHandlers;
using Serilog.Events;
namespace PepperDash.Essentials.Core.Web;
/// <summary>
/// Represents a EssentialsWebApi
/// </summary>
public class EssentialsWebApi : EssentialsDevice
{
private readonly WebApiServer _server;
private readonly WebApiServer _debugServer;
///<example>
/// http(s)://{ipaddress}/cws/{basePath}
/// http(s)://{ipaddress}/VirtualControl/Rooms/{roomId}/cws/{basePath}
/// </example>
private readonly string _defaultBasePath = CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance
? string.Format("/app{0:00}/api", InitialParametersClass.ApplicationNumber)
: "/api";
/// <summary>
/// Gets or sets the BasePath
/// </summary>
public string BasePath { get; private set; }
/// <summary>
/// Tracks if CWS is registered
/// </summary>
public bool IsRegistered
{
get { return _server.IsRegistered; }
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="key"></param>
/// <param name="name"></param>
public EssentialsWebApi(string key, string name)
: this(key, name, null)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="key"></param>
/// <param name="name"></param>
/// <param name="config"></param>
public EssentialsWebApi(string key, string name, EssentialsWebApiPropertiesConfig config)
: base(key, name)
{
Key = key;
if (config == null)
BasePath = _defaultBasePath;
else
BasePath = string.IsNullOrEmpty(config.BasePath) ? _defaultBasePath : config.BasePath;
_server = new WebApiServer(Key, Name, BasePath);
_debugServer = new WebApiServer($"{key}-debug-app", $"{name} Debug App", "/debug");
_debugServer.SetFallbackHandler(new ServeDebugAppRequestHandler());
SetupRoutes();
}
private void SetupRoutes()
{
var routes = new List<HttpCwsRoute>
{
new HttpCwsRoute("login")
{
Name = "Root",
RouteHandler = new LoginRequestHandler()
},
new HttpCwsRoute("versions")
{
Name = "ReportVersions",
RouteHandler = new ReportVersionsRequestHandler()
},
new HttpCwsRoute("packageManifest")
{
Name = "GetPackageManifest",
RouteHandler = new GetPackageManifestRequestHandler()
},
new HttpCwsRoute("appdebug")
{
Name = "AppDebug",
RouteHandler = new AppDebugRequestHandler()
},
new HttpCwsRoute("devices")
{
Name = "DevList",
RouteHandler = new DevListRequestHandler()
},
new HttpCwsRoute("deviceCommands/{deviceKey}")
{
Name = "DevJson",
RouteHandler = new DevJsonRequestHandler()
},
new HttpCwsRoute("deviceProperties/{deviceKey}")
{
Name = "DevProps",
RouteHandler = new DevPropsRequestHandler()
},
new HttpCwsRoute("deviceMethods/{deviceKey}")
{
Name = "DevMethods",
RouteHandler = new DevMethodsRequestHandler()
},
new HttpCwsRoute("deviceFeedbacks/{deviceKey}")
{
Name = "GetFeedbacksForDeviceKey",
RouteHandler = new GetFeedbacksForDeviceRequestHandler()
},
new HttpCwsRoute("deviceStreamDebug")
{
Name = "SetDeviceStreamDebug",
RouteHandler = new SetDeviceStreamDebugRequestHandler()
},
new HttpCwsRoute("disableAllStreamDebug")
{
Name = "DisableAllStreamDebug",
RouteHandler = new DisableAllStreamDebugRequestHandler()
},
new HttpCwsRoute("config")
{
Name = "ShowConfig",
RouteHandler = new ShowConfigRequestHandler()
},
new HttpCwsRoute("types")
{
Name = "GetTypes",
RouteHandler = new GetTypesRequestHandler()
},
new HttpCwsRoute("types/{filter}")
{
Name = "GetTypesByFilter",
RouteHandler = new GetTypesByFilterRequestHandler()
},
new HttpCwsRoute("joinMap/{bridgeKey}")
{
Name = "GetJoinMapsForBridgeKey",
RouteHandler = new GetJoinMapForBridgeKeyRequestHandler()
},
new HttpCwsRoute("joinMap/{bridgeKey}/{deviceKey}")
{
Name = "GetJoinMapsForDeviceKey",
RouteHandler = new GetJoinMapForDeviceKeyRequestHandler()
},
new HttpCwsRoute("debugSession")
{
Name = "DebugSession",
RouteHandler = new DebugSessionRequestHandler()
},
new HttpCwsRoute("doNotLoadConfigOnNextBoot")
{
Name = "DoNotLoadConfigOnNextBoot",
RouteHandler = new DoNotLoadConfigOnNextBootRequestHandler()
},
new HttpCwsRoute("restartProgram")
{
Name = "Restart Program",
RouteHandler = new RestartProgramRequestHandler()
},
new HttpCwsRoute("loadConfig")
{
Name = "Load Config",
RouteHandler = new LoadConfigRequestHandler()
},
new HttpCwsRoute("tielines")
{
Name = "Get TieLines",
RouteHandler = new GetTieLinesRequestHandler()
},
new HttpCwsRoute("device/{deviceKey}/routingPorts")
{
Name = "Get Routing Ports for a device",
RouteHandler = new GetRoutingPortsHandler()
},
new HttpCwsRoute("routingDevicesAndTieLines")
{
Name = "Get Routing Devices and TieLines",
RouteHandler = new GetRoutingDevicesAndTieLinesHandler()
},
new HttpCwsRoute("routingFeedbackSession")
{
Name = "Routing Feedback WebSocket Session",
RouteHandler = new RoutingFeedbackSessionRequestHandler()
},
new HttpCwsRoute("initializationExceptions")
{
Name = "Get Initialization Exceptions",
RouteHandler = new GetInitializationExceptionsRequestHandler()
}
};
AddRoute(routes);
}
/// <summary>
/// Add a single route to the API. MUST be done during the activation phase
/// </summary>
/// <param name="route"></param>
public void AddRoute(HttpCwsRoute route)
{
_server.AddRoute(route);
}
/// <summary>
/// Add a collection of routes to the API. MUST be done during the activation phase
/// </summary>
/// <param name="routes"></param>
public void AddRoute(List<HttpCwsRoute> routes)
{
foreach (var route in routes)
{
AddRoute(route);
}
}
/// <summary>
/// Initializes the CWS class
/// </summary>
protected override void Initialize()
{
AddRoute(new HttpCwsRoute("apiPaths")
{
Name = "GetPaths",
RouteHandler = new GetRoutesHandler(_server.GetRouteCollection(), BasePath)
});
// If running on an appliance
if (CrestronEnvironment.DevicePlatform == eDevicePlatform.Appliance)
{
/*
WEBSERVER [ON | OFF | TIMEOUT <VALUE IN SECONDS> | MAXSESSIONSPERUSER <Number of sessions>]
*/
var response = string.Empty;
CrestronConsole.SendControlSystemCommand("webserver", ref response);
if (response.Contains("OFF")) return;
var is4Series = eCrestronSeries.Series4 == (Global.ProcessorSeries & eCrestronSeries.Series4);
Debug.LogMessage(LogEventLevel.Verbose, "Starting Essentials Web API on {0} Appliance", is4Series ? "4-series" : "3-series");
_server.Start();
_debugServer.Start();
PrintPaths();
return;
}
// Automatically start CWS when running on a server (Linux OS, Virtual Control)
Debug.LogMessage(LogEventLevel.Verbose, "Starting Essentials Web API on Virtual Control Server");
_server.Start();
_debugServer.Start();
PrintPaths();
}
/// <summary>
/// Print the available paths
/// </summary>
/// <example>
/// http(s)://{ipaddress}/cws/{basePath}
/// http(s)://{ipaddress}/VirtualControl/Rooms/{roomId}/cws/{basePath}
/// </example>
/// <summary>
/// GetPaths method
/// </summary>
public void PrintPaths()
{
Debug.LogMessage(LogEventLevel.Information, this, new string('-', 50));
var currentIp = CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_CURRENT_IP_ADDRESS, 0);
var hostname = CrestronEthernetHelper.GetEthernetParameter(
CrestronEthernetHelper.ETHERNET_PARAMETER_TO_GET.GET_HOSTNAME, 0);
var path = CrestronEnvironment.DevicePlatform == eDevicePlatform.Server
? $"https://{hostname}/VirtualControl/Rooms/{InitialParametersClass.RoomId}/cws{BasePath}"
: $"https://{currentIp}/cws{BasePath}";
Debug.LogMessage(LogEventLevel.Information, this, "Server: {path:l}", path);
var routeCollection = _server.GetRouteCollection();
if (routeCollection == null)
{
Debug.LogMessage(LogEventLevel.Information, this, "Server route collection is null");
return;
}
Debug.LogMessage(LogEventLevel.Information, this, "Configured Routes:");
foreach (var route in routeCollection)
{
Debug.LogMessage(LogEventLevel.Information, this, "{routeName:l}: {routePath:l}/{routeUrl:l}", route.Name, path, route.Url);
}
var debugPath = CrestronEnvironment.DevicePlatform == eDevicePlatform.Server
? $"https://{hostname}/VirtualControl/Rooms/{InitialParametersClass.RoomId}/cws/debug"
: $"https://{currentIp}/cws/debug";
Debug.LogMessage(LogEventLevel.Information, this, "Debug App: {debugPath:l}", debugPath);
Debug.LogInformation(this, "Web API initialized and ready to accept requests");
Debug.LogMessage(LogEventLevel.Information, this, new string('-', 50));
var debugAppUrl = CrestronEnvironment.DevicePlatform == eDevicePlatform.Server
? $"https://{hostname}/VirtualControl/Rooms/{InitialParametersClass.RoomId}/cws/debug"
: $"https://{currentIp}/cws/debug";
Debug.LogMessage(LogEventLevel.Information, this, "Developer Tools Web App available at: {debugAppUrl:l}", debugAppUrl);
}
}