From 2c42fe9301d7e85b0700fd5c83eeff7379757f72 Mon Sep 17 00:00:00 2001 From: Chr_ Date: Fri, 24 Nov 2023 14:07:12 +0800 Subject: [PATCH] update --- Directory.Build.props | 2 +- Directory.Packages.props | 8 +- XinjingdailyBot.Command/AdminCommand.cs | 247 +++++----- XinjingdailyBot.Command/CommonCommand.cs | 33 +- XinjingdailyBot.Command/NormalCommand.cs | 46 +- XinjingdailyBot.Command/ObsoleteCommand.cs | 425 ++++++++++++++++++ XinjingdailyBot.Command/PostCommand.cs | 38 +- XinjingdailyBot.Command/ReviewCommand.cs | 34 +- XinjingdailyBot.Command/SuperCommand.cs | 351 +-------------- .../Data/IBanRecordService.cs | 6 + .../Data/IPostService.cs | 49 ++ .../Bot/Common/PollingService.cs | 62 +-- .../Bot/Common/UpdateService.cs | 23 +- .../Bot/Handler/ChannelPostHandler.cs | 53 +-- .../Bot/Handler/InlineQueryHandler.cs | 26 +- .../Data/AttachmentService.cs | 6 +- .../Data/BanRecordService.cs | 6 +- .../Data/DialogueService.cs | 6 +- XinjingdailyBot.Service/Data/PostService.cs | 90 ++-- XinjingdailyBot.Service/Data/UserService.cs | 56 +-- .../Helper/TextHelperService.cs | 16 +- XinjingdailyBot.Tasks/ExpiredPostsTask.cs | 43 +- XinjingdailyBot.Tasks/PlanedPostsTask.cs | 14 +- XinjingdailyBot.Tasks/ReviewStatusTask.cs | 46 +- .../IPC/Controllers/PostController.cs | 68 +-- 25 files changed, 804 insertions(+), 950 deletions(-) create mode 100644 XinjingdailyBot.Command/ObsoleteCommand.cs diff --git a/Directory.Build.props b/Directory.Build.props index 257c2e00..ed0cbf87 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 2.2.4.4 + 2.2.4.5 diff --git a/Directory.Packages.props b/Directory.Packages.props index a3e4e6eb..86e5663b 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,13 +7,13 @@ - + - - + + - + diff --git a/XinjingdailyBot.Command/AdminCommand.cs b/XinjingdailyBot.Command/AdminCommand.cs index f8d54fd9..f5308363 100644 --- a/XinjingdailyBot.Command/AdminCommand.cs +++ b/XinjingdailyBot.Command/AdminCommand.cs @@ -1,5 +1,4 @@ using Microsoft.Extensions.Logging; -using SqlSugar; using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; @@ -24,57 +23,23 @@ namespace XinjingdailyBot.Command; /// 管理员命令 /// [AppService(LifeTime.Scoped)] -internal class AdminCommand +internal class AdminCommand( + ILogger _logger, + ITelegramBotClient _botClient, + IUserService _userService, + GroupRepository groupRepository, + IBanRecordService banRecordService, + IPostService postService, + IAttachmentService attachmentService, + IChannelOptionService channelOptionService, + IChannelService channelService, + IMarkupHelperService markupHelperService, + ICmdRecordService cmdRecordService, + IUserTokenService userTokenService, + IMediaGroupService mediaGroupService, + ITextHelperService textHelperService, + IDialogueService dialogueService) { - private readonly ILogger _logger; - private readonly ITelegramBotClient _botClient; - private readonly IUserService _userService; - private readonly GroupRepository _groupRepository; - private readonly IBanRecordService _banRecordService; - private readonly IPostService _postService; - private readonly IAttachmentService _attachmentService; - private readonly IChannelOptionService _channelOptionService; - private readonly IChannelService _channelService; - private readonly IMarkupHelperService _markupHelperService; - private readonly ICmdRecordService _cmdRecordService; - private readonly IUserTokenService _userTokenService; - private readonly IMediaGroupService _mediaGroupService; - private readonly ITextHelperService _textHelperService; - private readonly IDialogueService _dialogueService; - - public AdminCommand( - ILogger logger, - ITelegramBotClient botClient, - IUserService userService, - GroupRepository groupRepository, - IBanRecordService banRecordService, - IPostService postService, - IAttachmentService attachmentService, - IChannelOptionService channelOptionService, - IChannelService channelService, - IMarkupHelperService markupHelperService, - ICmdRecordService cmdRecordService, - IUserTokenService userTokenService, - IMediaGroupService mediaGroupService, - ITextHelperService textHelperService, - IDialogueService dialogueService) - { - _logger = logger; - _botClient = botClient; - _userService = userService; - _groupRepository = groupRepository; - _banRecordService = banRecordService; - _postService = postService; - _attachmentService = attachmentService; - _channelOptionService = channelOptionService; - _channelService = channelService; - _markupHelperService = markupHelperService; - _cmdRecordService = cmdRecordService; - _userTokenService = userTokenService; - _mediaGroupService = mediaGroupService; - _textHelperService = textHelperService; - _dialogueService = dialogueService; - } /// /// 启动时间 @@ -134,7 +99,7 @@ public async Task ResponseUserInfo(Message message, string[] args) if (targetUser == null) { - if (args.Any()) + if (args.Length > 0) { targetUser = await _userService.FetchUserByUserNameOrUserID(args.First()); } @@ -179,7 +144,7 @@ async Task exec() if (targetUser == null) { - if (args.Any()) + if (args.Length > 0) { targetUser = await _userService.FetchUserByUserNameOrUserID(args.First()); args = args[1..]; @@ -191,7 +156,7 @@ async Task exec() return "找不到指定用户"; } - if (targetUser.Id == _channelService.BotUser.Id) + if (targetUser.Id == channelService.BotUser.Id) { return "你有事?"; } @@ -219,7 +184,7 @@ async Task exec() else { await _userService.BanUser(targetUser, true); - await _banRecordService.AddBanRecord(targetUser, dbUser, EBanType.Ban, reason); + await banRecordService.AddBanRecord(targetUser, dbUser, EBanType.Ban, reason); try { @@ -270,7 +235,7 @@ async Task exec() if (targetUser == null) { - if (args.Any()) + if (args.Length > 0) { targetUser = await _userService.FetchUserByUserNameOrUserID(args.First()); args = args[1..]; @@ -282,7 +247,7 @@ async Task exec() return "找不到指定用户"; } - if (targetUser.Id == _channelService.BotUser.Id) + if (targetUser.Id == channelService.BotUser.Id) { return "你有事?"; } @@ -310,7 +275,7 @@ async Task exec() else { await _userService.BanUser(targetUser, false); - await _banRecordService.AddBanRecord(targetUser, dbUser, EBanType.UnBan, reason); + await banRecordService.AddBanRecord(targetUser, dbUser, EBanType.UnBan, reason); try { @@ -358,7 +323,7 @@ async Task exec() if (targetUser == null) { - if (args.Any()) + if (args.Length > 0) { targetUser = await _userService.FetchUserByUserNameOrUserID(args.First()); args = args[1..]; @@ -370,7 +335,7 @@ async Task exec() return "找不到指定用户"; } - if (targetUser.Id == _channelService.BotUser.Id) + if (targetUser.Id == channelService.BotUser.Id) { return "你有事?"; } @@ -397,9 +362,9 @@ async Task exec() } else { - int warnCount = await _banRecordService.GetWarnCount(targetUser); + int warnCount = await banRecordService.GetWarnCount(targetUser); - await _banRecordService.AddBanRecord(targetUser, dbUser, EBanType.Warning, reason); + await banRecordService.AddBanRecord(targetUser, dbUser, EBanType.Warning, reason); warnCount++; @@ -412,7 +377,7 @@ async Task exec() if (warnCount >= WarningLimit) { await _userService.BanUser(targetUser, true); - await _banRecordService.AddBanRecord(targetUser, dbUser, EBanType.Ban, "90天内受到警告过多, 自动封禁"); + await banRecordService.AddBanRecord(targetUser, dbUser, EBanType.Ban, "90天内受到警告过多, 自动封禁"); sb.AppendLine("90天内受到警告过多, 系统自动封禁该用户"); } @@ -468,7 +433,7 @@ public async Task ResponseQueryBan(Message message, string[] args) if (targetUser == null) { - if (args.Any()) + if (args.Length > 0) { targetUser = await _userService.FetchUserByUserNameOrUserID(args.First()); } @@ -481,7 +446,7 @@ public async Task ResponseQueryBan(Message message, string[] args) else { sb.AppendLine("投稿机器人封禁状态:"); - var records = await _banRecordService.GetBanRecores(targetUser); + var records = await banRecordService.GetBanRecores(targetUser); var status = targetUser.IsBan ? "已封禁" : "正常"; sb.AppendLine($"用户名: {targetUser.HtmlUserLink()}"); @@ -493,7 +458,7 @@ public async Task ResponseQueryBan(Message message, string[] args) { sb.AppendLine("查询封禁/解封记录出错"); } - else if (!records.Any()) + else if (records.Count == 0) { sb.AppendLine("尚未查到封禁/解封记录"); } @@ -534,14 +499,14 @@ public async Task ResponseQueryBan(Message message, string[] args) sb.AppendLine(); sb.AppendLine("频道和群组封禁状态:"); - sb.AppendLine(await _botClient.GetChatMemberStatusAsync(_channelService.AcceptChannel, targetUser.UserID)); - sb.AppendLine(await _botClient.GetChatMemberStatusAsync(_channelService.RejectChannel, targetUser.UserID)); - sb.AppendLine(await _botClient.GetChatMemberStatusAsync(_channelService.CommentGroup, targetUser.UserID)); - sb.AppendLine(await _botClient.GetChatMemberStatusAsync(_channelService.SubGroup, targetUser.UserID)); - if (_channelService.HasSecondChannel) + sb.AppendLine(await _botClient.GetChatMemberStatusAsync(channelService.AcceptChannel, targetUser.UserID)); + sb.AppendLine(await _botClient.GetChatMemberStatusAsync(channelService.RejectChannel, targetUser.UserID)); + sb.AppendLine(await _botClient.GetChatMemberStatusAsync(channelService.CommentGroup, targetUser.UserID)); + sb.AppendLine(await _botClient.GetChatMemberStatusAsync(channelService.SubGroup, targetUser.UserID)); + if (channelService.HasSecondChannel) { - sb.AppendLine(await _botClient.GetChatMemberStatusAsync(_channelService.SecondChannel, targetUser.UserID)); - sb.AppendLine(await _botClient.GetChatMemberStatusAsync(_channelService.SecondCommentGroup, targetUser.UserID)); + sb.AppendLine(await _botClient.GetChatMemberStatusAsync(channelService.SecondChannel, targetUser.UserID)); + sb.AppendLine(await _botClient.GetChatMemberStatusAsync(channelService.SecondCommentGroup, targetUser.UserID)); } } @@ -566,7 +531,7 @@ async Task exec() if (targetUser == null) { - if (args.Any()) + if (args.Length > 0) { targetUser = await _userService.FetchUserByUserNameOrUserID(args.First()); args = args[1..]; @@ -578,7 +543,7 @@ async Task exec() return "找不到指定用户"; } - if (targetUser.Id == _channelService.BotUser.Id) + if (targetUser.Id == channelService.BotUser.Id) { return "你有事?"; } @@ -626,7 +591,7 @@ async Task exec() [TextCmd("QUERYUSER", EUserRights.AdminCmd, Alias = "SEARCHUSER,QUSER", Description = "搜索用户")] public async Task ResponseQueryUser(Users dbUser, Message message, string[] args) { - if (!args.Any()) + if (args.Length == 0) { await _botClient.SendCommandReply("请指定 用户昵称/用户名/用户ID 作为查询参数, 或者使用通配符 * 查找全部用户", message, true); return; @@ -692,7 +657,7 @@ public async Task QResponseQueryUser(Users dbUser, CallbackQuery callbackQuery, [TextCmd("QUERYALLUSER", EUserRights.AdminCmd, Alias = "SEARALLCHUSER,QAUSER", Description = "搜索用户")] public async Task ResponseQueryAllUser(Users dbUser, Message message, string[] args) { - if (!args.Any()) + if (args.Length == 0) { await _botClient.SendCommandReply("请指定 用户昵称/用户名/用户ID 作为查询参数, 或者使用通配符 * 查找全部用户", message, true); return; @@ -776,88 +741,88 @@ public async Task ResponsePostReport(Message message) var monthStart = now.AddDays(1 - now.Day).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second); var yearStart = now.AddMonths(1 - now.Month).AddDays(1 - now.Day).AddHours(-now.Hour).AddMinutes(-now.Minute).AddSeconds(-now.Second); - var second = _channelService.HasSecondChannel; + var second = channelService.HasSecondChannel; var sb = new StringBuilder(); - var todayPost = await _postService.CountAllPosts(today); - var todayAcceptPost = await _postService.CountAcceptedPosts(today); - var todayRejectPost = await _postService.CountRejectedPosts(today); + var todayPost = await postService.CountAllPosts(today); + var todayAcceptPost = await postService.CountAcceptedPosts(today); + var todayRejectPost = await postService.CountRejectedPosts(today); sb.AppendLine("-- 24小时投稿统计 --"); sb.AppendLine($"接受/拒绝: {todayAcceptPost} / {todayRejectPost}"); if (second) { - var todayAcceptSecondPost = await _postService.CountAcceptedSecondPosts(today); + var todayAcceptSecondPost = await postService.CountAcceptedSecondPosts(today); sb.AppendLine($"接受(二频): {todayAcceptSecondPost}"); } sb.AppendLine($"通过率: {(todayPost > 0 ? (100 * todayAcceptPost / todayPost).ToString("f2") : "--")}%"); sb.AppendLine($"累计投稿: {todayPost}"); - var weekPost = await _postService.CountAllPosts(prev7Days); - var weekAcceptPost = await _postService.CountAcceptedPosts(prev7Days); - var weekRejectPost = await _postService.CountRejectedPosts(prev7Days); - var weekExpiredPost = await _postService.CountExpiredPosts(prev7Days); + var weekPost = await postService.CountAllPosts(prev7Days); + var weekAcceptPost = await postService.CountAcceptedPosts(prev7Days); + var weekRejectPost = await postService.CountRejectedPosts(prev7Days); + var weekExpiredPost = await postService.CountExpiredPosts(prev7Days); sb.AppendLine(); sb.AppendLine("-- 7日投稿统计 --"); sb.AppendLine($"接受/拒绝: {weekAcceptPost} / {weekRejectPost}"); if (second) { - var weekAcceptSecondPost = await _postService.CountAcceptedSecondPosts(prev7Days); + var weekAcceptSecondPost = await postService.CountAcceptedSecondPosts(prev7Days); sb.AppendLine($"接受(二频): {weekAcceptSecondPost}"); } sb.AppendLine($"通过率: {(weekPost > 0 ? (100 * weekAcceptPost / weekPost).ToString("f2") : "--")}%"); sb.AppendLine($"过期投稿: {weekExpiredPost}"); sb.AppendLine($"累计投稿: {weekPost + weekExpiredPost}"); - var monthPost = await _postService.CountAllPosts(monthStart); - var monthAcceptPost = await _postService.CountAcceptedPosts(monthStart); - var monthRejectPost = await _postService.CountRejectedPosts(monthStart); - var monthExpiredPost = await _postService.CountExpiredPosts(monthStart); + var monthPost = await postService.CountAllPosts(monthStart); + var monthAcceptPost = await postService.CountAcceptedPosts(monthStart); + var monthRejectPost = await postService.CountRejectedPosts(monthStart); + var monthExpiredPost = await postService.CountExpiredPosts(monthStart); sb.AppendLine(); sb.AppendLine($"-- {monthStart.ToString("MM")}月投稿统计 --"); sb.AppendLine($"接受/拒绝: {monthAcceptPost} / {monthRejectPost}"); if (second) { - var monthAcceptSecondPost = await _postService.CountAcceptedSecondPosts(monthStart); + var monthAcceptSecondPost = await postService.CountAcceptedSecondPosts(monthStart); sb.AppendLine($"接受(二频): {monthAcceptSecondPost}"); } sb.AppendLine($"通过率: {(monthPost > 0 ? (100 * monthAcceptPost / monthPost).ToString("f2") : "--")}%"); sb.AppendLine($"过期投稿: {monthExpiredPost}"); sb.AppendLine($"累计投稿: {monthPost}"); - var yearPost = await _postService.CountAllPosts(yearStart); - var yearAcceptPost = await _postService.CountAcceptedPosts(yearStart); - var yearRejectPost = await _postService.CountRejectedPosts(yearStart); - var yearExpiredPost = await _postService.CountExpiredPosts(yearStart); + var yearPost = await postService.CountAllPosts(yearStart); + var yearAcceptPost = await postService.CountAcceptedPosts(yearStart); + var yearRejectPost = await postService.CountRejectedPosts(yearStart); + var yearExpiredPost = await postService.CountExpiredPosts(yearStart); sb.AppendLine(); sb.AppendLine($"-- {yearStart.ToString("yyyy")}年投稿统计 --"); sb.AppendLine($"接受/拒绝: {yearAcceptPost} / {yearRejectPost}"); if (second) { - var yearAcceptSecondPost = await _postService.CountAcceptedSecondPosts(yearStart); + var yearAcceptSecondPost = await postService.CountAcceptedSecondPosts(yearStart); sb.AppendLine($"接受(二频): {yearAcceptSecondPost}"); } sb.AppendLine($"通过率: {(yearPost > 0 ? (100 * yearAcceptPost / yearPost).ToString("f2") : "--")}%"); sb.AppendLine($"过期投稿: {yearExpiredPost}"); sb.AppendLine($"累计投稿: {yearPost}"); - var totalPost = await _postService.CountAllPosts(); - var totalAcceptPost = await _postService.CountAcceptedPosts(); - var totalRejectPost = await _postService.CountRejectedPosts(); - var totalExpiredPost = await _postService.CountExpiredPosts(); - var totalChannel = await _channelOptionService.ChannelCount(); - var totalAttachment = await _attachmentService.GetAttachmentCount(); + var totalPost = await postService.CountAllPosts(); + var totalAcceptPost = await postService.CountAcceptedPosts(); + var totalRejectPost = await postService.CountRejectedPosts(); + var totalExpiredPost = await postService.CountExpiredPosts(); + var totalChannel = await channelOptionService.ChannelCount(); + var totalAttachment = await attachmentService.GetAttachmentCount(); sb.AppendLine(); sb.AppendLine("-- 历史投稿统计 --"); sb.AppendLine($"接受/拒绝: {totalAcceptPost} / {totalRejectPost}"); if (second) { - var totalAcceptSecondPost = await _postService.CountAcceptedSecondPosts(); + var totalAcceptSecondPost = await postService.CountAcceptedSecondPosts(); sb.AppendLine($"接受(二频): {totalAcceptSecondPost}"); } sb.AppendLine($"通过率: {(totalPost > 0 ? (100 * totalAcceptPost / totalPost).ToString("f2") : "--")}%"); @@ -908,9 +873,9 @@ public async Task ResponseSystemReport(Message message) sb.AppendLine($"运行时间: {day}{hours:F8} 小时"); var today = DateTime.Now.AddHours(-24); - var cmdCount = await _cmdRecordService.GetTextCmdCount(today); - var QueryCount = await _cmdRecordService.GetQueryCmdCount(today); - var errorCount = await _cmdRecordService.GetErrorCmdCount(today); + var cmdCount = await cmdRecordService.GetTextCmdCount(today); + var QueryCount = await cmdRecordService.GetQueryCmdCount(today); + var errorCount = await cmdRecordService.GetErrorCmdCount(today); sb.AppendLine(); sb.AppendLine("-- 调用统计 --"); @@ -922,7 +887,7 @@ public async Task ResponseSystemReport(Message message) sb.AppendLine("-- 硬盘信息 --"); var drives = DriveInfo.GetDrives(); - string[] sizes = new[] { " B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB" }; + var sizes = new[] { " B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB" }; foreach (var drive in drives) { @@ -960,7 +925,7 @@ public async Task ResponseSystemReport(Message message) [TextCmd("INVITE", EUserRights.AdminCmd, Description = "创建审核群的邀请链接")] public async Task ResponseInviteToReviewGroup(Users dbUser, Message message) { - if (_channelService.ReviewGroup.Id == -1) + if (channelService.ReviewGroup.Id == -1) { await _botClient.SendCommandReply("尚未设置审核群, 无法完成此操作", message); return; @@ -974,11 +939,11 @@ public async Task ResponseInviteToReviewGroup(Users dbUser, Message message) try { - var inviteLink = await _botClient.CreateChatInviteLinkAsync(_channelService.ReviewGroup.Id, $"{dbUser} 创建的邀请链接", DateTime.Now.AddHours(1), 1, false); + var inviteLink = await _botClient.CreateChatInviteLinkAsync(channelService.ReviewGroup.Id, $"{dbUser} 创建的邀请链接", DateTime.Now.AddHours(1), 1, false); var sb = new StringBuilder(); - sb.AppendLine($"创建 {_channelService.ReviewGroup.Title} 的邀请链接成功, 一小时内有效, 仅限1人使用"); + sb.AppendLine($"创建 {channelService.ReviewGroup.Title} 的邀请链接成功, 一小时内有效, 仅限1人使用"); sb.AppendLine($"{(inviteLink.Name ?? inviteLink.InviteLink).EscapeHtml()}"); @@ -1073,7 +1038,7 @@ public async Task SetUserGroup(Users dbUser, Message message, string[] args) if (targetUser == null) { - if (args.Any()) + if (args.Length > 0) { targetUser = await _userService.FetchUserByUserNameOrUserID(args.First()); } @@ -1089,7 +1054,7 @@ public async Task SetUserGroup(Users dbUser, Message message, string[] args) return ("该用户已被封禁, 无法执行此操作", null); } - if (targetUser.Id == _channelService.BotUser.Id) + if (targetUser.Id == channelService.BotUser.Id) { return ("你有事?", null); } @@ -1104,8 +1069,8 @@ public async Task SetUserGroup(Users dbUser, Message message, string[] args) return ("无法对同级管理员进行此操作", null); } - var keyboard = await _markupHelperService.SetUserGroupKeyboard(dbUser, targetUser); - var groupName = _groupRepository.GetGroupById(targetUser.GroupID)?.Name ?? "未知"; + var keyboard = await markupHelperService.SetUserGroupKeyboard(dbUser, targetUser); + var groupName = groupRepository.GetGroupById(targetUser.GroupID)?.Name ?? "未知"; return (keyboard != null ? $"请选择 {targetUser.EscapedFullName()} 的新用户组, 当前用户组 {groupName}" : "获取可用用户组失败", keyboard); } @@ -1138,7 +1103,7 @@ async Task exec() return "找不到指定用户"; } - if (targetUser.Id == _channelService.BotUser.Id) + if (targetUser.Id == channelService.BotUser.Id) { return "你有事?"; } @@ -1155,7 +1120,7 @@ async Task exec() if (int.TryParse(args[2], out int groupID)) { - var group = _groupRepository.GetGroupById(groupID); + var group = groupRepository.GetGroupById(groupID); if (group != null) { await _userService.UpdateUserGroupId(targetUser, groupID); @@ -1250,7 +1215,7 @@ public async Task ResponseNuke(Users dbUser, Message message, string[] args) if (targetUser == null) { - if (args.Any()) + if (args.Length > 0) { targetUser = await _userService.FetchUserByUserNameOrUserID(args.First()); args = args[1..]; @@ -1278,7 +1243,7 @@ public async Task ResponseNuke(Users dbUser, Message message, string[] args) return (null, "请指定NUKE理由"); } - int warnCount = await _banRecordService.GetWarnCount(targetUser); + int warnCount = await banRecordService.GetWarnCount(targetUser); var sb = new StringBuilder(); sb.AppendLine($"用户名: {targetUser.HtmlUserLink()}"); @@ -1288,7 +1253,7 @@ public async Task ResponseNuke(Users dbUser, Message message, string[] args) sb.AppendLine($"累计警告 {warnCount} / {WarningLimit} 次"); sb.AppendLine("请选择 NUKE 操作"); - return (_markupHelperService.NukeMenuKeyboard(dbUser, targetUser, reason), sb.ToString()); + return (markupHelperService.NukeMenuKeyboard(dbUser, targetUser, reason), sb.ToString()); } var (keyboard, text) = await exec(); @@ -1340,18 +1305,18 @@ public async Task QResponseNuke(Users dbUser, CallbackQuery callbackQuery, strin }; try { - await _botClient.RestrictChatMemberAsync(_channelService.SubGroup, targetUser.UserID, permission); + await _botClient.RestrictChatMemberAsync(channelService.SubGroup, targetUser.UserID, permission); } catch { } - await _botClient.RestrictChatMemberAsync(_channelService.SubGroup, targetUser.UserID, permission); + await _botClient.RestrictChatMemberAsync(channelService.SubGroup, targetUser.UserID, permission); } break; case "ban": - await _botClient.BanChatMemberAsync(_channelService.SubGroup, targetUser.UserID); - await _botClient.BanChatMemberAsync(_channelService.CommentGroup, targetUser.UserID); + await _botClient.BanChatMemberAsync(channelService.SubGroup, targetUser.UserID); + await _botClient.BanChatMemberAsync(channelService.CommentGroup, targetUser.UserID); break; case "unmute": { @@ -1366,13 +1331,13 @@ public async Task QResponseNuke(Users dbUser, CallbackQuery callbackQuery, strin CanSendPolls = false, CanSendOtherMessages = false, }; - await _botClient.RestrictChatMemberAsync(_channelService.SubGroup, targetUser.UserID, permission); - await _botClient.RestrictChatMemberAsync(_channelService.SubGroup, targetUser.UserID, permission); + await _botClient.RestrictChatMemberAsync(channelService.SubGroup, targetUser.UserID, permission); + await _botClient.RestrictChatMemberAsync(channelService.SubGroup, targetUser.UserID, permission); } break; case "unban": - await _botClient.UnbanChatMemberAsync(_channelService.SubGroup, targetUser.UserID); - await _botClient.UnbanChatMemberAsync(_channelService.CommentGroup, targetUser.UserID); + await _botClient.UnbanChatMemberAsync(channelService.SubGroup, targetUser.UserID); + await _botClient.UnbanChatMemberAsync(channelService.CommentGroup, targetUser.UserID); break; default: await _botClient.AutoReplyAsync("参数有误", callbackQuery, true); @@ -1398,7 +1363,7 @@ public async Task QResponseNuke(Users dbUser, CallbackQuery callbackQuery, strin string reason = string.Join(' ', args[3..]); - await _banRecordService.AddBanRecord(targetUser, dbUser, banType, reason); + await banRecordService.AddBanRecord(targetUser, dbUser, banType, reason); try { @@ -1438,7 +1403,7 @@ public async Task ResponseToken(Users dbUser, Message message) } else { - var token = await _userTokenService.GenerateNewUserToken(dbUser); + var token = await userTokenService.GenerateNewUserToken(dbUser); await _botClient.SendCommandReply(token.APIToken.ToString(), message, false); } } @@ -1464,7 +1429,7 @@ async Task exec() if (int.TryParse(args[1], out int postId)) { - post = await _postService.GetPostByPostId(postId); + post = await postService.GetPostByPostId(postId); } if (post == null) @@ -1477,13 +1442,13 @@ async Task exec() return "稿件可能已被撤回"; } - var chat = post.Status == EPostStatus.Accepted ? _channelService.AcceptChannel : _channelService.SecondChannel; + var chat = post.Status == EPostStatus.Accepted ? channelService.AcceptChannel : channelService.SecondChannel; if (chat == null) { return "第二频道未设定"; } - await _postService.RevocationPost(post); + await postService.RevocationPost(post); if (post.WarnTextID != -1 && post.WarnTextID != 0) { @@ -1499,9 +1464,9 @@ async Task exec() if (post.IsMediaGroup) { - var mediaGroups = await _mediaGroupService.QueryMediaGroup(post.PublishMediaGroupID); + var mediaGroups = await mediaGroupService.QueryMediaGroup(post.PublishMediaGroupID); int error = 0; - if (!mediaGroups.Any()) + if (mediaGroups.Count == 0) { return "找不到媒体组信息"; } @@ -1604,11 +1569,11 @@ public async Task QResponseGotoLatest(Users dbUser, CallbackQuery callbackQuery) return; } - var post = await _postService.GetLatestReviewingPostLink(); + var post = await postService.GetLatestReviewingPostLink(); if (post != null) { var chatId = Math.Abs(post.ReviewChatID + 1000000000000); - var link = _textHelperService.HtmlMessageLink(post.ReviewMsgID, $"c/{chatId}", $"前往投稿{post.Id}"); + var link = textHelperService.HtmlMessageLink(post.ReviewMsgID, $"c/{chatId}", $"前往投稿{post.Id}"); try { await _botClient.SendTextMessageAsync(dbUser.PrivateChatID, link, parseMode: ParseMode.Html); @@ -1635,7 +1600,7 @@ async Task exec() if (targetUser == null) { - if (args.Any()) + if (args.Length > 0) { targetUser = await _userService.FetchUserByUserNameOrUserID(args.First()); } @@ -1646,14 +1611,14 @@ async Task exec() return "找不到指定用户"; } - if (targetUser.Id == _channelService.BotUser.Id) + if (targetUser.Id == channelService.BotUser.Id) { return "无法查询当前机器人的发言"; } - var dialogs = await _dialogueService.FetchUserGroupMessages(targetUser, 0, 30); + var dialogs = await dialogueService.FetchUserGroupMessages(targetUser, 0, 30); - if (!dialogs.Any()) + if (dialogs.Count == 0) { return $"没有用户 {targetUser.EscapedFullName()} 的群聊发言记录"; } diff --git a/XinjingdailyBot.Command/CommonCommand.cs b/XinjingdailyBot.Command/CommonCommand.cs index a6da066a..0ce2d2f3 100644 --- a/XinjingdailyBot.Command/CommonCommand.cs +++ b/XinjingdailyBot.Command/CommonCommand.cs @@ -19,30 +19,15 @@ namespace XinjingdailyBot.Command; /// 通用命令 /// [AppService(LifeTime.Scoped)] -internal class CommonCommand +internal class CommonCommand( + ITelegramBotClient _botClient, + IOptions _configuration, + IBanRecordService _banRecordService, + ITextHelperService _textHelperService, + ICommandHandler _commandHandler, + IChannelService _channelService) { - private readonly ITelegramBotClient _botClient; - private readonly OptionsSetting _optionsSetting; - private readonly IBanRecordService _banRecordService; - private readonly ITextHelperService _textHelperService; - private readonly ICommandHandler _commandHandler; - private readonly IChannelService _channelService; - - public CommonCommand( - ITelegramBotClient botClient, - IOptions options, - IBanRecordService banRecordService, - ITextHelperService textHelperService, - ICommandHandler commandHandler, - IChannelService channelService) - { - _botClient = botClient; - _optionsSetting = options.Value; - _banRecordService = banRecordService; - _textHelperService = textHelperService; - _commandHandler = commandHandler; - _channelService = channelService; - } + private readonly OptionsSetting _optionsSetting = _configuration.Value; /// private readonly int WarnDuration = IBanRecordService.WarnDuration; @@ -163,7 +148,7 @@ public async Task ResponseMyBan(Users dbUser, Message message) { sb.AppendLine("查询封禁/解封记录出错"); } - else if (!records.Any()) + else if (records.Count == 0) { sb.AppendLine("尚未查到封禁/解封/警告记录"); } diff --git a/XinjingdailyBot.Command/NormalCommand.cs b/XinjingdailyBot.Command/NormalCommand.cs index c068fd56..14294f28 100644 --- a/XinjingdailyBot.Command/NormalCommand.cs +++ b/XinjingdailyBot.Command/NormalCommand.cs @@ -19,42 +19,18 @@ namespace XinjingdailyBot.Command; /// 通用命令 /// [AppService(LifeTime.Scoped)] -internal class NormalCommand +internal class NormalCommand( + ILogger _logger, + ITelegramBotClient _botClient, + IUserService _userService, + GroupRepository _groupRepository, + IMarkupHelperService _markupHelperService, + IAttachmentService _attachmentService, + IPostService _postService, + TagRepository _tagRepository, + IHttpHelperService _httpHelperService, + IMediaGroupService _mediaGroupService) { - private readonly ILogger _logger; - private readonly ITelegramBotClient _botClient; - private readonly IUserService _userService; - private readonly GroupRepository _groupRepository; - private readonly IMarkupHelperService _markupHelperService; - private readonly IAttachmentService _attachmentService; - private readonly IPostService _postService; - private readonly TagRepository _tagRepository; - private readonly IHttpHelperService _httpHelperService; - private readonly IMediaGroupService _mediaGroupService; - - public NormalCommand( - ILogger logger, - ITelegramBotClient botClient, - IUserService userService, - GroupRepository groupRepository, - IMarkupHelperService markupHelperService, - IAttachmentService attachmentService, - IPostService postService, - TagRepository tagRepository, - IHttpHelperService httpHelperService, - IMediaGroupService mediaGroupService) - { - _logger = logger; - _botClient = botClient; - _userService = userService; - _groupRepository = groupRepository; - _markupHelperService = markupHelperService; - _attachmentService = attachmentService; - _postService = postService; - _tagRepository = tagRepository; - _httpHelperService = httpHelperService; - _mediaGroupService = mediaGroupService; - } /// /// 检测机器人是否存活 diff --git a/XinjingdailyBot.Command/ObsoleteCommand.cs b/XinjingdailyBot.Command/ObsoleteCommand.cs new file mode 100644 index 00000000..8786d124 --- /dev/null +++ b/XinjingdailyBot.Command/ObsoleteCommand.cs @@ -0,0 +1,425 @@ +using Microsoft.Extensions.Logging; +using System.IO.Compression; +using System.Text; +using Telegram.Bot; +using Telegram.Bot.Types; +using Telegram.Bot.Types.Enums; +using XinjingdailyBot.Infrastructure; +using XinjingdailyBot.Infrastructure.Attribute; +using XinjingdailyBot.Infrastructure.Enums; +using XinjingdailyBot.Infrastructure.Extensions; +using XinjingdailyBot.Interface.Bot.Common; +using XinjingdailyBot.Interface.Data; +using XinjingdailyBot.Interface.Helper; +using XinjingdailyBot.Model.Models; +using XinjingdailyBot.Repository; + +namespace XinjingdailyBot.Command; + +/// +/// 超级管理员命令 +/// +[Obsolete("迁移使用")] +[AppService(LifeTime.Scoped)] +internal class ObsoleteCommand( + ILogger _logger, + ITelegramBotClient _botClient, + IPostService _postService, + OldPostRepository _oldPostService, + IChannelOptionService _channelOptionService, + IChannelService _channelService, + IHttpHelperService _httpHelperService, + ITextHelperService _textHelperService) +{ + /// + /// 迁移旧的稿件数据 + /// + /// + /// + [TextCmd("MERGEPOSTTAG", EUserRights.SuperCmd, Description = "迁移旧的稿件标签数据")] + [Obsolete("迁移旧数据用")] + public async Task ResponseMergePostTag(Message message) + { + const int threads = 30; + + int startId = 1; + int effectCount = 0; + + int totalPosts = await _oldPostService.Queryable().CountAsync(); + + var msg = await _botClient.SendCommandReply($"开始更新稿件表, 共计 {totalPosts} 条记录", message, autoDelete: false); + + while (startId <= totalPosts) + { + var oldOosts = await _oldPostService.Queryable().Where(x => x.Id >= startId && x.Tags != EBuildInTags.None).Take(threads).ToListAsync(); + if (oldOosts.Count == 0) + { + break; + } + + var tasks = oldOosts.Select(async oldPost => { + if (oldPost.Tags != EBuildInTags.None) + { + var oldTag = oldPost.Tags; + if (oldTag.HasFlag(EBuildInTags.Spoiler)) + { + oldPost.HasSpoiler = true; + } + int newTag = 0; + if (oldTag.HasFlag(EBuildInTags.NSFW)) + { + newTag += 1; + } + if (oldTag.HasFlag(EBuildInTags.Friend)) + { + newTag += 2; + } + if (oldTag.HasFlag(EBuildInTags.WanAn)) + { + newTag += 4; + } + if (oldTag.HasFlag(EBuildInTags.AIGraph)) + { + newTag += 8; + } + oldPost.Tags = EBuildInTags.None; + oldPost.NewTags = newTag; + oldPost.ModifyAt = DateTime.Now; + + effectCount++; + + await _oldPostService.Updateable(oldPost).UpdateColumns(static x => new { + x.Tags, + x.NewTags, + x.ModifyAt + }).ExecuteCommandAsync(); + } + }).ToList(); + + await Task.WhenAll(tasks); + + startId = oldOosts.Last().Id + 1; + + _logger.LogInformation("更新进度 {startId} / {totalUsers}, 更新数量 {effectCount}", startId, totalPosts, effectCount); + } + + try + { + await _botClient.EditMessageTextAsync(msg, $"更新稿件表完成, 更新了 {effectCount} 条记录"); + } + catch + { + await _botClient.SendCommandReply($"更新稿件表完成, 更新了 {effectCount} 条记录", message, autoDelete: false); + } + } + + /// + /// 迁移旧的稿件数据 + /// + /// + /// + [TextCmd("MERGEPOST", EUserRights.SuperCmd, Description = "迁移旧的稿件数据")] + [Obsolete("迁移旧数据用")] + public async Task ResponseMergePost(Message message) + { + const int threads = 30; + + int startId = 1; + int effectCount = 0; + + int totalPosts = await _oldPostService.Queryable().CountAsync(x => !x.Merged); + var msg = await _botClient.SendCommandReply($"开始迁移稿件表, 共计 {totalPosts} 条记录", message, autoDelete: false); + + while (startId <= totalPosts) + { + var oldPosts = await _oldPostService.Queryable().Where(x => x.Id >= startId && !x.Merged).Take(threads).ToListAsync(); + if (oldPosts.Count == 0) + { + break; + } + + var tasks = oldPosts.Select(async oldPost => { + + long channelId = -1, channelMsgId = -1; + if (oldPost.IsFromChannel) + { + ChannelOptions? channel = null; + + var name = oldPost.ChannelName; + var title = oldPost.ChannelTitle; + + if (name.EndsWith('~')) + { + name = name[..^1]; + } + + var text = name.Split('/'); + if (text.Length >= 2) + { + if (!long.TryParse(text[1], out channelMsgId)) + { + channelMsgId = -1; + } + channel = await _channelOptionService.FetchChannelByNameOrTitle(text[0], title); + } + else + { + channel = await _channelOptionService.FetchChannelByNameOrTitle(name, title); + } + + if (channel != null) + { + channelId = channel.ChannelID; + } + } + + string reason = oldPost.Reason switch { + ERejectReason.Fuzzy => "模糊", + ERejectReason.Duplicate => "重复", + ERejectReason.Boring => "无趣", + ERejectReason.Confused => "没懂", + ERejectReason.Deny => "内容不合适", + ERejectReason.QRCode => "广告水印", + ERejectReason.Other => "其他原因", + ERejectReason.CustomReason => "自定义拒绝理由", + ERejectReason.AutoReject => "稿件审核超时", + _ => "", + }; + + bool countReject = oldPost.Status == EPostStatus.Rejected && (oldPost.Reason != ERejectReason.Fuzzy && oldPost.Reason != ERejectReason.Duplicate); + + var post = new NewPosts { + Id = oldPost.Id, + OriginChatID = oldPost.OriginChatID, + OriginMsgID = oldPost.OriginMsgID, + OriginActionChatID = oldPost.OriginChatID, + OriginActionMsgID = oldPost.ActionMsgID, + PublicMsgID = oldPost.PublicMsgID, + Anonymous = oldPost.Anonymous, + Text = oldPost.Text, + RawText = oldPost.RawText, + ChannelID = channelId, + ChannelMsgID = channelMsgId, + Status = oldPost.Status, + PostType = oldPost.PostType, + OriginMediaGroupID = "", + ReviewMediaGroupID = "", + PublishMediaGroupID = "", + Tags = oldPost.NewTags, + HasSpoiler = oldPost.HasSpoiler, + RejectReason = reason, + CountReject = countReject, + PosterUID = oldPost.PosterUID, + ReviewerUID = oldPost.ReviewerUID, + CreateAt = oldPost.CreateAt, + }; + + if (oldPost.IsDirectPost) + { + post.ReviewChatID = oldPost.OriginChatID; + post.ReviewMsgID = oldPost.OriginMsgID; + post.ReviewActionChatID = oldPost.OriginChatID; + post.ReviewActionMsgID = oldPost.ActionMsgID; + } + else + { + post.ReviewChatID = _channelService.ReviewGroup.Id; + post.ReviewMsgID = oldPost.ReviewMsgID; + post.ReviewActionChatID = _channelService.ReviewGroup.Id; + post.ReviewActionMsgID = oldPost.ManageMsgID; + } + + effectCount++; + + post.ModifyAt = DateTime.Now; + + try + { + await _postService.Insertable(post).OffIdentity().ExecuteCommandAsync(); + } + catch (Exception) + { + _logger.LogWarning("稿件Id {id} 已存在", oldPost.Id); + await _postService.Updateable(post).ExecuteCommandAsync(); + } + + oldPost.Merged = true; + await _oldPostService.Updateable(oldPost).UpdateColumns(static x => new { x.Merged }).ExecuteCommandAsync(); + + }).ToList(); + + await Task.WhenAll(tasks); + + startId = oldPosts.Last().Id + 1; + + _logger.LogInformation("迁移进度 {startId} / {totalUsers}, 更新数量 {effectCount}", startId, totalPosts, effectCount); + } + + try + { + await _botClient.EditMessageTextAsync(msg, $"迁移稿件表完成, 更新了 {effectCount} 条记录"); + } + catch + { + await _botClient.SendCommandReply($"迁移稿件表完成, 更新了 {effectCount} 条记录", message, autoDelete: false); + } + } + + /// + /// 修补稿件数据 + /// + /// + /// + [TextCmd("FIXPOST", EUserRights.SuperCmd, Description = "修补稿件数据")] + [Obsolete("过时方法")] + public async Task ResponseFixPost(Message message) + { + const int threads = 30; + + int startId = 1; + int effectCount = 0; + + int totalPosts = await _postService.Queryable().CountAsync(x => x.ReviewActionChatID == x.ReviewActionMsgID); + var msg = await _botClient.SendCommandReply($"开始修补稿件表, 共计 {totalPosts} 条记录", message, autoDelete: false); + + while (startId <= totalPosts) + { + var posts = await _postService.Queryable().Where(x => x.Id >= startId && + x.ReviewActionChatID == x.ReviewActionMsgID + ).Take(threads).ToListAsync(); + + if (posts.Count == 0) + { + break; + } + + var tasks = posts.Select(async post => { + effectCount++; + + post.ReviewActionChatID = post.ReviewChatID; + post.ModifyAt = DateTime.Now; + + await _postService.Updateable(post).UpdateColumns(static x => new { x.ReviewActionChatID, x.ModifyAt }).ExecuteCommandAsync(); + + }).ToList(); + + await Task.WhenAll(tasks); + + startId = posts.Last().Id + 1; + + _logger.LogInformation("迁移进度 {startId} / {totalUsers}, 更新数量 {effectCount}", startId, totalPosts, effectCount); + } + + try + { + await _botClient.EditMessageTextAsync(msg, $"修补稿件表完成, 更新了 {effectCount} 条记录"); + } + catch + { + await _botClient.SendCommandReply($"修补稿件表完成, 更新了 {effectCount} 条记录", message, autoDelete: false); + } + } + + /// + /// 自动升级机器人 + /// + /// + /// + [TextCmd("UPDATE", EUserRights.SuperCmd, Description = "自动升级机器人")] + public async Task ResponseUpdate(Message message) + { + async Task exec() + { + if (!BuildInfo.CanUpdate) + { + return "当前版本不支持自动升级"; + } + + var releaseResponse = await _httpHelperService.GetLatestRelease(); + + if (releaseResponse == null) + { + return "读取在线版本信息失败"; + } + + if (Utils.Version == releaseResponse.TagName) + { + return string.Format("当前已经是最新版本 {0}", Utils.Version); + } + + string varint = BuildInfo.Variant; + string? downloadUrl = null; + + foreach (var asset in releaseResponse.Assets) + { + if (asset.Name.Contains(varint)) + { + downloadUrl = asset.DownloadUrl; + break; + } + } + + if (string.IsNullOrEmpty(downloadUrl) && releaseResponse.Assets.Count != 0) + { + return "自动更新失败, 找不到适配的更新包"; + } + + var bs = await _httpHelperService.DownloadRelease(downloadUrl).ConfigureAwait(false); + + if (bs == null) + { + return "自动更新失败, 下载更新包失败"; + } + + try + { + await using (bs.ConfigureAwait(false)) + { + using var zipArchive = new ZipArchive(bs); + + string currentPath = Utils.ExeFullPath; + string backupPath = Utils.BackupFullPath; + + System.IO.File.Move(currentPath, backupPath, true); + + int count = 0; + foreach (var entry in zipArchive.Entries) + { + if (entry.FullName.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) + || entry.FullName.Equals(Utils.ExeFileName, StringComparison.OrdinalIgnoreCase)) + { + entry.ExtractToFile(currentPath); + count++; + } + } + + if (count > 0) + { + var sb = new StringBuilder(); + sb.AppendLine(string.Format("自动更新成功, 更新了{0}个文件", count)); + sb.AppendLine(string.Format("版本变动: {0} -> {1}", Utils.Version, releaseResponse.TagName)); + sb.AppendLine(); + sb.AppendLine("发行版日志:"); + sb.AppendLine(string.Format("{0}", releaseResponse.Body)); + sb.AppendLine(); + sb.AppendLine(_textHelperService.HtmlLink(releaseResponse.Url, "在线查看")); + return sb.ToString(); + } + else + { + System.IO.File.Move(backupPath, currentPath); + return "自动更新失败, 无文件变动"; + } + } + } + catch (Exception ex) + { + _logger.LogError(ex, "自动更新失败, 解压遇到问题"); + return "自动更新失败, 解压遇到问题"; + } + } + + string text = await exec(); + await _botClient.SendCommandReply(text, message, false, ParseMode.Html); + } +} diff --git a/XinjingdailyBot.Command/PostCommand.cs b/XinjingdailyBot.Command/PostCommand.cs index 72b255eb..743039b7 100644 --- a/XinjingdailyBot.Command/PostCommand.cs +++ b/XinjingdailyBot.Command/PostCommand.cs @@ -16,36 +16,16 @@ namespace XinjingdailyBot.Command; /// 投稿命令 /// [AppService(LifeTime.Scoped)] -internal class PostCommand +internal class PostCommand( + ITelegramBotClient _botClient, + IUserService _userService, + IChannelService _channelService, + IPostService _postService, + IMarkupHelperService _markupHelperService, + IAttachmentService _attachmentService, + ITextHelperService _textHelperService, + IMediaGroupService _mediaGroupService) { - private readonly ITelegramBotClient _botClient; - private readonly IUserService _userService; - private readonly IChannelService _channelService; - private readonly IPostService _postService; - private readonly IMarkupHelperService _markupHelperService; - private readonly IAttachmentService _attachmentService; - private readonly ITextHelperService _textHelperService; - private readonly IMediaGroupService _mediaGroupService; - - public PostCommand( - ITelegramBotClient botClient, - IUserService userService, - IChannelService channelService, - IPostService postService, - IMarkupHelperService markupHelperService, - IAttachmentService attachmentService, - ITextHelperService textHelperService, - IMediaGroupService mediaGroupService) - { - _botClient = botClient; - _userService = userService; - _channelService = channelService; - _postService = postService; - _markupHelperService = markupHelperService; - _attachmentService = attachmentService; - _textHelperService = textHelperService; - _mediaGroupService = mediaGroupService; - } /// /// 投稿消息处理 diff --git a/XinjingdailyBot.Command/ReviewCommand.cs b/XinjingdailyBot.Command/ReviewCommand.cs index 7596cb3c..6be76ab7 100644 --- a/XinjingdailyBot.Command/ReviewCommand.cs +++ b/XinjingdailyBot.Command/ReviewCommand.cs @@ -17,33 +17,15 @@ namespace XinjingdailyBot.Command; /// 审核命令 /// [AppService(LifeTime.Scoped)] -internal class ReviewCommand +internal class ReviewCommand( + ITelegramBotClient _botClient, + IUserService _userService, + IChannelService _channelService, + IPostService _postService, + IMarkupHelperService _markupHelperService, + RejectReasonRepository _rejectReasonRepository, + ITextHelperService _textHelperService) { - private readonly ITelegramBotClient _botClient; - private readonly IUserService _userService; - private readonly IChannelService _channelService; - private readonly IPostService _postService; - private readonly IMarkupHelperService _markupHelperService; - private readonly RejectReasonRepository _rejectReasonRepository; - private readonly ITextHelperService _textHelperService; - - public ReviewCommand( - ITelegramBotClient botClient, - IUserService userService, - IChannelService channelService, - IPostService postService, - IMarkupHelperService markupHelperService, - RejectReasonRepository rejectReasonRepository, - ITextHelperService textHelperService) - { - _botClient = botClient; - _userService = userService; - _channelService = channelService; - _postService = postService; - _markupHelperService = markupHelperService; - _rejectReasonRepository = rejectReasonRepository; - _textHelperService = textHelperService; - } /// /// 自定义拒绝稿件理由 diff --git a/XinjingdailyBot.Command/SuperCommand.cs b/XinjingdailyBot.Command/SuperCommand.cs index e8e7ab1f..a8f1217d 100644 --- a/XinjingdailyBot.Command/SuperCommand.cs +++ b/XinjingdailyBot.Command/SuperCommand.cs @@ -15,7 +15,6 @@ using XinjingdailyBot.Interface.Data; using XinjingdailyBot.Interface.Helper; using XinjingdailyBot.Model.Models; -using XinjingdailyBot.Repository; namespace XinjingdailyBot.Command; @@ -23,51 +22,19 @@ namespace XinjingdailyBot.Command; /// 超级管理员命令 /// [AppService(LifeTime.Scoped)] -internal class SuperCommand +internal class SuperCommand( + ILogger _logger, + ITelegramBotClient _botClient, + IPostService _postService, + IChannelOptionService _channelOptionService, + IChannelService _channelService, + IMarkupHelperService _markupHelperService, + ICommandHandler _commandHandler, + IUserService _userService, + IHttpHelperService _httpHelperService, + ITextHelperService _textHelperService, + IAdvertiseService _advertiseService) { - private readonly ILogger _logger; - private readonly ITelegramBotClient _botClient; - private readonly IPostService _postService; - [Obsolete("迁移使用")] - private readonly OldPostRepository _oldPostService; - private readonly IChannelOptionService _channelOptionService; - private readonly IChannelService _channelService; - private readonly IMarkupHelperService _markupHelperService; - private readonly ICommandHandler _commandHandler; - private readonly IUserService _userService; - private readonly IHttpHelperService _httpHelperService; - private readonly ITextHelperService _textHelperService; - private readonly IAdvertiseService _advertiseService; - - [Obsolete("迁移使用")] - public SuperCommand( - ILogger logger, - ITelegramBotClient botClient, - IPostService postService, - OldPostRepository oldPostService, - IChannelOptionService channelOptionService, - IChannelService channelService, - IMarkupHelperService markupHelperService, - ICommandHandler commandHandler, - IUserService userService, - IHttpHelperService httpHelperService, - ITextHelperService textHelperService, - IAdvertiseService advertiseService) - { - _logger = logger; - _botClient = botClient; - _postService = postService; - _oldPostService = oldPostService; - _channelOptionService = channelOptionService; - _channelService = channelService; - _markupHelperService = markupHelperService; - _commandHandler = commandHandler; - _userService = userService; - _httpHelperService = httpHelperService; - _textHelperService = textHelperService; - _advertiseService = advertiseService; - } - /// /// 重启机器人 /// @@ -238,7 +205,6 @@ public async Task ResponseClearCommand(Message message) /// /// [TextCmd("RECALCPOST", EUserRights.SuperCmd, Description = "重新计算用户投稿数量")] - [Obsolete("过时方法")] public async Task ResponseReCalcPost(Message message) { const int threads = 10; @@ -253,7 +219,7 @@ public async Task ResponseReCalcPost(Message message) while (startId <= totalUsers) { var users = await _userService.GetUserListAfterId(startId, threads); - if (!users.Any()) + if (users.Count == 0) { break; } @@ -296,295 +262,6 @@ public async Task ResponseReCalcPost(Message message) } } - /// - /// 迁移旧的稿件数据 - /// - /// - /// - [TextCmd("MERGEPOSTTAG", EUserRights.SuperCmd, Description = "迁移旧的稿件标签数据")] - [Obsolete("迁移旧数据用")] - public async Task ResponseMergePostTag(Message message) - { - const int threads = 30; - - int startId = 1; - int effectCount = 0; - - int totalPosts = await _oldPostService.Queryable().CountAsync(); - - var msg = await _botClient.SendCommandReply($"开始更新稿件表, 共计 {totalPosts} 条记录", message, autoDelete: false); - - while (startId <= totalPosts) - { - var oldOosts = await _oldPostService.Queryable().Where(x => x.Id >= startId && x.Tags != EBuildInTags.None).Take(threads).ToListAsync(); - if (!oldOosts.Any()) - { - break; - } - - var tasks = oldOosts.Select(async oldPost => { - if (oldPost.Tags != EBuildInTags.None) - { - var oldTag = oldPost.Tags; - if (oldTag.HasFlag(EBuildInTags.Spoiler)) - { - oldPost.HasSpoiler = true; - } - int newTag = 0; - if (oldTag.HasFlag(EBuildInTags.NSFW)) - { - newTag += 1; - } - if (oldTag.HasFlag(EBuildInTags.Friend)) - { - newTag += 2; - } - if (oldTag.HasFlag(EBuildInTags.WanAn)) - { - newTag += 4; - } - if (oldTag.HasFlag(EBuildInTags.AIGraph)) - { - newTag += 8; - } - oldPost.Tags = EBuildInTags.None; - oldPost.NewTags = newTag; - oldPost.ModifyAt = DateTime.Now; - - effectCount++; - - await _oldPostService.Updateable(oldPost).UpdateColumns(static x => new { - x.Tags, - x.NewTags, - x.ModifyAt - }).ExecuteCommandAsync(); - } - }).ToList(); - - await Task.WhenAll(tasks); - - startId = oldOosts.Last().Id + 1; - - _logger.LogInformation("更新进度 {startId} / {totalUsers}, 更新数量 {effectCount}", startId, totalPosts, effectCount); - } - - try - { - await _botClient.EditMessageTextAsync(msg, $"更新稿件表完成, 更新了 {effectCount} 条记录"); - } - catch - { - await _botClient.SendCommandReply($"更新稿件表完成, 更新了 {effectCount} 条记录", message, autoDelete: false); - } - } - - /// - /// 迁移旧的稿件数据 - /// - /// - /// - [TextCmd("MERGEPOST", EUserRights.SuperCmd, Description = "迁移旧的稿件数据")] - [Obsolete("迁移旧数据用")] - public async Task ResponseMergePost(Message message) - { - const int threads = 30; - - int startId = 1; - int effectCount = 0; - - int totalPosts = await _oldPostService.Queryable().CountAsync(x => !x.Merged); - var msg = await _botClient.SendCommandReply($"开始迁移稿件表, 共计 {totalPosts} 条记录", message, autoDelete: false); - - while (startId <= totalPosts) - { - var oldPosts = await _oldPostService.Queryable().Where(x => x.Id >= startId && !x.Merged).Take(threads).ToListAsync(); - if (!oldPosts.Any()) - { - break; - } - - var tasks = oldPosts.Select(async oldPost => { - - long channelId = -1, channelMsgId = -1; - if (oldPost.IsFromChannel) - { - ChannelOptions? channel = null; - - var name = oldPost.ChannelName; - var title = oldPost.ChannelTitle; - - if (name.EndsWith('~')) - { - name = name[..^1]; - } - - var text = name.Split('/'); - if (text.Length >= 2) - { - if (!long.TryParse(text[1], out channelMsgId)) - { - channelMsgId = -1; - } - channel = await _channelOptionService.FetchChannelByNameOrTitle(text[0], title); - } - else - { - channel = await _channelOptionService.FetchChannelByNameOrTitle(name, title); - } - - if (channel != null) - { - channelId = channel.ChannelID; - } - } - - string reason = oldPost.Reason switch { - ERejectReason.Fuzzy => "模糊", - ERejectReason.Duplicate => "重复", - ERejectReason.Boring => "无趣", - ERejectReason.Confused => "没懂", - ERejectReason.Deny => "内容不合适", - ERejectReason.QRCode => "广告水印", - ERejectReason.Other => "其他原因", - ERejectReason.CustomReason => "自定义拒绝理由", - ERejectReason.AutoReject => "稿件审核超时", - _ => "", - }; - - bool countReject = oldPost.Status == EPostStatus.Rejected && (oldPost.Reason != ERejectReason.Fuzzy && oldPost.Reason != ERejectReason.Duplicate); - - var post = new NewPosts { - Id = oldPost.Id, - OriginChatID = oldPost.OriginChatID, - OriginMsgID = oldPost.OriginMsgID, - OriginActionChatID = oldPost.OriginChatID, - OriginActionMsgID = oldPost.ActionMsgID, - PublicMsgID = oldPost.PublicMsgID, - Anonymous = oldPost.Anonymous, - Text = oldPost.Text, - RawText = oldPost.RawText, - ChannelID = channelId, - ChannelMsgID = channelMsgId, - Status = oldPost.Status, - PostType = oldPost.PostType, - OriginMediaGroupID = "", - ReviewMediaGroupID = "", - PublishMediaGroupID = "", - Tags = oldPost.NewTags, - HasSpoiler = oldPost.HasSpoiler, - RejectReason = reason, - CountReject = countReject, - PosterUID = oldPost.PosterUID, - ReviewerUID = oldPost.ReviewerUID, - CreateAt = oldPost.CreateAt, - }; - - if (oldPost.IsDirectPost) - { - post.ReviewChatID = oldPost.OriginChatID; - post.ReviewMsgID = oldPost.OriginMsgID; - post.ReviewActionChatID = oldPost.OriginChatID; - post.ReviewActionMsgID = oldPost.ActionMsgID; - } - else - { - post.ReviewChatID = _channelService.ReviewGroup.Id; - post.ReviewMsgID = oldPost.ReviewMsgID; - post.ReviewActionChatID = _channelService.ReviewGroup.Id; - post.ReviewActionMsgID = oldPost.ManageMsgID; - } - - effectCount++; - - post.ModifyAt = DateTime.Now; - - try - { - await _postService.Insertable(post).OffIdentity().ExecuteCommandAsync(); - } - catch (Exception) - { - _logger.LogWarning("稿件Id {id} 已存在", oldPost.Id); - await _postService.Updateable(post).ExecuteCommandAsync(); - } - - oldPost.Merged = true; - await _oldPostService.Updateable(oldPost).UpdateColumns(static x => new { x.Merged }).ExecuteCommandAsync(); - - }).ToList(); - - await Task.WhenAll(tasks); - - startId = oldPosts.Last().Id + 1; - - _logger.LogInformation("迁移进度 {startId} / {totalUsers}, 更新数量 {effectCount}", startId, totalPosts, effectCount); - } - - try - { - await _botClient.EditMessageTextAsync(msg, $"迁移稿件表完成, 更新了 {effectCount} 条记录"); - } - catch - { - await _botClient.SendCommandReply($"迁移稿件表完成, 更新了 {effectCount} 条记录", message, autoDelete: false); - } - } - - /// - /// 修补稿件数据 - /// - /// - /// - [TextCmd("FIXPOST", EUserRights.SuperCmd, Description = "修补稿件数据")] - [Obsolete("过时方法")] - public async Task ResponseFixPost(Message message) - { - const int threads = 30; - - int startId = 1; - int effectCount = 0; - - int totalPosts = await _postService.Queryable().CountAsync(x => x.ReviewActionChatID == x.ReviewActionMsgID); - var msg = await _botClient.SendCommandReply($"开始修补稿件表, 共计 {totalPosts} 条记录", message, autoDelete: false); - - while (startId <= totalPosts) - { - var posts = await _postService.Queryable().Where(x => x.Id >= startId && - x.ReviewActionChatID == x.ReviewActionMsgID - ).Take(threads).ToListAsync(); - - if (!posts.Any()) - { - break; - } - - var tasks = posts.Select(async post => { - effectCount++; - - post.ReviewActionChatID = post.ReviewChatID; - post.ModifyAt = DateTime.Now; - - await _postService.Updateable(post).UpdateColumns(static x => new { x.ReviewActionChatID, x.ModifyAt }).ExecuteCommandAsync(); - - }).ToList(); - - await Task.WhenAll(tasks); - - startId = posts.Last().Id + 1; - - _logger.LogInformation("迁移进度 {startId} / {totalUsers}, 更新数量 {effectCount}", startId, totalPosts, effectCount); - } - - try - { - await _botClient.EditMessageTextAsync(msg, $"修补稿件表完成, 更新了 {effectCount} 条记录"); - } - catch - { - await _botClient.SendCommandReply($"修补稿件表完成, 更新了 {effectCount} 条记录", message, autoDelete: false); - } - } - /// /// 自动升级机器人 /// @@ -624,7 +301,7 @@ async Task exec() } } - if (string.IsNullOrEmpty(downloadUrl) && releaseResponse.Assets.Any()) + if (string.IsNullOrEmpty(downloadUrl) && releaseResponse.Assets.Count != 0) { return "自动更新失败, 找不到适配的更新包"; } diff --git a/XinjingdailyBot.Interface/Data/IBanRecordService.cs b/XinjingdailyBot.Interface/Data/IBanRecordService.cs index 79bd3026..4d39be05 100644 --- a/XinjingdailyBot.Interface/Data/IBanRecordService.cs +++ b/XinjingdailyBot.Interface/Data/IBanRecordService.cs @@ -34,6 +34,12 @@ public interface IBanRecordService : IBaseService /// /// Task> GetBanRecores(Users targetUser); + /// + /// 获取封禁记录 + /// + /// + /// + /// Task> GetBanRecores(Users targetUser, DateTime expireTime); /// diff --git a/XinjingdailyBot.Interface/Data/IPostService.cs b/XinjingdailyBot.Interface/Data/IPostService.cs index 65b30980..c83cf1ad 100644 --- a/XinjingdailyBot.Interface/Data/IPostService.cs +++ b/XinjingdailyBot.Interface/Data/IPostService.cs @@ -1,4 +1,5 @@ using Telegram.Bot.Types; +using XinjingdailyBot.Infrastructure.Enums; using XinjingdailyBot.Interface.Data.Base; using XinjingdailyBot.Model.Models; @@ -224,4 +225,52 @@ public interface IPostService : IBaseService /// /// Task SetPostTag(NewPosts post, string payload, CallbackQuery callbackQuery); + /// + /// 统计全部稿件 + /// + /// + /// + /// + Task CountAllPosts(DateTime afterTime, DateTime beforeTime); + /// + /// 统计二频通过稿件 + /// + /// + /// + /// + Task CountAcceptedSecondPosts(DateTime afterTime, DateTime beforeTime); + /// + /// 统计拒绝稿件 + /// + /// + /// + /// + Task CountRejectedPosts(DateTime afterTime, DateTime beforeTime); + /// + /// 统计审核中稿件 + /// + /// + /// + /// + Task CountReviewingPosts(DateTime afterTime, DateTime beforeTime); + /// + /// 统计通过稿件 + /// + /// + /// + /// + Task CountAcceptedPosts(DateTime afterTime, DateTime beforeTime); + /// + /// 更新稿件状态 + /// + /// + /// + /// + Task UpdatePostStatus(NewPosts post, EPostStatus status); + /// + /// 创建稿件 + /// + /// + /// + Task CreateNewPosts(NewPosts post); } diff --git a/XinjingdailyBot.Service/Bot/Common/PollingService.cs b/XinjingdailyBot.Service/Bot/Common/PollingService.cs index a62cc11c..7e88cce0 100644 --- a/XinjingdailyBot.Service/Bot/Common/PollingService.cs +++ b/XinjingdailyBot.Service/Bot/Common/PollingService.cs @@ -6,7 +6,6 @@ using Telegram.Bot; using Telegram.Bot.Exceptions; using Telegram.Bot.Polling; -using Telegram.Bot.Types.Enums; using XinjingdailyBot.Infrastructure; using XinjingdailyBot.Interface.Bot.Common; using XinjingdailyBot.Interface.Bot.Handler; @@ -17,55 +16,20 @@ namespace XinjingdailyBot.Service.Bot.Common; /// /// 消息接收服务 /// -public class PollingService : BackgroundService +public class PollingService( + IServiceProvider _serviceProvider, + ILogger _logger, + IChannelService _channelService, + ICommandHandler _commandHandler, + GroupRepository _groupRepository, + LevelRepository _levelRepository, + TagRepository _tagRepository, + RejectReasonRepository _rejectReasonRepository, + ITelegramBotClient _botClient, + IOptions options) : BackgroundService { - private readonly IServiceProvider _serviceProvider; - private readonly ILogger _logger; - private readonly IChannelService _channelService; - private readonly ICommandHandler _commandHandler; - private readonly GroupRepository _groupRepository; - private readonly LevelRepository _levelRepository; - private readonly TagRepository _tagRepository; - private readonly RejectReasonRepository _rejectReasonRepository; - private readonly ITelegramBotClient _botClient; - private readonly bool _throwPendingUpdates; - /// - /// 消息接收服务 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public PollingService( - IServiceProvider serviceProvider, - ILogger logger, - IChannelService channelService, - ICommandHandler commandHandler, - GroupRepository groupRepository, - LevelRepository levelRepository, - TagRepository tagRepository, - RejectReasonRepository rejectReasonRepository, - ITelegramBotClient botClient, - IOptions options) - { - _serviceProvider = serviceProvider; - _logger = logger; - _channelService = channelService; - _commandHandler = commandHandler; - _groupRepository = groupRepository; - _levelRepository = levelRepository; - _tagRepository = tagRepository; - _rejectReasonRepository = rejectReasonRepository; - _botClient = botClient; - _throwPendingUpdates = options.Value.Bot.ThrowPendingUpdates; - } + private readonly bool _throwPendingUpdates = options.Value.Bot.ThrowPendingUpdates; /// /// 执行 @@ -101,7 +65,7 @@ private async Task DoWork(CancellationToken stoppingToken) try { var receiverOptions = new ReceiverOptions { - AllowedUpdates = Array.Empty(), + AllowedUpdates = [], ThrowPendingUpdates = _throwPendingUpdates, Limit = 100, }; diff --git a/XinjingdailyBot.Service/Bot/Common/UpdateService.cs b/XinjingdailyBot.Service/Bot/Common/UpdateService.cs index 4bc7a055..b744fcdf 100644 --- a/XinjingdailyBot.Service/Bot/Common/UpdateService.cs +++ b/XinjingdailyBot.Service/Bot/Common/UpdateService.cs @@ -11,25 +11,12 @@ namespace XinjingdailyBot.Service.Bot.Common; [AppService(typeof(IUpdateService), LifeTime.Scoped)] -internal class UpdateService : IUpdateService +internal class UpdateService( + ILogger _logger, + IUserService _userService, + IDispatcherService _dispatcherService, + IChannelService _channelService) : IUpdateService { - private readonly ILogger _logger; - private readonly IUserService _userService; - private readonly IDispatcherService _dispatcherService; - private readonly IChannelService _channelService; - - public UpdateService( - ILogger logger, - IUserService userService, - IDispatcherService dispatcherService, - IChannelService channelService) - { - _logger = logger; - _userService = userService; - _dispatcherService = dispatcherService; - _channelService = channelService; - } - private int LastUpdateId { get; set; } = 0; public async Task HandleUpdateAsync(ITelegramBotClient _, Update update, CancellationToken cancellationToken) diff --git a/XinjingdailyBot.Service/Bot/Handler/ChannelPostHandler.cs b/XinjingdailyBot.Service/Bot/Handler/ChannelPostHandler.cs index c71e7872..65ea01d2 100644 --- a/XinjingdailyBot.Service/Bot/Handler/ChannelPostHandler.cs +++ b/XinjingdailyBot.Service/Bot/Handler/ChannelPostHandler.cs @@ -15,42 +15,18 @@ namespace XinjingdailyBot.Service.Bot.Handler; [AppService(typeof(IChannelPostHandler), LifeTime.Singleton)] -internal class ChannelPostHandler : IChannelPostHandler +internal class ChannelPostHandler( + ILogger _logger, + IPostService _postService, + ITextHelperService _textHelperService, + IAttachmentService _attachmentService, + IUserService _userService, + IChannelOptionService _channelOptionService, + TagRepository _tagRepository, + ITelegramBotClient _botClient, + IMediaGroupService _mediaGroupService, + IChannelService _channelService) : IChannelPostHandler { - private readonly ILogger _logger; - private readonly IPostService _postService; - private readonly ITextHelperService _textHelperService; - private readonly IAttachmentService _attachmentService; - private readonly IUserService _userService; - private readonly IChannelOptionService _channelOptionService; - private readonly TagRepository _tagRepository; - private readonly ITelegramBotClient _botClient; - private readonly IMediaGroupService _mediaGroupService; - private readonly IChannelService _channelService; - - public ChannelPostHandler( - ILogger logger, - IPostService postService, - ITextHelperService textHelperService, - IAttachmentService attachmentService, - IUserService userService, - IChannelOptionService channelOptionService, - TagRepository tagRepository, - ITelegramBotClient botClient, - IMediaGroupService mediaGroupService, - IChannelService channelService) - { - _logger = logger; - _postService = postService; - _textHelperService = textHelperService; - _attachmentService = attachmentService; - _userService = userService; - _channelOptionService = channelOptionService; - _tagRepository = tagRepository; - _botClient = botClient; - _mediaGroupService = mediaGroupService; - _channelService = channelService; - } public async Task OnTextChannelPostReceived(Users dbUser, Message message) { @@ -79,7 +55,6 @@ public async Task OnTextChannelPostReceived(Users dbUser, Message message) _logger.LogInformation("删除消息 {msgid}", message.MessageId); return; } - } int newTag = _tagRepository.FetchTags(message.Text); @@ -108,7 +83,7 @@ public async Task OnTextChannelPostReceived(Users dbUser, Message message) ReviewerUID = dbUser.UserID }; - await _postService.Insertable(newPost).ExecuteCommandAsync(); + await _postService.CreateNewPosts(newPost); //增加通过数量 dbUser.AcceptCount++; @@ -161,7 +136,7 @@ public async Task OnMediaChannelPostReceived(Users dbUser, Message message) ReviewerUID = dbUser.UserID }; - long postID = await _postService.Insertable(newPost).ExecuteReturnBigIdentityAsync(); + var postID = await _postService.CreateNewPosts(newPost); var attachment = _attachmentService.GenerateAttachment(message, postID); @@ -236,7 +211,7 @@ public async Task OnMediaGroupChannelPostReceived(Users dbUser, Message message) ReviewerUID = dbUser.UserID }; - postID = await _postService.Insertable(newPost).ExecuteReturnBigIdentityAsync(); + postID = await _postService.CreateNewPosts(newPost); MediaGroupIDs[mediaGroupId] = postID; diff --git a/XinjingdailyBot.Service/Bot/Handler/InlineQueryHandler.cs b/XinjingdailyBot.Service/Bot/Handler/InlineQueryHandler.cs index 8a8a5c62..adbd6809 100644 --- a/XinjingdailyBot.Service/Bot/Handler/InlineQueryHandler.cs +++ b/XinjingdailyBot.Service/Bot/Handler/InlineQueryHandler.cs @@ -12,24 +12,12 @@ namespace XinjingdailyBot.Service.Bot.Handler; [AppService(typeof(IInlineQueryHandler), LifeTime.Singleton)] -internal class InlineQueryHandler : IInlineQueryHandler +internal class InlineQueryHandler( + ITelegramBotClient _botClient, + IAttachmentService _attachmentService, + IPostService _postService, + IMarkupHelperService _markupHelperService) : IInlineQueryHandler { - private readonly ITelegramBotClient _botClient; - private readonly IAttachmentService _attachmentService; - private readonly IPostService _postService; - private readonly IMarkupHelperService _markupHelperService; - - public InlineQueryHandler( - ITelegramBotClient botClient, - IAttachmentService attachmentService, - IPostService postService, - IMarkupHelperService markupHelperService) - { - _botClient = botClient; - _attachmentService = attachmentService; - _postService = postService; - _markupHelperService = markupHelperService; - } public async Task OnInlineQueryReceived(Users dbUser, InlineQuery query) { @@ -70,9 +58,9 @@ await _botClient.AnswerInlineQueryAsync( } else { - InlineQueryResult[] results = { + InlineQueryResult[] results = [ new InlineQueryResultArticle("1", "该功能暂时仅对管理员开放", new InputTextMessageContent("To be continued")) - }; + ]; await _botClient.AnswerInlineQueryAsync(inlineQueryId: query.Id, results: results, cacheTime: 10, isPersonal: true); } diff --git a/XinjingdailyBot.Service/Data/AttachmentService.cs b/XinjingdailyBot.Service/Data/AttachmentService.cs index 441ac793..e904bd6a 100644 --- a/XinjingdailyBot.Service/Data/AttachmentService.cs +++ b/XinjingdailyBot.Service/Data/AttachmentService.cs @@ -10,12 +10,8 @@ namespace XinjingdailyBot.Service.Data; /// [AppService(typeof(IAttachmentService), LifeTime.Transient)] -internal sealed class AttachmentService : BaseService, IAttachmentService +internal sealed class AttachmentService(ISqlSugarClient context) : BaseService(context), IAttachmentService { - public AttachmentService(ISqlSugarClient context) : base(context) - { - } - public Attachments? GenerateAttachment(Message message, long postID) { string? fileID, fileName, fileUid, mimeType; diff --git a/XinjingdailyBot.Service/Data/BanRecordService.cs b/XinjingdailyBot.Service/Data/BanRecordService.cs index f5e1c161..b1f551ad 100644 --- a/XinjingdailyBot.Service/Data/BanRecordService.cs +++ b/XinjingdailyBot.Service/Data/BanRecordService.cs @@ -9,12 +9,8 @@ namespace XinjingdailyBot.Service.Data; /// [AppService(typeof(IBanRecordService), LifeTime.Transient)] -internal sealed class BanRecordService : BaseService, IBanRecordService +internal sealed class BanRecordService(ISqlSugarClient context) : BaseService(context), IBanRecordService { - public BanRecordService(ISqlSugarClient context) : base(context) - { - } - public async Task AddBanRecord(Users targetUser, Users operatorUser, EBanType banType, string reason) { var record = new BanRecords { diff --git a/XinjingdailyBot.Service/Data/DialogueService.cs b/XinjingdailyBot.Service/Data/DialogueService.cs index 4d01239a..dc6350da 100644 --- a/XinjingdailyBot.Service/Data/DialogueService.cs +++ b/XinjingdailyBot.Service/Data/DialogueService.cs @@ -10,12 +10,8 @@ namespace XinjingdailyBot.Service.Data; /// [AppService(typeof(IDialogueService), LifeTime.Transient)] -internal sealed class DialogueService : BaseService, IDialogueService +internal sealed class DialogueService(ISqlSugarClient context) : BaseService(context), IDialogueService { - public DialogueService(ISqlSugarClient context) : base(context) - { - } - public async Task RecordMessage(Message message) { string? content = message.Type switch { diff --git a/XinjingdailyBot.Service/Data/PostService.cs b/XinjingdailyBot.Service/Data/PostService.cs index 1c6ab71c..da71e071 100644 --- a/XinjingdailyBot.Service/Data/PostService.cs +++ b/XinjingdailyBot.Service/Data/PostService.cs @@ -21,46 +21,21 @@ namespace XinjingdailyBot.Service.Data; /// [AppService(typeof(IPostService), LifeTime.Singleton)] -internal sealed class PostService : BaseService, IPostService +internal sealed class PostService( + ILogger _logger, + IAttachmentService _attachmentService, + IChannelService _channelService, + IChannelOptionService _channelOptionService, + ITextHelperService _textHelperService, + IMarkupHelperService _markupHelperService, + ITelegramBotClient _botClient, + IUserService _userService, + IOptions options, + TagRepository _tagRepository, + IMediaGroupService _mediaGroupService, + ISqlSugarClient _context) : BaseService(_context), IPostService { - private readonly ILogger _logger; - private readonly IAttachmentService _attachmentService; - private readonly IChannelService _channelService; - private readonly IChannelOptionService _channelOptionService; - private readonly ITextHelperService _textHelperService; - private readonly IMarkupHelperService _markupHelperService; - private readonly ITelegramBotClient _botClient; - private readonly IUserService _userService; - private readonly OptionsSetting.PostOption _postOption; - private readonly TagRepository _tagRepository; - private readonly IMediaGroupService _mediaGroupService; - - public PostService( - ILogger logger, - IAttachmentService attachmentService, - IChannelService channelService, - IChannelOptionService channelOptionService, - ITextHelperService textHelperService, - IMarkupHelperService markupHelperService, - ITelegramBotClient botClient, - IUserService userService, - IOptions options, - TagRepository tagRepository, - IMediaGroupService mediaGroupService, - ISqlSugarClient context) : base(context) - { - _logger = logger; - _attachmentService = attachmentService; - _channelService = channelService; - _channelOptionService = channelOptionService; - _textHelperService = textHelperService; - _markupHelperService = markupHelperService; - _botClient = botClient; - _userService = userService; - _postOption = options.Value.Post; - _tagRepository = tagRepository; - _mediaGroupService = mediaGroupService; - } + private readonly OptionsSetting.PostOption _postOption = options.Value.Post; public async Task CheckPostLimit(Users dbUser, Message? message = null, CallbackQuery? query = null) { @@ -1044,6 +1019,11 @@ public Task CountAllPosts(DateTime afterTime) return Queryable().Where(x => x.CreateAt >= afterTime && x.Status > EPostStatus.Cancel).CountAsync(); } + public Task CountAllPosts(DateTime afterTime, DateTime beforeTime) + { + return Queryable().Where(x => x.CreateAt >= afterTime && x.CreateAt < beforeTime && x.Status > EPostStatus.Cancel).CountAsync(); + } + public Task CountAcceptedPosts() { return Queryable().Where(x => x.Status == EPostStatus.Accepted).CountAsync(); @@ -1054,6 +1034,11 @@ public Task CountAcceptedPosts(DateTime afterTime) return Queryable().Where(x => x.CreateAt >= afterTime && x.Status == EPostStatus.Accepted).CountAsync(); } + public Task CountAcceptedPosts(DateTime afterTime, DateTime beforeTime) + { + return Queryable().Where(x => x.CreateAt >= afterTime && x.CreateAt < beforeTime && x.Status == EPostStatus.Accepted).CountAsync(); + } + public Task CountAcceptedSecondPosts() { return Queryable().Where(x => x.Status == EPostStatus.AcceptedSecond).CountAsync(); @@ -1064,6 +1049,11 @@ public Task CountAcceptedSecondPosts(DateTime afterTime) return Queryable().Where(x => x.CreateAt >= afterTime && x.Status == EPostStatus.AcceptedSecond).CountAsync(); } + public Task CountAcceptedSecondPosts(DateTime afterTime, DateTime beforeTime) + { + return Queryable().Where(x => x.CreateAt >= afterTime && x.CreateAt < beforeTime && x.Status == EPostStatus.AcceptedSecond).CountAsync(); + } + public Task CountRejectedPosts() { return Queryable().Where(x => x.Status == EPostStatus.Rejected).CountAsync(); @@ -1074,6 +1064,11 @@ public Task CountRejectedPosts(DateTime afterTime) return Queryable().Where(x => x.CreateAt >= afterTime && x.Status == EPostStatus.Rejected).CountAsync(); } + public Task CountRejectedPosts(DateTime afterTime, DateTime beforeTime) + { + return Queryable().Where(x => x.CreateAt >= afterTime && x.CreateAt < beforeTime && x.Status == EPostStatus.Rejected).CountAsync(); + } + public Task CountExpiredPosts() { return Queryable().Where(x => x.Status < 0).CountAsync(); @@ -1089,6 +1084,11 @@ public Task CountReviewingPosts(DateTime afterTime) return Queryable().Where(x => x.CreateAt >= afterTime && x.Status == EPostStatus.Reviewing).CountAsync(); } + public Task CountReviewingPosts(DateTime afterTime, DateTime beforeTime) + { + return Queryable().Where(x => x.CreateAt >= afterTime && x.CreateAt < beforeTime && x.Status == EPostStatus.Reviewing).CountAsync(); + } + public Task RevocationPost(NewPosts post) { post.Status = EPostStatus.Revocation; @@ -1140,4 +1140,16 @@ public Task GetInPlanPost() { return Queryable().Where(static x => x.Status == EPostStatus.InPlan).FirstAsync(); } + + public Task UpdatePostStatus(NewPosts post, EPostStatus status) + { + post.Status = status; + post.ModifyAt = DateTime.Now; + return Updateable(post).UpdateColumns(static x => new { x.Status, x.ModifyAt }).ExecuteCommandAsync(); + } + + public Task CreateNewPosts(NewPosts post) + { + return Insertable(post).ExecuteReturnIdentityAsync(); + } } diff --git a/XinjingdailyBot.Service/Data/UserService.cs b/XinjingdailyBot.Service/Data/UserService.cs index 2d6ed8b8..1bc5b2a0 100644 --- a/XinjingdailyBot.Service/Data/UserService.cs +++ b/XinjingdailyBot.Service/Data/UserService.cs @@ -20,46 +20,22 @@ namespace XinjingdailyBot.Service.Data; /// [AppService(typeof(IUserService), LifeTime.Singleton)] -internal sealed class UserService : BaseService, IUserService +internal sealed class UserService( + ILogger _logger, + IOptions _configuration, + GroupRepository _groupRepository, + IMarkupHelperService _markupHelperService, + IChannelService _channelService, + ICmdRecordService _cmdRecordService, + PostRepository _postRepository, + ITelegramBotClient _botClient, + LevelRepository _levelRepository, + INameHistoryService _nameHistoryService, + IMediaGroupService _mediaGroupService, + ISqlSugarClient _context) : BaseService(_context), IUserService { - private readonly ILogger _logger; - private readonly OptionsSetting _optionsSetting; - private readonly GroupRepository _groupRepository; - private readonly IMarkupHelperService _markupHelperService; - private readonly IChannelService _channelService; - private readonly ICmdRecordService _cmdRecordService; - private readonly PostRepository _postRepository; - private readonly ITelegramBotClient _botClient; - private readonly LevelRepository _levelRepository; - private readonly INameHistoryService _nameHistoryService; - private readonly IMediaGroupService _mediaGroupService; - - public UserService( - ILogger logger, - IOptions configuration, - GroupRepository groupRepository, - IMarkupHelperService markupHelperService, - IChannelService channelService, - ICmdRecordService cmdRecordService, - PostRepository postRepository, - ITelegramBotClient botClient, - LevelRepository levelRepository, - INameHistoryService nameHistoryService, - IMediaGroupService mediaGroupService, - ISqlSugarClient context) : base(context) - { - _logger = logger; - _optionsSetting = configuration.Value; - _groupRepository = groupRepository; - _markupHelperService = markupHelperService; - _channelService = channelService; - _cmdRecordService = cmdRecordService; - _postRepository = postRepository; - _botClient = botClient; - _levelRepository = levelRepository; - _nameHistoryService = nameHistoryService; - _mediaGroupService = mediaGroupService; - } + + private readonly OptionsSetting _optionsSetting = _configuration.Value; /// /// 更新周期 @@ -336,7 +312,7 @@ private async Task AutoLeaveChat(Chat? msgChat) /// /// 频道管理员缓存 /// - private readonly Dictionary _channelUserIdCache = new(); + private readonly Dictionary _channelUserIdCache = []; /// /// 根据ChannelPost Author获取用户 diff --git a/XinjingdailyBot.Service/Helper/TextHelperService.cs b/XinjingdailyBot.Service/Helper/TextHelperService.cs index 8e48fa29..db628978 100644 --- a/XinjingdailyBot.Service/Helper/TextHelperService.cs +++ b/XinjingdailyBot.Service/Helper/TextHelperService.cs @@ -25,7 +25,7 @@ public TextHelperService( _tagRepository = tagRepository; var postOption = options.Value.Post; - PureWords = postOption.PureWords.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries); + PureWords = postOption.PureWords.Split(Separator, StringSplitOptions.RemoveEmptyEntries); PureReturns = postOption.PureReturns; PureHashTag = postOption.PureHashTag; } @@ -34,6 +34,8 @@ public TextHelperService( private bool PureReturns { get; init; } private bool PureHashTag { get; init; } + private static readonly char[] Separator = ['|']; + public string PureText(string? text) { if (string.IsNullOrEmpty(text)) @@ -315,22 +317,22 @@ private string ParseMessage(MessageEntity[]? entities, string text) int start = entity.Offset; int end = entity.Offset + entity.Length; - if (!tagMap.ContainsKey(start)) + if (tagMap.TryGetValue(start, out var tagStart)) { - tagMap.Add(start, new TagObjct(head)); + tagStart.AddLast(head); } else { - tagMap[start].AddLast(head); + tagMap.Add(start, new TagObjct(head)); } - if (!tagMap.ContainsKey(end)) + if (tagMap.TryGetValue(end, out var tagEnd)) { - tagMap.Add(end, new TagObjct(tail)); + tagEnd.AddFirst(tail); } else { - tagMap[end].AddFirst(tail); + tagMap.Add(end, new TagObjct(tail)); } } diff --git a/XinjingdailyBot.Tasks/ExpiredPostsTask.cs b/XinjingdailyBot.Tasks/ExpiredPostsTask.cs index d4be2243..0a31df77 100644 --- a/XinjingdailyBot.Tasks/ExpiredPostsTask.cs +++ b/XinjingdailyBot.Tasks/ExpiredPostsTask.cs @@ -14,32 +14,18 @@ namespace XinjingdailyBot.Tasks; /// 过期稿件处理 /// [Job("0 0 0 * * ?")] -internal class ExpiredPostsTask : IJob +internal class ExpiredPostsTask( + ILogger _logger, + IPostService _postService, + IUserService _userService, + ITelegramBotClient _botClient, + IOptions _options) : IJob { - private readonly ILogger _logger; - private readonly IPostService _postService; - private readonly IUserService _userService; - private readonly ITelegramBotClient _botClient; + /// /// 稿件过期时间 /// - private readonly TimeSpan PostExpiredTime; - - public ExpiredPostsTask( - ILogger logger, - IPostService postService, - IUserService userService, - ITelegramBotClient botClient, - IOptions options) - { - _logger = logger; - _postService = postService; - _userService = userService; - _botClient = botClient; - - var expiredTime = options.Value.Post.PostExpiredTime; - PostExpiredTime = expiredTime > 0 ? TimeSpan.FromDays(options.Value.Post.PostExpiredTime) : TimeSpan.Zero; - } + private readonly TimeSpan PostExpiredTime = _options.Value.Post.PostExpiredTime > 0 ? TimeSpan.FromDays(_options.Value.Post.PostExpiredTime) : TimeSpan.Zero; public async Task Execute(IJobExecutionContext context) { @@ -57,7 +43,7 @@ public async Task Execute(IJobExecutionContext context) .Where(x => (x.Status == EPostStatus.Padding || x.Status == EPostStatus.Reviewing) && x.ModifyAt < expiredDate) .Distinct().Select(x => x.PosterUID).ToListAsync(); - if (!userIDList.Any()) + if (userIDList.Count == 0) { _logger.LogInformation("结束定时任务, 没有需要清理的过期稿件"); return; @@ -72,7 +58,7 @@ public async Task Execute(IJobExecutionContext context) .Where(x => x.PosterUID == userID && (x.Status == EPostStatus.Padding || x.Status == EPostStatus.Reviewing) && x.ModifyAt < expiredDate) .ToListAsync(); - if (!paddingPosts.Any()) + if (paddingPosts.Count == 0) { continue; } @@ -80,22 +66,23 @@ public async Task Execute(IJobExecutionContext context) int cTmout = 0, rTmout = 0; foreach (var post in paddingPosts) { + EPostStatus status; if (post.Status == EPostStatus.Padding) { - post.Status = EPostStatus.ConfirmTimeout; + status = EPostStatus.ConfirmTimeout; cTmout++; } else { - post.Status = EPostStatus.ReviewTimeout; + status = EPostStatus.ReviewTimeout; rTmout++; } post.ModifyAt = DateTime.Now; - await _postService.Updateable(post).UpdateColumns(static x => new { x.Status, x.ModifyAt }).ExecuteCommandAsync(); + await _postService.UpdatePostStatus(post, status); } - var user = await _userService.Queryable().FirstAsync(x => x.UserID == userID); + var user = await _userService.FetchUserByUserID(userID); if (user == null) { diff --git a/XinjingdailyBot.Tasks/PlanedPostsTask.cs b/XinjingdailyBot.Tasks/PlanedPostsTask.cs index f3bdc6c6..3b60d3c0 100644 --- a/XinjingdailyBot.Tasks/PlanedPostsTask.cs +++ b/XinjingdailyBot.Tasks/PlanedPostsTask.cs @@ -8,18 +8,10 @@ namespace XinjingdailyBot.Tasks; /// 定期发布稿件处理 /// [Job("0 0 0 * * ?")] -internal class PlanedPostsTask : IJob +internal class PlanedPostsTask( + ILogger _logger, + IPostService _postService) : IJob { - private readonly ILogger _logger; - private readonly IPostService _postService; - - public PlanedPostsTask( - ILogger logger, - IPostService postService) - { - _logger = logger; - _postService = postService; - } public async Task Execute(IJobExecutionContext context) { diff --git a/XinjingdailyBot.Tasks/ReviewStatusTask.cs b/XinjingdailyBot.Tasks/ReviewStatusTask.cs index 8761f3db..d91a99ee 100644 --- a/XinjingdailyBot.Tasks/ReviewStatusTask.cs +++ b/XinjingdailyBot.Tasks/ReviewStatusTask.cs @@ -4,7 +4,6 @@ using Telegram.Bot.Types; using Telegram.Bot.Types.Enums; using XinjingdailyBot.Infrastructure.Attribute; -using XinjingdailyBot.Infrastructure.Enums; using XinjingdailyBot.Interface.Bot.Common; using XinjingdailyBot.Interface.Data; using XinjingdailyBot.Interface.Helper; @@ -15,30 +14,14 @@ namespace XinjingdailyBot.Tasks; /// 定期发布审核状态通知 /// [Job("0 * * * * ?")] -internal class ReviewStatusTask : IJob +internal class ReviewStatusTask( + ILogger _logger, + IPostService _postService, + ITelegramBotClient _botClient, + IChannelService _channelService, + IReviewStatusService _reviewStatusService, + IMarkupHelperService _markupHelperService) : IJob { - private readonly ILogger _logger; - private readonly IPostService _postService; - private readonly ITelegramBotClient _botClient; - private readonly IChannelService _channelService; - private readonly IReviewStatusService _reviewStatusService; - private readonly IMarkupHelperService _markupHelperService; - - public ReviewStatusTask( - ILogger logger, - IPostService postService, - ITelegramBotClient botClient, - IChannelService channelService, - IReviewStatusService reviewStatusService, - IMarkupHelperService markupHelperService) - { - _logger = logger; - _postService = postService; - _botClient = botClient; - _channelService = channelService; - _reviewStatusService = reviewStatusService; - _markupHelperService = markupHelperService; - } public async Task Execute(IJobExecutionContext context) { @@ -84,19 +67,14 @@ public async Task Execute(IJobExecutionContext context) var startTime = oldTime.AddHours(-oldTime.Hour).AddMinutes(-oldTime.Minute).AddSeconds(oldTime.Second); var endTime = startTime.AddDays(1); - var post = await _postService.Queryable() - .Where(x => x.CreateAt >= startTime && x.CreateAt < endTime && x.Status > EPostStatus.Cancel).CountAsync(); - var acceptPost = await _postService.Queryable() - .Where(x => x.CreateAt >= startTime && x.CreateAt < endTime && x.Status == EPostStatus.Accepted).CountAsync(); - var rejectPost = await _postService.Queryable() - .Where(x => x.CreateAt >= startTime && x.CreateAt < endTime && x.Status == EPostStatus.Rejected).CountAsync(); - var paddingPost = await _postService.Queryable() - .Where(x => x.CreateAt >= startTime && x.CreateAt < endTime && x.Status == EPostStatus.Reviewing).CountAsync(); + var post = await _postService.CountAllPosts(startTime, endTime); + var acceptPost = await _postService.CountAcceptedPosts(startTime, endTime); + var rejectPost = await _postService.CountRejectedPosts(startTime, endTime); + var paddingPost = await _postService.CountReviewingPosts(startTime, endTime); if (_channelService.HasSecondChannel) { - var acceptSecondPost = await _postService.Queryable() - .Where(x => x.CreateAt >= startTime && x.CreateAt < endTime && x.Status == EPostStatus.AcceptedSecond).CountAsync(); + var acceptSecondPost = await _postService.CountAcceptedSecondPosts(startTime, endTime); acceptPost += acceptSecondPost; } diff --git a/XinjingdailyBot.WebAPI/IPC/Controllers/PostController.cs b/XinjingdailyBot.WebAPI/IPC/Controllers/PostController.cs index be0bba39..38bae8d6 100644 --- a/XinjingdailyBot.WebAPI/IPC/Controllers/PostController.cs +++ b/XinjingdailyBot.WebAPI/IPC/Controllers/PostController.cs @@ -20,59 +20,19 @@ namespace XinjingdailyBot.WebAPI.IPC.Controllers; /// 主页控制器 /// [Verify] -public sealed class PostController : XjbController +public sealed class PostController( + IHttpContextAccessor _httpContextAccessor, + IPostService _postService, + IChannelOptionService _channelOptionService, + IUserService _userService, + ITelegramBotClient _botClient, + IChannelService _channelService, + IMarkupHelperService _markupHelperService, + ITextHelperService _textHelperService, + IAttachmentService _attachmentService, + TagRepository _tagRepository, + IMediaGroupService _mediaGroupService) : XjbController { - private readonly IHttpContextAccessor _httpContextAccessor; - private readonly IPostService _postService; - private readonly IChannelOptionService _channelOptionService; - private readonly IUserService _userService; - private readonly ITelegramBotClient _botClient; - private readonly IChannelService _channelService; - private readonly IMarkupHelperService _markupHelperService; - private readonly ITextHelperService _textHelperService; - private readonly IAttachmentService _attachmentService; - private readonly TagRepository _tagRepository; - private readonly IMediaGroupService _mediaGroupService; - - /// - /// 构造函数 - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - public PostController( - IHttpContextAccessor httpContextAccessor, - IPostService postService, - IChannelOptionService channelOptionService, - IUserService userService, - ITelegramBotClient botClient, - IChannelService channelService, - IMarkupHelperService markupHelperService, - ITextHelperService textHelperService, - IAttachmentService attachmentService, - TagRepository tagRepository, - IMediaGroupService mediaGroupService) - { - _httpContextAccessor = httpContextAccessor; - _postService = postService; - _channelOptionService = channelOptionService; - _userService = userService; - _botClient = botClient; - _channelService = channelService; - _markupHelperService = markupHelperService; - _textHelperService = textHelperService; - _attachmentService = attachmentService; - _tagRepository = tagRepository; - _mediaGroupService = mediaGroupService; - } /// /// 连接测试 @@ -198,7 +158,7 @@ public async Task>> CreatePost([FromForm] PosterUID = dbUser.UserID, }; - var newPostId = await _postService.Insertable(newPost).ExecuteReturnIdentityAsync(); + var newPostId = await _postService.CreateNewPosts(newPost); Message? originMsg = null; @@ -436,7 +396,7 @@ public async Task>> EditReviewMessage([Fr PosterUID = dbUser.UserID, }; - var newPostId = await _postService.Insertable(newPost).ExecuteReturnIdentityAsync(); + var newPostId = await _postService.CreateNewPosts(newPost); Message? originMsg = null;