网站首页 网站源码
website
站点相关全部源代码,隐藏了一些关于服务器的信息
using System.Text;
using Dpz.Core.Service.Network;
using Dpz.Core.Service.Network.Models;
using Dpz.Core.Service.RepositoryService;
using Hangfire;
using JetBrains.Annotations;
using Medallion.Threading;
using Microsoft.Extensions.Logging;

namespace Dpz.Core.Hangfire;

[UsedImplicitly]
public class AnalyzeCodeActivator(
    AnalyzeService analyzeService,
    ICodeNoteService codeNoteService,
    IDistributedLockProvider distributedLockProvider,
    ILogger<AnalyzeCodeActivator> logger
) : JobActivator
{
    /// <summary>
    /// analyze code
    /// </summary>
    /// <param name="codeContent"></param>
    /// <param name="path"></param>
    /// <param name="fileName"></param>
    [ProlongExpirationTime]
    public async Task AnalyzeAsync(string codeContent, string[] path, string fileName)
    {
        var key = new List<string>(path) { fileName };
        if (GetContentLineCount(codeContent) < 50)
        {
            return;
        }

        var keyParts = new List<string>(path) { fileName };
        var subKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Join("\0", keyParts)));
        var lockKey = $"AI_Analyze.Code.Lock:{subKey}";
        await using (await distributedLockProvider.AcquireLockAsync(lockKey))
        {
            var codeNote = await codeNoteService.FindAsync(path, fileName);
            if (!string.IsNullOrWhiteSpace(codeNote?.AiAnalyzeResult))
            {
                return;
            }

            var prompt = new StringBuilder(codeContent)
                .AppendLine()
                .AppendLine()
                .Append("请解释一下上述代码的功能")
                .ToString();
            var result = await analyzeService.ChatAsync(
                [
                    new ChatMessage
                    {
                        Role = "system",
                        Message = "你是一个经验丰富且专业的开发人员",
                    },
                    new ChatMessage { Role = "user", Message = prompt },
                ]
            );

            if (result is { Success: true, Data: not null })
            {
                logger.LogInformation(
                    "AI分析成功 | Path:{@Path} File:{FileName},Data:{@Data}",
                    path,
                    fileName,
                    result.Data
                );
                await codeNoteService.SaveAiAnalyzeResultAsync(path, fileName, result.Data);
                return;
            }

            logger.LogWarning(
                "AI分析失败 | 错误信息:{Message} | Path:{@Path} File:{FileName}",
                result.Message,
                path,
                fileName
            );
        }
    }

    private static int GetContentLineCount(string codeContent)
    {
        return codeContent.Split(["\r\n", "\r", "\n"], StringSplitOptions.None).Length;
    }
}
loading