84 lines
2.8 KiB
C#
84 lines
2.8 KiB
C#
using System;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
using ChessGameService;
|
|
using CommonDomain;
|
|
using DotNetCore.CAP;
|
|
using Microsoft.Extensions.Logging;
|
|
using RedisService;
|
|
|
|
namespace ChessGameService.Subscribers
|
|
{
|
|
public class ChessLoginSubscriber : ICapSubscribe
|
|
{
|
|
private readonly IChessGameService _chessService;
|
|
private readonly IRedisService _redisService;
|
|
private readonly ICapPublisher _capPublisher;
|
|
private readonly ILogger<ChessLoginSubscriber> _logger;
|
|
|
|
public ChessLoginSubscriber(
|
|
IChessGameService chessService,
|
|
IRedisService redisService,
|
|
ICapPublisher capPublisher,
|
|
ILogger<ChessLoginSubscriber> logger)
|
|
{
|
|
_chessService = chessService;
|
|
_redisService = redisService;
|
|
_capPublisher = capPublisher;
|
|
_logger = logger;
|
|
}
|
|
|
|
[CapSubscribe(TopicKeys.登录绑定)]
|
|
public async Task HandleLoginBind(LoginBindMessage msg)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(msg.UserId))
|
|
return;
|
|
|
|
var rooms = _redisService.GetAllChessRooms();
|
|
if (rooms == null)
|
|
return;
|
|
|
|
foreach (var room in rooms)
|
|
{
|
|
if (room == null || room.state != 2 || room.IsGameEnded)
|
|
continue;
|
|
|
|
var player = room.users?.FirstOrDefault(u => u.userId == msg.UserId);
|
|
if (player == null)
|
|
continue;
|
|
|
|
var winnerUserId = room.users.FirstOrDefault(u => u.userId != msg.UserId)?.userId ?? "";
|
|
if (string.IsNullOrWhiteSpace(winnerUserId))
|
|
{
|
|
continue;
|
|
}
|
|
|
|
try
|
|
{
|
|
await _chessService.EndGame(room.RoomId, winnerUserId);
|
|
await _capPublisher.PublishAsync(TopicKeys.登录结果通知, new LoginBindResultMessage
|
|
{
|
|
UserId = msg.UserId,
|
|
RoomId = room.RoomId,
|
|
OperationId = msg.OperationId,
|
|
Success = true
|
|
});
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
_logger.LogError(ex, "[象棋] 登录结算失败 userId={UserId} roomId={RoomId}", msg.UserId, room.RoomId);
|
|
await _capPublisher.PublishAsync(TopicKeys.登录结果通知, new LoginBindResultMessage
|
|
{
|
|
UserId = msg.UserId,
|
|
RoomId = room.RoomId,
|
|
OperationId = msg.OperationId,
|
|
Success = false,
|
|
Error = ex.Message
|
|
});
|
|
}
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
}
|