Reduce usage of GetAwaiter().GetResult()

This commit is contained in:
Bond_009 2023-03-01 18:57:23 +01:00
parent af611367c1
commit d8ec3a5470
12 changed files with 74 additions and 70 deletions

View File

@ -157,16 +157,16 @@ namespace Emby.Server.Implementations.Channels
} }
/// <inheritdoc /> /// <inheritdoc />
public QueryResult<Channel> GetChannelsInternal(ChannelQuery query) public async Task<QueryResult<Channel>> GetChannelsInternalAsync(ChannelQuery query)
{ {
var user = query.UserId.Equals(default) var user = query.UserId.Equals(default)
? null ? null
: _userManager.GetUserById(query.UserId); : _userManager.GetUserById(query.UserId);
var channels = GetAllChannels() var channels = await GetAllChannelEntitiesAsync()
.Select(GetChannelEntity)
.OrderBy(i => i.SortName) .OrderBy(i => i.SortName)
.ToList(); .ToListAsync()
.ConfigureAwait(false);
if (query.IsRecordingsFolder.HasValue) if (query.IsRecordingsFolder.HasValue)
{ {
@ -226,6 +226,7 @@ namespace Emby.Server.Implementations.Channels
if (user is not null) if (user is not null)
{ {
var userId = user.Id.ToString("N", CultureInfo.InvariantCulture);
channels = channels.Where(i => channels = channels.Where(i =>
{ {
if (!i.IsVisible(user)) if (!i.IsVisible(user))
@ -235,7 +236,7 @@ namespace Emby.Server.Implementations.Channels
try try
{ {
return GetChannelProvider(i).IsEnabledFor(user.Id.ToString("N", CultureInfo.InvariantCulture)); return GetChannelProvider(i).IsEnabledFor(userId);
} }
catch catch
{ {
@ -258,7 +259,7 @@ namespace Emby.Server.Implementations.Channels
{ {
foreach (var item in all) foreach (var item in all)
{ {
RefreshLatestChannelItems(GetChannelProvider(item), CancellationToken.None).GetAwaiter().GetResult(); await RefreshLatestChannelItems(GetChannelProvider(item), CancellationToken.None).ConfigureAwait(false);
} }
} }
@ -269,13 +270,13 @@ namespace Emby.Server.Implementations.Channels
} }
/// <inheritdoc /> /// <inheritdoc />
public QueryResult<BaseItemDto> GetChannels(ChannelQuery query) public async Task<QueryResult<BaseItemDto>> GetChannelsAsync(ChannelQuery query)
{ {
var user = query.UserId.Equals(default) var user = query.UserId.Equals(default)
? null ? null
: _userManager.GetUserById(query.UserId); : _userManager.GetUserById(query.UserId);
var internalResult = GetChannelsInternal(query); var internalResult = await GetChannelsInternalAsync(query).ConfigureAwait(false);
var dtoOptions = new DtoOptions(); var dtoOptions = new DtoOptions();
@ -327,9 +328,12 @@ namespace Emby.Server.Implementations.Channels
progress.Report(100); progress.Report(100);
} }
private Channel GetChannelEntity(IChannel channel) private async IAsyncEnumerable<Channel> GetAllChannelEntitiesAsync()
{ {
return GetChannel(GetInternalChannelId(channel.Name)) ?? GetChannel(channel, CancellationToken.None).GetAwaiter().GetResult(); foreach (IChannel channel in GetAllChannels())
{
yield return GetChannel(GetInternalChannelId(channel.Name)) ?? await GetChannel(channel, CancellationToken.None).ConfigureAwait(false);
}
} }
private MediaSourceInfo[] GetSavedMediaSources(BaseItem item) private MediaSourceInfo[] GetSavedMediaSources(BaseItem item)

View File

@ -276,25 +276,31 @@ namespace Emby.Server.Implementations.EntryPoints
/// Libraries the update timer callback. /// Libraries the update timer callback.
/// </summary> /// </summary>
/// <param name="state">The state.</param> /// <param name="state">The state.</param>
private void LibraryUpdateTimerCallback(object state) private async void LibraryUpdateTimerCallback(object state)
{ {
List<Folder> foldersAddedTo;
List<Folder> foldersRemovedFrom;
List<BaseItem> itemsUpdated;
List<BaseItem> itemsAdded;
List<BaseItem> itemsRemoved;
lock (_libraryChangedSyncLock) lock (_libraryChangedSyncLock)
{ {
// Remove dupes in case some were saved multiple times // Remove dupes in case some were saved multiple times
var foldersAddedTo = _foldersAddedTo foldersAddedTo = _foldersAddedTo
.DistinctBy(x => x.Id) .DistinctBy(x => x.Id)
.ToList(); .ToList();
var foldersRemovedFrom = _foldersRemovedFrom foldersRemovedFrom = _foldersRemovedFrom
.DistinctBy(x => x.Id) .DistinctBy(x => x.Id)
.ToList(); .ToList();
var itemsUpdated = _itemsUpdated itemsUpdated = _itemsUpdated
.Where(i => !_itemsAdded.Contains(i)) .Where(i => !_itemsAdded.Contains(i))
.DistinctBy(x => x.Id) .DistinctBy(x => x.Id)
.ToList(); .ToList();
SendChangeNotifications(_itemsAdded.ToList(), itemsUpdated, _itemsRemoved.ToList(), foldersAddedTo, foldersRemovedFrom, CancellationToken.None).GetAwaiter().GetResult(); itemsAdded = _itemsAdded.ToList();
itemsRemoved = _itemsRemoved.ToList();
if (LibraryUpdateTimer is not null) if (LibraryUpdateTimer is not null)
{ {
@ -308,6 +314,8 @@ namespace Emby.Server.Implementations.EntryPoints
_foldersAddedTo.Clear(); _foldersAddedTo.Clear();
_foldersRemovedFrom.Clear(); _foldersRemovedFrom.Clear();
} }
await SendChangeNotifications(itemsAdded, itemsUpdated, itemsRemoved, foldersAddedTo, foldersRemovedFrom, CancellationToken.None).ConfigureAwait(false);
} }
/// <summary> /// <summary>

View File

@ -87,29 +87,30 @@ namespace Emby.Server.Implementations.EntryPoints
} }
} }
private void UpdateTimerCallback(object? state) private async void UpdateTimerCallback(object? state)
{ {
List<KeyValuePair<Guid, List<BaseItem>>> changes;
lock (_syncLock) lock (_syncLock)
{ {
// Remove dupes in case some were saved multiple times // Remove dupes in case some were saved multiple times
var changes = _changedItems.ToList(); changes = _changedItems.ToList();
_changedItems.Clear(); _changedItems.Clear();
SendNotifications(changes, CancellationToken.None).GetAwaiter().GetResult();
if (_updateTimer is not null) if (_updateTimer is not null)
{ {
_updateTimer.Dispose(); _updateTimer.Dispose();
_updateTimer = null; _updateTimer = null;
} }
} }
await SendNotifications(changes, CancellationToken.None).ConfigureAwait(false);
} }
private async Task SendNotifications(List<KeyValuePair<Guid, List<BaseItem>>> changes, CancellationToken cancellationToken) private async Task SendNotifications(List<KeyValuePair<Guid, List<BaseItem>>> changes, CancellationToken cancellationToken)
{ {
foreach (var pair in changes) foreach ((var key, var value) in changes)
{ {
await SendNotifications(pair.Key, pair.Value, cancellationToken).ConfigureAwait(false); await SendNotifications(key, value, cancellationToken).ConfigureAwait(false);
} }
} }

View File

@ -111,10 +111,10 @@ namespace Emby.Server.Implementations.Library
if (query.IncludeExternalContent) if (query.IncludeExternalContent)
{ {
var channelResult = _channelManager.GetChannelsInternal(new ChannelQuery var channelResult = _channelManager.GetChannelsInternalAsync(new ChannelQuery
{ {
UserId = query.UserId UserId = query.UserId
}); }).GetAwaiter().GetResult();
var channels = channelResult.Items; var channels = channelResult.Items;

View File

@ -1312,20 +1312,19 @@ namespace Emby.Server.Implementations.LiveTv
return 7; return 7;
} }
private QueryResult<BaseItem> GetEmbyRecordings(RecordingQuery query, DtoOptions dtoOptions, User user) private async Task<QueryResult<BaseItem>> GetEmbyRecordingsAsync(RecordingQuery query, DtoOptions dtoOptions, User user)
{ {
if (user is null) if (user is null)
{ {
return new QueryResult<BaseItem>(); return new QueryResult<BaseItem>();
} }
var folderIds = GetRecordingFolders(user, true) var folders = await GetRecordingFoldersAsync(user, true).ConfigureAwait(false);
.Select(i => i.Id) var folderIds = Array.ConvertAll(folders, x => x.Id);
.ToList();
var excludeItemTypes = new List<BaseItemKind>(); var excludeItemTypes = new List<BaseItemKind>();
if (folderIds.Count == 0) if (folderIds.Length == 0)
{ {
return new QueryResult<BaseItem>(); return new QueryResult<BaseItem>();
} }
@ -1392,7 +1391,7 @@ namespace Emby.Server.Implementations.LiveTv
{ {
MediaTypes = new[] { MediaType.Video }, MediaTypes = new[] { MediaType.Video },
Recursive = true, Recursive = true,
AncestorIds = folderIds.ToArray(), AncestorIds = folderIds,
IsFolder = false, IsFolder = false,
IsVirtualItem = false, IsVirtualItem = false,
Limit = limit, Limit = limit,
@ -1528,7 +1527,7 @@ namespace Emby.Server.Implementations.LiveTv
} }
} }
public QueryResult<BaseItemDto> GetRecordings(RecordingQuery query, DtoOptions options) public async Task<QueryResult<BaseItemDto>> GetRecordingsAsync(RecordingQuery query, DtoOptions options)
{ {
var user = query.UserId.Equals(default) var user = query.UserId.Equals(default)
? null ? null
@ -1536,7 +1535,7 @@ namespace Emby.Server.Implementations.LiveTv
RemoveFields(options); RemoveFields(options);
var internalResult = GetEmbyRecordings(query, options, user); var internalResult = await GetEmbyRecordingsAsync(query, options, user).ConfigureAwait(false);
var returnArray = _dtoService.GetBaseItemDtos(internalResult.Items, options, user); var returnArray = _dtoService.GetBaseItemDtos(internalResult.Items, options, user);
@ -2379,12 +2378,11 @@ namespace Emby.Server.Implementations.LiveTv
return _tvDtoService.GetInternalProgramId(externalId); return _tvDtoService.GetInternalProgramId(externalId);
} }
public List<BaseItem> GetRecordingFolders(User user) /// <inheritdoc />
{ public Task<BaseItem[]> GetRecordingFoldersAsync(User user)
return GetRecordingFolders(user, false); => GetRecordingFoldersAsync(user, false);
}
private List<BaseItem> GetRecordingFolders(User user, bool refreshChannels) private async Task<BaseItem[]> GetRecordingFoldersAsync(User user, bool refreshChannels)
{ {
var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders() var folders = EmbyTV.EmbyTV.Current.GetRecordingFolders()
.SelectMany(i => i.Locations) .SelectMany(i => i.Locations)
@ -2396,14 +2394,16 @@ namespace Emby.Server.Implementations.LiveTv
.OrderBy(i => i.SortName) .OrderBy(i => i.SortName)
.ToList(); .ToList();
folders.AddRange(_channelManager.GetChannelsInternal(new MediaBrowser.Model.Channels.ChannelQuery var channels = await _channelManager.GetChannelsInternalAsync(new MediaBrowser.Model.Channels.ChannelQuery
{ {
UserId = user.Id, UserId = user.Id,
IsRecordingsFolder = true, IsRecordingsFolder = true,
RefreshLatestChannelItems = refreshChannels RefreshLatestChannelItems = refreshChannels
}).Items); }).ConfigureAwait(false);
return folders.Cast<BaseItem>().ToList(); folders.AddRange(channels.Items);
return folders.Cast<BaseItem>().ToArray();
} }
} }
} }

View File

@ -52,7 +52,7 @@ public class ChannelsController : BaseJellyfinApiController
/// <returns>An <see cref="OkResult"/> containing the channels.</returns> /// <returns>An <see cref="OkResult"/> containing the channels.</returns>
[HttpGet] [HttpGet]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
public ActionResult<QueryResult<BaseItemDto>> GetChannels( public async Task<ActionResult<QueryResult<BaseItemDto>>> GetChannels(
[FromQuery] Guid? userId, [FromQuery] Guid? userId,
[FromQuery] int? startIndex, [FromQuery] int? startIndex,
[FromQuery] int? limit, [FromQuery] int? limit,
@ -61,7 +61,7 @@ public class ChannelsController : BaseJellyfinApiController
[FromQuery] bool? isFavorite) [FromQuery] bool? isFavorite)
{ {
userId = RequestHelpers.GetUserId(User, userId); userId = RequestHelpers.GetUserId(User, userId);
return _channelManager.GetChannels(new ChannelQuery return await _channelManager.GetChannelsAsync(new ChannelQuery
{ {
Limit = limit, Limit = limit,
StartIndex = startIndex, StartIndex = startIndex,
@ -69,7 +69,7 @@ public class ChannelsController : BaseJellyfinApiController
SupportsLatestItems = supportsLatestItems, SupportsLatestItems = supportsLatestItems,
SupportsMediaDeletion = supportsMediaDeletion, SupportsMediaDeletion = supportsMediaDeletion,
IsFavorite = isFavorite IsFavorite = isFavorite
}); }).ConfigureAwait(false);
} }
/// <summary> /// <summary>

View File

@ -252,7 +252,7 @@ public class LiveTvController : BaseJellyfinApiController
[HttpGet("Recordings")] [HttpGet("Recordings")]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[Authorize(Policy = Policies.LiveTvAccess)] [Authorize(Policy = Policies.LiveTvAccess)]
public ActionResult<QueryResult<BaseItemDto>> GetRecordings( public async Task<ActionResult<QueryResult<BaseItemDto>>> GetRecordings(
[FromQuery] string? channelId, [FromQuery] string? channelId,
[FromQuery] Guid? userId, [FromQuery] Guid? userId,
[FromQuery] int? startIndex, [FromQuery] int? startIndex,
@ -278,7 +278,7 @@ public class LiveTvController : BaseJellyfinApiController
.AddClientFields(User) .AddClientFields(User)
.AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes); .AddAdditionalDtoOptions(enableImages, enableUserData, imageTypeLimit, enableImageTypes);
return _liveTvManager.GetRecordings( return await _liveTvManager.GetRecordingsAsync(
new RecordingQuery new RecordingQuery
{ {
ChannelId = channelId, ChannelId = channelId,
@ -299,7 +299,7 @@ public class LiveTvController : BaseJellyfinApiController
ImageTypeLimit = imageTypeLimit, ImageTypeLimit = imageTypeLimit,
EnableImages = enableImages EnableImages = enableImages
}, },
dtoOptions); dtoOptions).ConfigureAwait(false);
} }
/// <summary> /// <summary>
@ -383,13 +383,13 @@ public class LiveTvController : BaseJellyfinApiController
[HttpGet("Recordings/Folders")] [HttpGet("Recordings/Folders")]
[ProducesResponseType(StatusCodes.Status200OK)] [ProducesResponseType(StatusCodes.Status200OK)]
[Authorize(Policy = Policies.LiveTvAccess)] [Authorize(Policy = Policies.LiveTvAccess)]
public ActionResult<QueryResult<BaseItemDto>> GetRecordingFolders([FromQuery] Guid? userId) public async Task<ActionResult<QueryResult<BaseItemDto>>> GetRecordingFolders([FromQuery] Guid? userId)
{ {
userId = RequestHelpers.GetUserId(User, userId); userId = RequestHelpers.GetUserId(User, userId);
var user = userId.Value.Equals(default) var user = userId.Value.Equals(default)
? null ? null
: _userManager.GetUserById(userId.Value); : _userManager.GetUserById(userId.Value);
var folders = _liveTvManager.GetRecordingFolders(user); var folders = await _liveTvManager.GetRecordingFoldersAsync(user).ConfigureAwait(false);
var returnArray = _dtoService.GetBaseItemDtos(folders, new DtoOptions(), user); var returnArray = _dtoService.GetBaseItemDtos(folders, new DtoOptions(), user);

View File

@ -56,8 +56,8 @@ public class ActivityLogWebSocketListener : BasePeriodicWebSocketListener<Activi
base.Dispose(dispose); base.Dispose(dispose);
} }
private void OnEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e) private async void OnEntryCreated(object? sender, GenericEventArgs<ActivityLogEntry> e)
{ {
SendData(true).GetAwaiter().GetResult(); await SendData(true).ConfigureAwait(false);
} }
} }

View File

@ -46,14 +46,14 @@ namespace MediaBrowser.Controller.Channels
/// </summary> /// </summary>
/// <param name="query">The query.</param> /// <param name="query">The query.</param>
/// <returns>The channels.</returns> /// <returns>The channels.</returns>
QueryResult<Channel> GetChannelsInternal(ChannelQuery query); Task<QueryResult<Channel>> GetChannelsInternalAsync(ChannelQuery query);
/// <summary> /// <summary>
/// Gets the channels. /// Gets the channels.
/// </summary> /// </summary>
/// <param name="query">The query.</param> /// <param name="query">The query.</param>
/// <returns>The channels.</returns> /// <returns>The channels.</returns>
QueryResult<BaseItemDto> GetChannels(ChannelQuery query); Task<QueryResult<BaseItemDto>> GetChannelsAsync(ChannelQuery query);
/// <summary> /// <summary>
/// Gets the latest channel items. /// Gets the latest channel items.

View File

@ -97,7 +97,7 @@ namespace MediaBrowser.Controller.LiveTv
/// <param name="query">The query.</param> /// <param name="query">The query.</param>
/// <param name="options">The options.</param> /// <param name="options">The options.</param>
/// <returns>A recording.</returns> /// <returns>A recording.</returns>
QueryResult<BaseItemDto> GetRecordings(RecordingQuery query, DtoOptions options); Task<QueryResult<BaseItemDto>> GetRecordingsAsync(RecordingQuery query, DtoOptions options);
/// <summary> /// <summary>
/// Gets the timers. /// Gets the timers.
@ -308,6 +308,6 @@ namespace MediaBrowser.Controller.LiveTv
void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, ActiveRecordingInfo activeRecordingInfo, User user = null); void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, ActiveRecordingInfo activeRecordingInfo, User user = null);
List<BaseItem> GetRecordingFolders(User user); Task<BaseItem[]> GetRecordingFoldersAsync(User user);
} }
} }

View File

@ -44,32 +44,24 @@ namespace MediaBrowser.Model.Dlna
{ {
ValidateMediaOptions(options, false); ValidateMediaOptions(options, false);
var mediaSources = new List<MediaSourceInfo>(); var streams = new List<StreamInfo>();
foreach (var mediaSource in options.MediaSources) foreach (var mediaSource in options.MediaSources)
{ {
if (string.IsNullOrEmpty(options.MediaSourceId) if (!(string.IsNullOrEmpty(options.MediaSourceId)
|| string.Equals(mediaSource.Id, options.MediaSourceId, StringComparison.OrdinalIgnoreCase)) || string.Equals(mediaSource.Id, options.MediaSourceId, StringComparison.OrdinalIgnoreCase)))
{ {
mediaSources.Add(mediaSource); continue;
}
} }
var streams = new List<StreamInfo>(); StreamInfo? streamInfo = GetOptimalAudioStream(mediaSource, options);
foreach (var mediaSourceInfo in mediaSources)
{
StreamInfo? streamInfo = GetOptimalAudioStream(mediaSourceInfo, options);
if (streamInfo is not null) if (streamInfo is not null)
{ {
streamInfo.DeviceId = options.DeviceId;
streamInfo.DeviceProfileId = options.Profile.Id;
streams.Add(streamInfo); streams.Add(streamInfo);
} }
} }
foreach (var stream in streams)
{
stream.DeviceId = options.DeviceId;
stream.DeviceProfileId = options.Profile.Id;
}
return GetOptimalStream(streams, options.GetMaxBitrate(true) ?? 0); return GetOptimalStream(streams, options.GetMaxBitrate(true) ?? 0);
} }
@ -399,7 +391,6 @@ namespace MediaBrowser.Model.Dlna
return (null, null, GetTranscodeReasonsFromDirectPlayProfile(item, null, audioStream, options.Profile.DirectPlayProfiles)); return (null, null, GetTranscodeReasonsFromDirectPlayProfile(item, null, audioStream, options.Profile.DirectPlayProfiles));
} }
var playMethods = new List<PlayMethod>();
TranscodeReason transcodeReasons = 0; TranscodeReason transcodeReasons = 0;
// The profile describes what the device supports // The profile describes what the device supports

View File

@ -53,7 +53,7 @@ namespace MediaBrowser.Providers.Plugins.StudioImages
/// <inheritdoc /> /// <inheritdoc />
public IEnumerable<ImageType> GetSupportedImages(BaseItem item) public IEnumerable<ImageType> GetSupportedImages(BaseItem item)
{ {
return new List<ImageType> return new ImageType[]
{ {
ImageType.Thumb ImageType.Thumb
}; };