Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add deviceconfigvalidator #56

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 73 additions & 93 deletions OpenIPC_Config/App.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,53 @@ public override void OnFrameworkInitializationCompleted()

base.OnFrameworkInitializationCompleted();
}

private string GetConfigPath()
{
var appName = Assembly.GetExecutingAssembly().GetName().Name;
string configPath;

if (OperatingSystem.IsAndroid() || OperatingSystem.IsIOS() || OperatingSystem.IsMacOS())
{
var configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), appName);
if (!Directory.Exists(configDirectory))
Directory.CreateDirectory(configDirectory);

configPath = Path.Combine(configDirectory, "appsettings.json");
}
else if (OperatingSystem.IsWindows())
{
var configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), appName);
if (!Directory.Exists(configDirectory))
Directory.CreateDirectory(configDirectory);

configPath = Path.Combine(configDirectory, "appsettings.json");
}
else // Assume Linux
{
var configDirectory = Path.Combine($"./config/{appName}");
if (!Directory.Exists(configDirectory))
Directory.CreateDirectory(configDirectory);

configPath = Path.Combine(configDirectory, "appsettings.json");
}

return configPath;
}

private void CreateAppSettings()
{
var configPath = GetConfigPath();

// Create default settings if not present
if (!File.Exists(configPath))
{
var defaultSettings = createDefaultAppSettings();
File.WriteAllText(configPath, defaultSettings.ToString());
Log.Information($"Default appsettings.json created at {configPath}");
}
}


private void ConfigureServices(IServiceCollection services)
{
Expand All @@ -63,11 +110,19 @@ private void ConfigureServices(IServiceCollection services)
services.AddSingleton<IEventSubscriptionService, EventSubscriptionService>();
services.AddSingleton<ISshClientService, SshClientService>();
services.AddSingleton<IMessageBoxService, MessageBoxService>();

services.AddSingleton<IYamlConfigService, YamlConfigService>();
services.AddSingleton<ILogger>(sp => Log.Logger);

// Load the configuration
var configPath = GetConfigPath();
var configuration = new ConfigurationBuilder()
.AddJsonFile(configPath, optional: false, reloadOnChange: true)
.Build();

// Register IConfiguration
services.AddSingleton<IConfiguration>(configuration);
services.AddTransient<DeviceConfigValidator>();

// Register ViewModels
services.AddTransient<MainViewModel>();

Expand Down Expand Up @@ -96,103 +151,20 @@ private void ConfigureServices(IServiceCollection services)

}

private async void CreateAppSettings()
{
string configPath;
string configDirectory;

var appName = Assembly.GetExecutingAssembly().GetName().Name;
Log.Information($"Application name: {appName}, running on {RuntimeInformation.OSDescription}");
if (OperatingSystem.IsAndroid())
{
// Android-specific path
configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
appName);
configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
appName, "appsettings.json");
}
else if (OperatingSystem.IsIOS())
{
configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
appName);
configPath = Path.Combine(configDirectory, "appsettings.json");
}
else if (OperatingSystem.IsWindows())
{
configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
appName);
configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
appName,
"appsettings.json");
}
else if (OperatingSystem.IsMacOS())
{
configDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
appName);
configPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
appName,
"appsettings.json");
}
else // Assume Linux
{
configDirectory = Path.Combine($"./config/{appName}");
configPath = Path.Combine($"./config/{appName}", "appsettings.json");
}

if (!Directory.Exists(configDirectory))
Directory.CreateDirectory(configDirectory);

// Check if appsettings.json exists, otherwise create a default one
if (!File.Exists(configPath))
{
// Create default settings
var defaultSettings = createDefaultAppSettings();

File.WriteAllText(configPath, defaultSettings.ToString());

await Task.Delay(2000); // Non-blocking pause


Log.Information($"Default appsettings.json created at {configPath}");
}


var configuration = new ConfigurationBuilder()
.AddJsonFile(configPath, false, true)
.AddJsonFile("appsettings.json", true, true)
// .AddJsonFile("appsettings.Development.json", Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development")
// .AddJsonFile(
// $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json",
// true)
.Build();

Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(configuration)
.WriteTo.Sink(new EventAggregatorSink(ServiceProvider.GetRequiredService<IEventAggregator>()))
.CreateLogger();

Log.Information(
"**********************************************************************************************");
Log.Information($"Starting up log for OpenIPC Configurator v{VersionHelper.GetAppVersion()}");
Log.Information($"Using appsettings.json from {configPath}");
// Log.Logger = new LoggerConfiguration()
// .MinimumLevel.Debug()
// .WriteTo.Sink(new EventAggregatorSink(EventAggregator))
// //.ReadFrom.Configuration(configuration)
// .ReadFrom.AppSettings()
// .CreateLogger();


}


private JObject createDefaultAppSettings()
{
// Create default settings
var defaultSettings = new JObject(
new JProperty("UpdateChecker",
new JObject(
new JProperty("LatestJsonUrl", "https://github.com/OpenIPC/openipc-configurator/releases/latest/download/latest.json")
)
),
new JProperty("Serilog",
new JObject(
new JProperty("Using", new JArray("Serilog.Sinks.Console", "Serilog.Sinks.RollingFile")),
new JProperty("MinimumLevel", "Debug"),
new JProperty("MinimumLevel", "Verbose"),
new JProperty("WriteTo",
new JArray(
new JObject(
Expand All @@ -203,8 +175,7 @@ private JObject createDefaultAppSettings()
new JProperty("Args",
new JObject(
new JProperty("pathFormat",
$"{Models.OpenIPC.AppDataConfigDirectory}/Logs/configurator-{{Date}}.log")

$"{Models.OpenIPC.AppDataConfigDirectory}/Logs/configurator-{{Date}}.log")
)
)
)
Expand All @@ -216,8 +187,17 @@ private JObject createDefaultAppSettings()
)
)
)
),
new JProperty("DeviceHostnameMapping",
new JObject(
new JProperty("Camera", new JArray("openipc-ssc338q","openipc-ssc330")),
new JProperty("Radxa", new JArray("radxa", "raspberrypi")),
new JProperty("NVR", new JArray("openipc-hi3536dv100"))
)
)
);

return defaultSettings;
}

}
35 changes: 35 additions & 0 deletions OpenIPC_Config/Services/DeviceConfigValidator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using OpenIPC_Config.Models;

namespace OpenIPC_Config.Services;

public class DeviceConfigValidator
{
private readonly IConfiguration _configuration;
private readonly Dictionary<DeviceType, List<string>> _deviceHostnameMapping;

public DeviceConfigValidator(IConfiguration configuration)
{
_configuration = configuration;

_deviceHostnameMapping = _configuration.GetSection("DeviceHostnameMapping")
.Get<Dictionary<DeviceType, List<string>>>()
?? new Dictionary<DeviceType, List<string>>();
}

public bool IsDeviceConfigValid(DeviceConfig deviceConfig)
{
if (_deviceHostnameMapping.TryGetValue(deviceConfig.DeviceType, out var allowedHostnames))
{
return allowedHostnames.Any(hostname => deviceConfig.Hostname.Contains(hostname));
}

return false; // Invalid if no mapping exists
}
}

21 changes: 19 additions & 2 deletions OpenIPC_Config/ViewModels/ConnectControlsViewModel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using MsBox.Avalonia;
using MsBox.Avalonia.Enums;
using OpenIPC_Config.Events;
Expand Down Expand Up @@ -239,8 +240,8 @@ private async void Connect()
return;
}

if ((_deviceConfig.Hostname.Contains("radxa") && _deviceConfig.DeviceType != DeviceType.Radxa) ||
(_deviceConfig.Hostname.Contains("openipc") && _deviceConfig.DeviceType != DeviceType.Camera))
var validator = App.ServiceProvider.GetRequiredService<DeviceConfigValidator>();
if (!validator.IsDeviceConfigValid(_deviceConfig))
{
UpdateUIMessage("Hostname Error!");
var msBox = MessageBoxManager.GetMessageBoxStandard("Hostname Error!",
Expand All @@ -254,6 +255,22 @@ private async void Connect()
return;
}
}

// if ((_deviceConfig.Hostname.Contains("radxa") && _deviceConfig.DeviceType != DeviceType.Radxa) ||
// (_deviceConfig.Hostname.Contains("openipc") && _deviceConfig.DeviceType != DeviceType.Camera))
// {
// UpdateUIMessage("Hostname Error!");
// var msBox = MessageBoxManager.GetMessageBoxStandard("Hostname Error!",
// $"Hostname does not match device type! \nHostname: {_deviceConfig.Hostname} Device Type: {_selectedDeviceType}.\nPlease check device..\nOk to continue anyway\nCancel to quit",
// ButtonEnum.OkCancel);
//
// var result = await msBox.ShowAsync();
// if (result == ButtonResult.Cancel)
// {
// Log.Debug("Device selection and hostname mismatch, stopping");
// return;
// }
// }

// Save the config to app settings
SaveConfig();
Expand Down
Loading