Skip to content

Commit

Permalink
添加直播监控工具;优化稳定性
Browse files Browse the repository at this point in the history
  • Loading branch information
withsalt committed Apr 27, 2022
1 parent cf1d228 commit e06befe
Show file tree
Hide file tree
Showing 18 changed files with 175 additions and 93 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<PublishDir>bin\Release\publish\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net6.0</TargetFramework>
<SelfContained>false</SelfContained>
<SelfContained>true</SelfContained>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<PublishSingleFile>true</PublishSingleFile>
<PublishReadyToRun>false</PublishReadyToRun>
<PublishTrimmed>false</PublishTrimmed>
</PropertyGroup>
</Project>
2 changes: 2 additions & 0 deletions src/BilibiliLiveCommon/Config/CacheKeyConstant.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,7 @@ public class CacheKeyConstant
public const string COOKIE_KEY = "COOKIE_KEY";

public const string LIVE_STATUS_KEY = "LIVE_STATUS_KEY";

public const string MAIL_SEND_CACHE_KEY = "MAIL_{0}_SEND_STATUS_KEY";
}
}
2 changes: 1 addition & 1 deletion src/BilibiliLiveCommon/Services/BilibiliLiveApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ private async Task<LiveAreaItem> CheckArea(int areaId)
private async Task SlowDownOperation(string operationName)
{
int sleepMsec = new Random().Next(5000, 10000);
_logger.LogInformation($"执行{operationName}操作完成,休眠{sleepMsec / 1000}(避免频繁操作)。");
_logger.LogDebug($"执行{operationName}操作完成,休眠{sleepMsec / 1000},避免被B站频繁操作。");
await Task.Delay(sleepMsec);
}

Expand Down
40 changes: 27 additions & 13 deletions src/BilibiliLiveMonitor/Jobs/MonitorClientJob.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using BilibiliLiveCommon.Model;
using BilibiliLiveCommon.Services.Interface;
using BilibiliLiveCommon.Config;
using BilibiliLiveCommon.Utils;

namespace BilibiliLiveMonitor.Jobs
{
Expand Down Expand Up @@ -37,7 +38,7 @@ public async Task Execute(IJobExecutionContext context)
try
{
_logger.LogInformation($"开始查询直播间{_liveSettings.RoomId}状态....");
if(_liveSettings.RoomId <= 0)
if (_liveSettings.RoomId <= 0)
{
throw new Exception("获取需要查询的直播房间号失败,请检查配置文件是否正确配置房间号。");
}
Expand All @@ -46,24 +47,19 @@ public async Task Execute(IJobExecutionContext context)
{
throw new Exception("获取直播间信息失败。");
}
_logger.LogInformation($"获取直播间{_liveSettings.RoomId}状态成功,当前状态:{(playInfo.is_living ? "直播中" : "停止直播")}");
RoomPlayInfo lastPlayInfo = _cache.Get<RoomPlayInfo>(CacheKeyConstant.LIVE_STATUS_KEY);
if(lastPlayInfo == null)
if (lastPlayInfo == null)
{
//第一次存缓存强制设置直播状态为1,免得第一次开启时就发送通知
playInfo.live_status = 1;
_cache.Set(CacheKeyConstant.LIVE_STATUS_KEY, playInfo);
return;
}
if(lastPlayInfo.is_living != playInfo.is_living)
if (lastPlayInfo.is_living != playInfo.is_living)
{
if (playInfo.is_living)
{
//开启了直播
}
else
{
//直播已关闭
}
await SendEmailNotice(playInfo);
_cache.Set(CacheKeyConstant.LIVE_STATUS_KEY, playInfo);
}
}
catch (Exception ex)
Expand All @@ -77,11 +73,29 @@ public async Task Execute(IJobExecutionContext context)
/// </summary>
/// <param name="reason"></param>
/// <returns></returns>
private async Task SendEmailNotice(string reason)
private async Task SendEmailNotice(RoomPlayInfo info)
{
try
{
var result = await _email.Send("直播停止通知", reason);
_logger.LogInformation($"直播间{info.room_id}直播状态发生改变,发送通知邮件");
String reason = "";
string cacheKey = string.Format(CacheKeyConstant.MAIL_SEND_CACHE_KEY, info.live_status);
if (info.is_living)
{
reason = $"开播提醒:\r\n您订阅的直播间(https://live.bilibili.com/{info.room_id})开始直播啦。";
}
else
{
reason = $"关闭提醒:\r\n您订阅的直播间(https://live.bilibili.com/{info.room_id})已经停止直播。";
}
long lastSendTime = _cache.Get<long>(cacheKey);
if (TimeUtil.Timestamp() - lastSendTime < 600)
{
_logger.LogWarning($"邮件发送过于频繁,忽略本次发送。{reason}");
return;
}
var result = await _email.Send("直播订阅通知", reason);
_cache.Set(cacheKey, TimeUtil.Timestamp());
if (result.Item1 != SendStatus.Success)
{
throw new Exception(result.Item2);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<TargetFramework>net6.0</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>true</SelfContained>
<PublishSingleFile>false</PublishSingleFile>
<PublishSingleFile>true</PublishSingleFile>
<PublishTrimmed>false</PublishTrimmed>
<PublishReadyToRun>false</PublishReadyToRun>
</PropertyGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/BilibiliLiveMonitor/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
}
},
"AppSettings": {
"IntervalTime": 30, //检查间隔时间 单位:秒
"IntervalTime": 60, //检查间隔时间 单位:秒
"IsEnableEmailNotice": false,
"EmailConfig": {
"SmtpServer": "smtp.oncemi.com",
Expand Down
6 changes: 5 additions & 1 deletion src/BilibiliLiver/BilibiliLiver.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<AssemblyVersion>3.0.1</AssemblyVersion>
<FileVersion>3.0.1</FileVersion>
<Authors>withsalt</Authors>
<Version>2.0.2</Version>
<Version>3.0.3</Version>
<Description>B站直播工具。</Description>
</PropertyGroup>

Expand All @@ -28,6 +28,7 @@
<PackageReference Include="Microsoft.Extensions.Hosting" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="6.0.0" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.14.0" />
</ItemGroup>

<ItemGroup>
Expand All @@ -41,6 +42,9 @@
<None Update="cookie.txt">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="nlog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>

<ProjectExtensions><VisualStudio><UserProperties appsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
namespace BilibiliLiver.Config.Models
{
public class LiveSetting
public class LiveSettings
{
public int LiveAreaId { get; set; }

Expand All @@ -10,6 +10,8 @@ public class LiveSetting

public bool AutoRestart { get; set; }

public static string Position { get { return "LiveSetting"; } }
public int RepushFailedExitMinutes { get; set; }

public static string Position { get { return "LiveSettings"; } }
}
}
2 changes: 1 addition & 1 deletion src/BilibiliLiver/DependencyInjection/RegisteConfigure.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ public static class RegisteConfigure
{
public static IServiceCollection ConfigureSettings(this IServiceCollection services, HostBuilderContext hostContext)
{
services.Configure<LiveSetting>(hostContext.Configuration.GetSection(LiveSetting.Position));
services.Configure<LiveSettings>(hostContext.Configuration.GetSection(LiveSettings.Position));
return services;
}
}
Expand Down
10 changes: 10 additions & 0 deletions src/BilibiliLiver/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
using BilibiliLiver.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
using System;
using System.Reflection;

Expand All @@ -18,6 +20,14 @@ static void Main(string[] args)

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
//移除已经注册的其他日志处理程序
logging.ClearProviders();
//设置最小的日志级别
logging.SetMinimumLevel(LogLevel.Trace);
})
.UseNLog()
.ConfigureServices((hostContext, services) =>
{
//配置初始化
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,9 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net6.0</TargetFramework>
<SelfContained>true</SelfContained>
<RuntimeIdentifier>linux-x64</RuntimeIdentifier>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<PublishSingleFile>true</PublishSingleFile>
<PublishTrimmed>false</PublishTrimmed>
<PublishReadyToRun>false</PublishReadyToRun>
</PropertyGroup>
</Project>
4 changes: 2 additions & 2 deletions src/BilibiliLiver/Services/ConfigureService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ public class ConfigureService : IHostedService
private readonly IBilibiliLiveApiService _api;
private readonly IBilibiliCookieService _cookie;
private readonly IPushStreamService _push;
private readonly LiveSetting _liveSetting;
private readonly LiveSettings _liveSetting;

public ConfigureService(ILogger<ConfigureService> logger
, IBilibiliAccountService account
, IBilibiliLiveApiService api
, IBilibiliCookieService cookie
, IPushStreamService push
, IOptions<LiveSetting> liveSettingOptions)
, IOptions<LiveSettings> liveSettingOptions)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_account = account ?? throw new ArgumentNullException(nameof(account));
Expand Down
Loading

0 comments on commit e06befe

Please sign in to comment.