网站首页 网站源码
website
站点相关全部源代码,隐藏了一些关于服务器的信息
using Dpz.Core.Service.Network;
using Dpz.Core.Service.Network.Models.XunFei;
using Microsoft.AspNetCore.SignalR;

namespace Dpz.Core.Web.Library.Hub;

public class RobotChatHub(
    ILogger<RobotChatHub> logger,
    IChatRecordService chatRecordService,
    IConfiguration configuration,
    XunFeiService xunFeiService
) : Microsoft.AspNetCore.SignalR.Hub
{
    public async Task SendMessage(string question)
    {
        var sessionId = Guid.NewGuid().ToString("N");

        var httpContext = Context.GetHttpContext();
        var userId =
            Context.User?.IsLogin() == true
                ? Context.User.GetIdentity()?.Id
                : httpContext?.Request.Cookies[Program.AuthorizeCookieName + ".SessionId"];
        if (!string.IsNullOrEmpty(userId))
        {
            sessionId = userId;
        }

        var request = GetRequest(sessionId, question);
        List<XunFeiResponse?>? responses = null;
        try
        {
            responses = await xunFeiService.ChatAsync(request);
        }
        catch (Exception ex)
        {
            await Clients.Caller.SendCoreAsync("SystemError", [$"调用API出错,错误信息:{ex.Message}"]);
            logger.LogError(ex, "API调用出错");
        }

        var message = "";
        if (responses != null)
        {
            var messageSb = new StringBuilder();
            responses.ForEach(x =>
                messageSb.Append(x?.Payload?.Choices?.Text?.FirstOrDefault()?.Content ?? "")
            );
            message = messageSb.ToString();
            await Clients.Caller.SendCoreAsync(
                "Answer",
                [
                    new
                    {
                        id = "kefu",
                        avatar = $"{configuration["CDNBaseAddress"]}/images/ai.jpg",
                        username = "星火认知大模型",
                        type = "friend",
                        content = message,
                        mine = false
                    }
                ]
            );
        }

        VmUserInfo? sender;
        if (Context.User.IsLogin())
        {
            #region save record

            sender = Context.User?.GetIdentity();

            #endregion
        }
        else
        {
            sender = new VmUserInfo
            {
                Avatar = $"{configuration["CDNBaseAddress"]}/images/member.png",
                Enable = false,
                Id = sessionId,
                Key = "",
                LastAccessTime = DateTime.Now,
                Name = sessionId,
                Permissions = null
            };
        }

        await chatRecordService.SaveRobotRecordAsync(sender, question, message);
    }

    private XunFeiRequest GetRequest(string uid, string question)
    {
        return new XunFeiRequest
        {
            Header = new XunFeiRequestHeader
            {
                AppId = configuration["XunFei:AppId"] ?? throw new Exception("AppId is null"),
                Uid = uid
            },
            Parameter = new XunFeiRequestParameter { Chat = new XunFeiRequestChat(), },
            Payload = new XunFeiRequestPayload
            {
                Message = new XunFeiRequestMessage
                {
                    Text = [new XunFeiRequestText { Content = question, Role = "user" }]
                }
            }
        };
    }

    public override Task OnConnectedAsync()
    {
        var sessionId = Context
            .GetHttpContext()
            ?.Request.Cookies[Program.AuthorizeCookieName + ".SessionId"];
        Clients.Caller.SendCoreAsync("Connected", ["websocket connected.", sessionId]);
        return base.OnConnectedAsync();
    }

    public override Task OnDisconnectedAsync(Exception? exception)
    {
        var sessionId = Context
            .GetHttpContext()
            ?.Request.Cookies[Program.AuthorizeCookieName + ".SessionId"];
        Clients.Caller.SendCoreAsync("Disconnected", ["websocket disconnected.", sessionId]);
        if (exception != null)
        {
            logger.LogError(exception, "signalR disconnected");
        }

        return base.OnDisconnectedAsync(exception);
    }
}
loading