Add Authentication stuff

This commit is contained in:
Stone_Red
2023-06-13 22:28:00 +02:00
parent 996cf987c6
commit 9ac40ba0cb
9 changed files with 437 additions and 429 deletions
@@ -1 +0,0 @@

@@ -1,4 +1,5 @@
<Bar Breakpoint="Breakpoint.Desktop" NavigationBreakpoint="Breakpoint.Tablet" ThemeContrast="ThemeContrast.Dark" @using Elektrifikatsiya.Models;
<Bar Breakpoint="Breakpoint.Desktop" NavigationBreakpoint="Breakpoint.Tablet" ThemeContrast="ThemeContrast.Dark"
Mode="BarMode.VerticalInline" CollapseMode="BarCollapseMode.Small"> Mode="BarMode.VerticalInline" CollapseMode="BarCollapseMode.Small">
<BarToggler TextColor="TextColor.Primary" /> <BarToggler TextColor="TextColor.Primary" />
<BarBrand> <BarBrand>
@@ -15,14 +16,18 @@
<BarLink To="/" TextColor="TextColor.White"> <BarLink To="/" TextColor="TextColor.White">
<BarIcon Style="color:white" IconName="IconName.Dashboard" /> <BarIcon Style="color:white" IconName="IconName.Dashboard" />
Dashboard Dashboard
</BarLink>
</BarItem>
<BarItem>
<BarLink To="/admin" TextColor="TextColor.White">
<BarIcon Style="color:white" IconName="IconName.ShieldAlt" />
Admin
</BarLink> </BarLink>
</BarItem> </BarItem>
<Protected RequiredRole="Role.Admin">
<Authorized>
<BarItem>
<BarLink To="/admin" TextColor="TextColor.White">
<BarIcon Style="color:white" IconName="IconName.ShieldAlt" />
Admin
</BarLink>
</BarItem>
</Authorized>
</Protected>
<BarItem> <BarItem>
<BarLink To="/settings" TextColor="TextColor.White"> <BarLink To="/settings" TextColor="TextColor.White">
<BarIcon Style="color:white" IconName="IconName.Wrench" /> <BarIcon Style="color:white" IconName="IconName.Wrench" />
@@ -1,5 +1,6 @@
@page "/Admin" @page "/Admin"
@using Blazorise.Components; @using Blazorise.Components;
@using Elektrifikatsiya.Components
@using Elektrifikatsiya.Models; @using Elektrifikatsiya.Models;
@using System.Net @using System.Net
@using Elektrifikatsiya.Services; @using Elektrifikatsiya.Services;
@@ -10,190 +11,193 @@
@inject IMessageService MessageService @inject IMessageService MessageService
@inject IAuthenticationService AuthenthicationService; @inject IAuthenticationService AuthenthicationService;
@inject NavigationManager NavigationManager; @inject NavigationManager NavigationManager;
<Div>
<Row Style="width: 100%; height: 100%" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
<Div Display="Display.Flex.Row.OnDesktop" Margin=" Margin.Is3.FromBottom" Width="Width.Is100"> <Protected RequiredRole="Role.Admin">
<Column ColumnSize="ColumnSize.Is5.OnDesktop.Is12.OnMobile"> <Authorized>
<Bar Breakpoint="Breakpoint.Desktop" <Div>
Background="Background.White" <Row Style="width: 100%; height: 100%" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
ThemeContrast="ThemeContrast.None" <Div Display="Display.Flex.Row.OnDesktop" Margin=" Margin.Is3.FromBottom" Width="Width.Is100">
Shadow="Shadow.Remove" <Column ColumnSize="ColumnSize.Is5.OnDesktop.Is12.OnMobile">
Border="Border.Is1.RoundedTop"> <Bar Breakpoint="Breakpoint.Desktop"
<BarBrand> Background="Background.White"
<Column ColumnSize="ColumnSize.Is12"> ThemeContrast="ThemeContrast.None"
Users Shadow="Shadow.Remove"
</Column> Border="Border.Is1.RoundedTop">
<Column ColumnSize="ColumnSize.Is12.Is11.WithOffset.OnDesktop.IsAuto.OnMobile"> <BarBrand>
<Button Clicked="@ShowModalAddUser" TextAlignment="TextAlignment.End" Shadow="Shadow.Remove"> <Column ColumnSize="ColumnSize.Is12">
<BarIcon IconName="IconName.Add"></BarIcon> Users
</Button>
</Column>
</BarBrand>
</Bar>
<ListView TItem="User"
Data="@users"
TextField="@((_)=>(""))"
ValueField="@((_)=>(""))"
Style="border-radius: 0px 0px"
Height="100%"
MaxHeight="90%">
<ItemTemplate>
<ListGroupItem Border="Border.OnBottom">
<Row>
<Column ColumnSize="ColumnSize.Is6">
<Row>
<Column ColumnSize="ColumnSize.Is7">
<Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading>
</Column>
</Row>
<Row>
<Column>
<Small>Name: @context.Item.Name</Small>
<br />
<Small>Rolle: @context.Item.Role</Small>
<br />
<Small>E-Mail: @context.Item.Email</Small>
</Column>
</Row>
</Column> </Column>
<Column ColumnSize="ColumnSize.Is12.Is11.WithOffset.OnDesktop.IsAuto.OnMobile">
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is7.OnMobile"> <Button Clicked="@ShowModalAddUser" TextAlignment="TextAlignment.End" Shadow="Shadow.Remove">
<Button @onclick="() => Delete(context.Item)" class="btn1" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Outline> <BarIcon IconName="IconName.Add"></BarIcon>
<BarIcon IconName="IconName.Delete" />
</Button> </Button>
<style>
.btn1:hover {
background: #E50000;
}
</style>
<Modal @ref="modalRefAddUser">
<ModalContent Centered>
<ModalHeader>
<ModalTitle>Add User</ModalTitle>
<CloseButton />
</ModalHeader>
<ModalBody>
<Field>
<FieldLabel>User Name</FieldLabel>
<TextEdit @ref="modalAddUserName" Placeholder="Enter new name..." />
</Field>
<Field>
<FieldLabel>User E-Mail</FieldLabel>
<TextEdit @ref="modalAddUserEmail" Placeholder="Enter new E-mail..." />
</Field>
<Field>
<FieldLabel>User Password</FieldLabel>
<TextEdit @ref="modalAddUserPW" Placeholder="Enter new password..." />
</Field>
</ModalBody>
<ModalFooter>
<Button Color="Color.Secondary" style="border-bottom-left-radius: 3px; border-bottom-right-radius: 3px" Clicked="@HideModalAddUser">Close</Button>
<Button Color="Color.Primary" style="border-bottom-left-radius: 0px; border-bottom-right-radius: 0" Clicked="@AddButtonPressed">Add</Button>
</ModalFooter>
</ModalContent>
</Modal>
</Column> </Column>
</BarBrand>
</Bar>
<ListView TItem="User"
Data="@users"
TextField="@((_)=>(""))"
ValueField="@((_)=>(""))"
Style="border-radius: 0px 0px"
Height="100%"
MaxHeight="90%">
<ItemTemplate>
<ListGroupItem Border="Border.OnBottom">
<Row>
<Column ColumnSize="ColumnSize.Is6">
<Row>
<Column ColumnSize="ColumnSize.Is7">
<Heading Size="HeadingSize.Is6" Margin="Margin.Is1.FromBottom">@context.Item.Name</Heading>
</Column>
</Row>
<Row>
<Column>
<Small>Name: @context.Item.Name</Small>
<br />
<Small>Rolle: @context.Item.Role</Small>
<br />
<Small>E-Mail: @context.Item.Email</Small>
</Column>
</Row>
</Column>
<Column ColumnSize="ColumnSize.Is4.OnDesktop.Is7.OnMobile">
<Button @onclick="() => Delete(context.Item)" class="btn1" Position="Position.Absolute.Top.Is50.Start.Is50.Translate.Middle" Color="Color.Dark" Outline>
<BarIcon IconName="IconName.Delete" />
</Button>
<style>
.btn1:hover {
background: #E50000;
}
</style>
<Modal @ref="modalRefAddUser">
<ModalContent Centered>
<ModalHeader>
<ModalTitle>Add User</ModalTitle>
<CloseButton />
</ModalHeader>
<ModalBody>
<Field>
<FieldLabel>User Name</FieldLabel>
<TextEdit @ref="modalAddUserName" Placeholder="Enter new name..." />
</Field>
<Field>
<FieldLabel>User E-Mail</FieldLabel>
<TextEdit @ref="modalAddUserEmail" Placeholder="Enter new E-mail..." />
</Field>
<Field>
<FieldLabel>User Password</FieldLabel>
<TextEdit @ref="modalAddUserPW" Placeholder="Enter new password..." />
</Field>
</ModalBody>
<ModalFooter>
<Button Color="Color.Secondary" style="border-bottom-left-radius: 3px; border-bottom-right-radius: 3px" Clicked="@HideModalAddUser">Close</Button>
<Button Color="Color.Primary" style="border-bottom-left-radius: 0px; border-bottom-right-radius: 0" Clicked="@AddButtonPressed">Add</Button>
</ModalFooter>
</ModalContent>
</Modal>
</Column>
<br />
<br />
<Row>
<Column ColumnSize="ColumnSize.Is1.OnDesktop">
<Button @onclick="() => Toggle(context.Item)" Position="Position.Absolute.Top.Is50.Start.Is100.Translate.Middle" Color="Color.Dark" Outline>
<BarIcon IconName="IconName.Pen" />
</Button>
</Column>
</Row>
</Row>
</ListGroupItem>
</ItemTemplate>
</ListView>
</Column>
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12.OnMobile" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile">
@if (SelectedUser is not null)
{
<Div hidden="@hideButtonSettings">
<Field>
<FieldLabel>
<h2>
User Settings
</h2>
</FieldLabel>
</Field>
<Field>
<FieldLabel>
<h5>
User Name
</h5>
<Paragraph>
Here you can change the name of the User
</Paragraph>
</FieldLabel>
<TextEdit @bind-Text="@SelectedUser.Name" Placeholder="Enter User Name" />
</Field>
<br /> <br />
<br /> <br />
<Row> <Field>
<Column ColumnSize="ColumnSize.Is1.OnDesktop"> <FieldLabel>
<Button @onclick="() => Toggle(context.Item)" Position="Position.Absolute.Top.Is50.Start.Is100.Translate.Middle" Color="Color.Dark" Outline> <h5>
<BarIcon IconName="IconName.Pen" /> E-Mail
</Button> </h5>
</Column> <Paragraph>
</Row> Here you can change the E-Mail of a User
</Paragraph>
</Row> </FieldLabel>
</ListGroupItem> <TextEdit @bind-Text="@SelectedUser.Email" Placeholder="Enter new email" />
</ItemTemplate> </Field>
</ListView> <br />
</Column> <Field>
<Column ColumnSize="ColumnSize.Is6.OnDesktop.Is12.OnMobile" Margin="Margin.Is3.FromTop.OnMobile" Padding="Padding.Is4.FromStart.OnMobile"> <FieldLabel>
@if (SelectedUser is not null) <h5>
{ Password
<Div hidden="@hideButtonSettings"> </h5>
<Field> <Paragraph>
<FieldLabel> Here you can change the password of a User
<h2> </Paragraph>
User Settings </FieldLabel>
</h2> <TextEdit Placeholder="Enter old password" />
</FieldLabel> <br />
</Field> <TextEdit Placeholder="Enter new password" />
<Field> </Field>
<FieldLabel> <br />
<h5> <br />
User Name <Field>
</h5> <FieldLabel>
<Paragraph> <h5>
Here you can change the name of the User Select Role
</Paragraph> </h5>
</FieldLabel> <Paragraph>
<TextEdit @bind-Text="@SelectedUser.Name" Placeholder="Enter User Name" /> Here you select or change the role of to User or Admin
</Field> </Paragraph>
<br /> </FieldLabel>
<br /> <br />
<Field> <Dropdown Display="Display.InlineBlock">
<FieldLabel> <DropdownToggle Color="Color.Primary" Width="Width.Is100">Roles</DropdownToggle>
<h5> <DropdownMenu>
E-Mail <DropdownItem>Admin</DropdownItem>
</h5> <DropdownDivider />
<Paragraph> <DropdownItem>User</DropdownItem>
Here you can change the E-Mail of a User </DropdownMenu>
</Paragraph> </Dropdown>
</FieldLabel> </Field>
<TextEdit @bind-Text="@SelectedUser.Email" Placeholder="Enter new email" /> <Column ColumnSize="ColumnSize.IsFull" TextAlignment="TextAlignment.End">
</Field> <Button Color="Color.Primary">Save</Button>
<br /> </Column>
<Field> </Div>
<FieldLabel> }
<h5> </Column>
Password </Div>
</h5> </Row>
<Paragraph>
Here you can change the password of a User
</Paragraph>
</FieldLabel>
<TextEdit Placeholder="Enter old password" />
<br />
<TextEdit Placeholder="Enter new password" />
</Field>
<br />
<br />
<Field>
<FieldLabel>
<h5>
Select Role
</h5>
<Paragraph>
Here you select or change the role of to User or Admin
</Paragraph>
</FieldLabel>
<br />
<Dropdown Display="Display.InlineBlock">
<DropdownToggle Color="Color.Primary" Width="Width.Is100">Roles</DropdownToggle>
<DropdownMenu>
<DropdownItem>Admin</DropdownItem>
<DropdownDivider />
<DropdownItem>User</DropdownItem>
</DropdownMenu>
</Dropdown>
</Field>
<Column ColumnSize="ColumnSize.IsFull" TextAlignment="TextAlignment.End">
<Button Color="Color.Primary">Save</Button>
</Column>
</Div>
}
</Column>
</Div> </Div>
</Row> </Authorized>
</Div> <NotAuthorized>
Bro no! this page is only for admins! 😠
</NotAuthorized>
</Protected>
@code { @code {
List<User> users = new List<User>(); List<User> users = new List<User>();
@@ -12,6 +12,7 @@
@inject IDeviceStatusService DeviceStatusService; @inject IDeviceStatusService DeviceStatusService;
@inject IDeviceManagmentService DeviceManagmentService; @inject IDeviceManagmentService DeviceManagmentService;
@inject IEventService EventService; @inject IEventService EventService;
@inject IAuthenticationService AuthenticationService;
@inject IEnergyPriceService EnergyPriceService; @inject IEnergyPriceService EnergyPriceService;
@inject MainDatabaseContext MainDatabaseContext; @inject MainDatabaseContext MainDatabaseContext;
@@ -8,94 +8,94 @@ namespace Elektrifikatsiya.Pages;
public partial class Dashboard public partial class Dashboard
{ {
private readonly List<string> labels = new List<string>(); private readonly List<string> labels = new List<string>();
//TODO: insert new event here if plug produces one //TODO: insert new event here if plug produces one
private List<Event> events = new List<Event>() { new Event("Text", "Text", DateTime.Today, null) }; private List<Event> events = new List<Event>() { new Event("Text", "Text", DateTime.Today, null) };
//code for graph //code for graph
private LineChart<double> lineChart; private LineChart<double> lineChart;
//TODO: insert new Device here if user adds one //TODO: insert new Device here if user adds one
private List<Device> plugs = new List<Device>(); private List<Device> plugs = new List<Device>();
protected override async Task OnAfterRenderAsync(bool firstRender) protected override async Task OnAfterRenderAsync(bool firstRender)
{ {
if (firstRender) if (firstRender)
{ {
await HandleRedraw(); await HandleRedraw();
} }
} }
protected override void OnInitialized() protected override async Task OnInitializedAsync()
{ {
plugs = DeviceStatusService.GetDevices().ValueOrDefault ?? new List<Device>(); plugs = DeviceManagmentService.GetDevices((await AuthenticationService.GetUserAsync()).ValueOrDefault).ValueOrDefault ?? new List<Device>();
events = EventService.Events; events = EventService.Events;
EventService.OnEventCalled += (__, e) => EventService.OnEventCalled += (__, e) =>
{ {
_ = InvokeAsync(StateHasChanged); _ = InvokeAsync(StateHasChanged);
}; };
DeviceStatusService.OnDeviceStatusChanged += (__, e) => DeviceStatusService.OnDeviceStatusChanged += (__, e) =>
{ {
_ = InvokeAsync(StateHasChanged); _ = InvokeAsync(StateHasChanged);
}; };
} }
private async Task<List<double>> GetData() private async Task<List<double>> GetData()
{ {
if (plugs.Count == 0) if (plugs.Count == 0)
{ {
return new(); return new();
} }
PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090"); PrometheusQuery promQueryer = new PrometheusQuery("http://localhost:9090");
string plugnames = ""; string plugnames = "";
foreach (Device device in plugs) foreach (Device device in plugs)
{ {
plugnames += $"shellyplug-s-{device.MacAddress}/relay/0|"; plugnames += $"shellyplug-s-{device.MacAddress}/relay/0|";
} }
plugnames = plugnames[0..^1]; plugnames = plugnames[0..^1];
double energyPrice = MainDatabaseContext.EnergyPriceChanges.OrderByDescending(e => e.DateTime).FirstOrDefault()?.EnergyPrice ?? 0; double energyPrice = MainDatabaseContext.EnergyPriceChanges.OrderByDescending(e => e.DateTime).FirstOrDefault()?.EnergyPrice ?? 0;
PrometheusDataWrapper? deviceData = (await promQueryer.Query($$"""sum(power{sensor=~"{{plugnames}}"})[1h:1m]"""))?.Data; PrometheusDataWrapper? deviceData = (await promQueryer.Query($$"""sum(power{sensor=~"{{plugnames}}"})[1h:1m]"""))?.Data;
//PrometheusDataWrapper? priceData = (await promQueryer.Query($$"""sum(sum_over_time(power{sensor=~"{{plugnames}}"}[1y])*{{energyPrice}})"""))?.Data; //PrometheusDataWrapper? priceData = (await promQueryer.Query($$"""sum(sum_over_time(power{sensor=~"{{plugnames}}"}[1y])*{{energyPrice}})"""))?.Data;
//Console.WriteLine(priceData.VectorTypeToTimestampFloatTuple()); //Console.WriteLine(priceData.VectorTypeToTimestampFloatTuple());
Random r = new Random(DateTime.Now.Millisecond); Random r = new Random(DateTime.Now.Millisecond);
return deviceData?.MatrixTypeToTimestampFloatTuple().ValueOrDefault?.Select(x => return deviceData?.MatrixTypeToTimestampFloatTuple().ValueOrDefault?.Select(x =>
{ {
labels.Add(DateTimeOffset.FromUnixTimeSeconds(long.Parse($"1{x.Item1}0")).UtcDateTime.ToLocalTime().ToShortTimeString()); labels.Add(DateTimeOffset.FromUnixTimeSeconds(long.Parse($"1{x.Item1}0")).UtcDateTime.ToLocalTime().ToShortTimeString());
return x.Item2; return x.Item2;
}).ToList() ?? new List<double>(); }).ToList() ?? new List<double>();
} }
//TODO: insert dataset of current and last voltage usages //TODO: insert dataset of current and last voltage usages
private async Task<LineChartDataset<double>> GetLineChartDataset() private async Task<LineChartDataset<double>> GetLineChartDataset()
{ {
return new LineChartDataset<double> return new LineChartDataset<double>
{ {
Label = "Wattage", Label = "Wattage",
Data = await GetData(), Data = await GetData(),
Fill = true, Fill = true,
PointRadius = 3, PointRadius = 3,
CubicInterpolationMode = "monotone", CubicInterpolationMode = "monotone",
}; };
} }
private async Task HandleRedraw() private async Task HandleRedraw()
{ {
labels.Clear(); labels.Clear();
await lineChart.Clear(); await lineChart.Clear();
await lineChart.AddLabelsDatasetsAndUpdate(labels, await GetLineChartDataset()); await lineChart.AddLabelsDatasetsAndUpdate(labels, await GetLineChartDataset());
} }
private async Task Switch(Device device) private async Task Switch(Device device)
{ {
device.Enabled = !device.Enabled; device.Enabled = !device.Enabled;
_ = await DeviceManagmentService.UpdateDevice(device); _ = await DeviceManagmentService.UpdateDevice(device);
} }
} }
@@ -10,6 +10,7 @@
@inject IDeviceManagmentService DeviceManagmentService @inject IDeviceManagmentService DeviceManagmentService
@inject IMessageService MessageService @inject IMessageService MessageService
@inject IAuthenticationService AuthenticationService
@inject MainDatabaseContext MainDatabaseContext @inject MainDatabaseContext MainDatabaseContext
<Div> <Div>
@@ -157,9 +158,9 @@
Device? SelectedDevice = null; Device? SelectedDevice = null;
Device? DeviceCopy = null; Device? DeviceCopy = null;
protected override void OnInitialized() protected override async Task OnInitializedAsync()
{ {
Result<List<Device>> getDevicesResult = DeviceManagmentService.GetDevices(); Result<List<Device>> getDevicesResult = DeviceManagmentService.GetDevices((await AuthenticationService.GetUserAsync()).ValueOrDefault);
if (getDevicesResult.IsSuccess) if (getDevicesResult.IsSuccess)
{ {
@@ -8,17 +8,17 @@ namespace Elektrifikatsiya.Services;
public interface IDeviceManagmentService public interface IDeviceManagmentService
{ {
public Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default"); public Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default");
public Task<Result> UnregisterDevice(string macAdress); public Task<Result> UnregisterDevice(string macAdress);
public Result<Device> GetDevice(string macAdress); public Result<Device> GetDevice(string macAdress);
public Result<List<Device>> GetDevices(); public Result<List<Device>> GetDevices(User user);
public Result<List<Device>> GetDevicesInRoom(string room); public Result<List<Device>> GetDevicesInRoom(string room);
public Result<List<Device>> GetDevicesOfUser(int userId); public Result<List<Device>> GetDevicesOfUser(int userId);
public Task<Result> UpdateDevice(Device device); public Task<Result> UpdateDevice(Device device);
} }
@@ -15,168 +15,168 @@ namespace Elektrifikatsiya.Services.Implementations;
public class DeviceManagmentService : IDeviceManagmentService public class DeviceManagmentService : IDeviceManagmentService
{ {
private readonly IServiceScopeFactory serviceScopeFactory; private readonly IServiceScopeFactory serviceScopeFactory;
private readonly IDeviceStatusService deviceStatusService; private readonly IDeviceStatusService deviceStatusService;
private readonly ILogger<DeviceManagmentService> logger; private readonly ILogger<DeviceManagmentService> logger;
private readonly IHiveMQClient hiveMQClient; private readonly IHiveMQClient hiveMQClient;
private readonly HttpClient httpClient; private readonly HttpClient httpClient;
public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, IHiveMQClient hiveMQClient, HttpClient httpClient) public DeviceManagmentService(IServiceScopeFactory serviceScopeFactory, IDeviceStatusService deviceStatusService, ILogger<DeviceManagmentService> logger, IHiveMQClient hiveMQClient, HttpClient httpClient)
{ {
this.serviceScopeFactory = serviceScopeFactory; this.serviceScopeFactory = serviceScopeFactory;
this.deviceStatusService = deviceStatusService; this.deviceStatusService = deviceStatusService;
this.logger = logger; this.logger = logger;
this.hiveMQClient = hiveMQClient; this.hiveMQClient = hiveMQClient;
this.httpClient = httpClient; this.httpClient = httpClient;
} }
public Result<Device> GetDevice(string macAdress) public Result<Device> GetDevice(string macAdress)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); return getDevicesResult.ToResult();
} }
Device? device = getDevicesResult.Value.FirstOrDefault(d => d.MacAddress == macAdress); Device? device = getDevicesResult.Value.FirstOrDefault(d => d.MacAddress == macAdress);
if (device is null) if (device is null)
{ {
return Result.Fail("Device does not exist!"); return Result.Fail("Device does not exist!");
} }
return device; return device;
} }
public Result<List<Device>> GetDevices() public Result<List<Device>> GetDevices(User user)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); return getDevicesResult.ToResult();
} }
return getDevicesResult.Value.ToList(); return getDevicesResult.Value.Where(d => d.User.Id == user.Id || user.Role == Role.Admin).ToList();
} }
public Result<List<Device>> GetDevicesInRoom(string room) public Result<List<Device>> GetDevicesInRoom(string room)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); return getDevicesResult.ToResult();
} }
return getDevicesResult.Value.Where(d => d.Room == room).ToList(); return getDevicesResult.Value.Where(d => d.Room == room).ToList();
} }
public Result<List<Device>> GetDevicesOfUser(int userId) public Result<List<Device>> GetDevicesOfUser(int userId)
{ {
Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices(); Result<List<Device>> getDevicesResult = deviceStatusService.GetDevices();
if (getDevicesResult.IsFailed) if (getDevicesResult.IsFailed)
{ {
return getDevicesResult.ToResult(); return getDevicesResult.ToResult();
} }
return getDevicesResult.Value.Where(d => d.User.Id == userId).ToList(); return getDevicesResult.Value.Where(d => d.User.Id == userId).ToList();
} }
public async Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default") public async Task<Result<Device>> RegisterDevice(IPAddress ip, User user, string? name = null, string room = "default")
{ {
using IServiceScope scope = serviceScopeFactory.CreateScope(); using IServiceScope scope = serviceScopeFactory.CreateScope();
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>(); MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
ShellyResponse? shellyResponse = null; ShellyResponse? shellyResponse = null;
try try
{ {
shellyResponse = await httpClient.GetFromJsonAsync<ShellyResponse>($"http://{ip}/shelly"); shellyResponse = await httpClient.GetFromJsonAsync<ShellyResponse>($"http://{ip}/shelly");
} }
catch (Exception ex) catch (Exception ex)
{ {
logger.LogError("HTTP request failed! {message}", ex.Message); logger.LogError("HTTP request failed! {message}", ex.Message);
} }
if (shellyResponse is null || shellyResponse.Type != "SHPLG-S") if (shellyResponse is null || shellyResponse.Type != "SHPLG-S")
{ {
return Result.Fail("Device is not reachable or not a \"SHPLG-S\"!"); return Result.Fail("Device is not reachable or not a \"SHPLG-S\"!");
} }
string mac = shellyResponse.Mac; string mac = shellyResponse.Mac;
if (!PhysicalAddress.TryParse(mac, out _)) if (!PhysicalAddress.TryParse(mac, out _))
{ {
return Result.Fail("Invalid mac address!"); return Result.Fail("Invalid mac address!");
} }
Device device = new Device(mac, name ?? mac, ip, user, room); Device device = new Device(mac, name ?? mac, ip, user, room);
mainDatabaseContext.Entry(user).State = EntityState.Unchanged; mainDatabaseContext.Entry(user).State = EntityState.Unchanged;
_ = mainDatabaseContext.Add(device); _ = mainDatabaseContext.Add(device);
Result saveDatabaseChangesResult = await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync()); Result saveDatabaseChangesResult = await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
if (saveDatabaseChangesResult.IsFailed) if (saveDatabaseChangesResult.IsFailed)
{ {
return saveDatabaseChangesResult; return saveDatabaseChangesResult;
} }
return deviceStatusService.TrackDevice(device); return deviceStatusService.TrackDevice(device);
} }
public async Task<Result> UnregisterDevice(string macAdress) public async Task<Result> UnregisterDevice(string macAdress)
{ {
using IServiceScope scope = serviceScopeFactory.CreateScope(); using IServiceScope scope = serviceScopeFactory.CreateScope();
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>(); MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
Result<Device> getDeviceResult = GetDevice(macAdress); Result<Device> getDeviceResult = GetDevice(macAdress);
if (getDeviceResult.IsFailed) if (getDeviceResult.IsFailed)
{ {
return getDeviceResult.ToResult(); return getDeviceResult.ToResult();
} }
Result untrackDeviceResult = deviceStatusService.UntrackDevice(macAdress); Result untrackDeviceResult = deviceStatusService.UntrackDevice(macAdress);
if (untrackDeviceResult.IsFailed) if (untrackDeviceResult.IsFailed)
{ {
return untrackDeviceResult; return untrackDeviceResult;
} }
_ = mainDatabaseContext.Remove(getDeviceResult.Value); _ = mainDatabaseContext.Remove(getDeviceResult.Value);
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync()); return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
} }
public async Task<Result> UpdateDevice(Device device) public async Task<Result> UpdateDevice(Device device)
{ {
using IServiceScope scope = serviceScopeFactory.CreateScope(); using IServiceScope scope = serviceScopeFactory.CreateScope();
MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>(); MainDatabaseContext mainDatabaseContext = scope.ServiceProvider.GetRequiredService<MainDatabaseContext>();
Result<Device> getDeviceResult = GetDevice(device.MacAddress); Result<Device> getDeviceResult = GetDevice(device.MacAddress);
if (getDeviceResult.IsFailed) if (getDeviceResult.IsFailed)
{ {
return getDeviceResult.ToResult(); return getDeviceResult.ToResult();
} }
Result updateDeviceResult = deviceStatusService.UpdateDeviceStatus(device); Result updateDeviceResult = deviceStatusService.UpdateDeviceStatus(device);
if (updateDeviceResult.IsFailed) if (updateDeviceResult.IsFailed)
{ {
return updateDeviceResult; return updateDeviceResult;
} }
PublishResult res = await hiveMQClient.PublishAsync($"shellies/shellyplug-s-{device.MacAddress}/relay/0/command", device.Enabled ? "on" : "off"); PublishResult res = await hiveMQClient.PublishAsync($"shellies/shellyplug-s-{device.MacAddress}/relay/0/command", device.Enabled ? "on" : "off");
device.User = mainDatabaseContext.Users.First(u => u.Id == device.User.Id); device.User = mainDatabaseContext.Users.First(u => u.Id == device.User.Id);
_ = mainDatabaseContext.Update(device); _ = mainDatabaseContext.Update(device);
return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync()); return await Result.Try(Task () => mainDatabaseContext.SaveChangesAsync());
} }
} }
@@ -1,55 +1,53 @@
using Elektrifikatsiya.Models; using Elektrifikatsiya.Models;
using FluentResults;
using System.Reflection; using System.Reflection;
namespace Elektrifikatsiya.Services.Implementations namespace Elektrifikatsiya.Services.Implementations;
public class EventService : IEventService
{ {
public class EventService : IEventService public event EventHandler<EventServiceEventArgs>? OnEventCalled;
public List<Event> Events { get; } = new();
public EventService(IDeviceStatusService deviceStatusService, IDeviceManagmentService deviceManagmentService)
{ {
private readonly ILogger<EventService> logger; List<Device> deviceList = deviceStatusService.GetDevices().ValueOrDefault.Select(x => x.CopyDevice()).ToList();
public event EventHandler<EventServiceEventArgs> OnEventCalled;
public List<Event> Events { get; } = new();
public EventService(ILogger<EventService> logger, IDeviceStatusService deviceStatusService, IDeviceManagmentService deviceManagmentService) deviceStatusService.OnDeviceStatusChanged += (_, e) =>
{ {
this.logger = logger; bool newDevice = true;
List<Device> deviceList = deviceManagmentService.GetDevices().ValueOrDefault.Select(x=>x.CopyDevice()).ToList(); Device currentDevice = deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault;
deviceStatusService.OnDeviceStatusChanged += (_, e) => for (int i = 0; i < deviceList.Count; i++)
{ {
bool newDevice = true; if (deviceList[i].MacAddress == currentDevice.MacAddress)
Device currentDevice = deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault;
for (int i = 0; i < deviceList.Count; i++)
{ {
if (deviceList[i].MacAddress == currentDevice.MacAddress) PropertyInfo[] properties = typeof(Device).GetProperties();
foreach (PropertyInfo property in properties)
{ {
PropertyInfo[] properties = typeof(Device).GetProperties(); object? currentvalue = property.GetValue(deviceList[i], null);
object? newvalue = property.GetValue(currentDevice, null);
foreach(PropertyInfo property in properties) { if (newvalue is not null && !newvalue?.ToString()?.Equals(currentvalue?.ToString()) == true)
var currentvalue = property.GetValue(deviceList[i], null); {
var newvalue = property.GetValue(currentDevice, null); string eventName = $"Plug {deviceList[i].Name} changed: {property.Name}";
if(newvalue is not null && !newvalue.ToString().Equals(currentvalue.ToString())) string description = $"Changed {property.Name} of plug [{currentvalue}] to [{newvalue}]";
{ DateTime dateTime = DateTime.Now;
string eventName = $"Plug {deviceList[i].Name} changed: {property.Name}";
string description = $"Changed {property.Name} of plug [{currentvalue}] to [{newvalue}]";
DateTime dateTime = DateTime.Now;
Event newEvent = new Event(eventName, description, dateTime, currentDevice);
Events.Insert(0,newEvent);
OnEventCalled?.Invoke(this, new EventServiceEventArgs(newEvent));
}
Event newEvent = new Event(eventName, description, dateTime, currentDevice);
Events.Insert(0, newEvent);
OnEventCalled?.Invoke(this, new EventServiceEventArgs(newEvent));
} }
deviceList[i].OverwiteDevice(currentDevice);
newDevice = false; break;
} }
deviceList[i].OverwiteDevice(currentDevice);
newDevice = false; break;
} }
if (newDevice) }
{ if (newDevice)
deviceList.Add(deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault); {
} deviceList.Add(deviceManagmentService.GetDevice(e.MacAddress).ValueOrDefault);
}; }
} };
} }
} }