Skip to content

Commit

Permalink
Chat update
Browse files Browse the repository at this point in the history
  • Loading branch information
KrystianKempski committed May 14, 2024
1 parent 7bd4bab commit e797c10
Show file tree
Hide file tree
Showing 14 changed files with 779 additions and 103 deletions.
6 changes: 6 additions & 0 deletions DagoniteEmpire/Helper/IJSRuntimeExtension.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Microsoft.JSInterop;
using static Microsoft.AspNetCore.Razor.Language.TagHelperMetadata;

namespace DagoniteEmpire.Helper
{
Expand Down Expand Up @@ -44,6 +45,11 @@ public static async ValueTask ScrollToBottom(this IJSRuntime jsRuntime, string c
await jsRuntime.InvokeVoidAsync("ScrollToBottom", container);
}

public static async ValueTask<int> GetWindowWidth(this IJSRuntime jsRuntime)
{
return await jsRuntime.InvokeAsync<int>("GetWindowWidth");
}

}

}
43 changes: 23 additions & 20 deletions DagoniteEmpire/Pages/CharacterPages/CharacterList.razor
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,30 @@
}
else
{
<div class="row mt-4">
<div class="col-12">
<h4 class="card-title">@Title</h4>
<div class="page">

<div class="row mt-4">
<div class="col-12">
<h4 class="card-title">@Title</h4>
</div>
</div>
</div>
<div class="row mt-4">
<div class="col-12">
<SfGrid ID="Grid"DataSource="@Characters" AllowPaging="true"
Toolbar="@ToolbarItems">
<GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true" Mode="@EditMode.Dialog"></GridEditSettings>
<GridEvents OnActionBegin="ActionHandler" TValue="CharacterDTO"></GridEvents>
<GridColumns>
@if (IsAdminOrMG){
<GridColumn Field=@nameof(CharacterDTO.UserName) HeaderText="User name" TextAlign="TextAlign.Left" Width="200"></GridColumn>
}
<GridColumn Field=@nameof(CharacterDTO.NPCName) HeaderText="Name" TextAlign="TextAlign.Left" Width="200"></GridColumn>
<GridColumn Field=@nameof(CharacterDTO.RaceName) HeaderText="Race" TextAlign="TextAlign.Left" Width="200"></GridColumn>
<GridColumn Field=@nameof(CharacterDTO.ProfessionName) HeaderText="Class" TextAlign="TextAlign.Left" Width="200"></GridColumn>
<GridColumn Field=@nameof(CharacterDTO.Age) HeaderText="Age" Format="d" TextAlign="TextAlign.Left" Width="50"></GridColumn>
</GridColumns>
</SfGrid>
<div class="row mt-4">
<div class="col-12">
<SfGrid ID="Grid"DataSource="@Characters" AllowPaging="true"
Toolbar="@ToolbarItems">
<GridEditSettings AllowAdding="true" AllowEditing="true" AllowDeleting="true" Mode="@EditMode.Dialog"></GridEditSettings>
<GridEvents OnActionBegin="ActionHandler" TValue="CharacterDTO"></GridEvents>
<GridColumns>
@if (IsAdminOrMG){
<GridColumn Field=@nameof(CharacterDTO.UserName) HeaderText="User name" TextAlign="TextAlign.Left" Width="200"></GridColumn>
}
<GridColumn Field=@nameof(CharacterDTO.NPCName) HeaderText="Name" TextAlign="TextAlign.Left" Width="200"></GridColumn>
<GridColumn Field=@nameof(CharacterDTO.RaceName) HeaderText="Race" TextAlign="TextAlign.Left" Width="200"></GridColumn>
<GridColumn Field=@nameof(CharacterDTO.ProfessionName) HeaderText="Class" TextAlign="TextAlign.Left" Width="200"></GridColumn>
<GridColumn Field=@nameof(CharacterDTO.Age) HeaderText="Age" Format="d" TextAlign="TextAlign.Left" Width="50"></GridColumn>
</GridColumns>
</SfGrid>
</div>
</div>
</div>
}
Expand Down
4 changes: 4 additions & 0 deletions DagoniteEmpire/Pages/CharacterPages/CharacterList.razor.css
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,7 @@
color: black;
padding-left:8px;
}

.page {
height: calc(100vh - 61px);
}
4 changes: 2 additions & 2 deletions DagoniteEmpire/Pages/Chat/Chat.razor
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
<div>
<MudText Typo="Typo.body1">@message.FromUser.Email</MudText>
<MudText Typo="Typo.caption" Style="font-size: xx-small!important;">@message.CreatedDate.ToString("dd MMM, yyyy hh:mm tt")</MudText>
<MudText Typo="Typo.body2" Style=" padding: 15px;background-color: var(--mud-palette-background-grey);border-radius: 5px;margin-top:5px">@message.Message</MudText>
<MudText Typo="Typo.body2" Style=" padding: 15px;background-color: var(--mud-palette-background-grey);border-radius: 12px;margin-top:5px">@message.Message</MudText>
</div>
</div>
}
Expand All @@ -47,7 +47,7 @@
<div>
<MudText Typo="Typo.body1">@message.FromUser.Email</MudText>
<MudText Typo="Typo.caption" Style="font-size: xx-small!important;">@message.CreatedDate.ToString("dd MMM, yyyy hh:mm tt")</MudText>
<MudText Typo="Typo.body2" Style=" padding: 15px;background-color: var(--mud-palette-background-grey);border-radius: 5px;margin-top:5px">@message.Message</MudText>
<MudText Typo="Typo.body2" Style=" padding: 15px;background-color: var(--mud-palette-background-grey);border-radius: 12px;margin-top:5px">@message.Message</MudText>
</div>
</div>
}
Expand Down
2 changes: 1 addition & 1 deletion DagoniteEmpire/Pages/Index.razor.css
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ h1 {

.hero-img {
position: relative;
height: calc(100vh - 61px);
height: calc(100vh - 64px);
background-image: url('../images/EastMarchy_header.webp');
background-size: cover;
background-position: center;
Expand Down
2 changes: 0 additions & 2 deletions DagoniteEmpire/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,6 @@
app.MapHub<ChatHub>(ChatHub.HubUrl);
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");
//app.MapHub<ChatHub>(ChatHub.HubUrl);
//app.MapHub<SignalRHub>("/signalRHub");

app.Run();

Expand Down
6 changes: 3 additions & 3 deletions DagoniteEmpire/Service/DbInitializer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public void Initialize()

ApplicationUser user = new()
{
UserName = "[email protected]",
UserName = "AdminKrystian",
Email = "[email protected]",
EmailConfirmed = true,
};
Expand All @@ -56,7 +56,7 @@ public void Initialize()

user = new()
{
UserName = "player@example.com",
UserName = "player",
Email = "[email protected]",
EmailConfirmed = true,
};
Expand All @@ -66,7 +66,7 @@ public void Initialize()

user = new()
{
UserName = "gm@example.com",
UserName = "gm",
Email = "[email protected]",
EmailConfirmed = true,
};
Expand Down
228 changes: 228 additions & 0 deletions DagoniteEmpire/Shared/Chat.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,228 @@
@using Microsoft.AspNetCore.SignalR.Client
@inject IChatManager _chatManager
@inject IJSRuntime _jsRuntime
@inject NavigationManager _navigationManager
@inject AuthenticationStateProvider _stateProvider

@attribute [Authorize(Roles = SD.Role_Admin + "," + SD.Role_HeroPlayer + "," + SD.Role_DukePlayer + "," + SD.Role_GameMaster)]

<div class="d-flex flex-grow-1 flex-row">
<MudPaper Elevation="25" Class="py-4 flex-grow-1">
<MudToolBar Dense="true">
@if (string.IsNullOrEmpty(ContactId))
{
<MudIcon Icon="@Icons.Material.Outlined.Person" Style="margin-right:10px"></MudIcon>
<MudText Typo="Typo.h6">chat</MudText>
}
else
{
<MudIcon Icon="@Icons.Material.Outlined.ChatBubble" Style="margin-right:10px"></MudIcon>
<MudText Typo="Typo.h6">@ContactEmail</MudText>
}
</MudToolBar>
<div class="d-flex flex-column px-4" style="max-height:65vh;min-height:65vh; overflow:scroll;" id="chatContainer">
@foreach (var message in messages)
{
@if (message.FromUser.Email == CurrentUserEmail)
{
<div class="d-flex flex-row my-4">
<div class="mr-4">
<MudAvatar Color="Color.Secondary" Style="height:50px; width:50px;">@message.FromUser.Email.ToUpper().FirstOrDefault()</MudAvatar>
</div>
<div>
<MudText Typo="Typo.body1">@message.FromUser.Email</MudText>
<MudText Typo="Typo.caption" Style="font-size: xx-small!important;">@message.CreatedDate.ToString("dd MMM, yyyy hh:mm tt")</MudText>
<MudText Typo="Typo.body2" Style=" padding: 15px;background-color: var(--mud-palette-background-grey);border-radius: 12px;margin-top:5px">@message.Message</MudText>
</div>
</div>
}
else
{
<div class="d-flex flex-row-reverse my-4">
<div class="mr-4">
<MudAvatar Color="Color.Primary" Style="height:50px; width:50px;">@message.FromUser.Email.ToUpper().FirstOrDefault()</MudAvatar>
</div>
<div>
<MudText Typo="Typo.body1">@message.FromUser.Email</MudText>
<MudText Typo="Typo.caption" Style="font-size: xx-small!important;">@message.CreatedDate.ToString("dd MMM, yyyy hh:mm tt")</MudText>
<MudText Typo="Typo.body2" Style=" padding: 15px;background-color: var(--mud-palette-background-grey);border-radius: 12px;margin-top:5px">@message.Message</MudText>
</div>
</div>
}


}
</div>
<MudPaper Elevation="25" Class="d-flex flex-row px-2 mx-4" Style="">
<MudTextField Disabled="!IsUserChosen" @ref="ChatTextField" Immediate="true" T="string" Placeholder="Enter your message..." DisableUnderLine="true" Class="mt-n2 mx-4"
@bind-Value="CurrentMessage" For="@(()=> CurrentMessage)" OnKeyDown="Enter" />
<MudButton Disabled="!IsUserChosen" OnClick="SubmitAsync" StartIcon="@Icons.Material.Outlined.Send" Color="Color.Secondary" ButtonType="MudBlazor.ButtonType.Button">Send</MudButton>
</MudPaper>
</MudPaper>
<MudPaper Elevation="25" Class="pa-3 ml-6" MinWidth="350px">
<MudToolBar Dense="true">
<MudText Typo="Typo.h6" Inline="true" Class="mr-2">#</MudText>
<MudText Typo="Typo.h6">contacts</MudText>
</MudToolBar>
<div class="d-flex flex-column px-4" style="max-height:70vh;min-height:70vh; overflow:scroll;">
<MudList Clickable="true">
@foreach (var user in ChatUsers)
{
<MudListItem Class="pa-0 px-2" OnClick="@(() => LoadUserChat(user.Id))">
<div class="d-flex flex-row mt-n1 mb-n1">
<div class="mr-4">
<MudBadge Class="my-2">
@if (user.Id == ContactId)
{
<MudAvatar Color="Color.Secondary" Style="height:50px; width:50px;">@user.Email.ToUpper().FirstOrDefault()</MudAvatar>
}
else
{
<MudAvatar Color="Color.Dark" Style="height:50px; width:50px;">@user.Email.ToUpper().FirstOrDefault()</MudAvatar>
}
</MudBadge>
</div>
<div>
<MudText Typo="Typo.body2" Class="mt-3 mb-n2">@user.Email</MudText>@*
<MudText Typo="Typo.caption" Style="font-size: xx-small!important;">@user.Id</MudText> *@
</div>
</div>
</MudListItem>
}
</MudList>
</div>
</MudPaper>
</div>

@code{
[CascadingParameter] public HubConnection hubConnection { get; set; }
[Parameter] public string CurrentMessage { get; set; }
[Parameter] public string CurrentUserId { get; set; }
[Parameter] public string CurrentUserEmail { get; set; }

MudTextField<string> ChatTextField = new();
private string HubUrl;
private List<ChatMessage> messages = new List<ChatMessage>();
private async Task SubmitAsync()
{
if(IsUserChosen==false)
return;
if (!string.IsNullOrEmpty(CurrentMessage) && !string.IsNullOrEmpty(ContactId))
{
//Save Message to DB
var chatHistory = new ChatMessage()
{
Message = CurrentMessage,
ToUserId = ContactId,
CreatedDate = DateTime.Now

};

chatHistory.FromUserId = CurrentUserId;
await hubConnection.SendAsync("SendMessage", CurrentUserEmail, chatHistory);
CurrentMessage = string.Empty;
await _chatManager.SaveMessageAsync(chatHistory);

}
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await _jsRuntime.ScrollToBottom("chatContainer");
}
protected override async Task OnInitializedAsync()
{
try
{
if (hubConnection == null)
{
hubConnection = new HubConnectionBuilder().WithUrl(_navigationManager.ToAbsoluteUri(ChatHub.HubUrl)).Build();
}
if (hubConnection.State == HubConnectionState.Disconnected)
{
await hubConnection.StartAsync();
}

hubConnection.On<string, ChatMessage>("SendMessage", ReceiveMessage);

await GetUsersAsync();
var state = await _stateProvider.GetAuthenticationStateAsync();
var user = state.User;
CurrentUserId = user.FindFirst(u => u.Type.Contains("nameidentifier"))?.Value;
CurrentUserEmail = user.FindFirst(u => u.Type.Contains("emailaddress"))?.Value;
if (!string.IsNullOrEmpty(ContactId))
{
await LoadUserChat(ContactId);
}

// await SendAsync($"[Notice] {_username} joined chat room.");
}
catch (Exception e)
{
;
// _message = $"ERROR: Failed to start chat client: {e.Message}";
// _isChatting = false;
}

}

private async Task ReceiveMessage(string name, ChatMessage message)
{
if ((ContactId == message.ToUserId && CurrentUserId == message.FromUserId) || (ContactId == message.FromUserId && CurrentUserId == message.ToUserId))
{

if ((ContactId == message.ToUserId && CurrentUserId == message.FromUserId))
{
messages.Add(new ChatMessage { Message = message.Message, CreatedDate = message.CreatedDate, FromUser = new ApplicationUser() { Email = CurrentUserEmail } });
//await hubConnection.SendAsync("ChatNotificationAsync", $"New Message From {name}", ContactId, CurrentUserId);
}
else if ((ContactId == message.FromUserId && CurrentUserId == message.ToUserId))
{
messages.Add(new ChatMessage { Message = message.Message, CreatedDate = message.CreatedDate, FromUser = new ApplicationUser() { Email = ContactEmail } });
}

// Inform blazor the UI needs updating
InvokeAsync(StateHasChanged);

await Task.Delay(1000);

await _jsRuntime.ScrollToBottom("chatContainer");
}
}

public async Task Enter(KeyboardEventArgs e)
{
if (e.Code == "Enter" || e.Code == "NumpadEnter")
{
ChatTextField.TextUpdateSuppression = false;
await SubmitAsync();
CurrentMessage = string.Empty;
StateHasChanged();
await Task.Run(async () =>
{
await Task.Delay(150);
ChatTextField.TextUpdateSuppression = true;
});
}
}

public List<ApplicationUser> ChatUsers = new List<ApplicationUser>();
public string ContactEmail { get; set; }
public string ContactId { get; set; }
private bool IsUserChosen { get; set; } = false;
async Task LoadUserChat(string userId)
{
var contact = await _chatManager.GetUserDetailsAsync(userId);
ContactId = contact.Id;
ContactEmail = contact.Email;
_navigationManager.NavigateTo($"chat/{ContactId}");
messages = new List<ChatMessage>();
messages = await _chatManager.GetConversationAsync(ContactId);
IsUserChosen = true;
}
private async Task GetUsersAsync()
{
ChatUsers = await _chatManager.GetUsersAsync();
}

}
Loading

0 comments on commit e797c10

Please sign in to comment.