Skip to content

Commit

Permalink
bug free chat!!!
Browse files Browse the repository at this point in the history
  • Loading branch information
NielsPilgaard committed Feb 25, 2024
1 parent 49ccadd commit 94d281b
Show file tree
Hide file tree
Showing 7 changed files with 407 additions and 68 deletions.
14 changes: 1 addition & 13 deletions src/web/Jordnaer/Components/Account/Pages/Register.razor
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,6 @@
<DataAnnotationsValidator />
<h2>Opret en ny konto.</h2>
<hr />
<div class="form-floating mb-3">
<InputText @bind-Value="Input.Username" class="form-control" autocomplete="username" aria-required="true" placeholder=""/>
<label for="username">Brugernavn</label>
<ValidationMessage For="() => Input.Username" class="text-danger" />
</div>
<div class="form-floating mb-3">
<InputText @bind-Value="Input.Email" class="form-control" autocomplete="email" aria-required="true" placeholder="[email protected]" />
<label for="email">Email</label>
Expand Down Expand Up @@ -87,7 +82,7 @@

var userId = await UserManager.GetUserIdAsync(user);

var userProfile = new UserProfile { Id = user.Id, UserName = Input.Username };
var userProfile = new UserProfile { Id = user.Id };
await using var context = await DbContextFactory.CreateDbContextAsync();
context.UserProfiles.Add(userProfile);
await context.SaveChangesAsync();
Expand Down Expand Up @@ -135,13 +130,6 @@

private sealed class InputModel
{
[Required(ErrorMessage = "Påkrævet.")]
[StringLength(30, MinimumLength = 2, ErrorMessage = "{0] skal være mellem {2} og {1} karakter langt.")]
[RegularExpression("^[\\w@-_\\.^][^\\\\]+$",
ErrorMessage = "Brugernavn må kun bestå af bogstaver, tal, og udvalgte tegn.")]
[Display(Name = "Brugernavn")]
public string Username { get; set; } = "";

[Required(ErrorMessage = "Påkrævet.")]
[EmailAddress(ErrorMessage = "Email skal være gyldig.")]
[Display(Name = "Email")]
Expand Down
7 changes: 4 additions & 3 deletions src/web/Jordnaer/Consumers/SendMessageConsumer.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Jordnaer.Database;
using Jordnaer.Extensions;
using Jordnaer.Features.Chat;
using Jordnaer.Shared;
using MassTransit;
Expand Down Expand Up @@ -50,12 +51,12 @@ public async Task Consume(ConsumeContext<SendMessage> consumeContext)
});
}

await _chatHub.Clients.Users(recipientIds).ReceiveChatMessage(chatMessage);

try
{
await _context.SaveChangesAsync(consumeContext.CancellationToken);

await _chatHub.Clients.Users(recipientIds).ReceiveChatMessage(chatMessage);

await _context.Chats
.Where(chat => chat.Id == chatMessage.ChatId)
.ExecuteUpdateAsync(call =>
Expand All @@ -64,7 +65,7 @@ await _context.Chats
}
catch (Exception exception)
{
_logger.LogError(exception, "Exception occurred while processing {command} command", nameof(SendMessage));
_logger.LogException(exception);
throw;
}
}
Expand Down
49 changes: 26 additions & 23 deletions src/web/Jordnaer/Features/Chat/ChatComponent.razor
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@
@inject ChatSignalRClient ChatSignalRClient
@inject NavigationManager Navigation
@implements IAsyncDisposable

@rendermode @(new InteractiveServerRenderMode(false))

@attribute [Authorize]

<MetadataComponent Title="Mini Møder - Chat"
Description="Her kan du skrive med andre"/>
Description="Her kan du skrive med andre" />

<MudLoading @bind-Loading="_isLoading" Darken Overlap>
<MudGrid Style="height: 85svh">
Expand Down Expand Up @@ -136,7 +139,6 @@
var lastChatMessage = chat.Messages.LastOrDefault();
if (lastChatMessage is not null && lastChatMessage.SenderId == _currentUser.Id)
{
await InvokeAsync(StateHasChanged);
return;
}

Expand Down Expand Up @@ -166,16 +168,18 @@

if (_activeChat?.Id == chat.Id)
{
LastMessageWasSentSuccessfullyByCurrentUser = false;
LastMessageWasSentSuccessfullyByCurrentUser = false;
await ChatService.MarkMessagesAsReadAsync(_currentUser.Id, message.ChatId);
await InvokeAsync(StateHasChanged);
await ScrollToBottom();
}
else
{
chat.UnreadMessageCount++;
_chats = _chats.OrderByDescending(c => c.UnreadMessageCount).ToList();
await InvokeAsync(StateHasChanged);
await InvokeAsync(() =>
{
chat.UnreadMessageCount++;
_chats = _chats.OrderByDescending(c => c.UnreadMessageCount).ToList();
StateHasChanged();
});
}
});

Expand All @@ -186,7 +190,6 @@
{
if (_activeChat is null)
{
Snackbar.Add(ErrorMessages.Something_Went_Wrong_Refresh, Severity.Warning);
return;
}

Expand All @@ -211,27 +214,27 @@

MarkMessageIfSuccessfullySentByCurrentUser();

if (!Navigation.Uri.EndsWith($"/chat/{_activeChat.Id}"))
if (_activeChat is not null && !Navigation.Uri.EndsWith($"/chat/{_activeChat.Id}"))
{
Navigation.NavigateTo($"/chat/{_activeChat.Id}");
}
}

private void MarkMessageIfSuccessfullySentByCurrentUser()
{
if (_activeChat is null)
{
return;
}

var lastMessage = _activeChat.Messages.LastOrDefault();
if (lastMessage is null)
{
LastMessageWasSentSuccessfullyByCurrentUser = false;
return;
}
LastMessageWasSentSuccessfullyByCurrentUser= lastMessage.SenderId == _currentUser.Id;
if (_activeChat is null)
{
return;
}

var lastMessage = _activeChat.Messages.LastOrDefault();
if (lastMessage is null)
{
LastMessageWasSentSuccessfullyByCurrentUser = false;
return;
}

LastMessageWasSentSuccessfullyByCurrentUser = lastMessage.SenderId == _currentUser.Id;
}

private async Task HideFooter() => await JsRuntime.InvokeVoidAsync("utilities.hideElement", ".footer");
Expand All @@ -241,7 +244,7 @@
private void BackToList()
{
_activeChat = null;
Navigation.NavigateTo(Navigation.GetUriWithQueryParameter("activeChat", (Guid?)null));
Navigation.NavigateTo($"{Navigation.BaseUri}chat");
}

private async Task SendMessage()
Expand Down
14 changes: 10 additions & 4 deletions src/web/Jordnaer/Features/Chat/ChatSignalRClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,23 @@ public class ChatSignalRClient(
{
public void OnMessageReceived(Func<SendMessage, Task> action)
{
if (!Started && HubConnection is not null)
if (HubConnection is null)
{
HubConnection.On(nameof(IChatHub.ReceiveChatMessage), action);
return;
}

HubConnection.Remove(nameof(IChatHub.ReceiveChatMessage));
HubConnection.On(nameof(IChatHub.ReceiveChatMessage), action);
}

public void OnChatStarted(Func<StartChat, Task> action)
{
if (!Started && HubConnection is not null)
if (HubConnection is null)
{
HubConnection.On(nameof(IChatHub.StartChat), action);
return;
}

HubConnection.Remove(nameof(IChatHub.StartChat));
HubConnection.On(nameof(IChatHub.StartChat), action);
}
}
14 changes: 10 additions & 4 deletions src/web/Jordnaer/Features/Chat/UnreadMessageSignalRClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,23 @@ public class UnreadMessageSignalRClient(
{
public void OnMessageReceived(Func<SendMessage, Task> action)
{
if (!Started && HubConnection is not null)
if (HubConnection is null)
{
HubConnection.On(nameof(IChatHub.ReceiveChatMessage), action);
return;
}

HubConnection.Remove(nameof(IChatHub.ReceiveChatMessage));
HubConnection.On(nameof(IChatHub.ReceiveChatMessage), action);
}

public void OnChatStarted(Func<StartChat, Task> action)
{
if (!Started && HubConnection is not null)
if (HubConnection is null)
{
HubConnection.On(nameof(IChatHub.StartChat), action);
return;
}

HubConnection.Remove(nameof(IChatHub.StartChat));
HubConnection.On(nameof(IChatHub.StartChat), action);
}
}
Loading

0 comments on commit 94d281b

Please sign in to comment.