jellyfin/Emby.Server.Implementations/Channels/ChannelManager.cs

1233 lines
44 KiB
C#
Raw Normal View History

#nullable disable
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
2020-05-20 17:07:53 +00:00
using Jellyfin.Data.Entities;
2020-07-01 01:44:41 +00:00
using Jellyfin.Data.Enums;
using Jellyfin.Extensions.Json;
2021-10-02 18:11:59 +00:00
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.Progress;
2014-03-18 01:45:41 +00:00
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
using MediaBrowser.Controller.Entities.Audio;
2014-03-18 01:45:41 +00:00
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Providers;
using MediaBrowser.Model.Channels;
using MediaBrowser.Model.Dto;
2014-05-03 04:20:04 +00:00
using MediaBrowser.Model.Entities;
using MediaBrowser.Model.IO;
2014-03-18 01:45:41 +00:00
using MediaBrowser.Model.Querying;
2020-07-29 21:33:40 +00:00
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
2020-05-20 17:07:53 +00:00
using Episode = MediaBrowser.Controller.Entities.TV.Episode;
using Movie = MediaBrowser.Controller.Entities.Movies.Movie;
using MusicAlbum = MediaBrowser.Controller.Entities.Audio.MusicAlbum;
using Season = MediaBrowser.Controller.Entities.TV.Season;
using Series = MediaBrowser.Controller.Entities.TV.Series;
2014-03-18 01:45:41 +00:00
namespace Emby.Server.Implementations.Channels
2014-03-18 01:45:41 +00:00
{
/// <summary>
/// The LiveTV channel manager.
/// </summary>
public class ChannelManager : IChannelManager
2014-03-18 01:45:41 +00:00
{
private readonly IUserManager _userManager;
2014-05-03 04:20:04 +00:00
private readonly IUserDataManager _userDataManager;
2014-03-18 01:45:41 +00:00
private readonly IDtoService _dtoService;
private readonly ILibraryManager _libraryManager;
2020-06-06 00:15:56 +00:00
private readonly ILogger<ChannelManager> _logger;
2014-03-18 01:45:41 +00:00
private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
2015-10-17 15:05:12 +00:00
private readonly IProviderManager _providerManager;
2020-07-29 21:33:40 +00:00
private readonly IMemoryCache _memoryCache;
2020-04-11 10:03:10 +00:00
private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1);
2021-03-09 04:57:38 +00:00
private readonly JsonSerializerOptions _jsonOptions = JsonDefaults.Options;
2020-05-13 02:10:35 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="ChannelManager"/> class.
/// </summary>
/// <param name="userManager">The user manager.</param>
/// <param name="dtoService">The dto service.</param>
/// <param name="libraryManager">The library manager.</param>
/// <param name="logger">The logger.</param>
/// <param name="config">The server configuration manager.</param>
/// <param name="fileSystem">The filesystem.</param>
/// <param name="userDataManager">The user data manager.</param>
/// <param name="providerManager">The provider manager.</param>
2020-07-29 21:33:40 +00:00
/// <param name="memoryCache">The memory cache.</param>
public ChannelManager(
IUserManager userManager,
IDtoService dtoService,
ILibraryManager libraryManager,
2020-04-11 10:03:10 +00:00
ILogger<ChannelManager> logger,
IServerConfigurationManager config,
IFileSystem fileSystem,
IUserDataManager userDataManager,
2020-07-29 21:33:40 +00:00
IProviderManager providerManager,
IMemoryCache memoryCache)
2014-03-18 01:45:41 +00:00
{
_userManager = userManager;
_dtoService = dtoService;
_libraryManager = libraryManager;
2020-04-11 10:03:10 +00:00
_logger = logger;
2014-03-18 01:45:41 +00:00
_config = config;
_fileSystem = fileSystem;
2014-05-03 04:20:04 +00:00
_userDataManager = userDataManager;
2015-10-17 15:05:12 +00:00
_providerManager = providerManager;
2020-07-29 21:33:40 +00:00
_memoryCache = memoryCache;
2014-03-18 01:45:41 +00:00
}
2020-04-11 10:03:10 +00:00
internal IChannel[] Channels { get; private set; }
private static TimeSpan CacheLength => TimeSpan.FromHours(3);
/// <inheritdoc />
2015-09-16 03:55:26 +00:00
public void AddParts(IEnumerable<IChannel> channels)
2014-03-18 01:45:41 +00:00
{
Channels = channels.ToArray();
2014-05-03 23:38:23 +00:00
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public bool EnableMediaSourceDisplay(BaseItem item)
{
var internalChannel = _libraryManager.GetItemById(item.ChannelId);
var channel = Channels.FirstOrDefault(i => GetInternalChannelId(i.Name).Equals(internalChannel.Id));
2021-08-28 22:32:50 +00:00
return channel is not IDisableMediaSourceDisplay;
2018-09-12 17:26:21 +00:00
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public bool CanDelete(BaseItem item)
{
var internalChannel = _libraryManager.GetItemById(item.ChannelId);
var channel = Channels.FirstOrDefault(i => GetInternalChannelId(i.Name).Equals(internalChannel.Id));
return channel is ISupportsDelete supportsDelete && supportsDelete.CanDelete(item);
2018-09-12 17:26:21 +00:00
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public bool EnableMediaProbe(BaseItem item)
{
var internalChannel = _libraryManager.GetItemById(item.ChannelId);
var channel = Channels.FirstOrDefault(i => GetInternalChannelId(i.Name).Equals(internalChannel.Id));
return channel is ISupportsMediaProbe;
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public Task DeleteItem(BaseItem item)
{
var internalChannel = _libraryManager.GetItemById(item.ChannelId);
if (internalChannel == null)
{
throw new ArgumentException();
}
var channel = Channels.FirstOrDefault(i => GetInternalChannelId(i.Name).Equals(internalChannel.Id));
var supportsDelete = channel as ISupportsDelete;
if (supportsDelete == null)
{
throw new ArgumentException();
}
return supportsDelete.DeleteItem(item.ExternalId, CancellationToken.None);
}
2014-05-03 23:38:23 +00:00
private IEnumerable<IChannel> GetAllChannels()
{
return Channels
2014-05-03 23:38:23 +00:00
.OrderBy(i => i.Name);
2014-03-18 01:45:41 +00:00
}
/// <summary>
2020-04-19 17:39:12 +00:00
/// Get the installed channel IDs.
/// </summary>
2020-04-19 17:39:12 +00:00
/// <returns>An <see cref="IEnumerable{T}"/> containing installed channel IDs.</returns>
2015-11-21 05:01:16 +00:00
public IEnumerable<Guid> GetInstalledChannelIds()
{
return GetAllChannels().Select(i => GetInternalChannelId(i.Name));
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public QueryResult<Channel> GetChannelsInternal(ChannelQuery query)
2014-03-18 01:45:41 +00:00
{
2018-09-12 17:26:21 +00:00
var user = query.UserId.Equals(Guid.Empty)
2014-03-18 01:45:41 +00:00
? null
2014-09-14 15:10:51 +00:00
: _userManager.GetUserById(query.UserId);
2014-03-18 01:45:41 +00:00
var channels = GetAllChannels()
.Select(GetChannelEntity)
.OrderBy(i => i.SortName)
.ToList();
2014-03-18 01:45:41 +00:00
2018-09-12 17:26:21 +00:00
if (query.IsRecordingsFolder.HasValue)
{
var val = query.IsRecordingsFolder.Value;
channels = channels.Where(i =>
{
try
{
return (GetChannelProvider(i) is IHasFolderAttributes hasAttributes
2020-04-11 10:03:10 +00:00
&& hasAttributes.Attributes.Contains("Recordings", StringComparer.OrdinalIgnoreCase)) == val;
2018-09-12 17:26:21 +00:00
}
catch
{
return false;
}
}).ToList();
}
2014-06-17 16:03:14 +00:00
if (query.SupportsLatestItems.HasValue)
{
var val = query.SupportsLatestItems.Value;
channels = channels.Where(i =>
{
try
{
2016-03-27 21:11:27 +00:00
return GetChannelProvider(i) is ISupportsLatestMedia == val;
}
catch
{
return false;
}
}).ToList();
2014-06-17 16:03:14 +00:00
}
2018-09-12 17:26:21 +00:00
if (query.SupportsMediaDeletion.HasValue)
{
var val = query.SupportsMediaDeletion.Value;
channels = channels.Where(i =>
{
try
{
return GetChannelProvider(i) is ISupportsDelete == val;
}
catch
{
return false;
}
}).ToList();
}
2014-06-23 16:05:19 +00:00
if (query.IsFavorite.HasValue)
{
var val = query.IsFavorite.Value;
2017-05-26 06:48:54 +00:00
channels = channels.Where(i => _userDataManager.GetUserData(user, i).IsFavorite == val)
2014-06-23 16:05:19 +00:00
.ToList();
}
2014-06-17 16:03:14 +00:00
2014-03-18 01:45:41 +00:00
if (user != null)
{
2015-10-19 15:33:49 +00:00
channels = channels.Where(i =>
{
if (!i.IsVisible(user))
{
return false;
}
try
{
return GetChannelProvider(i).IsEnabledFor(user.Id.ToString("N", CultureInfo.InvariantCulture));
2015-10-19 15:33:49 +00:00
}
catch
{
return false;
}
}).ToList();
2014-03-18 01:45:41 +00:00
}
2014-05-14 18:04:26 +00:00
var all = channels;
var totalCount = all.Count;
2020-11-06 15:15:30 +00:00
if (query.StartIndex.HasValue || query.Limit.HasValue)
2014-05-14 18:04:26 +00:00
{
2020-11-06 15:15:30 +00:00
int startIndex = query.StartIndex ?? 0;
int count = query.Limit == null ? totalCount - startIndex : Math.Min(query.Limit.Value, totalCount - startIndex);
all = all.GetRange(startIndex, count);
2014-05-14 18:04:26 +00:00
}
2018-09-12 17:26:21 +00:00
if (query.RefreshLatestChannelItems)
{
2020-11-06 15:15:30 +00:00
foreach (var item in all)
2018-09-12 17:26:21 +00:00
{
RefreshLatestChannelItems(GetChannelProvider(item), CancellationToken.None).GetAwaiter().GetResult();
2018-09-12 17:26:21 +00:00
}
}
return new QueryResult<Channel>
2014-07-30 03:31:35 +00:00
{
2020-11-06 15:15:30 +00:00
Items = all,
2014-07-30 03:31:35 +00:00
TotalRecordCount = totalCount
};
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public QueryResult<BaseItemDto> GetChannels(ChannelQuery query)
2014-07-30 03:31:35 +00:00
{
2018-09-12 17:26:21 +00:00
var user = query.UserId.Equals(Guid.Empty)
2014-07-30 03:31:35 +00:00
? null
2014-09-14 15:10:51 +00:00
: _userManager.GetUserById(query.UserId);
2014-07-30 03:31:35 +00:00
2018-09-12 17:26:21 +00:00
var internalResult = GetChannelsInternal(query);
2014-07-30 03:31:35 +00:00
2020-04-11 10:03:10 +00:00
var dtoOptions = new DtoOptions();
2014-03-18 01:45:41 +00:00
2020-04-11 10:03:10 +00:00
// TODO Fix The co-variant conversion (internalResult.Items) between Folder[] and BaseItem[], this can generate runtime issues.
2017-08-28 00:33:05 +00:00
var returnItems = _dtoService.GetBaseItemDtos(internalResult.Items, dtoOptions, user);
2014-03-18 01:45:41 +00:00
var result = new QueryResult<BaseItemDto>
{
Items = returnItems,
2014-07-30 03:31:35 +00:00
TotalRecordCount = internalResult.TotalRecordCount
2014-03-18 01:45:41 +00:00
};
2014-07-30 03:31:35 +00:00
return result;
2014-03-18 01:45:41 +00:00
}
/// <summary>
/// Refreshes the associated channels.
/// </summary>
/// <param name="progress">The progress.</param>
2020-04-19 17:39:12 +00:00
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
/// <returns>The completed task.</returns>
2014-03-18 01:45:41 +00:00
public async Task RefreshChannels(IProgress<double> progress, CancellationToken cancellationToken)
{
2014-05-03 23:38:23 +00:00
var allChannelsList = GetAllChannels().ToList();
2014-03-18 01:45:41 +00:00
var numComplete = 0;
foreach (var channelInfo in allChannelsList)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
2015-10-25 17:13:30 +00:00
await GetChannel(channelInfo, cancellationToken).ConfigureAwait(false);
2014-03-18 01:45:41 +00:00
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error getting channel information for {0}", channelInfo.Name);
2014-03-18 01:45:41 +00:00
}
numComplete++;
double percent = (double)numComplete / allChannelsList.Count;
2014-03-18 01:45:41 +00:00
progress.Report(100 * percent);
}
progress.Report(100);
}
private Channel GetChannelEntity(IChannel channel)
{
return GetChannel(GetInternalChannelId(channel.Name)) ?? GetChannel(channel, CancellationToken.None).Result;
}
private MediaSourceInfo[] GetSavedMediaSources(BaseItem item)
2016-10-31 05:51:43 +00:00
{
2018-09-12 17:26:21 +00:00
var path = Path.Combine(item.GetInternalMetadataPath(), "channelmediasourceinfos.json");
2016-10-31 05:51:43 +00:00
try
{
var bytes = File.ReadAllBytes(path);
return JsonSerializer.Deserialize<MediaSourceInfo[]>(bytes, _jsonOptions)
?? Array.Empty<MediaSourceInfo>();
2016-10-31 05:51:43 +00:00
}
catch
{
return Array.Empty<MediaSourceInfo>();
2016-10-31 05:51:43 +00:00
}
}
private async Task SaveMediaSources(BaseItem item, List<MediaSourceInfo> mediaSources)
2016-10-31 05:51:43 +00:00
{
2018-09-12 17:26:21 +00:00
var path = Path.Combine(item.GetInternalMetadataPath(), "channelmediasourceinfos.json");
2016-10-31 05:51:43 +00:00
if (mediaSources == null || mediaSources.Count == 0)
{
try
{
_fileSystem.DeleteFile(path);
}
catch
{
}
2020-04-11 10:03:10 +00:00
2016-10-31 05:51:43 +00:00
return;
}
Directory.CreateDirectory(Path.GetDirectoryName(path));
2020-12-24 09:31:51 +00:00
await using FileStream createStream = File.Create(path);
await JsonSerializer.SerializeAsync(createStream, mediaSources, _jsonOptions).ConfigureAwait(false);
2016-10-31 05:51:43 +00:00
}
/// <inheritdoc />
2017-05-26 06:48:54 +00:00
public IEnumerable<MediaSourceInfo> GetStaticMediaSources(BaseItem item, CancellationToken cancellationToken)
2014-05-18 19:58:42 +00:00
{
2018-09-12 17:26:21 +00:00
IEnumerable<MediaSourceInfo> results = GetSavedMediaSources(item);
2014-05-18 19:58:42 +00:00
2018-09-12 17:26:21 +00:00
return results
.Select(i => NormalizeMediaSource(item, i))
2015-03-28 20:22:27 +00:00
.ToList();
}
/// <summary>
/// Gets the dynamic media sources based on the provided item.
/// </summary>
/// <param name="item">The item.</param>
2020-04-19 17:39:12 +00:00
/// <param name="cancellationToken">A cancellation token that can be used to cancel the operation.</param>
/// <returns>The task representing the operation to get the media sources.</returns>
2016-03-19 04:22:33 +00:00
public async Task<IEnumerable<MediaSourceInfo>> GetDynamicMediaSources(BaseItem item, CancellationToken cancellationToken)
2015-03-28 20:22:27 +00:00
{
var channel = GetChannel(item.ChannelId);
2014-05-18 22:26:06 +00:00
var channelPlugin = GetChannelProvider(channel);
2014-05-18 19:58:42 +00:00
2018-09-12 17:26:21 +00:00
IEnumerable<MediaSourceInfo> results;
2014-06-02 19:32:41 +00:00
2020-04-11 10:03:10 +00:00
if (channelPlugin is IRequiresMediaInfoCallback requiresCallback)
2014-05-18 19:58:42 +00:00
{
results = await GetChannelItemMediaSourcesInternal(requiresCallback, item.ExternalId, cancellationToken)
2015-03-28 20:22:27 +00:00
.ConfigureAwait(false);
2014-06-02 19:32:41 +00:00
}
else
{
2018-09-12 17:26:21 +00:00
results = new List<MediaSourceInfo>();
2014-05-18 19:58:42 +00:00
}
2018-09-12 17:26:21 +00:00
return results
.Select(i => NormalizeMediaSource(item, i))
2014-06-02 19:32:41 +00:00
.ToList();
}
2018-09-12 17:26:21 +00:00
private async Task<IEnumerable<MediaSourceInfo>> GetChannelItemMediaSourcesInternal(IRequiresMediaInfoCallback channel, string id, CancellationToken cancellationToken)
2014-06-20 04:50:30 +00:00
{
2020-07-29 21:33:40 +00:00
if (_memoryCache.TryGetValue(id, out List<MediaSourceInfo> cachedInfo))
2014-06-20 04:50:30 +00:00
{
2020-07-29 21:33:40 +00:00
return cachedInfo;
2014-06-20 04:50:30 +00:00
}
var mediaInfo = await channel.GetChannelItemMediaInfo(id, cancellationToken)
.ConfigureAwait(false);
var list = mediaInfo.ToList();
2020-08-07 17:22:18 +00:00
_memoryCache.Set(id, list, DateTimeOffset.UtcNow.AddMinutes(5));
2014-06-20 04:50:30 +00:00
return list;
}
private static MediaSourceInfo NormalizeMediaSource(BaseItem item, MediaSourceInfo info)
2014-06-03 02:01:30 +00:00
{
info.RunTimeTicks ??= item.RunTimeTicks;
2014-06-03 02:01:30 +00:00
2018-09-12 17:26:21 +00:00
return info;
2014-05-18 19:58:42 +00:00
}
2014-03-18 01:45:41 +00:00
private async Task<Channel> GetChannel(IChannel channelInfo, CancellationToken cancellationToken)
{
2018-09-12 17:26:21 +00:00
var parentFolderId = Guid.Empty;
2015-11-21 05:01:16 +00:00
2015-01-24 04:50:45 +00:00
var id = GetInternalChannelId(channelInfo.Name);
var path = Channel.GetInternalMetadataPath(_config.ApplicationPaths.InternalMetadataPath, id);
2014-03-18 01:45:41 +00:00
var isNew = false;
2015-11-21 05:01:16 +00:00
var forceUpdate = false;
2014-03-18 01:45:41 +00:00
var item = _libraryManager.GetItemById(id) as Channel;
if (item == null)
{
item = new Channel
{
Name = channelInfo.Name,
Id = id,
2015-10-04 03:38:46 +00:00
DateCreated = _fileSystem.GetCreationTimeUtc(path),
2015-11-21 05:01:16 +00:00
DateModified = _fileSystem.GetLastWriteTimeUtc(path)
2014-03-18 01:45:41 +00:00
};
isNew = true;
}
2015-11-21 05:01:16 +00:00
if (!string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase))
2015-11-06 15:02:22 +00:00
{
2015-11-21 04:57:11 +00:00
isNew = true;
2015-11-02 17:25:01 +00:00
}
2020-04-11 10:03:10 +00:00
2015-11-21 05:01:16 +00:00
item.Path = path;
2018-09-12 17:26:21 +00:00
if (!item.ChannelId.Equals(id))
2015-11-21 05:01:16 +00:00
{
forceUpdate = true;
}
2020-04-11 10:03:10 +00:00
2018-09-12 17:26:21 +00:00
item.ChannelId = id;
2015-11-21 05:01:16 +00:00
if (item.ParentId != parentFolderId)
{
forceUpdate = true;
}
2020-04-11 10:03:10 +00:00
2015-11-21 05:01:16 +00:00
item.ParentId = parentFolderId;
2015-09-29 17:35:23 +00:00
2014-06-07 19:46:24 +00:00
item.OfficialRating = GetOfficialRating(channelInfo.ParentalRating);
item.Overview = channelInfo.Description;
2014-03-18 01:45:41 +00:00
2015-10-20 02:06:05 +00:00
if (string.IsNullOrWhiteSpace(item.Name))
2014-03-18 01:45:41 +00:00
{
item.Name = channelInfo.Name;
}
2015-11-21 04:57:11 +00:00
2015-11-21 05:01:16 +00:00
if (isNew)
{
2018-09-12 17:26:21 +00:00
item.OnMetadataChanged();
_libraryManager.CreateItem(item, null);
2015-11-21 05:01:16 +00:00
}
2018-09-12 17:26:21 +00:00
2020-04-11 10:03:10 +00:00
await item.RefreshMetadata(
new MetadataRefreshOptions(new DirectoryService(_fileSystem))
{
ForceSave = !isNew && forceUpdate
},
cancellationToken).ConfigureAwait(false);
2014-03-18 01:45:41 +00:00
return item;
}
private static string GetOfficialRating(ChannelParentalRating rating)
2014-06-06 17:14:02 +00:00
{
return rating switch
{
ChannelParentalRating.Adult => "XXX",
ChannelParentalRating.UsR => "R",
ChannelParentalRating.UsPG13 => "PG-13",
ChannelParentalRating.UsPG => "PG",
_ => null
};
2014-06-06 17:14:02 +00:00
}
/// <summary>
/// Gets a channel with the provided Guid.
/// </summary>
/// <param name="id">The Guid.</param>
/// <returns>The corresponding channel.</returns>
2018-09-12 17:26:21 +00:00
public Channel GetChannel(Guid id)
{
return _libraryManager.GetItemById(id) as Channel;
}
/// <inheritdoc />
public Channel GetChannel(string id)
{
2016-03-19 19:32:37 +00:00
return _libraryManager.GetItemById(id) as Channel;
}
/// <inheritdoc />
2017-08-19 19:43:35 +00:00
public ChannelFeatures[] GetAllChannelFeatures()
2014-06-02 19:32:41 +00:00
{
2020-04-11 10:03:10 +00:00
return _libraryManager.GetItemIds(
new InternalItemsQuery
{
2020-12-01 18:09:01 +00:00
IncludeItemTypes = new[] { nameof(Channel) },
OrderBy = new[] { (ItemSortBy.SortName, SortOrder.Ascending) }
}).Select(i => GetChannelFeatures(i)).ToArray();
2014-06-02 19:32:41 +00:00
}
/// <inheritdoc />
public ChannelFeatures GetChannelFeatures(Guid? id)
2014-05-27 17:09:48 +00:00
{
if (!id.HasValue)
2016-03-19 19:32:37 +00:00
{
throw new ArgumentNullException(nameof(id));
2016-03-19 19:32:37 +00:00
}
var channel = GetChannel(id.Value);
2014-05-27 17:09:48 +00:00
var channelProvider = GetChannelProvider(channel);
2014-06-06 17:14:02 +00:00
return GetChannelFeaturesDto(channel, channelProvider, channelProvider.GetChannelFeatures());
2014-05-27 17:57:29 +00:00
}
/// <summary>
/// Checks whether the provided Guid supports external transfer.
/// </summary>
/// <param name="channelId">The Guid.</param>
/// <returns>Whether or not the provided Guid supports external transfer.</returns>
2018-09-12 17:26:21 +00:00
public bool SupportsExternalTransfer(Guid channelId)
{
var channelProvider = GetChannelProvider(channelId);
return channelProvider.GetChannelFeatures().SupportsContentDownloading;
}
/// <summary>
/// Gets the provided channel's supported features.
/// </summary>
/// <param name="channel">The channel.</param>
/// <param name="provider">The provider.</param>
/// <param name="features">The features.</param>
/// <returns>The supported features.</returns>
2020-04-19 17:39:12 +00:00
public ChannelFeatures GetChannelFeaturesDto(
Channel channel,
2014-06-06 17:14:02 +00:00
IChannel provider,
InternalChannelFeatures features)
2014-05-27 17:57:29 +00:00
{
var supportsLatest = provider is ISupportsLatestMedia;
2014-06-06 17:14:02 +00:00
2014-05-27 17:57:29 +00:00
return new ChannelFeatures
{
CanFilter = !features.MaxPageSize.HasValue,
2014-06-06 17:14:02 +00:00
CanSearch = provider is ISearchableChannel,
2017-08-19 19:43:35 +00:00
ContentTypes = features.ContentTypes.ToArray(),
DefaultSortFields = features.DefaultSortFields.ToArray(),
2014-05-27 17:57:29 +00:00
MaxPageSize = features.MaxPageSize,
2017-08-19 19:43:35 +00:00
MediaTypes = features.MediaTypes.ToArray(),
2014-06-02 19:32:41 +00:00
SupportsSortOrderToggle = features.SupportsSortOrderToggle,
SupportsLatestMedia = supportsLatest,
2014-06-02 19:32:41 +00:00
Name = channel.Name,
Id = channel.Id.ToString("N", CultureInfo.InvariantCulture),
2018-09-12 17:26:21 +00:00
SupportsContentDownloading = features.SupportsContentDownloading,
2014-09-28 15:27:26 +00:00
AutoRefreshLevels = features.AutoRefreshLevels
2014-05-27 17:57:29 +00:00
};
2014-05-27 17:09:48 +00:00
}
2014-03-18 01:45:41 +00:00
private Guid GetInternalChannelId(string name)
{
2018-09-12 17:26:21 +00:00
if (string.IsNullOrEmpty(name))
2014-03-18 01:45:41 +00:00
{
throw new ArgumentNullException(nameof(name));
2014-03-18 01:45:41 +00:00
}
2020-04-11 10:03:10 +00:00
return _libraryManager.GetNewItemId("Channel " + name, typeof(Channel));
2014-03-18 01:45:41 +00:00
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public async Task<QueryResult<BaseItemDto>> GetLatestChannelItems(InternalItemsQuery query, CancellationToken cancellationToken)
2014-09-30 04:47:30 +00:00
{
var internalResult = await GetLatestChannelItemsInternal(query, cancellationToken).ConfigureAwait(false);
2014-12-14 05:23:04 +00:00
var items = internalResult.Items;
var totalRecordCount = internalResult.TotalRecordCount;
2018-09-12 17:26:21 +00:00
var returnItems = _dtoService.GetBaseItemDtos(items, query.DtoOptions, query.User);
2014-09-30 04:47:30 +00:00
var result = new QueryResult<BaseItemDto>
{
Items = returnItems,
2014-12-14 05:23:04 +00:00
TotalRecordCount = totalRecordCount
2014-09-30 04:47:30 +00:00
};
return result;
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public async Task<QueryResult<BaseItem>> GetLatestChannelItemsInternal(InternalItemsQuery query, CancellationToken cancellationToken)
{
2018-09-12 17:26:21 +00:00
var channels = GetAllChannels().Where(i => i is ISupportsLatestMedia).ToArray();
if (query.ChannelIds.Count > 0)
{
// Avoid implicitly captured closure
var ids = query.ChannelIds;
channels = channels
2018-09-12 17:26:21 +00:00
.Where(i => ids.Contains(GetInternalChannelId(i.Name)))
.ToArray();
}
2018-09-12 17:26:21 +00:00
if (channels.Length == 0)
2014-09-28 15:27:26 +00:00
{
2018-09-12 17:26:21 +00:00
return new QueryResult<BaseItem>();
2014-09-28 15:27:26 +00:00
}
2018-09-12 17:26:21 +00:00
foreach (var channel in channels)
{
2018-09-12 17:26:21 +00:00
await RefreshLatestChannelItems(channel, cancellationToken).ConfigureAwait(false);
}
2018-09-12 17:26:21 +00:00
query.IsFolder = false;
2018-09-12 17:26:21 +00:00
// hack for trailers, figure out a better way later
2020-04-11 10:03:10 +00:00
var sortByPremiereDate = channels.Length == 1 && channels[0].GetType().Name.Contains("Trailer", StringComparison.Ordinal);
2014-06-20 04:50:30 +00:00
2018-09-12 17:26:21 +00:00
if (sortByPremiereDate)
2014-06-20 04:50:30 +00:00
{
query.OrderBy = new[]
2014-06-20 04:50:30 +00:00
{
2019-10-20 14:08:40 +00:00
(ItemSortBy.PremiereDate, SortOrder.Descending),
(ItemSortBy.ProductionYear, SortOrder.Descending),
(ItemSortBy.DateCreated, SortOrder.Descending)
2018-09-12 17:26:21 +00:00
};
2014-06-20 04:50:30 +00:00
}
2018-09-12 17:26:21 +00:00
else
2014-06-02 19:32:41 +00:00
{
query.OrderBy = new[]
2014-06-02 19:32:41 +00:00
{
2019-10-20 14:08:40 +00:00
(ItemSortBy.DateCreated, SortOrder.Descending)
2018-09-12 17:26:21 +00:00
};
2014-06-02 19:32:41 +00:00
}
2018-09-12 17:26:21 +00:00
return _libraryManager.GetItemsResult(query);
2014-06-02 19:32:41 +00:00
}
2014-09-28 15:27:26 +00:00
2018-09-12 17:26:21 +00:00
private async Task RefreshLatestChannelItems(IChannel channel, CancellationToken cancellationToken)
2014-09-22 21:56:54 +00:00
{
2019-10-25 10:47:20 +00:00
var internalChannel = await GetChannel(channel, cancellationToken).ConfigureAwait(false);
2014-09-22 21:56:54 +00:00
2020-04-11 10:03:10 +00:00
var query = new InternalItemsQuery
{
Parent = internalChannel,
EnableTotalRecordCount = false,
ChannelIds = new Guid[] { internalChannel.Id }
};
2014-09-22 21:56:54 +00:00
2018-09-12 17:26:21 +00:00
var result = await GetChannelItemsInternal(query, new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
2014-10-02 00:28:16 +00:00
2018-09-12 17:26:21 +00:00
foreach (var item in result.Items)
2014-10-02 00:28:16 +00:00
{
if (item is Folder folder)
2014-10-02 00:28:16 +00:00
{
2020-04-11 10:03:10 +00:00
await GetChannelItemsInternal(
new InternalItemsQuery
{
Parent = folder,
EnableTotalRecordCount = false,
ChannelIds = new Guid[] { internalChannel.Id }
},
new SimpleProgress<double>(),
cancellationToken).ConfigureAwait(false);
2014-10-02 00:28:16 +00:00
}
}
2014-06-20 04:50:30 +00:00
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public async Task<QueryResult<BaseItem>> GetChannelItemsInternal(InternalItemsQuery query, IProgress<double> progress, CancellationToken cancellationToken)
2014-03-18 01:45:41 +00:00
{
// Get the internal channel entity
2018-09-12 17:26:21 +00:00
var channel = GetChannel(query.ChannelIds[0]);
2014-03-18 01:45:41 +00:00
// Find the corresponding channel provider plugin
var channelProvider = GetChannelProvider(channel);
var parentItem = query.ParentId == Guid.Empty ? channel : _libraryManager.GetItemById(query.ParentId);
2014-05-27 21:17:48 +00:00
2020-04-11 10:03:10 +00:00
var itemsResult = await GetChannelItems(
channelProvider,
query.User,
2018-09-12 17:26:21 +00:00
parentItem is Channel ? null : parentItem.ExternalId,
null,
false,
2014-05-27 21:17:48 +00:00
cancellationToken)
.ConfigureAwait(false);
2014-05-18 22:26:06 +00:00
if (query.ParentId == Guid.Empty)
2018-09-12 17:26:21 +00:00
{
query.Parent = channel;
}
2020-04-11 10:03:10 +00:00
2018-09-12 17:26:21 +00:00
query.ChannelIds = Array.Empty<Guid>();
2014-05-05 00:46:52 +00:00
2018-09-12 17:26:21 +00:00
// Not yet sure why this is causing a problem
query.GroupByPresentationUniqueKey = false;
2018-09-12 17:26:21 +00:00
// null if came from cache
if (itemsResult != null)
{
2020-08-21 20:01:19 +00:00
var items = itemsResult.Items;
var itemsLen = items.Count;
var internalItems = new Guid[itemsLen];
for (int i = 0; i < itemsLen; i++)
{
internalItems[i] = (await GetChannelItemEntityAsync(
items[i],
channelProvider,
channel.Id,
parentItem,
cancellationToken).ConfigureAwait(false)).Id;
}
2018-09-12 17:26:21 +00:00
var existingIds = _libraryManager.GetItemIds(query);
2020-08-21 20:01:19 +00:00
var deadIds = existingIds.Except(internalItems)
2018-09-12 17:26:21 +00:00
.ToArray();
2014-03-18 01:45:41 +00:00
2018-09-12 17:26:21 +00:00
foreach (var deadId in deadIds)
{
2018-09-12 17:26:21 +00:00
var deadItem = _libraryManager.GetItemById(deadId);
if (deadItem != null)
{
2020-04-11 10:03:10 +00:00
_libraryManager.DeleteItem(
deadItem,
new DeleteOptions
{
DeleteFileLocation = false,
DeleteFromExternalProvider = false
},
parentItem,
false);
2018-09-12 17:26:21 +00:00
}
}
}
2014-05-05 00:46:52 +00:00
2018-09-12 17:26:21 +00:00
return _libraryManager.GetItemsResult(query);
2014-03-18 01:45:41 +00:00
}
/// <inheritdoc />
2018-09-12 17:26:21 +00:00
public async Task<QueryResult<BaseItemDto>> GetChannelItems(InternalItemsQuery query, CancellationToken cancellationToken)
2014-07-30 03:31:35 +00:00
{
2017-06-23 16:04:45 +00:00
var internalResult = await GetChannelItemsInternal(query, new SimpleProgress<double>(), cancellationToken).ConfigureAwait(false);
2014-07-30 03:31:35 +00:00
2018-09-12 17:26:21 +00:00
var returnItems = _dtoService.GetBaseItemDtos(internalResult.Items, query.DtoOptions, query.User);
2014-07-30 03:31:35 +00:00
var result = new QueryResult<BaseItemDto>
{
Items = returnItems,
TotalRecordCount = internalResult.TotalRecordCount
};
return result;
}
2020-05-13 02:10:35 +00:00
private async Task<ChannelItemResult> GetChannelItems(
IChannel channel,
2020-05-20 17:07:53 +00:00
User user,
2018-09-12 17:26:21 +00:00
string externalFolderId,
2014-05-27 21:17:48 +00:00
ChannelItemSortField? sortField,
bool sortDescending,
CancellationToken cancellationToken)
2014-03-18 01:45:41 +00:00
{
var userId = user?.Id.ToString("N", CultureInfo.InvariantCulture);
2014-06-06 17:14:02 +00:00
var cacheLength = CacheLength;
2018-09-12 17:26:21 +00:00
var cachePath = GetChannelDataCachePath(channel, userId, externalFolderId, sortField, sortDescending);
2014-03-18 01:45:41 +00:00
2014-05-04 14:19:46 +00:00
try
2014-03-18 01:45:41 +00:00
{
2018-09-12 17:26:21 +00:00
if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
2014-05-04 14:19:46 +00:00
{
await using FileStream jsonStream = AsyncFile.OpenRead(cachePath);
var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
2018-09-12 17:26:21 +00:00
if (cachedResult != null)
{
2018-09-12 17:26:21 +00:00
return null;
}
2014-05-04 14:19:46 +00:00
}
}
catch (FileNotFoundException)
{
}
catch (IOException)
2014-05-04 14:19:46 +00:00
{
}
await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
try
{
2018-09-12 17:26:21 +00:00
if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(cacheLength) > DateTime.UtcNow)
2014-05-04 14:19:46 +00:00
{
await using FileStream jsonStream = AsyncFile.OpenRead(cachePath);
var cachedResult = await JsonSerializer.DeserializeAsync<ChannelItemResult>(jsonStream, _jsonOptions, cancellationToken).ConfigureAwait(false);
2018-09-12 17:26:21 +00:00
if (cachedResult != null)
{
2018-09-12 17:26:21 +00:00
return null;
}
2014-05-04 14:19:46 +00:00
}
}
catch (FileNotFoundException)
{
}
catch (IOException)
2014-05-04 14:19:46 +00:00
{
}
var query = new InternalChannelItemQuery
{
UserId = user?.Id ?? Guid.Empty,
2014-05-27 21:17:48 +00:00
SortBy = sortField,
2018-09-12 17:26:21 +00:00
SortDescending = sortDescending,
FolderId = externalFolderId
2014-05-04 14:19:46 +00:00
};
2018-09-12 17:26:21 +00:00
query.FolderId = externalFolderId;
2014-05-18 19:58:42 +00:00
2014-05-04 14:19:46 +00:00
var result = await channel.GetChannelItems(query, cancellationToken).ConfigureAwait(false);
2016-11-14 03:44:54 +00:00
if (result == null)
{
throw new InvalidOperationException("Channel returned a null result from GetChannelItems");
}
await CacheResponse(result, cachePath);
2014-05-04 14:19:46 +00:00
return result;
2014-05-04 14:19:46 +00:00
}
finally
{
_resourcePool.Release();
}
}
2021-08-15 15:20:07 +00:00
private async Task CacheResponse(ChannelItemResult result, string path)
2014-05-04 14:19:46 +00:00
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
2014-05-04 14:19:46 +00:00
await using FileStream createStream = File.Create(path);
await JsonSerializer.SerializeAsync(createStream, result, _jsonOptions).ConfigureAwait(false);
2014-05-04 14:19:46 +00:00
}
catch (Exception ex)
{
2020-08-31 20:20:19 +00:00
_logger.LogError(ex, "Error writing to channel cache file: {Path}", path);
2014-05-04 14:19:46 +00:00
}
}
2020-04-11 10:03:10 +00:00
private string GetChannelDataCachePath(
IChannel channel,
2014-06-06 17:14:02 +00:00
string userId,
2018-09-12 17:26:21 +00:00
string externalFolderId,
2014-05-27 21:17:48 +00:00
ChannelItemSortField? sortField,
bool sortDescending)
2014-05-04 14:19:46 +00:00
{
var channelId = GetInternalChannelId(channel.Name).ToString("N", CultureInfo.InvariantCulture);
2014-03-18 01:45:41 +00:00
2014-06-06 17:14:02 +00:00
var userCacheKey = string.Empty;
if (channel is IHasCacheKey hasCacheKey)
2014-06-06 17:14:02 +00:00
{
userCacheKey = hasCacheKey.GetCacheKey(userId) ?? string.Empty;
}
var filename = string.IsNullOrEmpty(externalFolderId) ? "root" : externalFolderId.GetMD5().ToString("N", CultureInfo.InvariantCulture);
2014-06-07 19:46:24 +00:00
filename += userCacheKey;
2014-03-18 17:05:57 +00:00
var version = ((channel.DataVersion ?? string.Empty) + "2").GetMD5().ToString("N", CultureInfo.InvariantCulture);
2014-05-27 21:17:48 +00:00
if (sortField.HasValue)
{
filename += "-sortField-" + sortField.Value;
}
2020-04-11 10:03:10 +00:00
2014-05-27 21:17:48 +00:00
if (sortDescending)
{
filename += "-sortDescending";
}
filename = filename.GetMD5().ToString("N", CultureInfo.InvariantCulture);
2014-05-27 21:17:48 +00:00
2020-04-11 10:03:10 +00:00
return Path.Combine(
_config.ApplicationPaths.CachePath,
2014-06-06 17:14:02 +00:00
"channels",
channelId,
version,
filename + ".json");
2014-03-18 01:45:41 +00:00
}
private static string GetIdToHash(string externalId, string channelName)
2014-03-18 01:45:41 +00:00
{
2014-05-03 04:20:04 +00:00
// Increment this as needed to force new downloads
2014-05-18 22:26:06 +00:00
// Incorporate Name because it's being used to convert channel entity to provider
2014-09-28 15:27:26 +00:00
return externalId + (channelName ?? string.Empty) + "16";
2014-05-03 04:20:04 +00:00
}
2014-03-18 17:05:57 +00:00
2018-09-12 17:26:21 +00:00
private T GetItemById<T>(string idString, string channelName, out bool isNew)
2016-03-19 04:05:33 +00:00
where T : BaseItem, new()
2014-05-03 04:20:04 +00:00
{
2019-01-02 11:14:31 +00:00
var id = _libraryManager.GetNewItemId(GetIdToHash(idString, channelName), typeof(T));
2019-01-07 23:27:46 +00:00
2014-09-28 15:27:26 +00:00
T item = null;
2014-05-18 22:26:06 +00:00
2014-09-28 15:27:26 +00:00
try
2014-03-18 17:05:57 +00:00
{
2014-09-28 15:27:26 +00:00
item = _libraryManager.GetItemById(id) as T;
2014-03-18 17:05:57 +00:00
}
2014-09-28 15:27:26 +00:00
catch (Exception ex)
2014-03-18 17:05:57 +00:00
{
2018-12-20 12:11:26 +00:00
_logger.LogError(ex, "Error retrieving channel item from database");
2014-09-28 15:27:26 +00:00
}
2014-05-03 04:20:04 +00:00
2018-09-12 17:26:21 +00:00
if (item == null)
2014-09-28 15:27:26 +00:00
{
item = new T();
isNew = true;
2014-03-18 17:05:57 +00:00
}
else
{
2014-09-28 15:27:26 +00:00
isNew = false;
}
2014-05-03 04:20:04 +00:00
2014-09-28 15:27:26 +00:00
item.Id = id;
return item;
}
2014-05-03 04:20:04 +00:00
2020-08-21 20:01:19 +00:00
private async Task<BaseItem> GetChannelItemEntityAsync(ChannelItemInfo info, IChannel channelProvider, Guid internalChannelId, BaseItem parentFolder, CancellationToken cancellationToken)
2014-09-28 15:27:26 +00:00
{
2018-09-12 17:26:21 +00:00
var parentFolderId = parentFolder.Id;
2014-09-28 15:27:26 +00:00
BaseItem item;
bool isNew;
2015-11-21 05:01:16 +00:00
bool forceUpdate = false;
2014-09-28 15:27:26 +00:00
if (info.Type == ChannelItemType.Folder)
{
2020-04-19 17:39:12 +00:00
item = info.FolderType switch
2016-03-19 05:04:38 +00:00
{
2020-04-19 17:39:12 +00:00
ChannelFolderType.MusicAlbum => GetItemById<MusicAlbum>(info.Id, channelProvider.Name, out isNew),
ChannelFolderType.MusicArtist => GetItemById<MusicArtist>(info.Id, channelProvider.Name, out isNew),
ChannelFolderType.PhotoAlbum => GetItemById<PhotoAlbum>(info.Id, channelProvider.Name, out isNew),
ChannelFolderType.Series => GetItemById<Series>(info.Id, channelProvider.Name, out isNew),
ChannelFolderType.Season => GetItemById<Season>(info.Id, channelProvider.Name, out isNew),
_ => GetItemById<Folder>(info.Id, channelProvider.Name, out isNew)
};
2014-09-28 15:27:26 +00:00
}
else if (info.MediaType == ChannelMediaType.Audio)
{
item = info.ContentType == ChannelMediaContentType.Podcast
? GetItemById<AudioBook>(info.Id, channelProvider.Name, out isNew)
: GetItemById<Audio>(info.Id, channelProvider.Name, out isNew);
2014-09-28 15:27:26 +00:00
}
else
{
2020-04-19 17:39:12 +00:00
item = info.ContentType switch
2016-03-19 15:38:05 +00:00
{
2020-04-19 17:39:12 +00:00
ChannelMediaContentType.Episode => GetItemById<Episode>(info.Id, channelProvider.Name, out isNew),
ChannelMediaContentType.Movie => GetItemById<Movie>(info.Id, channelProvider.Name, out isNew),
var x when x == ChannelMediaContentType.Trailer || info.ExtraType == ExtraType.Trailer
=> GetItemById<Trailer>(info.Id, channelProvider.Name, out isNew),
_ => GetItemById<Video>(info.Id, channelProvider.Name, out isNew)
};
2014-03-18 17:05:57 +00:00
}
2018-09-12 17:26:21 +00:00
var enableMediaProbe = channelProvider is ISupportsMediaProbe;
if (info.IsLiveStream)
{
item.RunTimeTicks = null;
}
else if (isNew || !enableMediaProbe)
{
item.RunTimeTicks = info.RunTimeTicks;
}
2014-05-03 04:20:04 +00:00
if (isNew)
{
item.Name = info.Name;
2018-09-12 17:26:21 +00:00
item.Genres = info.Genres.ToArray();
2018-12-28 15:48:26 +00:00
item.Studios = info.Studios.ToArray();
2014-05-03 04:20:04 +00:00
item.CommunityRating = info.CommunityRating;
item.Overview = info.Overview;
2014-07-08 01:41:03 +00:00
item.IndexNumber = info.IndexNumber;
item.ParentIndexNumber = info.ParentIndexNumber;
2014-05-03 04:20:04 +00:00
item.PremiereDate = info.PremiereDate;
item.ProductionYear = info.ProductionYear;
item.ProviderIds = info.ProviderIds;
2014-09-22 21:56:54 +00:00
item.OfficialRating = info.OfficialRating;
2015-10-04 18:10:50 +00:00
item.DateCreated = info.DateCreated ?? DateTime.UtcNow;
2018-12-28 15:48:26 +00:00
item.Tags = info.Tags.ToArray();
2018-09-12 17:26:21 +00:00
item.OriginalTitle = info.OriginalTitle;
2014-05-03 04:20:04 +00:00
}
else if (info.Type == ChannelItemType.Folder && info.FolderType == ChannelFolderType.Container)
{
// At least update names of container folders
if (item.Name != info.Name)
{
item.Name = info.Name;
forceUpdate = true;
}
}
2014-05-03 04:20:04 +00:00
if (item is IHasArtist hasArtists)
2016-06-20 17:08:13 +00:00
{
2017-08-24 19:52:19 +00:00
hasArtists.Artists = info.Artists.ToArray();
2016-06-20 17:08:13 +00:00
}
if (item is IHasAlbumArtist hasAlbumArtists)
2016-06-20 17:08:13 +00:00
{
2018-12-28 15:48:26 +00:00
hasAlbumArtists.AlbumArtists = info.AlbumArtists.ToArray();
2016-06-20 17:08:13 +00:00
}
if (item is Trailer trailer)
2016-03-19 19:32:37 +00:00
{
if (!info.TrailerTypes.SequenceEqual(trailer.TrailerTypes))
{
_logger.LogDebug("Forcing update due to TrailerTypes {0}", item.Name);
2016-03-19 19:32:37 +00:00
forceUpdate = true;
}
2020-04-11 10:03:10 +00:00
2018-09-12 17:26:21 +00:00
trailer.TrailerTypes = info.TrailerTypes.ToArray();
}
if (info.DateModified > item.DateModified)
{
item.DateModified = info.DateModified;
_logger.LogDebug("Forcing update due to DateModified {0}", item.Name);
2018-09-12 17:26:21 +00:00
forceUpdate = true;
2016-03-19 19:32:37 +00:00
}
2018-09-12 17:26:21 +00:00
// was used for status
2020-06-14 09:11:11 +00:00
// if (!string.Equals(item.ExternalEtag ?? string.Empty, info.Etag ?? string.Empty, StringComparison.Ordinal))
2021-08-28 22:32:50 +00:00
// {
2018-09-12 17:26:21 +00:00
// item.ExternalEtag = info.Etag;
// forceUpdate = true;
// _logger.LogDebug("Forcing update due to ExternalEtag {0}", item.Name);
2021-08-28 22:32:50 +00:00
// }
2015-10-04 18:10:50 +00:00
2018-09-12 17:26:21 +00:00
if (!internalChannelId.Equals(item.ChannelId))
2015-11-02 17:25:01 +00:00
{
2015-11-21 05:01:16 +00:00
forceUpdate = true;
_logger.LogDebug("Forcing update due to ChannelId {0}", item.Name);
2018-09-12 17:26:21 +00:00
}
2020-04-11 10:03:10 +00:00
2018-09-12 17:26:21 +00:00
item.ChannelId = internalChannelId;
if (!item.ParentId.Equals(parentFolderId))
{
forceUpdate = true;
_logger.LogDebug("Forcing update due to parent folder Id {0}", item.Name);
2018-09-12 17:26:21 +00:00
}
2020-04-11 10:03:10 +00:00
2018-09-12 17:26:21 +00:00
item.ParentId = parentFolderId;
if (item is IHasSeries hasSeries)
2018-09-12 17:26:21 +00:00
{
if (!string.Equals(hasSeries.SeriesName, info.SeriesName, StringComparison.OrdinalIgnoreCase))
{
forceUpdate = true;
_logger.LogDebug("Forcing update due to SeriesName {0}", item.Name);
2018-09-12 17:26:21 +00:00
}
2020-04-11 10:03:10 +00:00
2018-09-12 17:26:21 +00:00
hasSeries.SeriesName = info.SeriesName;
2015-11-02 17:25:01 +00:00
}
2016-03-19 04:05:33 +00:00
if (!string.Equals(item.ExternalId, info.Id, StringComparison.OrdinalIgnoreCase))
2015-10-04 18:10:50 +00:00
{
2015-11-21 05:01:16 +00:00
forceUpdate = true;
_logger.LogDebug("Forcing update due to ExternalId {0}", item.Name);
2015-10-04 18:10:50 +00:00
}
2020-04-11 10:03:10 +00:00
2016-03-19 04:05:33 +00:00
item.ExternalId = info.Id;
2014-05-03 04:20:04 +00:00
if (item is Audio channelAudioItem)
2014-05-03 04:20:04 +00:00
{
2016-03-19 04:22:33 +00:00
channelAudioItem.ExtraType = info.ExtraType;
2014-05-18 19:58:42 +00:00
var mediaSource = info.MediaSources.FirstOrDefault();
item.Path = mediaSource?.Path;
2016-03-19 04:22:33 +00:00
}
2014-05-18 19:58:42 +00:00
if (item is Video channelVideoItem)
2016-03-19 04:22:33 +00:00
{
channelVideoItem.ExtraType = info.ExtraType;
var mediaSource = info.MediaSources.FirstOrDefault();
item.Path = mediaSource?.Path;
2014-05-03 04:20:04 +00:00
}
2018-09-12 17:26:21 +00:00
if (!string.IsNullOrEmpty(info.ImageUrl) && !item.HasImage(ImageType.Primary))
2015-10-25 17:13:30 +00:00
{
item.SetImagePath(ImageType.Primary, info.ImageUrl);
_logger.LogDebug("Forcing update due to ImageUrl {0}", item.Name);
2018-09-12 17:26:21 +00:00
forceUpdate = true;
}
if (!info.IsLiveStream)
{
if (item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase))
{
item.Tags = item.Tags.Except(new[] { "livestream" }, StringComparer.OrdinalIgnoreCase).ToArray();
_logger.LogDebug("Forcing update due to Tags {0}", item.Name);
2018-09-12 17:26:21 +00:00
forceUpdate = true;
}
}
else
{
if (!item.Tags.Contains("livestream", StringComparer.OrdinalIgnoreCase))
{
item.Tags = item.Tags.Concat(new[] { "livestream" }).ToArray();
_logger.LogDebug("Forcing update due to Tags {0}", item.Name);
2018-09-12 17:26:21 +00:00
forceUpdate = true;
}
2015-10-25 17:13:30 +00:00
}
2017-09-13 18:41:48 +00:00
item.OnMetadataChanged();
2014-05-03 04:20:04 +00:00
if (isNew)
{
2018-09-12 17:26:21 +00:00
_libraryManager.CreateItem(item, parentFolder);
2015-06-28 16:36:25 +00:00
2015-10-25 17:13:30 +00:00
if (info.People != null && info.People.Count > 0)
{
2018-09-12 17:26:21 +00:00
_libraryManager.UpdatePeople(item, info.People);
2015-10-25 17:13:30 +00:00
}
2014-05-03 04:20:04 +00:00
}
2015-11-21 05:01:16 +00:00
else if (forceUpdate)
{
2020-08-21 20:01:19 +00:00
await item.UpdateToRepositoryAsync(ItemUpdateType.None, cancellationToken).ConfigureAwait(false);
2015-11-21 05:01:16 +00:00
}
2014-03-18 17:05:57 +00:00
2018-09-12 17:26:21 +00:00
if ((isNew || forceUpdate) && info.Type == ChannelItemType.Media)
2014-05-03 04:20:04 +00:00
{
2018-09-12 17:26:21 +00:00
if (enableMediaProbe && !info.IsLiveStream && item.HasPathProtocol)
{
2020-12-28 23:35:59 +00:00
await SaveMediaSources(item, new List<MediaSourceInfo>()).ConfigureAwait(false);
2018-09-12 17:26:21 +00:00
}
else
{
2020-12-28 23:35:59 +00:00
await SaveMediaSources(item, info.MediaSources).ConfigureAwait(false);
2018-09-12 17:26:21 +00:00
}
2014-05-03 04:20:04 +00:00
}
2020-04-11 10:03:10 +00:00
if (isNew || forceUpdate || item.DateLastRefreshed == default)
2014-05-03 04:20:04 +00:00
{
2019-09-10 20:37:53 +00:00
_providerManager.QueueRefresh(item.Id, new MetadataRefreshOptions(new DirectoryService(_fileSystem)), RefreshPriority.Normal);
2014-05-03 04:20:04 +00:00
}
2018-09-12 17:26:21 +00:00
return item;
2014-05-03 04:20:04 +00:00
}
2014-03-18 17:05:57 +00:00
internal IChannel GetChannelProvider(Channel channel)
2014-03-18 01:45:41 +00:00
{
2016-03-19 19:32:37 +00:00
if (channel == null)
{
throw new ArgumentNullException(nameof(channel));
2016-03-19 19:32:37 +00:00
}
2016-04-08 18:32:38 +00:00
var result = GetAllChannels()
2018-09-12 17:26:21 +00:00
.FirstOrDefault(i => GetInternalChannelId(i.Name).Equals(channel.ChannelId) || string.Equals(i.Name, channel.Name, StringComparison.OrdinalIgnoreCase));
if (result == null)
{
throw new ResourceNotFoundException("No channel provider found for channel " + channel.Name);
}
return result;
2014-03-18 01:45:41 +00:00
}
2014-05-03 04:20:04 +00:00
2018-09-12 17:26:21 +00:00
internal IChannel GetChannelProvider(Guid internalChannelId)
{
var result = GetAllChannels()
2018-09-12 17:26:21 +00:00
.FirstOrDefault(i => internalChannelId.Equals(GetInternalChannelId(i.Name)));
if (result == null)
{
throw new ResourceNotFoundException("No channel provider found for channel id " + internalChannelId);
}
return result;
}
}
2018-12-27 23:27:57 +00:00
}