diff options
| author | Luke Pulverenti <luke.pulverenti@gmail.com> | 2016-02-14 16:35:09 -0500 |
|---|---|---|
| committer | Luke Pulverenti <luke.pulverenti@gmail.com> | 2016-02-14 16:35:09 -0500 |
| commit | daa0b6cd0ecefd60611752802d062c15e6da85de (patch) | |
| tree | f58a16e47afed9b61471e3871280faa9fc8bd951 /MediaBrowser.Server.Implementations | |
| parent | 7d26b8995f313917829573a7cd96c37decc9158a (diff) | |
| parent | fd5f12e76227d96c52cdc31b67ef9543b485169b (diff) | |
Merge branch 'beta'
Diffstat (limited to 'MediaBrowser.Server.Implementations')
98 files changed, 2498 insertions, 1085 deletions
diff --git a/MediaBrowser.Server.Implementations/Activity/ActivityRepository.cs b/MediaBrowser.Server.Implementations/Activity/ActivityRepository.cs index f491a5c44..3a89d6928 100644 --- a/MediaBrowser.Server.Implementations/Activity/ActivityRepository.cs +++ b/MediaBrowser.Server.Implementations/Activity/ActivityRepository.cs @@ -14,19 +14,17 @@ using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.Activity { - public class ActivityRepository : IActivityRepository, IDisposable + public class ActivityRepository : BaseSqliteRepository, IActivityRepository { private IDbConnection _connection; - private readonly ILogger _logger; - private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); private readonly IServerApplicationPaths _appPaths; private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private IDbCommand _saveActivityCommand; - public ActivityRepository(ILogger logger, IServerApplicationPaths appPaths) + public ActivityRepository(ILogManager logManager, IServerApplicationPaths appPaths) + : base(logManager) { - _logger = logger; _appPaths = appPaths; } @@ -34,7 +32,7 @@ namespace MediaBrowser.Server.Implementations.Activity { var dbFile = Path.Combine(_appPaths.DataPath, "activitylog.db"); - _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false); + _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false); string[] queries = { @@ -47,7 +45,7 @@ namespace MediaBrowser.Server.Implementations.Activity "pragma shrink_memory" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); PrepareStatements(); } @@ -82,7 +80,7 @@ namespace MediaBrowser.Server.Implementations.Activity throw new ArgumentNullException("entry"); } - await _writeLock.WaitAsync().ConfigureAwait(false); + await WriteLock.WaitAsync().ConfigureAwait(false); IDbTransaction transaction = null; @@ -119,7 +117,7 @@ namespace MediaBrowser.Server.Implementations.Activity } catch (Exception e) { - _logger.ErrorException("Failed to save record:", e); + Logger.ErrorException("Failed to save record:", e); if (transaction != null) { @@ -135,7 +133,7 @@ namespace MediaBrowser.Server.Implementations.Activity transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -264,45 +262,17 @@ namespace MediaBrowser.Server.Implementations.Activity return info; } - /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// </summary> - public void Dispose() + protected override void CloseConnection() { - Dispose(true); - GC.SuppressFinalize(this); - } - - private readonly object _disposeLock = new object(); - - /// <summary> - /// Releases unmanaged and - optionally - managed resources. - /// </summary> - /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool dispose) - { - if (dispose) + if (_connection != null) { - try + if (_connection.IsOpen()) { - lock (_disposeLock) - { - if (_connection != null) - { - if (_connection.IsOpen()) - { - _connection.Close(); - } - - _connection.Dispose(); - _connection = null; - } - } - } - catch (Exception ex) - { - _logger.ErrorException("Error disposing database", ex); + _connection.Close(); } + + _connection.Dispose(); + _connection = null; } } } diff --git a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs index 284556c72..c7865b6aa 100644 --- a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs +++ b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs @@ -96,6 +96,11 @@ namespace MediaBrowser.Server.Implementations.Channels .OrderBy(i => i.Name); } + public IEnumerable<Guid> GetInstalledChannelIds() + { + return GetAllChannels().Select(i => GetInternalChannelId(i.Name)); + } + public Task<QueryResult<Channel>> GetChannelsInternal(ChannelQuery query, CancellationToken cancellationToken) { var user = string.IsNullOrWhiteSpace(query.UserId) @@ -402,25 +407,15 @@ namespace MediaBrowser.Server.Implementations.Channels private async Task<Channel> GetChannel(IChannel channelInfo, CancellationToken cancellationToken) { + var parentFolder = await GetInternalChannelFolder(cancellationToken).ConfigureAwait(false); + var parentFolderId = parentFolder.Id; + var id = GetInternalChannelId(channelInfo.Name); var path = Channel.GetInternalMetadataPath(_config.ApplicationPaths.InternalMetadataPath, id); var isNew = false; - - if (!_fileSystem.DirectoryExists(path)) - { - _logger.Debug("Creating directory {0}", path); - - _fileSystem.CreateDirectory(path); - - if (!_fileSystem.DirectoryExists(path)) - { - throw new IOException("Path not created: " + path); - } - - isNew = true; - } + var forceUpdate = false; var item = _libraryManager.GetItemById(id) as Channel; var channelId = channelInfo.Name.GetMD5().ToString("N"); @@ -432,18 +427,29 @@ namespace MediaBrowser.Server.Implementations.Channels Name = channelInfo.Name, Id = id, DateCreated = _fileSystem.GetCreationTimeUtc(path), - DateModified = _fileSystem.GetLastWriteTimeUtc(path), - Path = path, - ChannelId = channelId + DateModified = _fileSystem.GetLastWriteTimeUtc(path) }; isNew = true; } - if (!string.Equals(item.ChannelId, channelId, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase)) { isNew = true; } + item.Path = path; + + if (!string.Equals(item.ChannelId, channelId, StringComparison.OrdinalIgnoreCase)) + { + forceUpdate = true; + } + item.ChannelId = channelId; + + if (item.ParentId != parentFolderId) + { + forceUpdate = true; + } + item.ParentId = parentFolderId; item.OfficialRating = GetOfficialRating(channelInfo.ParentalRating); item.Overview = channelInfo.Description; @@ -453,13 +459,17 @@ namespace MediaBrowser.Server.Implementations.Channels { item.Name = channelInfo.Name; } - - await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem) - { - ForceSave = isNew - }, cancellationToken); + if (isNew) + { + await _libraryManager.CreateItem(item, cancellationToken).ConfigureAwait(false); + } + else if (forceUpdate) + { + await item.UpdateToRepository(ItemUpdateType.None, cancellationToken).ConfigureAwait(false); + } + await item.RefreshMetadata(new MetadataRefreshOptions(_fileSystem), cancellationToken); return item; } @@ -1219,6 +1229,7 @@ namespace MediaBrowser.Server.Implementations.Channels { BaseItem item; bool isNew; + bool forceUpdate = false; if (info.Type == ChannelItemType.Folder) { @@ -1248,24 +1259,25 @@ namespace MediaBrowser.Server.Implementations.Channels item.ProductionYear = info.ProductionYear; item.ProviderIds = info.ProviderIds; item.OfficialRating = info.OfficialRating; - item.DateCreated = info.DateCreated ?? DateTime.UtcNow; + item.Tags = info.Tags; } var channelItem = (IChannelItem)item; channelItem.ChannelId = internalChannelId.ToString("N"); - if (!string.Equals(channelItem.ExternalId, info.Id, StringComparison.OrdinalIgnoreCase)) + if (item.ParentId != internalChannelId) { - isNew = true; + forceUpdate = true; } - channelItem.ExternalId = info.Id; + item.ParentId = internalChannelId; - if (isNew) + if (!string.Equals(channelItem.ExternalId, info.Id, StringComparison.OrdinalIgnoreCase)) { - channelItem.Tags = info.Tags; + forceUpdate = true; } + channelItem.ExternalId = info.Id; var channelMediaItem = item as IChannelMediaItem; @@ -1294,6 +1306,10 @@ namespace MediaBrowser.Server.Implementations.Channels await _libraryManager.UpdatePeople(item, info.People ?? new List<PersonInfo>()).ConfigureAwait(false); } } + else if (forceUpdate) + { + await item.UpdateToRepository(ItemUpdateType.None, cancellationToken).ConfigureAwait(false); + } return item; } @@ -1518,4 +1534,4 @@ namespace MediaBrowser.Server.Implementations.Channels } } } -} +}
\ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/Channels/ChannelPostScanTask.cs b/MediaBrowser.Server.Implementations/Channels/ChannelPostScanTask.cs index 2e9d42f49..da4a72cd4 100644 --- a/MediaBrowser.Server.Implementations/Channels/ChannelPostScanTask.cs +++ b/MediaBrowser.Server.Implementations/Channels/ChannelPostScanTask.cs @@ -123,15 +123,15 @@ namespace MediaBrowser.Server.Implementations.Channels private async Task CleanDatabase(CancellationToken cancellationToken) { - var allChannels = await _channelManager.GetChannelsInternal(new ChannelQuery { }, cancellationToken); + var installedChannelIds = ((ChannelManager)_channelManager).GetInstalledChannelIds(); - var allIds = _libraryManager.GetItemIds(new InternalItemsQuery + var databaseIds = _libraryManager.GetItemIds(new InternalItemsQuery { IncludeItemTypes = new[] { typeof(Channel).Name } }); - var invalidIds = allIds - .Except(allChannels.Items.Select(i => i.Id).ToList()) + var invalidIds = databaseIds + .Except(installedChannelIds) .ToList(); foreach (var id in invalidIds) diff --git a/MediaBrowser.Server.Implementations/Collections/CollectionImageProvider.cs b/MediaBrowser.Server.Implementations/Collections/CollectionImageProvider.cs index 9ea457284..7ed0d43b1 100644 --- a/MediaBrowser.Server.Implementations/Collections/CollectionImageProvider.cs +++ b/MediaBrowser.Server.Implementations/Collections/CollectionImageProvider.cs @@ -59,7 +59,7 @@ namespace MediaBrowser.Server.Implementations.Collections return subItem; } - var parent = subItem.Parent; + var parent = subItem.GetParent(); if (parent != null && parent.HasImage(ImageType.Primary)) { @@ -78,24 +78,9 @@ namespace MediaBrowser.Server.Implementations.Collections return Task.FromResult(GetFinalItems(items, 2)); } - protected override async Task<string> CreateImage(IHasImages item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex) + protected override Task<string> CreateImage(IHasImages item, List<BaseItem> itemsWithImages, string outputPathWithoutExtension, ImageType imageType, int imageIndex) { - var image = itemsWithImages - .Where(i => i.HasImage(ImageType.Primary) && i.GetImageInfo(ImageType.Primary, 0).IsLocalFile && Path.HasExtension(i.GetImagePath(ImageType.Primary))) - .Select(i => i.GetImagePath(ImageType.Primary)) - .FirstOrDefault(); - - if (string.IsNullOrWhiteSpace(image)) - { - return null; - } - - var ext = Path.GetExtension(image); - - var outputPath = Path.ChangeExtension(outputPathWithoutExtension, ext); - File.Copy(image, outputPath); - - return outputPath; + return CreateSingleImage(itemsWithImages, outputPathWithoutExtension, ImageType.Primary); } } } diff --git a/MediaBrowser.Server.Implementations/Collections/CollectionManager.cs b/MediaBrowser.Server.Implementations/Collections/CollectionManager.cs index 5c98e401f..4e742ca7a 100644 --- a/MediaBrowser.Server.Implementations/Collections/CollectionManager.cs +++ b/MediaBrowser.Server.Implementations/Collections/CollectionManager.cs @@ -40,6 +40,7 @@ namespace MediaBrowser.Server.Implementations.Collections public Folder GetCollectionsFolder(string userId) { return _libraryManager.RootFolder.Children.OfType<ManualCollectionsFolder>() + .FirstOrDefault() ?? _libraryManager.GetUserRootFolder().Children.OfType<ManualCollectionsFolder>() .FirstOrDefault(); } diff --git a/MediaBrowser.Server.Implementations/Collections/ManualCollectionsFolder.cs b/MediaBrowser.Server.Implementations/Collections/ManualCollectionsFolder.cs index d62918d56..7a1d86047 100644 --- a/MediaBrowser.Server.Implementations/Collections/ManualCollectionsFolder.cs +++ b/MediaBrowser.Server.Implementations/Collections/ManualCollectionsFolder.cs @@ -3,7 +3,7 @@ using System.Linq; namespace MediaBrowser.Server.Implementations.Collections { - public class ManualCollectionsFolder : BasePluginFolder + public class ManualCollectionsFolder : BasePluginFolder, IHiddenFromDisplay { public ManualCollectionsFolder() { @@ -11,11 +11,6 @@ namespace MediaBrowser.Server.Implementations.Collections DisplayMediaType = "CollectionFolder"; } - public override bool IsVisible(User user) - { - return base.IsVisible(user) && GetChildren(user, false).Any(); - } - public override bool IsHidden { get @@ -24,7 +19,7 @@ namespace MediaBrowser.Server.Implementations.Collections } } - public override bool IsHiddenFromUser(User user) + public bool IsHiddenFromUser(User user) { return !user.Configuration.DisplayCollectionsView; } @@ -36,7 +31,7 @@ namespace MediaBrowser.Server.Implementations.Collections public override string GetClientTypeName() { - return typeof (CollectionFolder).Name; + return typeof(CollectionFolder).Name; } } }
\ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/Configuration/ServerConfigurationManager.cs b/MediaBrowser.Server.Implementations/Configuration/ServerConfigurationManager.cs index d7df37332..1a5c35df8 100644 --- a/MediaBrowser.Server.Implementations/Configuration/ServerConfigurationManager.cs +++ b/MediaBrowser.Server.Implementations/Configuration/ServerConfigurationManager.cs @@ -35,7 +35,6 @@ namespace MediaBrowser.Server.Implementations.Configuration public ServerConfigurationManager(IApplicationPaths applicationPaths, ILogManager logManager, IXmlSerializer xmlSerializer, IFileSystem fileSystem) : base(applicationPaths, logManager, xmlSerializer, fileSystem) { - UpdateItemsByNamePath(); UpdateMetadataPath(); } @@ -73,7 +72,6 @@ namespace MediaBrowser.Server.Implementations.Configuration /// </summary> protected override void OnConfigurationUpdated() { - UpdateItemsByNamePath(); UpdateMetadataPath(); base.OnConfigurationUpdated(); @@ -87,19 +85,6 @@ namespace MediaBrowser.Server.Implementations.Configuration } /// <summary> - /// Updates the items by name path. - /// </summary> - private void UpdateItemsByNamePath() - { - if (!Configuration.MergeMetadataAndImagesByName) - { - ((ServerApplicationPaths)ApplicationPaths).ItemsByNamePath = string.IsNullOrEmpty(Configuration.ItemsByNamePath) ? - null : - Configuration.ItemsByNamePath; - } - } - - /// <summary> /// Updates the metadata path. /// </summary> private void UpdateMetadataPath() @@ -163,12 +148,36 @@ namespace MediaBrowser.Server.Implementations.Configuration ValidateItemByNamePath(newConfig); ValidatePathSubstitutions(newConfig); ValidateMetadataPath(newConfig); + ValidateSslCertificate(newConfig); EventHelper.FireEventIfNotNull(ConfigurationUpdating, this, new GenericEventArgs<ServerConfiguration> { Argument = newConfig }, Logger); base.ReplaceConfiguration(newConfiguration); } + + /// <summary> + /// Validates the SSL certificate. + /// </summary> + /// <param name="newConfig">The new configuration.</param> + /// <exception cref="System.IO.DirectoryNotFoundException"></exception> + private void ValidateSslCertificate(BaseApplicationConfiguration newConfig) + { + var serverConfig = (ServerConfiguration)newConfig; + + var newPath = serverConfig.CertificatePath; + + if (!string.IsNullOrWhiteSpace(newPath) + && !string.Equals(Configuration.CertificatePath ?? string.Empty, newPath)) + { + // Validate + if (!FileSystem.FileExists(newPath)) + { + throw new FileNotFoundException(string.Format("Certificate file '{0}' does not exist.", newPath)); + } + } + } + private void ValidatePathSubstitutions(ServerConfiguration newConfig) { foreach (var map in newConfig.PathSubstitutions) diff --git a/MediaBrowser.Server.Implementations/Devices/CameraUploadsFolder.cs b/MediaBrowser.Server.Implementations/Devices/CameraUploadsFolder.cs index 6d7265972..947933561 100644 --- a/MediaBrowser.Server.Implementations/Devices/CameraUploadsFolder.cs +++ b/MediaBrowser.Server.Implementations/Devices/CameraUploadsFolder.cs @@ -3,12 +3,15 @@ using MediaBrowser.Controller.Entities; using System; using System.IO; using System.Linq; +using System.Runtime.Serialization; +using System.Threading; +using System.Threading.Tasks; using CommonIO; -using MediaBrowser.Common.IO; +using MediaBrowser.Controller.Providers; namespace MediaBrowser.Server.Implementations.Devices { - public class CameraUploadsFolder : BasePluginFolder + public class CameraUploadsFolder : BasePluginFolder, ISupportsUserSpecificView { public CameraUploadsFolder() { @@ -21,32 +24,41 @@ namespace MediaBrowser.Server.Implementations.Devices { return false; } - - return GetChildren(user, true).Any() && - base.IsVisible(user); + + return base.IsVisible(user) && HasChildren(); } - public override bool IsHidden + public override string CollectionType { - get - { - return base.IsHidden || !Children.Any(); - } + get { return Model.Entities.CollectionType.Photos; } } - public override bool IsHiddenFromUser(User user) + public override string GetClientTypeName() { - return false; + return typeof(CollectionFolder).Name; } - public override string CollectionType + private bool? _hasChildren; + private bool HasChildren() { - get { return Model.Entities.CollectionType.Photos; } + if (!_hasChildren.HasValue) + { + _hasChildren = LibraryManager.GetItemIds(new InternalItemsQuery { ParentId = Id }).Count > 0; + } + + return _hasChildren.Value; } - public override string GetClientTypeName() + protected override Task ValidateChildrenInternal(IProgress<double> progress, CancellationToken cancellationToken, bool recursive, bool refreshChildMetadata, MetadataRefreshOptions refreshOptions, IDirectoryService directoryService) { - return typeof(CollectionFolder).Name; + _hasChildren = null; + return base.ValidateChildrenInternal(progress, cancellationToken, recursive, refreshChildMetadata, refreshOptions, directoryService); + } + + [IgnoreDataMember] + public bool EnableUserSpecificView + { + get { return true; } } } @@ -65,7 +77,7 @@ namespace MediaBrowser.Server.Implementations.Devices { var path = Path.Combine(_appPaths.DataPath, "camerauploads"); - _fileSystem.CreateDirectory(path); + _fileSystem.CreateDirectory(path); return new CameraUploadsFolder { diff --git a/MediaBrowser.Server.Implementations/Devices/DeviceManager.cs b/MediaBrowser.Server.Implementations/Devices/DeviceManager.cs index 0b2c082a8..6b1af8d2d 100644 --- a/MediaBrowser.Server.Implementations/Devices/DeviceManager.cs +++ b/MediaBrowser.Server.Implementations/Devices/DeviceManager.cs @@ -1,6 +1,5 @@ using MediaBrowser.Common.Configuration; using MediaBrowser.Common.Events; -using MediaBrowser.Common.IO; using MediaBrowser.Common.Net; using MediaBrowser.Controller.Devices; using MediaBrowser.Controller.Library; @@ -18,6 +17,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; using CommonIO; +using MediaBrowser.Controller.Configuration; namespace MediaBrowser.Server.Implementations.Devices { @@ -27,7 +27,7 @@ namespace MediaBrowser.Server.Implementations.Devices private readonly IUserManager _userManager; private readonly IFileSystem _fileSystem; private readonly ILibraryMonitor _libraryMonitor; - private readonly IConfigurationManager _config; + private readonly IServerConfigurationManager _config; private readonly ILogger _logger; private readonly INetworkManager _network; @@ -38,7 +38,7 @@ namespace MediaBrowser.Server.Implementations.Devices /// </summary> public event EventHandler<GenericEventArgs<DeviceInfo>> DeviceOptionsUpdated; - public DeviceManager(IDeviceRepository repo, IUserManager userManager, IFileSystem fileSystem, ILibraryMonitor libraryMonitor, IConfigurationManager config, ILogger logger, INetworkManager network) + public DeviceManager(IDeviceRepository repo, IUserManager userManager, IFileSystem fileSystem, ILibraryMonitor libraryMonitor, IServerConfigurationManager config, ILogger logger, INetworkManager network) { _repo = repo; _userManager = userManager; @@ -187,11 +187,6 @@ namespace MediaBrowser.Server.Implementations.Devices } } - private string GetUploadPath(string deviceId) - { - return GetUploadPath(GetDevice(deviceId)); - } - private string GetUploadPath(DeviceInfo device) { if (!string.IsNullOrWhiteSpace(device.CameraUploadPath)) @@ -205,7 +200,7 @@ namespace MediaBrowser.Server.Implementations.Devices return config.CameraUploadPath; } - var path = Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads"); + var path = DefaultCameraUploadsPath; if (config.EnableCameraUploadSubfolders) { @@ -215,6 +210,11 @@ namespace MediaBrowser.Server.Implementations.Devices return path; } + private string DefaultCameraUploadsPath + { + get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "camerauploads"); } + } + public async Task UpdateDeviceInfo(string id, DeviceOptions options) { var device = GetDevice(id); diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index 0cd551f6a..590c5fd3f 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -163,16 +163,11 @@ namespace MediaBrowser.Server.Implementations.Dto if (person != null) { - var items = _libraryManager.GetItems(new InternalItemsQuery + var items = _libraryManager.GetItems(new InternalItemsQuery(user) { Person = byName.Name - }).Items; - - if (user != null) - { - return items.Where(i => i.IsVisibleStandalone(user)).ToList(); - } + }, new string[] { }); return items.ToList(); } @@ -217,17 +212,17 @@ namespace MediaBrowser.Server.Implementations.Dto }).Items; } - public void FillSyncInfo(IEnumerable<IHasSyncInfo> dtos, DtoOptions options, User user) + public void FillSyncInfo(IEnumerable<Tuple<BaseItem, BaseItemDto>> tuples, DtoOptions options, User user) { if (options.Fields.Contains(ItemFields.SyncInfo)) { var syncProgress = GetSyncedItemProgress(options); - foreach (var dto in dtos) + foreach (var tuple in tuples) { - var item = _libraryManager.GetItemById(dto.Id); + var item = tuple.Item1; - FillSyncInfo(dto, item, syncProgress, options, user); + FillSyncInfo(tuple.Item2, item, syncProgress, options, user); } } } @@ -361,6 +356,8 @@ namespace MediaBrowser.Server.Implementations.Dto var collectionFolder = item as ICollectionFolder; if (collectionFolder != null) { + dto.OriginalCollectionType = collectionFolder.CollectionType; + dto.CollectionType = user == null ? collectionFolder.CollectionType : collectionFolder.GetViewType(user); @@ -398,7 +395,7 @@ namespace MediaBrowser.Server.Implementations.Dto else if (item is LiveTvProgram) { - _livetvManager().AddInfoToProgramDto(item, dto, fields.Contains(ItemFields.ChannelInfo), user); + _livetvManager().AddInfoToProgramDto(item, dto, fields, user); } return dto; @@ -468,13 +465,15 @@ namespace MediaBrowser.Server.Implementations.Dto var folder = (Folder)item; - dto.ChildCount = GetChildCount(folder, user); - - // These are just far too slow. - // TODO: Disable for CollectionFolder - if (!(folder is UserRootFolder) && !(folder is UserView)) + if (!(folder is IChannelItem) && !(folder is Channel)) { - SetSpecialCounts(folder, user, dto, fields, syncProgress); + dto.ChildCount = GetChildCount(folder, user); + + // These are just far too slow. + if (!(folder is UserRootFolder) && !(folder is UserView) && !(folder is ICollectionFolder)) + { + SetSpecialCounts(folder, user, dto, fields, syncProgress); + } } dto.UserData.Played = dto.UserData.PlayedPercentage.HasValue && dto.UserData.PlayedPercentage.Value >= 100; @@ -815,7 +814,7 @@ namespace MediaBrowser.Server.Implementations.Dto /// <returns>BaseItem.</returns> private BaseItem GetParentBackdropItem(BaseItem item, BaseItem owner) { - var parent = item.Parent ?? owner; + var parent = item.GetParent() ?? owner; while (parent != null) { @@ -824,7 +823,7 @@ namespace MediaBrowser.Server.Implementations.Dto return parent; } - parent = parent.Parent; + parent = parent.GetParent(); } return null; @@ -839,7 +838,7 @@ namespace MediaBrowser.Server.Implementations.Dto /// <returns>BaseItem.</returns> private BaseItem GetParentImageItem(BaseItem item, ImageType type, BaseItem owner) { - var parent = item.Parent ?? owner; + var parent = item.GetParent() ?? owner; while (parent != null) { @@ -848,7 +847,7 @@ namespace MediaBrowser.Server.Implementations.Dto return parent; } - parent = parent.Parent; + parent = parent.GetParent(); } return null; @@ -1042,7 +1041,11 @@ namespace MediaBrowser.Server.Implementations.Dto dto.IsFolder = item.IsFolder; dto.MediaType = item.MediaType; dto.LocationType = item.LocationType; - dto.IsHD = item.IsHD; + if (item.IsHD.HasValue && item.IsHD.Value) + { + dto.IsHD = item.IsHD; + } + dto.Audio = item.Audio; dto.PreferredMetadataCountryCode = item.PreferredMetadataCountryCode; dto.PreferredMetadataLanguage = item.PreferredMetadataLanguage; @@ -1209,15 +1212,15 @@ namespace MediaBrowser.Server.Implementations.Dto dto.VoteCount = item.VoteCount; } - if (item.IsFolder) - { - var folder = (Folder)item; + //if (item.IsFolder) + //{ + // var folder = (Folder)item; - if (fields.Contains(ItemFields.IndexOptions)) - { - dto.IndexOptions = folder.IndexByOptionStrings.ToArray(); - } - } + // if (fields.Contains(ItemFields.IndexOptions)) + // { + // dto.IndexOptions = folder.IndexByOptionStrings.ToArray(); + // } + //} var supportsPlaceHolders = item as ISupportsPlaceHolders; if (supportsPlaceHolders != null) @@ -1520,7 +1523,7 @@ namespace MediaBrowser.Server.Implementations.Dto } dto.ChannelId = item.ChannelId; - + var channelItem = item as IChannelItem; if (channelItem != null) { diff --git a/MediaBrowser.Server.Implementations/EntryPoints/UsageReporter.cs b/MediaBrowser.Server.Implementations/EntryPoints/UsageReporter.cs index be2817fd2..47c754643 100644 --- a/MediaBrowser.Server.Implementations/EntryPoints/UsageReporter.cs +++ b/MediaBrowser.Server.Implementations/EntryPoints/UsageReporter.cs @@ -18,7 +18,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints private readonly IHttpClient _httpClient; private readonly IUserManager _userManager; private readonly ILogger _logger; - private const string MbAdminUrl = "http://www.mb3admin.com/admin/"; + private const string MbAdminUrl = "https://www.mb3admin.com/admin/"; public UsageReporter(IApplicationHost applicationHost, IHttpClient httpClient, IUserManager userManager, ILogger logger) { diff --git a/MediaBrowser.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs b/MediaBrowser.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs index 008363ca4..b059e4144 100644 --- a/MediaBrowser.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs +++ b/MediaBrowser.Server.Implementations/EntryPoints/UserDataChangeNotifier.cs @@ -74,7 +74,7 @@ namespace MediaBrowser.Server.Implementations.EntryPoints // Go up one level for indicators if (baseItem != null) { - var parent = baseItem.Parent; + var parent = baseItem.GetParent(); if (parent != null) { diff --git a/MediaBrowser.Server.Implementations/FileOrganization/EpisodeFileOrganizer.cs b/MediaBrowser.Server.Implementations/FileOrganization/EpisodeFileOrganizer.cs index 73cc5ab01..9d43dabcd 100644 --- a/MediaBrowser.Server.Implementations/FileOrganization/EpisodeFileOrganizer.cs +++ b/MediaBrowser.Server.Implementations/FileOrganization/EpisodeFileOrganizer.cs @@ -46,12 +46,12 @@ namespace MediaBrowser.Server.Implementations.FileOrganization public Task<FileOrganizationResult> OrganizeEpisodeFile(string path, CancellationToken cancellationToken) { - var options = _config.GetAutoOrganizeOptions().TvOptions; + var options = _config.GetAutoOrganizeOptions(); return OrganizeEpisodeFile(path, options, false, cancellationToken); } - public async Task<FileOrganizationResult> OrganizeEpisodeFile(string path, TvFileOrganizationOptions options, bool overwriteExisting, CancellationToken cancellationToken) + public async Task<FileOrganizationResult> OrganizeEpisodeFile(string path, AutoOrganizeOptions options, bool overwriteExisting, CancellationToken cancellationToken) { _logger.Info("Sorting file {0}", path); @@ -110,6 +110,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization premiereDate, options, overwriteExisting, + false, result, cancellationToken).ConfigureAwait(false); } @@ -145,7 +146,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization return result; } - public async Task<FileOrganizationResult> OrganizeWithCorrection(EpisodeFileOrganizationRequest request, TvFileOrganizationOptions options, CancellationToken cancellationToken) + public async Task<FileOrganizationResult> OrganizeWithCorrection(EpisodeFileOrganizationRequest request, AutoOrganizeOptions options, CancellationToken cancellationToken) { var result = _organizationService.GetResult(request.ResultId); @@ -159,6 +160,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization null, options, true, + request.RememberCorrection, result, cancellationToken).ConfigureAwait(false); @@ -173,12 +175,13 @@ namespace MediaBrowser.Server.Implementations.FileOrganization int? episodeNumber, int? endingEpiosdeNumber, DateTime? premiereDate, - TvFileOrganizationOptions options, + AutoOrganizeOptions options, bool overwriteExisting, + bool rememberCorrection, FileOrganizationResult result, CancellationToken cancellationToken) { - var series = GetMatchingSeries(seriesName, result); + var series = GetMatchingSeries(seriesName, result, options); if (series == null) { @@ -197,6 +200,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization premiereDate, options, overwriteExisting, + rememberCorrection, result, cancellationToken); } @@ -207,15 +211,18 @@ namespace MediaBrowser.Server.Implementations.FileOrganization int? episodeNumber, int? endingEpiosdeNumber, DateTime? premiereDate, - TvFileOrganizationOptions options, + AutoOrganizeOptions options, bool overwriteExisting, + bool rememberCorrection, FileOrganizationResult result, CancellationToken cancellationToken) { _logger.Info("Sorting file {0} into series {1}", sourcePath, series.Path); + var originalExtractedSeriesString = result.ExtractedName; + // Proceed to sort the file - var newPath = await GetNewPath(sourcePath, series, seasonNumber, episodeNumber, endingEpiosdeNumber, premiereDate, options, cancellationToken).ConfigureAwait(false); + var newPath = await GetNewPath(sourcePath, series, seasonNumber, episodeNumber, endingEpiosdeNumber, premiereDate, options.TvOptions, cancellationToken).ConfigureAwait(false); if (string.IsNullOrEmpty(newPath)) { @@ -234,7 +241,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization if (!overwriteExisting) { - if (options.CopyOriginalFile && fileExists && IsSameEpisode(sourcePath, newPath)) + if (options.TvOptions.CopyOriginalFile && fileExists && IsSameEpisode(sourcePath, newPath)) { _logger.Info("File {0} already copied to new path {1}, stopping organization", sourcePath, newPath); result.Status = FileSortingStatus.SkippedExisting; @@ -251,7 +258,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization } } - PerformFileSorting(options, result); + PerformFileSorting(options.TvOptions, result); if (overwriteExisting) { @@ -285,6 +292,35 @@ namespace MediaBrowser.Server.Implementations.FileOrganization } } } + + if (rememberCorrection) + { + SaveSmartMatchString(originalExtractedSeriesString, series, options); + } + } + + private void SaveSmartMatchString(string matchString, Series series, AutoOrganizeOptions options) + { + SmartMatchInfo info = options.SmartMatchInfos.FirstOrDefault(i => string.Equals(i.ItemName, series.Name, StringComparison.OrdinalIgnoreCase)); + + if (info == null) + { + info = new SmartMatchInfo(); + info.ItemName = series.Name; + info.OrganizerType = FileOrganizerType.Episode; + info.DisplayName = series.Name; + var list = options.SmartMatchInfos.ToList(); + list.Add(info); + options.SmartMatchInfos = list.ToArray(); + } + + if (!info.MatchStrings.Contains(matchString, StringComparer.OrdinalIgnoreCase)) + { + var list = info.MatchStrings.ToList(); + list.Add(matchString); + info.MatchStrings = list.ToArray(); + _config.SaveAutoOrganizeOptions(options); + } } private void DeleteLibraryFile(string path, bool renameRelatedFiles, string targetPath) @@ -331,7 +367,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization int? endingEpisodeNumber) { // TODO: Support date-naming? - if (!seasonNumber.HasValue || episodeNumber.HasValue) + if (!seasonNumber.HasValue || !episodeNumber.HasValue) { return new List<string>(); } @@ -435,7 +471,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization } } - private Series GetMatchingSeries(string seriesName, FileOrganizationResult result) + private Series GetMatchingSeries(string seriesName, FileOrganizationResult result, AutoOrganizeOptions options) { var parsedName = _libraryManager.ParseName(seriesName); @@ -445,13 +481,28 @@ namespace MediaBrowser.Server.Implementations.FileOrganization result.ExtractedName = nameWithoutYear; result.ExtractedYear = yearInName; - return _libraryManager.RootFolder.GetRecursiveChildren(i => i is Series) + var series = _libraryManager.RootFolder.GetRecursiveChildren(i => i is Series) .Cast<Series>() .Select(i => NameUtils.GetMatchScore(nameWithoutYear, yearInName, i)) .Where(i => i.Item2 > 0) .OrderByDescending(i => i.Item2) .Select(i => i.Item1) .FirstOrDefault(); + + if (series == null) + { + SmartMatchInfo info = options.SmartMatchInfos.FirstOrDefault(e => e.MatchStrings.Contains(seriesName, StringComparer.OrdinalIgnoreCase)); + + if (info != null) + { + series = _libraryManager.RootFolder + .GetRecursiveChildren(i => i is Series) + .Cast<Series>() + .FirstOrDefault(i => string.Equals(i.Name, info.ItemName, StringComparison.OrdinalIgnoreCase)); + } + } + + return series ?? new Series(); } /// <summary> diff --git a/MediaBrowser.Server.Implementations/FileOrganization/Extensions.cs b/MediaBrowser.Server.Implementations/FileOrganization/Extensions.cs index e43ab3665..c560152db 100644 --- a/MediaBrowser.Server.Implementations/FileOrganization/Extensions.cs +++ b/MediaBrowser.Server.Implementations/FileOrganization/Extensions.cs @@ -10,6 +10,10 @@ namespace MediaBrowser.Server.Implementations.FileOrganization { return manager.GetConfiguration<AutoOrganizeOptions>("autoorganize"); } + public static void SaveAutoOrganizeOptions(this IConfigurationManager manager, AutoOrganizeOptions options) + { + manager.SaveConfiguration("autoorganize", options); + } } public class AutoOrganizeOptionsFactory : IConfigurationFactory diff --git a/MediaBrowser.Server.Implementations/FileOrganization/FileOrganizationService.cs b/MediaBrowser.Server.Implementations/FileOrganization/FileOrganizationService.cs index 839a85adb..cf1387b0e 100644 --- a/MediaBrowser.Server.Implementations/FileOrganization/FileOrganizationService.cs +++ b/MediaBrowser.Server.Implementations/FileOrganization/FileOrganizationService.cs @@ -11,6 +11,7 @@ using MediaBrowser.Model.Logging; using MediaBrowser.Model.Querying; using System; using System.IO; +using System.Linq; using System.Threading; using System.Threading.Tasks; using CommonIO; @@ -96,9 +97,9 @@ namespace MediaBrowser.Server.Implementations.FileOrganization return _repo.Delete(resultId); } - private TvFileOrganizationOptions GetTvOptions() + private AutoOrganizeOptions GetAutoOrganizeptions() { - return _config.GetAutoOrganizeOptions().TvOptions; + return _config.GetAutoOrganizeOptions(); } public async Task PerformOrganization(string resultId) @@ -113,7 +114,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization var organizer = new EpisodeFileOrganizer(this, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager); - await organizer.OrganizeEpisodeFile(result.OriginalPath, GetTvOptions(), true, CancellationToken.None) + await organizer.OrganizeEpisodeFile(result.OriginalPath, GetAutoOrganizeptions(), true, CancellationToken.None) .ConfigureAwait(false); } @@ -127,7 +128,58 @@ namespace MediaBrowser.Server.Implementations.FileOrganization var organizer = new EpisodeFileOrganizer(this, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager); - await organizer.OrganizeWithCorrection(request, GetTvOptions(), CancellationToken.None).ConfigureAwait(false); + await organizer.OrganizeWithCorrection(request, GetAutoOrganizeptions(), CancellationToken.None).ConfigureAwait(false); + } + + public QueryResult<SmartMatchInfo> GetSmartMatchInfos(FileOrganizationResultQuery query) + { + if (query == null) + { + throw new ArgumentNullException("query"); + } + + var options = GetAutoOrganizeptions(); + + var items = options.SmartMatchInfos.Skip(query.StartIndex ?? 0).Take(query.Limit ?? Int32.MaxValue).ToArray(); + + return new QueryResult<SmartMatchInfo>() + { + Items = items, + TotalRecordCount = options.SmartMatchInfos.Length + }; + } + + public void DeleteSmartMatchEntry(string itemName, string matchString) + { + if (string.IsNullOrEmpty(itemName)) + { + throw new ArgumentNullException("itemName"); + } + + if (string.IsNullOrEmpty(matchString)) + { + throw new ArgumentNullException("matchString"); + } + + var options = GetAutoOrganizeptions(); + + SmartMatchInfo info = options.SmartMatchInfos.FirstOrDefault(i => string.Equals(i.ItemName, itemName)); + + if (info != null && info.MatchStrings.Contains(matchString)) + { + var list = info.MatchStrings.ToList(); + list.Remove(matchString); + info.MatchStrings = list.ToArray(); + + if (info.MatchStrings.Length == 0) + { + var infos = options.SmartMatchInfos.ToList(); + infos.Remove(info); + options.SmartMatchInfos = infos.ToArray(); + } + + _config.SaveAutoOrganizeOptions(options); + } } } } diff --git a/MediaBrowser.Server.Implementations/FileOrganization/OrganizerScheduledTask.cs b/MediaBrowser.Server.Implementations/FileOrganization/OrganizerScheduledTask.cs index f1fe5539f..ace3b5af7 100644 --- a/MediaBrowser.Server.Implementations/FileOrganization/OrganizerScheduledTask.cs +++ b/MediaBrowser.Server.Implementations/FileOrganization/OrganizerScheduledTask.cs @@ -50,17 +50,17 @@ namespace MediaBrowser.Server.Implementations.FileOrganization get { return "Library"; } } - private TvFileOrganizationOptions GetTvOptions() + private AutoOrganizeOptions GetAutoOrganizeOptions() { - return _config.GetAutoOrganizeOptions().TvOptions; + return _config.GetAutoOrganizeOptions(); } public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress) { - if (GetTvOptions().IsEnabled) + if (GetAutoOrganizeOptions().TvOptions.IsEnabled) { await new TvFolderOrganizer(_libraryManager, _logger, _fileSystem, _libraryMonitor, _organizationService, _config, _providerManager) - .Organize(GetTvOptions(), cancellationToken, progress).ConfigureAwait(false); + .Organize(GetAutoOrganizeOptions(), cancellationToken, progress).ConfigureAwait(false); } } @@ -74,12 +74,12 @@ namespace MediaBrowser.Server.Implementations.FileOrganization public bool IsHidden { - get { return !GetTvOptions().IsEnabled; } + get { return !GetAutoOrganizeOptions().TvOptions.IsEnabled; } } public bool IsEnabled { - get { return GetTvOptions().IsEnabled; } + get { return GetAutoOrganizeOptions().TvOptions.IsEnabled; } } public bool IsActivityLogged diff --git a/MediaBrowser.Server.Implementations/FileOrganization/TvFolderOrganizer.cs b/MediaBrowser.Server.Implementations/FileOrganization/TvFolderOrganizer.cs index 3e5296639..845fcdff2 100644 --- a/MediaBrowser.Server.Implementations/FileOrganization/TvFolderOrganizer.cs +++ b/MediaBrowser.Server.Implementations/FileOrganization/TvFolderOrganizer.cs @@ -52,13 +52,13 @@ namespace MediaBrowser.Server.Implementations.FileOrganization return false; } - public async Task Organize(TvFileOrganizationOptions options, CancellationToken cancellationToken, IProgress<double> progress) + public async Task Organize(AutoOrganizeOptions options, CancellationToken cancellationToken, IProgress<double> progress) { - var watchLocations = options.WatchLocations.ToList(); + var watchLocations = options.TvOptions.WatchLocations.ToList(); var eligibleFiles = watchLocations.SelectMany(GetFilesToOrganize) .OrderBy(_fileSystem.GetCreationTimeUtc) - .Where(i => EnableOrganization(i, options)) + .Where(i => EnableOrganization(i, options.TvOptions)) .ToList(); var processedFolders = new HashSet<string>(); @@ -76,7 +76,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization try { - var result = await organizer.OrganizeEpisodeFile(file.FullName, options, options.OverwriteExistingEpisodes, cancellationToken).ConfigureAwait(false); + var result = await organizer.OrganizeEpisodeFile(file.FullName, options, options.TvOptions.OverwriteExistingEpisodes, cancellationToken).ConfigureAwait(false); if (result.Status == FileSortingStatus.Success && !processedFolders.Contains(file.DirectoryName, StringComparer.OrdinalIgnoreCase)) { processedFolders.Add(file.DirectoryName); @@ -100,7 +100,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization foreach (var path in processedFolders) { - var deleteExtensions = options.LeftOverFileExtensionsToDelete + var deleteExtensions = options.TvOptions.LeftOverFileExtensionsToDelete .Select(i => i.Trim().TrimStart('.')) .Where(i => !string.IsNullOrEmpty(i)) .Select(i => "." + i) @@ -111,7 +111,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization DeleteLeftOverFiles(path, deleteExtensions); } - if (options.DeleteEmptyFolders) + if (options.TvOptions.DeleteEmptyFolders) { if (!IsWatchFolder(path, watchLocations)) { diff --git a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs index 038116703..a11eb3aaa 100644 --- a/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs +++ b/MediaBrowser.Server.Implementations/HttpServer/HttpListenerHost.cs @@ -241,7 +241,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer } catch (Exception errorEx) { - _logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx); + //_logger.ErrorException("Error this.ProcessRequest(context)(Exception while writing error to the response)", errorEx); } } @@ -266,13 +266,26 @@ namespace MediaBrowser.Server.Implementations.HttpServer {".html", 0} }; - private bool EnableLogging(string url) + private bool EnableLogging(string url, string localPath) { - var parts = url.Split(new[] { '?' }, 2); + var extension = GetExtension(url); + + if (string.IsNullOrWhiteSpace(extension) || !_skipLogExtensions.ContainsKey(extension)) + { + if (string.IsNullOrWhiteSpace(localPath) || localPath.IndexOf("system/ping", StringComparison.OrdinalIgnoreCase) == -1) + { + return true; + } + } + + return false; + } - var extension = Path.GetExtension(parts[0]); + private string GetExtension(string url) + { + var parts = url.Split(new[] { '?' }, 2); - return string.IsNullOrWhiteSpace(extension) || !_skipLogExtensions.ContainsKey(extension); + return Path.GetExtension(parts[0]); } /// <summary> @@ -291,7 +304,7 @@ namespace MediaBrowser.Server.Implementations.HttpServer var localPath = url.LocalPath; var urlString = url.OriginalString; - var enableLog = EnableLogging(urlString); + var enableLog = EnableLogging(urlString, localPath); if (enableLog) { @@ -337,8 +350,16 @@ namespace MediaBrowser.Server.Implementations.HttpServer if (!string.IsNullOrWhiteSpace(GlobalResponse)) { - httpRes.Write(GlobalResponse); - httpRes.ContentType = "text/plain"; + if (string.Equals(GetExtension(urlString), "html", StringComparison.OrdinalIgnoreCase)) + { + httpRes.Write(GlobalResponse); + httpRes.ContentType = "text/plain"; + } + else + { + httpRes.StatusCode = 503; + } + return Task.FromResult(true); } diff --git a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs index 184b72d8f..764eb7c68 100644 --- a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs +++ b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs @@ -217,7 +217,7 @@ namespace MediaBrowser.Server.Implementations.IO /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param> void LibraryManager_ItemRemoved(object sender, ItemChangeEventArgs e) { - if (e.Item.Parent is AggregateFolder) + if (e.Item.GetParent() is AggregateFolder) { StopWatchingPath(e.Item.Path); } @@ -230,7 +230,7 @@ namespace MediaBrowser.Server.Implementations.IO /// <param name="e">The <see cref="ItemChangeEventArgs"/> instance containing the event data.</param> void LibraryManager_ItemAdded(object sender, ItemChangeEventArgs e) { - if (e.Item.Parent is AggregateFolder) + if (e.Item.GetParent() is AggregateFolder) { StartWatchingPath(e.Item.Path); } @@ -542,9 +542,16 @@ namespace MediaBrowser.Server.Implementations.IO return false; } + // In order to determine if the file is being written to, we have to request write access + // But if the server only has readonly access, this is going to cause this entire algorithm to fail + // So we'll take a best guess about our access level + var requestedFileAccess = ConfigurationManager.Configuration.SaveLocalMeta + ? FileAccess.ReadWrite + : FileAccess.Read; + try { - using (_fileSystem.GetFileStream(path, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)) + using (_fileSystem.GetFileStream(path, FileMode.Open, requestedFileAccess, FileShare.ReadWrite)) { if (_updateTimer != null) { @@ -661,7 +668,7 @@ namespace MediaBrowser.Server.Implementations.IO // If the item has been deleted find the first valid parent that still exists while (!_fileSystem.DirectoryExists(item.Path) && !_fileSystem.FileExists(item.Path)) { - item = item.Parent; + item = item.GetParent(); if (item == null) { diff --git a/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs b/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs index 37131ad2c..5b72860b6 100644 --- a/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs +++ b/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs @@ -17,6 +17,7 @@ using System.Threading; using System.Threading.Tasks; using CommonIO; using MediaBrowser.Common.IO; +using MoreLinq; namespace MediaBrowser.Server.Implementations.Intros { @@ -28,8 +29,9 @@ namespace MediaBrowser.Server.Implementations.Intros private readonly IConfigurationManager _serverConfig; private readonly ILibraryManager _libraryManager; private readonly IFileSystem _fileSystem; + private readonly IMediaSourceManager _mediaSourceManager; - public DefaultIntroProvider(ISecurityManager security, IChannelManager channelManager, ILocalizationManager localization, IConfigurationManager serverConfig, ILibraryManager libraryManager, IFileSystem fileSystem) + public DefaultIntroProvider(ISecurityManager security, IChannelManager channelManager, ILocalizationManager localization, IConfigurationManager serverConfig, ILibraryManager libraryManager, IFileSystem fileSystem, IMediaSourceManager mediaSourceManager) { _security = security; _channelManager = channelManager; @@ -37,6 +39,7 @@ namespace MediaBrowser.Server.Implementations.Intros _serverConfig = serverConfig; _libraryManager = libraryManager; _fileSystem = fileSystem; + _mediaSourceManager = mediaSourceManager; } public async Task<IEnumerable<IntroInfo>> GetIntros(BaseItem item, User user) @@ -78,13 +81,11 @@ namespace MediaBrowser.Server.Implementations.Intros if (config.EnableIntrosFromMoviesInLibrary) { - var inputItems = _libraryManager.GetItems(new InternalItemsQuery + var inputItems = _libraryManager.GetItems(new InternalItemsQuery(user) { - IncludeItemTypes = new[] { typeof(Movie).Name }, + IncludeItemTypes = new[] { typeof(Movie).Name } - User = user - - }).Items; + }, new string[] { }); var itemsWithTrailers = inputItems .Where(i => @@ -163,7 +164,11 @@ namespace MediaBrowser.Server.Implementations.Intros private IEnumerable<IntroInfo> GetResult(BaseItem item, IEnumerable<ItemWithTrailer> candidates, CinemaModeConfiguration config, int? ratingLevel) { var customIntros = !string.IsNullOrWhiteSpace(config.CustomIntroPath) ? - GetCustomIntros(item) : + GetCustomIntros(config) : + new List<IntroInfo>(); + + var mediaInfoIntros = !string.IsNullOrWhiteSpace(config.MediaInfoIntroPath) ? + GetMediaInfoIntros(config, item) : new List<IntroInfo>(); var trailerLimit = config.TrailerLimit; @@ -187,7 +192,8 @@ namespace MediaBrowser.Server.Implementations.Intros .ThenByDescending(i => (i.IsPlayed ? 0 : 1)) .Select(i => i.IntroInfo) .Take(trailerLimit) - .Concat(customIntros.Take(1)); + .Concat(customIntros.Take(1)) + .Concat(mediaInfoIntros); } private bool IsDuplicate(BaseItem playingContent, BaseItem test) @@ -212,11 +218,11 @@ namespace MediaBrowser.Server.Implementations.Intros return _serverConfig.GetConfiguration<CinemaModeConfiguration>("cinemamode"); } - private List<IntroInfo> GetCustomIntros(BaseItem item) + private List<IntroInfo> GetCustomIntros(CinemaModeConfiguration options) { try { - return GetCustomIntroFiles() + return GetCustomIntroFiles(options, true, false) .OrderBy(i => Guid.NewGuid()) .Select(i => new IntroInfo { @@ -230,17 +236,151 @@ namespace MediaBrowser.Server.Implementations.Intros } } - private IEnumerable<string> GetCustomIntroFiles(CinemaModeConfiguration options = null) + private IEnumerable<IntroInfo> GetMediaInfoIntros(CinemaModeConfiguration options, BaseItem item) + { + try + { + var hasMediaSources = item as IHasMediaSources; + + if (hasMediaSources == null) + { + return new List<IntroInfo>(); + } + + var mediaSource = _mediaSourceManager.GetStaticMediaSources(hasMediaSources, false) + .FirstOrDefault(); + + if (mediaSource == null) + { + return new List<IntroInfo>(); + } + + var videoStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Video); + var audioStream = mediaSource.MediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio); + + var allIntros = GetCustomIntroFiles(options, false, true) + .OrderBy(i => Guid.NewGuid()) + .Select(i => new IntroInfo + { + Path = i + + }).ToList(); + + var returnResult = new List<IntroInfo>(); + + if (videoStream != null) + { + returnResult.AddRange(GetMediaInfoIntrosByVideoStream(allIntros, videoStream).Take(1)); + } + + if (audioStream != null) + { + returnResult.AddRange(GetMediaInfoIntrosByAudioStream(allIntros, audioStream).Take(1)); + } + + returnResult.AddRange(GetMediaInfoIntrosByTags(allIntros, item.Tags).Take(1)); + + return returnResult.DistinctBy(i => i.Path, StringComparer.OrdinalIgnoreCase); + } + catch (IOException) + { + return new List<IntroInfo>(); + } + } + + private IEnumerable<IntroInfo> GetMediaInfoIntrosByVideoStream(List<IntroInfo> allIntros, MediaStream stream) + { + var codec = stream.Codec; + + if (string.IsNullOrWhiteSpace(codec)) + { + return new List<IntroInfo>(); + } + + return allIntros + .Where(i => IsMatch(i.Path, codec)); + } + + private IEnumerable<IntroInfo> GetMediaInfoIntrosByAudioStream(List<IntroInfo> allIntros, MediaStream stream) + { + var codec = stream.Codec; + + if (string.IsNullOrWhiteSpace(codec)) + { + return new List<IntroInfo>(); + } + + return allIntros + .Where(i => IsAudioMatch(i.Path, stream)); + } + + private IEnumerable<IntroInfo> GetMediaInfoIntrosByTags(List<IntroInfo> allIntros, List<string> tags) { - options = options ?? GetOptions(); + return allIntros + .Where(i => tags.Any(t => IsMatch(i.Path, t))); + } + + private bool IsMatch(string file, string attribute) + { + var filename = Path.GetFileNameWithoutExtension(file) ?? string.Empty; + filename = Normalize(filename); + + if (string.IsNullOrWhiteSpace(filename)) + { + return false; + } + + attribute = Normalize(attribute); + if (string.IsNullOrWhiteSpace(attribute)) + { + return false; + } + + return string.Equals(filename, attribute, StringComparison.OrdinalIgnoreCase); + } + + private string Normalize(string value) + { + return value; + } + + private bool IsAudioMatch(string path, MediaStream stream) + { + if (!string.IsNullOrWhiteSpace(stream.Codec)) + { + if (IsMatch(path, stream.Codec)) + { + return true; + } + } + if (!string.IsNullOrWhiteSpace(stream.Profile)) + { + if (IsMatch(path, stream.Profile)) + { + return true; + } + } + + return false; + } + + private IEnumerable<string> GetCustomIntroFiles(CinemaModeConfiguration options, bool enableCustomIntros, bool enableMediaInfoIntros) + { + var list = new List<string>(); + + if (enableCustomIntros && !string.IsNullOrWhiteSpace(options.CustomIntroPath)) + { + list.AddRange(_fileSystem.GetFilePaths(options.CustomIntroPath, true) + .Where(_libraryManager.IsVideoFile)); + } - if (string.IsNullOrWhiteSpace(options.CustomIntroPath)) + if (enableMediaInfoIntros && !string.IsNullOrWhiteSpace(options.MediaInfoIntroPath)) { - return new List<string>(); + list.AddRange(_fileSystem.GetFilePaths(options.MediaInfoIntroPath, true) + .Where(_libraryManager.IsVideoFile)); } - return _fileSystem.GetFilePaths(options.CustomIntroPath, true) - .Where(_libraryManager.IsVideoFile); + return list.Distinct(StringComparer.OrdinalIgnoreCase); } private bool FilterByParentalRating(int? ratingLevel, BaseItem item) @@ -341,7 +481,7 @@ namespace MediaBrowser.Server.Implementations.Intros public IEnumerable<string> GetAllIntroFiles() { - return GetCustomIntroFiles(); + return GetCustomIntroFiles(GetOptions(), true, true); } private bool IsSupporter diff --git a/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs index 9035d6479..402fa439d 100644 --- a/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs +++ b/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs @@ -47,11 +47,14 @@ namespace MediaBrowser.Server.Implementations.Library /// <summary> /// Shoulds the ignore. /// </summary> - /// <param name="args">The args.</param> + /// <param name="fileInfo">The file information.</param> + /// <param name="parent">The parent.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise</returns> - public bool ShouldIgnore(ItemResolveArgs args) + public bool ShouldIgnore(FileSystemMetadata fileInfo, BaseItem parent) { - var filename = args.FileInfo.Name; + var filename = fileInfo.Name; + var isHidden = (fileInfo.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden; + var path = fileInfo.FullName; // Handle mac .DS_Store // https://github.com/MediaBrowser/MediaBrowser/issues/427 @@ -61,21 +64,24 @@ namespace MediaBrowser.Server.Implementations.Library } // Ignore hidden files and folders - if (args.IsHidden) + if (isHidden) { - var parentFolderName = Path.GetFileName(Path.GetDirectoryName(args.Path)); - - if (string.Equals(parentFolderName, BaseItem.ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase)) - { - return false; - } - if (string.Equals(parentFolderName, BaseItem.ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase)) + if (parent == null) { - return false; + var parentFolderName = Path.GetFileName(Path.GetDirectoryName(path)); + + if (string.Equals(parentFolderName, BaseItem.ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + if (string.Equals(parentFolderName, BaseItem.ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase)) + { + return false; + } } // Sometimes these are marked hidden - if (_fileSystem.IsRootPath(args.Path)) + if (_fileSystem.IsRootPath(path)) { return false; } @@ -83,7 +89,7 @@ namespace MediaBrowser.Server.Implementations.Library return true; } - if (args.IsDirectory) + if (fileInfo.IsDirectory) { // Ignore any folders in our list if (IgnoreFolders.Contains(filename, StringComparer.OrdinalIgnoreCase)) @@ -91,26 +97,29 @@ namespace MediaBrowser.Server.Implementations.Library return true; } - // Ignore trailer folders but allow it at the collection level - if (string.Equals(filename, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase) && - !(args.Parent is AggregateFolder) && !(args.Parent is UserRootFolder)) + if (parent != null) { - return true; - } + // Ignore trailer folders but allow it at the collection level + if (string.Equals(filename, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase) && + !(parent is AggregateFolder) && !(parent is UserRootFolder)) + { + return true; + } - if (string.Equals(filename, BaseItem.ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase)) - { - return true; - } + if (string.Equals(filename, BaseItem.ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } - if (string.Equals(filename, BaseItem.ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase)) - { - return true; + if (string.Equals(filename, BaseItem.ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } } } else { - if (args.Parent != null) + if (parent != null) { // Don't resolve these into audio files if (string.Equals(_fileSystem.GetFileNameWithoutExtension(filename), BaseItem.ThemeSongFilename) && _libraryManager.IsAudioFile(filename)) diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index b0b2680ca..333b1fbe9 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -27,6 +27,7 @@ using MediaBrowser.Server.Implementations.Library.Validators; using MediaBrowser.Server.Implementations.Logging; using MediaBrowser.Server.Implementations.ScheduledTasks; using System; +using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; @@ -37,6 +38,7 @@ using System.Threading; using System.Threading.Tasks; using CommonIO; using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.Library; using MediaBrowser.Model.Net; using MoreLinq; using SortOrder = MediaBrowser.Model.Entities.SortOrder; @@ -142,6 +144,7 @@ namespace MediaBrowser.Server.Implementations.Library private readonly Func<ILibraryMonitor> _libraryMonitorFactory; private readonly Func<IProviderManager> _providerManagerFactory; + private readonly Func<IUserViewManager> _userviewManager; /// <summary> /// The _library items cache @@ -169,7 +172,7 @@ namespace MediaBrowser.Server.Implementations.Library /// <param name="userManager">The user manager.</param> /// <param name="configurationManager">The configuration manager.</param> /// <param name="userDataRepository">The user data repository.</param> - public LibraryManager(ILogger logger, ITaskManager taskManager, IUserManager userManager, IServerConfigurationManager configurationManager, IUserDataManager userDataRepository, Func<ILibraryMonitor> libraryMonitorFactory, IFileSystem fileSystem, Func<IProviderManager> providerManagerFactory) + public LibraryManager(ILogger logger, ITaskManager taskManager, IUserManager userManager, IServerConfigurationManager configurationManager, IUserDataManager userDataRepository, Func<ILibraryMonitor> libraryMonitorFactory, IFileSystem fileSystem, Func<IProviderManager> providerManagerFactory, Func<IUserViewManager> userviewManager) { _logger = logger; _taskManager = taskManager; @@ -179,6 +182,7 @@ namespace MediaBrowser.Server.Implementations.Library _libraryMonitorFactory = libraryMonitorFactory; _fileSystem = fileSystem; _providerManagerFactory = providerManagerFactory; + _userviewManager = userviewManager; ByReferenceItems = new ConcurrentDictionary<Guid, BaseItem>(); _libraryItemsCache = new ConcurrentDictionary<Guid, BaseItem>(); @@ -403,12 +407,12 @@ namespace MediaBrowser.Server.Implementations.Library { foreach (var path in item.GetDeletePaths().ToList()) { - if (_fileSystem.DirectoryExists(path)) + if (_fileSystem.DirectoryExists(path)) { _logger.Debug("Deleting path {0}", path); _fileSystem.DeleteDirectory(path, true); } - else if (_fileSystem.FileExists(path)) + else if (_fileSystem.FileExists(path)) { _logger.Debug("Deleting path {0}", path); _fileSystem.DeleteFile(path); @@ -582,7 +586,7 @@ namespace MediaBrowser.Server.Implementations.Library }; // Return null if ignore rules deem that we should do so - if (EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(args))) + if (IgnoreFile(args.FileInfo, args.Parent)) { return null; } @@ -618,6 +622,11 @@ namespace MediaBrowser.Server.Implementations.Library return ResolveItem(args); } + public bool IgnoreFile(FileSystemMetadata file, BaseItem parent) + { + return EntityResolutionIgnoreRules.Any(r => r.ShouldIgnore(file, parent)); + } + public IEnumerable<FileSystemMetadata> NormalizeRootPathList(IEnumerable<FileSystemMetadata> paths) { var originalList = paths.ToList(); @@ -653,7 +662,7 @@ namespace MediaBrowser.Server.Implementations.Library public IEnumerable<BaseItem> ResolvePaths(IEnumerable<FileSystemMetadata> files, IDirectoryService directoryService, Folder parent, string collectionType) { - var fileList = files.ToList(); + var fileList = files.Where(i => !IgnoreFile(i, parent)).ToList(); if (parent != null) { @@ -704,7 +713,7 @@ namespace MediaBrowser.Server.Implementations.Library { var rootFolderPath = ConfigurationManager.ApplicationPaths.RootFolderPath; - _fileSystem.CreateDirectory(rootFolderPath); + _fileSystem.CreateDirectory(rootFolderPath); var rootFolder = GetItemById(GetNewItemId(rootFolderPath, typeof(AggregateFolder))) as AggregateFolder ?? (AggregateFolder)ResolvePath(_fileSystem.GetDirectoryInfo(rootFolderPath)); @@ -734,6 +743,13 @@ namespace MediaBrowser.Server.Implementations.Library folder = dbItem; } + if (folder.ParentId != rootFolder.Id) + { + folder.ParentId = rootFolder.Id; + var task = folder.UpdateToRepository(ItemUpdateType.MetadataImport, CancellationToken.None); + Task.WaitAll(task); + } + rootFolder.AddVirtualChild(folder); RegisterItem(folder); @@ -755,7 +771,7 @@ namespace MediaBrowser.Server.Implementations.Library { var userRootPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; - _fileSystem.CreateDirectory(userRootPath); + _fileSystem.CreateDirectory(userRootPath); var tmpItem = GetItemById(GetNewItemId(userRootPath, typeof(UserRootFolder))) as UserRootFolder; @@ -1007,9 +1023,9 @@ namespace MediaBrowser.Server.Implementations.Library private void SetPropertiesFromSongs(MusicArtist artist, IEnumerable<IHasMetadata> items) { - + } - + /// <summary> /// Validate and refresh the People sub-set of the IBN. /// The items are stored in the db but not loaded into memory until actually requested by an operation. @@ -1020,7 +1036,7 @@ namespace MediaBrowser.Server.Implementations.Library public Task ValidatePeople(CancellationToken cancellationToken, IProgress<double> progress) { // Ensure the location is available. - _fileSystem.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath); + _fileSystem.CreateDirectory(ConfigurationManager.ApplicationPaths.PeoplePath); return new PeopleValidator(this, _logger, ConfigurationManager, _fileSystem).ValidatePeople(cancellationToken, progress); } @@ -1267,6 +1283,11 @@ namespace MediaBrowser.Server.Implementations.Library public QueryResult<BaseItem> GetItems(InternalItemsQuery query) { + if (query.User != null) + { + AddUserToQuery(query, query.User); + } + var result = ItemRepository.GetItemIdsList(query); var items = result.Select(GetItemById).Where(i => i != null).ToArray(); @@ -1279,14 +1300,140 @@ namespace MediaBrowser.Server.Implementations.Library public QueryResult<BaseItem> QueryItems(InternalItemsQuery query) { + if (query.User != null) + { + AddUserToQuery(query, query.User); + } + return ItemRepository.GetItems(query); } public List<Guid> GetItemIds(InternalItemsQuery query) { + if (query.User != null) + { + AddUserToQuery(query, query.User); + } + return ItemRepository.GetItemIdsList(query); } + public IEnumerable<BaseItem> GetItems(InternalItemsQuery query, IEnumerable<string> parentIds) + { + var parents = parentIds.Select(i => GetItemById(new Guid(i))).Where(i => i != null).ToList(); + + SetTopParentIdsOrAncestors(query, parents); + + return GetItemIds(query).Select(GetItemById).Where(i => i != null); + } + + public QueryResult<BaseItem> GetItemsResult(InternalItemsQuery query, IEnumerable<string> parentIds) + { + var parents = parentIds.Select(i => GetItemById(new Guid(i))).Where(i => i != null).ToList(); + + SetTopParentIdsOrAncestors(query, parents); + + return GetItems(query); + } + + private void SetTopParentIdsOrAncestors(InternalItemsQuery query, List<BaseItem> parents) + { + if (parents.All(i => + { + if ((i is ICollectionFolder) || (i is UserView)) + { + return true; + } + + _logger.Debug("Query requires ancestor query due to type: " + i.GetType().Name); + return false; + + })) + { + // Optimize by querying against top level views + query.TopParentIds = parents.SelectMany(i => GetTopParentsForQuery(i, query.User)).Select(i => i.Id.ToString("N")).ToArray(); + } + else + { + // We need to be able to query from any arbitrary ancestor up the tree + query.AncestorIds = parents.SelectMany(i => i.GetIdsForAncestorQuery()).Select(i => i.ToString("N")).ToArray(); + } + } + + private void AddUserToQuery(InternalItemsQuery query, User user) + { + if (query.AncestorIds.Length == 0 && !query.ParentId.HasValue && query.ChannelIds.Length == 0 && query.TopParentIds.Length == 0) + { + var userViews = _userviewManager().GetUserViews(new UserViewQuery + { + UserId = user.Id.ToString("N"), + IncludeHidden = true + + }, CancellationToken.None).Result.ToList(); + + query.TopParentIds = userViews.SelectMany(i => GetTopParentsForQuery(i, user)).Select(i => i.Id.ToString("N")).ToArray(); + } + } + + private IEnumerable<BaseItem> GetTopParentsForQuery(BaseItem item, User user) + { + var view = item as UserView; + + if (view != null) + { + if (string.Equals(view.ViewType, CollectionType.LiveTv)) + { + return new[] { view }; + } + if (string.Equals(view.ViewType, CollectionType.Channels)) + { + // TODO: Return channels + return new[] { view }; + } + + // Translate view into folders + if (view.DisplayParentId != Guid.Empty) + { + var displayParent = GetItemById(view.DisplayParentId); + if (displayParent != null) + { + return GetTopParentsForQuery(displayParent, user); + } + return new BaseItem[] { }; + } + if (view.ParentId != Guid.Empty) + { + var displayParent = GetItemById(view.ParentId); + if (displayParent != null) + { + return GetTopParentsForQuery(displayParent, user); + } + return new BaseItem[] { }; + } + + // Handle grouping + if (user != null && !string.IsNullOrWhiteSpace(view.ViewType) && UserView.IsEligibleForGrouping(view.ViewType)) + { + var collectionFolders = user.RootFolder.GetChildren(user, true).OfType<CollectionFolder>().Where(i => string.IsNullOrWhiteSpace(i.CollectionType) || string.Equals(i.CollectionType, view.ViewType, StringComparison.OrdinalIgnoreCase)); + return collectionFolders.SelectMany(i => GetTopParentsForQuery(i, user)); + } + return new BaseItem[] { }; + } + + var collectionFolder = item as CollectionFolder; + if (collectionFolder != null) + { + return collectionFolder.GetPhysicalParents(); + } + + var topParent = item.GetTopParent(); + if (topParent != null) + { + return new[] { topParent }; + } + return new BaseItem[] { }; + } + /// <summary> /// Gets the intros. /// </summary> @@ -1389,6 +1536,10 @@ namespace MediaBrowser.Server.Implementations.Library { video = dbItem; } + else + { + return null; + } } } catch (Exception ex) @@ -1579,9 +1730,9 @@ namespace MediaBrowser.Server.Implementations.Library public IEnumerable<Folder> GetCollectionFolders(BaseItem item) { - while (!(item.Parent is AggregateFolder) && item.Parent != null) + while (!(item.GetParent() is AggregateFolder) && item.GetParent() != null) { - item = item.Parent; + item = item.GetParent(); } if (item == null) @@ -1618,7 +1769,7 @@ namespace MediaBrowser.Server.Implementations.Library return type; } - return item.Parents + return item.GetParents() .Select(GetConfiguredContentType) .LastOrDefault(i => !string.IsNullOrWhiteSpace(i)); } @@ -1655,14 +1806,14 @@ namespace MediaBrowser.Server.Implementations.Library private string GetTopFolderContentType(BaseItem item) { - while (!(item.Parent is AggregateFolder) && item.Parent != null) + if (item == null) { - item = item.Parent; + return null; } - if (item == null) + while (!(item.GetParent() is AggregateFolder) && item.GetParent() != null) { - return null; + item = item.GetParent(); } return GetUserRootFolder().Children @@ -1681,7 +1832,7 @@ namespace MediaBrowser.Server.Implementations.Library string sortName, CancellationToken cancellationToken) { - return GetNamedViewInternal(user, name, null, viewType, sortName, null, cancellationToken); + return GetNamedView(user, name, null, viewType, sortName, cancellationToken); } public async Task<UserView> GetNamedView(string name, @@ -1699,10 +1850,9 @@ namespace MediaBrowser.Server.Implementations.Library var refresh = false; - if (item == null || - !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase)) + if (item == null || !string.Equals(item.Path, path, StringComparison.OrdinalIgnoreCase)) { - _fileSystem.CreateDirectory(path); + _fileSystem.CreateDirectory(path); item = new UserView { @@ -1719,12 +1869,6 @@ namespace MediaBrowser.Server.Implementations.Library refresh = true; } - if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase)) - { - item.ViewType = viewType; - await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false); - } - if (!refresh) { refresh = (DateTime.UtcNow - item.DateLastRefreshed) >= _viewRefreshInterval; @@ -1750,40 +1894,14 @@ namespace MediaBrowser.Server.Implementations.Library return item; } - public Task<UserView> GetNamedView(User user, - string name, - string parentId, - string viewType, - string sortName, - string uniqueId, - CancellationToken cancellationToken) - { - if (string.IsNullOrWhiteSpace(parentId)) - { - throw new ArgumentNullException("parentId"); - } - - return GetNamedViewInternal(user, name, parentId, viewType, sortName, uniqueId, cancellationToken); - } - - private async Task<UserView> GetNamedViewInternal(User user, + public async Task<UserView> GetNamedView(User user, string name, string parentId, string viewType, string sortName, - string uniqueId, CancellationToken cancellationToken) { - if (string.IsNullOrWhiteSpace(name)) - { - throw new ArgumentNullException("name"); - } - - var idValues = "37_namedview_" + name + user.Id.ToString("N") + (parentId ?? string.Empty); - if (!string.IsNullOrWhiteSpace(uniqueId)) - { - idValues += uniqueId; - } + var idValues = "38_namedview_" + name + user.Id.ToString("N") + (parentId ?? string.Empty) + (viewType ?? string.Empty); var id = GetNewItemId(idValues, typeof(UserView)); @@ -1795,7 +1913,7 @@ namespace MediaBrowser.Server.Implementations.Library if (item == null) { - _fileSystem.CreateDirectory(path); + _fileSystem.CreateDirectory(path); item = new UserView { @@ -1818,18 +1936,6 @@ namespace MediaBrowser.Server.Implementations.Library isNew = true; } - if (!item.UserId.HasValue) - { - item.UserId = user.Id; - await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false); - } - - if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase)) - { - item.ViewType = viewType; - await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false); - } - var refresh = isNew || (DateTime.UtcNow - item.DateLastRefreshed) >= _viewRefreshInterval; if (!refresh && item.DisplayParentId != Guid.Empty) @@ -1853,7 +1959,6 @@ namespace MediaBrowser.Server.Implementations.Library public async Task<UserView> GetShadowView(BaseItem parent, string viewType, string sortName, - string uniqueId, CancellationToken cancellationToken) { if (parent == null) @@ -1864,11 +1969,7 @@ namespace MediaBrowser.Server.Implementations.Library var name = parent.Name; var parentId = parent.Id; - var idValues = "37_namedview_" + name + parentId + (viewType ?? string.Empty); - if (!string.IsNullOrWhiteSpace(uniqueId)) - { - idValues += uniqueId; - } + var idValues = "38_namedview_" + name + parentId + (viewType ?? string.Empty); var id = GetNewItemId(idValues, typeof(UserView)); @@ -1899,12 +2000,6 @@ namespace MediaBrowser.Server.Implementations.Library isNew = true; } - if (!string.Equals(viewType, item.ViewType, StringComparison.OrdinalIgnoreCase)) - { - item.ViewType = viewType; - await item.UpdateToRepository(ItemUpdateType.MetadataEdit, cancellationToken).ConfigureAwait(false); - } - var refresh = isNew || (DateTime.UtcNow - item.DateLastRefreshed) >= _viewRefreshInterval; if (!refresh && item.DisplayParentId != Guid.Empty) @@ -1924,7 +2019,7 @@ namespace MediaBrowser.Server.Implementations.Library return item; } - + public async Task<UserView> GetNamedView(string name, string parentId, string viewType, @@ -1953,7 +2048,7 @@ namespace MediaBrowser.Server.Implementations.Library if (item == null) { - _fileSystem.CreateDirectory(path); + _fileSystem.CreateDirectory(path); item = new UserView { @@ -2200,21 +2295,21 @@ namespace MediaBrowser.Server.Implementations.Library return ResolvePaths(files, directoryService, null, null) .OfType<Video>() .Select(video => - { - // Try to retrieve it from the db. If we don't find it, use the resolved version - var dbItem = GetItemById(video.Id) as Video; - - if (dbItem != null) { - video = dbItem; - } + // Try to retrieve it from the db. If we don't find it, use the resolved version + var dbItem = GetItemById(video.Id) as Video; - video.ExtraType = ExtraType.Trailer; + if (dbItem != null) + { + video = dbItem; + } - return video; + video.ExtraType = ExtraType.Trailer; - // Sort them so that the list can be easily compared for changes - }).OrderBy(i => i.Path).ToList(); + return video; + + // Sort them so that the list can be easily compared for changes + }).OrderBy(i => i.Path).ToList(); } public IEnumerable<Video> FindExtras(BaseItem owner, List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService) @@ -2386,7 +2481,7 @@ namespace MediaBrowser.Server.Implementations.Library return ItemRepository.UpdatePeople(item.Id, people); } - private readonly SemaphoreSlim _dynamicImageResourcePool = new SemaphoreSlim(1,1); + private readonly SemaphoreSlim _dynamicImageResourcePool = new SemaphoreSlim(1, 1); public async Task<ItemImageInfo> ConvertImageToLocal(IHasImages item, ItemImageInfo image, int imageIndex) { foreach (var url in image.Path.Split('|')) @@ -2425,4 +2520,4 @@ namespace MediaBrowser.Server.Implementations.Library throw new InvalidOperationException(); } } -} +}
\ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/Library/MusicManager.cs b/MediaBrowser.Server.Implementations/Library/MusicManager.cs index aee101ef4..11a1f190a 100644 --- a/MediaBrowser.Server.Implementations/Library/MusicManager.cs +++ b/MediaBrowser.Server.Implementations/Library/MusicManager.cs @@ -80,15 +80,13 @@ namespace MediaBrowser.Server.Implementations.Library { var genreList = genres.ToList(); - var inputItems = _libraryManager.GetItems(new InternalItemsQuery + var inputItems = _libraryManager.GetItems(new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(Audio).Name }, - Genres = genreList.ToArray(), + Genres = genreList.ToArray() - User = user - - }).Items; + }, new string[] { }); var genresDictionary = genreList.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase); diff --git a/MediaBrowser.Server.Implementations/Library/ResolverHelper.cs b/MediaBrowser.Server.Implementations/Library/ResolverHelper.cs index 4efa1071d..83fdd3da2 100644 --- a/MediaBrowser.Server.Implementations/Library/ResolverHelper.cs +++ b/MediaBrowser.Server.Implementations/Library/ResolverHelper.cs @@ -41,7 +41,7 @@ namespace MediaBrowser.Server.Implementations.Library item.Id = libraryManager.GetNewItemId(item.Path, item.GetType()); item.IsLocked = item.Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1 || - item.Parents.Any(i => i.IsLocked); + item.GetParents().Any(i => i.IsLocked); // Make sure DateCreated and DateModified have values var fileInfo = directoryService.GetFile(item.Path); @@ -78,7 +78,7 @@ namespace MediaBrowser.Server.Implementations.Library EnsureName(item, args.FileInfo); item.IsLocked = item.Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1 || - item.Parents.Any(i => i.IsLocked); + item.GetParents().Any(i => i.IsLocked); // Make sure DateCreated and DateModified have values EnsureDates(fileSystem, item, args, true); diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index fd74b68b8..9edd3f83f 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -191,6 +191,23 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers video.IsHD = true; } } + + SetIsoType(video); + } + + protected void SetIsoType(Video video) + { + if (video.VideoType == VideoType.Iso) + { + if (video.Path.IndexOf("dvd", StringComparison.OrdinalIgnoreCase) != -1) + { + video.IsoType = IsoType.Dvd; + } + else if (video.Path.IndexOf("bluray", StringComparison.OrdinalIgnoreCase) != -1) + { + video.IsoType = IsoType.BluRay; + } + } } protected void Set3DFormat(Video video, bool is3D, string format3D) @@ -225,6 +242,10 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers { video.Video3DFormat = Video3DFormat.HalfTopAndBottom; } + else if (string.Equals(format3D, "mvc", StringComparison.OrdinalIgnoreCase)) + { + video.Video3DFormat = Video3DFormat.MVC; + } } } diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 3252db505..23424bf3c 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -67,7 +67,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies string collectionType, IDirectoryService directoryService) { - if (IsInvalid(parent, collectionType, files)) + if (IsInvalid(parent, collectionType)) { return null; } @@ -77,16 +77,12 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies return ResolveVideos<MusicVideo>(parent, files, directoryService, false); } - if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) || + string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase)) { return ResolveVideos<Video>(parent, files, directoryService, false); } - if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase)) - { - //return ResolveVideos<Video>(parent, files, directoryService, collectionType, false); - } - if (string.IsNullOrEmpty(collectionType)) { // Owned items should just use the plain video type @@ -95,7 +91,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies return ResolveVideos<Video>(parent, files, directoryService, false); } - if (parent is Series || parent.Parents.OfType<Series>().Any()) + if (parent is Series || parent.GetParents().OfType<Series>().Any()) { return null; } @@ -185,7 +181,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies { var collectionType = args.GetCollectionType(); - if (IsInvalid(args.Parent, collectionType, args.FileSystemChildren)) + if (IsInvalid(args.Parent, collectionType)) { return null; } @@ -193,14 +189,18 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies // Find movies with their own folders if (args.IsDirectory) { + var files = args.FileSystemChildren + .Where(i => !LibraryManager.IgnoreFile(i, args.Parent)) + .ToList(); + if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase)) { - return FindMovie<MusicVideo>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); + return FindMovie<MusicVideo>(args.Path, args.Parent, files, args.DirectoryService, collectionType); } if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase)) { - return FindMovie<Video>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); + return FindMovie<Video>(args.Path, args.Parent, files, args.DirectoryService, collectionType); } if (string.IsNullOrEmpty(collectionType)) @@ -208,7 +208,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies // Owned items should just use the plain video type if (args.Parent == null) { - return FindMovie<Video>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); + return FindMovie<Video>(args.Path, args.Parent, files, args.DirectoryService, collectionType); } if (args.HasParent<Series>()) @@ -216,12 +216,12 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies return null; } - return FindMovie<Movie>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); + return FindMovie<Movie>(args.Path, args.Parent, files, args.DirectoryService, collectionType); } if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase)) { - return FindMovie<Movie>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); + return FindMovie<Movie>(args.Path, args.Parent, files, args.DirectoryService, collectionType); } return null; @@ -246,11 +246,8 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies item = ResolveVideo<Movie>(args, true); } - else if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase)) - { - item = ResolveVideo<Video>(args, false); - } - else if (string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase) || + string.Equals(collectionType, CollectionType.Photos, StringComparison.OrdinalIgnoreCase)) { item = ResolveVideo<Video>(args, false); } @@ -482,7 +479,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies return null; } - return new T + var returnVideo = new T { Path = folderPaths[0], @@ -492,9 +489,13 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies Name = result.Stacks[0].Name }; + + SetIsoType(returnVideo); + + return returnVideo; } - private bool IsInvalid(Folder parent, string collectionType, IEnumerable<FileSystemMetadata> files) + private bool IsInvalid(Folder parent, string collectionType) { if (parent != null) { diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs index 1a873f01e..e62049821 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs @@ -33,7 +33,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV // Not officially supported but in some cases we can handle it. if (season == null) { - season = parent.Parents.OfType<Season>().FirstOrDefault(); + season = parent.GetParents().OfType<Season>().FirstOrDefault(); } // If the parent is a Season or Series, then this is an Episode if the VideoResolver returns something diff --git a/MediaBrowser.Server.Implementations/Library/SearchEngine.cs b/MediaBrowser.Server.Implementations/Library/SearchEngine.cs index d6aff1192..62392c1c7 100644 --- a/MediaBrowser.Server.Implementations/Library/SearchEngine.cs +++ b/MediaBrowser.Server.Implementations/Library/SearchEngine.cs @@ -156,19 +156,19 @@ namespace MediaBrowser.Server.Implementations.Library } AddIfMissing(excludeItemTypes, typeof(CollectionFolder).Name); - - var mediaItems = _libraryManager.GetItems(new InternalItemsQuery + + var mediaItems = _libraryManager.GetItems(new InternalItemsQuery(user) { NameContains = searchTerm, ExcludeItemTypes = excludeItemTypes.ToArray(), IncludeItemTypes = includeItemTypes.ToArray(), - MaxParentalRating = user == null ? null : user.Policy.MaxParentalRating, - Limit = (query.Limit.HasValue ? (int?)(query.Limit.Value * 3) : null), + Limit = query.Limit, + IncludeItemsByName = true - }).Items; + }, new string[] { }); // Add search hints based on item name - hints.AddRange(mediaItems.Where(i => IncludeInSearch(i) && IsVisible(i, user)).Select(item => + hints.AddRange(mediaItems.Where(IncludeInSearch).Select(item => { var index = GetIndex(item.Name, searchTerm, terms); @@ -184,25 +184,6 @@ namespace MediaBrowser.Server.Implementations.Library return Task.FromResult(returnValue); } - private bool IsVisible(BaseItem item, User user) - { - if (user == null) - { - return true; - } - - if (item is IItemByName) - { - var dual = item as IHasDualAccess; - if (dual == null || dual.IsAccessedByName) - { - return true; - } - } - - return item.IsVisibleStandalone(user); - } - private bool IncludeInSearch(BaseItem item) { var episode = item as Episode; diff --git a/MediaBrowser.Server.Implementations/Library/UserManager.cs b/MediaBrowser.Server.Implementations/Library/UserManager.cs index cf1853c5e..0d588b97b 100644 --- a/MediaBrowser.Server.Implementations/Library/UserManager.cs +++ b/MediaBrowser.Server.Implementations/Library/UserManager.cs @@ -704,8 +704,7 @@ namespace MediaBrowser.Server.Implementations.Library Id = Guid.NewGuid(), DateCreated = DateTime.UtcNow, DateModified = DateTime.UtcNow, - UsesIdForConfigurationPath = true, - EnableUserViews = true + UsesIdForConfigurationPath = true }; } diff --git a/MediaBrowser.Server.Implementations/Library/UserViewManager.cs b/MediaBrowser.Server.Implementations/Library/UserViewManager.cs index 0df4742bd..a375dde31 100644 --- a/MediaBrowser.Server.Implementations/Library/UserViewManager.cs +++ b/MediaBrowser.Server.Implementations/Library/UserViewManager.cs @@ -16,6 +16,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Controller.Entities.Audio; namespace MediaBrowser.Server.Implementations.Library { @@ -48,103 +49,63 @@ namespace MediaBrowser.Server.Implementations.Library .OfType<Folder>() .ToList(); - var plainFolderIds = user.Configuration.PlainFolderViews.Select(i => new Guid(i)).ToList(); + if (!query.IncludeHidden) + { + folders = folders.Where(i => + { + var hidden = i as IHiddenFromDisplay; + return hidden == null || !hidden.IsHiddenFromUser(user); + }).ToList(); + } - var standaloneFolders = folders - .Where(i => UserView.IsExcludedFromGrouping(i) || !user.IsFolderGrouped(i.Id)) - .ToList(); + var plainFolderIds = user.Configuration.PlainFolderViews.Select(i => new Guid(i)).ToList(); - var foldersWithViewTypes = folders - .Except(standaloneFolders) - .OfType<ICollectionFolder>() - .ToList(); + var groupedFolders = new List<ICollectionFolder>(); var list = new List<Folder>(); - var enableUserViews = _config.Configuration.EnableUserViews || user.EnableUserViews; - - if (enableUserViews) + foreach (var folder in folders) { - foreach (var folder in standaloneFolders) + var collectionFolder = folder as ICollectionFolder; + var folderViewType = collectionFolder == null ? null : collectionFolder.CollectionType; + + if (UserView.IsUserSpecific(folder)) { - var collectionFolder = folder as ICollectionFolder; - var folderViewType = collectionFolder == null ? null : collectionFolder.CollectionType; + list.Add(await _libraryManager.GetNamedView(user, folder.Name, folder.Id.ToString("N"), folderViewType, null, cancellationToken).ConfigureAwait(false)); + continue; + } - if (UserView.IsUserSpecific(folder)) - { - list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, true, string.Empty, user, cancellationToken).ConfigureAwait(false)); - } - else if (plainFolderIds.Contains(folder.Id)) - { - list.Add(await GetUserView(folder, folderViewType, false, string.Empty, cancellationToken).ConfigureAwait(false)); - } - else if (!string.IsNullOrWhiteSpace(folderViewType)) - { - list.Add(await GetUserView(folder, folderViewType, true, string.Empty, cancellationToken).ConfigureAwait(false)); - } - else - { - list.Add(folder); - } + if (plainFolderIds.Contains(folder.Id) && UserView.IsEligibleForEnhancedView(folderViewType)) + { + list.Add(folder); + continue; } - } - else - { - // TODO: Deprecate this whole block - foreach (var folder in standaloneFolders) + + if (collectionFolder != null && UserView.IsEligibleForGrouping(folder) && user.IsFolderGrouped(folder.Id)) { - var collectionFolder = folder as ICollectionFolder; - var folderViewType = collectionFolder == null ? null : collectionFolder.CollectionType; - - if (UserView.IsUserSpecific(folder)) - { - list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, true, string.Empty, user, cancellationToken).ConfigureAwait(false)); - } - else if (plainFolderIds.Contains(folder.Id)) - { - list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, false, string.Empty, user, cancellationToken).ConfigureAwait(false)); - } - else if (!string.IsNullOrWhiteSpace(folderViewType)) - { - list.Add(await GetUserView(folder.Id, folder.Name, folderViewType, true, string.Empty, user, cancellationToken).ConfigureAwait(false)); - } - else - { - list.Add(folder); - } + groupedFolders.Add(collectionFolder); + continue; } - } - - var parents = foldersWithViewTypes.Where(i => string.Equals(i.GetViewType(user), CollectionType.TvShows, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(i.GetViewType(user))) - .ToList(); - - if (parents.Count > 0) - { - list.Add(await GetUserView(parents, list, CollectionType.TvShows, string.Empty, user, enableUserViews, cancellationToken).ConfigureAwait(false)); - } - - parents = foldersWithViewTypes.Where(i => string.Equals(i.GetViewType(user), CollectionType.Music, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(i.GetViewType(user))) - .ToList(); - if (parents.Count > 0) - { - list.Add(await GetUserView(parents, list, CollectionType.Music, string.Empty, user, enableUserViews, cancellationToken).ConfigureAwait(false)); + if (query.PresetViews.Contains(folderViewType ?? string.Empty, StringComparer.OrdinalIgnoreCase)) + { + list.Add(await GetUserView(folder, folderViewType, string.Empty, cancellationToken).ConfigureAwait(false)); + } + else + { + list.Add(folder); + } } - parents = foldersWithViewTypes.Where(i => string.Equals(i.GetViewType(user), CollectionType.Movies, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(i.GetViewType(user))) - .ToList(); - - if (parents.Count > 0) + foreach (var viewType in new[] { CollectionType.Movies, CollectionType.TvShows }) { - list.Add(await GetUserView(parents, list, CollectionType.Movies, string.Empty, user, enableUserViews, cancellationToken).ConfigureAwait(false)); - } - - parents = foldersWithViewTypes.Where(i => string.Equals(i.GetViewType(user), CollectionType.Games, StringComparison.OrdinalIgnoreCase)) - .ToList(); + var parents = groupedFolders.Where(i => string.Equals(i.CollectionType, viewType, StringComparison.OrdinalIgnoreCase) || string.IsNullOrWhiteSpace(i.CollectionType)) + .ToList(); - if (parents.Count > 0) - { - list.Add(await GetUserView(parents, list, CollectionType.Games, string.Empty, user, enableUserViews, cancellationToken).ConfigureAwait(false)); + if (parents.Count > 0) + { + list.Add(await GetUserView(parents, viewType, string.Empty, user, query.PresetViews, cancellationToken).ConfigureAwait(false)); + } } if (user.Configuration.DisplayFoldersView) @@ -187,6 +148,18 @@ namespace MediaBrowser.Server.Implementations.Library { var index = orders.IndexOf(i.Id.ToString("N")); + if (index == -1) + { + var view = i as UserView; + if (view != null) + { + if (view.DisplayParentId != Guid.Empty) + { + index = orders.IndexOf(view.DisplayParentId.ToString("N")); + } + } + } + return index == -1 ? int.MaxValue : index; }) .ThenBy(sorted.IndexOf) @@ -207,32 +180,25 @@ namespace MediaBrowser.Server.Implementations.Library return GetUserSubView(name, parentId, type, sortName, cancellationToken); } - private async Task<UserView> GetUserView(List<ICollectionFolder> parents, List<Folder> currentViews, string viewType, string sortName, User user, bool enableUserViews, CancellationToken cancellationToken) + private async Task<Folder> GetUserView(List<ICollectionFolder> parents, string viewType, string sortName, User user, string[] presetViews, CancellationToken cancellationToken) { - if (parents.Count == 1 && parents.All(i => string.Equals((enableUserViews ? i.GetViewType(user) : i.CollectionType), viewType, StringComparison.OrdinalIgnoreCase))) + if (parents.Count == 1 && parents.All(i => string.Equals(i.CollectionType, viewType, StringComparison.OrdinalIgnoreCase))) { - var parentId = parents[0].Id; - - var enableRichView = !user.Configuration.PlainFolderViews.Contains(parentId.ToString("N"), StringComparer.OrdinalIgnoreCase); + if (!presetViews.Contains(viewType, StringComparer.OrdinalIgnoreCase)) + { + return (Folder)parents[0]; + } - return await GetUserView((Folder)parents[0], viewType, enableRichView, string.Empty, cancellationToken).ConfigureAwait(false); + return await GetUserView((Folder)parents[0], viewType, string.Empty, cancellationToken).ConfigureAwait(false); } var name = _localizationManager.GetLocalizedString("ViewType" + viewType); return await _libraryManager.GetNamedView(user, name, viewType, sortName, cancellationToken).ConfigureAwait(false); } - public Task<UserView> GetUserView(Guid parentId, string name, string viewType, bool enableRichView, string sortName, User user, CancellationToken cancellationToken) - { - viewType = enableRichView ? viewType : null; - return _libraryManager.GetNamedView(user, name, parentId.ToString("N"), viewType, sortName, null, cancellationToken); - } - - public Task<UserView> GetUserView(Folder parent, string viewType, bool enableRichView, string sortName, CancellationToken cancellationToken) + public Task<UserView> GetUserView(Folder parent, string viewType, string sortName, CancellationToken cancellationToken) { - viewType = enableRichView ? viewType : null; - - return _libraryManager.GetShadowView(parent, viewType, sortName, null, cancellationToken); + return _libraryManager.GetShadowView(parent, viewType, sortName, cancellationToken); } public List<Tuple<BaseItem, List<BaseItem>>> GetLatestItems(LatestItemsQuery request) @@ -243,16 +209,8 @@ namespace MediaBrowser.Server.Implementations.Library var currentUser = user; - Func<BaseItem, bool> filter = i => + var libraryItems = GetItemsForLatestItems(user, request.ParentId, includeTypes, request.Limit ?? 10).Where(i => { - if (includeTypes.Length > 0) - { - if (!includeTypes.Contains(i.GetType().Name, StringComparer.OrdinalIgnoreCase)) - { - return false; - } - } - if (request.IsPlayed.HasValue) { var val = request.IsPlayed.Value; @@ -262,29 +220,12 @@ namespace MediaBrowser.Server.Implementations.Library } } - return i.LocationType != LocationType.Virtual && !i.IsFolder; - }; - - // Avoid implicitly captured closure - var libraryItems = string.IsNullOrEmpty(request.ParentId) && user != null ? - GetItemsConfiguredForLatest(user, filter) : - GetAllLibraryItems(request.UserId, _userManager, _libraryManager, request.ParentId, filter); - - libraryItems = libraryItems.OrderByDescending(i => i.DateCreated); - - if (request.IsPlayed.HasValue) - { - var takeLimit = (request.Limit ?? 20) * 20; - libraryItems = libraryItems.Take(takeLimit); - } - - // Avoid implicitly captured closure - var items = libraryItems - .ToList(); + return true; + }); var list = new List<Tuple<BaseItem, List<BaseItem>>>(); - foreach (var item in items) + foreach (var item in libraryItems) { // Only grab the index container for media var container = item.IsFolder || !request.GroupItems ? null : item.LatestItemsIndexContainer; @@ -316,59 +257,34 @@ namespace MediaBrowser.Server.Implementations.Library return list; } - protected IList<BaseItem> GetAllLibraryItems(string userId, IUserManager userManager, ILibraryManager libraryManager, string parentId, Func<BaseItem, bool> filter) + private IEnumerable<BaseItem> GetItemsForLatestItems(User user, string parentId, string[] includeItemTypes, int limit) { - if (!string.IsNullOrEmpty(parentId)) - { - var folder = (Folder)libraryManager.GetItemById(new Guid(parentId)); - - if (!string.IsNullOrWhiteSpace(userId)) - { - var user = userManager.GetUserById(userId); - - if (user == null) - { - throw new ArgumentException("User not found"); - } - - return folder - .GetRecursiveChildren(user, filter) - .ToList(); - } + var parentIds = string.IsNullOrEmpty(parentId) + ? new string[] { } + : new[] { parentId }; - return folder - .GetRecursiveChildren(filter); - } - if (!string.IsNullOrWhiteSpace(userId)) + if (parentIds.Length == 0) { - var user = userManager.GetUserById(userId); - - if (user == null) - { - throw new ArgumentException("User not found"); - } - - return user - .RootFolder - .GetRecursiveChildren(user, filter) - .ToList(); + parentIds = user.RootFolder.GetChildren(user, true) + .OfType<Folder>() + .Select(i => i.Id.ToString("N")) + .Where(i => !user.Configuration.LatestItemsExcludes.Contains(i)) + .ToArray(); } - return libraryManager - .RootFolder - .GetRecursiveChildren(filter); - } - - private IEnumerable<BaseItem> GetItemsConfiguredForLatest(User user, Func<BaseItem, bool> filter) - { - // Avoid implicitly captured closure - var currentUser = user; + var excludeItemTypes = includeItemTypes.Length == 0 ? new[] { "ChannelItem", "LiveTvItem", typeof(Person).Name, typeof(Studio).Name, typeof(Year).Name, typeof(GameGenre).Name, typeof(MusicGenre).Name, typeof(Genre).Name } : new string[] { }; - return user.RootFolder.GetChildren(user, true) - .OfType<Folder>() - .Where(i => !user.Configuration.LatestItemsExcludes.Contains(i.Id.ToString("N"))) - .SelectMany(i => i.GetRecursiveChildren(currentUser, filter)) - .DistinctBy(i => i.Id); + return _libraryManager.GetItems(new InternalItemsQuery(user) + { + IncludeItemTypes = includeItemTypes, + SortOrder = SortOrder.Descending, + SortBy = new[] { ItemSortBy.DateCreated }, + IsFolder = includeItemTypes.Length == 0 ? false : (bool?)null, + ExcludeItemTypes = excludeItemTypes, + ExcludeLocationTypes = new[] { LocationType.Virtual }, + Limit = limit * 20 + + }, parentIds); } } } diff --git a/MediaBrowser.Server.Implementations/Library/Validators/PeopleValidator.cs b/MediaBrowser.Server.Implementations/Library/Validators/PeopleValidator.cs index 26cde925e..2161c1454 100644 --- a/MediaBrowser.Server.Implementations/Library/Validators/PeopleValidator.cs +++ b/MediaBrowser.Server.Implementations/Library/Validators/PeopleValidator.cs @@ -165,11 +165,14 @@ namespace MediaBrowser.Server.Implementations.Library.Validators var item = _libraryManager.GetItemById(id); - await _libraryManager.DeleteItem(item, new DeleteOptions + if (item != null) { - DeleteFileLocation = false + await _libraryManager.DeleteItem(item, new DeleteOptions + { + DeleteFileLocation = false - }).ConfigureAwait(false); + }).ConfigureAwait(false); + } } progress.Report(100); diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs new file mode 100644 index 000000000..9ac96165f --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/DirectRecorder.cs @@ -0,0 +1,50 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using CommonIO; +using MediaBrowser.Common.IO; +using MediaBrowser.Common.Net; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Logging; + +namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV +{ + public class DirectRecorder : IRecorder + { + private readonly ILogger _logger; + private readonly IHttpClient _httpClient; + private readonly IFileSystem _fileSystem; + + public DirectRecorder(ILogger logger, IHttpClient httpClient, IFileSystem fileSystem) + { + _logger = logger; + _httpClient = httpClient; + _fileSystem = fileSystem; + } + + public async Task Record(MediaSourceInfo mediaSource, string targetFile, Action onStarted, CancellationToken cancellationToken) + { + var httpRequestOptions = new HttpRequestOptions() + { + Url = mediaSource.Path + }; + + httpRequestOptions.BufferContent = false; + + using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET").ConfigureAwait(false)) + { + _logger.Info("Opened recording stream from tuner provider"); + + using (var output = _fileSystem.GetFileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Read)) + { + onStarted(); + + _logger.Info("Copying recording stream to file stream"); + + await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, cancellationToken).ConfigureAwait(false); + } + } + } + } +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index cd91684ce..9e4cb66a8 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -171,7 +171,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { epgData = GetEpgDataForChannel(timer.ChannelId); } - await UpdateTimersForSeriesTimer(epgData, timer, false).ConfigureAwait(false); + await UpdateTimersForSeriesTimer(epgData, timer, true).ConfigureAwait(false); } var timers = await GetTimersAsync(cancellationToken).ConfigureAwait(false); @@ -664,12 +664,22 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV throw new ArgumentNullException("timer"); } + ProgramInfo info = null; + if (string.IsNullOrWhiteSpace(timer.ProgramId)) { - throw new InvalidOperationException("timer.ProgramId is null. Cannot record."); + _logger.Info("Timer {0} has null programId", timer.Id); + } + else + { + info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId); } - var info = GetProgramInfoFromCache(timer.ChannelId, timer.ProgramId); + if (info == null) + { + _logger.Info("Unable to find program with Id {0}. Will search using start date", timer.ProgramId); + info = GetProgramInfoFromCache(timer.ChannelId, timer.StartDate); + } if (info == null) { @@ -742,7 +752,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV try { - var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None); + var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None).ConfigureAwait(false); var mediaStreamInfo = result.Item1; var isResourceOpen = true; @@ -754,10 +764,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV var duration = recordingEndDate - DateTime.UtcNow; - HttpRequestOptions httpRequestOptions = new HttpRequestOptions() + var recorder = await GetRecorder().ConfigureAwait(false); + + if (recorder is EncodedRecorder) { - Url = mediaStreamInfo.Path - }; + recordPath = Path.ChangeExtension(recordPath, ".mp4"); + } recording.Path = recordPath; recording.Status = RecordingStatus.InProgress; @@ -766,21 +778,19 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); - httpRequestOptions.BufferContent = false; var durationToken = new CancellationTokenSource(duration); var linkedToken = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, durationToken.Token).Token; - httpRequestOptions.CancellationToken = linkedToken; + _logger.Info("Writing file to path: " + recordPath); - using (var response = await _httpClient.SendAsync(httpRequestOptions, "GET")) + _logger.Info("Opening recording stream from tuner provider"); + + Action onStarted = () => { - using (var output = _fileSystem.GetFileStream(recordPath, FileMode.Create, FileAccess.Write, FileShare.Read)) - { - result.Item2.Release(); - isResourceOpen = false; + result.Item2.Release(); + isResourceOpen = false; + }; - await response.Content.CopyToAsync(output, StreamDefaults.DefaultCopyToBufferSize, linkedToken); - } - } + await recorder.Record(mediaStreamInfo, recordPath, onStarted, linkedToken).ConfigureAwait(false); recording.Status = RecordingStatus.Completed; _logger.Info("Recording completed"); @@ -831,6 +841,21 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV } } + private async Task<IRecorder> GetRecorder() + { + if (GetConfiguration().EnableRecordingEncoding) + { + var regInfo = await _security.GetRegistrationStatus("embytvrecordingconversion").ConfigureAwait(false); + + if (regInfo.IsValid) + { + return new EncodedRecorder(_logger, _fileSystem, _mediaEncoder, _config.ApplicationPaths, _jsonSerializer); + } + } + + return new DirectRecorder(_logger, _httpClient, _fileSystem); + } + private async void OnSuccessfulRecording(RecordingInfo recording) { if (GetConfiguration().EnableAutoOrganize) @@ -862,6 +887,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV return epgData.FirstOrDefault(p => string.Equals(p.Id, programId, StringComparison.OrdinalIgnoreCase)); } + private ProgramInfo GetProgramInfoFromCache(string channelId, DateTime startDateUtc) + { + var epgData = GetEpgDataForChannel(channelId); + var startDateTicks = startDateUtc.Ticks; + // Find the first program that starts within 3 minutes + return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks); + } + private string RecordingPath { get diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs new file mode 100644 index 000000000..b4ff79567 --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EncodedRecorder.cs @@ -0,0 +1,255 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using CommonIO; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Controller.MediaEncoding; +using MediaBrowser.Model.Dto; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Logging; +using MediaBrowser.Model.Serialization; + +namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV +{ + public class EncodedRecorder : IRecorder + { + private readonly ILogger _logger; + private readonly IFileSystem _fileSystem; + private readonly IMediaEncoder _mediaEncoder; + private readonly IApplicationPaths _appPaths; + private bool _hasExited; + private Stream _logFileStream; + private string _targetPath; + private Process _process; + private readonly IJsonSerializer _json; + + public EncodedRecorder(ILogger logger, IFileSystem fileSystem, IMediaEncoder mediaEncoder, IApplicationPaths appPaths, IJsonSerializer json) + { + _logger = logger; + _fileSystem = fileSystem; + _mediaEncoder = mediaEncoder; + _appPaths = appPaths; + _json = json; + } + + public async Task Record(MediaSourceInfo mediaSource, string targetFile, Action onStarted, CancellationToken cancellationToken) + { + _targetPath = targetFile; + _fileSystem.CreateDirectory(Path.GetDirectoryName(targetFile)); + + var process = new Process + { + StartInfo = new ProcessStartInfo + { + CreateNoWindow = true, + UseShellExecute = false, + + // Must consume both stdout and stderr or deadlocks may occur + RedirectStandardOutput = true, + RedirectStandardError = true, + RedirectStandardInput = true, + + FileName = _mediaEncoder.EncoderPath, + Arguments = GetCommandLineArgs(mediaSource, targetFile), + + WindowStyle = ProcessWindowStyle.Hidden, + ErrorDialog = false + }, + + EnableRaisingEvents = true + }; + + _process = process; + + var commandLineLogMessage = process.StartInfo.FileName + " " + process.StartInfo.Arguments; + _logger.Info(commandLineLogMessage); + + var logFilePath = Path.Combine(_appPaths.LogDirectoryPath, "record-transcode-" + Guid.NewGuid() + ".txt"); + _fileSystem.CreateDirectory(Path.GetDirectoryName(logFilePath)); + + // FFMpeg writes debug/error info to stderr. This is useful when debugging so let's put it in the log directory. + _logFileStream = _fileSystem.GetFileStream(logFilePath, FileMode.Create, FileAccess.Write, FileShare.Read, true); + + var commandLineLogMessageBytes = Encoding.UTF8.GetBytes(_json.SerializeToString(mediaSource) + Environment.NewLine + Environment.NewLine + commandLineLogMessage + Environment.NewLine + Environment.NewLine); + await _logFileStream.WriteAsync(commandLineLogMessageBytes, 0, commandLineLogMessageBytes.Length, cancellationToken).ConfigureAwait(false); + + process.Exited += (sender, args) => OnFfMpegProcessExited(process); + + process.Start(); + + cancellationToken.Register(Stop); + + // MUST read both stdout and stderr asynchronously or a deadlock may occurr + process.BeginOutputReadLine(); + + // Important - don't await the log task or we won't be able to kill ffmpeg when the user stops playback + StartStreamingLog(process.StandardError.BaseStream, _logFileStream); + + // Wait for the file to exist before proceeeding + while (!_hasExited) + { + await Task.Delay(100, cancellationToken).ConfigureAwait(false); + } + } + + private string GetCommandLineArgs(MediaSourceInfo mediaSource, string targetFile) + { + string videoArgs; + if (EncodeVideo(mediaSource)) + { + var maxBitrate = 25000000; + videoArgs = string.Format( + "-codec:v:0 libx264 -force_key_frames expr:gte(t,n_forced*5) {0} -pix_fmt yuv420p -preset superfast -crf 23 -b:v {1} -maxrate {1} -bufsize ({1}*2) -vsync vfr -profile:v high -level 41", + GetOutputSizeParam(), + maxBitrate.ToString(CultureInfo.InvariantCulture)); + } + else + { + videoArgs = "-codec:v:0 copy"; + } + + var commandLineArgs = "-fflags +genpts -i \"{0}\" -sn {2} -map_metadata -1 -threads 0 {3} -y \"{1}\""; + + if (mediaSource.ReadAtNativeFramerate) + { + commandLineArgs = "-re " + commandLineArgs; + } + + commandLineArgs = string.Format(commandLineArgs, mediaSource.Path, targetFile, videoArgs, GetAudioArgs(mediaSource)); + + return commandLineArgs; + } + + private string GetAudioArgs(MediaSourceInfo mediaSource) + { + var copyAudio = new[] { "aac", "mp3" }; + var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>(); + if (mediaStreams.Any(i => i.Type == MediaStreamType.Audio && copyAudio.Contains(i.Codec, StringComparer.OrdinalIgnoreCase))) + { + return "-codec:a:0 copy"; + } + + var audioChannels = 2; + var audioStream = mediaStreams.FirstOrDefault(i => i.Type == MediaStreamType.Audio); + if (audioStream != null) + { + audioChannels = audioStream.Channels ?? audioChannels; + } + return "-codec:a:0 aac -strict experimental -ab 320000 -ac " + audioChannels.ToString(CultureInfo.InvariantCulture); + } + + private bool EncodeVideo(MediaSourceInfo mediaSource) + { + var mediaStreams = mediaSource.MediaStreams ?? new List<MediaStream>(); + return !mediaStreams.Any(i => i.Type == MediaStreamType.Video && string.Equals(i.Codec, "h264", StringComparison.OrdinalIgnoreCase) && !i.IsInterlaced); + } + + protected string GetOutputSizeParam() + { + var filters = new List<string>(); + + filters.Add("yadif=0:-1:0"); + + var output = string.Empty; + + if (filters.Count > 0) + { + output += string.Format(" -vf \"{0}\"", string.Join(",", filters.ToArray())); + } + + return output; + } + + private void Stop() + { + if (!_hasExited) + { + try + { + _logger.Info("Killing ffmpeg recording process for {0}", _targetPath); + + //process.Kill(); + _process.StandardInput.WriteLine("q"); + + // Need to wait because killing is asynchronous + _process.WaitForExit(5000); + } + catch (Exception ex) + { + _logger.ErrorException("Error killing transcoding job for {0}", ex, _targetPath); + } + } + } + + /// <summary> + /// Processes the exited. + /// </summary> + /// <param name="process">The process.</param> + private void OnFfMpegProcessExited(Process process) + { + _hasExited = true; + + _logger.Debug("Disposing stream resources"); + DisposeLogStream(); + + try + { + _logger.Info("FFMpeg exited with code {0}", process.ExitCode); + } + catch + { + _logger.Error("FFMpeg exited with an error."); + } + } + + private void DisposeLogStream() + { + if (_logFileStream != null) + { + try + { + _logFileStream.Dispose(); + } + catch (Exception ex) + { + _logger.ErrorException("Error disposing log stream", ex); + } + + _logFileStream = null; + } + } + + private async void StartStreamingLog(Stream source, Stream target) + { + try + { + using (var reader = new StreamReader(source)) + { + while (!reader.EndOfStream) + { + var line = await reader.ReadLineAsync().ConfigureAwait(false); + + var bytes = Encoding.UTF8.GetBytes(Environment.NewLine + line); + + await target.WriteAsync(bytes, 0, bytes.Length).ConfigureAwait(false); + await target.FlushAsync().ConfigureAwait(false); + } + } + } + catch (ObjectDisposedException) + { + // Don't spam the log. This doesn't seem to throw in windows, but sometimes under linux + } + catch (Exception ex) + { + _logger.ErrorException("Error reading ffmpeg log", ex); + } + } + } +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs new file mode 100644 index 000000000..12e73c1f3 --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/IRecorder.cs @@ -0,0 +1,12 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.Dto; + +namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV +{ + public interface IRecorder + { + Task Record(MediaSourceInfo mediaSource, string targetFile, Action onStarted, CancellationToken cancellationToken); + } +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs index 8bf1d27b8..14bfcba27 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/LiveTvManager.cs @@ -300,6 +300,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv public async Task<ILiveTvRecording> GetInternalRecording(string id, CancellationToken cancellationToken) { + if (string.IsNullOrWhiteSpace(id)) + { + throw new ArgumentNullException("id"); + } + var result = await GetInternalRecordings(new RecordingQuery { Id = id @@ -560,6 +565,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv } item.ExternalId = channelInfo.Id; + if (!item.ParentId.Equals(parentFolderId)) + { + isNew = true; + } + item.ParentId = parentFolderId; + item.ChannelType = channelInfo.ChannelType; item.ServiceName = serviceName; item.Number = channelInfo.Number; @@ -622,6 +633,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv }; } + if (!item.ParentId.Equals(channel.Id)) + { + forceUpdate = true; + } + item.ParentId = channel.Id; + //item.ChannelType = channelType; if (!string.Equals(item.ServiceName, serviceName, StringComparison.Ordinal)) { @@ -774,6 +791,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv } recording.IsSeries = info.IsSeries; + if (!item.ParentId.Equals(parentFolderId)) + { + dataChanged = true; + } + item.ParentId = parentFolderId; + if (!item.HasImage(ImageType.Primary)) { if (!string.IsNullOrWhiteSpace(info.ImagePath)) @@ -851,7 +874,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv { var user = string.IsNullOrEmpty(query.UserId) ? null : _userManager.GetUserById(query.UserId); - var internalQuery = new InternalItemsQuery + var internalQuery = new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvProgram).Name }, MinEndDate = query.MinEndDate, @@ -869,16 +892,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv SortOrder = query.SortOrder ?? SortOrder.Ascending }; - if (user != null) - { - internalQuery.MaxParentalRating = user.Policy.MaxParentalRating; - - if (user.Policy.BlockUnratedItems.Contains(UnratedItem.LiveTvProgram)) - { - internalQuery.HasParentalRating = true; - } - } - if (query.HasAired.HasValue) { if (query.HasAired.Value) @@ -913,7 +926,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv { var user = _userManager.GetUserById(query.UserId); - var internalQuery = new InternalItemsQuery + var internalQuery = new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvProgram).Name }, IsAiring = query.IsAiring, @@ -922,16 +935,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv IsKids = query.IsKids }; - if (user != null) - { - internalQuery.MaxParentalRating = user.Policy.MaxParentalRating; - - if (user.Policy.BlockUnratedItems.Contains(UnratedItem.LiveTvProgram)) - { - internalQuery.HasParentalRating = true; - } - } - if (query.HasAired.HasValue) { if (query.HasAired.Value) @@ -1399,7 +1402,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv await RefreshRecordings(cancellationToken).ConfigureAwait(false); - var internalQuery = new InternalItemsQuery + var internalQuery = new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvVideoRecording).Name, typeof(LiveTvAudioRecording).Name } }; @@ -1409,10 +1412,10 @@ namespace MediaBrowser.Server.Implementations.LiveTv internalQuery.ChannelIds = new[] { query.ChannelId }; } - var queryResult = _libraryManager.GetItems(internalQuery); - IEnumerable<ILiveTvRecording> recordings = queryResult.Items.Cast<ILiveTvRecording>(); + var queryResult = _libraryManager.GetItems(internalQuery, new string[] { }); + IEnumerable<ILiveTvRecording> recordings = queryResult.Cast<ILiveTvRecording>(); - if (!string.IsNullOrEmpty(query.Id)) + if (!string.IsNullOrWhiteSpace(query.Id)) { var guid = new Guid(query.Id); @@ -1420,7 +1423,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv .Where(i => i.Id == guid); } - if (!string.IsNullOrEmpty(query.GroupId)) + if (!string.IsNullOrWhiteSpace(query.GroupId)) { var guid = new Guid(query.GroupId); @@ -1469,7 +1472,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv }; } - public void AddInfoToProgramDto(BaseItem item, BaseItemDto dto, bool addChannelInfo, User user = null) + public void AddInfoToProgramDto(BaseItem item, BaseItemDto dto, List<ItemFields> fields, User user = null) { var program = (LiveTvProgram)item; @@ -1509,13 +1512,14 @@ namespace MediaBrowser.Server.Implementations.LiveTv dto.IsPremiere = program.IsPremiere; } - if (addChannelInfo) + if (fields.Contains(ItemFields.ChannelInfo)) { var channel = GetInternalChannel(program.ChannelId); if (channel != null) { dto.ChannelName = channel.Name; + dto.MediaType = channel.MediaType; if (channel.HasImage(ImageType.Primary)) { @@ -1523,6 +1527,15 @@ namespace MediaBrowser.Server.Implementations.LiveTv } } } + + if (fields.Contains(ItemFields.ServiceName)) + { + var service = GetService(program); + if (service != null) + { + dto.ServiceName = service.Name; + } + } } public void AddInfoToRecordingDto(BaseItem item, BaseItemDto dto, User user = null) @@ -1593,18 +1606,18 @@ namespace MediaBrowser.Server.Implementations.LiveTv var internalResult = await GetInternalRecordings(query, cancellationToken).ConfigureAwait(false); - var returnArray = internalResult.Items - .Select(i => _dtoService.GetBaseItemDto(i, options, user)) + var tuples = internalResult.Items + .Select(i => new Tuple<BaseItem, BaseItemDto>(i, _dtoService.GetBaseItemDto(i, options, user))) .ToArray(); if (user != null) { - _dtoService.FillSyncInfo(returnArray, new DtoOptions(), user); + _dtoService.FillSyncInfo(tuples, new DtoOptions(), user); } return new QueryResult<BaseItemDto> { - Items = returnArray, + Items = tuples.Select(i => i.Item2).ToArray(), TotalRecordCount = internalResult.TotalRecordCount }; } @@ -1674,6 +1687,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv throw new ResourceNotFoundException(string.Format("Recording with Id {0} not found", recordingId)); } + await DeleteRecording(recording).ConfigureAwait(false); + } + + public async Task DeleteRecording(ILiveTvRecording recording) + { var service = GetService(recording.ServiceName); try @@ -1685,6 +1703,8 @@ namespace MediaBrowser.Server.Implementations.LiveTv } + _lastRecordingRefreshTime = DateTime.MinValue; + // This is the responsibility of the live tv service await _libraryManager.DeleteItem((BaseItem)recording, new DeleteOptions { @@ -1812,7 +1832,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv var now = DateTime.UtcNow; - var programs = _libraryManager.GetItems(new InternalItemsQuery + var programs = _libraryManager.GetItems(new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvProgram).Name }, ChannelIds = new[] { id }, @@ -1821,7 +1841,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv Limit = 1, SortBy = new[] { "StartDate" } - }).Items.Cast<LiveTvProgram>(); + }, new string[] { }).Cast<LiveTvProgram>(); var currentProgram = programs.FirstOrDefault(); @@ -1836,7 +1856,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv var now = DateTime.UtcNow; - var programs = _libraryManager.GetItems(new InternalItemsQuery + var programs = _libraryManager.GetItems(new InternalItemsQuery(user) { IncludeItemTypes = new[] { typeof(LiveTvProgram).Name }, ChannelIds = new[] { channel.Id.ToString("N") }, @@ -1845,7 +1865,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv Limit = 1, SortBy = new[] { "StartDate" } - }).Items.Cast<LiveTvProgram>(); + }, new string[] { }).Cast<LiveTvProgram>(); var currentProgram = programs.FirstOrDefault(); diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs index ddbbb030d..f87d4f43f 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/M3UTunerHost.cs @@ -46,53 +46,59 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts protected override async Task<IEnumerable<ChannelInfo>> GetChannelsInternal(TunerHostInfo info, CancellationToken cancellationToken) { - var url = info.Url; - var urlHash = url.GetMD5().ToString("N"); + var urlHash = info.Url.GetMD5().ToString("N"); - string line; // Read the file and display it line by line. - using (var file = new StreamReader(await GetListingsStream(info, cancellationToken).ConfigureAwait(false))) + using (var reader = new StreamReader(await GetListingsStream(info, cancellationToken).ConfigureAwait(false))) { - var channels = new List<M3UChannel>(); + return GetChannels(reader, urlHash); + } + } + + private List<M3UChannel> GetChannels(StreamReader reader, string urlHash) + { + var channels = new List<M3UChannel>(); - string channnelName = null; - string channelNumber = null; + string channnelName = null; + string channelNumber = null; + string line; - while ((line = file.ReadLine()) != null) + while ((line = reader.ReadLine()) != null) + { + line = line.Trim(); + if (string.IsNullOrWhiteSpace(line)) { - line = line.Trim(); - if (string.IsNullOrWhiteSpace(line)) - { - continue; - } + continue; + } - if (line.StartsWith("#EXTM3U", StringComparison.OrdinalIgnoreCase)) - { - continue; - } + if (line.StartsWith("#EXTM3U", StringComparison.OrdinalIgnoreCase)) + { + continue; + } - if (line.StartsWith("#EXTINF:", StringComparison.OrdinalIgnoreCase)) - { - var parts = line.Split(new[] { ':' }, 2).Last().Split(new[] { ',' }, 2); - channelNumber = parts[0]; - channnelName = parts[1]; - } - else if (!string.IsNullOrWhiteSpace(channelNumber)) + if (line.StartsWith("#EXTINF:", StringComparison.OrdinalIgnoreCase)) + { + line = line.Substring(8); + Logger.Info("Found m3u channel: {0}", line); + var parts = line.Split(new[] { ',' }, 2); + channelNumber = parts[0]; + channnelName = parts[1]; + } + else if (!string.IsNullOrWhiteSpace(channelNumber)) + { + channels.Add(new M3UChannel { - channels.Add(new M3UChannel - { - Name = channnelName, - Number = channelNumber, - Id = ChannelIdPrefix + urlHash + channelNumber, - Path = line - }); - - channelNumber = null; - channnelName = null; - } + Name = channnelName, + Number = channelNumber, + Id = ChannelIdPrefix + urlHash + line.GetMD5().ToString("N"), + Path = line + }); + + channelNumber = null; + channnelName = null; } - return channels; } + return channels; } public Task<List<LiveTvTunerInfo>> GetTunerInfos(CancellationToken cancellationToken) @@ -159,8 +165,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts return null; } - //channelId = channelId.Substring(prefix.Length); - var channels = await GetChannels(info, true, cancellationToken).ConfigureAwait(false); var m3uchannels = channels.Cast<M3UChannel>(); var channel = m3uchannels.FirstOrDefault(c => string.Equals(c.Id, channelId, StringComparison.OrdinalIgnoreCase)); diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp.cs deleted file mode 100644 index ecd2864c5..000000000 --- a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using MediaBrowser.Common.Configuration; -using MediaBrowser.Controller.LiveTv; -using MediaBrowser.Controller.MediaEncoding; -using MediaBrowser.Model.Dto; -using MediaBrowser.Model.LiveTv; -using MediaBrowser.Model.Logging; -using MediaBrowser.Model.Serialization; - -namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts -{ - public class SatIp : BaseTunerHost - { - public SatIp(IConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder) - : base(config, logger, jsonSerializer, mediaEncoder) - { - } - - protected override Task<IEnumerable<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } - - public override string Type - { - get { return "SatIp"; } - } - - protected override Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } - - protected override Task<MediaSourceInfo> GetChannelStream(TunerHostInfo tuner, string channelId, string streamId, CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } - - protected override Task<bool> IsAvailableInternal(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken) - { - throw new NotImplementedException(); - } - - protected override bool IsValidChannelId(string channelId) - { - throw new NotImplementedException(); - } - } -} diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs new file mode 100644 index 000000000..95c04d61f --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpDiscovery.cs @@ -0,0 +1,142 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Common.Configuration; +using MediaBrowser.Common.Net; +using MediaBrowser.Controller.Configuration; +using MediaBrowser.Controller.Dlna; +using MediaBrowser.Controller.LiveTv; +using MediaBrowser.Controller.Plugins; +using MediaBrowser.Model.Extensions; +using MediaBrowser.Model.LiveTv; +using MediaBrowser.Model.Logging; + +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp +{ + public class SatIpDiscovery : IServerEntryPoint + { + private readonly IDeviceDiscovery _deviceDiscovery; + private readonly IServerConfigurationManager _config; + private readonly ILogger _logger; + private readonly ILiveTvManager _liveTvManager; + private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1); + private readonly IHttpClient _httpClient; + + public SatIpDiscovery(IDeviceDiscovery deviceDiscovery, IServerConfigurationManager config, ILogger logger, ILiveTvManager liveTvManager, IHttpClient httpClient) + { + _deviceDiscovery = deviceDiscovery; + _config = config; + _logger = logger; + _liveTvManager = liveTvManager; + _httpClient = httpClient; + } + + public void Run() + { + _deviceDiscovery.DeviceDiscovered += _deviceDiscovery_DeviceDiscovered; + } + + void _deviceDiscovery_DeviceDiscovered(object sender, SsdpMessageEventArgs e) + { + //string server = null; + //if (e.Headers.TryGetValue("SERVER", out server) && server.IndexOf("HDHomeRun", StringComparison.OrdinalIgnoreCase) != -1) + //{ + // string location; + // if (e.Headers.TryGetValue("Location", out location)) + // { + // //_logger.Debug("HdHomerun found at {0}", location); + + // // Just get the beginning of the url + // Uri uri; + // if (Uri.TryCreate(location, UriKind.Absolute, out uri)) + // { + // var apiUrl = location.Replace(uri.LocalPath, String.Empty, StringComparison.OrdinalIgnoreCase) + // .TrimEnd('/'); + + // //_logger.Debug("HdHomerun api url: {0}", apiUrl); + // AddDevice(apiUrl); + // } + // } + //} + } + + private async void AddDevice(string url) + { + await _semaphore.WaitAsync().ConfigureAwait(false); + + try + { + var options = GetConfiguration(); + + if (options.TunerHosts.Any(i => + string.Equals(i.Type, SatIpHost.DeviceType, StringComparison.OrdinalIgnoreCase) && + UriEquals(i.Url, url))) + { + return; + } + + // Strip off the port + url = new Uri(url).GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped).TrimEnd('/'); + + await TestUrl(url).ConfigureAwait(false); + + await _liveTvManager.SaveTunerHost(new TunerHostInfo + { + Type = SatIpHost.DeviceType, + Url = url + + }).ConfigureAwait(false); + } + catch (Exception ex) + { + _logger.ErrorException("Error saving device", ex); + } + finally + { + _semaphore.Release(); + } + } + + private async Task TestUrl(string url) + { + // Test it by pulling down the lineup + using (await _httpClient.Get(new HttpRequestOptions + { + Url = string.Format("{0}/lineup.json", url), + CancellationToken = CancellationToken.None + })) + { + } + } + + private bool UriEquals(string savedUri, string location) + { + return string.Equals(NormalizeUrl(location), NormalizeUrl(savedUri), StringComparison.OrdinalIgnoreCase); + } + + private string NormalizeUrl(string url) + { + if (!url.StartsWith("http", StringComparison.OrdinalIgnoreCase)) + { + url = "http://" + url; + } + + url = url.TrimEnd('/'); + + // Strip off the port + return new Uri(url).GetComponents(UriComponents.AbsoluteUri & ~UriComponents.Port, UriFormat.UriEscaped); + } + + private LiveTvOptions GetConfiguration() + { + return _config.GetConfiguration<LiveTvOptions>("livetv"); + } + + public void Dispose() + { + } + } +} diff --git a/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs new file mode 100644 index 000000000..205cdf74e --- /dev/null +++ b/MediaBrowser.Server.Implementations/LiveTv/TunerHosts/SatIp/SatIpHost.cs @@ -0,0 +1,45 @@ +namespace MediaBrowser.Server.Implementations.LiveTv.TunerHosts.SatIp +{ + public class SatIpHost /*: BaseTunerHost*/ + { + //public SatIpHost(IConfigurationManager config, ILogger logger, IJsonSerializer jsonSerializer, IMediaEncoder mediaEncoder) + // : base(config, logger, jsonSerializer, mediaEncoder) + //{ + //} + + //protected override Task<IEnumerable<ChannelInfo>> GetChannelsInternal(TunerHostInfo tuner, CancellationToken cancellationToken) + //{ + // throw new NotImplementedException(); + //} + + public static string DeviceType + { + get { return "satip"; } + } + + //public override string Type + //{ + // get { return DeviceType; } + //} + + //protected override Task<List<MediaSourceInfo>> GetChannelStreamMediaSources(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken) + //{ + // throw new NotImplementedException(); + //} + + //protected override Task<MediaSourceInfo> GetChannelStream(TunerHostInfo tuner, string channelId, string streamId, CancellationToken cancellationToken) + //{ + // throw new NotImplementedException(); + //} + + //protected override Task<bool> IsAvailableInternal(TunerHostInfo tuner, string channelId, CancellationToken cancellationToken) + //{ + // throw new NotImplementedException(); + //} + + //protected override bool IsValidChannelId(string channelId) + //{ + // throw new NotImplementedException(); + //} + } +} diff --git a/MediaBrowser.Server.Implementations/Localization/Core/ar.json b/MediaBrowser.Server.Implementations/Localization/Core/ar.json index b6b07dc1c..28977c4f9 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/ar.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/ar.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/bg-BG.json b/MediaBrowser.Server.Implementations/Localization/Core/bg-BG.json index aeebd2038..22b99408d 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/bg-BG.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/bg-BG.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "\u0421\u043c\u0435\u0441\u0435\u043d\u043e \u0441\u044a\u0434\u044a\u0440\u0436\u0430\u043d\u0438\u0435", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/ca.json b/MediaBrowser.Server.Implementations/Localization/Core/ca.json index 83d72030f..7cec213d3 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/ca.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/ca.json @@ -1,10 +1,11 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Dispositiu: {1}", "UserDownloadingItemWithValues": "{0} est\u00e0 descarregant {1}", - "FolderTypeMixed": "Mixed content", + "FolderTypeMixed": "Contingut barrejat", "FolderTypeMovies": "Pel\u00b7l\u00edcules", "FolderTypeMusic": "M\u00fasica", - "FolderTypeAdultVideos": "Adult videos", + "FolderTypeAdultVideos": "V\u00eddeos per adults", "FolderTypePhotos": "Fotos", "FolderTypeMusicVideos": "V\u00eddeos musicals", "FolderTypeHomeVideos": "V\u00eddeos dom\u00e8stics", @@ -115,7 +116,7 @@ "FailedLoginAttemptWithUserName": "Failed login attempt from {0}", "AuthenticationSucceededWithUserName": "{0} autenticat correctament", "DeviceOfflineWithName": "{0} has disconnected", - "UserLockedOutWithName": "User {0} has been locked out", + "UserLockedOutWithName": "L'usuari {0} ha estat blocat", "UserOfflineFromDevice": "{0} has disconnected from {1}", "UserStartedPlayingItemWithValues": "{0} ha comen\u00e7at a reproduir {1}", "UserStoppedPlayingItemWithValues": "{0} ha parat de reproduir {1}", @@ -157,13 +158,13 @@ "HeaderVideo": "V\u00eddeo", "HeaderEmbeddedImage": "Embedded image", "HeaderResolution": "Resolution", - "HeaderSubtitles": "Subtitles", + "HeaderSubtitles": "Subt\u00edtols", "HeaderGenres": "Genres", "HeaderCountries": "Countries", "HeaderStatus": "Estat", "HeaderTracks": "Tracks", "HeaderMusicArtist": "M\u00fasic", - "HeaderLocked": "Locked", + "HeaderLocked": "Blocat", "HeaderStudios": "Estudis", "HeaderActor": "Actors", "HeaderComposer": "Compositors", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/core.json b/MediaBrowser.Server.Implementations/Localization/Core/core.json index 5f11b9436..976faa8cb 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/core.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/core.json @@ -174,5 +174,6 @@ "HeaderWriter": "Writers", "HeaderParentalRatings": "Parental Ratings", "HeaderCommunityRatings": "Community ratings", - "StartupEmbyServerIsLoading": "Emby Server is loading. Please try again shortly." + "StartupEmbyServerIsLoading": "Emby Server is loading. Please try again shortly.", + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete." } diff --git a/MediaBrowser.Server.Implementations/Localization/Core/cs.json b/MediaBrowser.Server.Implementations/Localization/Core/cs.json index 3d630abb4..9c62daf73 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/cs.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/cs.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "Aplikace: {0}, Za\u0159\u00edzen\u00ed: {1}", "UserDownloadingItemWithValues": "{0} pr\u00e1v\u011b stahuje {1}", "FolderTypeMixed": "Sm\u00ed\u0161en\u00fd obsah", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/da.json b/MediaBrowser.Server.Implementations/Localization/Core/da.json index e6e4d9835..d2a628a80 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/da.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/da.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Enhed: {1}", "UserDownloadingItemWithValues": "{0} henter {1}", "FolderTypeMixed": "Blandet indhold", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/de.json b/MediaBrowser.Server.Implementations/Localization/Core/de.json index 0f22ff479..30e3d9215 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/de.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/de.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Bitte warten Sie w\u00e4hrend die Emby Datenbank aktualisiert wird. {0}% verarbeitet.", "AppDeviceValues": "App: {0}, Ger\u00e4t: {1}", "UserDownloadingItemWithValues": "{0} l\u00e4dt {1} herunter", "FolderTypeMixed": "Gemischte Inhalte", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/el.json b/MediaBrowser.Server.Implementations/Localization/Core/el.json index 7e94f7987..9e2d321cc 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/el.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/el.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "\u0391\u03bd\u03ac\u03bc\u03b5\u03b9\u03ba\u03c4\u03bf \u03a0\u03b5\u03c1\u03b9\u03b5\u03c7\u03cc\u03bc\u03b5\u03bd\u03bf", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/en-GB.json b/MediaBrowser.Server.Implementations/Localization/Core/en-GB.json index 4462c00fd..493c6c4e9 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/en-GB.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/en-GB.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/en-US.json b/MediaBrowser.Server.Implementations/Localization/Core/en-US.json index e444c0e93..0d5b5c4aa 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/en-US.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/en-US.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/es-AR.json b/MediaBrowser.Server.Implementations/Localization/Core/es-AR.json index 8068e32a9..0555aa9d9 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/es-AR.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/es-AR.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/es-MX.json b/MediaBrowser.Server.Implementations/Localization/Core/es-MX.json index 27aeee097..630c7a037 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/es-MX.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/es-MX.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Por favor espere mientras la base de datos de su Servidor Emby es actualizada. {0}% completo.", "AppDeviceValues": "App: {0}, Dispositivo: {1}", "UserDownloadingItemWithValues": "{0} esta descargando {1}", "FolderTypeMixed": "Contenido mezclado", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/es.json b/MediaBrowser.Server.Implementations/Localization/Core/es.json index 60dbd1a44..2a715a5b3 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/es.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/es.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Contenido mezclado", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/fi.json b/MediaBrowser.Server.Implementations/Localization/Core/fi.json index f0ab5b0d0..20efa1406 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/fi.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/fi.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/fr.json b/MediaBrowser.Server.Implementations/Localization/Core/fr.json index 182e89bf6..25c722989 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/fr.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/fr.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Veuillez patienter pendant que la base de donn\u00e9e de votre Emby Serveur se met \u00e0 jour. Termin\u00e9e \u00e0 {0}%.", "AppDeviceValues": "Application : {0}, Appareil: {1}", "UserDownloadingItemWithValues": "{0} est en train de t\u00e9l\u00e9charger {1}", "FolderTypeMixed": "Contenus m\u00e9lang\u00e9s", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/gsw.json b/MediaBrowser.Server.Implementations/Localization/Core/gsw.json index 736c3d18f..88af82b7e 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/gsw.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/gsw.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Verschiedeni Sache", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/he.json b/MediaBrowser.Server.Implementations/Localization/Core/he.json index f900946f1..137b45544 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/he.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/he.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "\u05ea\u05d5\u05db\u05df \u05de\u05e2\u05d5\u05e8\u05d1", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/hr.json b/MediaBrowser.Server.Implementations/Localization/Core/hr.json index 2b9d56566..7a94dc32b 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/hr.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/hr.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/hu.json b/MediaBrowser.Server.Implementations/Localization/Core/hu.json index 2dc90fb7e..0c9d16d38 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/hu.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/hu.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/id.json b/MediaBrowser.Server.Implementations/Localization/Core/id.json index 4fb839fe8..8d64b63c4 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/id.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/id.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Silahkan menunggu sementara database Emby Server anda diupgrade. {0}% selesai.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/it.json b/MediaBrowser.Server.Implementations/Localization/Core/it.json index 2030ea110..d2d697c3e 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/it.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/it.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Dispositivo: {1}", "UserDownloadingItemWithValues": "{0} sta scaricando {1}", "FolderTypeMixed": "contenuto misto", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/kk.json b/MediaBrowser.Server.Implementations/Localization/Core/kk.json index be7c4c56e..93252c30b 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/kk.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/kk.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Emby Server \u0434\u0435\u0440\u0435\u043a\u049b\u043e\u0440\u044b\u04a3\u044b\u0437\u0434\u044b\u04a3 \u0436\u0430\u04a3\u0493\u044b\u0440\u0442\u044b\u043b\u0443\u044b\u043d \u043a\u04af\u0442\u0435 \u0442\u04b1\u0440\u044b\u04a3\u044b\u0437. {0} % \u0430\u044f\u049b\u0442\u0430\u043b\u0434\u044b.", "AppDeviceValues": "\u049a\u043e\u043b\u0434\u0430\u043d\u0431\u0430: {0}, \u049a\u04b1\u0440\u044b\u043b\u0493\u044b: {1}", "UserDownloadingItemWithValues": "{0} \u043c\u044b\u043d\u0430\u043d\u044b \u0436\u04af\u043a\u0442\u0435\u043f \u0430\u043b\u0443\u0434\u0430: {1}", "FolderTypeMixed": "\u0410\u0440\u0430\u043b\u0430\u0441 \u043c\u0430\u0437\u043c\u04b1\u043d", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/ko.json b/MediaBrowser.Server.Implementations/Localization/Core/ko.json index dcd4d2346..834ccc17b 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/ko.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/ko.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "\uc571: {0}, \uc7a5\uce58: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "\ud63c\ud569 \ucf58\ud150\ud2b8", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/ms.json b/MediaBrowser.Server.Implementations/Localization/Core/ms.json index 6b5c4393f..fe5eef894 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/ms.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/ms.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/nb.json b/MediaBrowser.Server.Implementations/Localization/Core/nb.json index f4ebe89b6..315d49b5f 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/nb.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/nb.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0} , Device: {1}", "UserDownloadingItemWithValues": "{0} laster ned {1}", "FolderTypeMixed": "Forskjellig innhold", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/nl.json b/MediaBrowser.Server.Implementations/Localization/Core/nl.json index fd0c586a2..a83182ee8 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/nl.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/nl.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Even geduld svp terwijl de Emby Server database ge-upgrade wordt. {0}% gereed.", "AppDeviceValues": "App: {0}, Apparaat: {1}", "UserDownloadingItemWithValues": "{0} download {1}", "FolderTypeMixed": "Gemengde inhoud", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/pl.json b/MediaBrowser.Server.Implementations/Localization/Core/pl.json index 3b7d56def..db22dc6e4 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/pl.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/pl.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "Aplikacja: {0}, Urz\u0105dzenie: {1}", "UserDownloadingItemWithValues": "{0} pobiera {1}", "FolderTypeMixed": "Zawarto\u015b\u0107 mieszana", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/pt-BR.json b/MediaBrowser.Server.Implementations/Localization/Core/pt-BR.json index 9548262c9..b714fd44c 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/pt-BR.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/pt-BR.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Por favor, aguarde enquanto a base de dados do Servidor Emby \u00e9 atualizada. {0}% completado.", "AppDeviceValues": "App: {0}, Dispositivo: {1}", "UserDownloadingItemWithValues": "{0} est\u00e1 fazendo download de {1}", "FolderTypeMixed": "Conte\u00fado misto", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/pt-PT.json b/MediaBrowser.Server.Implementations/Localization/Core/pt-PT.json index c3d514c8a..f12939b10 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/pt-PT.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/pt-PT.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/ro.json b/MediaBrowser.Server.Implementations/Localization/Core/ro.json index a6aa9577b..c58df27d5 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/ro.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/ro.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Continut mixt", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/ru.json b/MediaBrowser.Server.Implementations/Localization/Core/ru.json index c22cf9f84..0aacc5362 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/ru.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/ru.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "\u041f\u043e\u0434\u043e\u0436\u0434\u0438\u0442\u0435, \u043f\u043e\u043a\u0430 \u0431\u0430\u0437\u0430 \u0434\u0430\u043d\u043d\u044b\u0445 \u043d\u0430 \u0432\u0430\u0448\u0435\u043c Emby Server \u043c\u043e\u0434\u0435\u0440\u043d\u0438\u0437\u0438\u0440\u0443\u0435\u0442\u0441\u044f. {0} % \u0432\u044b\u043f\u043e\u043b\u043d\u0435\u043d\u043e.", "AppDeviceValues": "\u041f\u0440\u0438\u043b.: {0}, \u0423\u0441\u0442\u0440.: {1}", "UserDownloadingItemWithValues": "{0} \u0437\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u0442 {1}", "FolderTypeMixed": "\u0420\u0430\u0437\u043d\u043e\u0442\u0438\u043f\u043d\u043e\u0435 \u0441\u043e\u0434\u0435\u0440\u0436\u0430\u043d\u0438\u0435", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/sl-SI.json b/MediaBrowser.Server.Implementations/Localization/Core/sl-SI.json index e444c0e93..0d5b5c4aa 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/sl-SI.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/sl-SI.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/sv.json b/MediaBrowser.Server.Implementations/Localization/Core/sv.json index 667b8e4b4..f52f656d4 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/sv.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/sv.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, enhet: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Blandat inneh\u00e5ll", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/tr.json b/MediaBrowser.Server.Implementations/Localization/Core/tr.json index 810df2665..a691e9d02 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/tr.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/tr.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/uk.json b/MediaBrowser.Server.Implementations/Localization/Core/uk.json index 73c9b26f9..0dc6afe8a 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/uk.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/uk.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/vi.json b/MediaBrowser.Server.Implementations/Localization/Core/vi.json index 75a5dbea7..6ea1d1d3f 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/vi.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/vi.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/zh-CN.json b/MediaBrowser.Server.Implementations/Localization/Core/zh-CN.json index a9430c0c2..580832a9e 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/zh-CN.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/zh-CN.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App\uff1a {0}\uff0c\u8bbe\u5907\uff1a {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "\u6df7\u5408\u5185\u5bb9", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/zh-HK.json b/MediaBrowser.Server.Implementations/Localization/Core/zh-HK.json index 8d25a28c4..a70e7a003 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/zh-HK.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/zh-HK.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "\u6df7\u5408\u5167\u5bb9", diff --git a/MediaBrowser.Server.Implementations/Localization/Core/zh-TW.json b/MediaBrowser.Server.Implementations/Localization/Core/zh-TW.json index 2bcb5c132..7f289fc1f 100644 --- a/MediaBrowser.Server.Implementations/Localization/Core/zh-TW.json +++ b/MediaBrowser.Server.Implementations/Localization/Core/zh-TW.json @@ -1,4 +1,5 @@ { + "DbUpgradeMessage": "Please wait while your Emby Server database is upgraded. {0}% complete.", "AppDeviceValues": "App: {0}, Device: {1}", "UserDownloadingItemWithValues": "{0} is downloading {1}", "FolderTypeMixed": "Mixed content", diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index f3376aff0..2dee8a5ed 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -45,12 +45,15 @@ <SpecificVersion>False</SpecificVersion> <HintPath>..\packages\CommonIO.1.0.0.7\lib\net45\CommonIO.dll</HintPath> </Reference> + <Reference Include="Emby.XmlTv"> + <HintPath>..\packages\Emby.XmlTv.1.0.0.46\lib\net45\Emby.XmlTv.dll</HintPath> + </Reference> <Reference Include="Interfaces.IO"> <HintPath>..\packages\Interfaces.IO.1.0.0.5\lib\portable-net45+sl4+wp71+win8+wpa81\Interfaces.IO.dll</HintPath> </Reference> - <Reference Include="MediaBrowser.Naming, Version=1.0.5877.22335, Culture=neutral, processorArchitecture=MSIL"> + <Reference Include="MediaBrowser.Naming, Version=1.0.5884.23751, Culture=neutral, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> - <HintPath>..\packages\MediaBrowser.Naming.1.0.0.46\lib\portable-net45+sl4+wp71+win8+wpa81\MediaBrowser.Naming.dll</HintPath> + <HintPath>..\packages\MediaBrowser.Naming.1.0.0.47\lib\portable-net45+sl4+wp71+win8+wpa81\MediaBrowser.Naming.dll</HintPath> </Reference> <Reference Include="MoreLinq"> <HintPath>..\packages\morelinq.1.4.0\lib\net35\MoreLinq.dll</HintPath> @@ -212,8 +215,11 @@ <Compile Include="Library\Validators\StudiosValidator.cs" /> <Compile Include="Library\Validators\YearsPostScanTask.cs" /> <Compile Include="LiveTv\ChannelImageProvider.cs" /> + <Compile Include="LiveTv\EmbyTV\DirectRecorder.cs" /> <Compile Include="LiveTv\EmbyTV\EmbyTV.cs" /> + <Compile Include="LiveTv\EmbyTV\EncodedRecorder.cs" /> <Compile Include="LiveTv\EmbyTV\EntryPoint.cs" /> + <Compile Include="LiveTv\EmbyTV\IRecorder.cs" /> <Compile Include="LiveTv\EmbyTV\ItemDataProvider.cs" /> <Compile Include="LiveTv\EmbyTV\RecordingHelper.cs" /> <Compile Include="LiveTv\EmbyTV\SeriesTimerManager.cs" /> @@ -231,6 +237,8 @@ <Compile Include="LiveTv\ProgramImageProvider.cs" /> <Compile Include="LiveTv\RecordingImageProvider.cs" /> <Compile Include="LiveTv\RefreshChannelsScheduledTask.cs" /> + <Compile Include="LiveTv\TunerHosts\SatIp\SatIpHost.cs" /> + <Compile Include="LiveTv\TunerHosts\SatIp\SatIpDiscovery.cs" /> <Compile Include="Localization\LocalizationManager.cs" /> <Compile Include="Logging\PatternsLogger.cs" /> <Compile Include="MediaEncoder\EncodingManager.cs" /> diff --git a/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs b/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs index bd634ed73..ac0f2c69d 100644 --- a/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs +++ b/MediaBrowser.Server.Implementations/MediaEncoder/EncodingManager.cs @@ -124,8 +124,7 @@ namespace MediaBrowser.Server.Implementations.MediaEncoder { if (extractImages) { - if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso || - video.VideoType == VideoType.BluRay) + if (video.VideoType == VideoType.HdDvd || video.VideoType == VideoType.Iso || video.VideoType == VideoType.BluRay) { continue; } diff --git a/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs b/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs index f883e6dbc..7302431e1 100644 --- a/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs +++ b/MediaBrowser.Server.Implementations/Notifications/SqliteNotificationsRepository.cs @@ -13,20 +13,11 @@ using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.Notifications { - public class SqliteNotificationsRepository : INotificationsRepository + public class SqliteNotificationsRepository : BaseSqliteRepository, INotificationsRepository { private IDbConnection _connection; - private readonly ILogger _logger; private readonly IServerApplicationPaths _appPaths; - private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); - - public SqliteNotificationsRepository(ILogManager logManager, IServerApplicationPaths appPaths) - { - _appPaths = appPaths; - _logger = logManager.GetLogger(GetType().Name); - } - public event EventHandler<NotificationUpdateEventArgs> NotificationAdded; public event EventHandler<NotificationReadEventArgs> NotificationsMarkedRead; public event EventHandler<NotificationUpdateEventArgs> NotificationUpdated; @@ -35,11 +26,17 @@ namespace MediaBrowser.Server.Implementations.Notifications private IDbCommand _markReadCommand; private IDbCommand _markAllReadCommand; + public SqliteNotificationsRepository(ILogManager logManager, IServerApplicationPaths appPaths) + : base(logManager) + { + _appPaths = appPaths; + } + public async Task Initialize() { var dbFile = Path.Combine(_appPaths.DataPath, "notifications.db"); - _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false); + _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false); string[] queries = { @@ -52,7 +49,7 @@ namespace MediaBrowser.Server.Implementations.Notifications "pragma shrink_memory" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); PrepareStatements(); } @@ -251,7 +248,7 @@ namespace MediaBrowser.Server.Implementations.Notifications } catch (Exception ex) { - _logger.ErrorException("Error in NotificationAdded event handler", ex); + Logger.ErrorException("Error in NotificationAdded event handler", ex); } } } @@ -275,7 +272,7 @@ namespace MediaBrowser.Server.Implementations.Notifications cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -311,7 +308,7 @@ namespace MediaBrowser.Server.Implementations.Notifications } catch (Exception e) { - _logger.ErrorException("Failed to save notification:", e); + Logger.ErrorException("Failed to save notification:", e); if (transaction != null) { @@ -327,7 +324,7 @@ namespace MediaBrowser.Server.Implementations.Notifications transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -359,7 +356,7 @@ namespace MediaBrowser.Server.Implementations.Notifications } catch (Exception ex) { - _logger.ErrorException("Error in NotificationsMarkedRead event handler", ex); + Logger.ErrorException("Error in NotificationsMarkedRead event handler", ex); } } } @@ -368,7 +365,7 @@ namespace MediaBrowser.Server.Implementations.Notifications { cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -396,7 +393,7 @@ namespace MediaBrowser.Server.Implementations.Notifications } catch (Exception e) { - _logger.ErrorException("Failed to save notification:", e); + Logger.ErrorException("Failed to save notification:", e); if (transaction != null) { @@ -412,7 +409,7 @@ namespace MediaBrowser.Server.Implementations.Notifications transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -420,7 +417,7 @@ namespace MediaBrowser.Server.Implementations.Notifications { cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -455,7 +452,7 @@ namespace MediaBrowser.Server.Implementations.Notifications } catch (Exception e) { - _logger.ErrorException("Failed to save notification:", e); + Logger.ErrorException("Failed to save notification:", e); if (transaction != null) { @@ -471,7 +468,21 @@ namespace MediaBrowser.Server.Implementations.Notifications transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); + } + } + + protected override void CloseConnection() + { + if (_connection != null) + { + if (_connection.IsOpen()) + { + _connection.Close(); + } + + _connection.Dispose(); + _connection = null; } } } diff --git a/MediaBrowser.Server.Implementations/Persistence/BaseSqliteRepository.cs b/MediaBrowser.Server.Implementations/Persistence/BaseSqliteRepository.cs index cac112b6c..395907844 100644 --- a/MediaBrowser.Server.Implementations/Persistence/BaseSqliteRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/BaseSqliteRepository.cs @@ -1,6 +1,8 @@ using MediaBrowser.Model.Logging; using System; +using System.Data; using System.Threading; +using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.Persistence { @@ -14,12 +16,48 @@ namespace MediaBrowser.Server.Implementations.Persistence Logger = logManager.GetLogger(GetType().Name); } + private bool _disposed; + protected void CheckDisposed() + { + if (_disposed) + { + throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed."); + } + } + public void Dispose() { + _disposed = true; Dispose(true); GC.SuppressFinalize(this); } + protected async Task Vacuum(IDbConnection connection) + { + CheckDisposed(); + + await WriteLock.WaitAsync().ConfigureAwait(false); + + try + { + using (var cmd = connection.CreateCommand()) + { + cmd.CommandText = "vacuum"; + cmd.ExecuteNonQuery(); + } + } + catch (Exception e) + { + Logger.ErrorException("Failed to vacuum:", e); + + throw; + } + finally + { + WriteLock.Release(); + } + } + private readonly object _disposeLock = new object(); /// <summary> diff --git a/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs b/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs index 070c5239e..6ca1bae6d 100644 --- a/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs +++ b/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs @@ -9,10 +9,16 @@ using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; using System; using System.Collections.Generic; +using System.Globalization; +using System.Linq; using System.Threading; using System.Threading.Tasks; using CommonIO; +using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Localization; +using MediaBrowser.Controller.Net; +using MediaBrowser.Server.Implementations.ScheduledTasks; namespace MediaBrowser.Server.Implementations.Persistence { @@ -23,14 +29,23 @@ namespace MediaBrowser.Server.Implementations.Persistence private readonly ILogger _logger; private readonly IServerConfigurationManager _config; private readonly IFileSystem _fileSystem; + private readonly IHttpServer _httpServer; + private readonly ILocalizationManager _localization; + private readonly ITaskManager _taskManager; - public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem) + public const int MigrationVersion = 20; + public static bool EnableUnavailableMessage = false; + + public CleanDatabaseScheduledTask(ILibraryManager libraryManager, IItemRepository itemRepo, ILogger logger, IServerConfigurationManager config, IFileSystem fileSystem, IHttpServer httpServer, ILocalizationManager localization, ITaskManager taskManager) { _libraryManager = libraryManager; _itemRepo = itemRepo; _logger = logger; _config = config; _fileSystem = fileSystem; + _httpServer = httpServer; + _localization = localization; + _taskManager = taskManager; } public string Name @@ -50,30 +65,82 @@ namespace MediaBrowser.Server.Implementations.Persistence public async Task Execute(CancellationToken cancellationToken, IProgress<double> progress) { + OnProgress(0); + + // Ensure these objects are lazy loaded. + // Without this there is a deadlock that will need to be investigated + var rootChildren = _libraryManager.RootFolder.Children.ToList(); + rootChildren = _libraryManager.GetUserRootFolder().Children.ToList(); + var innerProgress = new ActionableProgress<double>(); - innerProgress.RegisterAction(p => progress.Report(.4 * p)); + innerProgress.RegisterAction(p => + { + double newPercentCommplete = .4 * p; + OnProgress(newPercentCommplete); + + progress.Report(newPercentCommplete); + }); await UpdateToLatestSchema(cancellationToken, innerProgress).ConfigureAwait(false); innerProgress = new ActionableProgress<double>(); - innerProgress.RegisterAction(p => progress.Report(40 + (.05 * p))); + innerProgress.RegisterAction(p => + { + double newPercentCommplete = 40 + (.05 * p); + OnProgress(newPercentCommplete); + progress.Report(newPercentCommplete); + }); await CleanDeadItems(cancellationToken, innerProgress).ConfigureAwait(false); progress.Report(45); innerProgress = new ActionableProgress<double>(); - innerProgress.RegisterAction(p => progress.Report(45 + (.55 * p))); + innerProgress.RegisterAction(p => + { + double newPercentCommplete = 45 + (.55 * p); + OnProgress(newPercentCommplete); + progress.Report(newPercentCommplete); + }); await CleanDeletedItems(cancellationToken, innerProgress).ConfigureAwait(false); progress.Report(100); + + await _itemRepo.UpdateInheritedValues(cancellationToken).ConfigureAwait(false); + + if (_config.Configuration.MigrationVersion < MigrationVersion) + { + _config.Configuration.MigrationVersion = MigrationVersion; + _config.SaveConfiguration(); + } + + if (EnableUnavailableMessage) + { + EnableUnavailableMessage = false; + _httpServer.GlobalResponse = null; + _taskManager.QueueScheduledTask<RefreshMediaLibraryTask>(); + } + + _taskManager.SuspendTriggers = false; + } + + private void OnProgress(double newPercentCommplete) + { + if (EnableUnavailableMessage) + { + var html = "<!doctype html><html><head><title>Emby</title></head><body>"; + var text = _localization.GetLocalizedString("DbUpgradeMessage"); + html += string.Format(text, newPercentCommplete.ToString("N2", CultureInfo.InvariantCulture)); + + html += "<script>setTimeout(function(){window.location.reload(true);}, 5000);</script>"; + html += "</body></html>"; + + _httpServer.GlobalResponse = html; + } } private async Task UpdateToLatestSchema(CancellationToken cancellationToken, IProgress<double> progress) { var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery { - IsCurrentSchema = false, - - // These are constantly getting regenerated so don't bother with them here - ExcludeItemTypes = new[] { typeof(LiveTvProgram).Name } + IsCurrentSchema = false }); var numComplete = 0; @@ -85,27 +152,25 @@ namespace MediaBrowser.Server.Implementations.Persistence { cancellationToken.ThrowIfCancellationRequested(); - if (itemId == Guid.Empty) + if (itemId != Guid.Empty) { // Somehow some invalid data got into the db. It probably predates the boundary checking - continue; - } - - var item = _libraryManager.GetItemById(itemId); + var item = _libraryManager.GetItemById(itemId); - if (item != null) - { - try - { - await _itemRepo.SaveItem(item, cancellationToken).ConfigureAwait(false); - } - catch (OperationCanceledException) - { - throw; - } - catch (Exception ex) + if (item != null) { - _logger.ErrorException("Error saving item", ex); + try + { + await _itemRepo.SaveItem(item, cancellationToken).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) + { + _logger.ErrorException("Error saving item", ex); + } } } @@ -115,12 +180,6 @@ namespace MediaBrowser.Server.Implementations.Persistence progress.Report(percent * 100); } - if (!_config.Configuration.DisableStartupScan) - { - _config.Configuration.DisableStartupScan = true; - _config.SaveConfiguration(); - } - progress.Report(100); } @@ -146,10 +205,11 @@ namespace MediaBrowser.Server.Implementations.Persistence { _logger.Info("Cleaning item {0} type: {1} path: {2}", item.Name, item.GetType().Name, item.Path ?? string.Empty); - await _libraryManager.DeleteItem(item, new DeleteOptions + await item.Delete(new DeleteOptions { DeleteFileLocation = false - }); + + }).ConfigureAwait(false); } numComplete++; @@ -165,12 +225,22 @@ namespace MediaBrowser.Server.Implementations.Persistence { var result = _itemRepo.GetItemIdsWithPath(new InternalItemsQuery { - IsOffline = false, LocationType = LocationType.FileSystem, //Limit = limit, // These have their own cleanup routines - ExcludeItemTypes = new[] { typeof(Person).Name, typeof(Genre).Name, typeof(MusicGenre).Name, typeof(GameGenre).Name, typeof(Studio).Name, typeof(Year).Name } + ExcludeItemTypes = new[] + { + typeof(Person).Name, + typeof(Genre).Name, + typeof(MusicGenre).Name, + typeof(GameGenre).Name, + typeof(Studio).Name, + typeof(Year).Name, + typeof(Channel).Name, + typeof(AggregateFolder).Name, + typeof(CollectionFolder).Name + } }); var numComplete = 0; @@ -191,6 +261,11 @@ namespace MediaBrowser.Server.Implementations.Persistence var libraryItem = _libraryManager.GetItemById(item.Item1); + if (libraryItem.IsTopParent) + { + continue; + } + if (Folder.IsPathOffline(path)) { libraryItem.IsOffline = true; @@ -200,10 +275,11 @@ namespace MediaBrowser.Server.Implementations.Persistence _logger.Info("Deleting item from database {0} because path no longer exists. type: {1} path: {2}", libraryItem.Name, libraryItem.GetType().Name, libraryItem.Path ?? string.Empty); - await _libraryManager.DeleteItem(libraryItem, new DeleteOptions + await libraryItem.Delete(new DeleteOptions { DeleteFileLocation = false - }); + + }).ConfigureAwait(false); } catch (OperationCanceledException) { @@ -229,4 +305,4 @@ namespace MediaBrowser.Server.Implementations.Persistence }; } } -} +}
\ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/Persistence/MediaStreamColumns.cs b/MediaBrowser.Server.Implementations/Persistence/MediaStreamColumns.cs index f54e702d6..7e46db5a7 100644 --- a/MediaBrowser.Server.Implementations/Persistence/MediaStreamColumns.cs +++ b/MediaBrowser.Server.Implementations/Persistence/MediaStreamColumns.cs @@ -27,6 +27,70 @@ namespace MediaBrowser.Server.Implementations.Persistence AddIsCabacColumn(); AddKeyFramesColumn(); AddRefFramesCommand(); + AddCodecTagColumn(); + AddCommentColumn(); + } + + private void AddCommentColumn() + { + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = "PRAGMA table_info(mediastreams)"; + + using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)) + { + while (reader.Read()) + { + if (!reader.IsDBNull(1)) + { + var name = reader.GetString(1); + + if (string.Equals(name, "Comment", StringComparison.OrdinalIgnoreCase)) + { + return; + } + } + } + } + } + + var builder = new StringBuilder(); + + builder.AppendLine("alter table mediastreams"); + builder.AppendLine("add column Comment TEXT"); + + _connection.RunQueries(new[] { builder.ToString() }, _logger); + } + + private void AddCodecTagColumn() + { + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = "PRAGMA table_info(mediastreams)"; + + using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)) + { + while (reader.Read()) + { + if (!reader.IsDBNull(1)) + { + var name = reader.GetString(1); + + if (string.Equals(name, "CodecTag", StringComparison.OrdinalIgnoreCase)) + { + return; + } + } + } + } + } + + var builder = new StringBuilder(); + + builder.AppendLine("alter table mediastreams"); + builder.AppendLine("add column CodecTag TEXT"); + + _connection.RunQueries(new[] { builder.ToString() }, _logger); } private void AddPixelFormatColumnCommand() diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index dc6241362..346dcf359 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -19,18 +19,17 @@ using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Channels; +using MediaBrowser.Model.LiveTv; namespace MediaBrowser.Server.Implementations.Persistence { /// <summary> /// Class SQLiteItemRepository /// </summary> - public class SqliteItemRepository : IItemRepository + public class SqliteItemRepository : BaseSqliteRepository, IItemRepository { private IDbConnection _connection; - private readonly ILogger _logger; - private readonly TypeMapper _typeMapper = new TypeMapper(); /// <summary> @@ -76,7 +75,12 @@ namespace MediaBrowser.Server.Implementations.Persistence private IDbCommand _deleteStreamsCommand; private IDbCommand _saveStreamCommand; - private const int LatestSchemaVersion = 13; + private IDbCommand _deleteAncestorsCommand; + private IDbCommand _saveAncestorCommand; + + private IDbCommand _updateInheritedRatingCommand; + + private const int LatestSchemaVersion = 45; /// <summary> /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class. @@ -90,6 +94,7 @@ namespace MediaBrowser.Server.Implementations.Persistence /// jsonSerializer /// </exception> public SqliteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager) + : base(logManager) { if (appPaths == null) { @@ -104,8 +109,6 @@ namespace MediaBrowser.Server.Implementations.Persistence _jsonSerializer = jsonSerializer; _criticReviewsPath = Path.Combine(_appPaths.DataPath, "critic-reviews"); - - _logger = logManager.GetLogger(GetType().Name); } private const string ChaptersTableName = "Chapters2"; @@ -118,20 +121,27 @@ namespace MediaBrowser.Server.Implementations.Persistence { var dbFile = Path.Combine(_appPaths.DataPath, "library.db"); - _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false); + _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false); var createMediaStreamsTableCommand - = "create table if not exists mediastreams (ItemId GUID, StreamIndex INT, StreamType TEXT, Codec TEXT, Language TEXT, ChannelLayout TEXT, Profile TEXT, AspectRatio TEXT, Path TEXT, IsInterlaced BIT, BitRate INT NULL, Channels INT NULL, SampleRate INT NULL, IsDefault BIT, IsForced BIT, IsExternal BIT, Height INT NULL, Width INT NULL, AverageFrameRate FLOAT NULL, RealFrameRate FLOAT NULL, Level FLOAT NULL, PixelFormat TEXT, BitDepth INT NULL, IsAnamorphic BIT NULL, RefFrames INT NULL, IsCabac BIT NULL, KeyFrames TEXT NULL, PRIMARY KEY (ItemId, StreamIndex))"; + = "create table if not exists mediastreams (ItemId GUID, StreamIndex INT, StreamType TEXT, Codec TEXT, Language TEXT, ChannelLayout TEXT, Profile TEXT, AspectRatio TEXT, Path TEXT, IsInterlaced BIT, BitRate INT NULL, Channels INT NULL, SampleRate INT NULL, IsDefault BIT, IsForced BIT, IsExternal BIT, Height INT NULL, Width INT NULL, AverageFrameRate FLOAT NULL, RealFrameRate FLOAT NULL, Level FLOAT NULL, PixelFormat TEXT, BitDepth INT NULL, IsAnamorphic BIT NULL, RefFrames INT NULL, IsCabac BIT NULL, CodecTag TEXT NULL, Comment TEXT NULL, PRIMARY KEY (ItemId, StreamIndex))"; string[] queries = { - "create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB)", + "create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB, ParentId GUID)", "create index if not exists idx_TypedBaseItems on TypedBaseItems(guid)", + "create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)", + "create table if not exists AncestorIds (ItemId GUID, AncestorId GUID, AncestorIdText TEXT, PRIMARY KEY (ItemId, AncestorId))", + "create index if not exists idx_AncestorIds1 on AncestorIds(AncestorId)", + "create index if not exists idx_AncestorIds2 on AncestorIds(AncestorIdText)", + "create table if not exists ChildrenIds (ParentId GUID, ItemId GUID, PRIMARY KEY (ParentId, ItemId))", "create index if not exists idx_ChildrenIds on ChildrenIds(ParentId,ItemId)", "create table if not exists People (ItemId GUID, Name TEXT NOT NULL, Role TEXT, PersonType TEXT, SortOrder int, ListOrder int)", + "create index if not exists idxPeopleItemId on People(ItemId)", + "create index if not exists idxPeopleName on People(Name)", "create table if not exists "+ChaptersTableName+" (ItemId GUID, ChapterIndex INT, StartPositionTicks BIGINT, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))", "create index if not exists idx_"+ChaptersTableName+" on "+ChaptersTableName+"(ItemId, ChapterIndex)", @@ -145,62 +155,77 @@ namespace MediaBrowser.Server.Implementations.Persistence "pragma shrink_memory" }; - _connection.RunQueries(queries, _logger); - - _connection.AddColumn(_logger, "TypedBaseItems", "Path", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "StartDate", "DATETIME"); - _connection.AddColumn(_logger, "TypedBaseItems", "EndDate", "DATETIME"); - _connection.AddColumn(_logger, "TypedBaseItems", "ChannelId", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsMovie", "BIT"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsSports", "BIT"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsKids", "BIT"); - _connection.AddColumn(_logger, "TypedBaseItems", "CommunityRating", "Float"); - _connection.AddColumn(_logger, "TypedBaseItems", "CustomRating", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "IndexNumber", "INT"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsLocked", "BIT"); - _connection.AddColumn(_logger, "TypedBaseItems", "Name", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "OfficialRating", "Text"); - - _connection.AddColumn(_logger, "TypedBaseItems", "MediaType", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "Overview", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "ParentIndexNumber", "INT"); - _connection.AddColumn(_logger, "TypedBaseItems", "PremiereDate", "DATETIME"); - _connection.AddColumn(_logger, "TypedBaseItems", "ProductionYear", "INT"); - _connection.AddColumn(_logger, "TypedBaseItems", "ParentId", "GUID"); - _connection.AddColumn(_logger, "TypedBaseItems", "Genres", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "ParentalRatingValue", "INT"); - _connection.AddColumn(_logger, "TypedBaseItems", "SchemaVersion", "INT"); - _connection.AddColumn(_logger, "TypedBaseItems", "SortName", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "RunTimeTicks", "BIGINT"); - - _connection.AddColumn(_logger, "TypedBaseItems", "OfficialRatingDescription", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "HomePageUrl", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "VoteCount", "INT"); - _connection.AddColumn(_logger, "TypedBaseItems", "DisplayMediaType", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "DateCreated", "DATETIME"); - _connection.AddColumn(_logger, "TypedBaseItems", "DateModified", "DATETIME"); - - _connection.AddColumn(_logger, "TypedBaseItems", "ForcedSortName", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsOffline", "BIT"); - _connection.AddColumn(_logger, "TypedBaseItems", "LocationType", "Text"); - - _connection.AddColumn(_logger, "TypedBaseItems", "IsSeries", "BIT"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsLive", "BIT"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsNews", "BIT"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsPremiere", "BIT"); - - _connection.AddColumn(_logger, "TypedBaseItems", "EpisodeTitle", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsRepeat", "BIT"); - - _connection.AddColumn(_logger, "TypedBaseItems", "PreferredMetadataLanguage", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "PreferredMetadataCountryCode", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "IsHD", "BIT"); - _connection.AddColumn(_logger, "TypedBaseItems", "ExternalEtag", "Text"); - _connection.AddColumn(_logger, "TypedBaseItems", "DateLastRefreshed", "DATETIME"); + _connection.RunQueries(queries, Logger); + + _connection.AddColumn(Logger, "AncestorIds", "AncestorIdText", "Text"); + + _connection.AddColumn(Logger, "TypedBaseItems", "Path", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "StartDate", "DATETIME"); + _connection.AddColumn(Logger, "TypedBaseItems", "EndDate", "DATETIME"); + _connection.AddColumn(Logger, "TypedBaseItems", "ChannelId", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsMovie", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsSports", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsKids", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "CommunityRating", "Float"); + _connection.AddColumn(Logger, "TypedBaseItems", "CustomRating", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "IndexNumber", "INT"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsLocked", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "Name", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "OfficialRating", "Text"); + + _connection.AddColumn(Logger, "TypedBaseItems", "MediaType", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "Overview", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "ParentIndexNumber", "INT"); + _connection.AddColumn(Logger, "TypedBaseItems", "PremiereDate", "DATETIME"); + _connection.AddColumn(Logger, "TypedBaseItems", "ProductionYear", "INT"); + _connection.AddColumn(Logger, "TypedBaseItems", "ParentId", "GUID"); + _connection.AddColumn(Logger, "TypedBaseItems", "Genres", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "ParentalRatingValue", "INT"); + _connection.AddColumn(Logger, "TypedBaseItems", "SchemaVersion", "INT"); + _connection.AddColumn(Logger, "TypedBaseItems", "SortName", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "RunTimeTicks", "BIGINT"); + + _connection.AddColumn(Logger, "TypedBaseItems", "OfficialRatingDescription", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "HomePageUrl", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "VoteCount", "INT"); + _connection.AddColumn(Logger, "TypedBaseItems", "DisplayMediaType", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "DateCreated", "DATETIME"); + _connection.AddColumn(Logger, "TypedBaseItems", "DateModified", "DATETIME"); + + _connection.AddColumn(Logger, "TypedBaseItems", "ForcedSortName", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsOffline", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "LocationType", "Text"); + + _connection.AddColumn(Logger, "TypedBaseItems", "IsSeries", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsLive", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsNews", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsPremiere", "BIT"); + + _connection.AddColumn(Logger, "TypedBaseItems", "EpisodeTitle", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsRepeat", "BIT"); + + _connection.AddColumn(Logger, "TypedBaseItems", "PreferredMetadataLanguage", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "PreferredMetadataCountryCode", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsHD", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "ExternalEtag", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "DateLastRefreshed", "DATETIME"); + + _connection.AddColumn(Logger, "TypedBaseItems", "DateLastSaved", "DATETIME"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsInMixedFolder", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "LockedFields", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "Studios", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "Audio", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "ExternalServiceId", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "Tags", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsFolder", "BIT"); + _connection.AddColumn(Logger, "TypedBaseItems", "InheritedParentalRatingValue", "INT"); + _connection.AddColumn(Logger, "TypedBaseItems", "UnratedType", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "TopParentId", "Text"); + _connection.AddColumn(Logger, "TypedBaseItems", "IsItemByName", "BIT"); PrepareStatements(); - new MediaStreamColumns(_connection, _logger).AddColumns(); + new MediaStreamColumns(_connection, Logger).AddColumns(); var chapterDbFile = Path.Combine(_appPaths.DataPath, "chapters.db"); if (File.Exists(chapterDbFile)) @@ -229,11 +254,11 @@ namespace MediaBrowser.Server.Implementations.Persistence "REPLACE INTO mediastreams("+columns+") SELECT "+columns+" FROM MediaInfoOld.mediastreams;" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); } catch (Exception ex) { - _logger.ErrorException("Error migrating media info database", ex); + Logger.ErrorException("Error migrating media info database", ex); } finally { @@ -253,11 +278,11 @@ namespace MediaBrowser.Server.Implementations.Persistence "REPLACE INTO "+ChaptersTableName+"(ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath) SELECT ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath FROM ChaptersOld.Chapters;" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); } catch (Exception ex) { - _logger.ErrorException("Error migrating chapter database", ex); + Logger.ErrorException("Error migrating chapter database", ex); } finally { @@ -273,15 +298,10 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception ex) { - _logger.ErrorException("Error deleting file {0}", ex, file); + Logger.ErrorException("Error deleting file {0}", ex, file); } } - /// <summary> - /// The _write lock - /// </summary> - private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); - private readonly string[] _retriveItemColumns = { "type", @@ -307,7 +327,27 @@ namespace MediaBrowser.Server.Implementations.Persistence "PreferredMetadataCountryCode", "IsHD", "ExternalEtag", - "DateLastRefreshed" + "DateLastRefreshed", + "Name", + "Path", + "PremiereDate", + "Overview", + "ParentIndexNumber", + "ProductionYear", + "OfficialRating", + "OfficialRatingDescription", + "HomePageUrl", + "DisplayMediaType", + "ForcedSortName", + "RunTimeTicks", + "VoteCount", + "DateCreated", + "DateModified", + "guid", + "Genres", + "ParentId", + "Audio", + "ExternalServiceId" }; private readonly string[] _mediaStreamSaveColumns = @@ -338,7 +378,8 @@ namespace MediaBrowser.Server.Implementations.Persistence "IsAnamorphic", "RefFrames", "IsCabac", - "KeyFrames" + "CodecTag", + "Comment" }; /// <summary> @@ -378,6 +419,7 @@ namespace MediaBrowser.Server.Implementations.Persistence "ParentId", "Genres", "ParentalRatingValue", + "InheritedParentalRatingValue", "SchemaVersion", "SortName", "RunTimeTicks", @@ -394,7 +436,18 @@ namespace MediaBrowser.Server.Implementations.Persistence "PreferredMetadataCountryCode", "IsHD", "ExternalEtag", - "DateLastRefreshed" + "DateLastRefreshed", + "DateLastSaved", + "IsInMixedFolder", + "LockedFields", + "Studios", + "Audio", + "ExternalServiceId", + "Tags", + "IsFolder", + "UnratedType", + "TopParentId", + "IsItemByName" }; _saveItemCommand = _connection.CreateCommand(); _saveItemCommand.CommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns.ToArray()) + ") values ("; @@ -438,6 +491,17 @@ namespace MediaBrowser.Server.Implementations.Persistence _savePersonCommand.Parameters.Add(_savePersonCommand, "@SortOrder"); _savePersonCommand.Parameters.Add(_savePersonCommand, "@ListOrder"); + // Ancestors + _deleteAncestorsCommand = _connection.CreateCommand(); + _deleteAncestorsCommand.CommandText = "delete from AncestorIds where ItemId=@Id"; + _deleteAncestorsCommand.Parameters.Add(_deleteAncestorsCommand, "@Id"); + + _saveAncestorCommand = _connection.CreateCommand(); + _saveAncestorCommand.CommandText = "insert into AncestorIds (ItemId, AncestorId, AncestorIdText) values (@ItemId, @AncestorId, @AncestorIdText)"; + _saveAncestorCommand.Parameters.Add(_saveAncestorCommand, "@ItemId"); + _saveAncestorCommand.Parameters.Add(_saveAncestorCommand, "@AncestorId"); + _saveAncestorCommand.Parameters.Add(_saveAncestorCommand, "@AncestorIdText"); + // Chapters _deleteChaptersCommand = _connection.CreateCommand(); _deleteChaptersCommand.CommandText = "delete from " + ChaptersTableName + " where ItemId=@ItemId"; @@ -467,6 +531,11 @@ namespace MediaBrowser.Server.Implementations.Persistence { _saveStreamCommand.Parameters.Add(_saveStreamCommand, "@" + col); } + + _updateInheritedRatingCommand = _connection.CreateCommand(); + _updateInheritedRatingCommand.CommandText = "Update TypedBaseItems set InheritedParentalRatingValue=@InheritedParentalRatingValue where Guid=@Guid"; + _updateInheritedRatingCommand.Parameters.Add(_updateInheritedRatingCommand, "@InheritedParentalRatingValue"); + _updateInheritedRatingCommand.Parameters.Add(_updateInheritedRatingCommand, "@Guid"); } /// <summary> @@ -508,7 +577,7 @@ namespace MediaBrowser.Server.Implementations.Persistence CheckDisposed(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -592,7 +661,8 @@ namespace MediaBrowser.Server.Implementations.Persistence } _saveItemCommand.GetParameter(index++).Value = string.Join("|", item.Genres.ToArray()); - _saveItemCommand.GetParameter(index++).Value = item.GetParentalRatingValue(); + _saveItemCommand.GetParameter(index++).Value = item.GetParentalRatingValue() ?? 0; + _saveItemCommand.GetParameter(index++).Value = item.GetInheritedParentalRatingValue() ?? 0; _saveItemCommand.GetParameter(index++).Value = LatestSchemaVersion; _saveItemCommand.GetParameter(index++).Value = item.SortName; @@ -623,9 +693,62 @@ namespace MediaBrowser.Server.Implementations.Persistence _saveItemCommand.GetParameter(index++).Value = item.DateLastRefreshed; } + _saveItemCommand.GetParameter(index++).Value = item.DateLastSaved; + _saveItemCommand.GetParameter(index++).Value = item.IsInMixedFolder; + _saveItemCommand.GetParameter(index++).Value = string.Join("|", item.LockedFields.Select(i => i.ToString()).ToArray()); + _saveItemCommand.GetParameter(index++).Value = string.Join("|", item.Studios.ToArray()); + + if (item.Audio.HasValue) + { + _saveItemCommand.GetParameter(index++).Value = item.Audio.Value.ToString(); + } + else + { + _saveItemCommand.GetParameter(index++).Value = null; + } + + var tvItem = item as ILiveTvItem; + if (tvItem != null) + { + _saveItemCommand.GetParameter(index++).Value = tvItem.ServiceName; + } + else + { + _saveItemCommand.GetParameter(index++).Value = null; + } + + _saveItemCommand.GetParameter(index++).Value = string.Join("|", item.Tags.ToArray()); + _saveItemCommand.GetParameter(index++).Value = item.IsFolder; + + _saveItemCommand.GetParameter(index++).Value = item.GetBlockUnratedType().ToString(); + + var topParent = item.GetTopParent(); + if (topParent != null) + { + _saveItemCommand.GetParameter(index++).Value = topParent.Id.ToString("N"); + } + else + { + _saveItemCommand.GetParameter(index++).Value = null; + } + + var isByName = false; + var byName = item as IItemByName; + if (byName != null) + { + var dualAccess = item as IHasDualAccess; + isByName = dualAccess == null || dualAccess.IsAccessedByName; + } + _saveItemCommand.GetParameter(index++).Value = isByName; + _saveItemCommand.Transaction = transaction; _saveItemCommand.ExecuteNonQuery(); + + if (item.SupportsAncestors) + { + UpdateAncestors(item.Id, item.GetAncestorIds().Distinct().ToList(), transaction); + } } transaction.Commit(); @@ -641,7 +764,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save items:", e); + Logger.ErrorException("Failed to save items:", e); if (transaction != null) { @@ -657,7 +780,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -701,27 +824,37 @@ namespace MediaBrowser.Server.Implementations.Persistence if (type == null) { - _logger.Debug("Unknown type {0}", typeString); + Logger.Debug("Unknown type {0}", typeString); return null; } - BaseItem item; + BaseItem item = null; using (var stream = reader.GetMemoryStream(1)) { try { item = _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem; + } + catch (SerializationException ex) + { + Logger.ErrorException("Error deserializing item", ex); + } - if (item == null) + if (item == null) + { + try + { + item = Activator.CreateInstance(type) as BaseItem; + } + catch { - return null; } } - catch (SerializationException ex) + + if (item == null) { - _logger.ErrorException("Error deserializing item", ex); return null; } } @@ -844,6 +977,107 @@ namespace MediaBrowser.Server.Implementations.Persistence item.DateLastRefreshed = reader.GetDateTime(23).ToUniversalTime(); } + if (!reader.IsDBNull(24)) + { + item.Name = reader.GetString(24); + } + + if (!reader.IsDBNull(25)) + { + item.Path = reader.GetString(25); + } + + if (!reader.IsDBNull(26)) + { + item.PremiereDate = reader.GetDateTime(26).ToUniversalTime(); + } + + if (!reader.IsDBNull(27)) + { + item.Overview = reader.GetString(27); + } + + if (!reader.IsDBNull(28)) + { + item.ParentIndexNumber = reader.GetInt32(28); + } + + if (!reader.IsDBNull(29)) + { + item.ProductionYear = reader.GetInt32(29); + } + + if (!reader.IsDBNull(30)) + { + item.OfficialRating = reader.GetString(30); + } + + if (!reader.IsDBNull(31)) + { + item.OfficialRating = reader.GetString(31); + } + + if (!reader.IsDBNull(32)) + { + item.HomePageUrl = reader.GetString(32); + } + + if (!reader.IsDBNull(33)) + { + item.DisplayMediaType = reader.GetString(33); + } + + if (!reader.IsDBNull(34)) + { + item.ForcedSortName = reader.GetString(34); + } + + if (!reader.IsDBNull(35)) + { + item.RunTimeTicks = reader.GetInt64(35); + } + + if (!reader.IsDBNull(36)) + { + item.VoteCount = reader.GetInt32(36); + } + + if (!reader.IsDBNull(37)) + { + item.DateCreated = reader.GetDateTime(37).ToUniversalTime(); + } + + if (!reader.IsDBNull(38)) + { + item.DateModified = reader.GetDateTime(38).ToUniversalTime(); + } + + item.Id = reader.GetGuid(39); + + if (!reader.IsDBNull(40)) + { + item.Genres = reader.GetString(40).Split('|').Where(i => !string.IsNullOrWhiteSpace(i)).ToList(); + } + + if (!reader.IsDBNull(41)) + { + item.ParentId = reader.GetGuid(41); + } + + if (!reader.IsDBNull(42)) + { + item.Audio = (ProgramAudio)Enum.Parse(typeof(ProgramAudio), reader.GetString(42), true); + } + + if (!reader.IsDBNull(43)) + { + var tvItem = item as ILiveTvItem; + if (tvItem != null) + { + tvItem.ServiceName = reader.GetString(43); + } + } + return item; } @@ -1006,7 +1240,7 @@ namespace MediaBrowser.Server.Implementations.Persistence cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -1053,7 +1287,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save chapters:", e); + Logger.ErrorException("Failed to save chapters:", e); if (transaction != null) { @@ -1069,62 +1303,21 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } - /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// </summary> - public void Dispose() + protected override void CloseConnection() { - Dispose(true); - GC.SuppressFinalize(this); - } - - private readonly object _disposeLock = new object(); - - private bool _disposed; - private void CheckDisposed() - { - if (_disposed) - { - throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed."); - } - } - - /// <summary> - /// Releases unmanaged and - optionally - managed resources. - /// </summary> - /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool dispose) - { - if (dispose) + if (_connection != null) { - _disposed = true; - - try - { - lock (_disposeLock) - { - _writeLock.Wait(); - - if (_connection != null) - { - if (_connection.IsOpen()) - { - _connection.Close(); - } - - _connection.Dispose(); - _connection = null; - } - } - } - catch (Exception ex) + if (_connection.IsOpen()) { - _logger.ErrorException("Error disposing database", ex); + _connection.Close(); } + + _connection.Dispose(); + _connection = null; } } @@ -1168,6 +1361,8 @@ namespace MediaBrowser.Server.Implementations.Persistence cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId; + //Logger.Debug(cmd.CommandText); + using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)) { while (reader.Read()) @@ -1213,6 +1408,50 @@ namespace MediaBrowser.Server.Implementations.Persistence } } + public IEnumerable<BaseItem> GetItemList(InternalItemsQuery query) + { + if (query == null) + { + throw new ArgumentNullException("query"); + } + + CheckDisposed(); + + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = "select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems"; + + var whereClauses = GetWhereClauses(query, cmd, true); + + var whereText = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + cmd.CommandText += whereText; + + cmd.CommandText += GetOrderByText(query); + + if (query.Limit.HasValue) + { + cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(CultureInfo.InvariantCulture); + } + + //Logger.Debug(cmd.CommandText); + + using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)) + { + while (reader.Read()) + { + var item = GetItem(reader); + if (item != null) + { + yield return item; + } + } + } + } + } + public QueryResult<BaseItem> GetItems(InternalItemsQuery query) { if (query == null) @@ -1249,7 +1488,7 @@ namespace MediaBrowser.Server.Implementations.Persistence cmd.CommandText += "; select count (guid) from TypedBaseItems" + whereTextWithoutPaging; - _logger.Debug(cmd.CommandText); + Logger.Debug(cmd.CommandText); var list = new List<BaseItem>(); var count = 0; @@ -1293,6 +1532,12 @@ namespace MediaBrowser.Server.Implementations.Persistence private string MapOrderByField(string name) { + if (string.Equals(name, "airtime", StringComparison.OrdinalIgnoreCase)) + { + // TODO + return "SortName"; + } + return name; } @@ -1326,9 +1571,9 @@ namespace MediaBrowser.Server.Implementations.Persistence var list = new List<Guid>(); - _logger.Debug(cmd.CommandText); + Logger.Debug(cmd.CommandText); - using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) + using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)) { while (reader.Read()) { @@ -1379,7 +1624,7 @@ namespace MediaBrowser.Server.Implementations.Persistence var list = new List<Tuple<Guid, string>>(); var count = 0; - _logger.Debug(cmd.CommandText); + Logger.Debug(cmd.CommandText); using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { @@ -1448,7 +1693,7 @@ namespace MediaBrowser.Server.Implementations.Persistence var list = new List<Guid>(); var count = 0; - _logger.Debug(cmd.CommandText); + Logger.Debug(cmd.CommandText); using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess)) { @@ -1512,6 +1757,11 @@ namespace MediaBrowser.Server.Implementations.Persistence whereClauses.Add("IsSports=@IsSports"); cmd.Parameters.Add(cmd, "@IsSports", DbType.Boolean).Value = query.IsSports; } + if (query.IsFolder.HasValue) + { + whereClauses.Add("IsFolder=@IsFolder"); + cmd.Parameters.Add(cmd, "@IsFolder", DbType.Boolean).Value = query.IsFolder; + } var includeTypes = query.IncludeItemTypes.SelectMany(MapIncludeItemTypes).ToArray(); if (includeTypes.Length == 1) @@ -1572,6 +1822,12 @@ namespace MediaBrowser.Server.Implementations.Persistence cmd.Parameters.Add(cmd, "@MinStartDate", DbType.Date).Value = query.MinStartDate.Value; } + if (query.MinPremiereDate.HasValue) + { + whereClauses.Add("PremiereDate>=@MinPremiereDate"); + cmd.Parameters.Add(cmd, "@MinPremiereDate", DbType.Date).Value = query.MinPremiereDate.Value; + } + if (query.MaxStartDate.HasValue) { whereClauses.Add("StartDate<=@MaxStartDate"); @@ -1623,7 +1879,7 @@ namespace MediaBrowser.Server.Implementations.Persistence if (query.MaxParentalRating.HasValue) { - whereClauses.Add("(ParentalRatingValue is NULL OR ParentalRatingValue<=@MaxParentalRating)"); + whereClauses.Add("InheritedParentalRatingValue<=@MaxParentalRating"); cmd.Parameters.Add(cmd, "@MaxParentalRating", DbType.Int32).Value = query.MaxParentalRating.Value; } @@ -1631,11 +1887,11 @@ namespace MediaBrowser.Server.Implementations.Persistence { if (query.HasParentalRating.Value) { - whereClauses.Add("ParentalRatingValue NOT NULL"); + whereClauses.Add("InheritedParentalRatingValue > 0"); } else { - whereClauses.Add("ParentalRatingValue IS NULL"); + whereClauses.Add("InheritedParentalRatingValue = 0"); } } @@ -1646,7 +1902,78 @@ namespace MediaBrowser.Server.Implementations.Persistence whereClauses.Add("ParentId NOT NULL AND ParentId NOT IN (select guid from TypedBaseItems)"); } } + if (query.ExcludeLocationTypes.Length == 1) + { + whereClauses.Add("LocationType<>@LocationType"); + cmd.Parameters.Add(cmd, "@LocationType", DbType.String).Value = query.ExcludeLocationTypes[0].ToString(); + } + if (query.ExcludeLocationTypes.Length > 1) + { + var val = string.Join(",", query.ExcludeLocationTypes.Select(i => "'" + i + "'").ToArray()); + whereClauses.Add("LocationType not in (" + val + ")"); + } + + var enableItemsByName = query.IncludeItemsByName ?? query.IncludeItemTypes.Length > 0; + + if (query.TopParentIds.Length == 1) + { + if (enableItemsByName) + { + whereClauses.Add("(TopParentId=@TopParentId or IsItemByName=@IsItemByName)"); + cmd.Parameters.Add(cmd, "@IsItemByName", DbType.Boolean).Value = true; + } + else + { + whereClauses.Add("(TopParentId=@TopParentId)"); + } + cmd.Parameters.Add(cmd, "@TopParentId", DbType.String).Value = query.TopParentIds[0]; + } + if (query.TopParentIds.Length > 1) + { + var val = string.Join(",", query.TopParentIds.Select(i => "'" + i + "'").ToArray()); + + if (enableItemsByName) + { + whereClauses.Add("(IsItemByName=@IsItemByName or TopParentId in (" + val + "))"); + cmd.Parameters.Add(cmd, "@IsItemByName", DbType.Boolean).Value = true; + } + else + { + whereClauses.Add("(TopParentId in (" + val + "))"); + } + } + + if (query.AncestorIds.Length == 1) + { + whereClauses.Add("Guid in (select itemId from AncestorIds where AncestorId=@AncestorId)"); + cmd.Parameters.Add(cmd, "@AncestorId", DbType.Guid).Value = new Guid(query.AncestorIds[0]); + } + if (query.AncestorIds.Length > 1) + { + var inClause = string.Join(",", query.AncestorIds.Select(i => "'" + new Guid(i).ToString("N") + "'").ToArray()); + whereClauses.Add(string.Format("Guid in (select itemId from AncestorIds where AncestorIdText in ({0}))", inClause)); + } + + if (query.BlockUnratedItems.Length == 1) + { + whereClauses.Add("(InheritedParentalRatingValue > 0 or UnratedType <> @UnratedType)"); + cmd.Parameters.Add(cmd, "@UnratedType", DbType.String).Value = query.BlockUnratedItems[0].ToString(); + } + if (query.BlockUnratedItems.Length > 1) + { + var inClause = string.Join(",", query.BlockUnratedItems.Select(i => "'" + i.ToString() + "'").ToArray()); + whereClauses.Add(string.Format("(InheritedParentalRatingValue > 0 or UnratedType not in ({0}))", inClause)); + } + + //var excludeTagIndex = 0; + //foreach (var excludeTag in query.ExcludeTags) + //{ + // whereClauses.Add("Tags not like @excludeTag" + excludeTagIndex); + // cmd.Parameters.Add(cmd, "@excludeTag" + excludeTagIndex, DbType.String).Value = "%" + excludeTag + "%"; + // excludeTagIndex++; + //} + if (addPaging) { if (query.StartIndex.HasValue && query.StartIndex.Value > 0) @@ -1703,6 +2030,83 @@ namespace MediaBrowser.Server.Implementations.Persistence typeof(AggregateFolder) }; + public async Task UpdateInheritedValues(CancellationToken cancellationToken) + { + var newValues = new List<Tuple<Guid, int>>(); + + using (var cmd = _connection.CreateCommand()) + { + cmd.CommandText = "select Guid,InheritedParentalRatingValue,(select Max(ParentalRatingValue, (select COALESCE(MAX(ParentalRatingValue),0) from TypedBaseItems where guid in (Select AncestorId from AncestorIds where ItemId=Outer.guid)))) as NewInheritedParentalRatingValue from typedbaseitems as Outer where InheritedParentalRatingValue <> NewInheritedParentalRatingValue"; + + using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult)) + { + while (reader.Read()) + { + var id = reader.GetGuid(0); + var newValue = reader.GetInt32(2); + + newValues.Add(new Tuple<Guid, int>(id, newValue)); + } + } + } + + if (newValues.Count == 0) + { + return; + } + + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); + + IDbTransaction transaction = null; + + try + { + transaction = _connection.BeginTransaction(); + + foreach (var item in newValues) + { + _updateInheritedRatingCommand.GetParameter(0).Value = item.Item1; + _updateInheritedRatingCommand.GetParameter(1).Value = item.Item2; + + _updateInheritedRatingCommand.Transaction = transaction; + _updateInheritedRatingCommand.ExecuteNonQuery(); + + _updateInheritedRatingCommand.ExecuteNonQuery(); + } + + transaction.Commit(); + } + catch (OperationCanceledException) + { + if (transaction != null) + { + transaction.Rollback(); + } + + throw; + } + catch (Exception e) + { + Logger.ErrorException("Error running query:", e); + + if (transaction != null) + { + transaction.Rollback(); + } + + throw; + } + finally + { + if (transaction != null) + { + transaction.Dispose(); + } + + WriteLock.Release(); + } + } + private static Dictionary<string, string[]> GetTypeMapDictionary() { var dict = new Dictionary<string, string[]>(); @@ -1712,6 +2116,8 @@ namespace MediaBrowser.Server.Implementations.Persistence dict[t.Name] = new[] { t.FullName }; } + dict["ChannelItem"] = new[] { typeof(ChannelVideoItem).FullName, typeof(ChannelAudioItem).FullName, typeof(ChannelFolderItem).FullName }; + dict["LiveTvItem"] = new[] { typeof(LiveTvAudioRecording).FullName, typeof(LiveTvVideoRecording).FullName, typeof(LiveTvChannel).FullName, typeof(LiveTvProgram).FullName }; dict["Recording"] = new[] { typeof(LiveTvAudioRecording).FullName, typeof(LiveTvVideoRecording).FullName }; dict["Program"] = new[] { typeof(LiveTvProgram).FullName }; dict["TvChannel"] = new[] { typeof(LiveTvChannel).FullName }; @@ -1742,7 +2148,7 @@ namespace MediaBrowser.Server.Implementations.Persistence CheckDisposed(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -1770,11 +2176,16 @@ namespace MediaBrowser.Server.Implementations.Persistence _deleteStreamsCommand.Transaction = transaction; _deleteStreamsCommand.ExecuteNonQuery(); + // Delete ancestors + _deleteAncestorsCommand.GetParameter(0).Value = id; + _deleteAncestorsCommand.Transaction = transaction; + _deleteAncestorsCommand.ExecuteNonQuery(); + // Delete the item _deleteItemCommand.GetParameter(0).Value = id; _deleteItemCommand.Transaction = transaction; _deleteItemCommand.ExecuteNonQuery(); - + transaction.Commit(); } catch (OperationCanceledException) @@ -1788,7 +2199,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save children:", e); + Logger.ErrorException("Failed to save children:", e); if (transaction != null) { @@ -1804,7 +2215,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -1822,7 +2233,7 @@ namespace MediaBrowser.Server.Implementations.Persistence CheckDisposed(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -1861,7 +2272,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save children:", e); + Logger.ErrorException("Failed to save children:", e); if (transaction != null) { @@ -1877,7 +2288,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -2003,6 +2414,38 @@ namespace MediaBrowser.Server.Implementations.Persistence return whereClauses; } + private void UpdateAncestors(Guid itemId, List<Guid> ancestorIds, IDbTransaction transaction) + { + if (itemId == Guid.Empty) + { + throw new ArgumentNullException("itemId"); + } + + if (ancestorIds == null) + { + throw new ArgumentNullException("ancestorIds"); + } + + CheckDisposed(); + + // First delete + _deleteAncestorsCommand.GetParameter(0).Value = itemId; + _deleteAncestorsCommand.Transaction = transaction; + + _deleteAncestorsCommand.ExecuteNonQuery(); + + foreach (var ancestorId in ancestorIds) + { + _saveAncestorCommand.GetParameter(0).Value = itemId; + _saveAncestorCommand.GetParameter(1).Value = ancestorId; + _saveAncestorCommand.GetParameter(2).Value = ancestorId.ToString("N"); + + _saveAncestorCommand.Transaction = transaction; + + _saveAncestorCommand.ExecuteNonQuery(); + } + } + public async Task UpdatePeople(Guid itemId, List<PersonInfo> people) { if (itemId == Guid.Empty) @@ -2019,7 +2462,7 @@ namespace MediaBrowser.Server.Implementations.Persistence var cancellationToken = CancellationToken.None; - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -2065,7 +2508,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save people:", e); + Logger.ErrorException("Failed to save people:", e); if (transaction != null) { @@ -2081,7 +2524,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -2168,7 +2611,7 @@ namespace MediaBrowser.Server.Implementations.Persistence cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -2220,7 +2663,8 @@ namespace MediaBrowser.Server.Implementations.Persistence _saveStreamCommand.GetParameter(index++).Value = stream.RefFrames; _saveStreamCommand.GetParameter(index++).Value = stream.IsCabac; - _saveStreamCommand.GetParameter(index++).Value = null; + _saveStreamCommand.GetParameter(index++).Value = stream.CodecTag; + _saveStreamCommand.GetParameter(index++).Value = stream.Comment; _saveStreamCommand.Transaction = transaction; _saveStreamCommand.ExecuteNonQuery(); @@ -2239,7 +2683,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } catch (Exception e) { - _logger.ErrorException("Failed to save media streams:", e); + Logger.ErrorException("Failed to save media streams:", e); if (transaction != null) { @@ -2255,7 +2699,7 @@ namespace MediaBrowser.Server.Implementations.Persistence transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -2376,10 +2820,12 @@ namespace MediaBrowser.Server.Implementations.Persistence if (!reader.IsDBNull(26)) { - var frames = reader.GetString(26); - if (!string.IsNullOrWhiteSpace(frames)) - { - } + item.CodecTag = reader.GetString(26); + } + + if (!reader.IsDBNull(27)) + { + item.Comment = reader.GetString(27); } return item; diff --git a/MediaBrowser.Server.Implementations/Playlists/ManualPlaylistsFolder.cs b/MediaBrowser.Server.Implementations/Playlists/ManualPlaylistsFolder.cs index 4d3e091b1..fbf514423 100644 --- a/MediaBrowser.Server.Implementations/Playlists/ManualPlaylistsFolder.cs +++ b/MediaBrowser.Server.Implementations/Playlists/ManualPlaylistsFolder.cs @@ -34,11 +34,6 @@ namespace MediaBrowser.Server.Implementations.Playlists } } - public override bool IsHiddenFromUser(User user) - { - return false; - } - public override string CollectionType { get { return Model.Entities.CollectionType.Playlists; } diff --git a/MediaBrowser.Server.Implementations/Playlists/PlaylistImageProvider.cs b/MediaBrowser.Server.Implementations/Playlists/PlaylistImageProvider.cs index d9e9fac2a..4413a7ddf 100644 --- a/MediaBrowser.Server.Implementations/Playlists/PlaylistImageProvider.cs +++ b/MediaBrowser.Server.Implementations/Playlists/PlaylistImageProvider.cs @@ -47,7 +47,7 @@ namespace MediaBrowser.Server.Implementations.Playlists return subItem; } - var parent = subItem.Parent; + var parent = subItem.GetParent(); if (parent != null && parent.HasImage(ImageType.Primary)) { diff --git a/MediaBrowser.Server.Implementations/Playlists/PlaylistManager.cs b/MediaBrowser.Server.Implementations/Playlists/PlaylistManager.cs index d9b3ed755..048e2bf8d 100644 --- a/MediaBrowser.Server.Implementations/Playlists/PlaylistManager.cs +++ b/MediaBrowser.Server.Implementations/Playlists/PlaylistManager.cs @@ -264,6 +264,7 @@ namespace MediaBrowser.Server.Implementations.Playlists public Folder GetPlaylistsFolder(string userId) { return _libraryManager.RootFolder.Children.OfType<PlaylistsFolder>() + .FirstOrDefault() ?? _libraryManager.GetUserRootFolder().Children.OfType<PlaylistsFolder>() .FirstOrDefault(); } } diff --git a/MediaBrowser.Server.Implementations/ScheduledTasks/RefreshMediaLibraryTask.cs b/MediaBrowser.Server.Implementations/ScheduledTasks/RefreshMediaLibraryTask.cs index 2f219c299..64ae249cd 100644 --- a/MediaBrowser.Server.Implementations/ScheduledTasks/RefreshMediaLibraryTask.cs +++ b/MediaBrowser.Server.Implementations/ScheduledTasks/RefreshMediaLibraryTask.cs @@ -43,11 +43,6 @@ namespace MediaBrowser.Server.Implementations.ScheduledTasks }.ToList(); - if (!_config.Configuration.DisableStartupScan) - { - list.Add(new StartupTrigger()); - } - return list; } diff --git a/MediaBrowser.Server.Implementations/Security/AuthenticationRepository.cs b/MediaBrowser.Server.Implementations/Security/AuthenticationRepository.cs index b36db51b3..b932f0cac 100644 --- a/MediaBrowser.Server.Implementations/Security/AuthenticationRepository.cs +++ b/MediaBrowser.Server.Implementations/Security/AuthenticationRepository.cs @@ -13,19 +13,17 @@ using System.Threading.Tasks; namespace MediaBrowser.Server.Implementations.Security { - public class AuthenticationRepository : IAuthenticationRepository + public class AuthenticationRepository : BaseSqliteRepository, IAuthenticationRepository { private IDbConnection _connection; - private readonly ILogger _logger; - private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1); private readonly IServerApplicationPaths _appPaths; private readonly CultureInfo _usCulture = new CultureInfo("en-US"); private IDbCommand _saveInfoCommand; - public AuthenticationRepository(ILogger logger, IServerApplicationPaths appPaths) + public AuthenticationRepository(ILogManager logManager, IServerApplicationPaths appPaths) + : base(logManager) { - _logger = logger; _appPaths = appPaths; } @@ -33,7 +31,7 @@ namespace MediaBrowser.Server.Implementations.Security { var dbFile = Path.Combine(_appPaths.DataPath, "authentication.db"); - _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false); + _connection = await SqliteExtensions.ConnectToDb(dbFile, Logger).ConfigureAwait(false); string[] queries = { @@ -46,9 +44,9 @@ namespace MediaBrowser.Server.Implementations.Security "pragma shrink_memory" }; - _connection.RunQueries(queries, _logger); + _connection.RunQueries(queries, Logger); - _connection.AddColumn(_logger, "AccessTokens", "AppVersion", "TEXT"); + _connection.AddColumn(Logger, "AccessTokens", "AppVersion", "TEXT"); PrepareStatements(); } @@ -86,7 +84,7 @@ namespace MediaBrowser.Server.Implementations.Security cancellationToken.ThrowIfCancellationRequested(); - await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false); + await WriteLock.WaitAsync(cancellationToken).ConfigureAwait(false); IDbTransaction transaction = null; @@ -124,7 +122,7 @@ namespace MediaBrowser.Server.Implementations.Security } catch (Exception e) { - _logger.ErrorException("Failed to save record:", e); + Logger.ErrorException("Failed to save record:", e); if (transaction != null) { @@ -140,7 +138,7 @@ namespace MediaBrowser.Server.Implementations.Security transaction.Dispose(); } - _writeLock.Release(); + WriteLock.Release(); } } @@ -305,7 +303,7 @@ namespace MediaBrowser.Server.Implementations.Security { info.DeviceName = reader.GetString(5); } - + if (!reader.IsDBNull(6)) { info.UserId = reader.GetString(6); @@ -318,49 +316,21 @@ namespace MediaBrowser.Server.Implementations.Security { info.DateRevoked = reader.GetDateTime(9).ToUniversalTime(); } - - return info; - } - /// <summary> - /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. - /// </summary> - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); + return info; } - private readonly object _disposeLock = new object(); - - /// <summary> - /// Releases unmanaged and - optionally - managed resources. - /// </summary> - /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> - protected virtual void Dispose(bool dispose) + protected override void CloseConnection() { - if (dispose) + if (_connection != null) { - try + if (_connection.IsOpen()) { - lock (_disposeLock) - { - if (_connection != null) - { - if (_connection.IsOpen()) - { - _connection.Close(); - } - - _connection.Dispose(); - _connection = null; - } - } - } - catch (Exception ex) - { - _logger.ErrorException("Error disposing database", ex); + _connection.Close(); } + + _connection.Dispose(); + _connection = null; } } } diff --git a/MediaBrowser.Server.Implementations/Session/SessionManager.cs b/MediaBrowser.Server.Implementations/Session/SessionManager.cs index 8d3273421..a9ce5ba54 100644 --- a/MediaBrowser.Server.Implementations/Session/SessionManager.cs +++ b/MediaBrowser.Server.Implementations/Session/SessionManager.cs @@ -1621,17 +1621,17 @@ namespace MediaBrowser.Server.Implementations.Session if (backropItem == null) { - backropItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Backdrop)); + backropItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Backdrop)); } if (thumbItem == null) { - thumbItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Thumb)); + thumbItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Thumb)); } if (logoItem == null) { - logoItem = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Logo)); + logoItem = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Logo)); } if (thumbItem != null) diff --git a/MediaBrowser.Server.Implementations/Sorting/IsFolderComparer.cs b/MediaBrowser.Server.Implementations/Sorting/IsFolderComparer.cs index 9edbd90dc..d2341d065 100644 --- a/MediaBrowser.Server.Implementations/Sorting/IsFolderComparer.cs +++ b/MediaBrowser.Server.Implementations/Sorting/IsFolderComparer.cs @@ -33,7 +33,7 @@ namespace MediaBrowser.Server.Implementations.Sorting /// <value>The name.</value> public string Name { - get { return ItemSortBy.Album; } + get { return ItemSortBy.IsFolder; } } } } diff --git a/MediaBrowser.Server.Implementations/Sync/SyncManager.cs b/MediaBrowser.Server.Implementations/Sync/SyncManager.cs index db6a753b7..50a960956 100644 --- a/MediaBrowser.Server.Implementations/Sync/SyncManager.cs +++ b/MediaBrowser.Server.Implementations/Sync/SyncManager.cs @@ -341,7 +341,7 @@ namespace MediaBrowser.Server.Implementations.Sync if (primaryImage == null) { - var parentWithImage = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Primary)); + var parentWithImage = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Primary)); if (parentWithImage != null) { @@ -380,7 +380,7 @@ namespace MediaBrowser.Server.Implementations.Sync if (primaryImage == null) { - var parentWithImage = item.Parents.FirstOrDefault(i => i.HasImage(ImageType.Primary)); + var parentWithImage = item.GetParents().FirstOrDefault(i => i.HasImage(ImageType.Primary)); if (parentWithImage != null) { @@ -491,6 +491,11 @@ namespace MediaBrowser.Server.Implementations.Sync public bool SupportsSync(BaseItem item) { + if (item == null) + { + throw new ArgumentNullException("item"); + } + if (item is Playlist) { return true; @@ -739,10 +744,10 @@ namespace MediaBrowser.Server.Implementations.Sync var requiresSaving = false; var removeFromDevice = false; - var libraryItem = _libraryManager.GetItemById(jobItem.ItemId); - if (request.LocalItemIds.Contains(jobItem.ItemId, StringComparer.OrdinalIgnoreCase)) { + var libraryItem = _libraryManager.GetItemById(jobItem.ItemId); + var job = _repo.GetJob(jobItem.JobId); var user = _userManager.GetUserById(job.UserId); @@ -845,10 +850,10 @@ namespace MediaBrowser.Server.Implementations.Sync var requiresSaving = false; var removeFromDevice = false; - var libraryItem = _libraryManager.GetItemById(jobItem.ItemId); - if (request.SyncJobItemIds.Contains(jobItem.Id, StringComparer.OrdinalIgnoreCase)) { + var libraryItem = _libraryManager.GetItemById(jobItem.ItemId); + var job = _repo.GetJob(jobItem.JobId); var user = _userManager.GetUserById(job.UserId); diff --git a/MediaBrowser.Server.Implementations/Sync/SyncRepository.cs b/MediaBrowser.Server.Implementations/Sync/SyncRepository.cs index d266a534d..7a1f276f9 100644 --- a/MediaBrowser.Server.Implementations/Sync/SyncRepository.cs +++ b/MediaBrowser.Server.Implementations/Sync/SyncRepository.cs @@ -64,7 +64,7 @@ namespace MediaBrowser.Server.Implementations.Sync _connection.AddColumn(Logger, "SyncJobs", "Profile", "TEXT"); _connection.AddColumn(Logger, "SyncJobs", "Bitrate", "INT"); - + PrepareStatements(); } @@ -800,24 +800,6 @@ namespace MediaBrowser.Server.Implementations.Sync return item; } - private bool _disposed; - private void CheckDisposed() - { - if (_disposed) - { - throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed."); - } - } - - protected override void Dispose(bool dispose) - { - if (dispose) - { - _disposed = true; - } - base.Dispose(dispose); - } - protected override void CloseConnection() { if (_connection != null) diff --git a/MediaBrowser.Server.Implementations/Sync/SyncedMediaSourceProvider.cs b/MediaBrowser.Server.Implementations/Sync/SyncedMediaSourceProvider.cs index efd37fa00..456a1fcc1 100644 --- a/MediaBrowser.Server.Implementations/Sync/SyncedMediaSourceProvider.cs +++ b/MediaBrowser.Server.Implementations/Sync/SyncedMediaSourceProvider.cs @@ -11,6 +11,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Model.MediaInfo; namespace MediaBrowser.Server.Implementations.Sync { diff --git a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs index f34b43e43..69d1c89fe 100644 --- a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs +++ b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs @@ -36,8 +36,12 @@ namespace MediaBrowser.Server.Implementations.TV ? new string[] { } : new[] { request.ParentId }; - var items = GetAllLibraryItems(user, parentIds, i => i is Series) - .Cast<Series>(); + var items = _libraryManager.GetItems(new InternalItemsQuery(user) + { + IncludeItemTypes = new[] { typeof(Series).Name }, + SortOrder = SortOrder.Ascending + + }, parentIds).Cast<Series>(); // Avoid implicitly captured closure var episodes = GetNextUpEpisodes(request, user, items); @@ -54,9 +58,12 @@ namespace MediaBrowser.Server.Implementations.TV throw new ArgumentException("User not found"); } - var items = parentsFolders - .SelectMany(i => i.GetRecursiveChildren(user, s => s is Series)) - .Cast<Series>(); + var items = _libraryManager.GetItems(new InternalItemsQuery(user) + { + IncludeItemTypes = new[] { typeof(Series).Name }, + SortOrder = SortOrder.Ascending + + }, parentsFolders.Select(i => i.Id.ToString("N"))).Cast<Series>(); // Avoid implicitly captured closure var episodes = GetNextUpEpisodes(request, user, items); @@ -64,27 +71,6 @@ namespace MediaBrowser.Server.Implementations.TV return GetResult(episodes, null, request); } - private IEnumerable<BaseItem> GetAllLibraryItems(User user, string[] parentIds, Func<BaseItem,bool> filter) - { - if (parentIds.Length > 0) - { - return parentIds.SelectMany(i => - { - var folder = (Folder)_libraryManager.GetItemById(new Guid(i)); - - return folder.GetRecursiveChildren(user, filter); - - }); - } - - if (user == null) - { - throw new ArgumentException("User not found"); - } - - return user.RootFolder.GetRecursiveChildren(user, filter); - } - public IEnumerable<Episode> GetNextUpEpisodes(NextUpQuery request, User user, IEnumerable<Series> series) { // Avoid implicitly captured closure diff --git a/MediaBrowser.Server.Implementations/packages.config b/MediaBrowser.Server.Implementations/packages.config index c3c6e6e25..98c27786f 100644 --- a/MediaBrowser.Server.Implementations/packages.config +++ b/MediaBrowser.Server.Implementations/packages.config @@ -1,8 +1,9 @@ <?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="CommonIO" version="1.0.0.7" targetFramework="net45" />
+ <package id="Emby.XmlTv" version="1.0.0.46" targetFramework="net45" />
<package id="Interfaces.IO" version="1.0.0.5" targetFramework="net45" />
- <package id="MediaBrowser.Naming" version="1.0.0.46" targetFramework="net45" />
+ <package id="MediaBrowser.Naming" version="1.0.0.47" targetFramework="net45" />
<package id="Mono.Nat" version="1.2.24.0" targetFramework="net45" />
<package id="morelinq" version="1.4.0" targetFramework="net45" />
<package id="Patterns.Logging" version="1.0.0.2" targetFramework="net45" />
|
