diff --git a/CHANGELOG.md b/CHANGELOG.md index 058a0b4d6..18cfb4a00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,13 @@ ## 2.2.0 - Migrate from dotnet 6.0 to dotnet 8.0 - Add Bruno to document the APIs +- Fix[#824]: Log cookie when qinglong save env failed ## 2.1.3 - Code refactory - Fix[#791]:修复VipBigPoint任务异常导致终止的问题 ## 2.1.2 - Feature: enhancement CICD scripts -- Fix[#728]: compatible with qinglong history versions +- Fix[#728]: compatible with qinglong history versions ## 2.1.1 - Feature: listen ctrl+c at the very beginning - Fix: fix qinglong read cron error diff --git a/src/Ray.BiliBiliTool.Application/LoginTaskAppService.cs b/src/Ray.BiliBiliTool.Application/LoginTaskAppService.cs index 06571f45c..884adc3d1 100644 --- a/src/Ray.BiliBiliTool.Application/LoginTaskAppService.cs +++ b/src/Ray.BiliBiliTool.Application/LoginTaskAppService.cs @@ -1,88 +1,63 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.FileProviders; -using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using QRCoder; using Ray.BiliBiliTool.Agent; -using Ray.BiliBiliTool.Agent.BiliBiliAgent.Dtos.Passport; -using Ray.BiliBiliTool.Agent.BiliBiliAgent.Dtos; -using Ray.BiliBiliTool.Agent.BiliBiliAgent.Interfaces; -using Ray.BiliBiliTool.Agent.QingLong; using Ray.BiliBiliTool.Application.Attributes; using Ray.BiliBiliTool.Application.Contracts; using Ray.BiliBiliTool.Infrastructure.Enums; using System.Threading; using Ray.BiliBiliTool.DomainService.Interfaces; -using Ray.BiliBiliTool.Infrastructure.Cookie; -namespace Ray.BiliBiliTool.Application +namespace Ray.BiliBiliTool.Application; + +public class LoginTaskAppService( + IConfiguration configuration, + ILogger logger, + ILoginDomainService loginDomainService) + : AppService, ILoginTaskAppService { - public class LoginTaskAppService : AppService, ILoginTaskAppService + [TaskInterceptor("扫码登录", TaskLevel.One)] + public override async Task DoTaskAsync(CancellationToken cancellationToken = default) { - private readonly ILogger _logger; - private readonly ILoginDomainService _loginDomainService; - private readonly IConfiguration _configuration; + //扫码登录 + var cookieInfo = await QrCodeLoginAsync(cancellationToken); + if (cookieInfo == null) return; - public LoginTaskAppService( - IConfiguration configuration, - ILogger logger, - ILoginDomainService loginDomainService) - { - _configuration = configuration; - _logger = logger; - _loginDomainService = loginDomainService; - } + //set cookie + cookieInfo = await SetCookiesAsync(cookieInfo, cancellationToken); - [TaskInterceptor("扫码登录", TaskLevel.One)] - public override async Task DoTaskAsync(CancellationToken cancellationToken) - { - //扫码登录 - var cookieInfo = await QrCodeLoginAsync(cancellationToken); - if (cookieInfo == null) return; + //持久化cookie + await SaveCookieAsync(cookieInfo, cancellationToken); + } - //set cookie - cookieInfo = await SetCookiesAsync(cookieInfo, cancellationToken); + [TaskInterceptor("获取二维码")] + private async Task QrCodeLoginAsync(CancellationToken cancellationToken) + { + var biliCookie = await loginDomainService.LoginByQrCodeAsync(cancellationToken); + return biliCookie; + } - //持久化cookie - await SaveCookieAsync(cookieInfo, cancellationToken); - } + [TaskInterceptor("Set Cookie")] + private async Task SetCookiesAsync(BiliCookie biliCookie, CancellationToken cancellationToken) + { + var ck= await loginDomainService.SetCookieAsync(biliCookie, cancellationToken); + return ck; + } - [TaskInterceptor("获取二维码", TaskLevel.Two)] - protected async Task QrCodeLoginAsync(CancellationToken cancellationToken) - { - var biliCookie = await _loginDomainService.LoginByQrCodeAsync(cancellationToken); - return biliCookie; - } + [TaskInterceptor("持久化Cookie")] + private async Task SaveCookieAsync(BiliCookie ckInfo, CancellationToken cancellationToken) + { + var platformType = configuration.GetSection("PlateformType").Get(); + logger.LogInformation("当前运行平台:{platform}",platformType); - [TaskInterceptor("Set Cookie", TaskLevel.Two)] - protected async Task SetCookiesAsync(BiliCookie biliCookie, CancellationToken cancellationToken) + //更新cookie到青龙env + if (platformType == PlatformType.QingLong) { - var ck= await _loginDomainService.SetCookieAsync(biliCookie, cancellationToken); - return ck; + await loginDomainService.SaveCookieToQinLongAsync(ckInfo, cancellationToken); + return; } - [TaskInterceptor("持久化Cookie", TaskLevel.Two)] - protected async Task SaveCookieAsync(BiliCookie ckInfo, CancellationToken cancellationToken) - { - var platformType = _configuration.GetSection("PlateformType").Get(); - _logger.LogInformation("当前运行平台:{platform}",platformType); - - //更新cookie到青龙env - if (platformType == PlatformType.QingLong) - { - await _loginDomainService.SaveCookieToQinLongAsync(ckInfo, cancellationToken); - return; - } - - //更新cookie到json - await _loginDomainService.SaveCookieToJsonFileAsync(ckInfo, cancellationToken); - } + //更新cookie到json + await loginDomainService.SaveCookieToJsonFileAsync(ckInfo, cancellationToken); } -} +} \ No newline at end of file diff --git a/src/Ray.BiliBiliTool.DomainService/Interfaces/ILoginDomainService.cs b/src/Ray.BiliBiliTool.DomainService/Interfaces/ILoginDomainService.cs index f323b8e16..0fc4215f6 100644 --- a/src/Ray.BiliBiliTool.DomainService/Interfaces/ILoginDomainService.cs +++ b/src/Ray.BiliBiliTool.DomainService/Interfaces/ILoginDomainService.cs @@ -1,38 +1,38 @@ using System.Threading; using System.Threading.Tasks; using Ray.BiliBiliTool.Agent; -using Ray.BiliBiliTool.Agent.BiliBiliAgent.Dtos; -namespace Ray.BiliBiliTool.DomainService.Interfaces +namespace Ray.BiliBiliTool.DomainService.Interfaces; + +/// +/// 账户 +/// +public interface ILoginDomainService : IDomainService { /// - /// 账户 + /// 扫描二维码登录 /// - public interface ILoginDomainService : IDomainService - { - /// - /// 扫描二维码登录 - /// - /// - Task LoginByQrCodeAsync(CancellationToken cancellationToken); + /// + Task LoginByQrCodeAsync(CancellationToken cancellationToken); - /// - /// Set Cookie - /// - /// - /// - Task SetCookieAsync(BiliCookie cookie, CancellationToken cancellationToken); + /// + /// Set Cookie + /// + /// + /// + Task SetCookieAsync(BiliCookie cookie, CancellationToken cancellationToken); - /// - /// 持久化Cookie到配置文件 - /// - /// - Task SaveCookieToJsonFileAsync(BiliCookie ckInfo, CancellationToken cancellationToken); + /// + /// 持久化Cookie到配置文件 + /// + /// + Task SaveCookieToJsonFileAsync(BiliCookie ckInfo, CancellationToken cancellationToken); - /// - /// 持久化Cookie到青龙环境变量 - /// - /// - Task SaveCookieToQinLongAsync(BiliCookie ckInfo, CancellationToken cancellationToken); - } -} + /// + /// 持久化Cookie到青龙环境变量 + /// + /// + /// + /// + Task SaveCookieToQinLongAsync(BiliCookie ckInfo, CancellationToken cancellationToken); +} \ No newline at end of file diff --git a/src/Ray.BiliBiliTool.DomainService/LoginDomainService.cs b/src/Ray.BiliBiliTool.DomainService/LoginDomainService.cs index 6a834650c..b0a767de0 100644 --- a/src/Ray.BiliBiliTool.DomainService/LoginDomainService.cs +++ b/src/Ray.BiliBiliTool.DomainService/LoginDomainService.cs @@ -19,219 +19,203 @@ using Ray.BiliBiliTool.Agent.QingLong; using Ray.BiliBiliTool.Infrastructure.Cookie; -namespace Ray.BiliBiliTool.DomainService +namespace Ray.BiliBiliTool.DomainService; + +/// +/// 账户 +/// +public class LoginDomainService( + ILogger logger, + IPassportApi passportApi, + IHostEnvironment hostingEnvironment, + IQingLongApi qingLongApi, + IHomeApi homeApi, + IConfiguration configuration) + : ILoginDomainService { - /// - /// 账户 - /// - public class LoginDomainService : ILoginDomainService + public async Task LoginByQrCodeAsync(CancellationToken cancellationToken) { - private readonly ILogger _logger; - private readonly IPassportApi _passportApi; - private readonly IHostEnvironment _hostingEnvironment; - private readonly IQingLongApi _qingLongApi; - private readonly IHomeApi _homeApi; - private readonly IConfiguration _configuration; - - public LoginDomainService( - ILogger logger, - IPassportApi passportApi, - IHostEnvironment hostingEnvironment, - IQingLongApi qingLongApi, - IHomeApi homeApi, - IConfiguration configuration) + BiliCookie cookieInfo = null; + + var re = await passportApi.GenerateQrCode(); + if (re.Code != 0) { - _logger = logger; - _passportApi = passportApi; - _hostingEnvironment = hostingEnvironment; - _qingLongApi = qingLongApi; - _homeApi = homeApi; - _configuration = configuration; + logger.LogWarning("获取二维码失败:{msg}", re.ToJsonStr()); + return null; } - public async Task LoginByQrCodeAsync(CancellationToken cancellationToken) - { - BiliCookie cookieInfo = null; + var url = re.Data.Url; + GenerateQrCode(url); - var re = await _passportApi.GenerateQrCode(); - if (re.Code != 0) - { - _logger.LogWarning("获取二维码失败:{msg}", re.ToJsonStr()); - return null; - } + var online = GetOnlinePic(url); + logger.LogInformation(Environment.NewLine + Environment.NewLine); + logger.LogInformation("如果上方二维码显示异常,或扫描失败,请使用浏览器访问如下链接,查看高清二维码:"); + logger.LogInformation(online + Environment.NewLine + Environment.NewLine); - var url = re.Data.Url; - GenerateQrCode(url); + var waitTimes = 10; + logger.LogInformation("我数到{num},动作快点", waitTimes); + for (int i = 0; i < waitTimes; i++) + { + logger.LogInformation("[{num}]等待扫描...", i + 1); - var online = GetOnlinePic(url); - _logger.LogInformation(Environment.NewLine + Environment.NewLine); - _logger.LogInformation("如果上方二维码显示异常,或扫描失败,请使用浏览器访问如下链接,查看高清二维码:"); - _logger.LogInformation(online + Environment.NewLine + Environment.NewLine); + await Task.Delay(5 * 1000, cancellationToken); - var waitTimes = 10; - _logger.LogInformation("我数到{num},动作快点", waitTimes); - for (int i = 0; i < waitTimes; i++) + var check = await passportApi.CheckQrCodeHasScaned(re.Data.Qrcode_key); + if (!check.IsSuccessStatusCode) { - _logger.LogInformation("[{num}]等待扫描...", i + 1); - - await Task.Delay(5 * 1000, cancellationToken); - - var check = await _passportApi.CheckQrCodeHasScaned(re.Data.Qrcode_key); - if (!check.IsSuccessStatusCode) - { - _logger.LogWarning("调用检测接口异常"); - continue; - } - - var content = JsonConvert.DeserializeObject>(await check.Content.ReadAsStringAsync(cancellationToken)); - if (content.Code != 0) - { - _logger.LogWarning("调用检测接口异常:{msg}", check.ToJsonStr()); - break; - } + logger.LogWarning("调用检测接口异常"); + continue; + } - if (content.Data.Code == 86038)//已失效 - { - _logger.LogInformation(content.Data.Message); - break; - } + var content = JsonConvert.DeserializeObject>(await check.Content.ReadAsStringAsync(cancellationToken)); + if (content.Code != 0) + { + logger.LogWarning("调用检测接口异常:{msg}", check.ToJsonStr()); + break; + } - if (content.Data.Code == 0) - { - _logger.LogInformation("扫描成功!"); - IEnumerable cookies = check.Headers.SingleOrDefault(header => header.Key == "Set-Cookie").Value; + if (content.Data.Code == 86038)//已失效 + { + logger.LogInformation(content.Data.Message); + break; + } - var cookieStr = CookieInfo.ConvertSetCkHeadersToCkStr(cookies); - cookieInfo = new BiliCookie(cookieStr); - cookieInfo.Check(); + if (content.Data.Code == 0) + { + logger.LogInformation("扫描成功!"); + IEnumerable cookies = check.Headers.SingleOrDefault(header => header.Key == "Set-Cookie").Value; - break; - } + var cookieStr = CookieInfo.ConvertSetCkHeadersToCkStr(cookies); + cookieInfo = new BiliCookie(cookieStr); + cookieInfo.Check(); - _logger.LogInformation("{msg}", content.Data.Message + Environment.NewLine); + break; } - return cookieInfo; + logger.LogInformation("{msg}", content.Data.Message + Environment.NewLine); } - public async Task SetCookieAsync(BiliCookie biliCookie, CancellationToken cancellationToken) + return cookieInfo; + } + + public async Task SetCookieAsync(BiliCookie biliCookie, CancellationToken cancellationToken) + { + try { - try - { - var homePage = await _homeApi.GetHomePageAsync(biliCookie.ToString()); - if (homePage.IsSuccessStatusCode) - { - _logger.LogInformation("访问主站成功"); - IEnumerable setCookieHeaders = homePage.Headers.SingleOrDefault(header => header.Key == "Set-Cookie").Value; - biliCookie.MergeCurrentCookieBySetCookieHeaders(setCookieHeaders); - _logger.LogInformation("SetCookie成功"); - return biliCookie; - } - _logger.LogError("访问主站失败:{msg}", homePage.ToJsonStr()); - } - catch (Exception e) + var homePage = await homeApi.GetHomePageAsync(biliCookie.ToString()); + if (homePage.IsSuccessStatusCode) { - //buvid只影响分享和投币,可以吞掉异常 - _logger.LogError(e.ToJsonStr()); + logger.LogInformation("访问主站成功"); + IEnumerable setCookieHeaders = homePage.Headers.SingleOrDefault(header => header.Key == "Set-Cookie").Value; + biliCookie.MergeCurrentCookieBySetCookieHeaders(setCookieHeaders); + logger.LogInformation("SetCookie成功"); + return biliCookie; } + logger.LogError("访问主站失败:{msg}", homePage.ToJsonStr()); + } + catch (Exception e) + { + //buvid只影响分享和投币,可以吞掉异常 + logger.LogError(e.ToJsonStr()); + } + + return biliCookie; + } - return biliCookie; + public async Task SaveCookieToJsonFileAsync(BiliCookie ckInfo, CancellationToken cancellationToken) + { + //读取json + var path = hostingEnvironment.ContentRootPath; + var indexOfBin = path.LastIndexOf("bin"); + if (indexOfBin != -1) path = path[..indexOfBin]; + var fileProvider = new PhysicalFileProvider(path); + IFileInfo fileInfo = fileProvider.GetFileInfo("cookies.json"); + logger.LogInformation("目标json地址:{path}", fileInfo.PhysicalPath); + + if (!fileInfo.Exists) + { + await using var stream = File.Create(fileInfo.PhysicalPath); + await using var sw = new StreamWriter(stream); + await sw.WriteAsync($"{{{Environment.NewLine}}}"); } - public async Task SaveCookieToJsonFileAsync(BiliCookie ckInfo, CancellationToken cancellationToken) + string json; + await using (var stream = new FileStream(fileInfo.PhysicalPath, FileMode.Open)) { - //读取json - var path = _hostingEnvironment.ContentRootPath; - var indexOfBin = path.LastIndexOf("bin"); - if (indexOfBin != -1) path = path[..indexOfBin]; - var fileProvider = new PhysicalFileProvider(path); - IFileInfo fileInfo = fileProvider.GetFileInfo("cookies.json"); - _logger.LogInformation("目标json地址:{path}", fileInfo.PhysicalPath); - - if (!fileInfo.Exists) - { - await using var stream = File.Create(fileInfo.PhysicalPath); - await using var sw = new StreamWriter(stream); - await sw.WriteAsync($"{{{Environment.NewLine}}}"); - } + using var reader = new StreamReader(stream); + json = await reader.ReadToEndAsync(); + } + var lines = json.Split(Environment.NewLine).ToList(); - string json; - await using (var stream = new FileStream(fileInfo.PhysicalPath, FileMode.Open)) - { - using var reader = new StreamReader(stream); - json = await reader.ReadToEndAsync(); - } - var lines = json.Split(Environment.NewLine).ToList(); + var indexOfCkConfigKey = lines.FindIndex(x => x.TrimStart().StartsWith("\"BiliBiliCookies\"")); + if (indexOfCkConfigKey == -1) + { + logger.LogInformation("未配置过cookie,初始化并新增"); - var indexOfCkConfigKey = lines.FindIndex(x => x.TrimStart().StartsWith("\"BiliBiliCookies\"")); - if (indexOfCkConfigKey == -1) + var indexOfInsert = lines.FindIndex(x => x.TrimStart().StartsWith("{")); + lines.InsertRange(indexOfInsert + 1, new List() { - _logger.LogInformation("未配置过cookie,初始化并新增"); - - var indexOfInsert = lines.FindIndex(x => x.TrimStart().StartsWith("{")); - lines.InsertRange(indexOfInsert + 1, new List() - { - " \"BiliBiliCookies\":[", - $@" ""{ckInfo.CookieStr}"",", - " ]," - }); - - await SaveJson(lines, fileInfo); - _logger.LogInformation("新增成功!"); - return; - } + " \"BiliBiliCookies\":[", + $@" ""{ckInfo.CookieStr}"",", + " ]," + }); - ckInfo.CookieItemDictionary.TryGetValue("DedeUserID", out string userId); - userId ??= ckInfo.CookieStr; - var indexOfCkConfigEnd = lines.FindIndex(indexOfCkConfigKey, x => x.TrimStart().StartsWith("]")); - var indexOfTargetCk = lines.FindIndex(indexOfCkConfigKey, - indexOfCkConfigEnd - indexOfCkConfigKey, - x => x.Contains(userId) && !x.TrimStart().StartsWith("//")); + await SaveJson(lines, fileInfo); + logger.LogInformation("新增成功!"); + return; + } - if (indexOfTargetCk == -1) - { - _logger.LogInformation("不存在该用户,新增cookie"); - lines.Insert(indexOfCkConfigEnd, $@" ""{ckInfo.CookieStr}"","); - await SaveJson(lines, fileInfo); - _logger.LogInformation("新增成功!"); - return; - } + ckInfo.CookieItemDictionary.TryGetValue("DedeUserID", out string userId); + userId ??= ckInfo.CookieStr; + var indexOfCkConfigEnd = lines.FindIndex(indexOfCkConfigKey, x => x.TrimStart().StartsWith("]")); + var indexOfTargetCk = lines.FindIndex(indexOfCkConfigKey, + indexOfCkConfigEnd - indexOfCkConfigKey, + x => x.Contains(userId) && !x.TrimStart().StartsWith("//")); - _logger.LogInformation("已存在该用户,更新cookie"); - lines[indexOfTargetCk] = $@" ""{ckInfo.CookieStr}"","; + if (indexOfTargetCk == -1) + { + logger.LogInformation("不存在该用户,新增cookie"); + lines.Insert(indexOfCkConfigEnd, $@" ""{ckInfo.CookieStr}"","); await SaveJson(lines, fileInfo); - _logger.LogInformation("更新成功!"); + logger.LogInformation("新增成功!"); + return; } - public async Task SaveCookieToQinLongAsync(BiliCookie ckInfo, CancellationToken cancellationToken) + logger.LogInformation("已存在该用户,更新cookie"); + lines[indexOfTargetCk] = $@" ""{ckInfo.CookieStr}"","; + await SaveJson(lines, fileInfo); + logger.LogInformation("更新成功!"); + } + + public async Task SaveCookieToQinLongAsync(BiliCookie ckInfo, CancellationToken cancellationToken) + { + try { - //拿token var token = await GetQingLongAuthTokenAsync(); - - if (token.IsNullOrEmpty()) return; + if (token.IsNullOrEmpty()) + { + throw new Exception("获取青龙token失败"); + } token = $"Bearer {token}"; - //查env - var re = await _qingLongApi.GetEnvs("Ray_BiliBiliCookies__", token); - - if (re.Code != 200) + var qlEnvList = await qingLongApi.GetEnvs("Ray_BiliBiliCookies__", token); + if (qlEnvList.Code != 200) { - _logger.LogInformation($"查询环境变量失败:{re}", re.ToJsonStr()); - return; + throw new Exception($"查询环境变量失败:{qlEnvList.ToJsonStr()}"); } - _logger.LogDebug(re.Data.ToJsonStr()); - _logger.LogDebug(ckInfo.ToString()); + logger.LogDebug(qlEnvList.Data.ToJsonStr()); + logger.LogDebug(ckInfo.ToString()); - var list = re.Data.Where(x => x.name.StartsWith("Ray_BiliBiliCookies__")).ToList(); + var list = qlEnvList.Data.Where(x => x.name.StartsWith("Ray_BiliBiliCookies__")).ToList(); QingLongEnv oldEnv = list.FirstOrDefault(x => x.value.Contains(ckInfo.UserId)); if (oldEnv != null) { - _logger.LogInformation("用户已存在,更新cookie"); - _logger.LogInformation("Key:{key}", oldEnv.name); - var update = new UpdateQingLongEnv() + logger.LogInformation("用户已存在,更新cookie"); + logger.LogInformation("Key:{key}", oldEnv.name); + var update = new UpdateQingLongEnv { id = oldEnv.id, name = oldEnv.name, @@ -241,13 +225,13 @@ public async Task SaveCookieToQinLongAsync(BiliCookie ckInfo, CancellationToken : oldEnv.remarks, }; - var updateRe = await _qingLongApi.UpdateEnvs(update, token); - _logger.LogInformation(updateRe.Code == 200 ? "更新成功!" : updateRe.ToJsonStr()); + var updateRe = await qingLongApi.UpdateEnvs(update, token); + logger.LogInformation(updateRe.Code == 200 ? "更新成功!" : updateRe.ToJsonStr()); - return; + return true; } - _logger.LogInformation("用户不存在,新增cookie"); + logger.LogInformation("用户不存在,新增cookie"); var maxNum = -1; if (list.Any()) { @@ -258,153 +242,164 @@ public async Task SaveCookieToQinLongAsync(BiliCookie ckInfo, CancellationToken return parseSuc ? envNum : 0; }).Max(); } + var name = $"Ray_BiliBiliCookies__{maxNum + 1}"; - _logger.LogInformation("Key:{key}", name); + logger.LogInformation("Key:{key}", name); - var add = new AddQingLongEnv() - { - name = name, - value = ckInfo.CookieStr, - remarks = $"bili-{ckInfo.UserId}" - }; - var addRe = await _qingLongApi.AddEnvs(new List { add }, token); - _logger.LogInformation(addRe.Code == 200 ? "新增成功!" : addRe.ToJsonStr()); + var add = new AddQingLongEnv {name = name, value = ckInfo.CookieStr, remarks = $"bili-{ckInfo.UserId}"}; + var addRe = await qingLongApi.AddEnvs([add], token); + logger.LogInformation(addRe.Code == 200 ? "新增成功!" : addRe.ToJsonStr()); + return true; + } + catch + { + await PrintIfSaveCookieFailAsync(ckInfo, cancellationToken); + return false; } + } - #region private + #region private - private void GenerateQrCode(string str) - { - var qrGenerator = new QRCodeGenerator(); - QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, QRCodeGenerator.ECCLevel.L); + private void GenerateQrCode(string str) + { + var qrGenerator = new QRCodeGenerator(); + QRCodeData qrCodeData = qrGenerator.CreateQrCode(str, QRCodeGenerator.ECCLevel.L); - _logger.LogInformation("AsciiQRCode:"); - //var qrCode = new AsciiQRCode(qrCodeData); - //var qrCodeStr = qrCode.GetGraphic(1, drawQuietZones: false); - //_logger.LogInformation(Environment.NewLine + qrCodeStr); + logger.LogInformation("AsciiQRCode:"); + //var qrCode = new AsciiQRCode(qrCodeData); + //var qrCodeStr = qrCode.GetGraphic(1, drawQuietZones: false); + //_logger.LogInformation(Environment.NewLine + qrCodeStr); - //Console.WriteLine("Console:"); - //Print(qrCodeData); - PrintSmall(qrCodeData); - } + //Console.WriteLine("Console:"); + //Print(qrCodeData); + PrintSmall(qrCodeData); + } - private void Print(QRCodeData qrCodeData) + private void Print(QRCodeData qrCodeData) + { + Console.BackgroundColor = ConsoleColor.White; + for (int i = 0; i < qrCodeData.ModuleMatrix.Count + 2; i++) Console.Write(" ");//中文全角的空格符 + Console.WriteLine(); + for (int j = 0; j < qrCodeData.ModuleMatrix.Count; j++) { - Console.BackgroundColor = ConsoleColor.White; - for (int i = 0; i < qrCodeData.ModuleMatrix.Count + 2; i++) Console.Write(" ");//中文全角的空格符 - Console.WriteLine(); - for (int j = 0; j < qrCodeData.ModuleMatrix.Count; j++) + for (int i = 0; i < qrCodeData.ModuleMatrix.Count; i++) { - for (int i = 0; i < qrCodeData.ModuleMatrix.Count; i++) - { - //char charToPoint = qrCode.Matrix[i, j] ? '█' : ' '; - Console.Write(i == 0 ? " " : "");//中文全角的空格符 - Console.BackgroundColor = qrCodeData.ModuleMatrix[i][j] ? ConsoleColor.Black : ConsoleColor.White; - Console.Write(' ');//中文全角的空格符 - Console.BackgroundColor = ConsoleColor.White; - Console.Write(i == qrCodeData.ModuleMatrix.Count - 1 ? " " : "");//中文全角的空格符 - } - Console.WriteLine(); + //char charToPoint = qrCode.Matrix[i, j] ? '█' : ' '; + Console.Write(i == 0 ? " " : "");//中文全角的空格符 + Console.BackgroundColor = qrCodeData.ModuleMatrix[i][j] ? ConsoleColor.Black : ConsoleColor.White; + Console.Write(' ');//中文全角的空格符 + Console.BackgroundColor = ConsoleColor.White; + Console.Write(i == qrCodeData.ModuleMatrix.Count - 1 ? " " : "");//中文全角的空格符 } - for (int i = 0; i < qrCodeData.ModuleMatrix.Count + 2; i++) Console.Write(" ");//中文全角的空格符 - Console.WriteLine(); } + for (int i = 0; i < qrCodeData.ModuleMatrix.Count + 2; i++) Console.Write(" ");//中文全角的空格符 - private void PrintSmall(QRCodeData qrCodeData) + Console.WriteLine(); + } + + private void PrintSmall(QRCodeData qrCodeData) + { + //黑黑(" ") + //白白("█") + //黑白("▄") + //白黑("▀") + var dic = new Dictionary() { - //黑黑(" ") - //白白("█") - //黑白("▄") - //白黑("▀") - var dic = new Dictionary() - { - {"11", ' '}, - {"00", '█'}, - {"10", '▄'}, - {"01", '▀'},//todo:win平台的cmd会显示?,是已知问题,待想办法解决 - //{"01", '^'},//▼▔ - }; + {"11", ' '}, + {"00", '█'}, + {"10", '▄'}, + {"01", '▀'},//todo:win平台的cmd会显示?,是已知问题,待想办法解决 + //{"01", '^'},//▼▔ + }; - var count = qrCodeData.ModuleMatrix.Count; + var count = qrCodeData.ModuleMatrix.Count; - var list = new List(); - for (int rowNum = 0; rowNum < count; rowNum++) + var list = new List(); + for (int rowNum = 0; rowNum < count; rowNum++) + { + var rowStr = ""; + for (int colNum = 0; colNum < count; colNum++) { - var rowStr = ""; - for (int colNum = 0; colNum < count; colNum++) - { - var num = qrCodeData.ModuleMatrix[colNum][rowNum] ? "1" : "0"; - var numDown = "0"; - if (rowNum + 1 < count) - numDown = qrCodeData.ModuleMatrix[colNum][rowNum + 1] ? "1" : "0"; - - rowStr += dic[num + numDown]; - } - list.Add(rowStr); - rowNum++; - } + var num = qrCodeData.ModuleMatrix[colNum][rowNum] ? "1" : "0"; + var numDown = "0"; + if (rowNum + 1 < count) + numDown = qrCodeData.ModuleMatrix[colNum][rowNum + 1] ? "1" : "0"; - _logger.LogInformation(Environment.NewLine + string.Join(Environment.NewLine, list)); + rowStr += dic[num + numDown]; + } + list.Add(rowStr); + rowNum++; } - private string GetOnlinePic(string str) - { - var encode = System.Web.HttpUtility.UrlEncode(str); ; - return $"https://tool.lu/qrcode/basic.html?text={encode}"; - } + logger.LogInformation(Environment.NewLine + string.Join(Environment.NewLine, list)); + } - private string GetCookieStr(IEnumerable setCookies) - { - var ckItemList = new List(); - foreach (var item in setCookies) - { - ckItemList.Add(item.Split(';').FirstOrDefault()); - } - var biliCk = string.Join("; ", ckItemList); - return biliCk; - } + private string GetOnlinePic(string str) + { + var encode = System.Web.HttpUtility.UrlEncode(str); ; + return $"https://tool.lu/qrcode/basic.html?text={encode}"; + } - private async Task SaveJson(List lines, IFileInfo fileInfo) + private string GetCookieStr(IEnumerable setCookies) + { + var ckItemList = new List(); + foreach (var item in setCookies) { - var newJson = string.Join(Environment.NewLine, lines); - - await using var sw = new StreamWriter(fileInfo.PhysicalPath); - await sw.WriteAsync(newJson); + ckItemList.Add(item.Split(';').FirstOrDefault()); } + var biliCk = string.Join("; ", ckItemList); + return biliCk; + } - #region qinglong - - private async Task GetQingLongAuthTokenAsync() - { - var token = ""; + private async Task SaveJson(List lines, IFileInfo fileInfo) + { + var newJson = string.Join(Environment.NewLine, lines); - var qlDir = _configuration["QL_DIR"] ?? "/ql"; + await using var sw = new StreamWriter(fileInfo.PhysicalPath); + await sw.WriteAsync(newJson); + } - string authFile = qlDir; - if (_hostingEnvironment.ContentRootPath.Contains($"{qlDir}/data/")) - { - authFile = Path.Combine(authFile, "data"); - } - authFile = Path.Combine(authFile, "config/auth.json"); + #region qinglong - if (!File.Exists(authFile)) - { - _logger.LogWarning("获取青龙授权失败,文件不在:{authFile}", authFile); - return token; - } + private async Task GetQingLongAuthTokenAsync() + { + var token = ""; - var authJson = await File.ReadAllTextAsync(authFile); + var qlDir = configuration["QL_DIR"] ?? "/ql"; - var jb = JsonConvert.DeserializeObject(authJson); - token = jb["token"]?.ToString(); + string authFile = qlDir; + if (hostingEnvironment.ContentRootPath.Contains($"{qlDir}/data/")) + { + authFile = Path.Combine(authFile, "data"); + } + authFile = Path.Combine(authFile, "config/auth.json"); + if (!File.Exists(authFile)) + { + logger.LogWarning("获取青龙授权失败,文件不存在:{authFile}", authFile); return token; } - #endregion + var authJson = await File.ReadAllTextAsync(authFile); - #endregion + var jb = JsonConvert.DeserializeObject(authJson); + token = jb["token"]?.ToString(); + return token; } -} + + private Task PrintIfSaveCookieFailAsync(BiliCookie ckInfo, CancellationToken cancellationToken) + { + logger.LogError("持久化失败,青龙版本高于2.18,请手动添加环境变量到青龙"); + logger.LogWarning("变量Key:{key}", "Ray_BiliBiliCookies__0"); + logger.LogWarning("变量值:{value}", ckInfo.CookieStr); + logger.LogWarning("如果Key已存在,请自行+1,如Ray_BiliBiliCookies__1,Ray_BiliBiliCookies__2..."); + return Task.CompletedTask; + } + + #endregion + + #endregion + +} \ No newline at end of file