-
Notifications
You must be signed in to change notification settings - Fork 0
Feature/signalr chat #27
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
Open
Laki27
wants to merge
4
commits into
main
Choose a base branch
from
feature/signalr-chat
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| <Solution> | ||
| <Project Path="src/Services/Chat.API/Chat.API.csproj" /> | ||
| <Project Path="src/Web/" Type="Website" DisplayName="Web" Id="8ae733e2-87db-b11e-fdff-4762e944013d"> | ||
| <BuildType Project="Debug" /> | ||
| <Properties Name="WebsiteProperties"> | ||
| <Property Name="Debug.AspNetCompiler.Debug" Value=""True"" /> | ||
| <Property Name="Debug.AspNetCompiler.FixedNames" Value=""false"" /> | ||
| <Property Name="Debug.AspNetCompiler.ForceOverwrite" Value=""true"" /> | ||
| <Property Name="Debug.AspNetCompiler.PhysicalPath" Value=""src\Web\"" /> | ||
| <Property Name="Debug.AspNetCompiler.TargetPath" Value=""PrecompiledWeb\localhost_61851\"" /> | ||
| <Property Name="Debug.AspNetCompiler.Updateable" Value=""true"" /> | ||
| <Property Name="Debug.AspNetCompiler.VirtualPath" Value=""/localhost_61851"" /> | ||
| <Property Name="Release.AspNetCompiler.Debug" Value=""False"" /> | ||
| <Property Name="Release.AspNetCompiler.FixedNames" Value=""false"" /> | ||
| <Property Name="Release.AspNetCompiler.ForceOverwrite" Value=""true"" /> | ||
| <Property Name="Release.AspNetCompiler.PhysicalPath" Value=""src\Web\"" /> | ||
| <Property Name="Release.AspNetCompiler.TargetPath" Value=""PrecompiledWeb\localhost_61851\"" /> | ||
| <Property Name="Release.AspNetCompiler.Updateable" Value=""true"" /> | ||
| <Property Name="Release.AspNetCompiler.VirtualPath" Value=""/localhost_61851"" /> | ||
| <Property Name="TargetFrameworkMoniker" Value="".NETFramework,Version%3Dv4.8"" /> | ||
| <Property Name="VWDPort" Value=""61851"" /> | ||
| </Properties> | ||
| </Project> | ||
| </Solution> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
|
||
| <PropertyGroup> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.5" /> | ||
| <PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.9" /> | ||
| <PackageReference Include="MongoDB.Driver" Version="3.7.1" /> | ||
| <PackageReference Include="Scalar.AspNetCore" Version="2.13.15" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| @Chat.API_HostAddress = http://localhost:5075 | ||
|
|
||
| GET {{Chat.API_HostAddress}}/weatherforecast/ | ||
| Accept: application/json | ||
|
|
||
| ### |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| | ||
| using Chat.API.Models; | ||
| using Chat.API.Services; | ||
| using Microsoft.AspNetCore.Mvc; | ||
|
|
||
| namespace Chat.API.Controllers | ||
| { | ||
| [ApiController] | ||
| [Route("api/[controller]")] | ||
| public class MessagesController : ControllerBase | ||
| { | ||
| private readonly ChatService _chatService; | ||
|
|
||
| public MessagesController(ChatService chatService) | ||
| { | ||
| _chatService = chatService; | ||
| } | ||
| [HttpPost] | ||
| public async Task<IActionResult> SendMessage([FromBody] SendMessageRequest request) { | ||
| if (string.IsNullOrEmpty(request.Text)) | ||
| return BadRequest("Message cannot be empty"); | ||
|
|
||
| var message = await _chatService.SendMessageAsync( | ||
| request.SenderId, | ||
| request.ReciverId, | ||
| request.Text | ||
| ); | ||
|
|
||
| return Ok(message); | ||
|
|
||
| } | ||
|
|
||
| [HttpGet] | ||
| public async Task<IActionResult> GetMessages([FromQuery] string user1, [FromQuery] string user2) | ||
| { | ||
| if (string.IsNullOrEmpty(user1) || string.IsNullOrEmpty(user2)) | ||
| return BadRequest("User IDs are required"); | ||
|
|
||
| var messages = await _chatService.GetMessagesAsync(user1, user2); | ||
|
|
||
| return Ok(messages); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| using Chat.API.Services; | ||
| using Microsoft.AspNetCore.SignalR; | ||
| namespace Chat.API.Hubs | ||
| { | ||
| public class ChatHub : Hub | ||
| { | ||
| private readonly ChatService _chatService; | ||
| private static readonly Dictionary<string, string> _connections = new(); | ||
|
|
||
| public ChatHub(ChatService chatService) | ||
| { | ||
| _chatService = chatService; | ||
| } | ||
| public async Task SendMessage(string senderId, string reciverId, string message) | ||
| { | ||
| var savedMessage = await _chatService.SendMessageAsync(senderId, reciverId, message); | ||
| if(_connections.TryGetValue(reciverId, out var connectionId)) | ||
| { | ||
| await Clients.Client(connectionId).SendAsync("ReceiveMessage", | ||
| savedMessage.SenderId, | ||
| reciverId, | ||
| savedMessage.Text, | ||
| savedMessage.Timestamp); | ||
| } | ||
|
|
||
| if (_connections.TryGetValue(senderId, out var senderConnection)) | ||
| { | ||
| await Clients.Client(senderConnection).SendAsync("ReceiveMessage", | ||
| savedMessage.SenderId, | ||
| reciverId, | ||
| savedMessage.Text, | ||
| savedMessage.Timestamp); | ||
| } | ||
| } | ||
| public override Task OnConnectedAsync() | ||
| { | ||
| var userId = Context.GetHttpContext().Request.Query["userId"]; | ||
|
|
||
| if (!string.IsNullOrEmpty(userId)) | ||
| { | ||
| _connections[userId] = Context.ConnectionId; | ||
| } | ||
|
|
||
| return base.OnConnectedAsync(); | ||
| } | ||
|
|
||
| public override Task OnDisconnectedAsync(Exception exception) | ||
| { | ||
| var item = _connections.FirstOrDefault(x => x.Value == Context.ConnectionId); | ||
|
|
||
| if (!string.IsNullOrEmpty(item.Key)) | ||
| { | ||
| _connections.Remove(item.Key); | ||
| } | ||
|
|
||
| return base.OnDisconnectedAsync(exception); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,21 @@ | ||
| using MongoDB.Bson; | ||
| using MongoDB.Bson.Serialization.Attributes; | ||
|
|
||
|
|
||
| namespace Chat.API.Models | ||
| { | ||
|
|
||
| public class Chat | ||
| { | ||
| [BsonId] | ||
| [BsonRepresentation(BsonType.ObjectId)] | ||
|
|
||
| public string Id { get; set; } | ||
|
|
||
| public string User1Id { get; set; } | ||
|
|
||
| public string User2Id { get; set; } | ||
|
|
||
| public DateTime CreatedAt { get; set; } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| | ||
| using MongoDB.Bson; | ||
| using MongoDB.Bson.Serialization.Attributes; | ||
|
|
||
| namespace Chat.API.Models | ||
| { | ||
|
|
||
| public class Message | ||
| { | ||
| [BsonId] | ||
| [BsonRepresentation(BsonType.ObjectId)] | ||
| public string Id { get; set; } | ||
|
|
||
| public string ChatId { get; set; } | ||
|
|
||
| public string SenderId { get; set; } | ||
|
|
||
| public string Text { get; set; } | ||
|
|
||
| public DateTime Timestamp { get; set; } | ||
|
|
||
| } | ||
|
|
||
| } | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. new line at the end |
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| namespace Chat.API.Models | ||
| { | ||
| public class MongoDbSettings | ||
| { | ||
| public string ConnectionString { get; set; } | ||
| public string DatabaseName { get; set; } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| namespace Chat.API.Models | ||
| { | ||
| public class SendMessageRequest | ||
| { | ||
| public string SenderId { get; set; } | ||
| public string ReciverId { get; set; } | ||
|
|
||
| public string Text { get; set; } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| using Chat.API.Services; | ||
| using Scalar.AspNetCore; | ||
| using Chat.API.Hubs; | ||
| var builder = WebApplication.CreateBuilder(args); | ||
|
|
||
| // Add services to the container. | ||
|
|
||
| builder.Services.AddControllers(); | ||
| // Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi | ||
| builder.Services.AddOpenApi(); | ||
| builder.Services.AddSingleton<ChatService>(); | ||
| builder.Services.AddSignalR(); | ||
|
|
||
| builder.Services.AddCors(options => | ||
| { | ||
| options.AddPolicy("AllowAll", | ||
| policy => | ||
| { | ||
| policy.WithOrigins("http://127.0.0.1:5500", "null") | ||
| .AllowAnyHeader() | ||
| .AllowAnyMethod() | ||
| .AllowCredentials(); | ||
| }); | ||
| }); | ||
|
|
||
|
|
||
|
|
||
| var app = builder.Build(); | ||
|
|
||
| // Configure the HTTP request pipeline. | ||
| if (app.Environment.IsDevelopment()) | ||
| { | ||
| app.MapOpenApi(); | ||
| app.MapScalarApiReference(); | ||
| } | ||
|
|
||
| app.UseCors("AllowAll"); | ||
|
|
||
| app.UseAuthorization(); | ||
|
|
||
| app.MapControllers(); | ||
| app.MapHub<ChatHub>("/chatHub"); | ||
|
|
||
| app.Run(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| { | ||
| "$schema": "https://json.schemastore.org/launchsettings.json", | ||
| "profiles": { | ||
| "http": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": false, | ||
| "applicationUrl": "http://localhost:5075", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| }, | ||
| "https": { | ||
| "commandName": "Project", | ||
| "dotnetRunMessages": true, | ||
| "launchBrowser": false, | ||
| "applicationUrl": "https://localhost:7175;http://localhost:5075", | ||
| "environmentVariables": { | ||
| "ASPNETCORE_ENVIRONMENT": "Development" | ||
| } | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,99 @@ | ||
| using Chat.API.Models; | ||
| using MongoDB.Driver; | ||
|
|
||
|
|
||
|
|
||
| namespace Chat.API.Services | ||
| { | ||
| public class ChatService | ||
| { | ||
| private readonly IMongoCollection<Message> _messages; | ||
| private readonly IMongoCollection<Models.Chat> _chats; | ||
|
|
||
| public ChatService(IConfiguration config) | ||
| { | ||
| var settings = config.GetSection("MongoDbSettings").Get<MongoDbSettings>(); | ||
| var client = new MongoClient(settings.ConnectionString); | ||
| var database = client.GetDatabase(settings.DatabaseName); | ||
|
|
||
| _chats = database.GetCollection<Models.Chat>("Chats"); | ||
| _messages = database.GetCollection<Message>("Messages"); | ||
| } | ||
|
|
||
| public async Task<Models.Chat> GetOrCreateChatAsync(string user1, string user2) | ||
| { | ||
| // Sortiranje userId-eva | ||
| var sortedUsers = new List<string> { user1, user2 }; | ||
| sortedUsers.Sort(); | ||
|
|
||
| var u1 = sortedUsers[0]; | ||
| var u2 = sortedUsers[1]; | ||
|
|
||
| // Traženje postojećeg chata | ||
| var chat = await _chats | ||
| .Find(c => c.User1Id == u1 && c.User2Id == u2) | ||
| .FirstOrDefaultAsync(); | ||
|
|
||
| if (chat != null) | ||
| return chat; | ||
|
|
||
| // Kreiranje novog chata | ||
| var newChat = new Models.Chat | ||
| { | ||
| User1Id = u1, | ||
| User2Id = u2, | ||
| CreatedAt = DateTime.UtcNow | ||
| }; | ||
|
|
||
| await _chats.InsertOneAsync(newChat); | ||
|
|
||
| return newChat; | ||
| } | ||
|
|
||
| public async Task<Message> SendMessageAsync(string senderId, string receiverId, string text) | ||
| { | ||
| // 1. Uzmi ili kreiraj chat | ||
| var chat = await GetOrCreateChatAsync(senderId, receiverId); | ||
|
|
||
| // 2. Kreiraj poruku | ||
| var message = new Message | ||
| { | ||
| ChatId = chat.Id, | ||
| SenderId = senderId, | ||
| Text = text, | ||
| Timestamp = DateTime.UtcNow | ||
| }; | ||
|
|
||
| // 3. Sačuvaj u bazu | ||
| await _messages.InsertOneAsync(message); | ||
|
|
||
| return message; | ||
| } | ||
|
|
||
| public async Task<List<Message>> GetMessagesAsync(string user1, string user2) | ||
| { | ||
| // 1. Sortiranje userId-eva | ||
| var sortedUsers = new List<string> { user1, user2 }; | ||
| sortedUsers.Sort(); | ||
|
|
||
| var u1 = sortedUsers[0]; | ||
| var u2 = sortedUsers[1]; | ||
|
|
||
| // 2. Pronađi chat | ||
| var chat = await _chats | ||
| .Find(c => c.User1Id == u1 && c.User2Id == u2) | ||
| .FirstOrDefaultAsync(); | ||
|
|
||
| if (chat == null) | ||
| return new List<Message>(); | ||
|
|
||
| // 3. Uzmi sve poruke za taj chat | ||
| var messages = await _messages | ||
| .Find(m => m.ChatId == chat.Id) | ||
| .SortBy(m => m.Timestamp) | ||
| .ToListAsync(); | ||
|
|
||
| return messages; | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Add new line at the end of every file, so you don't get this sign. It's a styling issue, not a functional issue and it's in best practice.
