diff --git a/gutargu-backend/API/Controllers/UserController.cs b/gutargu-backend/API/Controllers/UserController.cs index 430034f..85c077f 100644 --- a/gutargu-backend/API/Controllers/UserController.cs +++ b/gutargu-backend/API/Controllers/UserController.cs @@ -51,4 +51,15 @@ public async Task GetContacts(int userId) var contactResponse = await this._userService.GetContacts(userId); return _customResponse.Success(data: contactResponse); } + + /// + /// Blocks/unblocks a user contact. + /// + /// /// The request containing the contact to block. + [HttpPut("contacts/block")] + public async Task BlockContact(UpdateBlockStatusRequestModel blockRequest) + { + await this._userService.UpdateBlockStatus(blockRequest); + return _customResponse.Success("Contact has been blocked successfully."); + } } diff --git a/gutargu-backend/Common/Models/Mappings/UserBlockingMappingProfile.cs b/gutargu-backend/Common/Models/Mappings/UserBlockingMappingProfile.cs new file mode 100644 index 0000000..a60f7b0 --- /dev/null +++ b/gutargu-backend/Common/Models/Mappings/UserBlockingMappingProfile.cs @@ -0,0 +1,15 @@ +using AutoMapper; +using Gutargu.Backend.DAL.Entities; +using Gutargu.Backend.Common.Models.Request; + +namespace Gutargu.Backend.Common.Models.Mappings; + +public class UserBlockingMappingProfile : Profile +{ + public UserBlockingMappingProfile() + { + CreateMap() + .ForMember(dest => dest.CreatedBy, opt => opt.MapFrom(src => src.BlockingUserEmail)) + .ForMember(dest => dest.UpdatedBy, opt => opt.MapFrom(src => src.BlockingUserEmail)); + } +} \ No newline at end of file diff --git a/gutargu-backend/Common/Models/Request/BlockContactRequestModel.cs b/gutargu-backend/Common/Models/Request/BlockContactRequestModel.cs new file mode 100644 index 0000000..2c7c539 --- /dev/null +++ b/gutargu-backend/Common/Models/Request/BlockContactRequestModel.cs @@ -0,0 +1,20 @@ +using System.ComponentModel.DataAnnotations; + +namespace Gutargu.Backend.Common.Models.Request; + +public class UpdateBlockStatusRequestModel +{ + [Required] + // The user who has been blocked + public int BlockedUserId { get; set; } + + // The user who has blocked the other user + [Required] + public int BlockingUserId { get; set; } + + [Required] + public string BlockingUserEmail { get; set; } + + [Required] + public bool ShouldBlock { get; set; } +} \ No newline at end of file diff --git a/gutargu-backend/Common/Models/Response/UserContactsResoponseModel.cs b/gutargu-backend/Common/Models/Response/UserContactsResoponseModel.cs index ed72bb1..e6c3ee6 100644 --- a/gutargu-backend/Common/Models/Response/UserContactsResoponseModel.cs +++ b/gutargu-backend/Common/Models/Response/UserContactsResoponseModel.cs @@ -24,4 +24,8 @@ public class ContactInformation public int? LastChatSenderId { get; set; } public bool IsLastChatSentByContact { get; set; } = true; + + public bool IsContactBlocked { get; set; } + + public bool HasBlockedCurrentUser { get; set; } } \ No newline at end of file diff --git a/gutargu-backend/DAL/Configurations/UserBlockingConfiguration.cs b/gutargu-backend/DAL/Configurations/UserBlockingConfiguration.cs new file mode 100644 index 0000000..ce6ad43 --- /dev/null +++ b/gutargu-backend/DAL/Configurations/UserBlockingConfiguration.cs @@ -0,0 +1,13 @@ +using Gutargu.Backend.DAL.Entities; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +namespace Gutargu.Backend.DAL.Configurations; + +internal class UserBlockingConfiguration : BaseEntityConfiguration +{ + public override void Configure(EntityTypeBuilder builder) + { + base.Configure(builder); + } +} + diff --git a/gutargu-backend/DAL/Contracts/IUserBlockingRepository.cs b/gutargu-backend/DAL/Contracts/IUserBlockingRepository.cs new file mode 100644 index 0000000..536bdc1 --- /dev/null +++ b/gutargu-backend/DAL/Contracts/IUserBlockingRepository.cs @@ -0,0 +1,8 @@ +using Gutargu.Backend.DAL.Entities; + +namespace Gutargu.Backend.DAL.Contracts; + +public interface IUserBlockingRepository : ICrudBaseRepository +{ +} + diff --git a/gutargu-backend/DAL/Entities/UserBlocking.cs b/gutargu-backend/DAL/Entities/UserBlocking.cs new file mode 100644 index 0000000..5ba3ba2 --- /dev/null +++ b/gutargu-backend/DAL/Entities/UserBlocking.cs @@ -0,0 +1,12 @@ +namespace Gutargu.Backend.DAL.Entities; + +public class UserBlocking : BaseEntity +{ + // The user who has been blocked + public int BlockedUserId { get; set; } + public User BlockedUser { get; set; } + + // The user who has blocked the other user + public int BlockingUserId { get; set; } + public User BlockingUser { get; set; } +} \ No newline at end of file diff --git a/gutargu-backend/DAL/Extensions/RepositoryCollectionExtension.cs b/gutargu-backend/DAL/Extensions/RepositoryCollectionExtension.cs index eb1c899..b978a3e 100644 --- a/gutargu-backend/DAL/Extensions/RepositoryCollectionExtension.cs +++ b/gutargu-backend/DAL/Extensions/RepositoryCollectionExtension.cs @@ -12,6 +12,8 @@ public static void RegisterRepositories(this IServiceCollection services) services.AddScoped(); services.AddScoped(); + + services.AddScoped(); } } diff --git a/gutargu-backend/DAL/GutarguDBContext.cs b/gutargu-backend/DAL/GutarguDBContext.cs index cd9f8d5..f7734d0 100644 --- a/gutargu-backend/DAL/GutarguDBContext.cs +++ b/gutargu-backend/DAL/GutarguDBContext.cs @@ -13,6 +13,8 @@ public GutarguDBContext(DbContextOptions options) : base(optio public DbSet Chats { get; set; } public DbSet UserContacts { get; set; } + + public DbSet UserBlockings { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { @@ -23,5 +25,7 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) modelBuilder.ApplyConfiguration(new ChatConfiguration()); modelBuilder.ApplyConfiguration(new UserContactConfiguration()); + + modelBuilder.ApplyConfiguration(new UserBlockingConfiguration()); } } \ No newline at end of file diff --git a/gutargu-backend/DAL/Migrations/20241219122704_add-user-blocking-table.Designer.cs b/gutargu-backend/DAL/Migrations/20241219122704_add-user-blocking-table.Designer.cs new file mode 100644 index 0000000..15c7b74 --- /dev/null +++ b/gutargu-backend/DAL/Migrations/20241219122704_add-user-blocking-table.Designer.cs @@ -0,0 +1,274 @@ +// +using System; +using Gutargu.Backend.DAL; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace gutargu_backend.DAL.Migrations +{ + [DbContext(typeof(GutarguDBContext))] + [Migration("20241219122704_add-user-blocking-table")] + partial class adduserblockingtable + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "9.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.Chat", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("ImageUrl") + .HasColumnType("text"); + + b.Property("IsRead") + .HasColumnType("boolean"); + + b.Property("Message") + .IsRequired() + .HasColumnType("text"); + + b.Property("ReceiverId") + .HasColumnType("integer"); + + b.Property("SenderId") + .HasColumnType("integer"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.HasKey("Id"); + + b.HasIndex("ReceiverId"); + + b.HasIndex("SenderId", "ReceiverId", "CreatedDate"); + + b.ToTable("Chats"); + }); + + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(254) + .HasColumnType("character varying(254)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)"); + + b.Property("PasswordHash") + .IsRequired() + .HasColumnType("text"); + + b.Property("ProfileImageUrl") + .HasColumnType("text"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.HasKey("Id"); + + b.HasIndex("Email") + .IsUnique(); + + b.ToTable("Users"); + }); + + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.UserBlocking", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BlockedUserId") + .HasColumnType("integer"); + + b.Property("BlockingUserId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.HasKey("Id"); + + b.HasIndex("BlockedUserId"); + + b.HasIndex("BlockingUserId"); + + b.ToTable("UserBlockings"); + }); + + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.UserContact", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("ContactUserId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("LastChatId") + .HasColumnType("integer"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("UserId") + .HasColumnType("integer"); + + b.HasKey("Id"); + + b.HasIndex("ContactUserId"); + + b.HasIndex("LastChatId"); + + b.HasIndex("UserId"); + + b.ToTable("UserContacts"); + }); + + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.Chat", b => + { + b.HasOne("Gutargu.Backend.DAL.Entities.User", "Receiver") + .WithMany() + .HasForeignKey("ReceiverId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Gutargu.Backend.DAL.Entities.User", "Sender") + .WithMany() + .HasForeignKey("SenderId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("Receiver"); + + b.Navigation("Sender"); + }); + + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.UserBlocking", b => + { + b.HasOne("Gutargu.Backend.DAL.Entities.User", "BlockedUser") + .WithMany() + .HasForeignKey("BlockedUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Gutargu.Backend.DAL.Entities.User", "BlockingUser") + .WithMany() + .HasForeignKey("BlockingUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("BlockedUser"); + + b.Navigation("BlockingUser"); + }); + + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.UserContact", b => + { + b.HasOne("Gutargu.Backend.DAL.Entities.User", "ContactUser") + .WithMany() + .HasForeignKey("ContactUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Gutargu.Backend.DAL.Entities.Chat", "LastChat") + .WithMany() + .HasForeignKey("LastChatId"); + + b.HasOne("Gutargu.Backend.DAL.Entities.User", "User") + .WithMany() + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("ContactUser"); + + b.Navigation("LastChat"); + + b.Navigation("User"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/gutargu-backend/DAL/Migrations/20241219122704_add-user-blocking-table.cs b/gutargu-backend/DAL/Migrations/20241219122704_add-user-blocking-table.cs new file mode 100644 index 0000000..9e7b39b --- /dev/null +++ b/gutargu-backend/DAL/Migrations/20241219122704_add-user-blocking-table.cs @@ -0,0 +1,63 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace gutargu_backend.DAL.Migrations +{ + /// + public partial class adduserblockingtable : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "UserBlockings", + columns: table => new + { + Id = table.Column(type: "integer", nullable: false) + .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), + BlockedUserId = table.Column(type: "integer", nullable: false), + BlockingUserId = table.Column(type: "integer", nullable: false), + CreatedDate = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"), + UpdatedDate = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"), + CreatedBy = table.Column(type: "text", nullable: true), + UpdatedBy = table.Column(type: "text", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_UserBlockings", x => x.Id); + table.ForeignKey( + name: "FK_UserBlockings_Users_BlockedUserId", + column: x => x.BlockedUserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + table.ForeignKey( + name: "FK_UserBlockings_Users_BlockingUserId", + column: x => x.BlockingUserId, + principalTable: "Users", + principalColumn: "Id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_UserBlockings_BlockedUserId", + table: "UserBlockings", + column: "BlockedUserId"); + + migrationBuilder.CreateIndex( + name: "IX_UserBlockings_BlockingUserId", + table: "UserBlockings", + column: "BlockingUserId"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "UserBlockings"); + } + } +} diff --git a/gutargu-backend/DAL/Migrations/GutarguDBContextModelSnapshot.cs b/gutargu-backend/DAL/Migrations/GutarguDBContextModelSnapshot.cs index 202a769..9d68cc5 100644 --- a/gutargu-backend/DAL/Migrations/GutarguDBContextModelSnapshot.cs +++ b/gutargu-backend/DAL/Migrations/GutarguDBContextModelSnapshot.cs @@ -120,6 +120,45 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("Users"); }); + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.UserBlocking", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(b.Property("Id")); + + b.Property("BlockedUserId") + .HasColumnType("integer"); + + b.Property("BlockingUserId") + .HasColumnType("integer"); + + b.Property("CreatedBy") + .HasColumnType("text"); + + b.Property("CreatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("UpdatedBy") + .HasColumnType("text"); + + b.Property("UpdatedDate") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.HasKey("Id"); + + b.HasIndex("BlockedUserId"); + + b.HasIndex("BlockingUserId"); + + b.ToTable("UserBlockings"); + }); + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.UserContact", b => { b.Property("Id") @@ -183,6 +222,25 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Sender"); }); + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.UserBlocking", b => + { + b.HasOne("Gutargu.Backend.DAL.Entities.User", "BlockedUser") + .WithMany() + .HasForeignKey("BlockedUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Gutargu.Backend.DAL.Entities.User", "BlockingUser") + .WithMany() + .HasForeignKey("BlockingUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.Navigation("BlockedUser"); + + b.Navigation("BlockingUser"); + }); + modelBuilder.Entity("Gutargu.Backend.DAL.Entities.UserContact", b => { b.HasOne("Gutargu.Backend.DAL.Entities.User", "ContactUser") diff --git a/gutargu-backend/DAL/Repositories/UserBlockingRepository.cs b/gutargu-backend/DAL/Repositories/UserBlockingRepository.cs new file mode 100644 index 0000000..9dd181a --- /dev/null +++ b/gutargu-backend/DAL/Repositories/UserBlockingRepository.cs @@ -0,0 +1,12 @@ +using Gutargu.Backend.DAL.Entities; +using Gutargu.Backend.DAL.Contracts; + +namespace Gutargu.Backend.DAL.Repositories; + +public class UserBlockingRepository : CrudBaseRepository, IUserBlockingRepository +{ + public UserBlockingRepository(GutarguDBContext dbContext) : base(dbContext) + { + } +} + diff --git a/gutargu-backend/Services/Contracts/IUserService.cs b/gutargu-backend/Services/Contracts/IUserService.cs index 15d3d48..adf44b9 100644 --- a/gutargu-backend/Services/Contracts/IUserService.cs +++ b/gutargu-backend/Services/Contracts/IUserService.cs @@ -10,4 +10,6 @@ public interface IUserService Task AddContact(AddContactRequestModel contactRequest); Task GetContacts(int currentUserId); + + Task UpdateBlockStatus(UpdateBlockStatusRequestModel blockRequest); } \ No newline at end of file diff --git a/gutargu-backend/Services/UserService.cs b/gutargu-backend/Services/UserService.cs index 2b6b4cb..9320f28 100644 --- a/gutargu-backend/Services/UserService.cs +++ b/gutargu-backend/Services/UserService.cs @@ -15,13 +15,22 @@ public class UserService : IUserService private readonly IImageService _imageService; private readonly IUserRepository _userRepository; private readonly IUserContactRepository _userContactRepository; - - public UserService(IMapper mapper, IImageService imageService, IUserRepository userRepository, IUserContactRepository userContactRepository) + private readonly IUserBlockingRepository _userBlockingRepository; + + public UserService + ( + IMapper mapper, + IImageService imageService, + IUserRepository userRepository, + IUserContactRepository userContactRepository, + IUserBlockingRepository userBlockingRepository + ) { _mapper = mapper; _imageService = imageService; _userRepository = userRepository; _userContactRepository = userContactRepository; + _userBlockingRepository = userBlockingRepository; } public async Task Search(int currentUserId, string searchKey) @@ -101,6 +110,12 @@ public async Task GetContacts(int currentUserId) ] ); + var userBlockings = await this._userBlockingRepository + .GetList + ( + predicate: ub => ub.BlockedUserId == currentUserId || ub.BlockingUserId == currentUserId + ); + var contacts = this._mapper.Map>(userContacts); foreach (var contact in contacts) { @@ -109,6 +124,12 @@ public async Task GetContacts(int currentUserId) contact.ProfileImageUrl = await this._imageService.GetImageURL(contact.ProfileImageUrl); } + contact.IsContactBlocked = userBlockings + .Any(ub => ub.BlockedUserId == contact.UserId && ub.BlockingUserId == currentUserId); + + contact.HasBlockedCurrentUser = userBlockings + .Any(ub => ub.BlockedUserId == currentUserId && ub.BlockingUserId == contact.UserId); + contact.IsLastChatSentByContact = contact.LastChatSenderId == contact.UserId; } @@ -117,4 +138,30 @@ public async Task GetContacts(int currentUserId) Contacts = contacts }; } + + public async Task UpdateBlockStatus(UpdateBlockStatusRequestModel blockRequest) + { + var userBlocking = await this._userBlockingRepository + .Get(ub => ub.BlockedUserId == blockRequest.BlockedUserId && ub.BlockingUserId == blockRequest.BlockingUserId); + + if (blockRequest.ShouldBlock) + { + if (userBlocking != null) + { + throw new ApiException("Contact already blocked.", AppConstants.ErrorCodeEnum.Conflict); + } + + var newUserBlocking = this._mapper.Map(blockRequest); + await this._userBlockingRepository.Add(newUserBlocking); + } + else + { + if (userBlocking == null) + { + throw new ApiException("Contact is not blocked.", AppConstants.ErrorCodeEnum.Conflict); + } + + await this._userBlockingRepository.Delete(userBlocking); + } + } } diff --git a/gutargu-frontend/src/components/chat/chatArea/ChatArea.css b/gutargu-frontend/src/components/chat/chatArea/ChatArea.css index e825fa3..a8b5013 100644 --- a/gutargu-frontend/src/components/chat/chatArea/ChatArea.css +++ b/gutargu-frontend/src/components/chat/chatArea/ChatArea.css @@ -50,8 +50,6 @@ font-weight: 300; color: #a5a5a5; } - - } } @@ -116,6 +114,7 @@ height: 300px; border-radius: 10px; object-fit: cover; + position: relative; } p { @@ -125,6 +124,10 @@ } } } + + .message.own .texts img { + margin-right: 10px; + } } .bottom { @@ -176,5 +179,33 @@ border-radius: 5px; cursor: pointer; } + + .blocked-info { + margin: 0 auto; + } } -} \ No newline at end of file + + /* Style for the cancel button */ + .message.own .texts { + position: relative; + } + + .cancel-button { + position: absolute; + top: 5px; + right: 5px; + background-color: rgba(17, 25, 40, 0.3); + color: white; + border: 1px solid white; + padding: 8px; + border-radius: 50%; + cursor: pointer; + z-index: 1; + font-size: 16px; + width: 30px; + height: 30px; + display: flex; + justify-content: center; + align-items: center; + } +} diff --git a/gutargu-frontend/src/components/chat/chatArea/ChatArea.tsx b/gutargu-frontend/src/components/chat/chatArea/ChatArea.tsx index dd0bca3..2c6db38 100644 --- a/gutargu-frontend/src/components/chat/chatArea/ChatArea.tsx +++ b/gutargu-frontend/src/components/chat/chatArea/ChatArea.tsx @@ -5,10 +5,11 @@ import useAuthStore from '../../../stores/UserStore'; import useChatStore from '../../../stores/ChatStore'; import apiService from '../../../services/ApiService'; import { ChatInformation, ChatResponseModel } from '../../../models/ChatResponse'; +import { toast } from 'react-toastify'; const ChatArea = () => { - const { chatUser } = useChatStore(); + const { isBlocked, chatUser } = useChatStore(); const { currentUser } = useAuthStore(); const [open, setOpen] = useState(false); @@ -18,7 +19,7 @@ const ChatArea = () => { const [chats, setChats] = useState([] as ChatInformation[]); - const endRef = useRef(null); + const endRef = useRef(null); useEffect(() => { endRef.current?.scrollIntoView({ behavior: "smooth" }); @@ -26,7 +27,7 @@ const ChatArea = () => { useEffect(() => { getChats(); - }, [chatUser?.id, currentUser?.id]) + }, [chatUser?.userId, currentUser?.id]) const handleImage = (e: React.ChangeEvent) => { if (e.target.files?.[0]) { @@ -42,7 +43,7 @@ const ChatArea = () => { const queryParams = { 'senderId': currentUser?.id, - 'recieverId': chatUser?.id, + 'recieverId': chatUser?.userId, }; const { data, status } = await apiService.get('chats', queryParams); @@ -67,14 +68,15 @@ const ChatArea = () => { const handleSend = async () => { if (!text || text == "") { + toast.info("Please enter some message."); return; } const formData = new FormData(); formData.append("senderId", currentUser?.id?.toString() || ""); - formData.append("receiverId", chatUser?.id?.toString() || ""); - formData.append("message", text); + formData.append("receiverId", chatUser?.userId?.toString() || ""); + formData.append("message", text.trim() || ""); formData.append("senderEmail", currentUser?.email || ""); if (image.file) { @@ -94,6 +96,10 @@ const ChatArea = () => { } }; + const handleCancelImage = () => { + setImage({ file: null, url: "" }); + }; + if (chatUser == null) { return (
@@ -106,9 +112,9 @@ const ChatArea = () => {
- +
- {chatUser?.name} + {chatUser?.userName}

This is a sample chat

@@ -121,7 +127,7 @@ const ChatArea = () => {
{ - chats.length === 0 ? ( + !isBlocked && chats.length === 0 ? (

Type some messages to start the conversation...

@@ -143,6 +149,7 @@ const ChatArea = () => {
+
} @@ -150,25 +157,53 @@ const ChatArea = () => {
-
- - - - -
+ { isBlocked() ? ( +

+ {chatUser.hasBlockedCurrentUser + ? "Can't send message. This user blocked you." + : "Can't send messaage. You have blocked this user."} +

+ ) : ( + <> +
+ + + Camera + Microphone +
- handleMessageChange(e?.target.value)} /> + handleMessageChange(e?.target.value)} + /> + +
+ Emoji +
+ +
+
-
- -
- -
-
- - + + + )}
) diff --git a/gutargu-frontend/src/components/chat/detail/Detail.tsx b/gutargu-frontend/src/components/chat/detail/Detail.tsx index cb58d7a..b55f050 100644 --- a/gutargu-frontend/src/components/chat/detail/Detail.tsx +++ b/gutargu-frontend/src/components/chat/detail/Detail.tsx @@ -2,24 +2,53 @@ import './Detail.css' import { toast } from 'react-toastify'; import useAuthStore from '../../../stores/UserStore'; import useChatStore from '../../../stores/ChatStore'; +import apiService from '../../../services/ApiService'; import StorageService from '../../../services/StorageService'; const Detail = () => { - const { chatUser } = useChatStore(); - const { clearUser } = useAuthStore(); + const { isBlocked, chatUser } = useChatStore(); + const { currentUser, clearUser } = useAuthStore(); const handleLogout = () => { clearUser(); StorageService.clearStorage(); toast.success("Logged out successfully."); } + + const getBlockButtonText = () => { + if (chatUser?.isContactBlocked) + return "Unblock User" + else + return "Block User" + }; + + const isContactBlocked = chatUser?.isContactBlocked; + + const handleBlockUnblock = async () => { + const updateBlockStatus = { + blockedUserId: chatUser?.userId, + blockingUserId: currentUser?.id, + blockingUserEmail: currentUser?.email, + shouldBlock: !isContactBlocked + }; + + const { status } = await apiService.put('users/contacts/block', updateBlockStatus); + + if (status === 'success') { + if (isContactBlocked) { + toast.success("Contact has been unblocked.") + } else { + toast.info("Contact has been blocked.") + } + } + }; return (
- -

{chatUser?.name}

+ +

{chatUser?.userName}

This is my status

@@ -71,7 +100,7 @@ const Detail = () => {
- +
diff --git a/gutargu-frontend/src/components/chat/list/chatList/ChatList.tsx b/gutargu-frontend/src/components/chat/list/chatList/ChatList.tsx index 97ee7a0..8b9f23e 100644 --- a/gutargu-frontend/src/components/chat/list/chatList/ChatList.tsx +++ b/gutargu-frontend/src/components/chat/list/chatList/ChatList.tsx @@ -1,10 +1,9 @@ import './ChatList.css' import AddUser from './addUser/AddUser'; import { useEffect, useState } from 'react'; +import useChatStore from '../../../../stores/ChatStore'; import useAuthStore from '../../../../stores/UserStore'; import apiService from '../../../../services/ApiService'; -import useChatStore from '../../../../stores/ChatStore'; -import { UserInformation } from '../../../../models/UserResponse'; import { UserContactInformation, UserContactsResponseModel } from '../../../../models/UserContactsResponse'; const ChatList = () => { @@ -16,13 +15,15 @@ const ChatList = () => { const [addMode, toggleAddMode] = useState(false) + const [filterText, setFilterText] = useState("") + const changeAddMode = () => { toggleAddMode((prev) => !prev); } useEffect(() => { getUserContacts(); - }, [currentUser?.id, chatUser?.id]); + }, [currentUser?.id, chatUser?.userId]); const getUserContacts = async () => { const queryParams = { @@ -37,15 +38,11 @@ const ChatList = () => { }; const handleContactClick = async (contact: UserContactInformation) => { - const user: UserInformation = { - id: contact.userId, - name: contact.userName, - email: contact.userEmail, - profileImageUrl: contact.profileImageUrl - }; - - setChatUser(user); + setChatUser(contact); + await setLastChatSeenStatus(contact); + } + const setLastChatSeenStatus = async (contact: UserContactInformation) => { if (!contact.isLastChatSentByContact || contact.lastChatId == null || contact.isLastChatRead) return; const updateChatRequest = { @@ -59,18 +56,23 @@ const ChatList = () => { } } + const filteredContacts = contacts.filter( + c => c.userName.toLocaleLowerCase().includes(filterText) + || c.userEmail.toLocaleLowerCase().includes(filterText) + ); + return (
- + setFilterText(e.target.value.toLocaleLowerCase())}/>
{ - contacts.map((contact) => ( + filteredContacts.map((contact) => (
{ backgroundColor: contact.isLastChatSentByContact && !contact.isLastChatRead ? "#5183fe" : "transparent" }} > - +
{contact.userName} -

{contact.lastChatMessage}

+

+ { !contact.isContactBlocked && !contact.hasBlockedCurrentUser ? contact.lastChatMessage + : contact?.isContactBlocked + ? "You have blocked this contact." + : "This user has blocked you." + } +

)) diff --git a/gutargu-frontend/src/models/UserContactsResponse.ts b/gutargu-frontend/src/models/UserContactsResponse.ts index 885ad1a..2760848 100644 --- a/gutargu-frontend/src/models/UserContactsResponse.ts +++ b/gutargu-frontend/src/models/UserContactsResponse.ts @@ -4,10 +4,11 @@ export interface UserContactInformation { userEmail: string; profileImageUrl?: string; lastChatId?: number; - lastChatSenderId?: number; lastChatMessage: string; isLastChatRead: boolean; isLastChatSentByContact: boolean; + isContactBlocked: boolean; + hasBlockedCurrentUser: boolean; } export interface UserContactsResponseModel { diff --git a/gutargu-frontend/src/stores/ChatStore.ts b/gutargu-frontend/src/stores/ChatStore.ts index 06630c3..35f5c92 100644 --- a/gutargu-frontend/src/stores/ChatStore.ts +++ b/gutargu-frontend/src/stores/ChatStore.ts @@ -1,16 +1,23 @@ import { create } from 'zustand'; -import { UserInformation } from '../models/UserResponse'; +import { UserContactInformation } from '../models/UserContactsResponse'; interface ChatState { - chatUser: UserInformation | null; + chatUser: UserContactInformation | null; + + setChatUser: (chatUser: UserContactInformation) => void; - setChatUser: (chatUser: UserInformation) => void; + isBlocked: () => boolean; } -const useChatStore = create((set) => ({ - chatUser: null, +const useChatStore = create((set, get) => ({ + chatUser: null, - setChatUser: (chatUser) => set({ chatUser }) + setChatUser: (chatUser) => set({ chatUser }), + + isBlocked: () => { + const chatUser = get().chatUser; + return chatUser?.hasBlockedCurrentUser || chatUser?.isContactBlocked || false; + } })); -export default useChatStore; \ No newline at end of file +export default useChatStore;