Files
stream-cinema/CinemaJellyfin/CinemaSubfolderHelper.cs
Roman Vaníček 591a92f6aa
All checks were successful
continuous-integration/drone/push Build is passing
TV Series playback works
2024-12-02 00:13:40 +01:00

100 lines
2.7 KiB
C#

using CinemaLib.API;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Model.Querying;
namespace Jellyfin.Plugin.Cinema;
/// <summary>
/// Helper data for Cinema items that inherit from a <see cref="Folder"/>.
/// </summary>
struct CinemaSubfolderHelper
{
private readonly Folder @this;
private readonly FilterSortBy _sortBy;
private int? _childrenCount;
private int? _totalChildrenCount;
private FilterResponse? _cached;
private DateTime _cacheValidTo;
internal CinemaSubfolderHelper(Folder @this, FilterSortBy sortBy)
{
this.@this = @this;
this._sortBy = sortBy;
}
public int ChildrenCount
{
get
{
if (_childrenCount == 0)
EnsureCached();
return _childrenCount ?? 0;
}
set
{
_childrenCount = value;
}
}
public int TotalChildrenCount
{
get
{
if (_totalChildrenCount == 0)
EnsureCached();
return _totalChildrenCount ?? 0;
}
set
{
_totalChildrenCount = value;
}
}
internal QueryResult<BaseItem> GetItemsInternal<TContainerType>(InternalItemsQuery query, bool allowSubfolders)
where TContainerType : Folder, new()
{
FilterResponse filterRes = EnsureCached();
List<BaseItem> items = new List<BaseItem>();
QueryResult<BaseItem> result = new QueryResult<BaseItem>() { Items = items };
if (filterRes != null && filterRes.hits != null && filterRes.hits.hits != null)
{
if (filterRes.hits.total != null)
result.TotalRecordCount = (int)filterRes.hits.total.value;
foreach (var i in filterRes.hits.hits)
{
if (i._source.TryCreateMediaItem<TContainerType>(i._id, @this, allowSubfolders, out BaseItem? a))
items.Add(a);
}
}
return result;
}
private FilterResponse EnsureCached()
{
DateTime now = DateTime.UtcNow;
if (_cached != null && _cacheValidTo > now)
return _cached;
string? csId;
if (!CinemaQueryExtensions.TryGetCinemaIdFromExternalId(@this.ExternalId, out csId))
throw new InvalidOperationException("Expected Cinema ID to be present.");
FilterResponse? filterRes = Metadata.ChildrenAsync(csId, order: ItemOrder.Ascending, sort: _sortBy).GetAwaiter().GetResult();
if (filterRes != null && filterRes.hits != null && filterRes.hits.hits != null)
{
_childrenCount = filterRes.hits.hits.Count;
_totalChildrenCount = filterRes.hits.total != null ? (int)filterRes.hits.total.value : 0;
}
else
{
_childrenCount = 0;
_totalChildrenCount = 0;
}
_cached = filterRes ?? new FilterResponse();
_cacheValidTo = now + CinemaMediaSourceManager.SubfolderValidityTimeout;
return _cached;
}
}