Use null coalescing when possible

This commit is contained in:
crobibero 2020-11-13 11:24:46 -07:00
parent 5f52a58e78
commit 95ebb9a55a
13 changed files with 22 additions and 110 deletions

View File

@ -50,11 +50,7 @@ namespace Emby.Server.Implementations.AppBase
// If the file didn't exist before, or if something has changed, re-save // If the file didn't exist before, or if something has changed, re-save
if (buffer == null || !newBytes.AsSpan(0, newBytesLen).SequenceEqual(buffer)) if (buffer == null || !newBytes.AsSpan(0, newBytesLen).SequenceEqual(buffer))
{ {
var directory = Path.GetDirectoryName(path); var directory = Path.GetDirectoryName(path) ?? throw new ResourceNotFoundException(nameof(path));
if (directory == null)
{
throw new ResourceNotFoundException(nameof(directory));
}
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
// Save it after load in case we got new items // Save it after load in case we got new items

View File

@ -81,12 +81,7 @@ namespace Emby.Server.Implementations.Cryptography
throw new CryptographicException($"Requested hash method is not supported: {hashMethod}"); throw new CryptographicException($"Requested hash method is not supported: {hashMethod}");
} }
using var h = HashAlgorithm.Create(hashMethod); using var h = HashAlgorithm.Create(hashMethod) ?? throw new ResourceNotFoundException(nameof(hashMethod));
if (h == null)
{
throw new ResourceNotFoundException(nameof(h));
}
if (salt.Length == 0) if (salt.Length == 0)
{ {
return h.ComputeHash(bytes); return h.ComputeHash(bytes);

View File

@ -58,12 +58,7 @@ namespace Emby.Server.Implementations.Session
private void OnConnectionClosed(object? sender, EventArgs e) private void OnConnectionClosed(object? sender, EventArgs e)
{ {
if (sender == null) var connection = sender as IWebSocketConnection ?? throw new ResourceNotFoundException(nameof(sender));
{
throw new ResourceNotFoundException(nameof(sender));
}
var connection = (IWebSocketConnection)sender;
_logger.LogDebug("Removing websocket from session {Session}", _session.Id); _logger.LogDebug("Removing websocket from session {Session}", _session.Id);
_sockets.Remove(connection); _sockets.Remove(connection);
connection.Closed -= OnConnectionClosed; connection.Closed -= OnConnectionClosed;

View File

@ -1348,11 +1348,7 @@ namespace Jellyfin.Api.Controllers
var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty; var mapArgs = state.IsOutputVideo ? _encodingHelper.GetMapArgs(state) : string.Empty;
var directory = Path.GetDirectoryName(outputPath); var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath));
if (directory == null)
{
throw new ResourceNotFoundException(nameof(directory));
}
var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer); var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + GetSegmentFileExtension(state.Request.SegmentContainer);
@ -1572,12 +1568,7 @@ namespace Jellyfin.Api.Controllers
private string GetSegmentPath(StreamState state, string playlist, int index) private string GetSegmentPath(StreamState state, string playlist, int index)
{ {
var folder = Path.GetDirectoryName(playlist); var folder = Path.GetDirectoryName(playlist) ?? throw new ResourceNotFoundException(nameof(playlist));
if (folder == null)
{
throw new ResourceNotFoundException(nameof(folder));
}
var filename = Path.GetFileNameWithoutExtension(playlist); var filename = Path.GetFileNameWithoutExtension(playlist);
return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + GetSegmentFileExtension(state.Request.SegmentContainer)); return Path.Combine(folder, filename + index.ToString(CultureInfo.InvariantCulture) + GetSegmentFileExtension(state.Request.SegmentContainer));

View File

@ -135,12 +135,8 @@ namespace Jellyfin.Api.Controllers
var playlistPath = _fileSystem.GetFilePaths(transcodeFolderPath) var playlistPath = _fileSystem.GetFilePaths(transcodeFolderPath)
.FirstOrDefault(i => .FirstOrDefault(i =>
string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase) string.Equals(Path.GetExtension(i), ".m3u8", StringComparison.OrdinalIgnoreCase)
&& i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1); && i.IndexOf(normalizedPlaylistId, StringComparison.OrdinalIgnoreCase) != -1)
?? throw new ResourceNotFoundException(nameof(transcodeFolderPath));
if (playlistPath == null)
{
throw new ResourceNotFoundException(nameof(playlistPath));
}
return GetFileResult(file, playlistPath); return GetFileResult(file, playlistPath);
} }

View File

@ -342,12 +342,7 @@ namespace Jellyfin.Api.Controllers
var ext = result.Content.Headers.ContentType.MediaType.Split('/')[^1]; var ext = result.Content.Headers.ContentType.MediaType.Split('/')[^1];
var fullCachePath = GetFullCachePath(urlHash + "." + ext); var fullCachePath = GetFullCachePath(urlHash + "." + ext);
var directory = Path.GetDirectoryName(fullCachePath); var directory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException(nameof(fullCachePath));
if (directory == null)
{
throw new ResourceNotFoundException(nameof(directory));
}
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
using (var stream = result.Content) using (var stream = result.Content)
{ {
@ -362,11 +357,7 @@ namespace Jellyfin.Api.Controllers
await stream.CopyToAsync(fileStream).ConfigureAwait(false); await stream.CopyToAsync(fileStream).ConfigureAwait(false);
} }
var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath); var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ResourceNotFoundException(nameof(pointerCachePath));
if (pointerCacheDirectory == null)
{
throw new ResourceNotFoundException(nameof(pointerCacheDirectory));
}
Directory.CreateDirectory(pointerCacheDirectory); Directory.CreateDirectory(pointerCacheDirectory);
await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false); await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath).ConfigureAwait(false);

View File

@ -257,22 +257,12 @@ namespace Jellyfin.Api.Controllers
var ext = response.Content.Headers.ContentType.MediaType.Split('/').Last(); var ext = response.Content.Headers.ContentType.MediaType.Split('/').Last();
var fullCachePath = GetFullCachePath(urlHash + "." + ext); var fullCachePath = GetFullCachePath(urlHash + "." + ext);
var fullCacheDirectory = Path.GetDirectoryName(fullCachePath); var fullCacheDirectory = Path.GetDirectoryName(fullCachePath) ?? throw new ResourceNotFoundException(nameof(fullCachePath));
if (fullCacheDirectory == null)
{
throw new ResourceNotFoundException(nameof(fullCacheDirectory));
}
Directory.CreateDirectory(fullCacheDirectory); Directory.CreateDirectory(fullCacheDirectory);
await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true); await using var fileStream = new FileStream(fullCachePath, FileMode.Create, FileAccess.Write, FileShare.Read, IODefaults.FileStreamBufferSize, true);
await response.Content.CopyToAsync(fileStream).ConfigureAwait(false); await response.Content.CopyToAsync(fileStream).ConfigureAwait(false);
var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath); var pointerCacheDirectory = Path.GetDirectoryName(pointerCachePath) ?? throw new ResourceNotFoundException(nameof(pointerCachePath));
if (pointerCacheDirectory == null)
{
throw new ResourceNotFoundException(nameof(pointerCacheDirectory));
}
Directory.CreateDirectory(pointerCacheDirectory); Directory.CreateDirectory(pointerCacheDirectory);
await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None) await System.IO.File.WriteAllTextAsync(pointerCachePath, fullCachePath, CancellationToken.None)
.ConfigureAwait(false); .ConfigureAwait(false);

View File

@ -362,12 +362,7 @@ namespace Jellyfin.Api.Controllers
var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec); var threads = _encodingHelper.GetNumberOfThreads(state, _encodingOptions, videoCodec);
var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions); var inputModifier = _encodingHelper.GetInputModifier(state, _encodingOptions);
var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts"; var format = !string.IsNullOrWhiteSpace(state.Request.SegmentContainer) ? "." + state.Request.SegmentContainer : ".ts";
var directory = Path.GetDirectoryName(outputPath); var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath));
if (directory == null)
{
throw new ResourceNotFoundException(nameof(directory));
}
var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format; var outputTsArg = Path.Combine(directory, Path.GetFileNameWithoutExtension(outputPath)) + "%d" + format;
var segmentFormat = format.TrimStart('.'); var segmentFormat = format.TrimStart('.');

View File

@ -45,11 +45,8 @@ namespace Jellyfin.Api.Helpers
while (!reader.EndOfStream) while (!reader.EndOfStream)
{ {
var line = await reader.ReadLineAsync().ConfigureAwait(false); var line = await reader.ReadLineAsync().ConfigureAwait(false)
if (line == null) ?? throw new ResourceNotFoundException(nameof(reader));
{
throw new ResourceNotFoundException(nameof(line));
}
if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1) if (line.IndexOf("#EXTINF:", StringComparison.OrdinalIgnoreCase) != -1)
{ {

View File

@ -196,12 +196,7 @@ namespace Jellyfin.Api.Helpers
/// <param name="state">The state.</param> /// <param name="state">The state.</param>
private async void OnTranscodeKillTimerStopped(object? state) private async void OnTranscodeKillTimerStopped(object? state)
{ {
var job = (TranscodingJobDto?)state; var job = state as TranscodingJobDto ?? throw new ResourceNotFoundException(nameof(state));
if (job == null)
{
throw new ResourceNotFoundException(nameof(job));
}
if (!job.HasExited && job.Type != TranscodingJobType.Progressive) if (!job.HasExited && job.Type != TranscodingJobType.Progressive)
{ {
var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds; var timeSinceLastPing = (DateTime.UtcNow - job.LastPingDate).TotalMilliseconds;
@ -494,12 +489,7 @@ namespace Jellyfin.Api.Helpers
CancellationTokenSource cancellationTokenSource, CancellationTokenSource cancellationTokenSource,
string? workingDirectory = null) string? workingDirectory = null)
{ {
var directory = Path.GetDirectoryName(outputPath); var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath));
if (directory == null)
{
throw new ResourceNotFoundException(nameof(directory));
}
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false); await AcquireResources(state, cancellationTokenSource).ConfigureAwait(false);

View File

@ -228,12 +228,7 @@ namespace Jellyfin.Drawing.Skia
} }
var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path)); var tempPath = Path.Combine(_appPaths.TempDirectory, Guid.NewGuid() + Path.GetExtension(path));
var directory = Path.GetDirectoryName(tempPath); var directory = Path.GetDirectoryName(tempPath) ?? throw new ResourceNotFoundException(nameof(tempPath));
if (directory == null)
{
throw new ResourceNotFoundException(nameof(directory));
}
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
File.Copy(path, tempPath, true); File.Copy(path, tempPath, true);
@ -499,12 +494,7 @@ namespace Jellyfin.Drawing.Skia
// If all we're doing is resizing then we can stop now // If all we're doing is resizing then we can stop now
if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator) if (!hasBackgroundColor && !hasForegroundColor && blur == 0 && !hasIndicator)
{ {
var outputDirectory = Path.GetDirectoryName(outputPath); var outputDirectory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath));
if (outputDirectory == null)
{
throw new ResourceNotFoundException(nameof(outputDirectory));
}
Directory.CreateDirectory(outputDirectory); Directory.CreateDirectory(outputDirectory);
using var outputStream = new SKFileWStream(outputPath); using var outputStream = new SKFileWStream(outputPath);
using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels()); using var pixmap = new SKPixmap(new SKImageInfo(width, height), resizedBitmap.GetPixels());
@ -552,12 +542,7 @@ namespace Jellyfin.Drawing.Skia
DrawIndicator(canvas, width, height, options); DrawIndicator(canvas, width, height, options);
} }
var directory = Path.GetDirectoryName(outputPath); var directory = Path.GetDirectoryName(outputPath) ?? throw new ResourceNotFoundException(nameof(outputPath));
if (directory == null)
{
throw new ResourceNotFoundException(nameof(directory));
}
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
using (var outputStream = new SKFileWStream(outputPath)) using (var outputStream = new SKFileWStream(outputPath))
{ {

View File

@ -57,12 +57,8 @@ namespace Jellyfin.Server.Implementations.Users
SerializablePasswordReset? spr; SerializablePasswordReset? spr;
await using (var str = File.OpenRead(resetFile)) await using (var str = File.OpenRead(resetFile))
{ {
spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false); spr = await JsonSerializer.DeserializeAsync<SerializablePasswordReset>(str).ConfigureAwait(false)
} ?? throw new ResourceNotFoundException(nameof(spr));
if (spr == null)
{
throw new ResourceNotFoundException(nameof(spr));
} }
if (spr.ExpirationDate < DateTime.UtcNow) if (spr.ExpirationDate < DateTime.UtcNow)

View File

@ -128,12 +128,7 @@ namespace MediaBrowser.LocalMetadata.Savers
private void SaveToFile(Stream stream, string path) private void SaveToFile(Stream stream, string path)
{ {
var directory = Path.GetDirectoryName(path); var directory = Path.GetDirectoryName(path) ?? throw new ResourceNotFoundException(nameof(path));
if (directory == null)
{
throw new ResourceNotFoundException(nameof(directory));
}
Directory.CreateDirectory(directory); Directory.CreateDirectory(directory);
// On Windows, savint the file will fail if the file is hidden or readonly // On Windows, savint the file will fail if the file is hidden or readonly
FileSystem.SetAttributes(path, false, false); FileSystem.SetAttributes(path, false, false);