Skip to content

Commit

Permalink
Merge branch 'pr/41' into v0.11.2
Browse files Browse the repository at this point in the history
  • Loading branch information
GardenHamster committed Dec 20, 2023
2 parents 9a33073 + bd5a36b commit 4a1a142
Show file tree
Hide file tree
Showing 9 changed files with 270 additions and 97 deletions.
7 changes: 7 additions & 0 deletions CookieDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace TheresaBot.Main.Model.DTO
{
public record CookieDto
{
public string pcookie { get; set; }
}
}
87 changes: 87 additions & 0 deletions Theresa3rd-Bot/TheresaBot.Main/Controller/CookieController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using TheresaBot.Main.Datas;
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 : BaseController
{
private WebsiteService websiteService;

public CookieController()
{
websiteService = new WebsiteService();
}

[HttpGet]
[Authorize]
[Route("get/pixiv")]
public ApiResult GetPixiv()
{
var data = new { cookie = WebsiteDatas.Pixiv?.Cookie ?? string.Empty };
return ApiResult.Success(data);
}

[HttpPost]
[Authorize]
[Route("set/pixiv")]
public ApiResult SetPixiv([FromBody] CookieDto cookie)
{
try
{
var cookieStr = cookie.Cookie;
if (string.IsNullOrWhiteSpace(cookieStr)) return ApiResult.ParamError;
var website = websiteService.UpdatePixivCookie(cookieStr);
WebsiteDatas.LoadWebsite();
return ApiResult.Success();
}
catch (HandleException ex)
{
return ApiResult.Fail(ex);
}
catch (Exception ex)
{
return ApiResult.Fail(ex);
}
}

[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
{
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);
}
}

}
}
8 changes: 4 additions & 4 deletions Theresa3rd-Bot/TheresaBot.Main/Datas/WebsiteDatas.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand All @@ -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)
Expand Down
12 changes: 12 additions & 0 deletions Theresa3rd-Bot/TheresaBot.Main/Exceptions/HandleException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
namespace TheresaBot.Main.Exceptions
{
public class HandleException : Exception
{
public string RemindMessage { get; init; }

public HandleException(string message) : base(message)
{
this.RemindMessage = message;
}
}
}
128 changes: 46 additions & 82 deletions Theresa3rd-Bot/TheresaBot.Main/Handler/CookieHandler.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
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;
using TheresaBot.Main.Services;
using TheresaBot.Main.Session;
using TheresaBot.Main.Type;

namespace TheresaBot.Main.Handler
{
Expand All @@ -20,123 +20,87 @@ 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]))
{
await command.ReplyFriendMessageAsync($"cookie中的PHPSESSID格式不正确,请重新获取cookie");
return;
}

long userId = 0;
if (long.TryParse(sessionArr[0].Trim(), out userId) == false)
catch (Exception ex)
{
await command.ReplyFriendMessageAsync($"cookie中的PHPSESSID格式不正确,请重新获取cookie");
return;
await LogAndReplyError(command, ex, "PixivCookie更新异常");
}

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;
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.UpdateSaucenaoCookie(cookie);
WebsiteDatas.LoadWebsite();
var expireDate = website.CookieExpireDate.ToSimpleString();
await command.ReplyFriendMessageAsync($"Cookie更新完毕,过期时间为:{expireDate}");
}
//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))
catch (HandleException ex)
{
await command.ReplyFriendMessageAsync($"cookie中没有检测到token,请重新获取cookie");
return;
await command.ReplyFriendMessageAsync(ex.RemindMessage);
}

string authStr = cookieDic.ContainsKey("auth") ? cookieDic["auth"] : string.Empty;
if (string.IsNullOrWhiteSpace(authStr))
catch (Exception ex)
{
await command.ReplyFriendMessageAsync($"cookie中没有检测到auth,请重新获取cookie");
return;
await LogAndReplyError(command, ex, "PixivCookie更新异常");
}

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));
WebsiteDatas.LoadWebsite();
await command.ReplyFriendMessageAsync($"cookie更新完毕");
}

/// <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);
}
}

Expand Down
17 changes: 9 additions & 8 deletions Theresa3rd-Bot/TheresaBot.Main/Helper/StringHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
7 changes: 7 additions & 0 deletions Theresa3rd-Bot/TheresaBot.Main/Model/DTO/CookieDto.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace TheresaBot.Main.Model.DTO
{
public record CookieDto
{
public string Cookie { get; set; }
}
}
Loading

0 comments on commit 4a1a142

Please sign in to comment.