Add system control feature for remote shutdown/restart with timer support and UI integration

This commit is contained in:
Din
2025-08-08 11:52:12 +08:00
parent 5ece1fbe27
commit 1129f9a2b1
4 changed files with 302 additions and 1 deletions
+80
View File
@@ -154,5 +154,85 @@ namespace ResourceMonitorService.Controllers
return StatusCode(500, "Internal server error");
}
}
[HttpPost("system-control")]
public ActionResult SystemControl([FromBody] SystemControlRequest request)
{
try
{
if (request == null)
{
return BadRequest("Invalid request");
}
// Validate action
if (request.Action != "shutdown" && request.Action != "restart")
{
return BadRequest("Invalid action. Use 'shutdown' or 'restart'");
}
// Validate timer
if (request.Timer < 0 || request.Timer > 86400)
{
return BadRequest("Timer must be between 0 and 86400 seconds (24 hours)");
}
// Build the shutdown command
var arguments = request.Action == "shutdown" ? "/s" : "/r";
if (request.Force)
{
arguments += " /f";
}
if (request.Timer > 0)
{
arguments += $" /t {request.Timer}";
}
// Execute the shutdown command
var processInfo = new ProcessStartInfo
{
FileName = "shutdown",
Arguments = arguments,
UseShellExecute = false,
CreateNoWindow = true
};
var process = Process.Start(processInfo);
string message;
if (request.Timer > 0)
{
var minutes = request.Timer / 60;
var seconds = request.Timer % 60;
var timeString = minutes > 0
? $"{minutes} minute{(minutes != 1 ? "s" : "")}" + (seconds > 0 ? $" and {seconds} second{(seconds != 1 ? "s" : "")}" : "")
: $"{seconds} second{(seconds != 1 ? "s" : "")}";
message = $"System {request.Action} scheduled in {timeString}";
}
else
{
message = $"System {request.Action} initiated immediately";
}
_logger.LogWarning($"System {request.Action} command executed by user. Timer: {request.Timer}s, Force: {request.Force}");
return Ok(new { message });
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error executing system {request?.Action} command");
return StatusCode(500, "Internal server error");
}
}
}
public class SystemControlRequest
{
public string Action { get; set; } = string.Empty;
public int Timer { get; set; } = 0;
public bool Force { get; set; } = true;
}
}