Merge pull request #12925 from Bond-009/await

Always await instead of directly returning Task
This commit is contained in:
Bond-009 2025-01-28 11:29:46 +01:00 committed by GitHub
commit 9734892322
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
14 changed files with 60 additions and 91 deletions

View File

@ -82,17 +82,17 @@ namespace Emby.Server.Implementations.HttpServer
public WebSocketState State => _socket.State; public WebSocketState State => _socket.State;
/// <inheritdoc /> /// <inheritdoc />
public Task SendAsync(OutboundWebSocketMessage message, CancellationToken cancellationToken) public async Task SendAsync(OutboundWebSocketMessage message, CancellationToken cancellationToken)
{ {
var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions); var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken); await _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false);
} }
/// <inheritdoc /> /// <inheritdoc />
public Task SendAsync<T>(OutboundWebSocketMessage<T> message, CancellationToken cancellationToken) public async Task SendAsync<T>(OutboundWebSocketMessage<T> message, CancellationToken cancellationToken)
{ {
var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions); var json = JsonSerializer.SerializeToUtf8Bytes(message, _jsonOptions);
return _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken); await _socket.SendAsync(json, WebSocketMessageType.Text, true, cancellationToken).ConfigureAwait(false);
} }
/// <inheritdoc /> /// <inheritdoc />
@ -224,12 +224,12 @@ namespace Emby.Server.Implementations.HttpServer
return ret; return ret;
} }
private Task SendKeepAliveResponse() private async Task SendKeepAliveResponse()
{ {
LastKeepAliveDate = DateTime.UtcNow; LastKeepAliveDate = DateTime.UtcNow;
return SendAsync( await SendAsync(
new OutboundKeepAliveMessage(), new OutboundKeepAliveMessage(),
CancellationToken.None); CancellationToken.None).ConfigureAwait(false);
} }
/// <inheritdoc /> /// <inheritdoc />

View File

@ -84,7 +84,7 @@ namespace Emby.Server.Implementations.HttpServer
/// Processes the web socket message received. /// Processes the web socket message received.
/// </summary> /// </summary>
/// <param name="result">The result.</param> /// <param name="result">The result.</param>
private Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result) private async Task ProcessWebSocketMessageReceived(WebSocketMessageInfo result)
{ {
var tasks = new Task[_webSocketListeners.Length]; var tasks = new Task[_webSocketListeners.Length];
for (var i = 0; i < _webSocketListeners.Length; ++i) for (var i = 0; i < _webSocketListeners.Length; ++i)
@ -92,7 +92,7 @@ namespace Emby.Server.Implementations.HttpServer
tasks[i] = _webSocketListeners[i].ProcessMessageAsync(result); tasks[i] = _webSocketListeners[i].ProcessMessageAsync(result);
} }
return Task.WhenAll(tasks); await Task.WhenAll(tasks).ConfigureAwait(false);
} }
} }
} }

View File

@ -276,11 +276,11 @@ namespace Emby.Server.Implementations.Session
/// </summary> /// </summary>
/// <param name="webSocket">The WebSocket.</param> /// <param name="webSocket">The WebSocket.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
private Task SendForceKeepAlive(IWebSocketConnection webSocket) private async Task SendForceKeepAlive(IWebSocketConnection webSocket)
{ {
return webSocket.SendAsync( await webSocket.SendAsync(
new ForceKeepAliveMessage(WebSocketLostTimeout), new ForceKeepAliveMessage(WebSocketLostTimeout),
CancellationToken.None); CancellationToken.None).ConfigureAwait(false);
} }
} }
} }

View File

@ -2056,16 +2056,16 @@ public class DynamicHlsController : BaseJellyfinApiController
} }
} }
private Task DeleteLastFile(string playlistPath, string segmentExtension, int retryCount) private async Task DeleteLastFile(string playlistPath, string segmentExtension, int retryCount)
{ {
var file = GetLastTranscodingFile(playlistPath, segmentExtension, _fileSystem); var file = GetLastTranscodingFile(playlistPath, segmentExtension, _fileSystem);
if (file is null) if (file is null)
{ {
return Task.CompletedTask; return;
} }
return DeleteFile(file.FullName, retryCount); await DeleteFile(file.FullName, retryCount).ConfigureAwait(false);
} }
private async Task DeleteFile(string path, int retryCount) private async Task DeleteFile(string path, int retryCount)

View File

@ -1,6 +1,4 @@
using System.Text; using System.Net.Mime;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Mvc.Formatters;
namespace Jellyfin.Api.Formatters; namespace Jellyfin.Api.Formatters;
@ -8,28 +6,14 @@ namespace Jellyfin.Api.Formatters;
/// <summary> /// <summary>
/// Css output formatter. /// Css output formatter.
/// </summary> /// </summary>
public class CssOutputFormatter : TextOutputFormatter public sealed class CssOutputFormatter : StringOutputFormatter
{ {
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="CssOutputFormatter"/> class. /// Initializes a new instance of the <see cref="CssOutputFormatter"/> class.
/// </summary> /// </summary>
public CssOutputFormatter() public CssOutputFormatter()
{ {
SupportedMediaTypes.Add("text/css"); SupportedMediaTypes.Clear();
SupportedMediaTypes.Add(MediaTypeNames.Text.Css);
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
}
/// <summary>
/// Write context object to stream.
/// </summary>
/// <param name="context">Writer context.</param>
/// <param name="selectedEncoding">Unused. Writer encoding.</param>
/// <returns>Write stream task.</returns>
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
var stringResponse = context.Object?.ToString();
return stringResponse is null ? Task.CompletedTask : context.HttpContext.Response.WriteAsync(stringResponse);
} }
} }

View File

@ -1,7 +1,4 @@
using System.Net.Mime; using System.Net.Mime;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Mvc.Formatters;
namespace Jellyfin.Api.Formatters; namespace Jellyfin.Api.Formatters;
@ -9,7 +6,7 @@ namespace Jellyfin.Api.Formatters;
/// <summary> /// <summary>
/// Xml output formatter. /// Xml output formatter.
/// </summary> /// </summary>
public class XmlOutputFormatter : TextOutputFormatter public sealed class XmlOutputFormatter : StringOutputFormatter
{ {
/// <summary> /// <summary>
/// Initializes a new instance of the <see cref="XmlOutputFormatter"/> class. /// Initializes a new instance of the <see cref="XmlOutputFormatter"/> class.
@ -18,15 +15,5 @@ public class XmlOutputFormatter : TextOutputFormatter
{ {
SupportedMediaTypes.Clear(); SupportedMediaTypes.Clear();
SupportedMediaTypes.Add(MediaTypeNames.Text.Xml); SupportedMediaTypes.Add(MediaTypeNames.Text.Xml);
SupportedEncodings.Add(Encoding.UTF8);
SupportedEncodings.Add(Encoding.Unicode);
}
/// <inheritdoc />
public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
{
var stringResponse = context.Object?.ToString();
return stringResponse is null ? Task.CompletedTask : context.HttpContext.Response.WriteAsync(stringResponse);
} }
} }

View File

@ -67,38 +67,40 @@ namespace Jellyfin.Server.Infrastructure
} }
/// <inheritdoc /> /// <inheritdoc />
protected override Task WriteFileAsync(ActionContext context, PhysicalFileResult result, RangeItemHeaderValue? range, long rangeLength) protected override async Task WriteFileAsync(ActionContext context, PhysicalFileResult result, RangeItemHeaderValue? range, long rangeLength)
{ {
ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(context);
ArgumentNullException.ThrowIfNull(result); ArgumentNullException.ThrowIfNull(result);
if (range is not null && rangeLength == 0) if (range is not null && rangeLength == 0)
{ {
return Task.CompletedTask; return;
} }
// It's a bit of wasted IO to perform this check again, but non-symlinks shouldn't use this code // It's a bit of wasted IO to perform this check again, but non-symlinks shouldn't use this code
if (!IsSymLink(result.FileName)) if (!IsSymLink(result.FileName))
{ {
return base.WriteFileAsync(context, result, range, rangeLength); await base.WriteFileAsync(context, result, range, rangeLength).ConfigureAwait(false);
return;
} }
var response = context.HttpContext.Response; var response = context.HttpContext.Response;
if (range is not null) if (range is not null)
{ {
return SendFileAsync( await SendFileAsync(
result.FileName, result.FileName,
response, response,
offset: range.From ?? 0L, offset: range.From ?? 0L,
count: rangeLength); count: rangeLength).ConfigureAwait(false);
return;
} }
return SendFileAsync( await SendFileAsync(
result.FileName, result.FileName,
response, response,
offset: 0, offset: 0,
count: null); count: null).ConfigureAwait(false);
} }
private async Task SendFileAsync(string filePath, HttpResponse response, long offset, long? count, CancellationToken cancellationToken = default) private async Task SendFileAsync(string filePath, HttpResponse response, long offset, long? count, CancellationToken cancellationToken = default)

View File

@ -111,15 +111,15 @@ namespace MediaBrowser.Controller.Entities.Audio
return base.IsSaveLocalMetadataEnabled(); return base.IsSaveLocalMetadataEnabled();
} }
protected override Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, bool allowRemoveRoot, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken) protected override async Task ValidateChildrenInternal(IProgress<double> progress, bool recursive, bool refreshChildMetadata, bool allowRemoveRoot, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService, CancellationToken cancellationToken)
{ {
if (IsAccessedByName) if (IsAccessedByName)
{ {
// Should never get in here anyway // Should never get in here anyway
return Task.CompletedTask; return;
} }
return base.ValidateChildrenInternal(progress, recursive, refreshChildMetadata, false, refreshOptions, directoryService, cancellationToken); await base.ValidateChildrenInternal(progress, recursive, refreshChildMetadata, false, refreshOptions, directoryService, cancellationToken).ConfigureAwait(false);
} }
public override List<string> GetUserDataKeys() public override List<string> GetUserDataKeys()

View File

@ -1984,8 +1984,8 @@ namespace MediaBrowser.Controller.Entities
ImageInfos = [.. ImageInfos, image]; ImageInfos = [.. ImageInfos, image];
} }
public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken) public virtual async Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)
=> LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken); => await LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken).ConfigureAwait(false);
/// <summary> /// <summary>
/// Validates that images within the item are still on the filesystem. /// Validates that images within the item are still on the filesystem.
@ -2374,7 +2374,7 @@ namespace MediaBrowser.Controller.Entities
} }
} }
protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken) protected async Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
{ {
var newOptions = new MetadataRefreshOptions(options) var newOptions = new MetadataRefreshOptions(options)
{ {
@ -2435,10 +2435,10 @@ namespace MediaBrowser.Controller.Entities
} }
} }
return ownedItem.RefreshMetadata(newOptions, cancellationToken); await ownedItem.RefreshMetadata(newOptions, cancellationToken).ConfigureAwait(false);
} }
protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken) protected async Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
{ {
var newOptions = new MetadataRefreshOptions(options) var newOptions = new MetadataRefreshOptions(options)
{ {
@ -2448,9 +2448,7 @@ namespace MediaBrowser.Controller.Entities
var id = LibraryManager.GetNewItemId(path, typeof(Video)); var id = LibraryManager.GetNewItemId(path, typeof(Video));
// Try to retrieve it from the db. If we don't find it, use the resolved version // Try to retrieve it from the db. If we don't find it, use the resolved version
var video = LibraryManager.GetItemById(id) as Video; if (LibraryManager.GetItemById(id) is not Video video)
if (video is null)
{ {
video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video; video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
@ -2459,15 +2457,15 @@ namespace MediaBrowser.Controller.Entities
if (video is null) if (video is null)
{ {
return Task.FromResult(true); return;
} }
if (video.OwnerId.IsEmpty()) if (video.OwnerId.IsEmpty())
{ {
video.OwnerId = this.Id; video.OwnerId = Id;
} }
return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken); await RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken).ConfigureAwait(false);
} }
public string GetEtag(User user) public string GetEtag(User user)

View File

@ -530,13 +530,13 @@ namespace MediaBrowser.Controller.Entities
} }
} }
private Task RefreshMetadataRecursive(IList<BaseItem> children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken) private async Task RefreshMetadataRecursive(IList<BaseItem> children, MetadataRefreshOptions refreshOptions, bool recursive, IProgress<double> progress, CancellationToken cancellationToken)
{ {
return RunTasks( await RunTasks(
(baseItem, innerProgress) => RefreshChildMetadata(baseItem, refreshOptions, recursive && baseItem.IsFolder, innerProgress, cancellationToken), (baseItem, innerProgress) => RefreshChildMetadata(baseItem, refreshOptions, recursive && baseItem.IsFolder, innerProgress, cancellationToken),
children, children,
progress, progress,
cancellationToken); cancellationToken).ConfigureAwait(false);
} }
private async Task RefreshAllMetadataForContainer(IMetadataContainer container, MetadataRefreshOptions refreshOptions, IProgress<double> progress, CancellationToken cancellationToken) private async Task RefreshAllMetadataForContainer(IMetadataContainer container, MetadataRefreshOptions refreshOptions, IProgress<double> progress, CancellationToken cancellationToken)
@ -577,13 +577,13 @@ namespace MediaBrowser.Controller.Entities
/// <param name="progress">The progress.</param> /// <param name="progress">The progress.</param>
/// <param name="cancellationToken">The cancellation token.</param> /// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns> /// <returns>Task.</returns>
private Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken) private async Task ValidateSubFolders(IList<Folder> children, IDirectoryService directoryService, IProgress<double> progress, CancellationToken cancellationToken)
{ {
return RunTasks( await RunTasks(
(folder, innerProgress) => folder.ValidateChildrenInternal(innerProgress, true, false, false, null, directoryService, cancellationToken), (folder, innerProgress) => folder.ValidateChildrenInternal(innerProgress, true, false, false, null, directoryService, cancellationToken),
children, children,
progress, progress,
cancellationToken); cancellationToken).ConfigureAwait(false);
} }
/// <summary> /// <summary>

View File

@ -45,16 +45,16 @@ namespace MediaBrowser.LocalMetadata.Savers
} }
/// <inheritdoc /> /// <inheritdoc />
protected override Task WriteCustomElementsAsync(BaseItem item, XmlWriter writer) protected override async Task WriteCustomElementsAsync(BaseItem item, XmlWriter writer)
{ {
var game = (Playlist)item; var game = (Playlist)item;
if (game.PlaylistMediaType == MediaType.Unknown) if (game.PlaylistMediaType == MediaType.Unknown)
{ {
return Task.CompletedTask; return;
} }
return writer.WriteElementStringAsync(null, "PlaylistMediaType", null, game.PlaylistMediaType.ToString()); await writer.WriteElementStringAsync(null, "PlaylistMediaType", null, game.PlaylistMediaType.ToString()).ConfigureAwait(false);
} }
/// <inheritdoc /> /// <inheritdoc />

View File

@ -148,21 +148,19 @@ namespace MediaBrowser.Providers.Plugins.AudioDb
item.Overview = (overview ?? string.Empty).StripHtml(); item.Overview = (overview ?? string.Empty).StripHtml();
} }
internal Task EnsureInfo(string musicBrainzReleaseGroupId, CancellationToken cancellationToken) internal async Task EnsureInfo(string musicBrainzReleaseGroupId, CancellationToken cancellationToken)
{ {
var xmlPath = GetAlbumInfoPath(_config.ApplicationPaths, musicBrainzReleaseGroupId); var xmlPath = GetAlbumInfoPath(_config.ApplicationPaths, musicBrainzReleaseGroupId);
var fileInfo = _fileSystem.GetFileSystemInfo(xmlPath); var fileInfo = _fileSystem.GetFileSystemInfo(xmlPath);
if (fileInfo.Exists) if (fileInfo.Exists
&& (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
{ {
if ((DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2) return;
{
return Task.CompletedTask;
}
} }
return DownloadInfo(musicBrainzReleaseGroupId, cancellationToken); await DownloadInfo(musicBrainzReleaseGroupId, cancellationToken).ConfigureAwait(false);
} }
internal async Task DownloadInfo(string musicBrainzReleaseGroupId, CancellationToken cancellationToken) internal async Task DownloadInfo(string musicBrainzReleaseGroupId, CancellationToken cancellationToken)

View File

@ -131,7 +131,7 @@ namespace MediaBrowser.Providers.Plugins.AudioDb
item.Overview = (overview ?? string.Empty).StripHtml(); item.Overview = (overview ?? string.Empty).StripHtml();
} }
internal Task EnsureArtistInfo(string musicBrainzId, CancellationToken cancellationToken) internal async Task EnsureArtistInfo(string musicBrainzId, CancellationToken cancellationToken)
{ {
var xmlPath = GetArtistInfoPath(_config.ApplicationPaths, musicBrainzId); var xmlPath = GetArtistInfoPath(_config.ApplicationPaths, musicBrainzId);
@ -140,10 +140,10 @@ namespace MediaBrowser.Providers.Plugins.AudioDb
if (fileInfo.Exists if (fileInfo.Exists
&& (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2) && (DateTime.UtcNow - _fileSystem.GetLastWriteTimeUtc(fileInfo)).TotalDays <= 2)
{ {
return Task.CompletedTask; return;
} }
return DownloadArtistInfo(musicBrainzId, cancellationToken); await DownloadArtistInfo(musicBrainzId, cancellationToken).ConfigureAwait(false);
} }
internal async Task DownloadArtistInfo(string musicBrainzId, CancellationToken cancellationToken) internal async Task DownloadArtistInfo(string musicBrainzId, CancellationToken cancellationToken)

View File

@ -101,11 +101,11 @@ namespace MediaBrowser.Providers.Plugins.StudioImages
return string.Format(CultureInfo.InvariantCulture, "{0}/images/{1}/{2}.jpg", GetRepositoryUrl(), image, filename); return string.Format(CultureInfo.InvariantCulture, "{0}/images/{1}/{2}.jpg", GetRepositoryUrl(), image, filename);
} }
private Task EnsureThumbsList(string file, CancellationToken cancellationToken) private async Task EnsureThumbsList(string file, CancellationToken cancellationToken)
{ {
string url = string.Format(CultureInfo.InvariantCulture, "{0}/thumbs.txt", GetRepositoryUrl()); string url = string.Format(CultureInfo.InvariantCulture, "{0}/thumbs.txt", GetRepositoryUrl());
return EnsureList(url, file, _fileSystem, cancellationToken); await EnsureList(url, file, _fileSystem, cancellationToken).ConfigureAwait(false);
} }
/// <inheritdoc /> /// <inheritdoc />