Revert "提交"

This reverts commit b96d895809.
This commit is contained in:
2026-02-12 21:59:08 +08:00
parent b96d895809
commit d429560511
339 changed files with 46657 additions and 46655 deletions
+29 -29
View File
@@ -1,30 +1,30 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**
+2 -2
View File
@@ -1,3 +1,3 @@
bin/
obj/
bin/
obj/
.vs/
@@ -1,20 +1,20 @@
using IM_API.Models;
namespace IM_API.Aggregate
{
public class FriendRequestAggregate
{
public Friend Friend { get; private set; }
public FriendRequest FriendRequest { get; private set; }
public FriendRequestAggregate() { }
public FriendRequestAggregate(Friend friend,FriendRequest friendRequest)
{
Friend = friend;
FriendRequest = friendRequest;
}
public void Accept(string? remarkName = null)
{
}
}
}
using IM_API.Models;
namespace IM_API.Aggregate
{
public class FriendRequestAggregate
{
public Friend Friend { get; private set; }
public FriendRequest FriendRequest { get; private set; }
public FriendRequestAggregate() { }
public FriendRequestAggregate(Friend friend,FriendRequest friendRequest)
{
Friend = friend;
FriendRequest = friendRequest;
}
public void Accept(string? remarkName = null)
{
}
}
}
@@ -1,23 +1,23 @@
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.FriendAddHandler
{
public class FriendAddConversationHandler : IConsumer<FriendAddEvent>
{
private readonly IConversationService _cService;
public FriendAddConversationHandler(IConversationService cService)
{
_cService = cService;
}
public async Task Consume(ConsumeContext<FriendAddEvent> context)
{
var @event = context.Message;
await _cService.MakeConversationAsync(@event.RequestUserId, @event.ResponseUserId, Models.ChatType.PRIVATE);
await _cService.MakeConversationAsync(@event.ResponseUserId, @event.RequestUserId, Models.ChatType.PRIVATE);
}
}
}
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.FriendAddHandler
{
public class FriendAddConversationHandler : IConsumer<FriendAddEvent>
{
private readonly IConversationService _cService;
public FriendAddConversationHandler(IConversationService cService)
{
_cService = cService;
}
public async Task Consume(ConsumeContext<FriendAddEvent> context)
{
var @event = context.Message;
await _cService.MakeConversationAsync(@event.RequestUserId, @event.ResponseUserId, Models.ChatType.PRIVATE);
await _cService.MakeConversationAsync(@event.ResponseUserId, @event.RequestUserId, Models.ChatType.PRIVATE);
}
}
}
@@ -1,29 +1,29 @@
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.FriendAddHandler
{
public class FriendAddDBHandler : IConsumer<FriendAddEvent>
{
private readonly IFriendSerivce _friendService;
private readonly ILogger<FriendAddDBHandler> _logger;
public FriendAddDBHandler(IFriendSerivce friendService, ILogger<FriendAddDBHandler> logger)
{
_friendService = friendService;
_logger = logger;
}
public async Task Consume(ConsumeContext<FriendAddEvent> context)
{
var @event = context.Message;
//为请求发起人添加好友记录
await _friendService.MakeFriendshipAsync(
@event.RequestUserId, @event.ResponseUserId, @event.RequestInfo.RemarkName);
//为接收人添加好友记录
await _friendService.MakeFriendshipAsync(
@event.ResponseUserId, @event.RequestUserId, @event.requestUserRemarkname);
}
}
}
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.FriendAddHandler
{
public class FriendAddDBHandler : IConsumer<FriendAddEvent>
{
private readonly IFriendSerivce _friendService;
private readonly ILogger<FriendAddDBHandler> _logger;
public FriendAddDBHandler(IFriendSerivce friendService, ILogger<FriendAddDBHandler> logger)
{
_friendService = friendService;
_logger = logger;
}
public async Task Consume(ConsumeContext<FriendAddEvent> context)
{
var @event = context.Message;
//为请求发起人添加好友记录
await _friendService.MakeFriendshipAsync(
@event.RequestUserId, @event.ResponseUserId, @event.RequestInfo.RemarkName);
//为接收人添加好友记录
await _friendService.MakeFriendshipAsync(
@event.ResponseUserId, @event.RequestUserId, @event.requestUserRemarkname);
}
}
}
@@ -1,37 +1,37 @@
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.Interface.Services;
using IM_API.Models;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.FriendAddHandler
{
public class FriendAddSignalRHandler : IConsumer<FriendAddEvent>
{
private readonly IHubContext<ChatHub> _chathub;
public FriendAddSignalRHandler(IHubContext<ChatHub> chathub)
{
_chathub = chathub;
}
public async Task Consume(ConsumeContext<FriendAddEvent> context)
{
var @event = context.Message;
var usersList = new List<string> {
@event.RequestUserId.ToString(), @event.ResponseUserId.ToString()
};
var res = new HubResponse<MessageBaseDto>("Event", new MessageBaseDto()
{
ChatType = ChatType.PRIVATE,
Content = "您有新的好友关系已添加",
//MsgId = @event.EventId.ToString(),
ReceiverId = @event.ResponseUserId,
SenderId = @event.RequestUserId,
TimeStamp = DateTime.Now
});
await _chathub.Clients.Users(usersList).SendAsync("ReceiveMessage", res);
}
}
}
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.Interface.Services;
using IM_API.Models;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.FriendAddHandler
{
public class FriendAddSignalRHandler : IConsumer<FriendAddEvent>
{
private readonly IHubContext<ChatHub> _chathub;
public FriendAddSignalRHandler(IHubContext<ChatHub> chathub)
{
_chathub = chathub;
}
public async Task Consume(ConsumeContext<FriendAddEvent> context)
{
var @event = context.Message;
var usersList = new List<string> {
@event.RequestUserId.ToString(), @event.ResponseUserId.ToString()
};
var res = new HubResponse<MessageBaseDto>("Event", new MessageBaseDto()
{
ChatType = ChatType.PRIVATE,
Content = "您有新的好友关系已添加",
//MsgId = @event.EventId.ToString(),
ReceiverId = @event.ResponseUserId,
SenderId = @event.RequestUserId,
TimeStamp = DateTime.Now
});
await _chathub.Clients.Users(usersList).SendAsync("ReceiveMessage", res);
}
}
}
@@ -1,24 +1,24 @@
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupInviteActionUpdateHandler
{
public class RequestDbHandler : IConsumer<GroupInviteActionUpdateEvent>
{
private readonly IGroupService _groupService;
public RequestDbHandler(IGroupService groupService)
{
_groupService = groupService;
}
public async Task Consume(ConsumeContext<GroupInviteActionUpdateEvent> context)
{
var @event = context.Message;
if(@event.Action == Models.GroupInviteState.Passed)
{
await _groupService.MakeGroupRequestAsync(@event.UserId, @event.InviteUserId,@event.GroupId);
}
}
}
}
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupInviteActionUpdateHandler
{
public class RequestDbHandler : IConsumer<GroupInviteActionUpdateEvent>
{
private readonly IGroupService _groupService;
public RequestDbHandler(IGroupService groupService)
{
_groupService = groupService;
}
public async Task Consume(ConsumeContext<GroupInviteActionUpdateEvent> context)
{
var @event = context.Message;
if(@event.Action == Models.GroupInviteState.Passed)
{
await _groupService.MakeGroupRequestAsync(@event.UserId, @event.InviteUserId,@event.GroupId);
}
}
}
}
@@ -1,34 +1,34 @@
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.VOs.Group;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.GroupInviteActionUpdateHandler
{
public class SignalRHandler : IConsumer<GroupInviteActionUpdateEvent>
{
private IHubContext<ChatHub> _hub;
public SignalRHandler(IHubContext<ChatHub> hub)
{
_hub = hub;
}
public async Task Consume(ConsumeContext<GroupInviteActionUpdateEvent> context)
{
var @event = context.Message;
var msg = new HubResponse<GroupInviteActionUpdateVo>("Event", new GroupInviteActionUpdateVo
{
Action = @event.Action,
GroupId = @event.GroupId,
InvitedUserId = @event.UserId,
InviteUserId = @event.InviteUserId,
InviteId = @event.InviteId
});
await _hub.Clients.Users([@event.UserId.ToString(), @event.InviteUserId.ToString()])
.SendAsync("ReceiveMessage",msg);
}
}
}
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.VOs.Group;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.GroupInviteActionUpdateHandler
{
public class SignalRHandler : IConsumer<GroupInviteActionUpdateEvent>
{
private IHubContext<ChatHub> _hub;
public SignalRHandler(IHubContext<ChatHub> hub)
{
_hub = hub;
}
public async Task Consume(ConsumeContext<GroupInviteActionUpdateEvent> context)
{
var @event = context.Message;
var msg = new HubResponse<GroupInviteActionUpdateVo>("Event", new GroupInviteActionUpdateVo
{
Action = @event.Action,
GroupId = @event.GroupId,
InvitedUserId = @event.UserId,
InviteUserId = @event.InviteUserId,
InviteId = @event.InviteId
});
await _hub.Clients.Users([@event.UserId.ToString(), @event.InviteUserId.ToString()])
.SendAsync("ReceiveMessage",msg);
}
}
}
@@ -1,26 +1,26 @@
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.VOs.Group;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.GroupInviteHandler
{
public class GroupInviteSignalRHandler : IConsumer<GroupInviteEvent>
{
private readonly IHubContext<ChatHub> _hub;
public GroupInviteSignalRHandler(IHubContext<ChatHub> hub)
{
_hub = hub;
}
public async Task Consume(ConsumeContext<GroupInviteEvent> context)
{
var @event = context.Message;
var list = @event.Ids.Select(id => id.ToString()).ToArray();
var msg = new HubResponse<GroupInviteVo>("Event", new GroupInviteVo { GroupId = @event.GroupId, UserId = @event.UserId });
await _hub.Clients.Users(list).SendAsync("ReceiveMessage", msg);
}
}
}
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.VOs.Group;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.GroupInviteHandler
{
public class GroupInviteSignalRHandler : IConsumer<GroupInviteEvent>
{
private readonly IHubContext<ChatHub> _hub;
public GroupInviteSignalRHandler(IHubContext<ChatHub> hub)
{
_hub = hub;
}
public async Task Consume(ConsumeContext<GroupInviteEvent> context)
{
var @event = context.Message;
var list = @event.Ids.Select(id => id.ToString()).ToArray();
var msg = new HubResponse<GroupInviteVo>("Event", new GroupInviteVo { GroupId = @event.GroupId, UserId = @event.UserId });
await _hub.Clients.Users(list).SendAsync("ReceiveMessage", msg);
}
}
}
@@ -1,21 +1,21 @@
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupJoinHandler
{
public class GroupJoinConversationHandler : IConsumer<GroupJoinEvent>
{
private IConversationService _conversationService;
public GroupJoinConversationHandler(IConversationService conversationService)
{
_conversationService = conversationService;
}
public async Task Consume(ConsumeContext<GroupJoinEvent> context)
{
var @event = context.Message;
await _conversationService.MakeConversationAsync(@event.UserId, @event.GroupId, Models.ChatType.GROUP);
}
}
}
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupJoinHandler
{
public class GroupJoinConversationHandler : IConsumer<GroupJoinEvent>
{
private IConversationService _conversationService;
public GroupJoinConversationHandler(IConversationService conversationService)
{
_conversationService = conversationService;
}
public async Task Consume(ConsumeContext<GroupJoinEvent> context)
{
var @event = context.Message;
await _conversationService.MakeConversationAsync(@event.UserId, @event.GroupId, Models.ChatType.GROUP);
}
}
}
@@ -1,22 +1,22 @@
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupJoinHandler
{
public class GroupJoinDbHandler : IConsumer<GroupJoinEvent>
{
private readonly IGroupService _groupService;
public GroupJoinDbHandler(IGroupService groupService)
{
_groupService = groupService;
}
public async Task Consume(ConsumeContext<GroupJoinEvent> context)
{
await _groupService.MakeGroupMemberAsync(context.Message.UserId,
context.Message.GroupId, context.Message.IsCreated ?
Models.GroupMemberRole.Master : Models.GroupMemberRole.Normal);
}
}
}
using IM_API.Domain.Events;
using IM_API.Interface.Services;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupJoinHandler
{
public class GroupJoinDbHandler : IConsumer<GroupJoinEvent>
{
private readonly IGroupService _groupService;
public GroupJoinDbHandler(IGroupService groupService)
{
_groupService = groupService;
}
public async Task Consume(ConsumeContext<GroupJoinEvent> context)
{
await _groupService.MakeGroupMemberAsync(context.Message.UserId,
context.Message.GroupId, context.Message.IsCreated ?
Models.GroupMemberRole.Master : Models.GroupMemberRole.Normal);
}
}
}
@@ -1,45 +1,45 @@
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.Tools;
using IM_API.VOs.Group;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
using StackExchange.Redis;
namespace IM_API.Application.EventHandlers.GroupJoinHandler
{
public class GroupJoinSignalrHandler : IConsumer<GroupJoinEvent>
{
private readonly IHubContext<ChatHub> _hub;
private readonly IDatabase _redis;
public GroupJoinSignalrHandler(IHubContext<ChatHub> hub, IConnectionMultiplexer connectionMultiplexer)
{
_hub = hub;
_redis = connectionMultiplexer.GetDatabase();
}
public async Task Consume(ConsumeContext<GroupJoinEvent> context)
{
var @event = context.Message;
string stramKey = StreamKeyBuilder.Group(@event.GroupId);
//将用户加入群组通知
var list = await _redis.SetMembersAsync(RedisKeys.GetConnectionIdKey(@event.UserId.ToString()));
if(list != null && list.Length > 0)
{
var tasks = list.Select(connectionId =>
_hub.Groups.AddToGroupAsync(connectionId!, stramKey)
).ToList();
await Task.WhenAll(tasks);
}
//发送通知给群成员
var msg = new GroupJoinVo
{
GroupId = @event.GroupId,
UserId = @event.UserId
};
await _hub.Clients.Group(stramKey).SendAsync("ReceiveMessage",new HubResponse<GroupJoinVo>("Event",msg));
}
}
}
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.Tools;
using IM_API.VOs.Group;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
using StackExchange.Redis;
namespace IM_API.Application.EventHandlers.GroupJoinHandler
{
public class GroupJoinSignalrHandler : IConsumer<GroupJoinEvent>
{
private readonly IHubContext<ChatHub> _hub;
private readonly IDatabase _redis;
public GroupJoinSignalrHandler(IHubContext<ChatHub> hub, IConnectionMultiplexer connectionMultiplexer)
{
_hub = hub;
_redis = connectionMultiplexer.GetDatabase();
}
public async Task Consume(ConsumeContext<GroupJoinEvent> context)
{
var @event = context.Message;
string stramKey = StreamKeyBuilder.Group(@event.GroupId);
//将用户加入群组通知
var list = await _redis.SetMembersAsync(RedisKeys.GetConnectionIdKey(@event.UserId.ToString()));
if(list != null && list.Length > 0)
{
var tasks = list.Select(connectionId =>
_hub.Groups.AddToGroupAsync(connectionId!, stramKey)
).ToList();
await Task.WhenAll(tasks);
}
//发送通知给群成员
var msg = new GroupJoinVo
{
GroupId = @event.GroupId,
UserId = @event.UserId
};
await _hub.Clients.Group(stramKey).SendAsync("ReceiveMessage",new HubResponse<GroupJoinVo>("Event",msg));
}
}
}
@@ -1,17 +1,17 @@
using IM_API.Domain.Events;
using IM_API.Hubs;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.GroupRequestHandler
{
public class GroupRequestSignalRHandler(IHubContext<ChatHub> hubContext) : IConsumer<GroupRequestEvent>
{
private readonly IHubContext<ChatHub> _hub = hubContext;
public async Task Consume(ConsumeContext<GroupRequestEvent> context)
{
}
}
}
using IM_API.Domain.Events;
using IM_API.Hubs;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.GroupRequestHandler
{
public class GroupRequestSignalRHandler(IHubContext<ChatHub> hubContext) : IConsumer<GroupRequestEvent>
{
private readonly IHubContext<ChatHub> _hub = hubContext;
public async Task Consume(ConsumeContext<GroupRequestEvent> context)
{
}
}
}
@@ -1,31 +1,31 @@
using IM_API.Domain.Events;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupRequestHandler
{
public class NextEventHandler : IConsumer<GroupRequestEvent>
{
private readonly IPublishEndpoint _endpoint;
public NextEventHandler(IPublishEndpoint endpoint)
{
_endpoint = endpoint;
}
public async Task Consume(ConsumeContext<GroupRequestEvent> context)
{
var @event = context.Message;
if(@event.Action == Models.GroupRequestState.Passed)
{
await _endpoint.Publish(new GroupJoinEvent
{
AggregateId = @event.AggregateId,
OccurredAt = @event.OccurredAt,
EventId = Guid.NewGuid(),
GroupId = @event.GroupId,
OperatorId = @event.OperatorId,
UserId = @event.UserId
});
}
}
}
}
using IM_API.Domain.Events;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupRequestHandler
{
public class NextEventHandler : IConsumer<GroupRequestEvent>
{
private readonly IPublishEndpoint _endpoint;
public NextEventHandler(IPublishEndpoint endpoint)
{
_endpoint = endpoint;
}
public async Task Consume(ConsumeContext<GroupRequestEvent> context)
{
var @event = context.Message;
if(@event.Action == Models.GroupRequestState.Passed)
{
await _endpoint.Publish(new GroupJoinEvent
{
AggregateId = @event.AggregateId,
OccurredAt = @event.OccurredAt,
EventId = Guid.NewGuid(),
GroupId = @event.GroupId,
OperatorId = @event.OperatorId,
UserId = @event.UserId
});
}
}
}
}
@@ -1,31 +1,31 @@
using IM_API.Domain.Events;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupRequestUpdateHandler
{
public class NextEventHandler : IConsumer<GroupRequestUpdateEvent>
{
private readonly IPublishEndpoint _endpoint;
public NextEventHandler(IPublishEndpoint endpoint)
{
_endpoint = endpoint;
}
public async Task Consume(ConsumeContext<GroupRequestUpdateEvent> context)
{
var @event = context.Message;
if(@event.Action == Models.GroupRequestState.Passed)
{
await _endpoint.Publish(new GroupJoinEvent
{
AggregateId = @event.AggregateId,
OccurredAt = @event.OccurredAt,
EventId = Guid.NewGuid(),
GroupId = @event.GroupId,
OperatorId = @event.OperatorId,
UserId = @event.UserId
});
}
}
}
}
using IM_API.Domain.Events;
using MassTransit;
namespace IM_API.Application.EventHandlers.GroupRequestUpdateHandler
{
public class NextEventHandler : IConsumer<GroupRequestUpdateEvent>
{
private readonly IPublishEndpoint _endpoint;
public NextEventHandler(IPublishEndpoint endpoint)
{
_endpoint = endpoint;
}
public async Task Consume(ConsumeContext<GroupRequestUpdateEvent> context)
{
var @event = context.Message;
if(@event.Action == Models.GroupRequestState.Passed)
{
await _endpoint.Publish(new GroupJoinEvent
{
AggregateId = @event.AggregateId,
OccurredAt = @event.OccurredAt,
EventId = Guid.NewGuid(),
GroupId = @event.GroupId,
OperatorId = @event.OperatorId,
UserId = @event.UserId
});
}
}
}
}
@@ -1,29 +1,29 @@
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.VOs.Group;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.GroupRequestUpdateHandler
{
public class RequestUpdateSignalrHandler : IConsumer<GroupRequestUpdateEvent>
{
private readonly IHubContext<ChatHub> _hub;
public RequestUpdateSignalrHandler(IHubContext<ChatHub> hub)
{
_hub = hub;
}
public async Task Consume(ConsumeContext<GroupRequestUpdateEvent> context)
{
var msg = new HubResponse<GroupRequestUpdateVo>("Event", new GroupRequestUpdateVo
{
GroupId = context.Message.GroupId,
RequestId = context.Message.RequestId,
UserId = context.Message.UserId
});
await _hub.Clients.User(context.Message.UserId.ToString()).SendAsync("ReceiveMessage", msg);
}
}
}
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.VOs.Group;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.GroupRequestUpdateHandler
{
public class RequestUpdateSignalrHandler : IConsumer<GroupRequestUpdateEvent>
{
private readonly IHubContext<ChatHub> _hub;
public RequestUpdateSignalrHandler(IHubContext<ChatHub> hub)
{
_hub = hub;
}
public async Task Consume(ConsumeContext<GroupRequestUpdateEvent> context)
{
var msg = new HubResponse<GroupRequestUpdateVo>("Event", new GroupRequestUpdateVo
{
GroupId = context.Message.GroupId,
RequestId = context.Message.RequestId,
UserId = context.Message.UserId
});
await _hub.Clients.User(context.Message.UserId.ToString()).SendAsync("ReceiveMessage", msg);
}
}
}
@@ -1,66 +1,66 @@
using AutoMapper;
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Exceptions;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.Services;
using IM_API.Tools;
using MassTransit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace IM_API.Application.EventHandlers.MessageCreatedHandler
{
public class ConversationEventHandler : IConsumer<MessageCreatedEvent>
{
private readonly IConversationService _conversationService;
private readonly ILogger<ConversationEventHandler> _logger;
private readonly IUserService _userSerivce;
private readonly IGroupService _groupService;
public ConversationEventHandler(
IConversationService conversationService,
ILogger<ConversationEventHandler> logger,
IUserService userService,
IGroupService groupService
)
{
_conversationService = conversationService;
_logger = logger;
_userSerivce = userService;
_groupService = groupService;
}
public async Task Consume(ConsumeContext<MessageCreatedEvent> context)
{
var @event = context.Message;
if (@event.ChatType == ChatType.GROUP)
{
var userinfo = await _userSerivce.GetUserInfoAsync(@event.MsgSenderId);
await _groupService.UpdateGroupConversationAsync(new Dtos.Group.GroupUpdateConversationDto
{
GroupId = @event.MsgRecipientId,
LastMessage = @event.MessageContent,
LastSenderName = userinfo.NickName,
LastUpdateTime = @event.MessageCreated,
MaxSequenceId = @event.SequenceId
});
}
else
{
await _conversationService.UpdateConversationAfterSentAsync(new Dtos.Conversation.UpdateConversationDto
{
LastMessage = @event.MessageContent,
LastSequenceId = @event.SequenceId,
ReceiptId = @event.MsgRecipientId,
SenderId = @event.MsgSenderId,
StreamKey = @event.StreamKey,
DateTime = @event.MessageCreated
});
}
}
}
}
using AutoMapper;
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Exceptions;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.Services;
using IM_API.Tools;
using MassTransit;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
namespace IM_API.Application.EventHandlers.MessageCreatedHandler
{
public class ConversationEventHandler : IConsumer<MessageCreatedEvent>
{
private readonly IConversationService _conversationService;
private readonly ILogger<ConversationEventHandler> _logger;
private readonly IUserService _userSerivce;
private readonly IGroupService _groupService;
public ConversationEventHandler(
IConversationService conversationService,
ILogger<ConversationEventHandler> logger,
IUserService userService,
IGroupService groupService
)
{
_conversationService = conversationService;
_logger = logger;
_userSerivce = userService;
_groupService = groupService;
}
public async Task Consume(ConsumeContext<MessageCreatedEvent> context)
{
var @event = context.Message;
if (@event.ChatType == ChatType.GROUP)
{
var userinfo = await _userSerivce.GetUserInfoAsync(@event.MsgSenderId);
await _groupService.UpdateGroupConversationAsync(new Dtos.Group.GroupUpdateConversationDto
{
GroupId = @event.MsgRecipientId,
LastMessage = @event.MessageContent,
LastSenderName = userinfo.NickName,
LastUpdateTime = @event.MessageCreated,
MaxSequenceId = @event.SequenceId
});
}
else
{
await _conversationService.UpdateConversationAfterSentAsync(new Dtos.Conversation.UpdateConversationDto
{
LastMessage = @event.MessageContent,
LastSequenceId = @event.SequenceId,
ReceiptId = @event.MsgRecipientId,
SenderId = @event.MsgSenderId,
StreamKey = @event.StreamKey,
DateTime = @event.MessageCreated
});
}
}
}
}
@@ -1,26 +1,26 @@
using IM_API.Domain.Events;
using MassTransit;
using IM_API.Interface.Services;
using AutoMapper;
using IM_API.Models;
namespace IM_API.Application.EventHandlers.MessageCreatedHandler
{
public class MessageCreatedDbHandler : IConsumer<MessageCreatedEvent>
{
private readonly IMessageSevice _messageService;
public readonly IMapper _mapper;
public MessageCreatedDbHandler(IMessageSevice messageSevice, IMapper mapper)
{
_messageService = messageSevice;
_mapper = mapper;
}
public async Task Consume(ConsumeContext<MessageCreatedEvent> context)
{
var @event = context.Message;
var msg = _mapper.Map<Message>(@event);
await _messageService.MakeMessageAsync(msg);
}
}
}
using IM_API.Domain.Events;
using MassTransit;
using IM_API.Interface.Services;
using AutoMapper;
using IM_API.Models;
namespace IM_API.Application.EventHandlers.MessageCreatedHandler
{
public class MessageCreatedDbHandler : IConsumer<MessageCreatedEvent>
{
private readonly IMessageSevice _messageService;
public readonly IMapper _mapper;
public MessageCreatedDbHandler(IMessageSevice messageSevice, IMapper mapper)
{
_messageService = messageSevice;
_mapper = mapper;
}
public async Task Consume(ConsumeContext<MessageCreatedEvent> context)
{
var @event = context.Message;
var msg = _mapper.Map<Message>(@event);
await _messageService.MakeMessageAsync(msg);
}
}
}
@@ -1,48 +1,48 @@
using AutoMapper;
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.Tools;
using IM_API.VOs.Message;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.MessageCreatedHandler
{
public class SignalREventHandler : IConsumer<MessageCreatedEvent>
{
private readonly IHubContext<ChatHub> _hub;
private readonly IMapper _mapper;
private readonly IUserService _userService;
public SignalREventHandler(IHubContext<ChatHub> hub, IMapper mapper,IUserService userService)
{
_hub = hub;
_mapper = mapper;
_userService = userService;
}
public async Task Consume(ConsumeContext<MessageCreatedEvent> context)
{
Console.ForegroundColor = ConsoleColor.Red;
var @event = context.Message;
try
{
var entity = _mapper.Map<Message>(@event);
var messageBaseVo = _mapper.Map<MessageBaseVo>(entity);
var senderinfo = await _userService.GetUserInfoAsync(@event.MsgSenderId);
messageBaseVo.SenderName = senderinfo.NickName;
messageBaseVo.SenderAvatar = senderinfo.Avatar ?? "";
await _hub.Clients.Group(@event.StreamKey).SendAsync("ReceiveMessage", new HubResponse<MessageBaseVo>("Event", messageBaseVo));
}
catch (Exception ex)
{
Console.WriteLine($"[SignalR] 发送失败: {ex.Message}");
Console.ResetColor();
throw;
}
}
}
}
using AutoMapper;
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Hubs;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.Tools;
using IM_API.VOs.Message;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.MessageCreatedHandler
{
public class SignalREventHandler : IConsumer<MessageCreatedEvent>
{
private readonly IHubContext<ChatHub> _hub;
private readonly IMapper _mapper;
private readonly IUserService _userService;
public SignalREventHandler(IHubContext<ChatHub> hub, IMapper mapper,IUserService userService)
{
_hub = hub;
_mapper = mapper;
_userService = userService;
}
public async Task Consume(ConsumeContext<MessageCreatedEvent> context)
{
Console.ForegroundColor = ConsoleColor.Red;
var @event = context.Message;
try
{
var entity = _mapper.Map<Message>(@event);
var messageBaseVo = _mapper.Map<MessageBaseVo>(entity);
var senderinfo = await _userService.GetUserInfoAsync(@event.MsgSenderId);
messageBaseVo.SenderName = senderinfo.NickName;
messageBaseVo.SenderAvatar = senderinfo.Avatar ?? "";
await _hub.Clients.Group(@event.StreamKey).SendAsync("ReceiveMessage", new HubResponse<MessageBaseVo>("Event", messageBaseVo));
}
catch (Exception ex)
{
Console.WriteLine($"[SignalR] 发送失败: {ex.Message}");
Console.ResetColor();
throw;
}
}
}
}
@@ -1,37 +1,37 @@
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Dtos.Friend;
using IM_API.Hubs;
using IM_API.Interface.Services;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.RequestFriendHandler
{
public class RequestFriendSignalRHandler:IConsumer<RequestFriendEvent>
{
private readonly IHubContext<ChatHub> _hub;
private readonly IUserService _userService;
public RequestFriendSignalRHandler(IHubContext<ChatHub> hubContext, IUserService userService)
{
_hub = hubContext;
_userService = userService;
}
public async Task Consume(ConsumeContext<RequestFriendEvent> context)
{
var @event = context.Message;
var userInfo = await _userService.GetUserInfoAsync(@event.FromUserId);
var res = new HubResponse<FriendRequestResDto>("Event", new FriendRequestResDto()
{
RequestUser = @event.FromUserId,
ResponseUser = @event.ToUserId,
Created = DateTime.UtcNow,
Description = @event.Description,
Avatar = userInfo.Avatar,
NickName = userInfo.NickName
});
await _hub.Clients.User(@event.ToUserId.ToString()).SendAsync("ReceiveMessage", res);
}
}
}
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Dtos.Friend;
using IM_API.Hubs;
using IM_API.Interface.Services;
using MassTransit;
using Microsoft.AspNetCore.SignalR;
namespace IM_API.Application.EventHandlers.RequestFriendHandler
{
public class RequestFriendSignalRHandler:IConsumer<RequestFriendEvent>
{
private readonly IHubContext<ChatHub> _hub;
private readonly IUserService _userService;
public RequestFriendSignalRHandler(IHubContext<ChatHub> hubContext, IUserService userService)
{
_hub = hubContext;
_userService = userService;
}
public async Task Consume(ConsumeContext<RequestFriendEvent> context)
{
var @event = context.Message;
var userInfo = await _userService.GetUserInfoAsync(@event.FromUserId);
var res = new HubResponse<FriendRequestResDto>("Event", new FriendRequestResDto()
{
RequestUser = @event.FromUserId,
ResponseUser = @event.ToUserId,
Created = DateTime.UtcNow,
Description = @event.Description,
Avatar = userInfo.Avatar,
NickName = userInfo.NickName
});
await _hub.Clients.User(@event.ToUserId.ToString()).SendAsync("ReceiveMessage", res);
}
}
}
@@ -1,9 +1,9 @@
using IM_API.Domain.Interfaces;
namespace IM_API.Application.Interfaces
{
public interface IEventBus
{
Task PublishAsync<TEvent>(TEvent @event) where TEvent : IEvent;
}
}
using IM_API.Domain.Interfaces;
namespace IM_API.Application.Interfaces
{
public interface IEventBus
{
Task PublishAsync<TEvent>(TEvent @event) where TEvent : IEvent;
}
}
@@ -1,9 +1,9 @@
using IM_API.Domain.Interfaces;
namespace IM_API.Application.Interfaces
{
public interface IEventHandler<in TEvent> where TEvent : IEvent
{
Task Handle(TEvent @event);
}
}
using IM_API.Domain.Interfaces;
namespace IM_API.Application.Interfaces
{
public interface IEventHandler<in TEvent> where TEvent : IEvent
{
Task Handle(TEvent @event);
}
}
+65 -65
View File
@@ -1,65 +1,65 @@
using AutoMapper;
using IM_API.Application.EventHandlers.FriendAddHandler;
using IM_API.Application.EventHandlers.GroupInviteActionUpdateHandler;
using IM_API.Application.EventHandlers.GroupInviteHandler;
using IM_API.Application.EventHandlers.GroupJoinHandler;
using IM_API.Application.EventHandlers.GroupRequestHandler;
using IM_API.Application.EventHandlers.GroupRequestUpdateHandler;
using IM_API.Application.EventHandlers.MessageCreatedHandler;
using IM_API.Application.EventHandlers.RequestFriendHandler;
using IM_API.Configs.Options;
using IM_API.Domain.Events;
using MassTransit;
using MySqlConnector;
namespace IM_API.Configs
{
public static class MQConfig
{
public static IServiceCollection AddRabbitMQ(this IServiceCollection services, RabbitMQOptions options)
{
services.AddMassTransit(x =>
{
x.AddConsumer<ConversationEventHandler>();
x.AddConsumer<SignalREventHandler>();
x.AddConsumer<FriendAddDBHandler>();
x.AddConsumer<FriendAddSignalRHandler>();
x.AddConsumer<RequestFriendSignalRHandler>();
x.AddConsumer<FriendAddConversationHandler>();
x.AddConsumer<MessageCreatedDbHandler>();
x.AddConsumer<GroupJoinConversationHandler>();
x.AddConsumer<GroupJoinDbHandler>();
x.AddConsumer<GroupJoinSignalrHandler>();
x.AddConsumer<GroupRequestSignalRHandler>();
x.AddConsumer<Application.EventHandlers.GroupRequestHandler.NextEventHandler>();
x.AddConsumer<Application.EventHandlers.GroupRequestUpdateHandler.NextEventHandler>();
x.AddConsumer<GroupInviteSignalRHandler>();
x.AddConsumer<RequestDbHandler>();
x.AddConsumer<SignalRHandler>();
x.AddConsumer<RequestUpdateSignalrHandler>();
x.UsingRabbitMq((ctx,cfg) =>
{
cfg.Host(options.Host, "/", h =>
{
h.Username(options.Username);
h.Password(options.Password);
});
cfg.ConfigureEndpoints(ctx);
cfg.UseMessageRetry(r =>
{
r.Handle<IOException>();
r.Handle<MySqlException>();
r.Ignore<AutoMapperMappingException>();
r.Exponential(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(2));
});
cfg.ConfigureEndpoints(ctx);
});
});
return services;
}
}
}
using AutoMapper;
using IM_API.Application.EventHandlers.FriendAddHandler;
using IM_API.Application.EventHandlers.GroupInviteActionUpdateHandler;
using IM_API.Application.EventHandlers.GroupInviteHandler;
using IM_API.Application.EventHandlers.GroupJoinHandler;
using IM_API.Application.EventHandlers.GroupRequestHandler;
using IM_API.Application.EventHandlers.GroupRequestUpdateHandler;
using IM_API.Application.EventHandlers.MessageCreatedHandler;
using IM_API.Application.EventHandlers.RequestFriendHandler;
using IM_API.Configs.Options;
using IM_API.Domain.Events;
using MassTransit;
using MySqlConnector;
namespace IM_API.Configs
{
public static class MQConfig
{
public static IServiceCollection AddRabbitMQ(this IServiceCollection services, RabbitMQOptions options)
{
services.AddMassTransit(x =>
{
x.AddConsumer<ConversationEventHandler>();
x.AddConsumer<SignalREventHandler>();
x.AddConsumer<FriendAddDBHandler>();
x.AddConsumer<FriendAddSignalRHandler>();
x.AddConsumer<RequestFriendSignalRHandler>();
x.AddConsumer<FriendAddConversationHandler>();
x.AddConsumer<MessageCreatedDbHandler>();
x.AddConsumer<GroupJoinConversationHandler>();
x.AddConsumer<GroupJoinDbHandler>();
x.AddConsumer<GroupJoinSignalrHandler>();
x.AddConsumer<GroupRequestSignalRHandler>();
x.AddConsumer<Application.EventHandlers.GroupRequestHandler.NextEventHandler>();
x.AddConsumer<Application.EventHandlers.GroupRequestUpdateHandler.NextEventHandler>();
x.AddConsumer<GroupInviteSignalRHandler>();
x.AddConsumer<RequestDbHandler>();
x.AddConsumer<SignalRHandler>();
x.AddConsumer<RequestUpdateSignalrHandler>();
x.UsingRabbitMq((ctx,cfg) =>
{
cfg.Host(options.Host, "/", h =>
{
h.Username(options.Username);
h.Password(options.Password);
});
cfg.ConfigureEndpoints(ctx);
cfg.UseMessageRetry(r =>
{
r.Handle<IOException>();
r.Handle<MySqlException>();
r.Ignore<AutoMapperMappingException>();
r.Exponential(5, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(60), TimeSpan.FromSeconds(2));
});
cfg.ConfigureEndpoints(ctx);
});
});
return services;
}
}
}
+176 -176
View File
@@ -1,176 +1,176 @@
using AutoMapper;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Dtos.Auth;
using IM_API.Dtos.Friend;
using IM_API.Dtos.Group;
using IM_API.Dtos.User;
using IM_API.Models;
using IM_API.Tools;
using IM_API.VOs.Conversation;
using IM_API.VOs.Message;
namespace IM_API.Configs
{
public class MapperConfig:Profile
{
public MapperConfig()
{
CreateMap<User, UserInfoDto>();
//用户信息更新模型转换
CreateMap<UpdateUserDto, User>()
.ForMember(dest => dest.Updated,opt => opt.MapFrom(src => DateTime.Now))
.ForAllMembers(opts => opts.Condition((src,dest,srcMember) => srcMember != null));
//用户注册模型转换
CreateMap<RegisterRequestDto, User>()
.ForMember(dest => dest.Username,opt => opt.MapFrom(src => src.Username))
.ForMember(dest => dest.Password,opt => opt.MapFrom(src => src.Password))
.ForMember(dest => dest.Avatar,opt => opt.MapFrom(src => "https://ts1.tc.mm.bing.net/th/id/OIP-C.dl0WpkTP6E2J4FnhDC_jHwAAAA?rs=1&pid=ImgDetMain&o=7&rm=3"))
.ForMember(dest => dest.StatusEnum,opt => opt.MapFrom(src => UserStatus.Normal))
.ForMember(dest => dest.OnlineStatusEnum,opt => opt.MapFrom(src => UserOnlineStatus.Offline))
.ForMember(dest => dest.NickName,opt => opt.MapFrom(src => src.NickName??"默认用户"))
.ForMember(dest => dest.Created,opt => opt.MapFrom(src => DateTime.Now))
.ForMember(dest => dest.IsDeleted,opt => opt.MapFrom(src => 0))
;
//好友信息模型转换
CreateMap<Friend, FriendInfoDto>()
.ForMember(dest => dest.UserInfo, opt => opt.MapFrom(src => src.FriendNavigation))
.ForMember(dest => dest.Avatar, opt => opt.MapFrom(src => src.FriendNavigation.Avatar))
;
//好友请求通过后新增好友关系
CreateMap<FriendRequestDto, Friend>()
.ForMember(dest => dest.UserId , opt => opt.MapFrom(src => src.FromUserId))
.ForMember(dest => dest.FriendId , opt => opt.MapFrom(src => src.ToUserId))
.ForMember(dest => dest.StatusEnum , opt =>opt.MapFrom(src => FriendStatus.Pending))
.ForMember(dest => dest.RemarkName , opt => opt.MapFrom(src => src.RemarkName))
.ForMember(dest => dest.Created , opt => opt.MapFrom(src => DateTime.Now))
;
//发起好友请求转换请求对象
CreateMap<FriendRequestDto, FriendRequest>()
.ForMember(dest => dest.RequestUser , opt => opt.MapFrom(src => src.FromUserId))
.ForMember(dest => dest.ResponseUser , opt => opt.MapFrom(src => src.ToUserId))
.ForMember(dest => dest.Created , opt => opt.MapFrom(src => DateTime.Now))
.ForMember(dest => dest.StateEnum , opt => opt.MapFrom(src => FriendRequestState.Pending))
.ForMember(dest => dest.Description , opt => opt.MapFrom(src => src.Description))
;
CreateMap<FriendRequest, FriendRequestDto>()
.ForMember(dest => dest.ToUserId, opt => opt.MapFrom(src => src.ResponseUser))
.ForMember(dest => dest.FromUserId, opt => opt.MapFrom(src => src.RequestUser))
.ForMember(dest => dest.RemarkName, opt => opt.MapFrom(src => src.RemarkName))
.ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description))
;
//消息模型转换
CreateMap<Message, MessageBaseVo>()
.ForMember(dest => dest.Type , opt => opt.MapFrom(src => src.MsgTypeEnum))
.ForMember(dest => dest.MsgId , opt => opt.MapFrom(src => src.ClientMsgId))
.ForMember(dest => dest.SenderId , opt => opt.MapFrom(src => src.Sender))
.ForMember(dest => dest.ChatType , opt => opt.MapFrom(src => src.ChatTypeEnum))
.ForMember(dest => dest.ReceiverId, opt => opt.MapFrom(src => src.Recipient))
.ForMember(dest => dest.Content, opt => opt.MapFrom(src => src.Content))
.ForMember(dest => dest.TimeStamp, opt => opt.MapFrom(src => src.Created))
.ForMember(dest => dest.SequenceId, opt => opt.MapFrom(src => src.SequenceId))
;
CreateMap<MessageBaseDto, Message>()
.ForMember(dest => dest.Sender, opt => opt.MapFrom(src => src.SenderId))
.ForMember(dest => dest.ChatTypeEnum,opt => opt.MapFrom(src => src.ChatType))
.ForMember(dest => dest.MsgTypeEnum, opt => opt.MapFrom(src => src.Type))
.ForMember(dest => dest.Created, opt => opt.MapFrom(src => src.TimeStamp))
.ForMember(dest => dest.Content, opt => opt.MapFrom(src => src.Content))
.ForMember(dest => dest.Recipient, opt => opt.MapFrom(src => src.ReceiverId))
.ForMember(dest => dest.StreamKey, opt => opt.Ignore() )
.ForMember(dest => dest.StateEnum, opt => opt.MapFrom(src => MessageState.Sent))
.ForMember(dest => dest.ChatType, opt => opt.Ignore())
.ForMember(dest => dest.MsgType, opt => opt.Ignore())
.ForMember(dest => dest.ClientMsgId, opt => opt.MapFrom(src => src.MsgId))
;
//会话对象深拷贝
CreateMap<Conversation, Conversation>()
.ForMember(dest => dest.Id, opt => opt.Ignore())
.ForMember(dest => dest.UserId, opt => opt.Ignore())
.ForMember(dest => dest.TargetId, opt => opt.Ignore())
.ForMember(dest => dest.ChatType, opt => opt.Ignore())
.ForMember(dest => dest.StreamKey, opt => opt.Ignore())
;
//消息对象转消息创建事件对象
CreateMap<Message, MessageCreatedEvent>()
.ForMember(dest => dest.MessageMsgType, opt => opt.MapFrom(src => src.MsgTypeEnum))
.ForMember(dest => dest.ChatType, opt => opt.MapFrom(src => src.ChatTypeEnum))
.ForMember(dest => dest.MessageContent, opt => opt.MapFrom(src => src.Content))
.ForMember(dest => dest.State, opt => opt.MapFrom(src => src.StateEnum))
.ForMember(dest => dest.MessageCreated, opt => opt.MapFrom(src => src.Created))
.ForMember(dest => dest.MsgRecipientId, opt => opt.MapFrom(src => src.Recipient))
.ForMember(dest => dest.MsgSenderId, opt => opt.MapFrom(src => src.Sender))
.ForMember(dest => dest.EventId, opt => opt.MapFrom(src => Guid.NewGuid()))
.ForMember(dest => dest.AggregateId, opt => opt.MapFrom(src => src.Sender.ToString()))
.ForMember(dest => dest.OccurredAt , opt => opt.MapFrom(src => DateTime.Now))
.ForMember(dest => dest.OperatorId, opt => opt.MapFrom(src => src.Sender))
.ForMember(dest => dest.StreamKey, opt => opt.MapFrom(src => src.StreamKey))
;
CreateMap<MessageCreatedEvent, Message>()
.ForMember(dest => dest.SequenceId, opt => opt.MapFrom(src => src.SequenceId))
.ForMember(dest => dest.ClientMsgId, opt => opt.MapFrom(src => src.ClientMsgId))
.ForMember(dest => dest.StateEnum, opt => opt.MapFrom(src => src.State))
.ForMember(dest => dest.ChatTypeEnum, opt => opt.MapFrom(src => src.ChatType))
.ForMember(dest => dest.Content, opt => opt.MapFrom(src => src.MessageContent))
.ForMember(dest => dest.Created, opt => opt.MapFrom(src => src.MessageCreated))
.ForMember(dest => dest.MsgTypeEnum, opt => opt.MapFrom(src => src.MessageMsgType))
.ForMember(dest => dest.Recipient, opt => opt.MapFrom(src => src.MsgRecipientId))
.ForMember(dest => dest.Sender, opt => opt.MapFrom(src => src.MsgSenderId))
.ForMember(dest => dest.StreamKey, opt => opt.MapFrom(src => src.StreamKey))
.ForMember(dest => dest.ChatType, opt => opt.Ignore())
.ForMember(dest => dest.State, opt => opt.Ignore())
.ForMember(dest => dest.MsgType, opt => opt.Ignore());
//消息发送事件转换会话对象
CreateMap<MessageCreatedEvent, Conversation>()
//.ForMember(dest => dest.LastReadMessageId, opt => opt.MapFrom(src => src.MessageId))
.ForMember(dest => dest.LastMessage, opt => opt.MapFrom(src => src.MessageContent))
.ForMember(dest => dest.ChatType, opt => opt.MapFrom(src => src.ChatType))
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.MsgSenderId))
.ForMember(dest => dest.TargetId, opt => opt.MapFrom(src => src.MsgRecipientId))
.ForMember(dest => dest.UnreadCount, opt => opt.MapFrom(src => 0))
.ForMember(dest => dest.StreamKey, opt => opt.MapFrom(src => src.StreamKey))
.ForMember(dest => dest.LastMessageTime, opt => opt.MapFrom(src => DateTime.Now))
;
//创建会话对象
CreateMap<Conversation, ConversationVo>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.LastMessage, opt => opt.MapFrom(src => src.LastMessage))
.ForMember(dest => dest.LastSequenceId, opt => opt.MapFrom(src => src.LastReadSequenceId))
.ForMember(dest => dest.ChatType, opt => opt.MapFrom(src => src.ChatTypeEnum))
.ForMember(dest => dest.DateTime, opt => opt.MapFrom(src => src.LastMessageTime))
.ForMember(dest => dest.TargetId, opt => opt.MapFrom(src => src.TargetId))
.ForMember(dest => dest.UnreadCount, opt => opt.MapFrom(src => src.UnreadCount))
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.UserId));
CreateMap<Friend, ConversationVo>()
.ForMember(dest => dest.TargetAvatar, opt => opt.MapFrom(src => src.FriendNavigation.Avatar))
.ForMember(dest => dest.TargetName, opt => opt.MapFrom(src => src.RemarkName));
CreateMap<Group, ConversationVo>()
.ForMember(dest => dest.TargetAvatar, opt => opt.MapFrom(src => src.Avatar))
.ForMember(dest => dest.TargetName, opt => opt.MapFrom(src => src.Name));
//群模型转换
CreateMap<Group, GroupInfoDto>()
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.StatusEnum))
.ForMember(dest => dest.AllMembersBanned, opt => opt.MapFrom(src => src.AllMembersBannedEnum))
.ForMember(dest => dest.Auhority, opt => opt.MapFrom(src => src.AuhorityEnum));
CreateMap<GroupCreateDto, Group>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.Avatar, opt => opt.MapFrom(src => src.Avatar))
.ForMember(dest => dest.Created, opt => opt.MapFrom(src => DateTime.Now))
.ForMember(dest => dest.AllMembersBannedEnum, opt => opt.MapFrom(src => GroupAllMembersBanned.ALLOWED))
.ForMember(dest => dest.AuhorityEnum, opt => opt.MapFrom(src => GroupAuhority.REQUIRE_CONSENT))
.ForMember(dest => dest.StatusEnum, opt => opt.MapFrom(src => GroupStatus.Normal))
;
}
}
}
using AutoMapper;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Dtos.Auth;
using IM_API.Dtos.Friend;
using IM_API.Dtos.Group;
using IM_API.Dtos.User;
using IM_API.Models;
using IM_API.Tools;
using IM_API.VOs.Conversation;
using IM_API.VOs.Message;
namespace IM_API.Configs
{
public class MapperConfig:Profile
{
public MapperConfig()
{
CreateMap<User, UserInfoDto>();
//用户信息更新模型转换
CreateMap<UpdateUserDto, User>()
.ForMember(dest => dest.Updated,opt => opt.MapFrom(src => DateTime.Now))
.ForAllMembers(opts => opts.Condition((src,dest,srcMember) => srcMember != null));
//用户注册模型转换
CreateMap<RegisterRequestDto, User>()
.ForMember(dest => dest.Username,opt => opt.MapFrom(src => src.Username))
.ForMember(dest => dest.Password,opt => opt.MapFrom(src => src.Password))
.ForMember(dest => dest.Avatar,opt => opt.MapFrom(src => "https://ts1.tc.mm.bing.net/th/id/OIP-C.dl0WpkTP6E2J4FnhDC_jHwAAAA?rs=1&pid=ImgDetMain&o=7&rm=3"))
.ForMember(dest => dest.StatusEnum,opt => opt.MapFrom(src => UserStatus.Normal))
.ForMember(dest => dest.OnlineStatusEnum,opt => opt.MapFrom(src => UserOnlineStatus.Offline))
.ForMember(dest => dest.NickName,opt => opt.MapFrom(src => src.NickName??"默认用户"))
.ForMember(dest => dest.Created,opt => opt.MapFrom(src => DateTime.Now))
.ForMember(dest => dest.IsDeleted,opt => opt.MapFrom(src => 0))
;
//好友信息模型转换
CreateMap<Friend, FriendInfoDto>()
.ForMember(dest => dest.UserInfo, opt => opt.MapFrom(src => src.FriendNavigation))
.ForMember(dest => dest.Avatar, opt => opt.MapFrom(src => src.FriendNavigation.Avatar))
;
//好友请求通过后新增好友关系
CreateMap<FriendRequestDto, Friend>()
.ForMember(dest => dest.UserId , opt => opt.MapFrom(src => src.FromUserId))
.ForMember(dest => dest.FriendId , opt => opt.MapFrom(src => src.ToUserId))
.ForMember(dest => dest.StatusEnum , opt =>opt.MapFrom(src => FriendStatus.Pending))
.ForMember(dest => dest.RemarkName , opt => opt.MapFrom(src => src.RemarkName))
.ForMember(dest => dest.Created , opt => opt.MapFrom(src => DateTime.Now))
;
//发起好友请求转换请求对象
CreateMap<FriendRequestDto, FriendRequest>()
.ForMember(dest => dest.RequestUser , opt => opt.MapFrom(src => src.FromUserId))
.ForMember(dest => dest.ResponseUser , opt => opt.MapFrom(src => src.ToUserId))
.ForMember(dest => dest.Created , opt => opt.MapFrom(src => DateTime.Now))
.ForMember(dest => dest.StateEnum , opt => opt.MapFrom(src => FriendRequestState.Pending))
.ForMember(dest => dest.Description , opt => opt.MapFrom(src => src.Description))
;
CreateMap<FriendRequest, FriendRequestDto>()
.ForMember(dest => dest.ToUserId, opt => opt.MapFrom(src => src.ResponseUser))
.ForMember(dest => dest.FromUserId, opt => opt.MapFrom(src => src.RequestUser))
.ForMember(dest => dest.RemarkName, opt => opt.MapFrom(src => src.RemarkName))
.ForMember(dest => dest.Description, opt => opt.MapFrom(src => src.Description))
;
//消息模型转换
CreateMap<Message, MessageBaseVo>()
.ForMember(dest => dest.Type , opt => opt.MapFrom(src => src.MsgTypeEnum))
.ForMember(dest => dest.MsgId , opt => opt.MapFrom(src => src.ClientMsgId))
.ForMember(dest => dest.SenderId , opt => opt.MapFrom(src => src.Sender))
.ForMember(dest => dest.ChatType , opt => opt.MapFrom(src => src.ChatTypeEnum))
.ForMember(dest => dest.ReceiverId, opt => opt.MapFrom(src => src.Recipient))
.ForMember(dest => dest.Content, opt => opt.MapFrom(src => src.Content))
.ForMember(dest => dest.TimeStamp, opt => opt.MapFrom(src => src.Created))
.ForMember(dest => dest.SequenceId, opt => opt.MapFrom(src => src.SequenceId))
;
CreateMap<MessageBaseDto, Message>()
.ForMember(dest => dest.Sender, opt => opt.MapFrom(src => src.SenderId))
.ForMember(dest => dest.ChatTypeEnum,opt => opt.MapFrom(src => src.ChatType))
.ForMember(dest => dest.MsgTypeEnum, opt => opt.MapFrom(src => src.Type))
.ForMember(dest => dest.Created, opt => opt.MapFrom(src => src.TimeStamp))
.ForMember(dest => dest.Content, opt => opt.MapFrom(src => src.Content))
.ForMember(dest => dest.Recipient, opt => opt.MapFrom(src => src.ReceiverId))
.ForMember(dest => dest.StreamKey, opt => opt.Ignore() )
.ForMember(dest => dest.StateEnum, opt => opt.MapFrom(src => MessageState.Sent))
.ForMember(dest => dest.ChatType, opt => opt.Ignore())
.ForMember(dest => dest.MsgType, opt => opt.Ignore())
.ForMember(dest => dest.ClientMsgId, opt => opt.MapFrom(src => src.MsgId))
;
//会话对象深拷贝
CreateMap<Conversation, Conversation>()
.ForMember(dest => dest.Id, opt => opt.Ignore())
.ForMember(dest => dest.UserId, opt => opt.Ignore())
.ForMember(dest => dest.TargetId, opt => opt.Ignore())
.ForMember(dest => dest.ChatType, opt => opt.Ignore())
.ForMember(dest => dest.StreamKey, opt => opt.Ignore())
;
//消息对象转消息创建事件对象
CreateMap<Message, MessageCreatedEvent>()
.ForMember(dest => dest.MessageMsgType, opt => opt.MapFrom(src => src.MsgTypeEnum))
.ForMember(dest => dest.ChatType, opt => opt.MapFrom(src => src.ChatTypeEnum))
.ForMember(dest => dest.MessageContent, opt => opt.MapFrom(src => src.Content))
.ForMember(dest => dest.State, opt => opt.MapFrom(src => src.StateEnum))
.ForMember(dest => dest.MessageCreated, opt => opt.MapFrom(src => src.Created))
.ForMember(dest => dest.MsgRecipientId, opt => opt.MapFrom(src => src.Recipient))
.ForMember(dest => dest.MsgSenderId, opt => opt.MapFrom(src => src.Sender))
.ForMember(dest => dest.EventId, opt => opt.MapFrom(src => Guid.NewGuid()))
.ForMember(dest => dest.AggregateId, opt => opt.MapFrom(src => src.Sender.ToString()))
.ForMember(dest => dest.OccurredAt , opt => opt.MapFrom(src => DateTime.Now))
.ForMember(dest => dest.OperatorId, opt => opt.MapFrom(src => src.Sender))
.ForMember(dest => dest.StreamKey, opt => opt.MapFrom(src => src.StreamKey))
;
CreateMap<MessageCreatedEvent, Message>()
.ForMember(dest => dest.SequenceId, opt => opt.MapFrom(src => src.SequenceId))
.ForMember(dest => dest.ClientMsgId, opt => opt.MapFrom(src => src.ClientMsgId))
.ForMember(dest => dest.StateEnum, opt => opt.MapFrom(src => src.State))
.ForMember(dest => dest.ChatTypeEnum, opt => opt.MapFrom(src => src.ChatType))
.ForMember(dest => dest.Content, opt => opt.MapFrom(src => src.MessageContent))
.ForMember(dest => dest.Created, opt => opt.MapFrom(src => src.MessageCreated))
.ForMember(dest => dest.MsgTypeEnum, opt => opt.MapFrom(src => src.MessageMsgType))
.ForMember(dest => dest.Recipient, opt => opt.MapFrom(src => src.MsgRecipientId))
.ForMember(dest => dest.Sender, opt => opt.MapFrom(src => src.MsgSenderId))
.ForMember(dest => dest.StreamKey, opt => opt.MapFrom(src => src.StreamKey))
.ForMember(dest => dest.ChatType, opt => opt.Ignore())
.ForMember(dest => dest.State, opt => opt.Ignore())
.ForMember(dest => dest.MsgType, opt => opt.Ignore());
//消息发送事件转换会话对象
CreateMap<MessageCreatedEvent, Conversation>()
//.ForMember(dest => dest.LastReadMessageId, opt => opt.MapFrom(src => src.MessageId))
.ForMember(dest => dest.LastMessage, opt => opt.MapFrom(src => src.MessageContent))
.ForMember(dest => dest.ChatType, opt => opt.MapFrom(src => src.ChatType))
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.MsgSenderId))
.ForMember(dest => dest.TargetId, opt => opt.MapFrom(src => src.MsgRecipientId))
.ForMember(dest => dest.UnreadCount, opt => opt.MapFrom(src => 0))
.ForMember(dest => dest.StreamKey, opt => opt.MapFrom(src => src.StreamKey))
.ForMember(dest => dest.LastMessageTime, opt => opt.MapFrom(src => DateTime.Now))
;
//创建会话对象
CreateMap<Conversation, ConversationVo>()
.ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
.ForMember(dest => dest.LastMessage, opt => opt.MapFrom(src => src.LastMessage))
.ForMember(dest => dest.LastSequenceId, opt => opt.MapFrom(src => src.LastReadSequenceId))
.ForMember(dest => dest.ChatType, opt => opt.MapFrom(src => src.ChatTypeEnum))
.ForMember(dest => dest.DateTime, opt => opt.MapFrom(src => src.LastMessageTime))
.ForMember(dest => dest.TargetId, opt => opt.MapFrom(src => src.TargetId))
.ForMember(dest => dest.UnreadCount, opt => opt.MapFrom(src => src.UnreadCount))
.ForMember(dest => dest.UserId, opt => opt.MapFrom(src => src.UserId));
CreateMap<Friend, ConversationVo>()
.ForMember(dest => dest.TargetAvatar, opt => opt.MapFrom(src => src.FriendNavigation.Avatar))
.ForMember(dest => dest.TargetName, opt => opt.MapFrom(src => src.RemarkName));
CreateMap<Group, ConversationVo>()
.ForMember(dest => dest.TargetAvatar, opt => opt.MapFrom(src => src.Avatar))
.ForMember(dest => dest.TargetName, opt => opt.MapFrom(src => src.Name));
//群模型转换
CreateMap<Group, GroupInfoDto>()
.ForMember(dest => dest.Status, opt => opt.MapFrom(src => src.StatusEnum))
.ForMember(dest => dest.AllMembersBanned, opt => opt.MapFrom(src => src.AllMembersBannedEnum))
.ForMember(dest => dest.Auhority, opt => opt.MapFrom(src => src.AuhorityEnum));
CreateMap<GroupCreateDto, Group>()
.ForMember(dest => dest.Name, opt => opt.MapFrom(src => src.Name))
.ForMember(dest => dest.Avatar, opt => opt.MapFrom(src => src.Avatar))
.ForMember(dest => dest.Created, opt => opt.MapFrom(src => DateTime.Now))
.ForMember(dest => dest.AllMembersBannedEnum, opt => opt.MapFrom(src => GroupAllMembersBanned.ALLOWED))
.ForMember(dest => dest.AuhorityEnum, opt => opt.MapFrom(src => GroupAuhority.REQUIRE_CONSENT))
.ForMember(dest => dest.StatusEnum, opt => opt.MapFrom(src => GroupStatus.Normal))
;
}
}
}
@@ -1,8 +1,8 @@
namespace IM_API.Configs.Options
{
public class ConnectionOptions
{
public string DefaultConnection { get; set; }
public string Redis { get; set; }
}
}
namespace IM_API.Configs.Options
{
public class ConnectionOptions
{
public string DefaultConnection { get; set; }
public string Redis { get; set; }
}
}
@@ -1,10 +1,10 @@
namespace IM_API.Configs.Options
{
public class RabbitMQOptions
{
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
namespace IM_API.Configs.Options
{
public class RabbitMQOptions
{
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
}
@@ -1,64 +1,64 @@
using IM_API.Application.EventHandlers;
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Infrastructure.EventBus;
using IM_API.Interface.Services;
using IM_API.Services;
using IM_API.Tools;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using RedLockNet;
using RedLockNet.SERedis;
using RedLockNet.SERedis.Configuration;
using StackExchange.Redis;
namespace IM_API.Configs
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddAllService(this IServiceCollection services, IConfiguration configuration)
{
services.AddAutoMapper(typeof(MapperConfig));
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IFriendSerivce, FriendService>();
services.AddScoped<IMessageSevice, MessageService>();
services.AddScoped<IConversationService, ConversationService>();
services.AddScoped<IGroupService, GroupService>();
services.AddScoped<ISequenceIdService, SequenceIdService>();
services.AddScoped<ICacheService, RedisCacheService>();
services.AddScoped<IEventBus, InMemoryEventBus>();
services.AddSingleton<IJWTService, JWTService>();
services.AddSingleton<IRefreshTokenService, RedisRefreshTokenService>();
services.AddSingleton<IDistributedLockFactory>(sp =>
{
var connection = sp.GetRequiredService<IConnectionMultiplexer>();
// 这里可以配置多个 Redis 节点提高安全性,单机运行传一个即可
return RedLockFactory.Create(new List<RedLockMultiplexer> { new RedLockMultiplexer(connection) });
});
return services;
}
public static IServiceCollection AddModelValidation(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var errors = context.ModelState
.Where(e => e.Value.Errors.Count > 0)
.Select(e => new
{
Field = e.Key,
Message = e.Value.Errors.First().ErrorMessage
});
Console.WriteLine(errors);
return new BadRequestObjectResult(new BaseResponse<object?>(CodeDefine.PARAMETER_ERROR.Code, errors.First().Message));
};
});
return services;
}
}
}
using IM_API.Application.EventHandlers;
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Infrastructure.EventBus;
using IM_API.Interface.Services;
using IM_API.Services;
using IM_API.Tools;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using RedLockNet;
using RedLockNet.SERedis;
using RedLockNet.SERedis.Configuration;
using StackExchange.Redis;
namespace IM_API.Configs
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddAllService(this IServiceCollection services, IConfiguration configuration)
{
services.AddAutoMapper(typeof(MapperConfig));
services.AddScoped<IAuthService, AuthService>();
services.AddScoped<IUserService, UserService>();
services.AddScoped<IFriendSerivce, FriendService>();
services.AddScoped<IMessageSevice, MessageService>();
services.AddScoped<IConversationService, ConversationService>();
services.AddScoped<IGroupService, GroupService>();
services.AddScoped<ISequenceIdService, SequenceIdService>();
services.AddScoped<ICacheService, RedisCacheService>();
services.AddScoped<IEventBus, InMemoryEventBus>();
services.AddSingleton<IJWTService, JWTService>();
services.AddSingleton<IRefreshTokenService, RedisRefreshTokenService>();
services.AddSingleton<IDistributedLockFactory>(sp =>
{
var connection = sp.GetRequiredService<IConnectionMultiplexer>();
// 这里可以配置多个 Redis 节点提高安全性,单机运行传一个即可
return RedLockFactory.Create(new List<RedLockMultiplexer> { new RedLockMultiplexer(connection) });
});
return services;
}
public static IServiceCollection AddModelValidation(this IServiceCollection services, IConfiguration configuration)
{
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var errors = context.ModelState
.Where(e => e.Value.Errors.Count > 0)
.Select(e => new
{
Field = e.Key,
Message = e.Value.Errors.First().ErrorMessage
});
Console.WriteLine(errors);
return new BadRequestObjectResult(new BaseResponse<object?>(CodeDefine.PARAMETER_ERROR.Code, errors.First().Message));
};
});
return services;
}
}
}
+82 -82
View File
@@ -1,82 +1,82 @@
using AutoMapper;
using IM_API.Dtos;
using IM_API.Dtos.Auth;
using IM_API.Dtos.User;
using IM_API.Interface.Services;
using IM_API.Tools;
using IM_API.VOs.Auth;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace IM_API.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly ILogger<AuthController> _logger;
private readonly IAuthService _authService;
private readonly IUserService _userService;
private readonly IJWTService _jwtService;
private readonly IRefreshTokenService _refreshTokenService;
private readonly IConfiguration _configuration;
private IMapper _mapper;
public AuthController(ILogger<AuthController> logger, IAuthService authService,
IJWTService jwtService, IRefreshTokenService refreshTokenService,
IConfiguration configuration,IUserService userService,
IMapper mapper
)
{
_logger = logger;
_authService = authService;
_jwtService = jwtService;
_refreshTokenService = refreshTokenService;
_configuration = configuration;
_userService = userService;
_mapper = mapper;
}
[HttpPost]
public async Task<IActionResult> Login(LoginRequestDto dto)
{
Stopwatch sw = Stopwatch.StartNew();
var user = await _authService.LoginAsync(dto);
_logger.LogInformation("服务耗时: {ms}ms", sw.ElapsedMilliseconds);
var userInfo = _mapper.Map<UserInfoDto>(user);
_logger.LogInformation("序列化耗时: {ms}ms", sw.ElapsedMilliseconds);
//生成凭证
(string token,DateTime expiresAt) = _jwtService.CreateAccessTokenForUser(user.Id,user.Username,"user");
_logger.LogInformation("Token生成耗时: {ms}ms", sw.ElapsedMilliseconds);
//生成刷新凭证
string refreshToken = await _refreshTokenService.CreateRefreshTokenAsync(user.Id);
_logger.LogInformation("RefreshToken生成耗时: {ms}ms", sw.ElapsedMilliseconds);
var res = new BaseResponse<LoginVo>(new LoginVo(userInfo,token,refreshToken, expiresAt));
_logger.LogInformation("总耗时: {ms}ms", sw.ElapsedMilliseconds);
return Ok(res);
}
[HttpPost]
public async Task<IActionResult> Register(RegisterRequestDto dto)
{
var userInfo = await _authService.RegisterAsync(dto);
var res = new BaseResponse<UserInfoDto>(userInfo);
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<LoginVo>),StatusCodes.Status200OK)]
public async Task<IActionResult> Refresh(RefreshDto dto)
{
(bool ok,int userId) = await _refreshTokenService.ValidateRefreshTokenAsync(dto.refreshToken);
if (!ok)
{
var err = new BaseResponse<LoginVo>(CodeDefine.AUTH_FAILED);
return Unauthorized(err);
}
var userinfo = await _userService.GetUserInfoAsync(userId);
(string token,DateTime expiresAt) = _jwtService.CreateAccessTokenForUser(userinfo.Id,userinfo.Username,"user");
var res = new BaseResponse<LoginVo>(new LoginVo(userinfo,token, dto.refreshToken, expiresAt));
return Ok(res);
}
}
}
using AutoMapper;
using IM_API.Dtos;
using IM_API.Dtos.Auth;
using IM_API.Dtos.User;
using IM_API.Interface.Services;
using IM_API.Tools;
using IM_API.VOs.Auth;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
namespace IM_API.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly ILogger<AuthController> _logger;
private readonly IAuthService _authService;
private readonly IUserService _userService;
private readonly IJWTService _jwtService;
private readonly IRefreshTokenService _refreshTokenService;
private readonly IConfiguration _configuration;
private IMapper _mapper;
public AuthController(ILogger<AuthController> logger, IAuthService authService,
IJWTService jwtService, IRefreshTokenService refreshTokenService,
IConfiguration configuration,IUserService userService,
IMapper mapper
)
{
_logger = logger;
_authService = authService;
_jwtService = jwtService;
_refreshTokenService = refreshTokenService;
_configuration = configuration;
_userService = userService;
_mapper = mapper;
}
[HttpPost]
public async Task<IActionResult> Login(LoginRequestDto dto)
{
Stopwatch sw = Stopwatch.StartNew();
var user = await _authService.LoginAsync(dto);
_logger.LogInformation("服务耗时: {ms}ms", sw.ElapsedMilliseconds);
var userInfo = _mapper.Map<UserInfoDto>(user);
_logger.LogInformation("序列化耗时: {ms}ms", sw.ElapsedMilliseconds);
//生成凭证
(string token,DateTime expiresAt) = _jwtService.CreateAccessTokenForUser(user.Id,user.Username,"user");
_logger.LogInformation("Token生成耗时: {ms}ms", sw.ElapsedMilliseconds);
//生成刷新凭证
string refreshToken = await _refreshTokenService.CreateRefreshTokenAsync(user.Id);
_logger.LogInformation("RefreshToken生成耗时: {ms}ms", sw.ElapsedMilliseconds);
var res = new BaseResponse<LoginVo>(new LoginVo(userInfo,token,refreshToken, expiresAt));
_logger.LogInformation("总耗时: {ms}ms", sw.ElapsedMilliseconds);
return Ok(res);
}
[HttpPost]
public async Task<IActionResult> Register(RegisterRequestDto dto)
{
var userInfo = await _authService.RegisterAsync(dto);
var res = new BaseResponse<UserInfoDto>(userInfo);
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<LoginVo>),StatusCodes.Status200OK)]
public async Task<IActionResult> Refresh(RefreshDto dto)
{
(bool ok,int userId) = await _refreshTokenService.ValidateRefreshTokenAsync(dto.refreshToken);
if (!ok)
{
var err = new BaseResponse<LoginVo>(CodeDefine.AUTH_FAILED);
return Unauthorized(err);
}
var userinfo = await _userService.GetUserInfoAsync(userId);
(string token,DateTime expiresAt) = _jwtService.CreateAccessTokenForUser(userinfo.Id,userinfo.Username,"user");
var res = new BaseResponse<LoginVo>(new LoginVo(userinfo,token, dto.refreshToken, expiresAt));
return Ok(res);
}
}
}
@@ -1,56 +1,56 @@
using IM_API.Dtos;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.VOs.Conversation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Route("api/[controller]/[action]")]
[Authorize]
[ApiController]
public class ConversationController : ControllerBase
{
private readonly IConversationService _conversationSerivice;
private readonly ILogger<ConversationController> _logger;
public ConversationController(IConversationService conversationSerivice, ILogger<ConversationController> logger)
{
_conversationSerivice = conversationSerivice;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> List()
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var list = await _conversationSerivice.GetConversationsAsync(int.Parse(userIdStr));
var res = new BaseResponse<List<ConversationVo>>(list);
return Ok(res);
}
[HttpGet]
public async Task<IActionResult> Get([FromQuery]int conversationId)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var conversation = await _conversationSerivice.GetConversationByIdAsync(int.Parse(userIdStr), conversationId);
var res = new BaseResponse<ConversationVo>(conversation);
return Ok(res);
}
[HttpPost]
public async Task<IActionResult> Clear()
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
await _conversationSerivice.ClearConversationsAsync(int.Parse(userIdStr));
return Ok(new BaseResponse<object?>());
}
[HttpPost]
public async Task<IActionResult> Delete(int cid)
{
await _conversationSerivice.DeleteConversationAsync(cid);
return Ok(new BaseResponse<object?>());
}
}
}
using IM_API.Dtos;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.VOs.Conversation;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Route("api/[controller]/[action]")]
[Authorize]
[ApiController]
public class ConversationController : ControllerBase
{
private readonly IConversationService _conversationSerivice;
private readonly ILogger<ConversationController> _logger;
public ConversationController(IConversationService conversationSerivice, ILogger<ConversationController> logger)
{
_conversationSerivice = conversationSerivice;
_logger = logger;
}
[HttpGet]
public async Task<IActionResult> List()
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var list = await _conversationSerivice.GetConversationsAsync(int.Parse(userIdStr));
var res = new BaseResponse<List<ConversationVo>>(list);
return Ok(res);
}
[HttpGet]
public async Task<IActionResult> Get([FromQuery]int conversationId)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var conversation = await _conversationSerivice.GetConversationByIdAsync(int.Parse(userIdStr), conversationId);
var res = new BaseResponse<ConversationVo>(conversation);
return Ok(res);
}
[HttpPost]
public async Task<IActionResult> Clear()
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
await _conversationSerivice.ClearConversationsAsync(int.Parse(userIdStr));
return Ok(new BaseResponse<object?>());
}
[HttpPost]
public async Task<IActionResult> Delete(int cid)
{
await _conversationSerivice.DeleteConversationAsync(cid);
return Ok(new BaseResponse<object?>());
}
}
}
+117 -117
View File
@@ -1,117 +1,117 @@
using IM_API.Dtos;
using IM_API.Dtos.Friend;
using IM_API.Interface.Services;
using IM_API.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class FriendController : ControllerBase
{
private readonly IFriendSerivce _friendService;
private readonly ILogger<FriendController> _logger;
public FriendController(IFriendSerivce friendService, ILogger<FriendController> logger)
{
_friendService = friendService;
_logger = logger;
}
/// <summary>
/// 发起好友请求
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Request(FriendRequestDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
dto.FromUserId = userId;
await _friendService.SendFriendRequestAsync(dto);
var res = new BaseResponse<object?>();
return Ok(res);
}
/// <summary>
/// 获取好友请求列表
/// </summary>
/// <param name="isReceived"></param>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <param name="desc"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Requests(int page,int limit,bool desc)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
var list = await _friendService.GetFriendRequestListAsync(userId,page,limit,desc);
var res = new BaseResponse<List<FriendRequestResDto>>(list);
return Ok(res);
}
/// <summary>
/// 处理好友请求
/// </summary>
/// <param name="id"></param>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> HandleRequest(
[FromQuery]int id, [FromBody]FriendRequestHandleDto dto
)
{
await _friendService.HandleFriendRequestAsync(new HandleFriendRequestDto()
{
RequestId = id,
RemarkName = dto.RemarkName,
Action = dto.Action
});
var res = new BaseResponse<object?>();
return Ok(res);
}
/// <summary>
/// 获取好友列表
/// </summary>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <param name="desc"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> List(int page,int limit,bool desc)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
var list = await _friendService.GetFriendListAsync(userId,page,limit,desc);
var res = new BaseResponse<List<FriendInfoDto>>(list);
return Ok(res);
}
/// <summary>
/// 删除好友
/// </summary>
/// <param name="friendId"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Delete([FromRoute] int friendId)
{
//TODO: 这里存在安全问题,当用户传入的id与用户无关时也可以删除成功,待修复。
await _friendService.DeleteFriendAsync(friendId);
return Ok(new BaseResponse<object?>());
}
/// <summary>
/// 拉黑好友
/// </summary>
/// <param name="friendId"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Block([FromRoute] int friendId)
{
//TODO: 这里存在安全问题,当用户传入的id与用户无关时也可以拉黑成功,待修复。
await _friendService.BlockeFriendAsync(friendId);
return Ok(new BaseResponse<object?>());
}
}
}
using IM_API.Dtos;
using IM_API.Dtos.Friend;
using IM_API.Interface.Services;
using IM_API.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class FriendController : ControllerBase
{
private readonly IFriendSerivce _friendService;
private readonly ILogger<FriendController> _logger;
public FriendController(IFriendSerivce friendService, ILogger<FriendController> logger)
{
_friendService = friendService;
_logger = logger;
}
/// <summary>
/// 发起好友请求
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Request(FriendRequestDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
dto.FromUserId = userId;
await _friendService.SendFriendRequestAsync(dto);
var res = new BaseResponse<object?>();
return Ok(res);
}
/// <summary>
/// 获取好友请求列表
/// </summary>
/// <param name="isReceived"></param>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <param name="desc"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Requests(int page,int limit,bool desc)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
var list = await _friendService.GetFriendRequestListAsync(userId,page,limit,desc);
var res = new BaseResponse<List<FriendRequestResDto>>(list);
return Ok(res);
}
/// <summary>
/// 处理好友请求
/// </summary>
/// <param name="id"></param>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> HandleRequest(
[FromQuery]int id, [FromBody]FriendRequestHandleDto dto
)
{
await _friendService.HandleFriendRequestAsync(new HandleFriendRequestDto()
{
RequestId = id,
RemarkName = dto.RemarkName,
Action = dto.Action
});
var res = new BaseResponse<object?>();
return Ok(res);
}
/// <summary>
/// 获取好友列表
/// </summary>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <param name="desc"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> List(int page,int limit,bool desc)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
var list = await _friendService.GetFriendListAsync(userId,page,limit,desc);
var res = new BaseResponse<List<FriendInfoDto>>(list);
return Ok(res);
}
/// <summary>
/// 删除好友
/// </summary>
/// <param name="friendId"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Delete([FromRoute] int friendId)
{
//TODO: 这里存在安全问题,当用户传入的id与用户无关时也可以删除成功,待修复。
await _friendService.DeleteFriendAsync(friendId);
return Ok(new BaseResponse<object?>());
}
/// <summary>
/// 拉黑好友
/// </summary>
/// <param name="friendId"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Block([FromRoute] int friendId)
{
//TODO: 这里存在安全问题,当用户传入的id与用户无关时也可以拉黑成功,待修复。
await _friendService.BlockeFriendAsync(friendId);
return Ok(new BaseResponse<object?>());
}
}
}
+71 -71
View File
@@ -1,71 +1,71 @@
using IM_API.Dtos;
using IM_API.Dtos.Group;
using IM_API.Interface.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class GroupController : ControllerBase
{
private readonly IGroupService _groupService;
private readonly ILogger<GroupController> _logger;
public GroupController(IGroupService groupService, ILogger<GroupController> logger)
{
_groupService = groupService;
_logger = logger;
}
[HttpGet]
[ProducesResponseType(typeof(BaseResponse<List<GroupInfoDto>>) ,StatusCodes.Status200OK)]
public async Task<IActionResult> GetGroups(int page = 1, int limit = 100, bool desc = false)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var list = await _groupService.GetGroupListAsync(int.Parse(userIdStr), page, limit, desc);
var res = new BaseResponse<List<GroupInfoDto>>(list);
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<GroupInfoDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> CreateGroup([FromBody]GroupCreateDto groupCreateDto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var groupInfo = await _groupService.CreateGroupAsync(int.Parse(userIdStr), groupCreateDto);
var res = new BaseResponse<GroupInfoDto>(groupInfo);
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<object?>), StatusCodes.Status200OK)]
public async Task<IActionResult> HandleGroupInvite([FromBody]HandleGroupInviteDto dto)
{
string userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier)!;
await _groupService.HandleGroupInviteAsync(int.Parse(userIdStr), dto);
var res = new BaseResponse<object?>();
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<object?>), StatusCodes.Status200OK)]
public async Task<IActionResult> HandleGroupRequest([FromBody]HandleGroupRequestDto dto)
{
string userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
await _groupService.HandleGroupRequestAsync(int.Parse(userIdStr),dto);
var res = new BaseResponse<object?>();
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<object?>), StatusCodes.Status200OK)]
public async Task<IActionResult> InviteUser([FromBody]GroupInviteUserDto dto)
{
string userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
await _groupService.InviteUsersAsync(int.Parse(userIdStr), dto.GroupId, dto.Ids);
var res = new BaseResponse<object?>();
return Ok(res);
}
}
}
using IM_API.Dtos;
using IM_API.Dtos.Group;
using IM_API.Interface.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class GroupController : ControllerBase
{
private readonly IGroupService _groupService;
private readonly ILogger<GroupController> _logger;
public GroupController(IGroupService groupService, ILogger<GroupController> logger)
{
_groupService = groupService;
_logger = logger;
}
[HttpGet]
[ProducesResponseType(typeof(BaseResponse<List<GroupInfoDto>>) ,StatusCodes.Status200OK)]
public async Task<IActionResult> GetGroups(int page = 1, int limit = 100, bool desc = false)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var list = await _groupService.GetGroupListAsync(int.Parse(userIdStr), page, limit, desc);
var res = new BaseResponse<List<GroupInfoDto>>(list);
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<GroupInfoDto>), StatusCodes.Status200OK)]
public async Task<IActionResult> CreateGroup([FromBody]GroupCreateDto groupCreateDto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var groupInfo = await _groupService.CreateGroupAsync(int.Parse(userIdStr), groupCreateDto);
var res = new BaseResponse<GroupInfoDto>(groupInfo);
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<object?>), StatusCodes.Status200OK)]
public async Task<IActionResult> HandleGroupInvite([FromBody]HandleGroupInviteDto dto)
{
string userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier)!;
await _groupService.HandleGroupInviteAsync(int.Parse(userIdStr), dto);
var res = new BaseResponse<object?>();
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<object?>), StatusCodes.Status200OK)]
public async Task<IActionResult> HandleGroupRequest([FromBody]HandleGroupRequestDto dto)
{
string userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
await _groupService.HandleGroupRequestAsync(int.Parse(userIdStr),dto);
var res = new BaseResponse<object?>();
return Ok(res);
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<object?>), StatusCodes.Status200OK)]
public async Task<IActionResult> InviteUser([FromBody]GroupInviteUserDto dto)
{
string userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
await _groupService.InviteUsersAsync(int.Parse(userIdStr), dto.GroupId, dto.Ids);
var res = new BaseResponse<object?>();
return Ok(res);
}
}
}
+55 -55
View File
@@ -1,55 +1,55 @@
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Dtos.Message;
using IM_API.Interface.Services;
using IM_API.VOs.Message;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class MessageController : ControllerBase
{
private readonly IMessageSevice _messageService;
private readonly ILogger<MessageController> _logger;
private readonly IEventBus _eventBus;
public MessageController(IMessageSevice messageService, ILogger<MessageController> logger, IEventBus eventBus)
{
_messageService = messageService;
_logger = logger;
_eventBus = eventBus;
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<MessageBaseVo>), StatusCodes.Status200OK)]
public async Task<IActionResult> SendMessage(MessageBaseDto dto)
{
var userIdstr = User.FindFirstValue(ClaimTypes.NameIdentifier);
MessageBaseVo messageBaseVo = new MessageBaseVo();
if(dto.ChatType == Models.ChatType.PRIVATE)
{
messageBaseVo = await _messageService.SendPrivateMessageAsync(int.Parse(userIdstr), dto.ReceiverId, dto);
}
else
{
messageBaseVo = await _messageService.SendGroupMessageAsync(int.Parse(userIdstr), dto.ReceiverId, dto);
}
return Ok(new BaseResponse<MessageBaseVo>(messageBaseVo));
}
[HttpGet]
[ProducesResponseType(typeof(BaseResponse<List<MessageBaseVo>>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetMessageList([FromQuery]MessageQueryDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var msgList = await _messageService.GetMessagesAsync(int.Parse(userIdStr),dto);
var res = new BaseResponse<List<MessageBaseVo>>(msgList);
return Ok(res);
}
}
}
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Dtos.Message;
using IM_API.Interface.Services;
using IM_API.VOs.Message;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class MessageController : ControllerBase
{
private readonly IMessageSevice _messageService;
private readonly ILogger<MessageController> _logger;
private readonly IEventBus _eventBus;
public MessageController(IMessageSevice messageService, ILogger<MessageController> logger, IEventBus eventBus)
{
_messageService = messageService;
_logger = logger;
_eventBus = eventBus;
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<MessageBaseVo>), StatusCodes.Status200OK)]
public async Task<IActionResult> SendMessage(MessageBaseDto dto)
{
var userIdstr = User.FindFirstValue(ClaimTypes.NameIdentifier);
MessageBaseVo messageBaseVo = new MessageBaseVo();
if(dto.ChatType == Models.ChatType.PRIVATE)
{
messageBaseVo = await _messageService.SendPrivateMessageAsync(int.Parse(userIdstr), dto.ReceiverId, dto);
}
else
{
messageBaseVo = await _messageService.SendGroupMessageAsync(int.Parse(userIdstr), dto.ReceiverId, dto);
}
return Ok(new BaseResponse<MessageBaseVo>(messageBaseVo));
}
[HttpGet]
[ProducesResponseType(typeof(BaseResponse<List<MessageBaseVo>>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetMessageList([FromQuery]MessageQueryDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
var msgList = await _messageService.GetMessagesAsync(int.Parse(userIdStr),dto);
var res = new BaseResponse<List<MessageBaseVo>>(msgList);
return Ok(res);
}
}
}
+114 -114
View File
@@ -1,114 +1,114 @@
using IM_API.Dtos;
using IM_API.Dtos.User;
using IM_API.Interface.Services;
using IM_API.Tools;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IUserService _userService;
private readonly ILogger<UserController> _logger;
public UserController(IUserService userService, ILogger<UserController> logger)
{
_userService = userService;
_logger = logger;
}
/// <summary>
/// 获取当前用户信息
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Me()
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
var userinfo = await _userService.GetUserInfoAsync(userId);
var res = new BaseResponse<UserInfoDto>(userinfo);
return Ok(res);
}
/// <summary>
/// 修改用户资料
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Profile(UpdateUserDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
var userinfo = await _userService.UpdateUserAsync(userId, dto);
var res = new BaseResponse<UserInfoDto>(userinfo);
return Ok(res);
}
/// <summary>
/// ID查询用户
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Find(int userId)
{
var userinfo = await _userService.GetUserInfoAsync(userId);
var res = new BaseResponse<UserInfoDto>(userinfo);
return Ok(res);
}
/// <summary>
/// 用户名查询用户
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> FindByUsername(string username)
{
var userinfo = await _userService.GetUserInfoByUsernameAsync(username);
var res = new BaseResponse<UserInfoDto>(userinfo);
return Ok(res);
}
/// <summary>
/// 重置用户密码
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> ResetPassword(PasswordResetDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
await _userService.ResetPasswordAsync(userId, dto.OldPassword, dto.Password);
return Ok(new BaseResponse<object?>());
}
/// <summary>
/// 设置在线状态
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> SetOnlineStatus(OnlineStatusSetDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
await _userService.UpdateOlineStatusAsync(userId, dto.OnlineStatus);
return Ok(new BaseResponse<object?>());
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<List<UserInfoDto>>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetUserList([FromBody][Required]List<int> ids)
{
var users = await _userService.GetUserInfoListAsync(ids);
var res = new BaseResponse<List<UserInfoDto>>(users);
return Ok(res);
}
}
}
using IM_API.Dtos;
using IM_API.Dtos.User;
using IM_API.Interface.Services;
using IM_API.Tools;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.ComponentModel.DataAnnotations;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
namespace IM_API.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly IUserService _userService;
private readonly ILogger<UserController> _logger;
public UserController(IUserService userService, ILogger<UserController> logger)
{
_userService = userService;
_logger = logger;
}
/// <summary>
/// 获取当前用户信息
/// </summary>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Me()
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
var userinfo = await _userService.GetUserInfoAsync(userId);
var res = new BaseResponse<UserInfoDto>(userinfo);
return Ok(res);
}
/// <summary>
/// 修改用户资料
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> Profile(UpdateUserDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
var userinfo = await _userService.UpdateUserAsync(userId, dto);
var res = new BaseResponse<UserInfoDto>(userinfo);
return Ok(res);
}
/// <summary>
/// ID查询用户
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Find(int userId)
{
var userinfo = await _userService.GetUserInfoAsync(userId);
var res = new BaseResponse<UserInfoDto>(userinfo);
return Ok(res);
}
/// <summary>
/// 用户名查询用户
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> FindByUsername(string username)
{
var userinfo = await _userService.GetUserInfoByUsernameAsync(username);
var res = new BaseResponse<UserInfoDto>(userinfo);
return Ok(res);
}
/// <summary>
/// 重置用户密码
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> ResetPassword(PasswordResetDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
await _userService.ResetPasswordAsync(userId, dto.OldPassword, dto.Password);
return Ok(new BaseResponse<object?>());
}
/// <summary>
/// 设置在线状态
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
[HttpPost]
public async Task<IActionResult> SetOnlineStatus(OnlineStatusSetDto dto)
{
var userIdStr = User.FindFirstValue(ClaimTypes.NameIdentifier);
int userId = int.Parse(userIdStr);
await _userService.UpdateOlineStatusAsync(userId, dto.OnlineStatus);
return Ok(new BaseResponse<object?>());
}
[HttpPost]
[ProducesResponseType(typeof(BaseResponse<List<UserInfoDto>>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetUserList([FromBody][Required]List<int> ids)
{
var users = await _userService.GetUserInfoListAsync(ids);
var res = new BaseResponse<List<UserInfoDto>>(users);
return Ok(res);
}
}
}
+29 -29
View File
@@ -1,30 +1,30 @@
# 请参阅 https://aka.ms/customizecontainer 以了解如何自定义调试容器,以及 Visual Studio 如何使用此 Dockerfile 生成映像以更快地进行调试。
# 此阶段用于在快速模式(默认为调试配置)下从 VS 运行时
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
# 此阶段用于生成服务项目
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["IM_API.csproj", "."]
RUN dotnet restore "./IM_API.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./IM_API.csproj" -c $BUILD_CONFIGURATION -o /app/build
# 此阶段用于发布要复制到最终阶段的服务项目
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./IM_API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
# 此阶段在生产中使用,或在常规模式下从 VS 运行时使用(在不使用调试配置时为默认值)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
# 请参阅 https://aka.ms/customizecontainer 以了解如何自定义调试容器,以及 Visual Studio 如何使用此 Dockerfile 生成映像以更快地进行调试。
# 此阶段用于在快速模式(默认为调试配置)下从 VS 运行时
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
USER $APP_UID
WORKDIR /app
EXPOSE 8080
EXPOSE 8081
# 此阶段用于生成服务项目
FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["IM_API.csproj", "."]
RUN dotnet restore "./IM_API.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "./IM_API.csproj" -c $BUILD_CONFIGURATION -o /app/build
# 此阶段用于发布要复制到最终阶段的服务项目
FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./IM_API.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false
# 此阶段在生产中使用,或在常规模式下从 VS 运行时使用(在不使用调试配置时为默认值)
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "IM_API.dll"]
+13 -13
View File
@@ -1,13 +1,13 @@
using IM_API.Domain.Interfaces;
namespace IM_API.Domain.Events
{
public abstract record DomainEvent: IEvent
{
public Guid EventId { get; init; } = Guid.NewGuid();
public DateTimeOffset OccurredAt { get; init; } = DateTime.Now;
public long OperatorId { get; init; }
public string AggregateId { get; init; } = "";
public abstract string EventType { get; }
}
}
using IM_API.Domain.Interfaces;
namespace IM_API.Domain.Events
{
public abstract record DomainEvent: IEvent
{
public Guid EventId { get; init; } = Guid.NewGuid();
public DateTimeOffset OccurredAt { get; init; } = DateTime.Now;
public long OperatorId { get; init; }
public string AggregateId { get; init; } = "";
public abstract string EventType { get; }
}
}
+25 -25
View File
@@ -1,25 +1,25 @@
using IM_API.Dtos.Friend;
namespace IM_API.Domain.Events
{
public record FriendAddEvent:DomainEvent
{
public override string EventType => "IM.FRIENDS_FRIEND_ADD";
/// <summary>
/// 发起请求用户
/// </summary>
public int RequestUserId { get; init; }
public string? requestUserRemarkname { get; init; }
/// <summary>
/// 接受请求用户
/// </summary>
public int ResponseUserId { get; init; }
public FriendRequestDto RequestInfo { get; init; }
/// <summary>
/// 好友关系创建时间
/// </summary>
public DateTimeOffset Created { get; init; }
}
}
using IM_API.Dtos.Friend;
namespace IM_API.Domain.Events
{
public record FriendAddEvent:DomainEvent
{
public override string EventType => "IM.FRIENDS_FRIEND_ADD";
/// <summary>
/// 发起请求用户
/// </summary>
public int RequestUserId { get; init; }
public string? requestUserRemarkname { get; init; }
/// <summary>
/// 接受请求用户
/// </summary>
public int ResponseUserId { get; init; }
public FriendRequestDto RequestInfo { get; init; }
/// <summary>
/// 好友关系创建时间
/// </summary>
public DateTimeOffset Created { get; init; }
}
}
@@ -1,14 +1,14 @@
using IM_API.Models;
namespace IM_API.Domain.Events
{
public record GroupInviteActionUpdateEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_INVITE_UPDATE";
public int UserId { get; set; }
public int InviteUserId { get; set; }
public int InviteId { get; set; }
public int GroupId { get; set; }
public GroupInviteState Action { get; set; }
}
}
using IM_API.Models;
namespace IM_API.Domain.Events
{
public record GroupInviteActionUpdateEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_INVITE_UPDATE";
public int UserId { get; set; }
public int InviteUserId { get; set; }
public int InviteId { get; set; }
public int GroupId { get; set; }
public GroupInviteState Action { get; set; }
}
}
@@ -1,10 +1,10 @@
namespace IM_API.Domain.Events
{
public record GroupInviteEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_INVITE_ADD";
public required List<int> Ids { get; init; }
public int GroupId { get; init; }
public int UserId { get; init; }
}
}
namespace IM_API.Domain.Events
{
public record GroupInviteEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_INVITE_ADD";
public required List<int> Ids { get; init; }
public int GroupId { get; init; }
public int UserId { get; init; }
}
}
+10 -10
View File
@@ -1,10 +1,10 @@
namespace IM_API.Domain.Events
{
public record GroupJoinEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_MEMBER_ADD";
public int UserId { get; set; }
public int GroupId { get; set; }
public bool IsCreated { get; set; } = false;
}
}
namespace IM_API.Domain.Events
{
public record GroupJoinEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_MEMBER_ADD";
public int UserId { get; set; }
public int GroupId { get; set; }
public bool IsCreated { get; set; } = false;
}
}
@@ -1,15 +1,15 @@
using IM_API.Dtos.Group;
using IM_API.Models;
namespace IM_API.Domain.Events
{
public record GroupRequestEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_GROUP_REQUEST";
public int GroupId { get; init; }
public int UserId { get; set; }
public string Description { get; set; }
public GroupRequestState Action { get; set; }
}
}
using IM_API.Dtos.Group;
using IM_API.Models;
namespace IM_API.Domain.Events
{
public record GroupRequestEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_GROUP_REQUEST";
public int GroupId { get; init; }
public int UserId { get; set; }
public string Description { get; set; }
public GroupRequestState Action { get; set; }
}
}
@@ -1,14 +1,14 @@
using IM_API.Models;
namespace IM_API.Domain.Events
{
public record GroupRequestUpdateEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_REQUEST_UPDATE";
public int UserId { get; set; }
public int GroupId { get; set; }
public int AdminUserId { get; set; }
public int RequestId { get; set; }
public GroupRequestState Action { get; set; }
}
}
using IM_API.Models;
namespace IM_API.Domain.Events
{
public record GroupRequestUpdateEvent : DomainEvent
{
public override string EventType => "IM.GROUPS_REQUEST_UPDATE";
public int UserId { get; set; }
public int GroupId { get; set; }
public int AdminUserId { get; set; }
public int RequestId { get; set; }
public GroupRequestState Action { get; set; }
}
}
@@ -1,23 +1,23 @@
using IM_API.Dtos;
using IM_API.Models;
namespace IM_API.Domain.Events
{
public record MessageCreatedEvent : DomainEvent
{
public override string EventType => "IM.MESSAGE.MESSAGE_CREATED";
public ChatType ChatType { get; set; }
public MessageMsgType MessageMsgType { get; set; }
public long SequenceId { get; set; }
public string MessageContent { get; set; }
public int MsgSenderId { get; set; }
public int MsgRecipientId { get; set; }
public MessageState State { get; set; }
public DateTimeOffset MessageCreated { get; set; }
public string StreamKey { get; set; }
public Guid ClientMsgId { get; set; }
}
}
using IM_API.Dtos;
using IM_API.Models;
namespace IM_API.Domain.Events
{
public record MessageCreatedEvent : DomainEvent
{
public override string EventType => "IM.MESSAGE.MESSAGE_CREATED";
public ChatType ChatType { get; set; }
public MessageMsgType MessageMsgType { get; set; }
public long SequenceId { get; set; }
public string MessageContent { get; set; }
public int MsgSenderId { get; set; }
public int MsgRecipientId { get; set; }
public MessageState State { get; set; }
public DateTimeOffset MessageCreated { get; set; }
public string StreamKey { get; set; }
public Guid ClientMsgId { get; set; }
}
}
@@ -1,10 +1,10 @@
namespace IM_API.Domain.Events
{
public record RequestFriendEvent : DomainEvent
{
public override string EventType => "IM.FRIENDS_FRIEND_REQUEST";
public int FromUserId { get; init; }
public int ToUserId { get; init; }
public string Description { get; init; }
}
}
namespace IM_API.Domain.Events
{
public record RequestFriendEvent : DomainEvent
{
public override string EventType => "IM.FRIENDS_FRIEND_REQUEST";
public int FromUserId { get; init; }
public int ToUserId { get; init; }
public string Description { get; init; }
}
}
+6 -6
View File
@@ -1,6 +1,6 @@
namespace IM_API.Domain.Interfaces
{
public interface IEvent
{
}
}
namespace IM_API.Domain.Interfaces
{
public interface IEvent
{
}
}
+4 -4
View File
@@ -1,4 +1,4 @@
namespace IM_API.Dtos.Auth
{
public record RefreshDto(string refreshToken);
}
namespace IM_API.Dtos.Auth
{
public record RefreshDto(string refreshToken);
}
+17 -17
View File
@@ -1,17 +1,17 @@
using IM_API.Tools;
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Auth
{
public class LoginRequestDto
{
[Required(ErrorMessage = "用户名不能为空")]
[StringLength(20, ErrorMessage = "用户名不能超过20字符")]
[RegularExpression(@"^[A-Za-z0-9]+$",ErrorMessage = "")]
public string Username { get; set; }
[Required(ErrorMessage = "密码不能为空")]
[StringLength(50, ErrorMessage = "密码不能超过50字符")]
public string Password { get; set; }
}
}
using IM_API.Tools;
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Auth
{
public class LoginRequestDto
{
[Required(ErrorMessage = "用户名不能为空")]
[StringLength(20, ErrorMessage = "用户名不能超过20字符")]
[RegularExpression(@"^[A-Za-z0-9]+$",ErrorMessage = "")]
public string Username { get; set; }
[Required(ErrorMessage = "密码不能为空")]
[StringLength(50, ErrorMessage = "密码不能超过50字符")]
public string Password { get; set; }
}
}
+19 -19
View File
@@ -1,19 +1,19 @@
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Auth
{
public class RegisterRequestDto
{
[Required(ErrorMessage = "用户名不能为空")]
[MaxLength(20, ErrorMessage = "用户名不能超过20字符")]
[RegularExpression(@"^[A-Za-z0-9]+$", ErrorMessage = "")]
public string Username { get; set; }
[Required(ErrorMessage = "密码不能为空")]
[MaxLength(50, ErrorMessage = "密码不能超过50字符")]
public string Password { get; set; }
[Required(ErrorMessage = "昵称不能为空")]
[MaxLength(20, ErrorMessage = "昵称不能超过20字符")]
public string? NickName { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Auth
{
public class RegisterRequestDto
{
[Required(ErrorMessage = "用户名不能为空")]
[MaxLength(20, ErrorMessage = "用户名不能超过20字符")]
[RegularExpression(@"^[A-Za-z0-9]+$", ErrorMessage = "")]
public string Username { get; set; }
[Required(ErrorMessage = "密码不能为空")]
[MaxLength(50, ErrorMessage = "密码不能超过50字符")]
public string Password { get; set; }
[Required(ErrorMessage = "昵称不能为空")]
[MaxLength(20, ErrorMessage = "昵称不能超过20字符")]
public string? NickName { get; set; }
}
}
+82 -82
View File
@@ -1,82 +1,82 @@
using IM_API.Tools;
namespace IM_API.Dtos
{
public class BaseResponse<T>
{
//响应状态码
public int Code { get; set; }
//响应消息
public string Message { get; set; }
//响应数据
public T? Data { get; set; }
/// <summary>
/// 默认成功响应返回
/// </summary>
/// <param name="msg"></param>
/// <param name="data"></param>
public BaseResponse(string msg,T data)
{
this.Code = 0;
this.Message = msg;
this.Data = data;
}
/// <summary>
/// 默认成功响应返回仅数据
/// </summary>
/// <param name="data"></param>
public BaseResponse(T data)
{
this.Code = CodeDefine.SUCCESS.Code;
this.Message = CodeDefine.SUCCESS.Message;
this.Data = data;
}
/// <summary>
/// 默认成功响应返回,不带数据
/// </summary>
/// <param name="msg"></param>
/// <param name="data"></param>
public BaseResponse(string msg)
{
this.Code = CodeDefine.SUCCESS.Code;
this.Message = msg;
}
/// <summary>
/// 非成功响应且带数据
/// </summary>
/// <param name="code"></param>
/// <param name="message"></param>
/// <param name="data"></param>
public BaseResponse(int code, string message, T? data)
{
Code = code;
Message = message;
Data = data;
}
/// <summary>
/// 非成功响应且不带数据
/// </summary>
/// <param name="code"></param>
/// <param name="message"></param>
/// <param name="data"></param>
public BaseResponse(int code, string message)
{
Code = code;
Message = message;
}
/// <summary>
/// 接受codedefine对象
/// </summary>
/// <param name="codeDefine"></param>
public BaseResponse(CodeDefine codeDefine)
{
this.Code = codeDefine.Code;
this.Message = codeDefine.Message;
}
public BaseResponse()
{
this.Code = CodeDefine.SUCCESS.Code;
this.Message = CodeDefine.SUCCESS.Message;
}
}
}
using IM_API.Tools;
namespace IM_API.Dtos
{
public class BaseResponse<T>
{
//响应状态码
public int Code { get; set; }
//响应消息
public string Message { get; set; }
//响应数据
public T? Data { get; set; }
/// <summary>
/// 默认成功响应返回
/// </summary>
/// <param name="msg"></param>
/// <param name="data"></param>
public BaseResponse(string msg,T data)
{
this.Code = 0;
this.Message = msg;
this.Data = data;
}
/// <summary>
/// 默认成功响应返回仅数据
/// </summary>
/// <param name="data"></param>
public BaseResponse(T data)
{
this.Code = CodeDefine.SUCCESS.Code;
this.Message = CodeDefine.SUCCESS.Message;
this.Data = data;
}
/// <summary>
/// 默认成功响应返回,不带数据
/// </summary>
/// <param name="msg"></param>
/// <param name="data"></param>
public BaseResponse(string msg)
{
this.Code = CodeDefine.SUCCESS.Code;
this.Message = msg;
}
/// <summary>
/// 非成功响应且带数据
/// </summary>
/// <param name="code"></param>
/// <param name="message"></param>
/// <param name="data"></param>
public BaseResponse(int code, string message, T? data)
{
Code = code;
Message = message;
Data = data;
}
/// <summary>
/// 非成功响应且不带数据
/// </summary>
/// <param name="code"></param>
/// <param name="message"></param>
/// <param name="data"></param>
public BaseResponse(int code, string message)
{
Code = code;
Message = message;
}
/// <summary>
/// 接受codedefine对象
/// </summary>
/// <param name="codeDefine"></param>
public BaseResponse(CodeDefine codeDefine)
{
this.Code = codeDefine.Code;
this.Message = codeDefine.Message;
}
public BaseResponse()
{
this.Code = CodeDefine.SUCCESS.Code;
this.Message = CodeDefine.SUCCESS.Message;
}
}
}
@@ -1,26 +1,26 @@
namespace IM_API.Dtos.Conversation
{
public class ClearConversationsDto
{
public int UserId { get; set; }
/// <summary>
/// 聊天类型
/// </summary>
public MsgChatType ChatType { get; set; }
/// <summary>
/// 目标ID,聊天类型为群则为群id,私聊为用户id
/// </summary>
public int TargetId { get; set; }
}
public enum MsgChatType
{
/// <summary>
/// 私聊
/// </summary>
single = 0,
/// <summary>
/// 私聊
/// </summary>
group = 1
}
}
namespace IM_API.Dtos.Conversation
{
public class ClearConversationsDto
{
public int UserId { get; set; }
/// <summary>
/// 聊天类型
/// </summary>
public MsgChatType ChatType { get; set; }
/// <summary>
/// 目标ID,聊天类型为群则为群id,私聊为用户id
/// </summary>
public int TargetId { get; set; }
}
public enum MsgChatType
{
/// <summary>
/// 私聊
/// </summary>
single = 0,
/// <summary>
/// 私聊
/// </summary>
group = 1
}
}
@@ -1,12 +1,12 @@
namespace IM_API.Dtos.Conversation
{
public class UpdateConversationDto
{
public string StreamKey { get; set; }
public int SenderId { get; set; }
public int ReceiptId { get; set; }
public string LastMessage { get; set; }
public long LastSequenceId { get; set; }
public DateTimeOffset DateTime { get; set; }
}
}
namespace IM_API.Dtos.Conversation
{
public class UpdateConversationDto
{
public string StreamKey { get; set; }
public int SenderId { get; set; }
public int ReceiptId { get; set; }
public string LastMessage { get; set; }
public long LastSequenceId { get; set; }
public DateTimeOffset DateTime { get; set; }
}
}
+33 -33
View File
@@ -1,33 +1,33 @@
using IM_API.Dtos.User;
using IM_API.Models;
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Friend
{
public record FriendInfoDto
{
public int Id { get; init; }
public int UserId { get; init; }
public int FriendId { get; init; }
public FriendStatus StatusEnum { get; init; }
public DateTimeOffset Created { get; init; }
public string RemarkName { get; init; } = string.Empty;
public string? Avatar { get; init; }
public UserInfoDto UserInfo { get; init; }
}
public record FriendRequestHandleDto
{
[Required(ErrorMessage = "操作必填")]
public HandleFriendRequestAction Action { get; init; }
[StringLength(20, ErrorMessage = "备注名最大20个字符")]
public string? RemarkName { get; init; }
}
}
using IM_API.Dtos.User;
using IM_API.Models;
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Friend
{
public record FriendInfoDto
{
public int Id { get; init; }
public int UserId { get; init; }
public int FriendId { get; init; }
public FriendStatus StatusEnum { get; init; }
public DateTimeOffset Created { get; init; }
public string RemarkName { get; init; } = string.Empty;
public string? Avatar { get; init; }
public UserInfoDto UserInfo { get; init; }
}
public record FriendRequestHandleDto
{
[Required(ErrorMessage = "操作必填")]
public HandleFriendRequestAction Action { get; init; }
[StringLength(20, ErrorMessage = "备注名最大20个字符")]
public string? RemarkName { get; init; }
}
}
+15 -15
View File
@@ -1,15 +1,15 @@
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Friend
{
public class FriendRequestDto
{
public int? FromUserId { get; set; }
public int ToUserId { get; set; }
[Required(ErrorMessage = "备注名必填")]
[StringLength(20, ErrorMessage = "备注名不能超过20位字符")]
public string? RemarkName { get; set; }
[StringLength(50, ErrorMessage = "描述不能超过50字符")]
public string? Description { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Friend
{
public class FriendRequestDto
{
public int? FromUserId { get; set; }
public int ToUserId { get; set; }
[Required(ErrorMessage = "备注名必填")]
[StringLength(20, ErrorMessage = "备注名不能超过20位字符")]
public string? RemarkName { get; set; }
[StringLength(50, ErrorMessage = "描述不能超过50字符")]
public string? Description { get; set; }
}
}
@@ -1,36 +1,36 @@
using IM_API.Models;
namespace IM_API.Dtos.Friend
{
public class FriendRequestResDto
{
public int Id { get; set; }
/// <summary>
/// 申请人
/// </summary>
public int RequestUser { get; set; }
/// <summary>
/// 被申请人
/// </summary>
public int ResponseUser { get; set; }
public string Avatar { get; set; }
public string NickName { get; set; }
/// <summary>
/// 申请时间
/// </summary>
public DateTimeOffset Created { get; set; }
/// <summary>
/// 申请附言
/// </summary>
public string? Description { get; set; }
/// <summary>
/// 申请状态(0:待通过,1:拒绝,2:同意,3:拉黑)
/// </summary>
public FriendRequestState State { get; set; }
}
}
using IM_API.Models;
namespace IM_API.Dtos.Friend
{
public class FriendRequestResDto
{
public int Id { get; set; }
/// <summary>
/// 申请人
/// </summary>
public int RequestUser { get; set; }
/// <summary>
/// 被申请人
/// </summary>
public int ResponseUser { get; set; }
public string Avatar { get; set; }
public string NickName { get; set; }
/// <summary>
/// 申请时间
/// </summary>
public DateTimeOffset Created { get; set; }
/// <summary>
/// 申请附言
/// </summary>
public string? Description { get; set; }
/// <summary>
/// 申请状态(0:待通过,1:拒绝,2:同意,3:拉黑)
/// </summary>
public FriendRequestState State { get; set; }
}
}
@@ -1,29 +1,29 @@
namespace IM_API.Dtos.Friend
{
public class HandleFriendRequestDto
{
/// <summary>
/// 好友请求Id
/// </summary>
public int RequestId { get; set; }
/// <summary>
/// 处理操作
/// </summary>
public HandleFriendRequestAction Action { get; set; }
/// <summary>
/// 好友备注名
/// </summary>
public string? RemarkName { get; set; }
}
public enum HandleFriendRequestAction
{
/// <summary>
/// 同意
/// </summary>
Accept = 0,
/// <summary>
/// 拒绝
/// </summary>
Reject = 1
}
}
namespace IM_API.Dtos.Friend
{
public class HandleFriendRequestDto
{
/// <summary>
/// 好友请求Id
/// </summary>
public int RequestId { get; set; }
/// <summary>
/// 处理操作
/// </summary>
public HandleFriendRequestAction Action { get; set; }
/// <summary>
/// 好友备注名
/// </summary>
public string? RemarkName { get; set; }
}
public enum HandleFriendRequestAction
{
/// <summary>
/// 同意
/// </summary>
Accept = 0,
/// <summary>
/// 拒绝
/// </summary>
Reject = 1
}
}
+22 -22
View File
@@ -1,22 +1,22 @@
using IM_API.Models;
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Group
{
public class GroupCreateDto
{
/// <summary>
/// 群聊名称
/// </summary>
[Required(ErrorMessage = "群名称必填")]
[MaxLength(20, ErrorMessage = "群名称不能大于20字符")]
public string Name { get; set; } = null!;
/// <summary>
/// 群头像
/// </summary>
[Required(ErrorMessage = "群头像必填")]
public string Avatar { get; set; } = null!;
public List<int>? UserIDs { get; set; }
}
}
using IM_API.Models;
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Group
{
public class GroupCreateDto
{
/// <summary>
/// 群聊名称
/// </summary>
[Required(ErrorMessage = "群名称必填")]
[MaxLength(20, ErrorMessage = "群名称不能大于20字符")]
public string Name { get; set; } = null!;
/// <summary>
/// 群头像
/// </summary>
[Required(ErrorMessage = "群头像必填")]
public string Avatar { get; set; } = null!;
public List<int>? UserIDs { get; set; }
}
}
+51 -51
View File
@@ -1,51 +1,51 @@
using IM_API.Models;
namespace IM_API.Dtos.Group
{
public class GroupInfoDto
{
public int Id { get; set; }
/// <summary>
/// 群聊名称
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// 群主
/// </summary>
public int GroupMaster { get; set; }
/// <summary>
/// 群权限
/// (0:需管理员同意,1:任意人可加群,2:不允许任何人加入)
/// </summary>
public GroupAuhority Auhority { get; set; }
/// <summary>
/// 全员禁言(0允许发言,2全员禁言)
/// </summary>
public GroupAllMembersBanned AllMembersBanned { get; set; }
/// <summary>
/// 群聊状态
/// (1:正常,2:封禁)
/// </summary>
public GroupStatus Status { get; set; }
/// <summary>
/// 群公告
/// </summary>
public string? Announcement { get; set; }
/// <summary>
/// 群聊创建时间
/// </summary>
public DateTimeOffset Created { get; set; }
/// <summary>
/// 群头像
/// </summary>
public string Avatar { get; set; } = null!;
}
}
using IM_API.Models;
namespace IM_API.Dtos.Group
{
public class GroupInfoDto
{
public int Id { get; set; }
/// <summary>
/// 群聊名称
/// </summary>
public string Name { get; set; } = null!;
/// <summary>
/// 群主
/// </summary>
public int GroupMaster { get; set; }
/// <summary>
/// 群权限
/// (0:需管理员同意,1:任意人可加群,2:不允许任何人加入)
/// </summary>
public GroupAuhority Auhority { get; set; }
/// <summary>
/// 全员禁言(0允许发言,2全员禁言)
/// </summary>
public GroupAllMembersBanned AllMembersBanned { get; set; }
/// <summary>
/// 群聊状态
/// (1:正常,2:封禁)
/// </summary>
public GroupStatus Status { get; set; }
/// <summary>
/// 群公告
/// </summary>
public string? Announcement { get; set; }
/// <summary>
/// 群聊创建时间
/// </summary>
public DateTimeOffset Created { get; set; }
/// <summary>
/// 群头像
/// </summary>
public string Avatar { get; set; } = null!;
}
}
@@ -1,8 +1,8 @@
namespace IM_API.Dtos.Group
{
public class GroupInviteUserDto
{
public int GroupId { get; set; }
public List<int> Ids { get; set; }
}
}
namespace IM_API.Dtos.Group
{
public class GroupInviteUserDto
{
public int GroupId { get; set; }
public List<int> Ids { get; set; }
}
}
@@ -1,11 +1,11 @@
namespace IM_API.Dtos.Group
{
public class GroupUpdateConversationDto
{
public int GroupId { get; set; }
public long MaxSequenceId { get; set; }
public string LastMessage { get; set; }
public string LastSenderName { get; set; }
public DateTimeOffset LastUpdateTime { get; set; }
}
}
namespace IM_API.Dtos.Group
{
public class GroupUpdateConversationDto
{
public int GroupId { get; set; }
public long MaxSequenceId { get; set; }
public string LastMessage { get; set; }
public string LastSenderName { get; set; }
public DateTimeOffset LastUpdateTime { get; set; }
}
}
@@ -1,10 +1,10 @@
using IM_API.Models;
namespace IM_API.Dtos.Group
{
public class HandleGroupInviteDto
{
public int InviteId { get; set; }
public GroupInviteState Action { get; set; }
}
}
using IM_API.Models;
namespace IM_API.Dtos.Group
{
public class HandleGroupInviteDto
{
public int InviteId { get; set; }
public GroupInviteState Action { get; set; }
}
}
@@ -1,10 +1,10 @@
using IM_API.Models;
namespace IM_API.Dtos.Group
{
public class HandleGroupRequestDto
{
public int RequestId { get; set; }
public GroupRequestState Action { get; set; }
}
}
using IM_API.Models;
namespace IM_API.Dtos.Group
{
public class HandleGroupRequestDto
{
public int RequestId { get; set; }
public GroupRequestState Action { get; set; }
}
}
+49 -49
View File
@@ -1,49 +1,49 @@
using IM_API.Tools;
namespace IM_API.Dtos
{
public class HubResponse<T>
{
public int Code { get; init; }
public string Method { get; init; }
public HubResponseType Type { get; init; }
public string Message { get; init; }
public T? Data { get; init; }
public HubResponse(string method)
{
Code = CodeDefine.SUCCESS.Code;
Message = CodeDefine.SUCCESS.Message;
Type = HubResponseType.ActionStatus;
Method = method;
}
public HubResponse(string method,T data)
{
Code = CodeDefine.SUCCESS.Code;
Message = CodeDefine.SUCCESS.Message;
Type = HubResponseType.ActionStatus;
Data = data;
Method = method;
}
public HubResponse(CodeDefine codedefine,string method)
{
Code = codedefine.Code;
Method = method;
Message = codedefine.Message;
Type = HubResponseType.ActionStatus;
}
public HubResponse(CodeDefine codeDefine, string method, HubResponseType type, T? data)
{
Code = codeDefine.Code;
Method = method;
Type = type;
Message = codeDefine.Message;
Data = data;
}
}
public enum HubResponseType
{
ChatMsg = 1, // 聊天内容
SystemNotice = 2, // 系统通知(如:申请好友成功)
ActionStatus = 3 // 状态变更(如:对方正在输入、已读回执)
}
}
using IM_API.Tools;
namespace IM_API.Dtos
{
public class HubResponse<T>
{
public int Code { get; init; }
public string Method { get; init; }
public HubResponseType Type { get; init; }
public string Message { get; init; }
public T? Data { get; init; }
public HubResponse(string method)
{
Code = CodeDefine.SUCCESS.Code;
Message = CodeDefine.SUCCESS.Message;
Type = HubResponseType.ActionStatus;
Method = method;
}
public HubResponse(string method,T data)
{
Code = CodeDefine.SUCCESS.Code;
Message = CodeDefine.SUCCESS.Message;
Type = HubResponseType.ActionStatus;
Data = data;
Method = method;
}
public HubResponse(CodeDefine codedefine,string method)
{
Code = codedefine.Code;
Method = method;
Message = codedefine.Message;
Type = HubResponseType.ActionStatus;
}
public HubResponse(CodeDefine codeDefine, string method, HubResponseType type, T? data)
{
Code = codeDefine.Code;
Method = method;
Type = type;
Message = codeDefine.Message;
Data = data;
}
}
public enum HubResponseType
{
ChatMsg = 1, // 聊天内容
SystemNotice = 2, // 系统通知(如:申请好友成功)
ActionStatus = 3 // 状态变更(如:对方正在输入、已读回执)
}
}
+18 -18
View File
@@ -1,18 +1,18 @@
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Message
{
public class MessageQueryDto
{
[Required(ErrorMessage = "会话ID必填")]
public int ConversationId { get; set; }
// 锚点序号(如果为空,说明是第一次进聊天框,拉最新的)
public long? Cursor { get; set; }
// 查询方向:0 - 查旧(Before), 1 - 查新(After)
public int Direction { get; set; } = 0;
public int Limit { get; set; } = 20;
}
}
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.Message
{
public class MessageQueryDto
{
[Required(ErrorMessage = "会话ID必填")]
public int ConversationId { get; set; }
// 锚点序号(如果为空,说明是第一次进聊天框,拉最新的)
public long? Cursor { get; set; }
// 查询方向:0 - 查旧(Before), 1 - 查新(After)
public int Direction { get; set; } = 0;
public int Limit { get; set; } = 20;
}
}
+17 -17
View File
@@ -1,17 +1,17 @@
using IM_API.Models;
namespace IM_API.Dtos
{
public record MessageBaseDto
{
// 使用 { get; init; } 确保对象创建后不可修改,且支持无参构造
public MessageMsgType Type { get; init; } = default!;
public ChatType ChatType { get; init; } = default!;
public Guid MsgId { get; init; }
public int SenderId { get; init; }
public int ReceiverId { get; init; }
public string Content { get; init; } = default!;
public DateTimeOffset TimeStamp { get; init; }
public MessageBaseDto() { }
}
}
using IM_API.Models;
namespace IM_API.Dtos
{
public record MessageBaseDto
{
// 使用 { get; init; } 确保对象创建后不可修改,且支持无参构造
public MessageMsgType Type { get; init; } = default!;
public ChatType ChatType { get; init; } = default!;
public Guid MsgId { get; init; }
public int SenderId { get; init; }
public int ReceiverId { get; init; }
public string Content { get; init; } = default!;
public DateTimeOffset TimeStamp { get; init; }
public MessageBaseDto() { }
}
}
+66 -66
View File
@@ -1,66 +1,66 @@
using IM_API.Tools;
namespace IM_API.Dtos
{
public class SignalRResponseDto
{
public string Type { get; set; }
public string Message { get; set; }
public int Code { get; set; }
public string Status { get; set; }
public SignalRResponseDto(SignalRResponseType type,CodeDefine codeDefine)
{
this.Type = type.ToString();
this.Code = codeDefine.Code;
this.Message = codeDefine.Message;
this.Status = codeDefine.Message;
}
public SignalRResponseDto(SignalRResponseType type)
{
this.Type = type.ToString();
this.Code = CodeDefine.SUCCESS.Code;
this.Message = CodeDefine.SUCCESS.Message;
this.Status = CodeDefine.SUCCESS.Message;
}
}
public enum SignalRResponseType
{
/// <summary>
/// 消息
/// </summary>
MESSAGE = 0,
/// <summary>
/// 鉴权
/// </summary>
AUTH = 1,
/// <summary>
/// 心跳
/// </summary>
HEARTBEAT = 2,
/// <summary>
/// 消息回执
/// </summary>
MESSAGE_ACK = 3,
/// <summary>
/// 消息撤回
/// </summary>
MESSAGE_RECALL = 4,
/// <summary>
/// 好友请求
/// </summary>
FRIEND_REQUEST = 5,
/// <summary>
/// 群邀请
/// </summary>
GROUP_INVITE = 6,
/// <summary>
/// 系统通知
/// </summary>
SYSTEM_NOTICE = 7,
/// <summary>
/// 错误
/// </summary>
ERROR = 8
}
}
using IM_API.Tools;
namespace IM_API.Dtos
{
public class SignalRResponseDto
{
public string Type { get; set; }
public string Message { get; set; }
public int Code { get; set; }
public string Status { get; set; }
public SignalRResponseDto(SignalRResponseType type,CodeDefine codeDefine)
{
this.Type = type.ToString();
this.Code = codeDefine.Code;
this.Message = codeDefine.Message;
this.Status = codeDefine.Message;
}
public SignalRResponseDto(SignalRResponseType type)
{
this.Type = type.ToString();
this.Code = CodeDefine.SUCCESS.Code;
this.Message = CodeDefine.SUCCESS.Message;
this.Status = CodeDefine.SUCCESS.Message;
}
}
public enum SignalRResponseType
{
/// <summary>
/// 消息
/// </summary>
MESSAGE = 0,
/// <summary>
/// 鉴权
/// </summary>
AUTH = 1,
/// <summary>
/// 心跳
/// </summary>
HEARTBEAT = 2,
/// <summary>
/// 消息回执
/// </summary>
MESSAGE_ACK = 3,
/// <summary>
/// 消息撤回
/// </summary>
MESSAGE_RECALL = 4,
/// <summary>
/// 好友请求
/// </summary>
FRIEND_REQUEST = 5,
/// <summary>
/// 群邀请
/// </summary>
GROUP_INVITE = 6,
/// <summary>
/// 系统通知
/// </summary>
SYSTEM_NOTICE = 7,
/// <summary>
/// 错误
/// </summary>
ERROR = 8
}
}
+8 -8
View File
@@ -1,8 +1,8 @@
namespace IM_API.Dtos
{
public class TestDto
{
public int Id { get; set; }
public string Name { get; set; }
}
}
namespace IM_API.Dtos
{
public class TestDto
{
public int Id { get; set; }
public string Name { get; set; }
}
}
+12 -12
View File
@@ -1,12 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.User
{
public class UpdateUserDto
{
[MaxLength(20, ErrorMessage = "昵称不能超过50字符")]
public string? NickName { get; set; }
public string? Avatar { get; set; }
}
}
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.User
{
public class UpdateUserDto
{
[MaxLength(20, ErrorMessage = "昵称不能超过50字符")]
public string? NickName { get; set; }
public string? Avatar { get; set; }
}
}
+21 -21
View File
@@ -1,21 +1,21 @@
using IM_API.Models;
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.User
{
public record PasswordResetDto
{
[Required(ErrorMessage = "旧密码不能为空")]
public string OldPassword { get; init; }
[Required(ErrorMessage = "新密码不能为空")]
[MaxLength(50, ErrorMessage = "密码不能超过50个字符")]
public string Password { get; init; }
}
public record OnlineStatusSetDto
{
[Required]
public UserOnlineStatus OnlineStatus { get; init; }
}
}
using IM_API.Models;
using System.ComponentModel.DataAnnotations;
namespace IM_API.Dtos.User
{
public record PasswordResetDto
{
[Required(ErrorMessage = "旧密码不能为空")]
public string OldPassword { get; init; }
[Required(ErrorMessage = "新密码不能为空")]
[MaxLength(50, ErrorMessage = "密码不能超过50个字符")]
public string Password { get; init; }
}
public record OnlineStatusSetDto
{
[Required]
public UserOnlineStatus OnlineStatus { get; init; }
}
}
+43 -43
View File
@@ -1,43 +1,43 @@
using IM_API.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace IM_API.Dtos.User
{
public class UserInfoDto
{
public int Id { get; set; }
/// <summary>
/// 唯一用户名
/// </summary>
public string Username { get; set; }
/// <summary>
/// 用户昵称
/// </summary>
public string NickName { get; set; }
/// <summary>
/// 用户头像
/// </summary>
public string? Avatar { get; set; }
/// <summary>
/// 用户在线状态
/// 0(默认):不在线
/// 1:在线
/// </summary>
public UserOnlineStatus OnlineStatusEnum { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTimeOffset Created { get; set; }
/// <summary>
/// 账户状态
/// (0:未激活,1:正常,2:封禁)
/// </summary>
public UserStatus StatusEnum { get; set; }
}
}
using IM_API.Models;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace IM_API.Dtos.User
{
public class UserInfoDto
{
public int Id { get; set; }
/// <summary>
/// 唯一用户名
/// </summary>
public string Username { get; set; }
/// <summary>
/// 用户昵称
/// </summary>
public string NickName { get; set; }
/// <summary>
/// 用户头像
/// </summary>
public string? Avatar { get; set; }
/// <summary>
/// 用户在线状态
/// 0(默认):不在线
/// 1:在线
/// </summary>
public UserOnlineStatus OnlineStatusEnum { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTimeOffset Created { get; set; }
/// <summary>
/// 账户状态
/// (0:未激活,1:正常,2:封禁)
/// </summary>
public UserStatus StatusEnum { get; set; }
}
}
+17 -17
View File
@@ -1,17 +1,17 @@
using IM_API.Tools;
namespace IM_API.Exceptions
{
public class BaseException:Exception
{
public int Code { get; set; }
public BaseException(int code,string message) : base(message) {
this.Code = code;
}
public BaseException(CodeDefine codeDefine) : base(codeDefine.Message)
{
this.Code = codeDefine.Code;
}
}
}
using IM_API.Tools;
namespace IM_API.Exceptions
{
public class BaseException:Exception
{
public int Code { get; set; }
public BaseException(int code,string message) : base(message) {
this.Code = code;
}
public BaseException(CodeDefine codeDefine) : base(codeDefine.Message)
{
this.Code = codeDefine.Code;
}
}
}
+39 -39
View File
@@ -1,39 +1,39 @@
using IM_API.Dtos;
using IM_API.Exceptions;
using IM_API.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace IM_API.Filters
{
public class GlobalExceptionFilter : IExceptionFilter
{
private readonly ILogger<GlobalExceptionFilter> _logger;
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
{
_logger = logger;
}
public void OnException(ExceptionContext context)
{
if(context.Exception is BaseException)
{
_logger.LogWarning(context.Exception, context.Exception.Message);
var exception = (BaseException)context.Exception;
BaseResponse<object?> res = new BaseResponse<object?>(
code:exception.Code,
message: exception.Message,
data:null
);
context.Result = new JsonResult(res);
}
else
{
_logger.LogError(context.Exception,context.Exception.Message);
BaseResponse<object?> res = new BaseResponse<object?>(CodeDefine.SYSTEM_ERROR);
context.Result = new JsonResult(res);
}
context.ExceptionHandled = true;
}
}
}
using IM_API.Dtos;
using IM_API.Exceptions;
using IM_API.Tools;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace IM_API.Filters
{
public class GlobalExceptionFilter : IExceptionFilter
{
private readonly ILogger<GlobalExceptionFilter> _logger;
public GlobalExceptionFilter(ILogger<GlobalExceptionFilter> logger)
{
_logger = logger;
}
public void OnException(ExceptionContext context)
{
if(context.Exception is BaseException)
{
_logger.LogWarning(context.Exception, context.Exception.Message);
var exception = (BaseException)context.Exception;
BaseResponse<object?> res = new BaseResponse<object?>(
code:exception.Code,
message: exception.Message,
data:null
);
context.Result = new JsonResult(res);
}
else
{
_logger.LogError(context.Exception,context.Exception.Message);
BaseResponse<object?> res = new BaseResponse<object?>(CodeDefine.SYSTEM_ERROR);
context.Result = new JsonResult(res);
}
context.ExceptionHandled = true;
}
}
}
+90 -90
View File
@@ -1,90 +1,90 @@
using AutoMapper;
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.Tools;
using IM_API.VOs.Message;
using Microsoft.AspNetCore.SignalR;
using StackExchange.Redis;
using System.Security.Claims;
namespace IM_API.Hubs
{
public class ChatHub:Hub
{
private IMessageSevice _messageService;
private readonly IConversationService _conversationService;
private readonly IDatabase _redis;
public ChatHub(IMessageSevice messageService, IConversationService conversationService,
IConnectionMultiplexer connectionMultiplexer)
{
_messageService = messageService;
_conversationService = conversationService;
_redis = connectionMultiplexer.GetDatabase();
}
public async override Task OnConnectedAsync()
{
if (!Context.User.Identity.IsAuthenticated)
{
Context.Abort();
return;
}
//将用户加入已加入聊天的会话组
string userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
var keys = await _conversationService.GetUserAllStreamKeyAsync(int.Parse(userIdStr));
foreach (var key in keys)
{
await Groups.AddToGroupAsync(Context.ConnectionId, key);
}
//储存用户对应的连接id
await _redis.SetAddAsync(RedisKeys.GetConnectionIdKey(userIdStr), Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
if (!Context.User.Identity.IsAuthenticated)
{
string useridStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
await _redis.SetRemoveAsync(RedisKeys.GetConnectionIdKey(useridStr), Context.ConnectionId);
}
await base.OnDisconnectedAsync(exception);
}
public async Task<HubResponse<MessageBaseVo?>> SendMessage(MessageBaseDto dto)
{
if (!Context.User.Identity.IsAuthenticated)
{
await Clients.Caller.SendAsync("ReceiveMessage", new BaseResponse<object?>(CodeDefine.AUTH_FAILED));
Context.Abort();
return new HubResponse<MessageBaseVo?>(CodeDefine.AUTH_FAILED, "SendMessage");
}
var userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
MessageBaseVo? msgInfo = null;
if(dto.ChatType == ChatType.PRIVATE)
{
msgInfo = await _messageService.SendPrivateMessageAsync(int.Parse(userIdStr), dto.ReceiverId, dto);
}
else
{
msgInfo = await _messageService.SendGroupMessageAsync(int.Parse(userIdStr), dto.ReceiverId, dto);
}
return new HubResponse<MessageBaseVo?>("SendMessage", msgInfo);
}
public async Task<HubResponse<object?>> ClearUnreadCount(int conversationId)
{
if (!Context.User.Identity.IsAuthenticated)
{
await Clients.Caller.SendAsync("ReceiveMessage", new BaseResponse<object?>(CodeDefine.AUTH_FAILED));
Context.Abort();
return new HubResponse<object?>(CodeDefine.AUTH_FAILED, "ClearUnreadCount"); ;
}
var userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
await _conversationService.ClearUnreadCountAsync(int.Parse(userIdStr), conversationId);
return new HubResponse<object?>("ClearUnreadCount");
}
}
}
using AutoMapper;
using IM_API.Application.Interfaces;
using IM_API.Domain.Events;
using IM_API.Dtos;
using IM_API.Interface.Services;
using IM_API.Models;
using IM_API.Tools;
using IM_API.VOs.Message;
using Microsoft.AspNetCore.SignalR;
using StackExchange.Redis;
using System.Security.Claims;
namespace IM_API.Hubs
{
public class ChatHub:Hub
{
private IMessageSevice _messageService;
private readonly IConversationService _conversationService;
private readonly IDatabase _redis;
public ChatHub(IMessageSevice messageService, IConversationService conversationService,
IConnectionMultiplexer connectionMultiplexer)
{
_messageService = messageService;
_conversationService = conversationService;
_redis = connectionMultiplexer.GetDatabase();
}
public async override Task OnConnectedAsync()
{
if (!Context.User.Identity.IsAuthenticated)
{
Context.Abort();
return;
}
//将用户加入已加入聊天的会话组
string userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
var keys = await _conversationService.GetUserAllStreamKeyAsync(int.Parse(userIdStr));
foreach (var key in keys)
{
await Groups.AddToGroupAsync(Context.ConnectionId, key);
}
//储存用户对应的连接id
await _redis.SetAddAsync(RedisKeys.GetConnectionIdKey(userIdStr), Context.ConnectionId);
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
if (!Context.User.Identity.IsAuthenticated)
{
string useridStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
await _redis.SetRemoveAsync(RedisKeys.GetConnectionIdKey(useridStr), Context.ConnectionId);
}
await base.OnDisconnectedAsync(exception);
}
public async Task<HubResponse<MessageBaseVo?>> SendMessage(MessageBaseDto dto)
{
if (!Context.User.Identity.IsAuthenticated)
{
await Clients.Caller.SendAsync("ReceiveMessage", new BaseResponse<object?>(CodeDefine.AUTH_FAILED));
Context.Abort();
return new HubResponse<MessageBaseVo?>(CodeDefine.AUTH_FAILED, "SendMessage");
}
var userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
MessageBaseVo? msgInfo = null;
if(dto.ChatType == ChatType.PRIVATE)
{
msgInfo = await _messageService.SendPrivateMessageAsync(int.Parse(userIdStr), dto.ReceiverId, dto);
}
else
{
msgInfo = await _messageService.SendGroupMessageAsync(int.Parse(userIdStr), dto.ReceiverId, dto);
}
return new HubResponse<MessageBaseVo?>("SendMessage", msgInfo);
}
public async Task<HubResponse<object?>> ClearUnreadCount(int conversationId)
{
if (!Context.User.Identity.IsAuthenticated)
{
await Clients.Caller.SendAsync("ReceiveMessage", new BaseResponse<object?>(CodeDefine.AUTH_FAILED));
Context.Abort();
return new HubResponse<object?>(CodeDefine.AUTH_FAILED, "ClearUnreadCount"); ;
}
var userIdStr = Context.User.FindFirstValue(ClaimTypes.NameIdentifier);
await _conversationService.ClearUnreadCountAsync(int.Parse(userIdStr), conversationId);
return new HubResponse<object?>("ClearUnreadCount");
}
}
}
+36 -36
View File
@@ -1,36 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>3f396849-59bd-435f-a0cb-351ec0559e70</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.0" />
<PackageReference Include="MassTransit.RabbitMQ" Version="8.5.5" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.21" />
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.21">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.21">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.2" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.22.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.3" />
<PackageReference Include="RedLock.net" Version="2.3.2" />
<PackageReference Include="StackExchange.Redis" Version="2.9.32" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.14.0" />
</ItemGroup>
</Project>
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>3f396849-59bd-435f-a0cb-351ec0559e70</UserSecretsId>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
<DockerfileContext>.</DockerfileContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AutoMapper" Version="12.0.1" />
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.0" />
<PackageReference Include="MassTransit.RabbitMQ" Version="8.5.5" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.21" />
<PackageReference Include="Microsoft.AspNetCore.SignalR" Version="1.2.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="8.0.21">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="8.0.21">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.Caching.StackExchangeRedis" Version="10.0.2" />
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.22.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.4" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.3" />
<PackageReference Include="RedLock.net" Version="2.3.2" />
<PackageReference Include="StackExchange.Redis" Version="2.9.32" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.14.0" />
</ItemGroup>
</Project>
+10 -10
View File
@@ -1,11 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>http</ActiveDebugProfile>
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>http</ActiveDebugProfile>
<Controller_SelectedScaffolderID>ApiControllerEmptyScaffolder</Controller_SelectedScaffolderID>
<Controller_SelectedScaffolderCategoryPath>root/Common/Api</Controller_SelectedScaffolderCategoryPath>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>
+6 -6
View File
@@ -1,6 +1,6 @@
@IM_API_HostAddress = http://localhost:5202
GET {{IM_API_HostAddress}}/weatherforecast/
Accept: application/json
###
@IM_API_HostAddress = http://localhost:5202
GET {{IM_API_HostAddress}}/weatherforecast/
Accept: application/json
###
+31 -31
View File
@@ -1,31 +1,31 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36408.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IM_API", "IM_API.csproj", "{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IMTest", "..\IMTest\IMTest.csproj", "{9DB9D44A-2D86-45A2-B651-D976277CF324}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}.Release|Any CPU.Build.0 = Release|Any CPU
{9DB9D44A-2D86-45A2-B651-D976277CF324}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9DB9D44A-2D86-45A2-B651-D976277CF324}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9DB9D44A-2D86-45A2-B651-D976277CF324}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9DB9D44A-2D86-45A2-B651-D976277CF324}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EC36B0B9-6176-4BC7-BF88-33F923E3E777}
EndGlobalSection
EndGlobal
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36408.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IM_API", "IM_API.csproj", "{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "IMTest", "..\IMTest\IMTest.csproj", "{9DB9D44A-2D86-45A2-B651-D976277CF324}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F001642C-3E66-4C2C-9A25-1AE5EE76CE97}.Release|Any CPU.Build.0 = Release|Any CPU
{9DB9D44A-2D86-45A2-B651-D976277CF324}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{9DB9D44A-2D86-45A2-B651-D976277CF324}.Debug|Any CPU.Build.0 = Debug|Any CPU
{9DB9D44A-2D86-45A2-B651-D976277CF324}.Release|Any CPU.ActiveCfg = Release|Any CPU
{9DB9D44A-2D86-45A2-B651-D976277CF324}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EC36B0B9-6176-4BC7-BF88-33F923E3E777}
EndGlobalSection
EndGlobal
@@ -1,32 +1,32 @@
using IM_API.Application.Interfaces;
using IM_API.Domain.Interfaces;
namespace IM_API.Infrastructure.EventBus
{
public class InMemoryEventBus : IEventBus
{
private IServiceProvider _serviceProvider;
private ILogger<InMemoryEventBus> _logger;
public InMemoryEventBus(IServiceProvider serviceProvider, ILogger<InMemoryEventBus> logger)
{
_serviceProvider = serviceProvider;
_logger = logger;
}
public async Task PublishAsync<TEvent>(TEvent @event) where TEvent : IEvent
{
var handlers = _serviceProvider.GetServices<IEventHandler<TEvent>>();
foreach (var handler in handlers)
{
try
{
await handler.Handle(@event);
}
catch(Exception e)
{
_logger.LogError("EventHandler error:"+e.Message, e);
}
}
}
}
}
using IM_API.Application.Interfaces;
using IM_API.Domain.Interfaces;
namespace IM_API.Infrastructure.EventBus
{
public class InMemoryEventBus : IEventBus
{
private IServiceProvider _serviceProvider;
private ILogger<InMemoryEventBus> _logger;
public InMemoryEventBus(IServiceProvider serviceProvider, ILogger<InMemoryEventBus> logger)
{
_serviceProvider = serviceProvider;
_logger = logger;
}
public async Task PublishAsync<TEvent>(TEvent @event) where TEvent : IEvent
{
var handlers = _serviceProvider.GetServices<IEventHandler<TEvent>>();
foreach (var handler in handlers)
{
try
{
await handler.Handle(@event);
}
catch(Exception e)
{
_logger.LogError("EventHandler error:"+e.Message, e);
}
}
}
}
}
@@ -1,22 +1,22 @@
using IM_API.Dtos.Auth;
using IM_API.Dtos.User;
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface IAuthService
{
/// <summary>
/// 登录
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
Task<User> LoginAsync(LoginRequestDto dto);
/// <summary>
/// 注册
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
Task<UserInfoDto> RegisterAsync(RegisterRequestDto dto);
}
}
using IM_API.Dtos.Auth;
using IM_API.Dtos.User;
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface IAuthService
{
/// <summary>
/// 登录
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
Task<User> LoginAsync(LoginRequestDto dto);
/// <summary>
/// 注册
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
Task<UserInfoDto> RegisterAsync(RegisterRequestDto dto);
}
}
@@ -1,49 +1,49 @@
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface ICacheService
{
/// <summary>
/// 设置缓存
/// </summary>
/// <typeparam name="T">缓存对象类型</typeparam>
/// <param name="key">缓存索引值</param>
/// <param name="value">要缓存的对象</param>
/// <param name="expiration">过期时间</param>
/// <returns></returns>
Task SetAsync<T>(string key, T value, TimeSpan? expiration = null);
/// <summary>
/// 获取缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">缓存索引</param>
/// <returns></returns>
Task<T?> GetAsync<T>(string key);
/// <summary>
/// 删除缓存
/// </summary>
/// <param name="key">缓存索引</param>
/// <returns></returns>
Task RemoveAsync(string key);
/// <summary>
/// 设置用户缓存
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
Task SetUserCacheAsync(User user);
/// <summary>
/// 通过用户名获取用户缓存
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
Task<User?> GetUserCacheAsync(string username);
/// <summary>
/// 删除用户缓存
/// </summary>
/// <param name="id"></param>
/// <param name="username"></param>
/// <returns></returns>
Task RemoveUserCacheAsync(string username);
}
}
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface ICacheService
{
/// <summary>
/// 设置缓存
/// </summary>
/// <typeparam name="T">缓存对象类型</typeparam>
/// <param name="key">缓存索引值</param>
/// <param name="value">要缓存的对象</param>
/// <param name="expiration">过期时间</param>
/// <returns></returns>
Task SetAsync<T>(string key, T value, TimeSpan? expiration = null);
/// <summary>
/// 获取缓存
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">缓存索引</param>
/// <returns></returns>
Task<T?> GetAsync<T>(string key);
/// <summary>
/// 删除缓存
/// </summary>
/// <param name="key">缓存索引</param>
/// <returns></returns>
Task RemoveAsync(string key);
/// <summary>
/// 设置用户缓存
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
Task SetUserCacheAsync(User user);
/// <summary>
/// 通过用户名获取用户缓存
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
Task<User?> GetUserCacheAsync(string username);
/// <summary>
/// 删除用户缓存
/// </summary>
/// <param name="id"></param>
/// <param name="username"></param>
/// <returns></returns>
Task RemoveUserCacheAsync(string username);
}
}
@@ -1,56 +1,56 @@
using IM_API.Dtos.Conversation;
using IM_API.Models;
using IM_API.VOs.Conversation;
namespace IM_API.Interface.Services
{
public interface IConversationService
{
/// <summary>
/// 清除消息会话
/// </summary>
/// <param name="clearConversationsDto"></param>
/// <returns></returns>
Task<bool> ClearConversationsAsync(int userId);
/// <summary>
/// 删除单个聊天会话
/// </summary>
/// <param name="conversationId"></param>
/// <returns></returns>
Task<bool> DeleteConversationAsync(int conversationId);
/// <summary>
/// 获取用户当前消息会话
/// </summary>
/// <param name="userId">用户id</param>
/// <returns></returns>
Task<List<ConversationVo>> GetConversationsAsync(int userId);
/// <summary>
/// 获取指定用户的所有推送标识符
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<List<string>> GetUserAllStreamKeyAsync(int userId);
/// <summary>
/// 获取单个conversation信息
/// </summary>
/// <param name="conversationId"></param>
/// <returns></returns>
Task<ConversationVo> GetConversationByIdAsync(int userId, int conversationId);
/// <summary>
/// 清空未读消息
/// </summary>
/// <param name="userId"></param>
/// <param name="conversationId"></param>
/// <returns></returns>
Task<bool> ClearUnreadCountAsync(int userId, int conversationId);
/// <summary>
/// 为用户创建会话
/// </summary>
/// <param name="userAId"></param>
/// <param name="userBId"></param>
/// <param name="chatType"></param>
/// <returns></returns>
Task MakeConversationAsync(int userAId, int userBId, ChatType chatType);
Task UpdateConversationAfterSentAsync(UpdateConversationDto dto);
}
}
using IM_API.Dtos.Conversation;
using IM_API.Models;
using IM_API.VOs.Conversation;
namespace IM_API.Interface.Services
{
public interface IConversationService
{
/// <summary>
/// 清除消息会话
/// </summary>
/// <param name="clearConversationsDto"></param>
/// <returns></returns>
Task<bool> ClearConversationsAsync(int userId);
/// <summary>
/// 删除单个聊天会话
/// </summary>
/// <param name="conversationId"></param>
/// <returns></returns>
Task<bool> DeleteConversationAsync(int conversationId);
/// <summary>
/// 获取用户当前消息会话
/// </summary>
/// <param name="userId">用户id</param>
/// <returns></returns>
Task<List<ConversationVo>> GetConversationsAsync(int userId);
/// <summary>
/// 获取指定用户的所有推送标识符
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<List<string>> GetUserAllStreamKeyAsync(int userId);
/// <summary>
/// 获取单个conversation信息
/// </summary>
/// <param name="conversationId"></param>
/// <returns></returns>
Task<ConversationVo> GetConversationByIdAsync(int userId, int conversationId);
/// <summary>
/// 清空未读消息
/// </summary>
/// <param name="userId"></param>
/// <param name="conversationId"></param>
/// <returns></returns>
Task<bool> ClearUnreadCountAsync(int userId, int conversationId);
/// <summary>
/// 为用户创建会话
/// </summary>
/// <param name="userAId"></param>
/// <param name="userBId"></param>
/// <param name="chatType"></param>
/// <returns></returns>
Task MakeConversationAsync(int userAId, int userBId, ChatType chatType);
Task UpdateConversationAfterSentAsync(UpdateConversationDto dto);
}
}
@@ -1,71 +1,71 @@
using IM_API.Dtos.Friend;
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface IFriendSerivce
{
/// <summary>
/// 获取好友列表
/// </summary>
/// <param name="userId">指定用户</param>
/// <param name="page">当前页</param>
/// <param name="limit">分页大小</param>
/// <returns></returns>
Task<List<FriendInfoDto>> GetFriendListAsync(int userId,int page,int limit,bool desc);
/// <summary>
/// 新增好友请求
/// </summary>
/// <param name="friendRequest"></param>
/// <returns></returns>
Task<bool> SendFriendRequestAsync(FriendRequestDto friendRequest);
/// <summary>
/// 获取好友请求
/// </summary>
/// <param name="userId"></param>
/// <param name="isReceived">是否为接受请求方</param>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <returns></returns>
Task<List<FriendRequestResDto>> GetFriendRequestListAsync(int userId,int page,int limit, bool desc);
/// <summary>
/// 处理好友请求
/// </summary>
/// <param name="requestDto"></param>
/// <returns></returns>
Task<bool> HandleFriendRequestAsync(HandleFriendRequestDto requestDto);
/// <summary>
/// 通过用户Id删除好友关系
/// </summary>
/// <param name="userId">操作用户Id</param>
/// <param name="toUserId">被删除用户ID</param>
/// <returns></returns>
Task<bool> DeleteFriendByUserIdAsync(int userId,int toUserId);
/// <summary>
/// 通过好友关系Id删除好友关系
/// </summary>
/// <param name="friendId">好友关系id</param>
/// <returns></returns>
Task<bool> DeleteFriendAsync(int friendId);
/// <summary>
/// 通过用户Id拉黑好友关系
/// </summary>
/// <param name="userId">操作用户Id</param>
/// <param name="toUserId">被拉黑用户ID</param>
/// <returns></returns>
Task<bool> BlockFriendByUserIdAsync(int userId, int toUserId);
/// <summary>
/// 通过好友关系Id拉黑好友关系
/// </summary>
/// <param name="friendId">好友关系id</param>
/// <returns></returns>
Task<bool> BlockeFriendAsync(int friendId);
/// <summary>
/// 创建好友关系
/// </summary>
/// <param name="userAId"></param>
/// <param name="userBId"></param>
/// <returns></returns>
Task MakeFriendshipAsync(int userAId, int userBId, string? remarkName);
}
}
using IM_API.Dtos.Friend;
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface IFriendSerivce
{
/// <summary>
/// 获取好友列表
/// </summary>
/// <param name="userId">指定用户</param>
/// <param name="page">当前页</param>
/// <param name="limit">分页大小</param>
/// <returns></returns>
Task<List<FriendInfoDto>> GetFriendListAsync(int userId,int page,int limit,bool desc);
/// <summary>
/// 新增好友请求
/// </summary>
/// <param name="friendRequest"></param>
/// <returns></returns>
Task<bool> SendFriendRequestAsync(FriendRequestDto friendRequest);
/// <summary>
/// 获取好友请求
/// </summary>
/// <param name="userId"></param>
/// <param name="isReceived">是否为接受请求方</param>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <returns></returns>
Task<List<FriendRequestResDto>> GetFriendRequestListAsync(int userId,int page,int limit, bool desc);
/// <summary>
/// 处理好友请求
/// </summary>
/// <param name="requestDto"></param>
/// <returns></returns>
Task<bool> HandleFriendRequestAsync(HandleFriendRequestDto requestDto);
/// <summary>
/// 通过用户Id删除好友关系
/// </summary>
/// <param name="userId">操作用户Id</param>
/// <param name="toUserId">被删除用户ID</param>
/// <returns></returns>
Task<bool> DeleteFriendByUserIdAsync(int userId,int toUserId);
/// <summary>
/// 通过好友关系Id删除好友关系
/// </summary>
/// <param name="friendId">好友关系id</param>
/// <returns></returns>
Task<bool> DeleteFriendAsync(int friendId);
/// <summary>
/// 通过用户Id拉黑好友关系
/// </summary>
/// <param name="userId">操作用户Id</param>
/// <param name="toUserId">被拉黑用户ID</param>
/// <returns></returns>
Task<bool> BlockFriendByUserIdAsync(int userId, int toUserId);
/// <summary>
/// 通过好友关系Id拉黑好友关系
/// </summary>
/// <param name="friendId">好友关系id</param>
/// <returns></returns>
Task<bool> BlockeFriendAsync(int friendId);
/// <summary>
/// 创建好友关系
/// </summary>
/// <param name="userAId"></param>
/// <param name="userBId"></param>
/// <returns></returns>
Task MakeFriendshipAsync(int userAId, int userBId, string? remarkName);
}
}
@@ -1,55 +1,55 @@
using IM_API.Dtos.Group;
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface IGroupService
{
/// <summary>
/// 邀请好友入群
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="groupId">群ID</param>
/// <param name="userIds">邀请的用户列表</param>
/// <returns></returns>
Task InviteUsersAsync(int userId,int groupId, List<int> userIds);
/// <summary>
/// 加入群聊
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="groupId">群ID</param>
/// <returns></returns>
Task JoinGroupAsync(int userId,int groupId);
/// <summary>
/// 创建群聊
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="groupCreateDto">群信息</param>
/// <param name="userIds">邀请用户列表</param>
/// <returns></returns>
Task<GroupInfoDto> CreateGroupAsync(int userId, GroupCreateDto groupCreateDto);
/// <summary>
/// 删除群
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="groupId">群ID</param>
/// <returns></returns>
Task DeleteGroupAsync(int userId, int groupId);
/// <summary>
/// 获取当前用户群列表
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <param name="desc"></param>
/// <returns></returns>
Task<List<GroupInfoDto>> GetGroupListAsync(int userId, int page, int limit, bool desc);
Task UpdateGroupConversationAsync(GroupUpdateConversationDto dto);
Task HandleGroupInviteAsync(int userid, HandleGroupInviteDto dto);
Task HandleGroupRequestAsync(int userid, HandleGroupRequestDto dto);
Task MakeGroupRequestAsync(int userId,int? adminUserId,int groupId);
Task MakeGroupMemberAsync(int userId, int groupId, GroupMemberRole? role);
}
}
using IM_API.Dtos.Group;
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface IGroupService
{
/// <summary>
/// 邀请好友入群
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="groupId">群ID</param>
/// <param name="userIds">邀请的用户列表</param>
/// <returns></returns>
Task InviteUsersAsync(int userId,int groupId, List<int> userIds);
/// <summary>
/// 加入群聊
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="groupId">群ID</param>
/// <returns></returns>
Task JoinGroupAsync(int userId,int groupId);
/// <summary>
/// 创建群聊
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="groupCreateDto">群信息</param>
/// <param name="userIds">邀请用户列表</param>
/// <returns></returns>
Task<GroupInfoDto> CreateGroupAsync(int userId, GroupCreateDto groupCreateDto);
/// <summary>
/// 删除群
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="groupId">群ID</param>
/// <returns></returns>
Task DeleteGroupAsync(int userId, int groupId);
/// <summary>
/// 获取当前用户群列表
/// </summary>
/// <param name="userId">操作者ID</param>
/// <param name="page"></param>
/// <param name="limit"></param>
/// <param name="desc"></param>
/// <returns></returns>
Task<List<GroupInfoDto>> GetGroupListAsync(int userId, int page, int limit, bool desc);
Task UpdateGroupConversationAsync(GroupUpdateConversationDto dto);
Task HandleGroupInviteAsync(int userid, HandleGroupInviteDto dto);
Task HandleGroupRequestAsync(int userid, HandleGroupRequestDto dto);
Task MakeGroupRequestAsync(int userId,int? adminUserId,int groupId);
Task MakeGroupMemberAsync(int userId, int groupId, GroupMemberRole? role);
}
}
@@ -1,21 +1,21 @@
using System.Security.Claims;
namespace IM_API.Interface.Services
{
public interface IJWTService
{
/// <summary>
/// 生成用户凭证
/// </summary>
/// <param name="claims">负载</param>
/// <param name="expiresAt">过期时间</param>
/// <returns></returns>
string GenerateAccessToken(IEnumerable<Claim> claims, DateTime expiresAt);
/// <summary>
/// 创建用户凭证
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
(string token, DateTime expiresAt) CreateAccessTokenForUser(int userId,string username,string role);
}
}
using System.Security.Claims;
namespace IM_API.Interface.Services
{
public interface IJWTService
{
/// <summary>
/// 生成用户凭证
/// </summary>
/// <param name="claims">负载</param>
/// <param name="expiresAt">过期时间</param>
/// <returns></returns>
string GenerateAccessToken(IEnumerable<Claim> claims, DateTime expiresAt);
/// <summary>
/// 创建用户凭证
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
(string token, DateTime expiresAt) CreateAccessTokenForUser(int userId,string username,string role);
}
}
@@ -1,53 +1,53 @@
using IM_API.Dtos;
using IM_API.Dtos.Message;
using IM_API.Models;
using IM_API.VOs.Message;
namespace IM_API.Interface.Services
{
public interface IMessageSevice
{
/// <summary>
/// 发送私聊消息
/// </summary>
/// <param name="senderId">发送人id</param>
/// <param name="receiverId">接收人</param>
/// <param name="dto"></param>
/// <returns></returns>
Task<MessageBaseVo> SendPrivateMessageAsync(int senderId,int receiverId,MessageBaseDto dto);
/// <summary>
/// 发送群聊消息
/// </summary>
/// <param name="senderId">发送人id</param>
/// <param name="groupId">接收群id</param>
/// <param name="dto"></param>
/// <returns></returns>
Task<MessageBaseVo> SendGroupMessageAsync(int senderId,int groupId,MessageBaseDto dto);
/// <summary>
/// 消息入库
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
Task MakeMessageAsync(Message message);
/// <summary>
/// 获取历史消息列表
/// </summary>
/// <param name="conversationId">会话id(用于获取指定用户间聊天消息)</param>
/// <param name="sequenceId">消息id</param>
/// <param name="pageSize">获取消息数量</param>
/// <returns></returns>
Task<List<MessageBaseVo>> GetMessagesAsync(int userId,MessageQueryDto dto);
/// <summary>
/// 获取未读消息数
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<int> GetUnreadCountAsync(int userId);
Task<List<MessageBaseDto>> GetUnreadMessagesAsync(int userId);
Task<bool> MarkAsReadAsync(int userId,long messageId);
Task<bool> MarkConversationAsReadAsync(int userId,int? userBId,int? groupId);
Task<bool> RecallMessageAsync(int userId,int messageId);
}
}
using IM_API.Dtos;
using IM_API.Dtos.Message;
using IM_API.Models;
using IM_API.VOs.Message;
namespace IM_API.Interface.Services
{
public interface IMessageSevice
{
/// <summary>
/// 发送私聊消息
/// </summary>
/// <param name="senderId">发送人id</param>
/// <param name="receiverId">接收人</param>
/// <param name="dto"></param>
/// <returns></returns>
Task<MessageBaseVo> SendPrivateMessageAsync(int senderId,int receiverId,MessageBaseDto dto);
/// <summary>
/// 发送群聊消息
/// </summary>
/// <param name="senderId">发送人id</param>
/// <param name="groupId">接收群id</param>
/// <param name="dto"></param>
/// <returns></returns>
Task<MessageBaseVo> SendGroupMessageAsync(int senderId,int groupId,MessageBaseDto dto);
/// <summary>
/// 消息入库
/// </summary>
/// <param name="message"></param>
/// <returns></returns>
Task MakeMessageAsync(Message message);
/// <summary>
/// 获取历史消息列表
/// </summary>
/// <param name="conversationId">会话id(用于获取指定用户间聊天消息)</param>
/// <param name="sequenceId">消息id</param>
/// <param name="pageSize">获取消息数量</param>
/// <returns></returns>
Task<List<MessageBaseVo>> GetMessagesAsync(int userId,MessageQueryDto dto);
/// <summary>
/// 获取未读消息数
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<int> GetUnreadCountAsync(int userId);
Task<List<MessageBaseDto>> GetUnreadMessagesAsync(int userId);
Task<bool> MarkAsReadAsync(int userId,long messageId);
Task<bool> MarkConversationAsReadAsync(int userId,int? userBId,int? groupId);
Task<bool> RecallMessageAsync(int userId,int messageId);
}
}
@@ -1,27 +1,27 @@
namespace IM_API.Interface.Services
{
public interface IRefreshTokenService
{
/// <summary>
/// 创建刷新令牌
/// </summary>
/// <param name="userId"></param>
/// <param name="ct"></param>
/// <returns></returns>
Task<string> CreateRefreshTokenAsync(int userId, CancellationToken ct = default);
/// <summary>
/// 验证刷新令牌
/// </summary>
/// <param name="token">刷新令牌</param>
/// <param name="ct"></param>
/// <returns></returns>
Task<(bool ok, int userId)> ValidateRefreshTokenAsync(string token, CancellationToken ct = default);
/// <summary>
/// 删除更新令牌
/// </summary>
/// <param name="token">刷新令牌</param>
/// <param name="ct"></param>
/// <returns></returns>
Task RevokeRefreshTokenAsync(string token, CancellationToken ct = default);
}
}
namespace IM_API.Interface.Services
{
public interface IRefreshTokenService
{
/// <summary>
/// 创建刷新令牌
/// </summary>
/// <param name="userId"></param>
/// <param name="ct"></param>
/// <returns></returns>
Task<string> CreateRefreshTokenAsync(int userId, CancellationToken ct = default);
/// <summary>
/// 验证刷新令牌
/// </summary>
/// <param name="token">刷新令牌</param>
/// <param name="ct"></param>
/// <returns></returns>
Task<(bool ok, int userId)> ValidateRefreshTokenAsync(string token, CancellationToken ct = default);
/// <summary>
/// 删除更新令牌
/// </summary>
/// <param name="token">刷新令牌</param>
/// <param name="ct"></param>
/// <returns></returns>
Task RevokeRefreshTokenAsync(string token, CancellationToken ct = default);
}
}
@@ -1,12 +1,12 @@
namespace IM_API.Interface.Services
{
public interface ISequenceIdService
{
/// <summary>
/// 创建消息序号
/// </summary>
/// <param name="streamKey">聊天唯一标识/param>
/// <returns></returns>
Task<long> GetNextSquenceIdAsync(string streamKey);
}
}
namespace IM_API.Interface.Services
{
public interface ISequenceIdService
{
/// <summary>
/// 创建消息序号
/// </summary>
/// <param name="streamKey">聊天唯一标识/param>
/// <returns></returns>
Task<long> GetNextSquenceIdAsync(string streamKey);
}
}
@@ -1,45 +1,45 @@
using IM_API.Dtos.User;
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface IUserService
{
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<UserInfoDto> GetUserInfoAsync(int userId);
/// <summary>
/// 用户名查找用户
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
Task<UserInfoDto> GetUserInfoByUsernameAsync(string username);
/// <summary>
/// 更新用户信息
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
Task<UserInfoDto> UpdateUserAsync(int userId, UpdateUserDto dto);
/// <summary>
/// 重置用户密码
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
Task<bool> ResetPasswordAsync(int userId, string oldPassword, string password);
/// <summary>
/// 更新用户在线状态
/// </summary>
/// <param name="onlineStatus"></param>
/// <returns></returns>
Task<bool> UpdateOlineStatusAsync(int userId, UserOnlineStatus onlineStatus);
/// <summary>
/// 批量获取用户信息
/// </summary>
/// <param name="ids">用户id列表</param>
/// <returns></returns>
Task<List<UserInfoDto>> GetUserInfoListAsync(List<int> ids);
}
}
using IM_API.Dtos.User;
using IM_API.Models;
namespace IM_API.Interface.Services
{
public interface IUserService
{
/// <summary>
/// 获取用户信息
/// </summary>
/// <param name="userId"></param>
/// <returns></returns>
Task<UserInfoDto> GetUserInfoAsync(int userId);
/// <summary>
/// 用户名查找用户
/// </summary>
/// <param name="username"></param>
/// <returns></returns>
Task<UserInfoDto> GetUserInfoByUsernameAsync(string username);
/// <summary>
/// 更新用户信息
/// </summary>
/// <param name="dto"></param>
/// <returns></returns>
Task<UserInfoDto> UpdateUserAsync(int userId, UpdateUserDto dto);
/// <summary>
/// 重置用户密码
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
Task<bool> ResetPasswordAsync(int userId, string oldPassword, string password);
/// <summary>
/// 更新用户在线状态
/// </summary>
/// <param name="onlineStatus"></param>
/// <returns></returns>
Task<bool> UpdateOlineStatusAsync(int userId, UserOnlineStatus onlineStatus);
/// <summary>
/// 批量获取用户信息
/// </summary>
/// <param name="ids">用户id列表</param>
/// <returns></returns>
Task<List<UserInfoDto>> GetUserInfoListAsync(List<int> ids);
}
}
File diff suppressed because it is too large Load Diff
@@ -1,73 +1,73 @@
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "admins");
migrationBuilder.DropTable(
name: "conversations");
migrationBuilder.DropTable(
name: "devices");
migrationBuilder.DropTable(
name: "files");
migrationBuilder.DropTable(
name: "friend_request");
migrationBuilder.DropTable(
name: "friends");
migrationBuilder.DropTable(
name: "group_invite");
migrationBuilder.DropTable(
name: "group_member");
migrationBuilder.DropTable(
name: "group_request");
migrationBuilder.DropTable(
name: "login_log");
migrationBuilder.DropTable(
name: "notifications");
migrationBuilder.DropTable(
name: "permissionarole");
migrationBuilder.DropTable(
name: "messages");
migrationBuilder.DropTable(
name: "groups");
migrationBuilder.DropTable(
name: "roles");
migrationBuilder.DropTable(
name: "permissions");
migrationBuilder.DropTable(
name: "users");
}
}
}
using System;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class InitialCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "admins");
migrationBuilder.DropTable(
name: "conversations");
migrationBuilder.DropTable(
name: "devices");
migrationBuilder.DropTable(
name: "files");
migrationBuilder.DropTable(
name: "friend_request");
migrationBuilder.DropTable(
name: "friends");
migrationBuilder.DropTable(
name: "group_invite");
migrationBuilder.DropTable(
name: "group_member");
migrationBuilder.DropTable(
name: "group_request");
migrationBuilder.DropTable(
name: "login_log");
migrationBuilder.DropTable(
name: "notifications");
migrationBuilder.DropTable(
name: "permissionarole");
migrationBuilder.DropTable(
name: "messages");
migrationBuilder.DropTable(
name: "groups");
migrationBuilder.DropTable(
name: "roles");
migrationBuilder.DropTable(
name: "permissions");
migrationBuilder.DropTable(
name: "users");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,28 +1,28 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class change_file : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Type",
table: "files",
newName: "FileType");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "FileType",
table: "files",
newName: "Type");
}
}
}
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class change_file : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "Type",
table: "files",
newName: "FileType");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "FileType",
table: "files",
newName: "Type");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,40 +1,40 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class addSequenceId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "GroupMemberId",
table: "messages");
migrationBuilder.AddColumn<long>(
name: "SequenceId",
table: "messages",
type: "bigint",
nullable: false,
defaultValue: 0L);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "SequenceId",
table: "messages");
migrationBuilder.AddColumn<int>(
name: "GroupMemberId",
table: "messages",
type: "int(11)",
nullable: true,
comment: "若为群消息则表示具体的成员id");
}
}
}
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class addSequenceId : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "GroupMemberId",
table: "messages");
migrationBuilder.AddColumn<long>(
name: "SequenceId",
table: "messages",
type: "bigint",
nullable: false,
defaultValue: 0L);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "SequenceId",
table: "messages");
migrationBuilder.AddColumn<int>(
name: "GroupMemberId",
table: "messages",
type: "int(11)",
nullable: true,
comment: "若为群消息则表示具体的成员id");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,41 +1,41 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class updateconversationlastreadmessageid : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "conversations_ibfk_2",
table: "conversations");
migrationBuilder.AddForeignKey(
name: "conversations_ibfk_2",
table: "conversations",
column: "lastReadMessageId",
principalTable: "messages",
principalColumn: "ID",
onDelete: ReferentialAction.SetNull);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "conversations_ibfk_2",
table: "conversations");
migrationBuilder.AddForeignKey(
name: "conversations_ibfk_2",
table: "conversations",
column: "lastReadMessageId",
principalTable: "messages",
principalColumn: "ID");
}
}
}
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class updateconversationlastreadmessageid : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "conversations_ibfk_2",
table: "conversations");
migrationBuilder.AddForeignKey(
name: "conversations_ibfk_2",
table: "conversations",
column: "lastReadMessageId",
principalTable: "messages",
principalColumn: "ID",
onDelete: ReferentialAction.SetNull);
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "conversations_ibfk_2",
table: "conversations");
migrationBuilder.AddForeignKey(
name: "conversations_ibfk_2",
table: "conversations",
column: "lastReadMessageId",
principalTable: "messages",
principalColumn: "ID");
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,93 +1,93 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class updatemessage : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "conversations_ibfk_2",
table: "conversations");
migrationBuilder.RenameIndex(
name: "lastMessageId",
table: "conversations",
newName: "LastReadSequenceId");
migrationBuilder.AddColumn<Guid>(
name: "ClientMsgId",
table: "messages",
type: "char(36)",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"),
collation: "ascii_general_ci");
migrationBuilder.AddColumn<int>(
name: "MessageId",
table: "conversations",
type: "int(11)",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_messages_SequenceId_StreamKey",
table: "messages",
columns: new[] { "SequenceId", "StreamKey" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_conversations_MessageId",
table: "conversations",
column: "MessageId");
migrationBuilder.AddForeignKey(
name: "FK_conversations_messages_MessageId",
table: "conversations",
column: "MessageId",
principalTable: "messages",
principalColumn: "ID");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_conversations_messages_MessageId",
table: "conversations");
migrationBuilder.DropIndex(
name: "IX_messages_SequenceId_StreamKey",
table: "messages");
migrationBuilder.DropIndex(
name: "IX_conversations_MessageId",
table: "conversations");
migrationBuilder.DropColumn(
name: "ClientMsgId",
table: "messages");
migrationBuilder.DropColumn(
name: "MessageId",
table: "conversations");
migrationBuilder.RenameIndex(
name: "LastReadSequenceId",
table: "conversations",
newName: "lastMessageId");
migrationBuilder.AddForeignKey(
name: "conversations_ibfk_2",
table: "conversations",
column: "lastReadMessageId",
principalTable: "messages",
principalColumn: "ID",
onDelete: ReferentialAction.SetNull);
}
}
}
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class updatemessage : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "conversations_ibfk_2",
table: "conversations");
migrationBuilder.RenameIndex(
name: "lastMessageId",
table: "conversations",
newName: "LastReadSequenceId");
migrationBuilder.AddColumn<Guid>(
name: "ClientMsgId",
table: "messages",
type: "char(36)",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"),
collation: "ascii_general_ci");
migrationBuilder.AddColumn<int>(
name: "MessageId",
table: "conversations",
type: "int(11)",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_messages_SequenceId_StreamKey",
table: "messages",
columns: new[] { "SequenceId", "StreamKey" },
unique: true);
migrationBuilder.CreateIndex(
name: "IX_conversations_MessageId",
table: "conversations",
column: "MessageId");
migrationBuilder.AddForeignKey(
name: "FK_conversations_messages_MessageId",
table: "conversations",
column: "MessageId",
principalTable: "messages",
principalColumn: "ID");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_conversations_messages_MessageId",
table: "conversations");
migrationBuilder.DropIndex(
name: "IX_messages_SequenceId_StreamKey",
table: "messages");
migrationBuilder.DropIndex(
name: "IX_conversations_MessageId",
table: "conversations");
migrationBuilder.DropColumn(
name: "ClientMsgId",
table: "messages");
migrationBuilder.DropColumn(
name: "MessageId",
table: "conversations");
migrationBuilder.RenameIndex(
name: "LastReadSequenceId",
table: "conversations",
newName: "lastMessageId");
migrationBuilder.AddForeignKey(
name: "conversations_ibfk_2",
table: "conversations",
column: "lastReadMessageId",
principalTable: "messages",
principalColumn: "ID",
onDelete: ReferentialAction.SetNull);
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,22 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class updatedatetimeToDateTimeOffset : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class updatedatetimeToDateTimeOffset : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
File diff suppressed because it is too large Load Diff
@@ -1,22 +1,22 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class updateDateTimeOffsettype : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace IM_API.Migrations
{
/// <inheritdoc />
public partial class updateDateTimeOffsettype : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
}
}
}

Some files were not shown because too many files have changed in this diff Show More