This commit is contained in:
Pistasj 2023-05-29 22:18:24 +02:00
parent 13d2b1b1fb
commit ce38633766
11 changed files with 49 additions and 301 deletions

View File

@ -4,21 +4,6 @@ namespace LiveChat.Server.Hubs;
public class ChatHub : Hub public class ChatHub : Hub
{ {
public async Task SendMessage(string user, string message, string room)
{
using (var db = new ChattingContext())
{
var messageData = new ChatMessage
{
User = user,
Message = message,
};
var dbSave = db.Messages.Add(messageData);
await Clients.AllExcept("LiveChat Room Users").SendAsync("ReceiveMessage", user, message);
db.SaveChanges();
}
}
public async Task SendMessageRoom(string user, string message, string room) public async Task SendMessageRoom(string user, string message, string room)
{ {
using (var db = new ChattingContext()) using (var db = new ChattingContext())
@ -27,9 +12,9 @@ public class ChatHub : Hub
{ {
User = user, User = user,
Message = message, Message = message,
RoomId = room RoomId = room,
}; };
var dbSave = db.RoomChatMessages.Add(messageData); db.RoomChatMessages.Add(messageData);
await Clients.Group(room).SendAsync("ReceiveMessage", user, message); await Clients.Group(room).SendAsync("ReceiveMessage", user, message);
db.SaveChanges(); db.SaveChanges();
} }
@ -38,7 +23,7 @@ public class ChatHub : Hub
public async Task JoinRoom(string room, string user) public async Task JoinRoom(string room, string user)
{ {
await Groups.AddToGroupAsync(Context.ConnectionId, room); await Groups.AddToGroupAsync(Context.ConnectionId, room);
await Groups.AddToGroupAsync(Context.ConnectionId, "Folk i rom"); await Groups.AddToGroupAsync(Context.ConnectionId, "Folk_i_rom");
await Clients.Caller.SendAsync("ConnectionIdReceive", Context.ConnectionId); await Clients.Caller.SendAsync("ConnectionIdReceive", Context.ConnectionId);
} }
} }

View File

@ -1,40 +0,0 @@
// <auto-generated />
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace LiveChat.Migrations
{
[DbContext(typeof(ChattingContext))]
[Migration("20230327073724_FuckThisShitv2")]
partial class FuckThisShitv2
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.4");
modelBuilder.Entity("ChatMessage", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Message")
.HasColumnType("TEXT");
b.Property<string>("User")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Messages");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -1,34 +0,0 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace LiveChat.Migrations
{
/// <inheritdoc />
public partial class FuckThisShitv2 : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Messages",
columns: table => new
{
Id = table.Column<string>(type: "TEXT", nullable: false),
User = table.Column<string>(type: "TEXT", nullable: true),
Message = table.Column<string>(type: "TEXT", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Messages", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Messages");
}
}
}

View File

@ -9,8 +9,8 @@ using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace LiveChat.Migrations namespace LiveChat.Migrations
{ {
[DbContext(typeof(ChattingContext))] [DbContext(typeof(ChattingContext))]
[Migration("20230526180433_sqlite.local_migration_189")] [Migration("20230529185839_sqlite.local_migration_918")]
partial class sqlitelocal_migration_189 partial class sqlitelocal_migration_918
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder) protected override void BuildTargetModel(ModelBuilder modelBuilder)
@ -18,23 +18,6 @@ namespace LiveChat.Migrations
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.4"); modelBuilder.HasAnnotation("ProductVersion", "7.0.4");
modelBuilder.Entity("ChatMessage", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Message")
.HasColumnType("TEXT");
b.Property<string>("User")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Messages");
});
modelBuilder.Entity("Room", b => modelBuilder.Entity("Room", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")

View File

@ -5,7 +5,7 @@
namespace LiveChat.Migrations namespace LiveChat.Migrations
{ {
/// <inheritdoc /> /// <inheritdoc />
public partial class sqlitelocal_migration_189 : Migration public partial class sqlitelocal_migration_918 : Migration
{ {
/// <inheritdoc /> /// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder) protected override void Up(MigrationBuilder migrationBuilder)

View File

@ -15,23 +15,6 @@ namespace LiveChat.Migrations
#pragma warning disable 612, 618 #pragma warning disable 612, 618
modelBuilder.HasAnnotation("ProductVersion", "7.0.4"); modelBuilder.HasAnnotation("ProductVersion", "7.0.4");
modelBuilder.Entity("ChatMessage", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("TEXT");
b.Property<string>("Message")
.HasColumnType("TEXT");
b.Property<string>("User")
.HasColumnType("TEXT");
b.HasKey("Id");
b.ToTable("Messages");
});
modelBuilder.Entity("Room", b => modelBuilder.Entity("Room", b =>
{ {
b.Property<string>("Id") b.Property<string>("Id")

View File

@ -7,8 +7,6 @@ using System.ComponentModel.DataAnnotations.Schema;
public class ChattingContext : DbContext public class ChattingContext : DbContext
{ {
public DbSet<ChatMessage> Messages { get; set; }
public DbSet<Room> Rooms { get; set; } public DbSet<Room> Rooms { get; set; }
public DbSet<RoomChatMessage> RoomChatMessages { get; set; } public DbSet<RoomChatMessage> RoomChatMessages { get; set; }
@ -37,17 +35,6 @@ public class Room
// koble tilsammen RoomChatMessage til Room // koble tilsammen RoomChatMessage til Room
// https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx // https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx
public RoomChatMessage? RoomChatMessage { get; set; } public RoomChatMessage? RoomChatMessage { get; set; }
}
public class ChatMessage
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string? Id { get; set; }
public string? User { get; set; }
public string? Message { get; set; }
} }
public class RoomChatMessage public class RoomChatMessage
@ -63,5 +50,4 @@ public class RoomChatMessage
// koble tilsammen RoomChatMessage til Room // koble tilsammen RoomChatMessage til Room
// https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx // https://www.entityframeworktutorial.net/efcore/one-to-many-conventions-entity-framework-core.aspx
public Room? Room { get; set; } public Room? Room { get; set; }
} }

View File

@ -2,6 +2,7 @@
@using Microsoft.AspNetCore.SignalR.Client; @using Microsoft.AspNetCore.SignalR.Client;
@using LiveChat.Models; @using LiveChat.Models;
@inject NavigationManager Navigation @inject NavigationManager Navigation
@inject IHttpContextAccessor httpContextAccessor;
<PageTitle>Chat room</PageTitle> <PageTitle>Chat room</PageTitle>
@ -13,11 +14,13 @@
<h1>Rom @Room</h1> <h1>Rom @Room</h1>
<p>Din tilkoblings ID: @connectionId. Brukernavn: @username</p> <p>Del @Room til vennene dine for å snakke med dem fra her. Ditt brukernavn: @username.</p>
@foreach (var msg in msgs) @foreach (var msg in msgs)
{ {
<div class="MessagesList" id="messagesList">
<div class="message">@msg</div> <div class="message">@msg</div>
</div>
} }
<div class="messageFormContainer"> <div class="messageFormContainer">
@ -49,17 +52,16 @@
private List<string> msgs = new List<string>(); private List<string> msgs = new List<string>();
private bool ErViInne = false;
private string connectionId = "";
private string username = ""; private string username = "";
private MessageModel messageModel = new MessageModel() { User = "Something", Message = "" }; private MessageModel messageModel = new MessageModel() { User = "Something", Message = "" };
private string? host { get; set; }
protected override async Task OnInitializedAsync() protected override async Task OnInitializedAsync()
{ {
//host = httpContextAccessor.HttpContext.Request.Headers["Host"];
hubConnection = new HubConnectionBuilder() hubConnection = new HubConnectionBuilder()
.WithUrl(Navigation.ToAbsoluteUri("/chathub")) .WithUrl(Navigation.ToAbsoluteUri("/chathub"))
.Build(); .Build();
@ -89,9 +91,18 @@
// bli med i rom // bli med i rom
await hubConnection.SendAsync("JoinRoom", Room, username); await hubConnection.SendAsync("JoinRoom", Room, username);
ErViInne = true;
messageModel.User = username; messageModel.User = username;
using (var db = new ChattingContext())
{
var messages = db.RoomChatMessages.Where(m => m.RoomId == Room).ToList();
foreach (var message in messages)
{
msgs.Add($"{message.User}: {message.Message}");
}
await InvokeAsync(StateHasChanged);
}
hubConnection.On<string, string>("ReceiveMessage", (user, message) => hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{ {
var encodedMsg = $"{user}: {message}"; var encodedMsg = $"{user}: {message}";

View File

@ -1,155 +1,44 @@
@page "/" @page "/"
@using LiveChat.Models; @using LiveChat.Models;
@using Microsoft.AspNetCore.SignalR.Client
@inject Blazored.LocalStorage.ILocalStorageService localStorage @inject Blazored.LocalStorage.ILocalStorageService localStorage
@inject NavigationManager Navigation @inject NavigationManager Navigation
@implements IAsyncDisposable
<PageTitle>LiveChat app</PageTitle> <PageTitle>LiveChat app</PageTitle>
<div class="container d-flex flex-column flex-wrap gap-4"> <div class="container d-flex flex-column flex-wrap gap-4">
<div>
<div hidden="@(!ModalIsVisible)"> <div>
<EditForm Model="@userModel" OnValidSubmit="@SetUser">
<DataAnnotationsValidator />
<div class="giveNameMessage">
<h1>Skriv inn navnet ditt</h1>
<p>Dette kan ikke endres (helt til du oppdaterer sida)</p>
<ValidationSummary />
<input @bind-value="userModel.User" disabled="@(!ModalIsVisible)" placeholder="Navn" class="MessageFormName" />
<button type="submit" disabled="@(!IsConnected)" class="MessageFormButton"><i class="bi bi-send-fill"></i> Sett navn</button>
</div>
</EditForm>
</div>
<div hidden="@(!ModalIsVisible)">
<div >
<h1>Skriv inn romkode</h1> <h1>Skriv inn romkode</h1>
<p>Få tak i koden av eieren av rommet eller noen som er i det.</p> <p>Få tak i koden av eieren av rommet eller noen som er i det.</p>
<input @bind-value="romkode"placeholder="Romkode" class="MessageFormName" />
<button type="submit" class="MessageFormButton" @onclick="BliMedIRom"><i class="bi bi-send-fill"></i> Bli med i rom</button>
</div>
</div> </div>
</div>
<div hidden="@(!ModalIsVisible)"> <div>
<div> <div>
<h1>Lag et rom</h1> <h1>Lag et rom</h1>
<p>Snakk med venner osv.</p> <p>Snakk med venner osv.</p>
<button type="submit" disabled="@(!IsConnected)" class="MessageFormButton">Lag et tilfeldig rom</button> <button type="submit" class="MessageFormButton" @onclick="LagTilfeldigRom">Lag et tilfeldig rom</button>
</div>
</div> </div>
</div> </div>
</div>
@if (msgs != null)
{
<div class="MessagesList" id="messagesList" hidden="@(ModalIsVisible)">
@foreach (var message in msgs)
{
<div class="message">@message</div>
}
</div>
}
else
{
<h1>Ingen meldinger tilgjengelig.</h1>
}
<div class="messageFormContainer" hidden="@(ModalIsVisible)">
@if (messageModel == null)
{
<p>laster inn meldingsboks</p>
}
else
{
<EditForm Model="@messageModel" OnValidSubmit="@HandleSubmit" class="MessageForm">
<DataAnnotationsValidator />
<div class="MessageFormValidation">
<ValidationSummary />
</div>
<div class="MessageFormInputs">
<input @bind-value="messageModel.Message" placeholder="Skriv inn din melding..." class="MessageFormMessage" />
<button type="submit" disabled="@(!IsConnected || ModalIsVisible)" class="MessageFormButton"><i class="bi bi-send-fill"></i></button>
</div>
</EditForm>
}
</div>
@code { @code {
private HubConnection? hubConnection; private string? romkode;
private bool ModalIsVisible = true; private void LagTilfeldigRom()
private MessageModel messageModel = new MessageModel() { User = "", Message = "" };
private UserModel userModel = new UserModel() { User = "" };
private List<string> msgs = new List<string>();
protected override async Task OnInitializedAsync()
{ {
hubConnection = new HubConnectionBuilder() // lag tilfeldig nummer
.WithUrl(Navigation.ToAbsoluteUri("/chathub")) Random random = new Random();
.Build(); var nummer = random.Next(0, 1000000);
// send bruker til rommet
using (var db = new ChattingContext()) Navigation.NavigateTo("/chat/" + nummer);
{
var messages = db.Messages.ToList();
foreach (var msg in messages)
{
var encodedMsg = $"{msg.User}: {msg.Message}";
msgs.Add(encodedMsg);
}
await InvokeAsync(StateHasChanged);
} }
private void BliMedIRom()
hubConnection.On<string, string>("ReceiveMessage", (user, message) =>
{ {
var encodedMsg = $"{user}: {message}"; // send bruker til rommet
msgs.Add(encodedMsg); Navigation.NavigateTo("/chat/" + romkode);
InvokeAsync(StateHasChanged);
});
await hubConnection.StartAsync();
}
private async Task SetUser()
{
ModalIsVisible = false;
messageModel.User = userModel.User;
await localStorage.SetItemAsync("user", userModel.User);
}
private async Task HandleSubmit()
{
var filter = new ProfanityFilter.ProfanityFilter();
// Kjempegøy
filter.AddProfanity("faen");
filter.AddProfanity("jævla");
filter.AddProfanity("jævel");
filter.AddProfanity("homse");
filter.AddProfanity("homo");
filter.AddProfanity("neger");
filter.AddProfanity("transe");
filter.AddProfanity("dritt");
messageModel.User = filter.CensorString(messageModel.User);
messageModel.Message = filter.CensorString(messageModel.Message);
if (hubConnection is not null)
{
await hubConnection.SendAsync("SendMessage", messageModel.User, messageModel.Message);
}
}
public bool IsConnected =>
hubConnection?.State == HubConnectionState.Connected;
public async ValueTask DisposeAsync()
{
if (hubConnection is not null)
{
await hubConnection.DisposeAsync();
}
} }
} }

View File

@ -10,6 +10,7 @@ var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages(); builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor(); builder.Services.AddServerSideBlazor();
builder.Services.AddBlazoredLocalStorage(); builder.Services.AddBlazoredLocalStorage();
builder.Services.AddHttpContextAccessor();
builder.Services.AddResponseCompression(opts => builder.Services.AddResponseCompression(opts =>
{ {
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat( opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(

View File

@ -1,16 +0,0 @@
<div class="alert alert-secondary mt-4">
<span class="oi oi-pencil me-2" aria-hidden="true"></span>
<strong>@Title</strong>
<span class="text-nowrap">
Please take our
<a target="_blank" class="font-weight-bold link-dark" href="https://go.microsoft.com/fwlink/?linkid=2186158">brief survey</a>
</span>
and tell us what you think.
</div>
@code {
// Demonstrates how a parent component can supply parameters
[Parameter]
public string? Title { get; set; }
}