using System.Diagnostics; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Moonlight.Api.Helpers; namespace Moonlight.Api.Services; public class ApplicationService : IHostedService { private readonly VersionService VersionService; private readonly ILogger Logger; public DateTimeOffset StartedAt { get; private set; } public string VersionName { get; private set; } = "N/A"; public bool IsUpToDate { get; set; } = true; public string OperatingSystem { get; private set; } = "N/A"; public ApplicationService(VersionService versionService, ILogger logger) { VersionService = versionService; Logger = logger; } public Task GetMemoryUsageAsync() { using var currentProcess = Process.GetCurrentProcess(); return Task.FromResult(currentProcess.WorkingSet64); } public async Task GetCpuUsageAsync() { using var currentProcess = Process.GetCurrentProcess(); // Get initial values var startCpuTime = currentProcess.TotalProcessorTime; var startTime = DateTime.UtcNow; // Wait a bit to calculate the diff await Task.Delay(500); // New values var endCpuTime = currentProcess.TotalProcessorTime; var endTime = DateTime.UtcNow; // Calculate CPU usage var cpuUsedMs = (endCpuTime - startCpuTime).TotalMilliseconds; var totalMsPassed = (endTime - startTime).TotalMilliseconds; var cpuUsagePercent = (cpuUsedMs / (Environment.ProcessorCount * totalMsPassed)) * 100; return Math.Round(cpuUsagePercent, 2); } public async Task StartAsync(CancellationToken cancellationToken) { StartedAt = DateTimeOffset.UtcNow; OperatingSystem = OsHelper.GetName(); try { var currentVersion = await VersionService.GetInstanceVersionAsync(); var latestVersion = await VersionService.GetLatestVersionAsync(); VersionName = currentVersion.Identifier; IsUpToDate = latestVersion == null || currentVersion.Identifier == latestVersion.Identifier; Logger.LogInformation("Running Moonlight Panel {version} on {operatingSystem}", VersionName, OperatingSystem); if (!IsUpToDate) Logger.LogWarning("Your instance is not up-to-date"); if (currentVersion.IsDevelopment) Logger.LogWarning("Your instance is running a development version"); if (currentVersion.IsPreRelease) Logger.LogWarning("Your instance is running a pre-release version"); } catch (Exception e) { Logger.LogError(e, "An unhandled exception occurred while fetching version details"); } } public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask; }