Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
24 changes: 24 additions & 0 deletions JobHubMATF.slnx
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="&quot;True&quot;" />
<Property Name="Debug.AspNetCompiler.FixedNames" Value="&quot;false&quot;" />
<Property Name="Debug.AspNetCompiler.ForceOverwrite" Value="&quot;true&quot;" />
<Property Name="Debug.AspNetCompiler.PhysicalPath" Value="&quot;src\Web\&quot;" />
<Property Name="Debug.AspNetCompiler.TargetPath" Value="&quot;PrecompiledWeb\localhost_61851\&quot;" />
<Property Name="Debug.AspNetCompiler.Updateable" Value="&quot;true&quot;" />
<Property Name="Debug.AspNetCompiler.VirtualPath" Value="&quot;/localhost_61851&quot;" />
<Property Name="Release.AspNetCompiler.Debug" Value="&quot;False&quot;" />
<Property Name="Release.AspNetCompiler.FixedNames" Value="&quot;false&quot;" />
<Property Name="Release.AspNetCompiler.ForceOverwrite" Value="&quot;true&quot;" />
<Property Name="Release.AspNetCompiler.PhysicalPath" Value="&quot;src\Web\&quot;" />
<Property Name="Release.AspNetCompiler.TargetPath" Value="&quot;PrecompiledWeb\localhost_61851\&quot;" />
<Property Name="Release.AspNetCompiler.Updateable" Value="&quot;true&quot;" />
<Property Name="Release.AspNetCompiler.VirtualPath" Value="&quot;/localhost_61851&quot;" />
<Property Name="TargetFrameworkMoniker" Value="&quot;.NETFramework,Version%3Dv4.8&quot;" />
<Property Name="VWDPort" Value="&quot;61851&quot;" />
</Properties>
</Project>
</Solution>
16 changes: 16 additions & 0 deletions src/Services/Chat.API/Chat.API.csproj
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>
6 changes: 6 additions & 0 deletions src/Services/Chat.API/Chat.API.http
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

###
44 changes: 44 additions & 0 deletions src/Services/Chat.API/Controllers/MessagesController.cs
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);
}
}
}
59 changes: 59 additions & 0 deletions src/Services/Chat.API/Hubs/ChatHub.cs
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);
}
}
}
21 changes: 21 additions & 0 deletions src/Services/Chat.API/Models/Chat.cs
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; }
}
}

Copy link
Copy Markdown
Collaborator

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.
Image

24 changes: 24 additions & 0 deletions src/Services/Chat.API/Models/Message.cs
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; }

}

}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

new line at the end

8 changes: 8 additions & 0 deletions src/Services/Chat.API/Models/MongoDbSettings.cs
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; }
}
}
10 changes: 10 additions & 0 deletions src/Services/Chat.API/Models/SendMessageRequest.cs
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; }
}
}
44 changes: 44 additions & 0 deletions src/Services/Chat.API/Program.cs
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();
23 changes: 23 additions & 0 deletions src/Services/Chat.API/Properties/launchSettings.json
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"
}
}
}
}
99 changes: 99 additions & 0 deletions src/Services/Chat.API/Services/ChatService.cs
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;
}
}
}
Loading