534 lines
22 KiB
C#
534 lines
22 KiB
C#
namespace ThreadPilot.Services
|
|
{
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Collections.ObjectModel;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Text.RegularExpressions;
|
|
using System.Threading.Tasks;
|
|
using Microsoft.Extensions.Logging;
|
|
using ThreadPilot.Models;
|
|
using ThreadPilot.Services.Abstractions;
|
|
|
|
public class PowerPlanService : IPowerPlanService
|
|
{
|
|
private static readonly Lazy<string> powerPlansPath = new(GetPowerPlansPath);
|
|
private static readonly string powerCfgExecutablePath = Path.Combine(Environment.SystemDirectory, "powercfg.exe");
|
|
private static readonly TimeSpan powerCfgTimeout = TimeSpan.FromSeconds(20);
|
|
private static readonly Regex powerSchemeRegex = new(@"Power Scheme GUID: (.*?) \((.*?)\)", RegexOptions.Multiline | RegexOptions.Compiled);
|
|
private static readonly Regex pathTraversalRegex = new(@"(^|[\\/])\.\.([\\/]|$)", RegexOptions.Compiled);
|
|
|
|
private static string PowerPlansPath => powerPlansPath.Value;
|
|
|
|
private readonly object lockObject = new();
|
|
private readonly ILogger<PowerPlanService> logger;
|
|
private readonly IEnhancedLoggingService enhancedLogger;
|
|
private readonly IProcessRunner processRunner;
|
|
private readonly Func<string> powerPlansPathProvider;
|
|
private string? lastActivePowerPlanGuid;
|
|
|
|
public event EventHandler<PowerPlanChangedEventArgs>? PowerPlanChanged;
|
|
|
|
public PowerPlanService(ILogger<PowerPlanService> logger, IEnhancedLoggingService enhancedLogger)
|
|
: this(logger, enhancedLogger, new SystemProcessRunner(), null)
|
|
{
|
|
}
|
|
|
|
public PowerPlanService(ILogger<PowerPlanService> logger, IEnhancedLoggingService enhancedLogger, IProcessRunner processRunner)
|
|
: this(logger, enhancedLogger, processRunner, null)
|
|
{
|
|
}
|
|
|
|
public PowerPlanService(
|
|
ILogger<PowerPlanService> logger,
|
|
IEnhancedLoggingService enhancedLogger,
|
|
IProcessRunner processRunner,
|
|
Func<string>? powerPlansPathProvider)
|
|
{
|
|
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
this.enhancedLogger = enhancedLogger ?? throw new ArgumentNullException(nameof(enhancedLogger));
|
|
this.processRunner = processRunner ?? throw new ArgumentNullException(nameof(processRunner));
|
|
this.powerPlansPathProvider = powerPlansPathProvider ?? (() => PowerPlansPath);
|
|
}
|
|
|
|
private static string GetPowerPlansPath()
|
|
{
|
|
StoragePaths.EnsureAppDataDirectories();
|
|
|
|
// Check portable mode first (Powerplans folder next to EXE)
|
|
var exeDir = AppContext.BaseDirectory;
|
|
var portablePath = Path.Combine(exeDir, "Powerplans");
|
|
if (Directory.Exists(portablePath) && Directory.EnumerateFiles(portablePath, "*.pow", SearchOption.AllDirectories).Any())
|
|
{
|
|
return portablePath;
|
|
}
|
|
|
|
// Installed mode: use AppData
|
|
var appDataPath = StoragePaths.PowerPlansDirectory;
|
|
|
|
// Ensure directory exists
|
|
if (!Directory.Exists(appDataPath))
|
|
{
|
|
Directory.CreateDirectory(appDataPath);
|
|
|
|
// If portable path exists but was empty, or we have bundled plans to copy
|
|
// Copy any .pow files from portable location to AppData
|
|
if (Directory.Exists(portablePath))
|
|
{
|
|
foreach (var file in Directory.EnumerateFiles(portablePath, "*.pow", SearchOption.AllDirectories))
|
|
{
|
|
var relativePath = Path.GetRelativePath(portablePath, file);
|
|
var destFile = Path.Combine(appDataPath, relativePath);
|
|
if (!File.Exists(destFile))
|
|
{
|
|
try
|
|
{
|
|
Directory.CreateDirectory(Path.GetDirectoryName(destFile) ?? appDataPath);
|
|
File.Copy(file, destFile);
|
|
}
|
|
catch
|
|
{
|
|
// Ignore copy errors, plans may not be available
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return appDataPath;
|
|
}
|
|
|
|
public async Task<ObservableCollection<PowerPlanModel>> GetPowerPlansAsync()
|
|
{
|
|
var powerPlans = new ObservableCollection<PowerPlanModel>();
|
|
var activePlan = await this.GetActivePowerPlan().ConfigureAwait(false);
|
|
|
|
var result = await this.RunPowerCfgAsync("/list").ConfigureAwait(false);
|
|
var matches = powerSchemeRegex.Matches(result.StandardOutput);
|
|
|
|
foreach (Match match in matches)
|
|
{
|
|
var guid = match.Groups[1].Value.Trim();
|
|
var name = match.Groups[2].Value.Trim();
|
|
|
|
var plan = new PowerPlanModel
|
|
{
|
|
Guid = guid,
|
|
Name = name,
|
|
IsActive = guid == activePlan?.Guid,
|
|
IsCustomPlan = false,
|
|
};
|
|
|
|
powerPlans.Add(plan);
|
|
}
|
|
|
|
return powerPlans;
|
|
}
|
|
|
|
public async Task<ObservableCollection<PowerPlanModel>> GetCustomPowerPlansAsync()
|
|
{
|
|
var customPlans = new ObservableCollection<PowerPlanModel>();
|
|
var powerPlansPath = this.powerPlansPathProvider();
|
|
if (!Directory.Exists(powerPlansPath))
|
|
{
|
|
return customPlans;
|
|
}
|
|
|
|
foreach (var file in Directory.EnumerateFiles(powerPlansPath, "*.pow", SearchOption.AllDirectories))
|
|
{
|
|
customPlans.Add(new PowerPlanModel
|
|
{
|
|
Name = Path.GetFileNameWithoutExtension(file),
|
|
FilePath = file,
|
|
IsCustomPlan = true,
|
|
});
|
|
}
|
|
|
|
return await Task.FromResult(customPlans).ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task<bool> SetActivePowerPlan(PowerPlanModel powerPlan)
|
|
{
|
|
return await this.SetActivePowerPlanByGuidAsync(powerPlan.Guid, false).ConfigureAwait(false);
|
|
}
|
|
|
|
public async Task<bool> SetActivePowerPlanByGuidAsync(string powerPlanGuid, bool preventDuplicateChanges = true)
|
|
{
|
|
if (!Guid.TryParse(powerPlanGuid, out _))
|
|
{
|
|
this.logger.LogWarning("Rejected invalid power plan GUID: {PowerPlanGuid}", powerPlanGuid);
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
// Check if change is needed when duplicate prevention is enabled
|
|
if (preventDuplicateChanges)
|
|
{
|
|
var isChangeNeeded = await this.IsPowerPlanChangeNeededAsync(powerPlanGuid).ConfigureAwait(false);
|
|
if (!isChangeNeeded)
|
|
{
|
|
this.logger.LogDebug("Power plan change skipped - already active: {PowerPlanGuid}", powerPlanGuid);
|
|
return true; // No change needed, consider it successful
|
|
}
|
|
}
|
|
|
|
var previousPowerPlan = await this.GetActivePowerPlan().ConfigureAwait(false);
|
|
var targetPowerPlan = await this.GetPowerPlanByGuidAsync(powerPlanGuid).ConfigureAwait(false);
|
|
|
|
this.logger.LogInformation(
|
|
"Attempting to change power plan from '{FromPlan}' to '{ToPlan}'",
|
|
previousPowerPlan?.Name ?? "Unknown", targetPowerPlan?.Name ?? "Unknown");
|
|
|
|
await this.enhancedLogger.LogPowerPlanChangeAsync(
|
|
previousPowerPlan?.Name ?? "Unknown",
|
|
targetPowerPlan?.Name ?? "Unknown",
|
|
"Manual power plan change requested").ConfigureAwait(false);
|
|
|
|
var result = await this.RunPowerCfgAsync("/setactive", powerPlanGuid).ConfigureAwait(false);
|
|
var success = result.ExitCode == 0;
|
|
|
|
if (success)
|
|
{
|
|
lock (this.lockObject)
|
|
{
|
|
this.lastActivePowerPlanGuid = powerPlanGuid;
|
|
}
|
|
|
|
var newPowerPlan = await this.GetPowerPlanByGuidAsync(powerPlanGuid).ConfigureAwait(false);
|
|
|
|
this.logger.LogInformation("Power plan successfully changed to '{PowerPlan}'", newPowerPlan?.Name ?? "Unknown");
|
|
|
|
await this.enhancedLogger.LogPowerPlanChangeAsync(
|
|
previousPowerPlan?.Name ?? "Unknown",
|
|
newPowerPlan?.Name ?? "Unknown",
|
|
"Manual power plan change completed").ConfigureAwait(false);
|
|
|
|
this.PowerPlanChanged?.Invoke(this, new PowerPlanChangedEventArgs(
|
|
previousPowerPlan, newPowerPlan, "Manual power plan change"));
|
|
}
|
|
else
|
|
{
|
|
this.logger.LogWarning(
|
|
"Failed to change power plan to '{PowerPlanGuid}' - powercfg exit code: {ExitCode}, stderr: {StdErr}",
|
|
powerPlanGuid,
|
|
result.ExitCode,
|
|
result.StandardError);
|
|
|
|
await this.enhancedLogger.LogSystemEventAsync(
|
|
LogEventTypes.PowerPlan.ChangeFailed,
|
|
$"Failed to change power plan to '{targetPowerPlan?.Name ?? powerPlanGuid}' - Exit code: {result.ExitCode}",
|
|
Microsoft.Extensions.Logging.LogLevel.Warning).ConfigureAwait(false);
|
|
}
|
|
|
|
return success;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Exception occurred while changing power plan to '{PowerPlanGuid}'", powerPlanGuid);
|
|
|
|
await this.enhancedLogger.LogErrorAsync(ex, "PowerPlanService.SetActivePowerPlanByGuidAsync",
|
|
new Dictionary<string, object>
|
|
{
|
|
["PowerPlanGuid"] = powerPlanGuid,
|
|
["PreventDuplicateChanges"] = preventDuplicateChanges,
|
|
}).ConfigureAwait(false);
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public async Task<PowerPlanModel?> GetActivePowerPlan()
|
|
{
|
|
try
|
|
{
|
|
var result = await this.RunPowerCfgAsync("/getactivescheme").ConfigureAwait(false);
|
|
var match = powerSchemeRegex.Match(result.StandardOutput);
|
|
|
|
if (match.Success)
|
|
{
|
|
return new PowerPlanModel
|
|
{
|
|
Guid = match.Groups[1].Value.Trim(),
|
|
Name = match.Groups[2].Value.Trim(),
|
|
IsActive = true,
|
|
};
|
|
}
|
|
|
|
this.logger.LogWarning("Could not parse active power plan from powercfg output.");
|
|
return null;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Failed to read active power plan.");
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public async Task<bool> ImportCustomPowerPlan(string filePath)
|
|
{
|
|
if (!this.TryNormalizePowerPlanPath(filePath, out var normalizedPath, out var validationError))
|
|
{
|
|
this.logger.LogWarning("Rejected power plan import path '{FilePath}': {ValidationError}", filePath, validationError);
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
var result = await this.RunPowerCfgAsync("/import", normalizedPath).ConfigureAwait(false);
|
|
|
|
if (result.ExitCode != 0)
|
|
{
|
|
this.logger.LogWarning(
|
|
"Power plan import failed for '{Path}' with exit code {ExitCode}. stderr: {StdErr}",
|
|
normalizedPath,
|
|
result.ExitCode,
|
|
result.StandardError);
|
|
|
|
return false;
|
|
}
|
|
|
|
this.logger.LogInformation("Imported custom power plan from '{Path}'", normalizedPath);
|
|
return true;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Exception occurred while importing custom power plan from '{Path}'", normalizedPath);
|
|
await this.enhancedLogger.LogErrorAsync(ex, "PowerPlanService.ImportCustomPowerPlan",
|
|
new Dictionary<string, object> { ["Path"] = normalizedPath }).ConfigureAwait(false);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public async Task<bool> AddCustomPowerPlanFileAsync(string filePath)
|
|
{
|
|
if (!this.TryNormalizePowerPlanPath(filePath, out var normalizedPath, out var validationError))
|
|
{
|
|
this.logger.LogWarning("Rejected custom power plan file '{FilePath}': {ValidationError}", filePath, validationError);
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
var powerPlansPath = this.powerPlansPathProvider();
|
|
Directory.CreateDirectory(powerPlansPath);
|
|
|
|
var fileName = Path.GetFileName(normalizedPath);
|
|
var destinationPath = Path.Combine(powerPlansPath, fileName);
|
|
|
|
// If user selects a file already in the managed folder, treat as success.
|
|
if (string.Equals(normalizedPath, destinationPath, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return true;
|
|
}
|
|
|
|
if (File.Exists(destinationPath))
|
|
{
|
|
var baseName = Path.GetFileNameWithoutExtension(fileName);
|
|
var extension = Path.GetExtension(fileName);
|
|
var suffix = 1;
|
|
|
|
do
|
|
{
|
|
destinationPath = Path.Combine(powerPlansPath, $"{baseName}_{suffix}{extension}");
|
|
suffix++;
|
|
}
|
|
while (File.Exists(destinationPath));
|
|
}
|
|
|
|
File.Copy(normalizedPath, destinationPath, false);
|
|
|
|
this.logger.LogInformation(
|
|
"Added custom power plan file '{SourcePath}' as '{DestinationPath}'",
|
|
normalizedPath,
|
|
destinationPath);
|
|
|
|
await Task.CompletedTask.ConfigureAwait(false);
|
|
return true;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Failed to add custom power plan file '{Path}'", normalizedPath);
|
|
await this.enhancedLogger.LogErrorAsync(ex, "PowerPlanService.AddCustomPowerPlanFileAsync",
|
|
new Dictionary<string, object> { ["Path"] = normalizedPath }).ConfigureAwait(false);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public async Task<bool> DeletePowerPlanAsync(string powerPlanGuid)
|
|
{
|
|
if (!Guid.TryParse(powerPlanGuid, out _))
|
|
{
|
|
this.logger.LogWarning("Rejected invalid power plan GUID for delete: {PowerPlanGuid}", powerPlanGuid);
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
var activePlan = await this.GetActivePowerPlan().ConfigureAwait(false);
|
|
if (string.Equals(activePlan?.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
this.logger.LogWarning("Blocked deletion of active power plan: {PowerPlanGuid}", powerPlanGuid);
|
|
await this.enhancedLogger.LogSystemEventAsync(
|
|
LogEventTypes.PowerPlan.ChangeFailed,
|
|
$"Blocked deletion of active power plan '{activePlan?.Name ?? powerPlanGuid}'",
|
|
Microsoft.Extensions.Logging.LogLevel.Warning).ConfigureAwait(false);
|
|
return false;
|
|
}
|
|
|
|
var targetPlan = await this.GetPowerPlanByGuidAsync(powerPlanGuid).ConfigureAwait(false);
|
|
var result = await this.RunPowerCfgAsync("/delete", powerPlanGuid).ConfigureAwait(false);
|
|
var success = result.ExitCode == 0;
|
|
|
|
if (success)
|
|
{
|
|
this.logger.LogInformation("Deleted power plan '{PowerPlan}' ({PowerPlanGuid})", targetPlan?.Name ?? "Unknown", powerPlanGuid);
|
|
await this.enhancedLogger.LogUserActionAsync(
|
|
"PowerPlanDeleted",
|
|
$"Deleted power plan {targetPlan?.Name ?? powerPlanGuid}",
|
|
$"Guid: {powerPlanGuid}").ConfigureAwait(false);
|
|
}
|
|
else
|
|
{
|
|
this.logger.LogWarning(
|
|
"Failed to delete power plan '{PowerPlanGuid}' - powercfg exit code: {ExitCode}, stderr: {StdErr}",
|
|
powerPlanGuid,
|
|
result.ExitCode,
|
|
result.StandardError);
|
|
|
|
await this.enhancedLogger.LogSystemEventAsync(
|
|
LogEventTypes.PowerPlan.ChangeFailed,
|
|
$"Failed to delete power plan '{targetPlan?.Name ?? powerPlanGuid}' - Exit code: {result.ExitCode}",
|
|
Microsoft.Extensions.Logging.LogLevel.Warning).ConfigureAwait(false);
|
|
}
|
|
|
|
return success;
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogError(ex, "Exception occurred while deleting power plan '{PowerPlanGuid}'", powerPlanGuid);
|
|
await this.enhancedLogger.LogErrorAsync(ex, "PowerPlanService.DeletePowerPlanAsync",
|
|
new Dictionary<string, object> { ["PowerPlanGuid"] = powerPlanGuid }).ConfigureAwait(false);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
public async Task<string?> GetActivePowerPlanGuidAsync()
|
|
{
|
|
var activePlan = await this.GetActivePowerPlan().ConfigureAwait(false);
|
|
return activePlan?.Guid;
|
|
}
|
|
|
|
public async Task<bool> PowerPlanExistsAsync(string powerPlanGuid)
|
|
{
|
|
if (!Guid.TryParse(powerPlanGuid, out _))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var powerPlans = await this.GetPowerPlansAsync().ConfigureAwait(false);
|
|
return powerPlans.Any(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
public async Task<PowerPlanModel?> GetPowerPlanByGuidAsync(string powerPlanGuid)
|
|
{
|
|
if (!Guid.TryParse(powerPlanGuid, out _))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
var powerPlans = await this.GetPowerPlansAsync().ConfigureAwait(false);
|
|
return powerPlans.FirstOrDefault(p => string.Equals(p.Guid, powerPlanGuid, StringComparison.OrdinalIgnoreCase));
|
|
}
|
|
|
|
public async Task<bool> IsPowerPlanChangeNeededAsync(string targetPowerPlanGuid)
|
|
{
|
|
try
|
|
{
|
|
var currentGuid = await this.GetActivePowerPlanGuidAsync().ConfigureAwait(false);
|
|
|
|
// Check if the target power plan is already active
|
|
if (string.Equals(currentGuid, targetPowerPlanGuid, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return false; // No change needed
|
|
}
|
|
|
|
// Check if we recently set this power plan (to prevent rapid switching)
|
|
lock (this.lockObject)
|
|
{
|
|
if (string.Equals(this.lastActivePowerPlanGuid, targetPowerPlanGuid, StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
return false; // We recently set this plan
|
|
}
|
|
}
|
|
|
|
return true; // Change is needed
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
this.logger.LogWarning(ex, "Could not determine if power plan change is needed for '{PowerPlanGuid}'", targetPowerPlanGuid);
|
|
return true; // If we can't determine, assume change is needed
|
|
}
|
|
}
|
|
|
|
private bool TryNormalizePowerPlanPath(string filePath, out string normalizedPath, out string error)
|
|
{
|
|
normalizedPath = string.Empty;
|
|
|
|
if (string.IsNullOrWhiteSpace(filePath))
|
|
{
|
|
error = "Path is empty.";
|
|
return false;
|
|
}
|
|
|
|
if (pathTraversalRegex.IsMatch(filePath))
|
|
{
|
|
error = "Path traversal segments are not allowed.";
|
|
return false;
|
|
}
|
|
|
|
if (!Path.IsPathFullyQualified(filePath))
|
|
{
|
|
error = "Path must be absolute.";
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
normalizedPath = Path.GetFullPath(filePath);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
error = $"Invalid file path: {ex.Message}";
|
|
return false;
|
|
}
|
|
|
|
if (!string.Equals(Path.GetExtension(normalizedPath), ".pow", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
error = "Only .pow files are supported.";
|
|
return false;
|
|
}
|
|
|
|
if (!File.Exists(normalizedPath))
|
|
{
|
|
error = "File does not exist.";
|
|
return false;
|
|
}
|
|
|
|
var fileInfo = new FileInfo(normalizedPath);
|
|
if (fileInfo.Length > 10 * 1024 * 1024)
|
|
{
|
|
error = "Power plan file size exceeds 10 MB limit.";
|
|
return false;
|
|
}
|
|
|
|
error = string.Empty;
|
|
return true;
|
|
}
|
|
|
|
private Task<ProcessRunResult> RunPowerCfgAsync(params string[] arguments) =>
|
|
this.processRunner.RunAsync(powerCfgExecutablePath, arguments, powerCfgTimeout);
|
|
}
|
|
}
|