misc(core): fix warnings

This commit is contained in:
genteure 2023-08-24 23:08:56 +08:00
parent 2f08500bc4
commit f63f7b21aa
13 changed files with 83 additions and 53 deletions

View File

@ -153,7 +153,7 @@ namespace BililiveRecorder.Core.Api.Danmaku
} }
#pragma warning disable VSTHRD100 // Avoid async void methods #pragma warning disable VSTHRD100 // Avoid async void methods
private async void SendPingMessageTimerCallback(object sender, ElapsedEventArgs e) private async void SendPingMessageTimerCallback(object? sender, ElapsedEventArgs e)
#pragma warning restore VSTHRD100 // Avoid async void methods #pragma warning restore VSTHRD100 // Avoid async void methods
{ {
try try
@ -248,9 +248,9 @@ namespace BililiveRecorder.Core.Api.Danmaku
if (this.danmakuTransport is not { } transport) if (this.danmakuTransport is not { } transport)
return; return;
var playload = ((body?.Length ?? 0) > 0) ? Encoding.UTF8.GetBytes(body) : Array.Empty<byte>(); var payload = Encoding.UTF8.GetBytes(body);
const int headerLength = 16; const int headerLength = 16;
var totalLength = playload.Length + headerLength; var totalLength = payload.Length + headerLength;
var buffer = ArrayPool<byte>.Shared.Rent(totalLength); var buffer = ArrayPool<byte>.Shared.Rent(totalLength);
try try
@ -261,8 +261,8 @@ namespace BililiveRecorder.Core.Api.Danmaku
BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 8, 4), (uint)action); BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 8, 4), (uint)action);
BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 12, 4), 1); BinaryPrimitives.WriteUInt32BigEndian(new Span<byte>(buffer, 12, 4), 1);
if (playload.Length > 0) if (payload.Length > 0)
Array.Copy(playload, 0, buffer, headerLength, playload.Length); Array.Copy(payload, 0, buffer, headerLength, payload.Length);
await transport.SendAsync(buffer, 0, totalLength).ConfigureAwait(false); await transport.SendAsync(buffer, 0, totalLength).ConfigureAwait(false);
} }

View File

@ -77,7 +77,7 @@ namespace BililiveRecorder.Core.Api.Http
old?.Dispose(); old?.Dispose();
} }
private void Config_PropertyChanged(object sender, PropertyChangedEventArgs e) private void Config_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{ {
if (e.PropertyName is (nameof(this.config.Cookie)) or (nameof(this.config.TimingApiTimeout))) if (e.PropertyName is (nameof(this.config.Cookie)) or (nameof(this.config.TimingApiTimeout)))
this.UpdateHttpClient(); this.UpdateHttpClient();

View File

@ -155,7 +155,7 @@ namespace BililiveRecorder.Core.Config
var ext = Path.GetExtension(path); var ext = Path.GetExtension(path);
var tempPath = Path.Combine(Path.GetDirectoryName(path), Path.ChangeExtension(path, RandomString(6) + ext)); var tempPath = Path.Combine(Path.GetDirectoryName(path)!, Path.ChangeExtension(path, RandomString(6) + ext));
var backupPath = Path.ChangeExtension(path, "backup" + ext); var backupPath = Path.ChangeExtension(path, "backup" + ext);
// delete any existing backups // delete any existing backups

View File

@ -58,7 +58,7 @@ namespace BililiveRecorder.Core.Danmaku
this.xmlWriter = null; this.xmlWriter = null;
} }
try { Directory.CreateDirectory(Path.GetDirectoryName(path)); } catch (Exception) { } try { Directory.CreateDirectory(Path.GetDirectoryName(path)!); } catch (Exception) { }
var stream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read); var stream = File.Open(path, FileMode.Create, FileAccess.Write, FileShare.Read);
this.config = room.RoomConfig; this.config = room.RoomConfig;

View File

@ -125,48 +125,48 @@ namespace BililiveRecorder.Core
#region Events #region Events
private void Room_IOStats(object sender, IOStatsEventArgs e) private void Room_IOStats(object? sender, IOStatsEventArgs e)
{ {
var room = (IRoom)sender; if (sender is not IRoom room) return;
IOStats?.Invoke(this, new AggregatedRoomEventArgs<IOStatsEventArgs>(room, e)); IOStats?.Invoke(this, new AggregatedRoomEventArgs<IOStatsEventArgs>(room, e));
} }
private void Room_RecordingStats(object sender, RecordingStatsEventArgs e) private void Room_RecordingStats(object? sender, RecordingStatsEventArgs e)
{ {
var room = (IRoom)sender; if (sender is not IRoom room) return;
RecordingStats?.Invoke(this, new AggregatedRoomEventArgs<RecordingStatsEventArgs>(room, e)); RecordingStats?.Invoke(this, new AggregatedRoomEventArgs<RecordingStatsEventArgs>(room, e));
} }
private void Room_RecordFileClosed(object sender, RecordFileClosedEventArgs e) private void Room_RecordFileClosed(object? sender, RecordFileClosedEventArgs e)
{ {
var room = (IRoom)sender; if (sender is not IRoom room) return;
_ = Task.Run(async () => await this.basicWebhookV2.SendFileClosedAsync(e).ConfigureAwait(false)); _ = Task.Run(async () => await this.basicWebhookV2.SendFileClosedAsync(e).ConfigureAwait(false));
_ = Task.Run(async () => await this.basicWebhookV1.SendAsync(new RecordEndData(e)).ConfigureAwait(false)); _ = Task.Run(async () => await this.basicWebhookV1.SendAsync(new RecordEndData(e)).ConfigureAwait(false));
RecordFileClosed?.Invoke(this, new AggregatedRoomEventArgs<RecordFileClosedEventArgs>(room, e)); RecordFileClosed?.Invoke(this, new AggregatedRoomEventArgs<RecordFileClosedEventArgs>(room, e));
} }
private void Room_RecordFileOpening(object sender, RecordFileOpeningEventArgs e) private void Room_RecordFileOpening(object? sender, RecordFileOpeningEventArgs e)
{ {
var room = (IRoom)sender; if (sender is not IRoom room) return;
_ = Task.Run(async () => await this.basicWebhookV2.SendFileOpeningAsync(e).ConfigureAwait(false)); _ = Task.Run(async () => await this.basicWebhookV2.SendFileOpeningAsync(e).ConfigureAwait(false));
RecordFileOpening?.Invoke(this, new AggregatedRoomEventArgs<RecordFileOpeningEventArgs>(room, e)); RecordFileOpening?.Invoke(this, new AggregatedRoomEventArgs<RecordFileOpeningEventArgs>(room, e));
} }
private void Room_RecordSessionStarted(object sender, RecordSessionStartedEventArgs e) private void Room_RecordSessionStarted(object? sender, RecordSessionStartedEventArgs e)
{ {
var room = (IRoom)sender; if (sender is not IRoom room) return;
_ = Task.Run(async () => await this.basicWebhookV2.SendSessionStartedAsync(e).ConfigureAwait(false)); _ = Task.Run(async () => await this.basicWebhookV2.SendSessionStartedAsync(e).ConfigureAwait(false));
RecordSessionStarted?.Invoke(this, new AggregatedRoomEventArgs<RecordSessionStartedEventArgs>(room, e)); RecordSessionStarted?.Invoke(this, new AggregatedRoomEventArgs<RecordSessionStartedEventArgs>(room, e));
} }
private void Room_RecordSessionEnded(object sender, RecordSessionEndedEventArgs e) private void Room_RecordSessionEnded(object? sender, RecordSessionEndedEventArgs e)
{ {
var room = (IRoom)sender; if (sender is not IRoom room) return;
_ = Task.Run(async () => await this.basicWebhookV2.SendSessionEndedAsync(e).ConfigureAwait(false)); _ = Task.Run(async () => await this.basicWebhookV2.SendSessionEndedAsync(e).ConfigureAwait(false));
RecordSessionEnded?.Invoke(this, new AggregatedRoomEventArgs<RecordSessionEndedEventArgs>(room, e)); RecordSessionEnded?.Invoke(this, new AggregatedRoomEventArgs<RecordSessionEndedEventArgs>(room, e));
} }
private void Room_PropertyChanged(object sender, PropertyChangedEventArgs e) private void Room_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{ {
if (sender is not IRoom room) if (sender is not IRoom room)
return; return;

View File

@ -31,7 +31,7 @@ namespace BililiveRecorder.Core.Recording
var (fullPath, relativePath) = this.CreateFileName(); var (fullPath, relativePath) = this.CreateFileName();
try try
{ Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); } { Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!); }
catch (Exception) { } catch (Exception) { }
this.fileOpeningEventArgs = new RecordFileOpeningEventArgs(this.room) this.fileOpeningEventArgs = new RecordFileOpeningEventArgs(this.room)
@ -110,12 +110,24 @@ namespace BililiveRecorder.Core.Recording
recordFileClosedEvent = null; recordFileClosedEvent = null;
try try
{ file.Dispose(); } {
#if NET6_0_OR_GREATER
await file.DisposeAsync();
#else
file.Dispose();
#endif
}
catch (Exception ex) catch (Exception ex)
{ this.logger.Warning(ex, "关闭文件时发生错误"); } { this.logger.Warning(ex, "关闭文件时发生错误"); }
try try
{ stream.Dispose(); } {
#if NET6_0_OR_GREATER
await stream.DisposeAsync();
#else
stream.Dispose();
#endif
}
catch (Exception) { } catch (Exception) { }
try try

View File

@ -115,9 +115,19 @@ namespace BililiveRecorder.Core.Recording
{ {
try try
{ {
if (state is not WeakReference<Stream> weakRef)
return;
await Task.Delay(1000); await Task.Delay(1000);
if (((WeakReference<Stream>)state).TryGetTarget(out var weakStream))
if (weakRef.TryGetTarget(out var weakStream))
{
#if NET6_0_OR_GREATER
await weakStream.DisposeAsync();
#else
weakStream.Dispose(); weakStream.Dispose();
#endif
}
} }
catch (Exception) catch (Exception)
{ } { }
@ -128,7 +138,7 @@ namespace BililiveRecorder.Core.Recording
protected abstract void StartRecordingLoop(Stream stream); protected abstract void StartRecordingLoop(Stream stream);
private void Timer_Elapsed_TriggerIOStats(object sender, ElapsedEventArgs e) private void Timer_Elapsed_TriggerIOStats(object? sender, ElapsedEventArgs e)
{ {
int networkDownloadBytes, diskWriteBytes; int networkDownloadBytes, diskWriteBytes;
TimeSpan durationDiff, diskWriteDuration; TimeSpan durationDiff, diskWriteDuration;
@ -161,7 +171,7 @@ namespace BililiveRecorder.Core.Recording
this.OnIOStats(new IOStatsEventArgs this.OnIOStats(new IOStatsEventArgs
{ {
StreamHost = streamHost, StreamHost = this.streamHost,
NetworkBytesDownloaded = networkDownloadBytes, NetworkBytesDownloaded = networkDownloadBytes,
Duration = durationDiff, Duration = durationDiff,
StartTime = startTime, StartTime = startTime,
@ -392,8 +402,8 @@ namespace BililiveRecorder.Core.Recording
case HttpStatusCode.Moved: case HttpStatusCode.Moved:
case HttpStatusCode.Redirect: case HttpStatusCode.Redirect:
{ {
fullUrl = new Uri(originalUri, resp.Headers.Location).ToString(); fullUrl = new Uri(originalUri, resp.Headers.Location!).ToString();
this.logger.Debug("跳转到 {Url}, 原文本 {Location}", fullUrl, resp.Headers.Location.OriginalString); this.logger.Debug("跳转到 {Url}, 原文本 {Location}", fullUrl, resp.Headers.Location!.OriginalString);
resp.Dispose(); resp.Dispose();
streamHostInfoBuilder.Append('\n'); streamHostInfoBuilder.Append('\n');
break; break;

View File

@ -151,7 +151,11 @@ namespace BililiveRecorder.Core.Recording
finally finally
{ {
this.timer.Stop(); this.timer.Stop();
#if NET6_0_OR_GREATER
await stream.DisposeAsync().ConfigureAwait(false);
#else
stream.Dispose(); stream.Dispose();
#endif
await writer.CompleteAsync(exception).ConfigureAwait(false); await writer.CompleteAsync(exception).ConfigureAwait(false);
} }
} }
@ -265,7 +269,7 @@ namespace BililiveRecorder.Core.Recording
} }
} }
private void StatsRule_StatsUpdated(object sender, RecordingStatsEventArgs e) private void StatsRule_StatsUpdated(object? sender, RecordingStatsEventArgs e)
{ {
switch (this.room.RoomConfig.CuttingMode) switch (this.room.RoomConfig.CuttingMode)
{ {
@ -300,7 +304,7 @@ namespace BililiveRecorder.Core.Recording
var paths = this.task.CreateFileName(); var paths = this.task.CreateFileName();
try try
{ _ = Directory.CreateDirectory(Path.GetDirectoryName(paths.fullPath)); } { _ = Directory.CreateDirectory(Path.GetDirectoryName(paths.fullPath)!); }
catch (Exception) { } catch (Exception) { }
this.last_path = paths.fullPath; this.last_path = paths.fullPath;
@ -317,7 +321,7 @@ namespace BililiveRecorder.Core.Recording
: Path.ChangeExtension(this.last_path, "txt"); : Path.ChangeExtension(this.last_path, "txt");
try try
{ _ = Directory.CreateDirectory(Path.GetDirectoryName(path)); } { _ = Directory.CreateDirectory(Path.GetDirectoryName(path)!); }
catch (Exception) { } catch (Exception) { }
var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read); var stream = new FileStream(path, FileMode.Append, FileAccess.Write, FileShare.Read);

View File

@ -402,7 +402,7 @@ namespace BililiveRecorder.Core
#region Event Handlers #region Event Handlers
/// ///
private void RecordTask_IOStats(object sender, IOStatsEventArgs e) private void RecordTask_IOStats(object? sender, IOStatsEventArgs e)
{ {
this.logger.Verbose("IO stats: {@stats}", e); this.logger.Verbose("IO stats: {@stats}", e);
@ -420,7 +420,7 @@ namespace BililiveRecorder.Core
} }
/// ///
private void RecordTask_RecordingStats(object sender, RecordingStatsEventArgs e) private void RecordTask_RecordingStats(object? sender, RecordingStatsEventArgs e)
{ {
this.logger.Verbose("Recording stats: {@stats}", e); this.logger.Verbose("Recording stats: {@stats}", e);
@ -454,7 +454,7 @@ namespace BililiveRecorder.Core
} }
/// ///
private void RecordTask_RecordFileClosed(object sender, RecordFileClosedEventArgs e) private void RecordTask_RecordFileClosed(object? sender, RecordFileClosedEventArgs e)
{ {
this.basicDanmakuWriter.Disable(); this.basicDanmakuWriter.Disable();
@ -462,7 +462,7 @@ namespace BililiveRecorder.Core
} }
/// ///
private void RecordTask_RecordFileOpening(object sender, RecordFileOpeningEventArgs e) private void RecordTask_RecordFileOpening(object? sender, RecordFileOpeningEventArgs e)
{ {
if (this.RoomConfig.RecordDanmaku) if (this.RoomConfig.RecordDanmaku)
this.basicDanmakuWriter.EnableWithPath(Path.ChangeExtension(e.FullPath, "xml"), this); this.basicDanmakuWriter.EnableWithPath(Path.ChangeExtension(e.FullPath, "xml"), this);
@ -513,7 +513,7 @@ namespace BililiveRecorder.Core
} }
/// ///
private void RecordTask_RecordSessionEnded(object sender, EventArgs e) private void RecordTask_RecordSessionEnded(object? sender, EventArgs e)
{ {
Guid id; Guid id;
lock (this.recordStartLock) lock (this.recordStartLock)
@ -570,7 +570,7 @@ namespace BililiveRecorder.Core
return this.userScriptRunner.CallOnDanmakuHandshake(this.logger, this, json); return this.userScriptRunner.CallOnDanmakuHandshake(this.logger, this, json);
} }
private void DanmakuClient_DanmakuReceived(object sender, Api.Danmaku.DanmakuReceivedEventArgs e) private void DanmakuClient_DanmakuReceived(object? sender, Api.Danmaku.DanmakuReceivedEventArgs e)
{ {
var d = e.Danmaku; var d = e.Danmaku;
@ -603,7 +603,7 @@ namespace BililiveRecorder.Core
_ = Task.Run(async () => await this.basicDanmakuWriter.WriteAsync(d)); _ = Task.Run(async () => await this.basicDanmakuWriter.WriteAsync(d));
} }
private void DanmakuClient_StatusChanged(object sender, Api.Danmaku.StatusChangedEventArgs e) private void DanmakuClient_StatusChanged(object? sender, Api.Danmaku.StatusChangedEventArgs e)
{ {
this.DanmakuConnected = e.Connected; this.DanmakuConnected = e.Connected;
if (e.Connected) if (e.Connected)
@ -622,7 +622,7 @@ namespace BililiveRecorder.Core
} }
} }
private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) private void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
{ {
this.StartDamakuConnection(delay: false); this.StartDamakuConnection(delay: false);
@ -645,7 +645,7 @@ namespace BililiveRecorder.Core
} }
} }
private void Room_PropertyChanged(object sender, PropertyChangedEventArgs e) private void Room_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{ {
switch (e.PropertyName) switch (e.PropertyName)
{ {
@ -666,7 +666,7 @@ namespace BililiveRecorder.Core
} }
} }
private void RoomConfig_PropertyChanged(object sender, PropertyChangedEventArgs e) private void RoomConfig_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{ {
switch (e.PropertyName) switch (e.PropertyName)
{ {

View File

@ -43,9 +43,9 @@ namespace BililiveRecorder.Core.Scripting.Runtime
this.query.Remove(name); this.query.Remove(name);
} }
public string[][] Entries() public string?[][] Entries()
{ {
return this.query.Select(x => new string[] { x.Name, x.Value.ToString() }).ToArray(); return this.query.Select(x => new string?[] { x.Name, x.Value.ToString() }).ToArray();
} }
public void ForEach(FunctionInstance callback, JsValue thisArg) public void ForEach(FunctionInstance callback, JsValue thisArg)
@ -63,7 +63,7 @@ namespace BililiveRecorder.Core.Scripting.Runtime
return this.query.TryGetFirst(name, out var value) ? value.ToString() : null; return this.query.TryGetFirst(name, out var value) ? value.ToString() : null;
} }
public string[] GetAll(string name) public string?[] GetAll(string name)
{ {
return this.query.GetAll(name).Select(x => x.ToString()).ToArray(); return this.query.GetAll(name).Select(x => x.ToString()).ToArray();
} }
@ -93,7 +93,7 @@ namespace BililiveRecorder.Core.Scripting.Runtime
return this.query.ToString(); return this.query.ToString();
} }
public string[] Values() public string?[] Values()
{ {
return this.query.Select(x => x.Value.ToString()).ToArray(); return this.query.Select(x => x.Value.ToString()).ToArray();
} }

View File

@ -108,7 +108,7 @@ namespace BililiveRecorder.Core.Templating
relativePath = template.Render(context); relativePath = template.Render(context);
relativePath = RemoveInvalidFileName(relativePath); relativePath = RemoveInvalidFileName(relativePath);
fullPath = skipFullPath ? null : Path.GetFullPath(Path.Combine(workDirectory, relativePath)); fullPath = workDirectory is null ? null : Path.GetFullPath(Path.Combine(workDirectory, relativePath));
if (!skipFullPath && !CheckIsWithinPath(workDirectory!, fullPath!)) if (!skipFullPath && !CheckIsWithinPath(workDirectory!, fullPath!))
{ {
@ -140,7 +140,7 @@ namespace BililiveRecorder.Core.Templating
returnDefaultPath: returnDefaultPath:
var defaultRelativePath = RemoveInvalidFileName(defaultTemplate.Render(context)); var defaultRelativePath = RemoveInvalidFileName(defaultTemplate.Render(context));
var defaultFullPath = skipFullPath ? null : Path.GetFullPath(Path.Combine(workDirectory, defaultRelativePath)); var defaultFullPath = workDirectory is null ? null : Path.GetFullPath(Path.Combine(workDirectory, defaultRelativePath));
return new FileNameTemplateOutput(status, errorMessage, defaultRelativePath, defaultFullPath); return new FileNameTemplateOutput(status, errorMessage, defaultRelativePath, defaultFullPath);
} }
@ -230,7 +230,7 @@ namespace BililiveRecorder.Core.Templating
internal static string RemoveInvalidFileName(string input, bool ignore_slash = true) internal static string RemoveInvalidFileName(string input, bool ignore_slash = true)
{ {
foreach (var c in Path.GetInvalidFileNameChars()) foreach (var c in Path.GetInvalidFileNameChars())
if (!ignore_slash || c != '\\' && c != '/') if (!ignore_slash || (c != '\\' && c != '/'))
input = input.Replace(c, '_'); input = input.Replace(c, '_');
input = invalidDirectoryNameRegex.Replace(input, "$1_$2"); input = invalidDirectoryNameRegex.Replace(input, "$1_$2");

View File

@ -26,7 +26,9 @@ namespace BililiveRecorder.WPF.Controls
private void MenuItem_StopRecording_Click(object sender, RoutedEventArgs e) => (this.DataContext as IRoom)?.StopRecord(); private void MenuItem_StopRecording_Click(object sender, RoutedEventArgs e) => (this.DataContext as IRoom)?.StopRecord();
#pragma warning disable VSTHRD110 // Observe result of async calls
private void MenuItem_RefreshInfo_Click(object sender, RoutedEventArgs e) => (this.DataContext as IRoom)?.RefreshRoomInfoAsync(); private void MenuItem_RefreshInfo_Click(object sender, RoutedEventArgs e) => (this.DataContext as IRoom)?.RefreshRoomInfoAsync();
#pragma warning restore VSTHRD110 // Observe result of async calls
private void MenuItem_StartMonitor_Click(object sender, RoutedEventArgs e) private void MenuItem_StartMonitor_Click(object sender, RoutedEventArgs e)
{ {

View File

@ -68,7 +68,9 @@ namespace BililiveRecorder.WPF
private class IPCRemoteService : MarshalByRefObject private class IPCRemoteService : MarshalByRefObject
{ {
#pragma warning disable VSTHRD110 // Observe result of async calls
public void Notify() => Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)ActivateFirstInstanceCallback); public void Notify() => Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)ActivateFirstInstanceCallback);
#pragma warning restore VSTHRD110 // Observe result of async calls
public override object? InitializeLifetimeService() => null; public override object? InitializeLifetimeService() => null;
} }
} }