Skip to content

Commit

Permalink
2022.13.0
Browse files Browse the repository at this point in the history
  • Loading branch information
LAB02 Research committed Oct 25, 2022
1 parent 17a44f4 commit 62eb333
Show file tree
Hide file tree
Showing 299 changed files with 19,525 additions and 7,686 deletions.
2 changes: 1 addition & 1 deletion src/HASS.Agent/API/ApiConfiguration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public void ConfigureServices(IServiceCollection services)

public void ConfigureServer(IRestServer server)
{
server.Prefixes.Add($"http://+:{Variables.AppSettings.NotifierApiPort}/");
server.Prefixes.Add($"http://+:{Variables.AppSettings.LocalApiPort}/");
server.Router.Options.SendExceptionMessages = true;
}
}
Expand Down
1 change: 1 addition & 0 deletions src/HASS.Agent/API/ApiDeserialization.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Text.Json;

namespace HASS.Agent.API
Expand Down
24 changes: 23 additions & 1 deletion src/HASS.Agent/API/ApiEndpoints.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
using Grapevine;
using System.Text.Json;
using Grapevine;
using HASS.Agent.Enums;
using HASS.Agent.Extensions;
using HASS.Agent.Managers;
using HASS.Agent.Media;
using HASS.Agent.Models.HomeAssistant;
using HASS.Agent.MQTT;
using Serilog;
using HttpMethod = System.Net.Http.HttpMethod;

Expand All @@ -14,6 +16,26 @@ namespace HASS.Agent.API
/// </summary>
public class ApiEndpoints : ApiDeserialization
{
/// <summary>
/// Info routes, provides device info on /info
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public static async Task DeviceInfoRoute(IHttpContext context)
{
context.Response.ContentType = "application/json";
await context.Response.SendResponseAsync(JsonSerializer.Serialize(new
{
serial_number = Variables.SerialNumber,
device = Variables.DeviceConfig,
apis = new
{
notifications = Variables.AppSettings.NotificationsEnabled,
media_player = Variables.AppSettings.MediaPlayerEnabled
}
}, MqttManager.JsonSerializerOptions));
}

/// <summary>
/// Notification route, handles all incoming notifications on '/notify'
/// </summary>
Expand Down
92 changes: 90 additions & 2 deletions src/HASS.Agent/API/ApiManager.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http;
using System.Text;
using Grapevine;
using HASS.Agent.Resources.Localization;
using HASS.Agent.Shared.Enums;
using HASS.Agent.Shared.Functions;
using HASS.Agent.Shared.Managers;
using Serilog;

#pragma warning disable CA1416 // Validate platform compatibility
Expand Down Expand Up @@ -58,6 +60,10 @@ internal static void Initialize()
await ctx.Response.SendResponseAsync("HASS.Agent Active");
}, "Get", "/", true, "RootEndpoint"));

// info route
var deviceInfoRoute = new Route(ApiEndpoints.DeviceInfoRoute, "Get", "/info", true, "DeviceInfoRoute");
s.Router.Register(deviceInfoRoute);

// notification route
var notifyRoute = new Route(ApiEndpoints.NotifyRoute, "Post", "/notify", true, "NotifyRoute");
s.Router.Register(notifyRoute);
Expand Down Expand Up @@ -169,7 +175,7 @@ internal static async Task<bool> ExecutePortReservationAsync(int port)
{
Log.Information("[LOCALAPI] Executing port reservation for port: {port}", port);

var args = $"http add urlacl url=http://+:{port}/ user=\"{Environment.UserDomainName}\\{Environment.UserName}\"";
var args = $"http add urlacl url=http://+:{port}/ user=\"{SharedHelperFunctions.EveryoneLocalizedAccountName()}\"";
var executionResult = await CommandLineManager.ExecuteCommandAsync("netsh", args, TimeSpan.FromMinutes(2));

// capture normal and error output
Expand All @@ -183,7 +189,7 @@ internal static async Task<bool> ExecutePortReservationAsync(int port)
Log.Information("[LOCALAPI] Port reservation succesfully added");
return true;
}

// check for known errors
if (output.Contains(": 183") || errOutput.Contains(": 183"))
{
Expand Down Expand Up @@ -239,6 +245,88 @@ internal static async Task<bool> ExecutePortReservationAsync(int port)
return false;
}
}

/// <summary>
/// Attempt to remove HTTP port reservation (requires elevation!)
/// </summary>
/// <returns></returns>
[SuppressMessage("ReSharper", "InvertIf")]
internal static async Task<bool> RemovePortReservationAsync(int port)
{
try
{
Log.Information("[LOCALAPI] Removing port reservation for port: {port}", port);

var args = $"http delete urlacl url=http://+:{port}/";
var executionResult = await CommandLineManager.ExecuteCommandAsync("netsh", args, TimeSpan.FromMinutes(2));

// capture normal and error output
var output = executionResult.Output.Trim();
var errOutput = executionResult.ErrorOutput.Trim();
var exitCode = executionResult.ExitCode;

// all good?
if (exitCode == 0)
{
Log.Information("[LOCALAPI] Port reservation succesfully removed");
return true;
}

// check for known errors
if (output.Contains(": 2") || errOutput.Contains(": 2"))
{
Log.Information("[LOCALAPI] Port reservation already removed, nothing to do");
return true;
}
if (output.Contains(": 5") || errOutput.Contains(": 5"))
{
Log.Error("[LOCALAPI] Port reservation failed, requires elevation");
return false;
}
if (output.Contains(": 1332") || errOutput.Contains(": 1332"))
{
Log.Error("[LOCALAPI] Port reservation failed, incorrect parameters provided: {param}", args);
return false;
}

// nope, something went wrong
Log.Error("[LOCALAPI] Execution failed, port reservation removal probably failed - exitcode: {code}", exitCode);

// process & print normal output
if (!string.IsNullOrEmpty(output))
{
var consoleLog = new StringBuilder();

consoleLog.AppendLine("[LOCALAPI] Console output:");
consoleLog.AppendLine("");
consoleLog.AppendLine(output);
consoleLog.AppendLine("");

Log.Information(consoleLog.ToString());
}

// process & print error output
if (!string.IsNullOrEmpty(errOutput))
{
var consoleErrLog = new StringBuilder();

consoleErrLog.AppendLine("[LOCALAPI] Error output:");
consoleErrLog.AppendLine("");
consoleErrLog.AppendLine(errOutput);
consoleErrLog.AppendLine("");

Log.Error(consoleErrLog.ToString());
}

// done
return false;
}
catch (Exception ex)
{
Log.Fatal("[LOCALAPI] Error while removing port reservation: {msg}", ex.Message);
return false;
}
}
}
}
#pragma warning restore CA1416 // Validate platform compatibility
31 changes: 31 additions & 0 deletions src/HASS.Agent/Commands/CommandsManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@ internal static class CommandsManager
/// </summary>
internal static async void Initialize()
{
// is mqtt enabled?
if (!Variables.AppSettings.MqttEnabled)
{
Variables.MainForm?.SetCommandsStatus(ComponentStatus.Stopped);
return;
}

// wait while mqtt's connecting
while (Variables.MqttManager.GetStatus() == MqttStatus.Connecting) await Task.Delay(250);

Expand Down Expand Up @@ -390,6 +397,22 @@ internal static void LoadCommandInfo()

// =================================

commandInfoCard = new CommandInfoCard(CommandType.MonitorSleepCommand,
Languages.CommandsManager_MonitorSleepCommandDescription,
true, false, false);

CommandInfoCards.Add(commandInfoCard.CommandType, commandInfoCard);

// =================================

commandInfoCard = new CommandInfoCard(CommandType.MonitorWakeCommand,
Languages.CommandsManager_MonitorWakeCommandDescription,
true, false, false);

CommandInfoCards.Add(commandInfoCard.CommandType, commandInfoCard);

// =================================

commandInfoCard = new CommandInfoCard(CommandType.MultipleKeysCommand,
Languages.CommandsManager_MultipleKeysCommandDescription,
true, false, false);
Expand Down Expand Up @@ -430,6 +453,14 @@ internal static void LoadCommandInfo()

// =================================

commandInfoCard = new CommandInfoCard(CommandType.SetVolumeCommand,
Languages.CommandsManager_SetVolumeCommandDescription,
true, true, true);

CommandInfoCards.Add(commandInfoCard.CommandType, commandInfoCard);

// =================================

commandInfoCard = new CommandInfoCard(CommandType.ShutdownCommand,
Languages.CommandsManager_ShutdownCommandDescription,
true, true, false);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Diagnostics;
using System.IO;
using HASS.Agent.Resources.Localization;
using Serilog;
using Syncfusion.Windows.Forms;
Expand Down
Loading

0 comments on commit 62eb333

Please sign in to comment.