BililiveRecorder/BililiveRecorder.Core/Recorder.cs

88 lines
2.6 KiB
C#
Raw Normal View History

2018-03-21 20:56:56 +08:00
using NLog;
using System;
2018-03-12 18:57:20 +08:00
using System.Collections.Generic;
using System.Collections.ObjectModel;
2018-03-24 09:48:06 +08:00
using System.Linq;
2018-03-12 18:57:20 +08:00
using System.Text;
using System.Threading;
using System.Threading.Tasks;
2018-03-12 18:57:20 +08:00
namespace BililiveRecorder.Core
{
public class Recorder
{
2018-03-21 20:56:56 +08:00
private static readonly Logger logger = LogManager.GetCurrentClassLogger();
public ObservableCollection<RecordedRoom> Rooms { get; } = new ObservableCollection<RecordedRoom>();
public Settings Settings { get; } = new Settings();
2018-03-20 00:12:32 +08:00
private CancellationTokenSource tokenSource;
2018-03-20 00:12:32 +08:00
public Recorder()
{
tokenSource = new CancellationTokenSource();
Repeat.Interval(TimeSpan.FromSeconds(6), DownloadWatchdog, tokenSource.Token);
}
2018-03-20 00:12:32 +08:00
private void DownloadWatchdog()
{
try
{
Rooms.ToList().ForEach(room =>
{
if (room.IsRecording)
{
if (DateTime.Now - room.LastUpdateDateTime > TimeSpan.FromSeconds(3))
{
logger.Warn("服务器停止提供 {0} 直播间的直播数据,通常是录制时网络不稳定导致,将会断开重连", room.Roomid);
room.StopRecord();
room.StreamMonitor.CheckAfterSeconeds(1, TriggerType.HttpApi);
}
}
});
}
catch (Exception ex)
{
logger.Error(ex, "直播流下载监控出错");
}
2018-03-20 00:12:32 +08:00
}
2018-03-12 18:57:20 +08:00
2018-03-24 02:27:58 +08:00
/// <summary>
/// 添加直播间到录播姬
/// </summary>
/// <param name="roomid">房间号(支持短号)</param>
/// <exception cref="ArgumentOutOfRangeException"/>
2018-03-24 09:48:06 +08:00
public void AddRoom(int roomid, bool enabled = false)
2018-03-21 20:56:56 +08:00
{
if (roomid <= 0)
throw new ArgumentOutOfRangeException(nameof(roomid), "房间号需要大于0");
2018-03-24 09:48:06 +08:00
var rr = new RecordedRoom(Settings, roomid);
if (enabled)
Task.Run(() => rr.Start());
2018-03-24 09:48:06 +08:00
Rooms.Add(rr);
2018-03-21 20:56:56 +08:00
}
2018-03-24 02:27:58 +08:00
/// <summary>
/// 从录播姬移除直播间
/// </summary>
/// <param name="rr">直播间</param>
public void RemoveRoom(RecordedRoom rr)
{
rr.Stop();
rr.StopRecord();
2018-03-24 08:58:46 +08:00
Rooms.Remove(rr);
2018-03-24 02:27:58 +08:00
}
2018-03-24 09:48:06 +08:00
public void Shutdown()
{
tokenSource.Cancel();
2018-03-24 09:48:06 +08:00
Rooms.ToList().ForEach(rr =>
{
rr.Stop();
rr.StopRecord();
});
}
2018-03-12 18:57:20 +08:00
}
}