jellyfin-server/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs

660 lines
23 KiB
C#
Raw Normal View History

2014-03-18 01:45:41 +00:00
using MediaBrowser.Common.Extensions;
using MediaBrowser.Common.IO;
using MediaBrowser.Controller.Channels;
using MediaBrowser.Controller.Configuration;
using MediaBrowser.Controller.Dto;
using MediaBrowser.Controller.Entities;
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;
2014-03-18 01:45:41 +00:00
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Querying;
2014-05-04 14:19:46 +00:00
using MediaBrowser.Model.Serialization;
2014-03-18 01:45:41 +00:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.Server.Implementations.Channels
{
public class ChannelManager : IChannelManager
{
private IChannel[] _channels;
2014-05-03 23:38:23 +00:00
private IChannelFactory[] _factories;
2014-03-18 01:45:41 +00:00
private List<Channel> _channelEntities = new List<Channel>();
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;
private readonly ILogger _logger;
private readonly IServerConfigurationManager _config;
private readonly IFileSystem _fileSystem;
2014-05-04 14:19:46 +00:00
private readonly IJsonSerializer _jsonSerializer;
2014-03-18 01:45:41 +00:00
2014-05-04 14:19:46 +00:00
public ChannelManager(IUserManager userManager, IDtoService dtoService, ILibraryManager libraryManager, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IUserDataManager userDataManager, IJsonSerializer jsonSerializer)
2014-03-18 01:45:41 +00:00
{
_userManager = userManager;
_dtoService = dtoService;
_libraryManager = libraryManager;
_logger = logger;
_config = config;
_fileSystem = fileSystem;
2014-05-03 04:20:04 +00:00
_userDataManager = userDataManager;
2014-05-04 14:19:46 +00:00
_jsonSerializer = jsonSerializer;
2014-03-18 01:45:41 +00:00
}
2014-05-03 23:38:23 +00:00
public void AddParts(IEnumerable<IChannel> channels, IEnumerable<IChannelFactory> factories)
2014-03-18 01:45:41 +00:00
{
_channels = channels.ToArray();
2014-05-03 23:38:23 +00:00
_factories = factories.ToArray();
}
private IEnumerable<IChannel> GetAllChannels()
{
return _factories
.SelectMany(i =>
{
try
{
return i.GetChannels().ToList();
}
catch (Exception ex)
{
_logger.ErrorException("Error getting channel list", ex);
return new List<IChannel>();
}
})
.Concat(_channels)
.OrderBy(i => i.Name);
2014-03-18 01:45:41 +00:00
}
public Task<QueryResult<BaseItemDto>> GetChannels(ChannelQuery query, CancellationToken cancellationToken)
{
var user = string.IsNullOrWhiteSpace(query.UserId)
? null
: _userManager.GetUserById(new Guid(query.UserId));
var channels = _channelEntities.OrderBy(i => i.SortName).ToList();
if (user != null)
{
channels = channels.Where(i => GetChannelProvider(i).IsEnabledFor(user) && i.IsVisible(user))
.ToList();
}
2014-05-14 18:04:26 +00:00
var all = channels;
var totalCount = all.Count;
if (query.StartIndex.HasValue)
{
all = all.Skip(query.StartIndex.Value).ToList();
}
if (query.Limit.HasValue)
{
all = all.Take(query.Limit.Value).ToList();
}
2014-05-18 19:58:42 +00:00
2014-03-18 01:45:41 +00:00
// Get everything
var fields = Enum.GetNames(typeof(ItemFields))
.Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
.ToList();
2014-05-14 18:04:26 +00:00
var returnItems = all.Select(i => _dtoService.GetBaseItemDto(i, fields, user))
2014-03-18 01:45:41 +00:00
.ToArray();
var result = new QueryResult<BaseItemDto>
{
Items = returnItems,
2014-05-14 18:04:26 +00:00
TotalRecordCount = totalCount
2014-03-18 01:45:41 +00:00
};
return Task.FromResult(result);
}
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 list = new List<Channel>();
var numComplete = 0;
foreach (var channelInfo in allChannelsList)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
var item = await GetChannel(channelInfo, cancellationToken).ConfigureAwait(false);
list.Add(item);
_libraryManager.RegisterItem(item);
}
catch (OperationCanceledException)
{
throw;
}
catch (Exception ex)
{
_logger.ErrorException("Error getting channel information for {0}", ex, channelInfo.Name);
}
numComplete++;
double percent = numComplete;
percent /= allChannelsList.Count;
progress.Report(100 * percent);
}
_channelEntities = list.ToList();
progress.Report(100);
}
2014-05-18 19:58:42 +00:00
public Task<IEnumerable<ChannelMediaInfo>> GetChannelItemMediaSources(string id, CancellationToken cancellationToken)
{
var item = (IChannelMediaItem)_libraryManager.GetItemById(id);
var channelGuid = new Guid(item.ChannelId);
var channel = _channelEntities.First(i => i.Id == channelGuid);
2014-05-18 22:26:06 +00:00
var channelPlugin = GetChannelProvider(channel);
2014-05-18 19:58:42 +00:00
2014-05-18 22:26:06 +00:00
var requiresCallback = channelPlugin as IRequiresMediaInfoCallback;
2014-05-18 19:58:42 +00:00
if (requiresCallback != null)
{
return requiresCallback.GetChannelItemMediaInfo(item.ExternalId, cancellationToken);
}
return Task.FromResult<IEnumerable<ChannelMediaInfo>>(item.ChannelMediaSources);
}
2014-03-18 01:45:41 +00:00
private async Task<Channel> GetChannel(IChannel channelInfo, CancellationToken cancellationToken)
{
var path = Path.Combine(_config.ApplicationPaths.ItemsByNamePath, "channels", _fileSystem.GetValidFilename(channelInfo.Name));
var fileInfo = new DirectoryInfo(path);
var isNew = false;
if (!fileInfo.Exists)
{
_logger.Debug("Creating directory {0}", path);
Directory.CreateDirectory(path);
fileInfo = new DirectoryInfo(path);
if (!fileInfo.Exists)
{
throw new IOException("Path not created: " + path);
}
isNew = true;
}
var id = GetInternalChannelId(channelInfo.Name);
var item = _libraryManager.GetItemById(id) as Channel;
if (item == null)
{
item = new Channel
{
Name = channelInfo.Name,
Id = id,
DateCreated = _fileSystem.GetCreationTimeUtc(fileInfo),
DateModified = _fileSystem.GetLastWriteTimeUtc(fileInfo),
Path = path
};
isNew = true;
}
item.HomePageUrl = channelInfo.HomePageUrl;
2014-03-18 01:45:41 +00:00
item.OriginalChannelName = channelInfo.Name;
if (string.IsNullOrEmpty(item.Name))
{
item.Name = channelInfo.Name;
}
await item.RefreshMetadata(new MetadataRefreshOptions
{
ForceSave = isNew
}, cancellationToken);
return item;
}
public Channel GetChannel(string id)
{
return (Channel)_libraryManager.GetItemById(new Guid(id));
}
2014-03-18 01:45:41 +00:00
private Guid GetInternalChannelId(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException("name");
}
return ("Channel " + name).GetMBId(typeof(Channel));
}
public async Task<QueryResult<BaseItemDto>> GetChannelItems(ChannelItemQuery query, CancellationToken cancellationToken)
{
2014-05-05 00:46:52 +00:00
var queryChannelId = query.ChannelId;
// Get the internal channel entity
var channel = _channelEntities.First(i => i.Id == new Guid(queryChannelId));
2014-03-18 01:45:41 +00:00
// Find the corresponding channel provider plugin
var channelProvider = GetChannelProvider(channel);
var channelInfo = channelProvider.GetChannelFeatures();
int? providerStartIndex = null;
int? providerLimit = null;
if (channelInfo.MaxPageSize.HasValue)
2014-05-05 00:46:52 +00:00
{
providerStartIndex = query.StartIndex;
2014-05-05 00:46:52 +00:00
2014-05-21 00:56:24 +00:00
if (query.Limit.HasValue && query.Limit.Value > channelInfo.MaxPageSize.Value)
{
throw new ArgumentException(string.Format("Channel {0} only supports a maximum of {1} records at a time.", channel.Name, channelInfo.MaxPageSize.Value));
}
providerLimit = query.Limit;
}
2014-05-05 00:46:52 +00:00
var user = string.IsNullOrWhiteSpace(query.UserId)
? null
: _userManager.GetUserById(new Guid(query.UserId));
2014-05-05 00:46:52 +00:00
var itemsResult = await GetChannelItems(channelProvider, user, query.FolderId, providerStartIndex, providerLimit, cancellationToken)
.ConfigureAwait(false);
2014-05-18 22:26:06 +00:00
var providerTotalRecordCount = providerLimit.HasValue ? itemsResult.TotalRecordCount : null;
2014-05-05 00:46:52 +00:00
var tasks = itemsResult.Items.Select(i => GetChannelItemEntity(i, channelProvider, channel, cancellationToken));
var internalItems = await Task.WhenAll(tasks).ConfigureAwait(false);
if (user != null)
{
internalItems = internalItems.Where(i => i.IsVisible(user)).ToArray();
2014-03-18 01:45:41 +00:00
if (providerTotalRecordCount.HasValue)
{
providerTotalRecordCount = providerTotalRecordCount.Value;
}
}
2014-05-05 00:46:52 +00:00
return await GetReturnItems(internalItems, providerTotalRecordCount, user, query, cancellationToken).ConfigureAwait(false);
2014-03-18 01:45:41 +00:00
}
2014-05-04 14:19:46 +00:00
private readonly SemaphoreSlim _resourcePool = new SemaphoreSlim(1, 1);
private async Task<ChannelItemResult> GetChannelItems(IChannel channel, User user, string folderId, int? startIndex, int? limit, CancellationToken cancellationToken)
2014-03-18 01:45:41 +00:00
{
var cachePath = GetChannelDataCachePath(channel, user, folderId);
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
{
if (!startIndex.HasValue && !limit.HasValue)
2014-05-04 14:19:46 +00:00
{
var channelItemResult = _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath);
if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(channelItemResult.CacheLength) > DateTime.UtcNow)
{
return channelItemResult;
}
2014-05-04 14:19:46 +00:00
}
}
catch (FileNotFoundException)
{
}
catch (DirectoryNotFoundException)
{
}
await _resourcePool.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
try
{
if (!startIndex.HasValue && !limit.HasValue)
2014-05-04 14:19:46 +00:00
{
var channelItemResult = _jsonSerializer.DeserializeFromFile<ChannelItemResult>(cachePath);
if (_fileSystem.GetLastWriteTimeUtc(cachePath).Add(channelItemResult.CacheLength) > DateTime.UtcNow)
{
return channelItemResult;
}
2014-05-04 14:19:46 +00:00
}
}
catch (FileNotFoundException)
{
}
catch (DirectoryNotFoundException)
{
}
var query = new InternalChannelItemQuery
{
User = user,
StartIndex = startIndex,
Limit = limit
2014-05-04 14:19:46 +00:00
};
if (!string.IsNullOrWhiteSpace(folderId))
2014-05-18 19:58:42 +00:00
{
var categoryItem = (IChannelItem)_libraryManager.GetItemById(new Guid(folderId));
2014-05-18 19:58:42 +00:00
query.FolderId = categoryItem.ExternalId;
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);
if (!startIndex.HasValue && !limit.HasValue)
{
CacheResponse(result, cachePath);
}
2014-05-04 14:19:46 +00:00
return result;
2014-05-04 14:19:46 +00:00
}
finally
{
_resourcePool.Release();
}
}
private void CacheResponse(ChannelItemResult result, string path)
{
try
{
Directory.CreateDirectory(Path.GetDirectoryName(path));
_jsonSerializer.SerializeToFile(result, path);
}
catch (Exception ex)
{
_logger.ErrorException("Error writing to channel cache file: {0}", ex, path);
}
}
private string GetChannelDataCachePath(IChannel channel, User user, string folderId)
2014-05-04 14:19:46 +00:00
{
var channelId = GetInternalChannelId(channel.Name).ToString("N");
2014-03-18 01:45:41 +00:00
var folderKey = string.IsNullOrWhiteSpace(folderId) ? "root" : folderId.GetMD5().ToString("N");
2014-03-18 17:05:57 +00:00
2014-05-18 22:26:06 +00:00
var version = string.IsNullOrWhiteSpace(channel.DataVersion) ? "0" : channel.DataVersion;
return Path.Combine(_config.ApplicationPaths.CachePath, "channels", channelId, version, folderKey, user.Id.ToString("N") + ".json");
2014-03-18 01:45:41 +00:00
}
private async Task<QueryResult<BaseItemDto>> GetReturnItems(IEnumerable<BaseItem> items, int? totalCountFromProvider, User user, ChannelItemQuery query, CancellationToken cancellationToken)
2014-03-18 01:45:41 +00:00
{
2014-05-05 00:46:52 +00:00
items = ApplyFilters(items, query.Filters, user);
2014-05-03 04:20:04 +00:00
var sortBy = query.SortBy.Length == 0 ? new[] { ItemSortBy.SortName } : query.SortBy;
items = _libraryManager.Sort(items, user, sortBy, query.SortOrder ?? SortOrder.Ascending);
2014-03-18 01:45:41 +00:00
2014-05-05 00:46:52 +00:00
var all = items.ToList();
var totalCount = totalCountFromProvider ?? all.Count;
2014-05-03 04:20:04 +00:00
if (!totalCountFromProvider.HasValue)
2014-05-03 04:20:04 +00:00
{
if (query.StartIndex.HasValue)
{
all = all.Skip(query.StartIndex.Value).ToList();
}
if (query.Limit.HasValue)
{
all = all.Take(query.Limit.Value).ToList();
}
2014-05-03 04:20:04 +00:00
}
await RefreshIfNeeded(all, cancellationToken).ConfigureAwait(false);
2014-05-05 00:46:52 +00:00
// Get everything
var fields = Enum.GetNames(typeof(ItemFields))
.Select(i => (ItemFields)Enum.Parse(typeof(ItemFields), i, true))
.ToList();
2014-05-03 04:20:04 +00:00
var returnItemArray = all.Select(i => _dtoService.GetBaseItemDto(i, fields, user))
2014-03-18 01:45:41 +00:00
.ToArray();
return new QueryResult<BaseItemDto>
{
Items = returnItemArray,
2014-05-03 04:20:04 +00:00
TotalRecordCount = totalCount
2014-03-18 01:45:41 +00:00
};
}
2014-05-18 22:26:06 +00:00
private string GetIdToHash(string externalId, IChannel channelProvider)
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
return externalId + (channelProvider.DataVersion ?? string.Empty) + (channelProvider.Name ?? string.Empty) + "13";
2014-05-03 04:20:04 +00:00
}
2014-03-18 17:05:57 +00:00
private async Task<BaseItem> GetChannelItemEntity(ChannelItemInfo info, IChannel channelProvider, Channel internalChannel, CancellationToken cancellationToken)
2014-05-03 04:20:04 +00:00
{
BaseItem item;
2014-03-19 01:35:40 +00:00
Guid id;
2014-05-03 04:20:04 +00:00
var isNew = false;
2014-03-19 01:35:40 +00:00
2014-05-18 22:26:06 +00:00
var idToHash = GetIdToHash(info.Id, channelProvider);
if (info.Type == ChannelItemType.Folder)
2014-03-18 17:05:57 +00:00
{
id = idToHash.GetMBId(typeof(ChannelFolderItem));
2014-05-03 04:20:04 +00:00
item = _libraryManager.GetItemById(id) as ChannelFolderItem;
2014-05-03 04:20:04 +00:00
if (item == null)
{
isNew = true;
item = new ChannelFolderItem();
2014-05-03 04:20:04 +00:00
}
2014-03-18 17:05:57 +00:00
}
else if (info.MediaType == ChannelMediaType.Audio)
{
id = idToHash.GetMBId(typeof(ChannelAudioItem));
2014-05-03 04:20:04 +00:00
item = _libraryManager.GetItemById(id) as ChannelAudioItem;
if (item == null)
{
isNew = true;
item = new ChannelAudioItem();
}
2014-03-18 17:05:57 +00:00
}
else
{
2014-05-18 22:26:06 +00:00
id = idToHash.GetMBId(typeof(ChannelVideoItem));
2014-05-03 04:20:04 +00:00
item = _libraryManager.GetItemById(id) as ChannelVideoItem;
if (item == null)
{
isNew = true;
item = new ChannelVideoItem();
}
2014-03-18 17:05:57 +00:00
}
2014-03-19 01:35:40 +00:00
item.Id = id;
2014-03-18 17:05:57 +00:00
item.RunTimeTicks = info.RunTimeTicks;
2014-05-03 04:20:04 +00:00
if (isNew)
{
item.Name = info.Name;
item.Genres = info.Genres;
item.Studios = info.Studios;
item.CommunityRating = info.CommunityRating;
item.OfficialRating = info.OfficialRating;
item.Overview = info.Overview;
item.People = info.People;
item.PremiereDate = info.PremiereDate;
item.ProductionYear = info.ProductionYear;
item.ProviderIds = info.ProviderIds;
if (info.DateCreated.HasValue)
{
item.DateCreated = info.DateCreated.Value;
}
}
var channelItem = (IChannelItem)item;
channelItem.OriginalImageUrl = info.ImageUrl;
channelItem.ExternalId = info.Id;
channelItem.ChannelId = internalChannel.Id.ToString("N");
2014-05-03 04:20:04 +00:00
channelItem.ChannelItemType = info.Type;
2014-05-18 19:58:42 +00:00
if (isNew)
{
channelItem.Tags = info.Tags;
}
2014-05-03 04:20:04 +00:00
var channelMediaItem = item as IChannelMediaItem;
if (channelMediaItem != null)
{
channelMediaItem.IsInfiniteStream = info.IsInfiniteStream;
channelMediaItem.ContentType = info.ContentType;
2014-05-18 19:58:42 +00:00
channelMediaItem.ChannelMediaSources = info.MediaSources;
var mediaSource = info.MediaSources.FirstOrDefault();
item.Path = mediaSource == null ? null : mediaSource.Path;
2014-05-03 04:20:04 +00:00
}
if (isNew)
{
await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false);
_libraryManager.RegisterItem(item);
}
2014-03-18 17:05:57 +00:00
return item;
2014-03-18 01:45:41 +00:00
}
2014-05-03 04:20:04 +00:00
private async Task RefreshIfNeeded(IEnumerable<BaseItem> programs, CancellationToken cancellationToken)
{
foreach (var program in programs)
{
await RefreshIfNeeded(program, cancellationToken).ConfigureAwait(false);
}
}
private async Task RefreshIfNeeded(BaseItem program, CancellationToken cancellationToken)
{
//if (_refreshedPrograms.ContainsKey(program.Id))
{
//return;
}
await program.RefreshMetadata(cancellationToken).ConfigureAwait(false);
//_refreshedPrograms.TryAdd(program.Id, true);
}
2014-03-18 17:05:57 +00:00
internal IChannel GetChannelProvider(Channel channel)
2014-03-18 01:45:41 +00:00
{
2014-05-03 23:38:23 +00:00
return GetAllChannels().First(i => string.Equals(i.Name, channel.OriginalChannelName, StringComparison.OrdinalIgnoreCase));
2014-03-18 01:45:41 +00:00
}
2014-05-03 04:20:04 +00:00
private IEnumerable<BaseItem> ApplyFilters(IEnumerable<BaseItem> items, IEnumerable<ItemFilter> filters, User user)
{
foreach (var filter in filters.OrderByDescending(f => (int)f))
{
items = ApplyFilter(items, filter, user);
}
return items;
}
private IEnumerable<BaseItem> ApplyFilter(IEnumerable<BaseItem> items, ItemFilter filter, User user)
{
// Avoid implicitly captured closure
var currentUser = user;
switch (filter)
{
case ItemFilter.IsFavoriteOrLikes:
return items.Where(item =>
{
var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
if (userdata == null)
{
return false;
}
var likes = userdata.Likes ?? false;
var favorite = userdata.IsFavorite;
return likes || favorite;
});
case ItemFilter.Likes:
return items.Where(item =>
{
var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
return userdata != null && userdata.Likes.HasValue && userdata.Likes.Value;
});
case ItemFilter.Dislikes:
return items.Where(item =>
{
var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
return userdata != null && userdata.Likes.HasValue && !userdata.Likes.Value;
});
case ItemFilter.IsFavorite:
return items.Where(item =>
{
var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
return userdata != null && userdata.IsFavorite;
});
case ItemFilter.IsResumable:
return items.Where(item =>
{
var userdata = _userDataManager.GetUserData(user.Id, item.GetUserDataKey());
return userdata != null && userdata.PlaybackPositionTicks > 0;
});
case ItemFilter.IsPlayed:
return items.Where(item => item.IsPlayed(currentUser));
case ItemFilter.IsUnplayed:
return items.Where(item => item.IsUnplayed(currentUser));
case ItemFilter.IsFolder:
return items.Where(item => item.IsFolder);
case ItemFilter.IsNotFolder:
return items.Where(item => !item.IsFolder);
}
return items;
}
2014-03-18 01:45:41 +00:00
}
}