Skip to content

Commit

Permalink
优化部分代码规范 (#530)
Browse files Browse the repository at this point in the history
* 优化部分代码规范

* 添加buildKey

* Update runInLocal.md

* Update runInLocal.md

* Update runInLocal.md

* Update runInLocal.md

* 恢复donte启动方式的描述

* 增加部分空格

* 增加if前面的空格

* 使用new()

* 删除分号前的空格

---------

Co-authored-by: 王学懿 <[email protected]>
Co-authored-by: Ray <[email protected]>
  • Loading branch information
3 people authored Jun 11, 2023
1 parent ae95bca commit 433a5d7
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 48 deletions.
1 change: 1 addition & 0 deletions docs/runInLocal.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ P.S.这里的运行环境指的是 `.NET Runtime 6.0.0` ,安装方法可详见
请下载 `win-x86-x64.zip`,此文件已自包含(self-contained)运行环境。

解压后,在应用目录打开cmd或powershell,执行`.\Ray.BiliBiliTool.Console.exe --runTasks=Login`,扫码登录。
也可以直接双击`Ray.BiliBiliTool.Console.exe`来运行,建议使用windows自带的定时任务来执行它

## 3. Linux:

Expand Down
22 changes: 14 additions & 8 deletions src/Ray.BiliBiliTool.Config/Constants.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@

using System.Collections;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

Expand Down Expand Up @@ -35,26 +34,30 @@ public static class OptionsNames
/// <returns></returns>
public static Dictionary<string, string> GetExpDic()
{
var dic = new Dictionary<string, string>()
Dictionary<string, string> dic = new()
{
{"每日登录", "5"},
{"每日观看视频", "5"},
{"每日分享视频", "5"},
{"每日投币", "10"}
};

string buildKey(string key) => $"{OptionsNames.ExpDictionaryName}:{key}";

return dic.Select(x =>
new KeyValuePair<string, string>($"{OptionsNames.ExpDictionaryName}:{x.Key}", x.Value))
new KeyValuePair<string, string>(buildKey(x.Key), x.Value))
.ToDictionary(k => k.Key, v => v.Value);
}

/// <summary>
/// 投币接口的data.code返回以下这些状态码,则可以继续尝试投币
/// 如返回除这些之外的状态码,则终止投币流程,不进行无意义的尝试(比如返回-101:账号未登录;-102:账号被封停;-111:csrf校验失败等)
/// 投币接口的data.code返回以下这些状态码,则可以继续尝试投币<para></para>
/// 如返回除这些之外的状态码,则终止投币流程,不进行无意义的尝试<para></para>
/// (比如返回-101:账号未登录;-102:账号被封停;-111:csrf校验失败等)
/// </summary>
/// <returns></returns>
public static Dictionary<string, string> GetDonateCoinCanContinueStatusDic()
{
var dic = new Dictionary<string, string>()
Dictionary<string, string> dic = new()
{
{"0", "成功"},
{"-400", "请求错误"},
Expand All @@ -64,8 +67,11 @@ public static Dictionary<string, string> GetDonateCoinCanContinueStatusDic()
{"34004", "投币间隔太短"},
{"34005", "超过投币上限"}
};

string buildKey(string key) => $"{OptionsNames.DonateCoinCanContinueStatusDictionaryName}:{key}";

return dic.Select(x =>
new KeyValuePair<string, string>($"{OptionsNames.DonateCoinCanContinueStatusDictionaryName}:{x.Key}", x.Value))
new KeyValuePair<string, string>(buildKey(x.Key), x.Value))
.ToDictionary(k => k.Key, v => v.Value)
;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
namespace Ray.BiliBiliTool.Config
{
/// <summary>
/// 自定义的排除空值的环境变量提供者
/// 自定义的排除空值的环境变量提供者<para></para>
/// (使用GitHub Actions的脚本传入环境变量,空值会保留,所以这里自己写了一个用来替换掉默认的<see cref="EnvironmentVariablesConfigurationProvider"/>)
/// </summary>
public class EnvironmentVariablesExcludeEmptyConfigurationProvider : EnvironmentVariablesConfigurationProvider
Expand All @@ -19,7 +19,10 @@ public class EnvironmentVariablesExcludeEmptyConfigurationProvider : Environment
private readonly Func<KeyValuePair<string, string>, bool> _removeNullValue;
private readonly Func<KeyValuePair<string, string>, bool> _fifter;

public EnvironmentVariablesExcludeEmptyConfigurationProvider(string prefix = null, bool removeKeyPrefix = true) : base(prefix)
public EnvironmentVariablesExcludeEmptyConfigurationProvider(
string prefix = null,
bool removeKeyPrefix = true)
: base(prefix)
{
_removeKeyPrefix = removeKeyPrefix;
_prefix = prefix ?? string.Empty;
Expand All @@ -46,7 +49,8 @@ public override void Load()
/// <returns></returns>
private string NormalizeKey(string key)
{
if(_removeKeyPrefix) key = RemoveKeyPrefix(key);
if (_removeKeyPrefix)
key = RemoveKeyPrefix(key);
key = ReplaceKeyDelimiter(key);
return key;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,15 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.EnvironmentVariables;

namespace Ray.BiliBiliTool.Config
{
/// <summary>
/// 自定义的排除空值的环境变量配置源
/// 自定义的排除空值的环境变量配置源<para></para>
/// (用于取待默认的<see cref="EnvironmentVariablesConfigurationSource"/>)
/// </summary>
public class EnvironmentVariablesExcludeEmptyConfigurationSource : IConfigurationSource
Expand Down
12 changes: 6 additions & 6 deletions src/Ray.BiliBiliTool.Config/Options/DailyTaskOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ public class DailyTaskOptions
/// </summary>
public bool SaveCoinsWhenLv6 { get; set; } = false;


/// <summary>
/// 投币时是否点赞[false,true]
/// </summary>
Expand All @@ -50,6 +49,7 @@ public class DailyTaskOptions
public string AutoChargeUpId { get; set; }

private string _chargeComment;

/// <summary>
/// 充电后留言
/// </summary>
Expand Down Expand Up @@ -77,16 +77,16 @@ public string ChargeComment
/// </summary>
public string DevicePlatform { get; set; } = "android";


public List<long> SupportUpIdList
{
get
{
var re = new List<long>();
if (string.IsNullOrWhiteSpace(SupportUpIds) | SupportUpIds == "-1") return re;
List<long> re = new();
if (string.IsNullOrWhiteSpace(SupportUpIds) | SupportUpIds == "-1")
return re;

var array = SupportUpIds.Split(',');
foreach (var item in array)
string[] array = SupportUpIds.Split(',');
foreach (string item in array)
{
if (long.TryParse(item.Trim(), out long upId))
re.Add(upId);
Expand Down
36 changes: 21 additions & 15 deletions src/Ray.BiliBiliTool.Console/BiliBiliToolHostedService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,25 +45,25 @@ IHostApplicationLifetime applicationLifetime

public async Task StartAsync(CancellationToken cancellationToken)
{
var isNotifySingle = _configuration.GetSection("Notification:IsSingleAccountSingleNotify").Get<bool>();
bool isNotifySingle = _configuration.GetSection("Notification:IsSingleAccountSingleNotify").Get<bool>();

try
{
_logger.LogInformation("BiliBiliToolPro 开始运行...{newLine}", Environment.NewLine);

var pass = await PreCheckAsync(cancellationToken);
if (!pass) return;
bool pass = await PreCheckAsync(cancellationToken);
if (!pass)
return;

await RandomSleepAsync(cancellationToken);

var tasks = await ReadTargetTasksAsync(cancellationToken);
string[] tasks = await ReadTargetTasksAsync(cancellationToken);
_logger.LogInformation("【目标任务】{tasks}", string.Join(",", tasks));

if (tasks.Contains("Login"))
{
await DoTasksAsync(tasks, cancellationToken);
}

else
{
for (int i = 0; i < _cookieStrFactory.Count; i++)
Expand All @@ -78,7 +78,7 @@ public async Task StartAsync(CancellationToken cancellationToken)
{
LogAppInfo();

var accountName = _cookieStrFactory.Count > 1 ? $"账号【{_cookieStrFactory.CurrentNum}】" : "";
string accountName = _cookieStrFactory.Count > 1 ? $"账号【{_cookieStrFactory.CurrentNum}】" : "";
_logger.LogInformation("·开始推送·{task}·{user}", $"{_configuration["RunTasks"]}任务", accountName);
}
}
Expand Down Expand Up @@ -134,7 +134,8 @@ private Task<bool> PreCheckAsync(CancellationToken cancellationToken)

private async Task RandomSleepAsync(CancellationToken cancellationToken)
{
if (_configuration["RunTasks"].Contains("Login") || _configuration["RunTasks"].Contains("Test")) return;
if (_configuration["RunTasks"].Contains("Login") || _configuration["RunTasks"].Contains("Test"))
return;

if (_securityOptions.RandomSleepMaxMin > 0)
{
Expand All @@ -144,9 +145,14 @@ private async Task RandomSleepAsync(CancellationToken cancellationToken)
}
}

/// <summary>
/// 读取目标任务
/// </summary>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private Task<string[]> ReadTargetTasksAsync(CancellationToken cancellationToken)
{
var tasks = _configuration["RunTasks"]
string[] tasks = _configuration["RunTasks"]
.Split("&", options: StringSplitOptions.RemoveEmptyEntries);
if (tasks.Any())
{
Expand All @@ -159,11 +165,11 @@ private Task<string[]> ReadTargetTasksAsync(CancellationToken cancellationToken)

while (true)
{
var index = System.Console.ReadLine();
var suc = int.TryParse(index, out int num);
string index = System.Console.ReadLine();
bool suc = int.TryParse(index, out int num);
if (suc)
{
var code = TaskTypeFactory.GetCodeByIndex(num);
string code = TaskTypeFactory.GetCodeByIndex(num);
_configuration["RunTasks"] = code;
return Task.FromResult(new string[] { code });
}
Expand All @@ -174,17 +180,17 @@ private Task<string[]> ReadTargetTasksAsync(CancellationToken cancellationToken)

private async Task DoTasksAsync(string[] tasks, CancellationToken cancellationToken)
{
using var scope = _serviceProvider.CreateScope();
foreach (var task in tasks)
using IServiceScope scope = _serviceProvider.CreateScope();
foreach (string task in tasks)
{
var type = TaskTypeFactory.Create(task);
Type type = TaskTypeFactory.Create(task);
if (type == null)
{
_logger.LogWarning("任务不存在:{task}", task);
continue;
}

var appService = (IAppService)scope.ServiceProvider.GetRequiredService(type);
IAppService appService = (IAppService)scope.ServiceProvider.GetRequiredService(type);
await appService?.DoTaskAsync(cancellationToken);
}
}
Expand Down
33 changes: 24 additions & 9 deletions src/Ray.BiliBiliTool.Console/Program.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
Expand Down Expand Up @@ -56,7 +54,8 @@ internal static IHostBuilder CreateHostBuilder(string[] args)

//hostBuilder.UseContentRoot(Directory.GetCurrentDirectory());

//承载系统自身的配置:
#region 承载系统自身的配置

hostBuilder.ConfigureHostConfiguration(hostConfigurationBuilder =>
{
hostConfigurationBuilder.AddEnvironmentVariables(prefix: "DOTNET_");
Expand All @@ -67,22 +66,26 @@ internal static IHostBuilder CreateHostBuilder(string[] args)
}
});

//应用配置:
#endregion 承载系统自身的配置

#region 应用配置

hostBuilder.ConfigureAppConfiguration((hostBuilderContext, configurationBuilder) =>
{
Global.HostingEnvironment = hostBuilderContext.HostingEnvironment;
IHostEnvironment env = hostBuilderContext.HostingEnvironment;

//json文件:
string envName = hostBuilderContext.HostingEnvironment.EnvironmentName;
configurationBuilder.AddJsonFile("appsettings.json", true, true)
.AddJsonFile($"appsettings.{hostBuilderContext.HostingEnvironment.EnvironmentName}.json", true, true)
.AddJsonFile($"appsettings.{envName}.json", true, true)
;

//用户机密:
if (env.IsDevelopment() && env.ApplicationName?.Length > 0)
{
//var appAssembly = Assembly.Load(new AssemblyName(env.ApplicationName));
var appAssembly = Assembly.GetAssembly(typeof(Program));
Assembly appAssembly = Assembly.GetAssembly(typeof(Program));
configurationBuilder.AddUserSecrets(appAssembly, optional: true, reloadOnChange: true);
}

Expand All @@ -104,16 +107,23 @@ internal static IHostBuilder CreateHostBuilder(string[] args)
configurationBuilder.AddInMemoryCollection(Config.Constants.GetDonateCoinCanContinueStatusDic());
});

//日志:
#endregion 应用配置

#region 日志

hostBuilder.ConfigureLogging((hostBuilderContext, loggingBuilder) =>
{
Log.Logger = new LoggerConfiguration()
.ReadFrom.Configuration(hostBuilderContext.Configuration)
.CreateLogger();
SelfLog.Enable(x => System.Console.WriteLine(x ?? ""));
}).UseSerilog();
})
.UseSerilog();

#endregion 日志

#region DI容器

//DI容器:
hostBuilder.ConfigureServices((hostContext, services) =>
{
Global.ConfigurationRoot = (IConfigurationRoot)hostContext.Configuration;
Expand All @@ -126,9 +136,14 @@ internal static IHostBuilder CreateHostBuilder(string[] args)
services.AddAppServices();
});

#endregion DI容器

return hostBuilder;
}

/// <summary>
/// 输出本工具启动logo
/// </summary>
private static void PrintLogo()
{
System.Console.WriteLine(@" ____ ____ _ _____ _ ");
Expand Down

0 comments on commit 433a5d7

Please sign in to comment.