diff --git a/Theresa3rd-Bot/TheresaBot.Main/Controller/CookieController.cs b/Theresa3rd-Bot/TheresaBot.Main/Controller/CookieController.cs index b814c333..51eaff17 100644 --- a/Theresa3rd-Bot/TheresaBot.Main/Controller/CookieController.cs +++ b/Theresa3rd-Bot/TheresaBot.Main/Controller/CookieController.cs @@ -1,79 +1,87 @@ +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; -using TheresaBot.Main.Common; -using TheresaBot.Main.Model.Result; using TheresaBot.Main.Datas; -using TheresaBot.Main.Helper; -using TheresaBot.Main.Model.PO; -using TheresaBot.Main.Services; -using TheresaBot.Main.Type; -using Microsoft.AspNetCore.Authorization; +using TheresaBot.Main.Exceptions; using TheresaBot.Main.Model.DTO; - +using TheresaBot.Main.Model.Result; +using TheresaBot.Main.Services; namespace TheresaBot.Main.Controller { [ApiController] [Route("api/[controller]")] - public class CookieController : ControllerBase + public class CookieController : BaseController { private WebsiteService websiteService; + public CookieController() { websiteService = new WebsiteService(); } - [HttpPost] + + [HttpGet] [Authorize] - [Route("update/pck")] - public async Task<ApiResult> UpdatePixivCookie([FromBody] CookieDto pck) + [Route("get/pixiv")] + public ApiResult GetPixiv() { - ApiResult result = await UpdatePixivCookieAsync(pck.pcookie); - return result; + var data = new { cookie = WebsiteDatas.Pixiv?.Cookie ?? string.Empty }; + return ApiResult.Success(data); } - private async Task<ApiResult> UpdatePixivCookieAsync(string pcko) + + [HttpPost] + [Authorize] + [Route("set/pixiv")] + public ApiResult SetPixiv([FromBody] CookieDto cookie) { - string cookie = pcko; - if (string.IsNullOrWhiteSpace(cookie)) + try { - Console.WriteLine($"未检测到cookie"); - return ApiResult.Fail($"未检测到cookie"); + var cookieStr = cookie.Cookie; + if (string.IsNullOrWhiteSpace(cookieStr)) return ApiResult.ParamError; + var website = websiteService.UpdatePixivCookie(cookieStr); + WebsiteDatas.LoadWebsite(); + return ApiResult.Success(); } - - cookie = cookie.Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace("\"", "").Trim(); - Dictionary<string, string> cookieDic = cookie.SplitCookie(); - string PHPSESSID = cookieDic.ContainsKey("PHPSESSID") ? cookieDic["PHPSESSID"] : string.Empty; - if (string.IsNullOrWhiteSpace(PHPSESSID)) + catch (HandleException ex) { - Console.WriteLine($"cookie中没有检测到PHPSESSID,请重新获取cookie"); - return ApiResult.Fail($"cookie中没有检测到PHPSESSID,请重新获取cookie"); + return ApiResult.Fail(ex); } - - string[] sessionArr = PHPSESSID.Split('_', StringSplitOptions.RemoveEmptyEntries); - if (sessionArr.Length < 2 || string.IsNullOrWhiteSpace(sessionArr[0])) + catch (Exception ex) { - Console.WriteLine($"cookie中的PHPSESSID格式不正确,请重新获取cookie"); - return ApiResult.Fail($"cookie中的PHPSESSID格式不正确,请重新获取cookie"); + return ApiResult.Fail(ex); } + } - long userId = 0; - if (long.TryParse(sessionArr[0].Trim(), out userId) == false) + [HttpGet] + [Authorize] + [Route("get/saucenao")] + public ApiResult GetSaucenao() + { + var data = new { cookie = WebsiteDatas.Saucenao?.Cookie ?? string.Empty }; + return ApiResult.Success(data); + } + + [HttpPost] + [Authorize] + [Route("set/saucenao")] + public ApiResult SetSaucenao([FromBody] CookieDto cookie) + { + try { - Console.WriteLine($"cookie中的PHPSESSID格式不正确,请重新获取cookie"); - return ApiResult.Fail($"cookie中的PHPSESSID格式不正确,请重新获取cookie"); + var cookieStr = cookie.Cookie; + if (string.IsNullOrWhiteSpace(cookieStr)) return ApiResult.ParamError; + var website = websiteService.UpdateSaucenaoCookie(cookieStr); + WebsiteDatas.LoadWebsite(); + return ApiResult.Success(); + } + catch (HandleException ex) + { + return ApiResult.Fail(ex); + } + catch (Exception ex) + { + return ApiResult.Fail(ex); } - - if (cookieDic.ContainsKey("__cf_bm")) cookieDic.Remove("__cf_bm"); - if (cookieDic.ContainsKey("cto_bundle")) cookieDic.Remove("cto_bundle"); - if (cookieDic.ContainsKey("categorized_tags")) cookieDic.Remove("cookieDic"); - if (cookieDic.ContainsKey("tag_view_ranking")) cookieDic.Remove("tag_view_ranking"); - cookie = cookieDic.JoinCookie(); - - string websiteCode = Enum.GetName(typeof(WebsiteType), WebsiteType.Pixiv) ?? string.Empty; - WebsitePO website = websiteService.UpdateWebsite(websiteCode, cookie, userId, BotConfig.PixivConfig.CookieExpire); - WebsiteDatas.LoadWebsite(); - string expireDate = website.CookieExpireDate.ToString("yyyy-MM-dd HH:mm:ss"); - Console.WriteLine($"cookie更新完毕,过期时间为{expireDate}"); - - return ApiResult.Success(); } + } } diff --git a/Theresa3rd-Bot/TheresaBot.Main/Datas/WebsiteDatas.cs b/Theresa3rd-Bot/TheresaBot.Main/Datas/WebsiteDatas.cs index 9735eddd..e416f7de 100644 --- a/Theresa3rd-Bot/TheresaBot.Main/Datas/WebsiteDatas.cs +++ b/Theresa3rd-Bot/TheresaBot.Main/Datas/WebsiteDatas.cs @@ -9,7 +9,7 @@ internal static class WebsiteDatas { public static WebsitePO Pixiv { get; private set; } - public static WebsitePO Bili { get; private set; } + public static WebsitePO BiliBili { get; private set; } public static WebsitePO Saucenao { get; private set; } @@ -18,9 +18,9 @@ public static void LoadWebsite() try { var websiteService = new WebsiteService(); - Pixiv = websiteService.GetOrInsert(Enum.GetName(typeof(WebsiteType), WebsiteType.Pixiv)); - Bili = websiteService.GetOrInsert(Enum.GetName(typeof(WebsiteType), WebsiteType.Bili)); - Saucenao = websiteService.GetOrInsert(Enum.GetName(typeof(WebsiteType), WebsiteType.Saucenao)); + Pixiv = websiteService.GetOrInsert(WebsiteType.Pixiv.ToString()); + BiliBili = websiteService.GetOrInsert(WebsiteType.BiliBili.ToString()); + Saucenao = websiteService.GetOrInsert(WebsiteType.Saucenao.ToString()); LogHelper.Info("网站cookie加载完成..."); } catch (Exception ex) diff --git a/Theresa3rd-Bot/TheresaBot.Main/Exceptions/HandleException.cs b/Theresa3rd-Bot/TheresaBot.Main/Exceptions/HandleException.cs new file mode 100644 index 00000000..3fb65d26 --- /dev/null +++ b/Theresa3rd-Bot/TheresaBot.Main/Exceptions/HandleException.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TheresaBot.Main.Exceptions +{ + public class HandleException : Exception + { + public string RemindMessage { get; init; } + + public HandleException(string message) : base(message) + { + this.RemindMessage = message; + } + } +} diff --git a/Theresa3rd-Bot/TheresaBot.Main/Handler/CookieHandler.cs b/Theresa3rd-Bot/TheresaBot.Main/Handler/CookieHandler.cs index 99fc97c8..693691db 100644 --- a/Theresa3rd-Bot/TheresaBot.Main/Handler/CookieHandler.cs +++ b/Theresa3rd-Bot/TheresaBot.Main/Handler/CookieHandler.cs @@ -1,6 +1,7 @@ using TheresaBot.Main.Command; using TheresaBot.Main.Common; using TheresaBot.Main.Datas; +using TheresaBot.Main.Exceptions; using TheresaBot.Main.Helper; using TheresaBot.Main.Model.PO; using TheresaBot.Main.Reporter; @@ -20,123 +21,76 @@ public CookieHandler(BaseSession session, BaseReporter reporter) : base(session, } /// <summary> - /// 更新pixivcookie + /// 更新Pixiv Cookie /// </summary> - /// <param name="session"></param> - /// <param name="args"></param> - /// <param name="message"></param> + /// <param name="command"></param> /// <returns></returns> public async Task UpdatePixivCookieAsync(PrivateCommand command) { - string cookie = command.KeyWord; - if (string.IsNullOrWhiteSpace(cookie)) + try { - await command.ReplyFriendMessageAsync($"未检测到cookie"); - return; + var cookie = command.KeyWord; + if (string.IsNullOrWhiteSpace(cookie)) + { + await command.ReplyFriendMessageAsync($"未检测到Cookie"); + return; + } + var website = websiteService.UpdatePixivCookie(cookie); + WebsiteDatas.LoadWebsite(); + var expireDate = website.CookieExpireDate.ToSimpleString(); + await command.ReplyFriendMessageAsync($"Cookie更新完毕,过期时间为:{expireDate}"); } - - cookie = cookie.Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace("\"", "").Trim(); - Dictionary<string, string> cookieDic = cookie.SplitCookie(); - string PHPSESSID = cookieDic.ContainsKey("PHPSESSID") ? cookieDic["PHPSESSID"] : string.Empty; - if (string.IsNullOrWhiteSpace(PHPSESSID)) + catch (HandleException ex) { - await command.ReplyFriendMessageAsync($"cookie中没有检测到PHPSESSID,请重新获取cookie"); - return; + await command.ReplyFriendMessageAsync(ex.RemindMessage); } - - string[] sessionArr = PHPSESSID.Split('_', StringSplitOptions.RemoveEmptyEntries); - if (sessionArr.Length < 2 || string.IsNullOrWhiteSpace(sessionArr[0])) + catch (Exception ex) { - await command.ReplyFriendMessageAsync($"cookie中的PHPSESSID格式不正确,请重新获取cookie"); - return; + await LogAndReplyError(command, ex, "PixivCookie更新异常"); } - - long userId = 0; - if (long.TryParse(sessionArr[0].Trim(), out userId) == false) - { - await command.ReplyFriendMessageAsync($"cookie中的PHPSESSID格式不正确,请重新获取cookie"); - return; - } - - if (cookieDic.ContainsKey("__cf_bm")) cookieDic.Remove("__cf_bm"); - if (cookieDic.ContainsKey("cto_bundle")) cookieDic.Remove("cto_bundle"); - if (cookieDic.ContainsKey("categorized_tags")) cookieDic.Remove("cookieDic"); - if (cookieDic.ContainsKey("tag_view_ranking")) cookieDic.Remove("tag_view_ranking"); - cookie = cookieDic.JoinCookie(); - - string websiteCode = Enum.GetName(typeof(WebsiteType), WebsiteType.Pixiv) ?? string.Empty; - WebsitePO website = websiteService.UpdateWebsite(websiteCode, cookie, userId, BotConfig.PixivConfig.CookieExpire); - WebsiteDatas.LoadWebsite(); - string expireDate = website.CookieExpireDate.ToString("yyyy-MM-dd HH:mm:ss"); - await command.ReplyFriendMessageAsync($"cookie更新完毕,过期时间为{expireDate}"); } /// <summary> - /// 更新SaucenaoCookie + /// 更新Saucenao Cookie /// </summary> - /// <param name="session"></param> - /// <param name="args"></param> - /// <param name="message"></param> + /// <param name="command"></param> /// <returns></returns> public async Task UpdateSaucenaoCookieAsync(PrivateCommand command) { - string cookie = command.KeyWord; + var cookie = command.KeyWord; if (string.IsNullOrWhiteSpace(cookie)) { - await command.ReplyFriendMessageAsync($"未检测到cookie"); - return; - } - //token=62b9ae236fdf9; user=58109; auth=9cd37025e035f2ed99d096f2b7cf5485b7dd50a7; - cookie = cookie.Replace("\r\n", "").Replace("\r", "").Replace("\n", "").Replace("\"", "").Trim(); - Dictionary<string, string> cookieDic = cookie.SplitCookie(); - - string tokenStr = cookieDic.ContainsKey("token") ? cookieDic["token"] : string.Empty; - if (string.IsNullOrWhiteSpace(tokenStr)) - { - await command.ReplyFriendMessageAsync($"cookie中没有检测到token,请重新获取cookie"); + await command.ReplyFriendMessageAsync($"未检测到Cookie"); return; } - - string authStr = cookieDic.ContainsKey("auth") ? cookieDic["auth"] : string.Empty; - if (string.IsNullOrWhiteSpace(authStr)) - { - await command.ReplyFriendMessageAsync($"cookie中没有检测到auth,请重新获取cookie"); - return; - } - - string userStr = cookieDic.ContainsKey("user") ? cookieDic["user"] : string.Empty; - if (string.IsNullOrWhiteSpace(userStr)) - { - await command.ReplyFriendMessageAsync($"cookie中没有检测到user,请重新获取cookie"); - return; - } - - long userId = 0; - if (long.TryParse(userStr, out userId) == false) - { - await command.ReplyFriendMessageAsync($"cookie中的user格式不正确,请重新获取cookie"); - return; - } - - string websiteCode = Enum.GetName(typeof(WebsiteType), WebsiteType.Saucenao) ?? string.Empty; - websiteService.UpdateWebsite(websiteCode, cookie, userId, DateTime.Now.AddYears(1)); + var website = websiteService.UpdateSaucenaoCookie(cookie); WebsiteDatas.LoadWebsite(); - await command.ReplyFriendMessageAsync($"cookie更新完毕"); + var expireDate = website.CookieExpireDate.ToSimpleString(); + await command.ReplyFriendMessageAsync($"Cookie更新完毕,过期时间为:{expireDate}"); } + /// <summary> + /// 判断Cookie是否即将过期并发送提醒消息 + /// </summary> + /// <param name="website"></param> + /// <param name="diffDay"></param> + /// <param name="cookieName"></param> + /// <returns></returns> public async Task CheckAndWarn(WebsitePO website, int diffDay, string cookieName) { - DateTime expireDate = website.CookieExpireDate; + var expireDate = website.CookieExpireDate; if (DateTime.Now.AddDays(diffDay) < expireDate) return; if (expireDate.AddDays(diffDay) < DateTime.Now) return; - string warnMessage = $"{cookieName}将在{expireDate.ToString("yyyy-MM-dd HH:mm:ss")}过期,请尽快更新cookie"; + var warnMessage = $"{cookieName}将在{expireDate.ToSimpleString()}过期,请尽快更新Cookie"; foreach (long groupId in BotConfig.ErrorPushGroups) { await Session.SendGroupMessageAsync(groupId, warnMessage); + await Task.Delay(1000); } foreach (long memberId in BotConfig.SuperManagers) { await Session.SendFriendMessageAsync(memberId, warnMessage); + await Task.Delay(1000); } } diff --git a/Theresa3rd-Bot/TheresaBot.Main/Helper/StringHelper.cs b/Theresa3rd-Bot/TheresaBot.Main/Helper/StringHelper.cs index 0f0ffd62..3b42e202 100644 --- a/Theresa3rd-Bot/TheresaBot.Main/Helper/StringHelper.cs +++ b/Theresa3rd-Bot/TheresaBot.Main/Helper/StringHelper.cs @@ -153,21 +153,22 @@ public static string[] SplitParams(this string value) } /// <summary> - /// 拆分cookie,返回键值对 + /// 拆分cookie,返回键值对,不区分key大小写 /// </summary> /// <param name="cookie"></param> /// <returns></returns> public static Dictionary<string, string> SplitCookie(this string cookie) { - Dictionary<string, string> cookieDic = new Dictionary<string, string>(); - if (string.IsNullOrEmpty(cookie)) return cookieDic; - string[] cookieArr = cookie.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); + if (string.IsNullOrWhiteSpace(cookie)) return new(); + var cookieDic = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + var cookieArr = cookie.Trim().Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in cookieArr) { - string[] cookieKVArr = item.Trim().Split(new string[] { "=" }, StringSplitOptions.RemoveEmptyEntries); - if (cookieKVArr.Length == 0) continue; - string key = cookieKVArr[0].Trim(); - string value = cookieKVArr.Length > 1 ? cookieKVArr[1].Trim() : ""; + var kvArr = item.Trim().Split("=", StringSplitOptions.RemoveEmptyEntries); + if (kvArr.Length == 0) continue; + var key = kvArr[0].Trim(); + if (string.IsNullOrWhiteSpace(key)) continue; + var value = kvArr.Length > 1 ? kvArr[1].Trim() : string.Empty; cookieDic[key] = value; } return cookieDic; diff --git a/Theresa3rd-Bot/TheresaBot.Main/Model/DTO/CookieDto.cs b/Theresa3rd-Bot/TheresaBot.Main/Model/DTO/CookieDto.cs new file mode 100644 index 00000000..7f46e44f --- /dev/null +++ b/Theresa3rd-Bot/TheresaBot.Main/Model/DTO/CookieDto.cs @@ -0,0 +1,13 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace TheresaBot.Main.Model.DTO +{ + public record CookieDto + { + public string Cookie { get; set; } + } +} diff --git a/Theresa3rd-Bot/TheresaBot.Main/Services/WebsiteService.cs b/Theresa3rd-Bot/TheresaBot.Main/Services/WebsiteService.cs index 24fbdd75..bfe8d6fe 100644 --- a/Theresa3rd-Bot/TheresaBot.Main/Services/WebsiteService.cs +++ b/Theresa3rd-Bot/TheresaBot.Main/Services/WebsiteService.cs @@ -1,5 +1,11 @@ -using TheresaBot.Main.Dao; +using TheresaBot.Main.Command; +using TheresaBot.Main.Common; +using TheresaBot.Main.Dao; +using TheresaBot.Main.Datas; +using TheresaBot.Main.Exceptions; +using TheresaBot.Main.Helper; using TheresaBot.Main.Model.PO; +using TheresaBot.Main.Type; namespace TheresaBot.Main.Services { @@ -12,6 +18,95 @@ public WebsiteService() websiteDao = new WebsiteDao(); } + /// <summary> + /// 更新Pixiv Cookie + /// </summary> + /// <param name="cookie"></param> + /// <returns></returns> + /// <exception cref="HandleException"></exception> + public WebsitePO UpdatePixivCookie(string cookie) + { + cookie = cookie.Replace("\r\n", string.Empty); + cookie = cookie.Replace("\r", string.Empty); + cookie = cookie.Replace("\n", string.Empty); + cookie = cookie.Replace("\"", string.Empty); + cookie = cookie.Trim(); + + var cookieDic = cookie.SplitCookie(); + var sessionId = cookieDic.ContainsKey("PHPSESSID") ? cookieDic["PHPSESSID"] : string.Empty; + if (string.IsNullOrWhiteSpace(sessionId)) + { + throw new HandleException($"cookie中缺少PHPSESSID,请重新获取cookie"); + } + + var splitArr = sessionId.Split('_', StringSplitOptions.RemoveEmptyEntries); + if (splitArr.Length < 2 || string.IsNullOrWhiteSpace(splitArr[0])) + { + throw new HandleException($"cookie中的PHPSESSID格式不正确,请重新获取cookie"); + } + + long userId = 0; + if (long.TryParse(splitArr[0].Trim(), out userId) == false) + { + throw new HandleException($"cookie中的PHPSESSID格式不正确,请重新获取cookie"); + } + + if (cookieDic.ContainsKey("__cf_bm")) cookieDic.Remove("__cf_bm"); + if (cookieDic.ContainsKey("cto_bundle")) cookieDic.Remove("cto_bundle"); + if (cookieDic.ContainsKey("categorized_tags")) cookieDic.Remove("cookieDic"); + if (cookieDic.ContainsKey("tag_view_ranking")) cookieDic.Remove("tag_view_ranking"); + + var websiteCookie = cookieDic.JoinCookie(); + var websiteCode = WebsiteType.Pixiv.ToString(); + var websiteExpire = BotConfig.PixivConfig.CookieExpire; + return UpdateWebsite(websiteCode, websiteCookie, userId, websiteExpire); + } + + /// <summary> + /// 更新Saucenao Cookie + /// </summary> + /// <param name="cookie"></param> + /// <returns></returns> + /// <exception cref="HandleException"></exception> + public WebsitePO UpdateSaucenaoCookie(string cookie) + { + cookie = cookie.Replace("\r\n", string.Empty); + cookie = cookie.Replace("\r", string.Empty); + cookie = cookie.Replace("\n", string.Empty); + cookie = cookie.Replace("\"", string.Empty); + cookie = cookie.Trim(); + + //token=62b9ae236fdf9; user=58109; auth=9cd37025e035f2ed99d096f2b7cf5485b7dd50a7; + var cookieDic = cookie.SplitCookie(); + var tokenStr = cookieDic.ContainsKey("token") ? cookieDic["token"] : string.Empty; + if (string.IsNullOrWhiteSpace(tokenStr)) + { + throw new HandleException($"cookie中缺少token,请重新获取cookie"); + } + + var authStr = cookieDic.ContainsKey("auth") ? cookieDic["auth"] : string.Empty; + if (string.IsNullOrWhiteSpace(authStr)) + { + throw new HandleException($"cookie中缺少auth,请重新获取cookie"); + } + + var userStr = cookieDic.ContainsKey("user") ? cookieDic["user"] : string.Empty; + if (string.IsNullOrWhiteSpace(userStr)) + { + throw new HandleException($"cookie中缺少user,请重新获取cookie"); + } + + long userId = 0; + if (long.TryParse(userStr, out userId) == false) + { + throw new HandleException($"cookie中user格式不正确,请重新获取cookie"); + } + + var websiteCode = WebsiteType.Saucenao.ToString(); + return UpdateWebsite(websiteCode, cookie, userId, DateTime.Now.AddYears(1)); + } + + public WebsitePO UpdateWebsite(string code, string cookie, long userid, int expireSeconds) { WebsitePO website = GetOrInsert(code); diff --git a/Theresa3rd-Bot/TheresaBot.Main/Type/WebsiteType.cs b/Theresa3rd-Bot/TheresaBot.Main/Type/WebsiteType.cs index 23223c67..7a80c7bc 100644 --- a/Theresa3rd-Bot/TheresaBot.Main/Type/WebsiteType.cs +++ b/Theresa3rd-Bot/TheresaBot.Main/Type/WebsiteType.cs @@ -4,7 +4,7 @@ public enum WebsiteType { Other = 0, Pixiv = 1, - Bili = 2, + BiliBili = 2, Saucenao = 3 } }