From 69622a74a8c60f60d9859de8d247bcbe488e68d3 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Mon, 25 Apr 2016 23:39:21 -0400 Subject: faster cleanup of missing episodes --- MediaBrowser.Controller/Library/ILibraryManager.cs | 30 ++++++++++++---------- 1 file changed, 16 insertions(+), 14 deletions(-) (limited to 'MediaBrowser.Controller/Library/ILibraryManager.cs') diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index c8b3d5131..0f6b10b43 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -25,7 +25,7 @@ namespace MediaBrowser.Controller.Library /// The file information. /// The parent. /// BaseItem. - BaseItem ResolvePath(FileSystemMetadata fileInfo, + BaseItem ResolvePath(FileSystemMetadata fileInfo, Folder parent = null); /// @@ -36,9 +36,9 @@ namespace MediaBrowser.Controller.Library /// The parent. /// Type of the collection. /// List{``0}. - IEnumerable ResolvePaths(IEnumerable files, + IEnumerable ResolvePaths(IEnumerable files, IDirectoryService directoryService, - Folder parent, string + Folder parent, string collectionType = null); /// @@ -60,7 +60,7 @@ namespace MediaBrowser.Controller.Library /// The path. /// BaseItem. BaseItem FindByPath(string path); - + /// /// Gets the artist. /// @@ -156,7 +156,7 @@ namespace MediaBrowser.Controller.Library /// The identifier. /// BaseItem. BaseItem GetMemoryItemById(Guid id); - + /// /// Gets the intros. /// @@ -243,6 +243,8 @@ namespace MediaBrowser.Controller.Library /// BaseItem. BaseItem RetrieveItem(Guid id); + bool IsScanRunning { get; } + /// /// Occurs when [item added]. /// @@ -290,7 +292,7 @@ namespace MediaBrowser.Controller.Library /// The path. /// System.String. string GetConfiguredContentType(string path); - + /// /// Normalizes the root path list. /// @@ -332,8 +334,8 @@ namespace MediaBrowser.Controller.Library Task GetNamedView(User user, string name, string parentId, - string viewType, - string sortName, + string viewType, + string sortName, CancellationToken cancellationToken); /// @@ -346,8 +348,8 @@ namespace MediaBrowser.Controller.Library /// The cancellation token. /// Task<UserView>. Task GetNamedView(User user, - string name, - string viewType, + string name, + string viewType, string sortName, CancellationToken cancellationToken); @@ -393,7 +395,7 @@ namespace MediaBrowser.Controller.Library string viewType, string sortName, CancellationToken cancellationToken); - + /// /// Determines whether [is video file] [the specified path]. /// @@ -477,14 +479,14 @@ namespace MediaBrowser.Controller.Library /// The query. /// List<PersonInfo>. List GetPeople(InternalPeopleQuery query); - + /// /// Gets the people items. /// /// The query. /// List<Person>. List GetPeopleItems(InternalPeopleQuery query); - + /// /// Gets all people names. /// @@ -559,7 +561,7 @@ namespace MediaBrowser.Controller.Library /// The query. /// QueryResult<BaseItem>. QueryResult GetItemsResult(InternalItemsQuery query); - + /// /// Ignores the file. /// -- cgit v1.2.3 From 6c62c20a9e3081950bf46fc96966e470ffc73b54 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 27 Apr 2016 13:53:23 -0400 Subject: update CollectionFolder --- MediaBrowser.Controller/Entities/BaseItem.cs | 2 +- .../Entities/CollectionFolder.cs | 27 +++++++++++++++++++--- MediaBrowser.Controller/Library/ILibraryManager.cs | 2 +- .../IO/LibraryMonitor.cs | 2 +- .../Library/LibraryManager.cs | 5 ++-- 5 files changed, 30 insertions(+), 8 deletions(-) (limited to 'MediaBrowser.Controller/Library/ILibraryManager.cs') diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index f9f03a9c5..908d65977 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1542,7 +1542,7 @@ namespace MediaBrowser.Controller.Entities { if (!string.IsNullOrEmpty(info.Path)) { - var itemByPath = LibraryManager.FindByPath(info.Path); + var itemByPath = LibraryManager.FindByPath(info.Path, null); if (itemByPath == null) { diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs index 429700327..5e0cf6e88 100644 --- a/MediaBrowser.Controller/Entities/CollectionFolder.cs +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -8,6 +8,7 @@ using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; using CommonIO; +using MoreLinq; namespace MediaBrowser.Controller.Entities { @@ -97,7 +98,6 @@ namespace MediaBrowser.Controller.Entities } } - return base.IsValidFromResolver(newItem); } @@ -200,9 +200,30 @@ namespace MediaBrowser.Controller.Entities public IEnumerable GetPhysicalParents() { - return LibraryManager.RootFolder.Children + var rootChildren = LibraryManager.RootFolder.Children .OfType() - .Where(i => i.Path != null && PhysicalLocations.Contains(i.Path, StringComparer.OrdinalIgnoreCase)); + .ToList(); + + return PhysicalLocations.Where(i => !string.Equals(i, Path, StringComparison.OrdinalIgnoreCase)).SelectMany(i => GetPhysicalParents(i, rootChildren)).DistinctBy(i => i.Id); + } + + private IEnumerable GetPhysicalParents(string path, List rootChildren) + { + var result = rootChildren + .Where(i => string.Equals(i.Path, path, StringComparison.OrdinalIgnoreCase)) + .ToList(); + + if (result.Count == 0) + { + var folder = LibraryManager.FindByPath(path, true) as Folder; + + if (folder != null) + { + result.Add(folder); + } + } + + return result; } [IgnoreDataMember] diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 0f6b10b43..5388b8668 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -59,7 +59,7 @@ namespace MediaBrowser.Controller.Library /// /// The path. /// BaseItem. - BaseItem FindByPath(string path); + BaseItem FindByPath(string path, bool? isFolder); /// /// Gets the artist. diff --git a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs index 13a06afc2..09ca134d1 100644 --- a/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs +++ b/MediaBrowser.Server.Implementations/IO/LibraryMonitor.cs @@ -663,7 +663,7 @@ namespace MediaBrowser.Server.Implementations.IO while (item == null && !string.IsNullOrEmpty(path)) { - item = LibraryManager.FindByPath(path); + item = LibraryManager.FindByPath(path, null); path = Path.GetDirectoryName(path); } diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 17c4f59ba..e1bcfa861 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -801,11 +801,12 @@ namespace MediaBrowser.Server.Implementations.Library return _userRootFolder; } - public BaseItem FindByPath(string path) + public BaseItem FindByPath(string path, bool? isFolder) { var query = new InternalItemsQuery { - Path = path + Path = path, + IsFolder = isFolder }; // Only use the database result if there's exactly one item, otherwise we run the risk of returning old data that hasn't been cleaned yet. -- cgit v1.2.3 From 107d1fc4f136813eed648dda5d18f433ed9302e2 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 4 May 2016 12:33:22 -0400 Subject: move media path methods to core --- MediaBrowser.Api/Library/LibraryHelpers.cs | 35 ------- .../Library/LibraryStructureService.cs | 72 +------------ MediaBrowser.Controller/Library/ILibraryManager.cs | 3 + .../Library/LibraryManager.cs | 115 ++++++++++++++++++++- 4 files changed, 116 insertions(+), 109 deletions(-) (limited to 'MediaBrowser.Controller/Library/ILibraryManager.cs') diff --git a/MediaBrowser.Api/Library/LibraryHelpers.cs b/MediaBrowser.Api/Library/LibraryHelpers.cs index 46ec4f270..22a88e2bf 100644 --- a/MediaBrowser.Api/Library/LibraryHelpers.cs +++ b/MediaBrowser.Api/Library/LibraryHelpers.cs @@ -50,40 +50,5 @@ namespace MediaBrowser.Api.Library fileSystem.DeleteFile(shortcut); } } - - /// - /// Adds an additional mediaPath to an existing virtual folder, within either the default view or a user view - /// - /// The file system. - /// Name of the virtual folder. - /// The path. - /// The app paths. - public static void AddMediaPath(IFileSystem fileSystem, string virtualFolderName, string path, IServerApplicationPaths appPaths) - { - if (string.IsNullOrWhiteSpace(path)) - { - throw new ArgumentNullException("path"); - } - - if (!fileSystem.DirectoryExists(path)) - { - throw new DirectoryNotFoundException("The path does not exist."); - } - - var rootFolderPath = appPaths.DefaultUserViewsPath; - var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName); - - var shortcutFilename = fileSystem.GetFileNameWithoutExtension(path); - - var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension); - - while (fileSystem.FileExists(lnk)) - { - shortcutFilename += "1"; - lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension); - } - - fileSystem.CreateShortcut(lnk, path); - } } } diff --git a/MediaBrowser.Api/Library/LibraryStructureService.cs b/MediaBrowser.Api/Library/LibraryStructureService.cs index 244dcf09f..817fd9ce0 100644 --- a/MediaBrowser.Api/Library/LibraryStructureService.cs +++ b/MediaBrowser.Api/Library/LibraryStructureService.cs @@ -190,75 +190,7 @@ namespace MediaBrowser.Api.Library /// The request. public void Post(AddVirtualFolder request) { - if (string.IsNullOrWhiteSpace(request.Name)) - { - throw new ArgumentNullException("request"); - } - - var name = _fileSystem.GetValidFilename(request.Name); - - var rootFolderPath = _appPaths.DefaultUserViewsPath; - - var virtualFolderPath = Path.Combine(rootFolderPath, name); - while (_fileSystem.DirectoryExists(virtualFolderPath)) - { - name += "1"; - virtualFolderPath = Path.Combine(rootFolderPath, name); - } - - if (request.Paths != null) - { - var invalidpath = request.Paths.FirstOrDefault(i => !_fileSystem.DirectoryExists(i)); - if (invalidpath != null) - { - throw new ArgumentException("The specified path does not exist: " + invalidpath + "."); - } - } - - _libraryMonitor.Stop(); - - try - { - _fileSystem.CreateDirectory(virtualFolderPath); - - if (!string.IsNullOrEmpty(request.CollectionType)) - { - var path = Path.Combine(virtualFolderPath, request.CollectionType + ".collection"); - - using (File.Create(path)) - { - - } - } - - if (request.Paths != null) - { - foreach (var path in request.Paths) - { - LibraryHelpers.AddMediaPath(_fileSystem, name, path, _appPaths); - } - } - } - finally - { - Task.Run(() => - { - // No need to start if scanning the library because it will handle it - if (request.RefreshLibrary) - { - _libraryManager.ValidateMediaLibrary(new Progress(), CancellationToken.None); - } - else - { - // Need to add a delay here or directory watchers may still pick up the changes - var task = Task.Delay(1000); - // Have to block here to allow exceptions to bubble - Task.WaitAll(task); - - _libraryMonitor.Start(); - } - }); - } + _libraryManager.AddVirtualFolder(request.Name, request.CollectionType, request.Paths, request.RefreshLibrary); } /// @@ -393,7 +325,7 @@ namespace MediaBrowser.Api.Library try { - LibraryHelpers.AddMediaPath(_fileSystem, request.Name, request.Path, _appPaths); + _libraryManager.AddMediaPath(request.Name, request.Path); } finally { diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 5388b8668..07ba41b3d 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -569,5 +569,8 @@ namespace MediaBrowser.Controller.Library /// The parent. /// true if XXXX, false otherwise. bool IgnoreFile(FileSystemMetadata file, BaseItem parent); + + void AddVirtualFolder(string name, string collectionType, string[] mediaPaths, bool refreshLibrary); + void AddMediaPath(string virtualFolderName, string path); } } \ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 87fdc56b3..f6e2ddb8e 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -952,10 +952,15 @@ namespace MediaBrowser.Server.Implementations.Library if (isArtist) { - var existing = RootFolder - .GetRecursiveChildren(i => i is T && NameExtensions.AreEqual(i.Name, name)) - .Cast() - .FirstOrDefault(); + var existing = GetItemList(new InternalItemsQuery + { + IncludeItemTypes = new[] { typeof(T).Name }, + Name = name + + }).Cast() + .Where(i => !i.IsAccessedByName) + .Cast() + .FirstOrDefault(); if (existing != null) { @@ -2558,5 +2563,107 @@ namespace MediaBrowser.Server.Implementations.Library throw new InvalidOperationException(); } + + public void AddVirtualFolder(string name, string collectionType, string[] mediaPaths, bool refreshLibrary) + { + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentNullException("name"); + } + + name = _fileSystem.GetValidFilename(name); + + var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; + + var virtualFolderPath = Path.Combine(rootFolderPath, name); + while (_fileSystem.DirectoryExists(virtualFolderPath)) + { + name += "1"; + virtualFolderPath = Path.Combine(rootFolderPath, name); + } + + if (mediaPaths != null) + { + var invalidpath = mediaPaths.FirstOrDefault(i => !_fileSystem.DirectoryExists(i)); + if (invalidpath != null) + { + throw new ArgumentException("The specified path does not exist: " + invalidpath + "."); + } + } + + _libraryMonitorFactory().Stop(); + + try + { + _fileSystem.CreateDirectory(virtualFolderPath); + + if (!string.IsNullOrEmpty(collectionType)) + { + var path = Path.Combine(virtualFolderPath, collectionType + ".collection"); + + using (File.Create(path)) + { + + } + } + + if (mediaPaths != null) + { + foreach (var path in mediaPaths) + { + AddMediaPath(name, path); + } + } + } + finally + { + Task.Run(() => + { + // No need to start if scanning the library because it will handle it + if (refreshLibrary) + { + ValidateMediaLibrary(new Progress(), CancellationToken.None); + } + else + { + // Need to add a delay here or directory watchers may still pick up the changes + var task = Task.Delay(1000); + // Have to block here to allow exceptions to bubble + Task.WaitAll(task); + + _libraryMonitorFactory().Start(); + } + }); + } + } + + private const string ShortcutFileExtension = ".mblink"; + public void AddMediaPath(string virtualFolderName, string path) + { + if (string.IsNullOrWhiteSpace(path)) + { + throw new ArgumentNullException("path"); + } + + if (!_fileSystem.DirectoryExists(path)) + { + throw new DirectoryNotFoundException("The path does not exist."); + } + + var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; + var virtualFolderPath = Path.Combine(rootFolderPath, virtualFolderName); + + var shortcutFilename = _fileSystem.GetFileNameWithoutExtension(path); + + var lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension); + + while (_fileSystem.FileExists(lnk)) + { + shortcutFilename += "1"; + lnk = Path.Combine(virtualFolderPath, shortcutFilename + ShortcutFileExtension); + } + + _fileSystem.CreateShortcut(lnk, path); + } } } \ No newline at end of file -- cgit v1.2.3 From 33c002684e30f910312eef7f796e2efc0607d4a5 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Wed, 4 May 2016 16:50:47 -0400 Subject: update recording saving --- MediaBrowser.Api/Library/LibraryHelpers.cs | 54 --- .../Library/LibraryStructureService.cs | 43 +- MediaBrowser.Api/MediaBrowser.Api.csproj | 1 - MediaBrowser.Controller/Library/ILibraryManager.cs | 2 + MediaBrowser.Model/LiveTv/LiveTvOptions.cs | 4 + .../Library/LibraryManager.cs | 68 +++ .../LiveTv/EmbyTV/EmbyTV.cs | 512 +++++++++++++-------- 7 files changed, 403 insertions(+), 281 deletions(-) delete mode 100644 MediaBrowser.Api/Library/LibraryHelpers.cs (limited to 'MediaBrowser.Controller/Library/ILibraryManager.cs') diff --git a/MediaBrowser.Api/Library/LibraryHelpers.cs b/MediaBrowser.Api/Library/LibraryHelpers.cs deleted file mode 100644 index 22a88e2bf..000000000 --- a/MediaBrowser.Api/Library/LibraryHelpers.cs +++ /dev/null @@ -1,54 +0,0 @@ -using MediaBrowser.Controller; -using System; -using System.IO; -using System.Linq; -using CommonIO; - -namespace MediaBrowser.Api.Library -{ - /// - /// Class LibraryHelpers - /// - public static class LibraryHelpers - { - /// - /// The shortcut file extension - /// - private const string ShortcutFileExtension = ".mblink"; - /// - /// The shortcut file search - /// - private const string ShortcutFileSearch = "*" + ShortcutFileExtension; - - /// - /// Deletes a shortcut from within a virtual folder, within either the default view or a user view - /// - /// The file system. - /// Name of the virtual folder. - /// The media path. - /// The app paths. - /// The media folder does not exist - public static void RemoveMediaPath(IFileSystem fileSystem, string virtualFolderName, string mediaPath, IServerApplicationPaths appPaths) - { - if (string.IsNullOrWhiteSpace(mediaPath)) - { - throw new ArgumentNullException("mediaPath"); - } - - var rootFolderPath = appPaths.DefaultUserViewsPath; - var path = Path.Combine(rootFolderPath, virtualFolderName); - - if (!fileSystem.DirectoryExists(path)) - { - throw new DirectoryNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName)); - } - - var shortcut = Directory.EnumerateFiles(path, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase)); - - if (!string.IsNullOrEmpty(shortcut)) - { - fileSystem.DeleteFile(shortcut); - } - } - } -} diff --git a/MediaBrowser.Api/Library/LibraryStructureService.cs b/MediaBrowser.Api/Library/LibraryStructureService.cs index 817fd9ce0..3cf0d5d93 100644 --- a/MediaBrowser.Api/Library/LibraryStructureService.cs +++ b/MediaBrowser.Api/Library/LibraryStructureService.cs @@ -268,46 +268,7 @@ namespace MediaBrowser.Api.Library /// The request. public void Delete(RemoveVirtualFolder request) { - if (string.IsNullOrWhiteSpace(request.Name)) - { - throw new ArgumentNullException("request"); - } - - var rootFolderPath = _appPaths.DefaultUserViewsPath; - - var path = Path.Combine(rootFolderPath, request.Name); - - if (!_fileSystem.DirectoryExists(path)) - { - throw new DirectoryNotFoundException("The media folder does not exist"); - } - - _libraryMonitor.Stop(); - - try - { - _fileSystem.DeleteDirectory(path, true); - } - finally - { - Task.Run(() => - { - // No need to start if scanning the library because it will handle it - if (request.RefreshLibrary) - { - _libraryManager.ValidateMediaLibrary(new Progress(), CancellationToken.None); - } - else - { - // Need to add a delay here or directory watchers may still pick up the changes - var task = Task.Delay(1000); - // Have to block here to allow exceptions to bubble - Task.WaitAll(task); - - _libraryMonitor.Start(); - } - }); - } + _libraryManager.RemoveVirtualFolder(request.Name, request.RefreshLibrary); } /// @@ -364,7 +325,7 @@ namespace MediaBrowser.Api.Library try { - LibraryHelpers.RemoveMediaPath(_fileSystem, request.Name, request.Path, _appPaths); + _libraryManager.RemoveMediaPath(request.Name, request.Path); } finally { diff --git a/MediaBrowser.Api/MediaBrowser.Api.csproj b/MediaBrowser.Api/MediaBrowser.Api.csproj index db8961a66..77949d179 100644 --- a/MediaBrowser.Api/MediaBrowser.Api.csproj +++ b/MediaBrowser.Api/MediaBrowser.Api.csproj @@ -129,7 +129,6 @@ - diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 07ba41b3d..936b97c6e 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -571,6 +571,8 @@ namespace MediaBrowser.Controller.Library bool IgnoreFile(FileSystemMetadata file, BaseItem parent); void AddVirtualFolder(string name, string collectionType, string[] mediaPaths, bool refreshLibrary); + void RemoveVirtualFolder(string name, bool refreshLibrary); void AddMediaPath(string virtualFolderName, string path); + void RemoveMediaPath(string virtualFolderName, string path); } } \ No newline at end of file diff --git a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs index fc2b155ec..4211fbd59 100644 --- a/MediaBrowser.Model/LiveTv/LiveTvOptions.cs +++ b/MediaBrowser.Model/LiveTv/LiveTvOptions.cs @@ -7,8 +7,11 @@ namespace MediaBrowser.Model.LiveTv public int? GuideDays { get; set; } public bool EnableMovieProviders { get; set; } public string RecordingPath { get; set; } + public string MovieRecordingPath { get; set; } + public string SeriesRecordingPath { get; set; } public bool EnableAutoOrganize { get; set; } public bool EnableRecordingEncoding { get; set; } + public bool EnableRecordingSubfolders { get; set; } public bool EnableOriginalAudioWithEncodedRecordings { get; set; } public List TunerHosts { get; set; } @@ -20,6 +23,7 @@ namespace MediaBrowser.Model.LiveTv public LiveTvOptions() { EnableMovieProviders = true; + EnableRecordingSubfolders = true; TunerHosts = new List(); ListingProviders = new List(); } diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 72132c4be..95d47b380 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -2640,7 +2640,52 @@ namespace MediaBrowser.Server.Implementations.Library } } + public void RemoveVirtualFolder(string name, bool refreshLibrary) + { + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentNullException("name"); + } + + var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; + + var path = Path.Combine(rootFolderPath, name); + + if (!_fileSystem.DirectoryExists(path)) + { + throw new DirectoryNotFoundException("The media folder does not exist"); + } + + _libraryMonitorFactory().Stop(); + + try + { + _fileSystem.DeleteDirectory(path, true); + } + finally + { + Task.Run(() => + { + // No need to start if scanning the library because it will handle it + if (refreshLibrary) + { + ValidateMediaLibrary(new Progress(), CancellationToken.None); + } + else + { + // Need to add a delay here or directory watchers may still pick up the changes + var task = Task.Delay(1000); + // Have to block here to allow exceptions to bubble + Task.WaitAll(task); + + _libraryMonitorFactory().Start(); + } + }); + } + } + private const string ShortcutFileExtension = ".mblink"; + private const string ShortcutFileSearch = "*" + ShortcutFileExtension; public void AddMediaPath(string virtualFolderName, string path) { if (string.IsNullOrWhiteSpace(path)) @@ -2668,5 +2713,28 @@ namespace MediaBrowser.Server.Implementations.Library _fileSystem.CreateShortcut(lnk, path); } + + public void RemoveMediaPath(string virtualFolderName, string mediaPath) + { + if (string.IsNullOrWhiteSpace(mediaPath)) + { + throw new ArgumentNullException("mediaPath"); + } + + var rootFolderPath = ConfigurationManager.ApplicationPaths.DefaultUserViewsPath; + var path = Path.Combine(rootFolderPath, virtualFolderName); + + if (!_fileSystem.DirectoryExists(path)) + { + throw new DirectoryNotFoundException(string.Format("The media collection {0} does not exist", virtualFolderName)); + } + + var shortcut = Directory.EnumerateFiles(path, ShortcutFileSearch, SearchOption.AllDirectories).FirstOrDefault(f => _fileSystem.ResolveShortcut(f).Equals(mediaPath, StringComparison.OrdinalIgnoreCase)); + + if (!string.IsNullOrEmpty(shortcut)) + { + _fileSystem.DeleteFile(shortcut); + } + } } } \ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs index df15c38fd..c5920d3d6 100644 --- a/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs +++ b/MediaBrowser.Server.Implementations/LiveTv/EmbyTV/EmbyTV.cs @@ -26,7 +26,10 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using CommonIO; +using MediaBrowser.Common.Events; using MediaBrowser.Common.Extensions; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Power; using Microsoft.Win32; @@ -40,7 +43,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV private readonly IServerConfigurationManager _config; private readonly IJsonSerializer _jsonSerializer; - private readonly ItemDataProvider _recordingProvider; private readonly ItemDataProvider _seriesTimerProvider; private readonly TimerManager _timerProvider; @@ -56,6 +58,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV public static EmbyTV Current; + public event EventHandler DataSourceChanged; + public event EventHandler RecordingStatusChanged; + + private readonly ConcurrentDictionary _activeRecordings = + new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); + public EmbyTV(IApplicationHost appHost, ILogger logger, IJsonSerializer jsonSerializer, IHttpClient httpClient, IServerConfigurationManager config, ILiveTvManager liveTvManager, IFileSystem fileSystem, ISecurityManager security, ILibraryManager libraryManager, ILibraryMonitor libraryMonitor, IProviderManager providerManager, IFileOrganizationService organizationService, IMediaEncoder mediaEncoder, IPowerManagement powerManagement) { Current = this; @@ -74,10 +82,19 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _liveTvManager = (LiveTvManager)liveTvManager; _jsonSerializer = jsonSerializer; - _recordingProvider = new ItemDataProvider(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "recordings"), (r1, r2) => string.Equals(r1.Id, r2.Id, StringComparison.OrdinalIgnoreCase)); _seriesTimerProvider = new SeriesTimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "seriestimers")); _timerProvider = new TimerManager(fileSystem, jsonSerializer, _logger, Path.Combine(DataPath, "timers"), powerManagement, _logger); _timerProvider.TimerFired += _timerProvider_TimerFired; + + _config.NamedConfigurationUpdated += _config_NamedConfigurationUpdated; + } + + private void _config_NamedConfigurationUpdated(object sender, ConfigurationUpdateEventArgs e) + { + if (string.Equals(e.Key, "livetv", StringComparison.OrdinalIgnoreCase)) + { + OnRecordingFoldersChanged(); + } } public void Start() @@ -85,6 +102,95 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _timerProvider.RestartTimers(); SystemEvents.PowerModeChanged += SystemEvents_PowerModeChanged; + + CreateRecordingFolders(); + } + + private void OnRecordingFoldersChanged() + { + CreateRecordingFolders(); + } + + private void CreateRecordingFolders() + { + var recordingFolders = GetRecordingFolders(); + + var defaultRecordingPath = DefaultRecordingPath; + if (!recordingFolders.Any(i => i.Locations.Contains(defaultRecordingPath, StringComparer.OrdinalIgnoreCase))) + { + RemovePathFromLibrary(defaultRecordingPath); + } + + var virtualFolders = _libraryManager.GetVirtualFolders() + .ToList(); + + var allExistingPaths = virtualFolders.SelectMany(i => i.Locations).ToList(); + + foreach (var recordingFolder in recordingFolders) + { + var pathsToCreate = recordingFolder.Locations + .Where(i => !allExistingPaths.Contains(i, StringComparer.OrdinalIgnoreCase)) + .ToList(); + + if (pathsToCreate.Count == 0) + { + continue; + } + + try + { + _libraryManager.AddVirtualFolder(recordingFolder.Name, recordingFolder.CollectionType, pathsToCreate.ToArray(), true); + } + catch (Exception ex) + { + _logger.ErrorException("Error creating virtual folder", ex); + } + } + } + + private void RemovePathFromLibrary(string path) + { + var requiresRefresh = false; + var virtualFolders = _libraryManager.GetVirtualFolders() + .ToList(); + + foreach (var virtualFolder in virtualFolders) + { + if (!virtualFolder.Locations.Contains(path, StringComparer.OrdinalIgnoreCase)) + { + continue; + } + + if (virtualFolder.Locations.Count == 1) + { + // remove entire virtual folder + try + { + _libraryManager.RemoveVirtualFolder(virtualFolder.Name, true); + } + catch (Exception ex) + { + _logger.ErrorException("Error removing virtual folder", ex); + } + } + else + { + try + { + _libraryManager.RemoveMediaPath(virtualFolder.Name, path); + requiresRefresh = true; + } + catch (Exception ex) + { + _logger.ErrorException("Error removing media path", ex); + } + } + } + + if (requiresRefresh) + { + _libraryManager.ValidateMediaLibrary(new Progress(), CancellationToken.None); + } } void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e) @@ -97,13 +203,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV } } - public event EventHandler DataSourceChanged; - - public event EventHandler RecordingStatusChanged; - - private readonly ConcurrentDictionary _activeRecordings = - new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - public string Name { get { return "Emby"; } @@ -114,6 +213,26 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV get { return Path.Combine(_config.CommonApplicationPaths.DataPath, "livetv"); } } + private string DefaultRecordingPath + { + get + { + return Path.Combine(DataPath, "recordings"); + } + } + + private string RecordingPath + { + get + { + var path = GetConfiguration().RecordingPath; + + return string.IsNullOrWhiteSpace(path) + ? DefaultRecordingPath + : path; + } + } + public string HomePageUrl { get { return "http://emby.media"; } @@ -280,49 +399,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV return Task.FromResult(true); } - public async Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken) + public Task DeleteRecordingAsync(string recordingId, CancellationToken cancellationToken) { - var remove = _recordingProvider.GetAll().FirstOrDefault(i => string.Equals(i.Id, recordingId, StringComparison.OrdinalIgnoreCase)); - if (remove != null) - { - if (!string.IsNullOrWhiteSpace(remove.TimerId)) - { - var enableDelay = _activeRecordings.ContainsKey(remove.TimerId); - - CancelTimerInternal(remove.TimerId); - - if (enableDelay) - { - // A hack yes, but need to make sure the file is closed before attempting to delete it - await Task.Delay(3000, cancellationToken).ConfigureAwait(false); - } - } - - if (!string.IsNullOrWhiteSpace(remove.Path)) - { - try - { - _fileSystem.DeleteFile(remove.Path); - } - catch (DirectoryNotFoundException) - { - - } - catch (FileNotFoundException) - { - - } - catch (Exception ex) - { - _logger.ErrorException("Error deleting recording file {0}", ex, remove.Path); - } - } - _recordingProvider.Delete(remove); - } - else - { - throw new ResourceNotFoundException("Recording not found: " + recordingId); - } + return Task.FromResult(true); } public Task CreateTimerAsync(TimerInfo info, CancellationToken cancellationToken) @@ -424,29 +503,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV public async Task> GetRecordingsAsync(CancellationToken cancellationToken) { - var recordings = _recordingProvider.GetAll().ToList(); - var updated = false; - - foreach (var recording in recordings) - { - if (recording.Status == RecordingStatus.InProgress) - { - if (string.IsNullOrWhiteSpace(recording.TimerId) || !_activeRecordings.ContainsKey(recording.TimerId)) - { - recording.Status = RecordingStatus.Cancelled; - recording.DateLastUpdated = DateTime.UtcNow; - _recordingProvider.Update(recording); - updated = true; - } - } - } - - if (updated) - { - recordings = _recordingProvider.GetAll().ToList(); - } - - return recordings; + return new List(); } public Task> GetTimersAsync(CancellationToken cancellationToken) @@ -695,104 +752,124 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV } } - private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken) + private string GetRecordingPath(TimerInfo timer, ProgramInfo info) { - if (timer == null) - { - throw new ArgumentNullException("timer"); - } - - ProgramInfo info = null; - - if (string.IsNullOrWhiteSpace(timer.ProgramId)) - { - _logger.Info("Timer {0} has null programId", timer.Id); - } - else - { - 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) - { - throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId)); - } - var recordPath = RecordingPath; + var config = GetConfiguration(); if (info.IsMovie) { - recordPath = Path.Combine(recordPath, "Movies", _fileSystem.GetValidFilename(info.Name).Trim()); + var customRecordingPath = config.MovieRecordingPath; + if ((string.IsNullOrWhiteSpace(customRecordingPath) || string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase)) && config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Movies"); + } + + var folderName = _fileSystem.GetValidFilename(info.Name).Trim(); + if (info.ProductionYear.HasValue) + { + folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")"; + } + recordPath = Path.Combine(recordPath, folderName); } else if (info.IsSeries) { - recordPath = Path.Combine(recordPath, "Series", _fileSystem.GetValidFilename(info.Name).Trim()); + var customRecordingPath = config.SeriesRecordingPath; + if ((string.IsNullOrWhiteSpace(customRecordingPath) || string.Equals(customRecordingPath, recordPath, StringComparison.OrdinalIgnoreCase)) && config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Series"); + } + + var folderName = _fileSystem.GetValidFilename(info.Name).Trim(); + var folderNameWithYear = folderName; + if (info.ProductionYear.HasValue) + { + folderNameWithYear += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")"; + } + + if (Directory.Exists(Path.Combine(recordPath, folderName))) + { + recordPath = Path.Combine(recordPath, folderName); + } + else + { + recordPath = Path.Combine(recordPath, folderNameWithYear); + } if (info.SeasonNumber.HasValue) { - var folderName = string.Format("Season {0}", info.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture)); + folderName = string.Format("Season {0}", info.SeasonNumber.Value.ToString(CultureInfo.InvariantCulture)); recordPath = Path.Combine(recordPath, folderName); } } else if (info.IsKids) { - recordPath = Path.Combine(recordPath, "Kids", _fileSystem.GetValidFilename(info.Name).Trim()); + if (config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Kids"); + } + + var folderName = _fileSystem.GetValidFilename(info.Name).Trim(); + if (info.ProductionYear.HasValue) + { + folderName += " (" + info.ProductionYear.Value.ToString(CultureInfo.InvariantCulture) + ")"; + } + recordPath = Path.Combine(recordPath, folderName); } else if (info.IsSports) { - recordPath = Path.Combine(recordPath, "Sports", _fileSystem.GetValidFilename(info.Name).Trim()); + if (config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Sports"); + } + recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim()); } else { - recordPath = Path.Combine(recordPath, "Other", _fileSystem.GetValidFilename(info.Name).Trim()); + if (config.EnableRecordingSubfolders) + { + recordPath = Path.Combine(recordPath, "Other"); + } + recordPath = Path.Combine(recordPath, _fileSystem.GetValidFilename(info.Name).Trim()); } var recordingFileName = _fileSystem.GetValidFilename(RecordingHelper.GetRecordingName(timer, info)).Trim() + ".ts"; - recordPath = Path.Combine(recordPath, recordingFileName); + return Path.Combine(recordPath, recordingFileName); + } - var recordingId = info.Id.GetMD5().ToString("N"); - var recording = _recordingProvider.GetAll().FirstOrDefault(x => string.Equals(x.Id, recordingId, StringComparison.OrdinalIgnoreCase)); + private async Task RecordStream(TimerInfo timer, DateTime recordingEndDate, ActiveRecordingInfo activeRecordingInfo, CancellationToken cancellationToken) + { + if (timer == null) + { + throw new ArgumentNullException("timer"); + } - if (recording == null) + ProgramInfo info = null; + + if (string.IsNullOrWhiteSpace(timer.ProgramId)) { - recording = new RecordingInfo - { - ChannelId = info.ChannelId, - Id = recordingId, - StartDate = info.StartDate, - EndDate = info.EndDate, - Genres = info.Genres, - IsKids = info.IsKids, - IsLive = info.IsLive, - IsMovie = info.IsMovie, - IsHD = info.IsHD, - IsNews = info.IsNews, - IsPremiere = info.IsPremiere, - IsSeries = info.IsSeries, - IsSports = info.IsSports, - IsRepeat = !info.IsPremiere, - Name = info.Name, - EpisodeTitle = info.EpisodeTitle, - ProgramId = info.Id, - ImagePath = info.ImagePath, - ImageUrl = info.ImageUrl, - OriginalAirDate = info.OriginalAirDate, - Status = RecordingStatus.Scheduled, - Overview = info.Overview, - SeriesTimerId = timer.SeriesTimerId, - TimerId = timer.Id, - ShowId = info.ShowId - }; - _recordingProvider.AddOrUpdate(recording); + _logger.Info("Timer {0} has null programId", timer.Id); + } + else + { + 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) + { + throw new InvalidOperationException(string.Format("Program with Id {0} not found", timer.ProgramId)); + } + + var recordPath = GetRecordingPath(timer, info); + var recordingStatus = RecordingStatus.New; + try { var result = await GetChannelStreamInternal(timer.ChannelId, null, CancellationToken.None).ConfigureAwait(false); @@ -817,11 +894,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _libraryMonitor.ReportFileSystemChangeBeginning(recordPath); - recording.Path = recordPath; - recording.Status = RecordingStatus.InProgress; - recording.DateLastUpdated = DateTime.UtcNow; - _recordingProvider.AddOrUpdate(recording); - var duration = recordingEndDate - DateTime.UtcNow; _logger.Info("Beginning recording. Will record for {0} minutes.", duration.TotalMinutes.ToString(CultureInfo.InvariantCulture)); @@ -846,7 +918,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV await recorder.Record(mediaStreamInfo, recordPath, duration, onStarted, cancellationToken).ConfigureAwait(false); - recording.Status = RecordingStatus.Completed; + recordingStatus = RecordingStatus.Completed; _logger.Info("Recording completed: {0}", recordPath); } finally @@ -862,12 +934,12 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV catch (OperationCanceledException) { _logger.Info("Recording stopped: {0}", recordPath); - recording.Status = RecordingStatus.Completed; + recordingStatus = RecordingStatus.Completed; } catch (Exception ex) { _logger.ErrorException("Error recording to {0}", ex, recordPath); - recording.Status = RecordingStatus.Error; + recordingStatus = RecordingStatus.Error; } finally { @@ -875,12 +947,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV _activeRecordings.TryRemove(timer.Id, out removed); } - recording.DateLastUpdated = DateTime.UtcNow; - _recordingProvider.AddOrUpdate(recording); - - if (recording.Status == RecordingStatus.Completed) + if (recordingStatus == RecordingStatus.Completed) { - OnSuccessfulRecording(recording); + OnSuccessfulRecording(info.IsSeries, recordPath); _timerProvider.Delete(timer); } else if (DateTime.UtcNow < timer.EndDate) @@ -893,7 +962,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV else { _timerProvider.Delete(timer); - _recordingProvider.Delete(recording); } } @@ -948,11 +1016,11 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV return new DirectRecorder(_logger, _httpClient, _fileSystem); } - private async void OnSuccessfulRecording(RecordingInfo recording) + private async void OnSuccessfulRecording(bool isSeries, string path) { if (GetConfiguration().EnableAutoOrganize) { - if (recording.IsSeries) + if (isSeries) { try { @@ -962,12 +1030,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV var organize = new EpisodeFileOrganizer(_organizationService, _config, _fileSystem, _logger, _libraryManager, _libraryMonitor, _providerManager); - var result = await organize.OrganizeEpisodeFile(recording.Path, CancellationToken.None).ConfigureAwait(false); - - if (result.Status == FileSortingStatus.Success) - { - _recordingProvider.Delete(recording); - } + var result = await organize.OrganizeEpisodeFile(path, CancellationToken.None).ConfigureAwait(false); } catch (Exception ex) { @@ -991,18 +1054,6 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV return epgData.FirstOrDefault(p => Math.Abs(startDateTicks - p.StartDate.Ticks) <= TimeSpan.FromMinutes(3).Ticks); } - private string RecordingPath - { - get - { - var path = GetConfiguration().RecordingPath; - - return string.IsNullOrWhiteSpace(path) - ? Path.Combine(DataPath, "recordings") - : path; - } - } - private LiveTvOptions GetConfiguration() { return _config.GetConfiguration("livetv"); @@ -1010,7 +1061,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV private async Task UpdateTimersForSeriesTimer(List epgData, SeriesTimerInfo seriesTimer, bool deleteInvalidTimers) { - var newTimers = GetTimersForSeries(seriesTimer, epgData, _recordingProvider.GetAll()).ToList(); + var newTimers = GetTimersForSeries(seriesTimer, epgData, true).ToList(); var registration = await GetRegistrationInfo("seriesrecordings").ConfigureAwait(false); @@ -1024,7 +1075,7 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV if (deleteInvalidTimers) { - var allTimers = GetTimersForSeries(seriesTimer, epgData, new List()) + var allTimers = GetTimersForSeries(seriesTimer, epgData, false) .Select(i => i.Id) .ToList(); @@ -1040,7 +1091,9 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV } } - private IEnumerable GetTimersForSeries(SeriesTimerInfo seriesTimer, IEnumerable allPrograms, IReadOnlyList currentRecordings) + private IEnumerable GetTimersForSeries(SeriesTimerInfo seriesTimer, + IEnumerable allPrograms, + bool filterByCurrentRecordings) { if (seriesTimer == null) { @@ -1050,23 +1103,71 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV { throw new ArgumentNullException("allPrograms"); } - if (currentRecordings == null) - { - throw new ArgumentNullException("currentRecordings"); - } // Exclude programs that have already ended allPrograms = allPrograms.Where(i => i.EndDate > DateTime.UtcNow && i.StartDate > DateTime.UtcNow); allPrograms = GetProgramsForSeries(seriesTimer, allPrograms); - var recordingShowIds = currentRecordings.Select(i => i.ProgramId).Where(i => !string.IsNullOrWhiteSpace(i)).ToList(); - - allPrograms = allPrograms.Where(i => !recordingShowIds.Contains(i.Id, StringComparer.OrdinalIgnoreCase)); + if (filterByCurrentRecordings) + { + allPrograms = allPrograms.Where(i => !IsProgramAlreadyInLibrary(i)); + } return allPrograms.Select(i => RecordingHelper.CreateTimer(i, seriesTimer)); } + private bool IsProgramAlreadyInLibrary(ProgramInfo program) + { + if ((program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) || !string.IsNullOrWhiteSpace(program.EpisodeTitle)) + { + var seriesIds = _libraryManager.GetItemIds(new InternalItemsQuery + { + IncludeItemTypes = new[] { typeof(Series).Name }, + Name = program.Name + + }).Select(i => i.ToString("N")).ToArray(); + + if (seriesIds.Length == 0) + { + return false; + } + + if (program.EpisodeNumber.HasValue && program.SeasonNumber.HasValue) + { + var result = _libraryManager.GetItemsResult(new InternalItemsQuery + { + IncludeItemTypes = new[] { typeof(Episode).Name }, + ParentIndexNumber = program.SeasonNumber.Value, + IndexNumber = program.EpisodeNumber.Value, + AncestorIds = seriesIds + }); + + if (result.TotalRecordCount > 0) + { + return true; + } + } + + if (!string.IsNullOrWhiteSpace(program.EpisodeTitle)) + { + var result = _libraryManager.GetItemsResult(new InternalItemsQuery + { + IncludeItemTypes = new[] { typeof(Episode).Name }, + Name = program.EpisodeTitle, + AncestorIds = seriesIds + }); + + if (result.TotalRecordCount > 0) + { + return true; + } + } + } + + return false; + } + private IEnumerable GetProgramsForSeries(SeriesTimerInfo seriesTimer, IEnumerable allPrograms) { if (!seriesTimer.RecordAnyTime) @@ -1151,6 +1252,47 @@ namespace MediaBrowser.Server.Implementations.LiveTv.EmbyTV }); } + public List GetRecordingFolders() + { + var list = new List(); + + var defaultFolder = RecordingPath; + var defaultName = "Recordings"; + + if (Directory.Exists(defaultFolder)) + { + list.Add(new VirtualFolderInfo + { + Locations = new List { defaultFolder }, + Name = defaultName + }); + } + + var customPath = GetConfiguration().MovieRecordingPath; + if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath)) + { + list.Add(new VirtualFolderInfo + { + Locations = new List { customPath }, + Name = "Recorded Movies", + CollectionType = CollectionType.Movies + }); + } + + customPath = GetConfiguration().SeriesRecordingPath; + if ((!string.IsNullOrWhiteSpace(customPath) && !string.Equals(customPath, defaultFolder, StringComparison.OrdinalIgnoreCase)) && Directory.Exists(customPath)) + { + list.Add(new VirtualFolderInfo + { + Locations = new List { customPath }, + Name = "Recorded Series", + CollectionType = CollectionType.TvShows + }); + } + + return list; + } + class ActiveRecordingInfo { public string Path { get; set; } -- cgit v1.2.3 From 626a2ed2a90d6be52d4e8ee636bcbb5337443aef Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Thu, 16 Jun 2016 09:24:12 -0400 Subject: update child count creation --- MediaBrowser.Controller/Entities/Folder.cs | 21 +++++++++++++ MediaBrowser.Controller/Entities/TV/Season.cs | 5 +++ MediaBrowser.Controller/Entities/TV/Series.cs | 14 +++++++++ MediaBrowser.Controller/Entities/UserRootFolder.cs | 5 +++ MediaBrowser.Controller/Entities/UserView.cs | 5 +++ MediaBrowser.Controller/Library/ILibraryManager.cs | 7 ----- .../Profiles/SamsungSmartTvProfile.cs | 4 +-- .../Profiles/Xml/Samsung Smart TV.xml | 2 +- .../Dto/DtoService.cs | 3 +- .../Library/LibraryManager.cs | 36 +++++++++++++++------- 10 files changed, 79 insertions(+), 23 deletions(-) (limited to 'MediaBrowser.Controller/Library/ILibraryManager.cs') diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 3c8d8baec..e3841099e 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -666,6 +666,27 @@ namespace MediaBrowser.Controller.Entities }); } + public virtual int GetChildCount(User user) + { + if (LinkedChildren.Count > 0) + { + if (!(this is ICollectionFolder)) + { + return GetChildren(user, true).Count(); + } + } + + var result = GetItems(new InternalItemsQuery(user) + { + Recursive = false, + Limit = 0, + ParentId = Id + + }).Result; + + return result.TotalRecordCount; + } + public QueryResult QueryRecursive(InternalItemsQuery query) { var user = query.User; diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index c984a2832..9a9014844 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -75,6 +75,11 @@ namespace MediaBrowser.Controller.Entities.TV return list; } + public override int GetChildCount(User user) + { + return GetChildren(user, true).Count(); + } + /// /// This Episode's Series Instance /// diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 1f341ba13..1cc496b35 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -111,6 +111,20 @@ namespace MediaBrowser.Controller.Entities.TV } } + public override int GetChildCount(User user) + { + var result = LibraryManager.GetItemsResult(new InternalItemsQuery(user) + { + AncestorWithPresentationUniqueKey = PresentationUniqueKey, + IncludeItemTypes = new[] { typeof(Season).Name }, + SortBy = new[] { ItemSortBy.SortName }, + IsVirtualItem = false, + Limit = 0 + }); + + return result.TotalRecordCount; + } + /// /// Gets the user data key. /// diff --git a/MediaBrowser.Controller/Entities/UserRootFolder.cs b/MediaBrowser.Controller/Entities/UserRootFolder.cs index 37c4c91b1..8e6f11c2c 100644 --- a/MediaBrowser.Controller/Entities/UserRootFolder.cs +++ b/MediaBrowser.Controller/Entities/UserRootFolder.cs @@ -38,6 +38,11 @@ namespace MediaBrowser.Controller.Entities return PostFilterAndSort(result.Where(filter), query); } + public override int GetChildCount(User user) + { + return GetChildren(user, true).Count(); + } + [IgnoreDataMember] protected override bool SupportsShortcutChildren { diff --git a/MediaBrowser.Controller/Entities/UserView.cs b/MediaBrowser.Controller/Entities/UserView.cs index 6ec719e87..35375e7e6 100644 --- a/MediaBrowser.Controller/Entities/UserView.cs +++ b/MediaBrowser.Controller/Entities/UserView.cs @@ -45,6 +45,11 @@ namespace MediaBrowser.Controller.Entities return list; } + public override int GetChildCount(User user) + { + return GetChildren(user, true).Count(); + } + protected override Task> GetItemsInternal(InternalItemsQuery query) { var parent = this as Folder; diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 936b97c6e..1d0e06482 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -150,13 +150,6 @@ namespace MediaBrowser.Controller.Library /// BaseItem. BaseItem GetItemById(Guid id); - /// - /// Gets the memory item by identifier. - /// - /// The identifier. - /// BaseItem. - BaseItem GetMemoryItemById(Guid id); - /// /// Gets the intros. /// diff --git a/MediaBrowser.Dlna/Profiles/SamsungSmartTvProfile.cs b/MediaBrowser.Dlna/Profiles/SamsungSmartTvProfile.cs index 1b06e1d6a..c117d030f 100644 --- a/MediaBrowser.Dlna/Profiles/SamsungSmartTvProfile.cs +++ b/MediaBrowser.Dlna/Profiles/SamsungSmartTvProfile.cs @@ -21,8 +21,8 @@ namespace MediaBrowser.Dlna.Profiles new HttpHeaderInfo { Name = "User-Agent", - Value = @"SEC_", - Match = HeaderMatchType.Substring + Value = @".*(SEC_HHP_\[TV\] [A-Z]{2}\d{2}J[A-Z]?\d{3,4})*.", + Match = HeaderMatchType.Regex } } }; diff --git a/MediaBrowser.Dlna/Profiles/Xml/Samsung Smart TV.xml b/MediaBrowser.Dlna/Profiles/Xml/Samsung Smart TV.xml index b09c25afa..967538bdf 100644 --- a/MediaBrowser.Dlna/Profiles/Xml/Samsung Smart TV.xml +++ b/MediaBrowser.Dlna/Profiles/Xml/Samsung Smart TV.xml @@ -4,7 +4,7 @@ samsung.com - + Emby diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index 31a35eec9..95a235109 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -549,8 +549,7 @@ namespace MediaBrowser.Server.Implementations.Dto private int GetChildCount(Folder folder, User user) { - return folder.GetChildren(user, true) - .Count(); + return folder.GetChildCount(user); } /// diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 2483ec93e..c0c40aa5b 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -1276,18 +1276,9 @@ namespace MediaBrowser.Server.Implementations.Library return item; } - public BaseItem GetMemoryItemById(Guid id) + private bool EnableCaching { - if (id == Guid.Empty) - { - throw new ArgumentNullException("id"); - } - - BaseItem item; - - LibraryItemsCache.TryGetValue(id, out item); - - return item; + get { return true; } } public IEnumerable GetItemList(InternalItemsQuery query) @@ -1297,6 +1288,11 @@ namespace MediaBrowser.Server.Implementations.Library AddUserToQuery(query, query.User); } + if (!EnableCaching) + { + return ItemRepository.GetItemList(query); + } + var result = ItemRepository.GetItemIdsList(query); return result.Select(GetItemById).Where(i => i != null); @@ -1336,6 +1332,11 @@ namespace MediaBrowser.Server.Implementations.Library SetTopParentIdsOrAncestors(query, parents); + if (!EnableCaching) + { + return ItemRepository.GetItemList(query); + } + return GetItemIds(query).Select(GetItemById).Where(i => i != null); } @@ -1358,6 +1359,11 @@ namespace MediaBrowser.Server.Implementations.Library if (query.EnableTotalRecordCount) { + if (!EnableCaching) + { + return ItemRepository.GetItems(query); + } + var initialResult = ItemRepository.GetItemIds(query); return new QueryResult @@ -1367,6 +1373,14 @@ namespace MediaBrowser.Server.Implementations.Library }; } + if (!EnableCaching) + { + return new QueryResult + { + Items = ItemRepository.GetItemList(query).ToArray() + }; + } + return new QueryResult { Items = ItemRepository.GetItemIdsList(query).Select(GetItemById).Where(i => i != null).ToArray() -- cgit v1.2.3 From f9847be17c5037671b622b61df9aaa113723f318 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 17 Jun 2016 09:06:13 -0400 Subject: update item by name queries --- MediaBrowser.Api/StartupWizardService.cs | 2 +- MediaBrowser.Api/UserLibrary/ArtistsService.cs | 40 ++- .../UserLibrary/BaseItemsByNameService.cs | 134 +++++++- MediaBrowser.Api/UserLibrary/GameGenresService.cs | 25 +- MediaBrowser.Api/UserLibrary/GenresService.cs | 61 +--- MediaBrowser.Api/UserLibrary/MusicGenresService.cs | 17 +- MediaBrowser.Api/UserLibrary/StudiosService.cs | 11 +- MediaBrowser.Controller/Entities/Audio/Audio.cs | 2 - .../Entities/Audio/MusicArtist.cs | 10 +- .../Entities/Audio/MusicGenre.cs | 11 +- MediaBrowser.Controller/Entities/BaseItem.cs | 4 + MediaBrowser.Controller/Entities/Folder.cs | 8 +- MediaBrowser.Controller/Entities/GameGenre.cs | 11 +- MediaBrowser.Controller/Entities/Genre.cs | 11 +- MediaBrowser.Controller/Entities/Person.cs | 11 +- MediaBrowser.Controller/Entities/Studio.cs | 11 +- MediaBrowser.Controller/Entities/Video.cs | 3 - MediaBrowser.Controller/Library/ILibraryManager.cs | 8 + .../Persistence/IItemRepository.cs | 8 + .../MediaBrowser.Model.Portable.csproj | 3 - .../MediaBrowser.Model.net35.csproj | 3 - MediaBrowser.Model/Dto/ItemCounts.cs | 1 + MediaBrowser.Model/Entities/MediaUrl.cs | 1 - MediaBrowser.Model/Entities/VideoSize.cs | 8 - MediaBrowser.Model/MediaBrowser.Model.csproj | 1 - .../Movies/GenericMovieDbInfo.cs | 3 +- .../Dto/DtoService.cs | 2 +- .../Library/LibraryManager.cs | 96 +++++- .../Library/Resolvers/BaseVideoResolver.cs | 2 +- .../MediaBrowser.Server.Implementations.csproj | 4 +- .../Persistence/CleanDatabaseScheduledTask.cs | 24 +- .../Persistence/SqliteItemRepository.cs | 348 +++++++++++++++++++-- .../packages.config | 2 +- 33 files changed, 733 insertions(+), 153 deletions(-) delete mode 100644 MediaBrowser.Model/Entities/VideoSize.cs (limited to 'MediaBrowser.Controller/Library/ILibraryManager.cs') diff --git a/MediaBrowser.Api/StartupWizardService.cs b/MediaBrowser.Api/StartupWizardService.cs index f4aee080a..e4949b4d8 100644 --- a/MediaBrowser.Api/StartupWizardService.cs +++ b/MediaBrowser.Api/StartupWizardService.cs @@ -114,7 +114,7 @@ namespace MediaBrowser.Api config.EnableStandaloneMusicKeys = true; config.EnableCaseSensitiveItemIds = true; config.EnableFolderView = true; - config.SchemaVersion = 92; + config.SchemaVersion = 95; } public void Post(UpdateStartupConfiguration request) diff --git a/MediaBrowser.Api/UserLibrary/ArtistsService.cs b/MediaBrowser.Api/UserLibrary/ArtistsService.cs index cde5eade5..df73ef720 100644 --- a/MediaBrowser.Api/UserLibrary/ArtistsService.cs +++ b/MediaBrowser.Api/UserLibrary/ArtistsService.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Controller.Dto; +using System; +using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; @@ -8,6 +9,8 @@ using MediaBrowser.Model.Dto; using ServiceStack; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Querying; namespace MediaBrowser.Api.UserLibrary { @@ -100,7 +103,12 @@ namespace MediaBrowser.Api.UserLibrary /// System.Object. public object Get(GetArtists request) { - var result = GetResult(request); + if (string.IsNullOrWhiteSpace(request.IncludeItemTypes)) + { + //request.IncludeItemTypes = "Audio,MusicVideo"; + } + + var result = GetResultSlim(request); return ToOptimizedResult(result); } @@ -112,11 +120,26 @@ namespace MediaBrowser.Api.UserLibrary /// System.Object. public object Get(GetAlbumArtists request) { - var result = GetResult(request); + if (string.IsNullOrWhiteSpace(request.IncludeItemTypes)) + { + //request.IncludeItemTypes = "Audio,MusicVideo"; + } + + var result = GetResultSlim(request); return ToOptimizedResult(result); } + protected override QueryResult> GetItems(GetItemsByName request, InternalItemsQuery query) + { + if (request is GetAlbumArtists) + { + return LibraryManager.GetAlbumArtists(query); + } + + return LibraryManager.GetArtists(query); + } + /// /// Gets all items. /// @@ -125,16 +148,7 @@ namespace MediaBrowser.Api.UserLibrary /// IEnumerable{Tuple{System.StringFunc{System.Int32}}}. protected override IEnumerable GetAllItems(GetItemsByName request, IEnumerable items) { - if (request is GetAlbumArtists) - { - return LibraryManager.GetAlbumArtists(items - .Where(i => !i.IsFolder) - .OfType()); - } - - return LibraryManager.GetArtists(items - .Where(i => !i.IsFolder) - .OfType()); + throw new NotImplementedException(); } } } diff --git a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs index 18dec3253..9465d1fdc 100644 --- a/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs +++ b/MediaBrowser.Api/UserLibrary/BaseItemsByNameService.cs @@ -8,6 +8,7 @@ using ServiceStack; using System; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Model.Dto; namespace MediaBrowser.Api.UserLibrary { @@ -83,6 +84,137 @@ namespace MediaBrowser.Api.UserLibrary return null; } + protected ItemsResult GetResultSlim(GetItemsByName request) + { + var dtoOptions = GetDtoOptions(request); + + User user = null; + BaseItem parentItem; + + if (!string.IsNullOrWhiteSpace(request.UserId)) + { + user = UserManager.GetUserById(request.UserId); + parentItem = string.IsNullOrEmpty(request.ParentId) ? user.RootFolder : LibraryManager.GetItemById(request.ParentId); + } + else + { + parentItem = string.IsNullOrEmpty(request.ParentId) ? LibraryManager.RootFolder : LibraryManager.GetItemById(request.ParentId); + } + + var excludeItemTypes = request.GetExcludeItemTypes(); + var includeItemTypes = request.GetIncludeItemTypes(); + var mediaTypes = request.GetMediaTypes(); + + var query = new InternalItemsQuery(user) + { + ExcludeItemTypes = excludeItemTypes, + IncludeItemTypes = includeItemTypes, + MediaTypes = mediaTypes, + StartIndex = request.StartIndex, + Limit = request.Limit, + IsFavorite = request.IsFavorite, + NameLessThan = request.NameLessThan, + NameStartsWith = request.NameStartsWith, + NameStartsWithOrGreater = request.NameStartsWithOrGreater, + AlbumArtistStartsWithOrGreater = request.AlbumArtistStartsWithOrGreater, + Tags = request.GetTags(), + OfficialRatings = request.GetOfficialRatings(), + Genres = request.GetGenres(), + GenreIds = request.GetGenreIds(), + Studios = request.GetStudios(), + StudioIds = request.GetStudioIds(), + Person = request.Person, + PersonIds = request.GetPersonIds(), + PersonTypes = request.GetPersonTypes(), + Years = request.GetYears(), + MinCommunityRating = request.MinCommunityRating + }; + + if (!string.IsNullOrWhiteSpace(request.ParentId)) + { + if (parentItem is Folder) + { + query.AncestorIds = new[] { request.ParentId }; + } + else + { + query.ItemIds = new[] { request.ParentId }; + } + } + + foreach (var filter in request.GetFilters()) + { + switch (filter) + { + case ItemFilter.Dislikes: + query.IsLiked = false; + break; + case ItemFilter.IsFavorite: + query.IsFavorite = true; + break; + case ItemFilter.IsFavoriteOrLikes: + query.IsFavoriteOrLiked = true; + break; + case ItemFilter.IsFolder: + query.IsFolder = true; + break; + case ItemFilter.IsNotFolder: + query.IsFolder = false; + break; + case ItemFilter.IsPlayed: + query.IsPlayed = true; + break; + case ItemFilter.IsRecentlyAdded: + break; + case ItemFilter.IsResumable: + query.IsResumable = true; + break; + case ItemFilter.IsUnplayed: + query.IsPlayed = false; + break; + case ItemFilter.Likes: + query.IsLiked = true; + break; + } + } + + var result = GetItems(request, query); + + var dtos = result.Items.Select(i => + { + var dto = DtoService.GetItemByNameDto(i.Item1, dtoOptions, null, user); + + if (!string.IsNullOrWhiteSpace(request.IncludeItemTypes)) + { + SetItemCounts(dto, i.Item2); + } + return dto; + }); + + return new ItemsResult + { + Items = dtos.ToArray(), + TotalRecordCount = result.TotalRecordCount + }; + } + + protected virtual QueryResult> GetItems(GetItemsByName request, InternalItemsQuery query) + { + return new QueryResult>(); + } + + private void SetItemCounts(BaseItemDto dto, ItemCounts counts) + { + dto.ChildCount = counts.ItemCount; + dto.SeriesCount = counts.SeriesCount; + dto.EpisodeCount = counts.EpisodeCount; + dto.MovieCount = counts.MovieCount; + dto.TrailerCount = counts.TrailerCount; + dto.AlbumCount = counts.AlbumCount; + dto.SongCount = counts.SongCount; + dto.GameCount = counts.GameCount; + } + /// /// Gets the specified request. /// @@ -374,7 +506,7 @@ namespace MediaBrowser.Api.UserLibrary /// The include item types. /// The media types. /// IEnumerable{BaseItem}. - protected bool FilterItem(GetItemsByName request, BaseItem f, string[] excludeItemTypes, string[] includeItemTypes, string[] mediaTypes) + private bool FilterItem(GetItemsByName request, BaseItem f, string[] excludeItemTypes, string[] includeItemTypes, string[] mediaTypes) { // Exclude item types if (excludeItemTypes.Length > 0) diff --git a/MediaBrowser.Api/UserLibrary/GameGenresService.cs b/MediaBrowser.Api/UserLibrary/GameGenresService.cs index 58237f80f..ebc9a970d 100644 --- a/MediaBrowser.Api/UserLibrary/GameGenresService.cs +++ b/MediaBrowser.Api/UserLibrary/GameGenresService.cs @@ -9,6 +9,7 @@ using ServiceStack; using System; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Model.Querying; namespace MediaBrowser.Api.UserLibrary { @@ -87,11 +88,16 @@ namespace MediaBrowser.Api.UserLibrary /// System.Object. public object Get(GetGameGenres request) { - var result = GetResult(request); + var result = GetResultSlim(request); return ToOptimizedSerializedResultUsingCache(result); } + protected override QueryResult> GetItems(GetItemsByName request, InternalItemsQuery query) + { + return LibraryManager.GetGameGenres(query); + } + /// /// Gets all items. /// @@ -100,22 +106,7 @@ namespace MediaBrowser.Api.UserLibrary /// IEnumerable{Tuple{System.StringFunc{System.Int32}}}. protected override IEnumerable GetAllItems(GetItemsByName request, IEnumerable items) { - return items - .SelectMany(i => i.Genres) - .DistinctNames() - .Select(name => - { - try - { - return LibraryManager.GetGameGenre(name); - } - catch (Exception ex) - { - Logger.ErrorException("Error getting genre {0}", ex, name); - return null; - } - }) - .Where(i => i != null); + throw new NotImplementedException(); } } } diff --git a/MediaBrowser.Api/UserLibrary/GenresService.cs b/MediaBrowser.Api/UserLibrary/GenresService.cs index d383bd0ad..57c11a1fa 100644 --- a/MediaBrowser.Api/UserLibrary/GenresService.cs +++ b/MediaBrowser.Api/UserLibrary/GenresService.cs @@ -9,6 +9,7 @@ using ServiceStack; using System; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Model.Querying; namespace MediaBrowser.Api.UserLibrary { @@ -92,65 +93,37 @@ namespace MediaBrowser.Api.UserLibrary /// System.Object. public object Get(GetGenres request) { - var result = GetResult(request); + var result = GetResultSlim(request); return ToOptimizedSerializedResultUsingCache(result); } - /// - /// Gets all items. - /// - /// The request. - /// The items. - /// IEnumerable{Tuple{System.StringFunc{System.Int32}}}. - protected override IEnumerable GetAllItems(GetItemsByName request, IEnumerable items) + protected override QueryResult> GetItems(GetItemsByName request, InternalItemsQuery query) { var viewType = GetParentItemViewType(request); if (string.Equals(viewType, CollectionType.Music) || string.Equals(viewType, CollectionType.MusicVideos)) { - return items - .SelectMany(i => i.Genres) - .DistinctNames() - .Select(name => LibraryManager.GetMusicGenre(name)); + return LibraryManager.GetMusicGenres(query); } if (string.Equals(viewType, CollectionType.Games)) { - return items - .SelectMany(i => i.Genres) - .DistinctNames() - .Select(name => - { - try - { - return LibraryManager.GetGameGenre(name); - } - catch (Exception ex) - { - Logger.ErrorException("Error getting genre {0}", ex, name); - return null; - } - }) - .Where(i => i != null); + return LibraryManager.GetGameGenres(query); } - return items - .SelectMany(i => i.Genres) - .DistinctNames() - .Select(name => - { - try - { - return LibraryManager.GetGenre(name); - } - catch (Exception ex) - { - Logger.ErrorException("Error getting genre {0}", ex, name); - return null; - } - }) - .Where(i => i != null); + return LibraryManager.GetGenres(query); + } + + /// + /// Gets all items. + /// + /// The request. + /// The items. + /// IEnumerable{Tuple{System.StringFunc{System.Int32}}}. + protected override IEnumerable GetAllItems(GetItemsByName request, IEnumerable items) + { + throw new NotImplementedException(); } } } diff --git a/MediaBrowser.Api/UserLibrary/MusicGenresService.cs b/MediaBrowser.Api/UserLibrary/MusicGenresService.cs index 12cb62fac..f02136e05 100644 --- a/MediaBrowser.Api/UserLibrary/MusicGenresService.cs +++ b/MediaBrowser.Api/UserLibrary/MusicGenresService.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Controller.Dto; +using System; +using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Library; @@ -8,6 +9,8 @@ using MediaBrowser.Model.Dto; using ServiceStack; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Model.Entities; +using MediaBrowser.Model.Querying; namespace MediaBrowser.Api.UserLibrary { @@ -86,11 +89,16 @@ namespace MediaBrowser.Api.UserLibrary /// System.Object. public object Get(GetMusicGenres request) { - var result = GetResult(request); + var result = GetResultSlim(request); return ToOptimizedSerializedResultUsingCache(result); } + protected override QueryResult> GetItems(GetItemsByName request, InternalItemsQuery query) + { + return LibraryManager.GetMusicGenres(query); + } + /// /// Gets all items. /// @@ -99,10 +107,7 @@ namespace MediaBrowser.Api.UserLibrary /// IEnumerable{Tuple{System.StringFunc{System.Int32}}}. protected override IEnumerable GetAllItems(GetItemsByName request, IEnumerable items) { - return items - .SelectMany(i => i.Genres) - .DistinctNames() - .Select(name => LibraryManager.GetMusicGenre(name)); + throw new NotImplementedException(); } } } diff --git a/MediaBrowser.Api/UserLibrary/StudiosService.cs b/MediaBrowser.Api/UserLibrary/StudiosService.cs index 2cdabf721..9e9c25d78 100644 --- a/MediaBrowser.Api/UserLibrary/StudiosService.cs +++ b/MediaBrowser.Api/UserLibrary/StudiosService.cs @@ -1,4 +1,5 @@ -using MediaBrowser.Controller.Dto; +using System; +using MediaBrowser.Controller.Dto; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Net; @@ -7,6 +8,7 @@ using MediaBrowser.Model.Dto; using ServiceStack; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Model.Querying; namespace MediaBrowser.Api.UserLibrary { @@ -90,11 +92,16 @@ namespace MediaBrowser.Api.UserLibrary /// System.Object. public object Get(GetStudios request) { - var result = GetResult(request); + var result = GetResultSlim(request); return ToOptimizedSerializedResultUsingCache(result); } + protected override QueryResult> GetItems(GetItemsByName request, InternalItemsQuery query) + { + return LibraryManager.GetStudios(query); + } + /// /// Gets all items. /// diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs index 06710b030..b3df34c4d 100644 --- a/MediaBrowser.Controller/Entities/Audio/Audio.cs +++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs @@ -26,8 +26,6 @@ namespace MediaBrowser.Controller.Entities.Audio { public List ChannelMediaSources { get; set; } - public long? Size { get; set; } - public string Container { get; set; } public int? TotalBitrate { get; set; } public ExtraType? ExtraType { get; set; } diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs index 950701687..6790a1bcf 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Runtime.Serialization; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Common.Extensions; namespace MediaBrowser.Controller.Entities.Audio { @@ -165,10 +166,17 @@ namespace MediaBrowser.Controller.Entities.Audio list.Add("Artist-Musicbrainz-" + id); } - list.Add("Artist-" + item.Name); + list.Add("Artist-" + (item.Name ?? string.Empty).RemoveDiacritics()); return list; } + public override string PresentationUniqueKey + { + get + { + return "Artist-" + (Name ?? string.Empty).RemoveDiacritics(); + } + } protected override bool GetBlockUnratedValue(UserPolicy config) { return config.BlockUnratedItems.Contains(UnratedItem.Music); diff --git a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs index 77cf0cc49..798bc79fb 100644 --- a/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs +++ b/MediaBrowser.Controller/Entities/Audio/MusicGenre.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; +using MediaBrowser.Common.Extensions; namespace MediaBrowser.Controller.Entities.Audio { @@ -14,10 +15,18 @@ namespace MediaBrowser.Controller.Entities.Audio { var list = base.GetUserDataKeys(); - list.Insert(0, "MusicGenre-" + Name); + list.Insert(0, GetType().Name + "-" + (Name ?? string.Empty).RemoveDiacritics()); return list; } + public override string PresentationUniqueKey + { + get + { + return GetUserDataKeys()[0]; + } + } + [IgnoreDataMember] public override bool SupportsAddingToPlaylist { diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 33fd03e15..ed838ab31 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -69,6 +69,10 @@ namespace MediaBrowser.Controller.Entities [IgnoreDataMember] public string PreferredMetadataLanguage { get; set; } + public long? Size { get; set; } + public string Container { get; set; } + public string ShortOverview { get; set; } + public List ImageInfos { get; set; } [IgnoreDataMember] diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index e3841099e..91ca1f009 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -216,7 +216,7 @@ namespace MediaBrowser.Controller.Entities { get { - return LoadChildren().Select(LibraryManager.GetItemById).Where(i => i != null); + return LoadChildren(); } } @@ -270,7 +270,7 @@ namespace MediaBrowser.Controller.Entities /// Loads our children. Validation will occur externally. /// We want this sychronous. /// - protected virtual IEnumerable LoadChildren() + protected virtual IEnumerable LoadChildren() { //just load our children from the repo - the library will be validated and maintained in other processes return GetCachedChildren(); @@ -657,9 +657,9 @@ namespace MediaBrowser.Controller.Entities /// Get our children from the repo - stubbed for now /// /// IEnumerable{BaseItem}. - protected IEnumerable GetCachedChildren() + protected IEnumerable GetCachedChildren() { - return ItemRepository.GetItemIdsList(new InternalItemsQuery + return ItemRepository.GetItemList(new InternalItemsQuery { ParentId = Id, GroupByPresentationUniqueKey = false diff --git a/MediaBrowser.Controller/Entities/GameGenre.cs b/MediaBrowser.Controller/Entities/GameGenre.cs index 7c1e88cb1..45e766c0f 100644 --- a/MediaBrowser.Controller/Entities/GameGenre.cs +++ b/MediaBrowser.Controller/Entities/GameGenre.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; +using MediaBrowser.Common.Extensions; namespace MediaBrowser.Controller.Entities { @@ -11,10 +12,18 @@ namespace MediaBrowser.Controller.Entities { var list = base.GetUserDataKeys(); - list.Insert(0, "GameGenre-" + Name); + list.Insert(0, GetType().Name + "-" + (Name ?? string.Empty).RemoveDiacritics()); return list; } + public override string PresentationUniqueKey + { + get + { + return GetUserDataKeys()[0]; + } + } + /// /// Returns the folder containing the item. /// If the item is a folder, it returns the folder itself diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs index c87d4daaf..cc5aebb2a 100644 --- a/MediaBrowser.Controller/Entities/Genre.cs +++ b/MediaBrowser.Controller/Entities/Genre.cs @@ -3,6 +3,7 @@ using MediaBrowser.Controller.Entities.Audio; using System; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Common.Extensions; namespace MediaBrowser.Controller.Entities { @@ -15,10 +16,18 @@ namespace MediaBrowser.Controller.Entities { var list = base.GetUserDataKeys(); - list.Insert(0, "Genre-" + Name); + list.Insert(0, GetType().Name + "-" + (Name ?? string.Empty).RemoveDiacritics()); return list; } + public override string PresentationUniqueKey + { + get + { + return GetUserDataKeys()[0]; + } + } + /// /// Returns the folder containing the item. /// If the item is a folder, it returns the folder itself diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs index 2b099e3d5..8ef0d70bf 100644 --- a/MediaBrowser.Controller/Entities/Person.cs +++ b/MediaBrowser.Controller/Entities/Person.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; +using MediaBrowser.Common.Extensions; using MediaBrowser.Model.Entities; namespace MediaBrowser.Controller.Entities @@ -22,10 +23,18 @@ namespace MediaBrowser.Controller.Entities { var list = base.GetUserDataKeys(); - list.Insert(0, "Person-" + Name); + list.Insert(0, GetType().Name + "-" + (Name ?? string.Empty).RemoveDiacritics()); return list; } + public override string PresentationUniqueKey + { + get + { + return GetUserDataKeys()[0]; + } + } + public PersonLookupInfo GetLookupInfo() { return GetItemLookupInfo(); diff --git a/MediaBrowser.Controller/Entities/Studio.cs b/MediaBrowser.Controller/Entities/Studio.cs index e46978af3..762798b55 100644 --- a/MediaBrowser.Controller/Entities/Studio.cs +++ b/MediaBrowser.Controller/Entities/Studio.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; +using MediaBrowser.Common.Extensions; namespace MediaBrowser.Controller.Entities { @@ -14,10 +15,18 @@ namespace MediaBrowser.Controller.Entities { var list = base.GetUserDataKeys(); - list.Insert(0, "Studio-" + Name); + list.Insert(0, GetType().Name + "-" + (Name ?? string.Empty).RemoveDiacritics()); return list; } + public override string PresentationUniqueKey + { + get + { + return GetUserDataKeys()[0]; + } + } + /// /// Returns the folder containing the item. /// If the item is a folder, it returns the folder itself diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs index 2502033c8..73c893dd6 100644 --- a/MediaBrowser.Controller/Entities/Video.cs +++ b/MediaBrowser.Controller/Entities/Video.cs @@ -58,10 +58,7 @@ namespace MediaBrowser.Controller.Entities } } - public long? Size { get; set; } - public string Container { get; set; } public int? TotalBitrate { get; set; } - public string ShortOverview { get; set; } public ExtraType? ExtraType { get; set; } /// diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 1d0e06482..4e641b005 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -11,6 +11,7 @@ using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using CommonIO; +using MediaBrowser.Model.Dto; namespace MediaBrowser.Controller.Library { @@ -567,5 +568,12 @@ namespace MediaBrowser.Controller.Library void RemoveVirtualFolder(string name, bool refreshLibrary); void AddMediaPath(string virtualFolderName, string path); void RemoveMediaPath(string virtualFolderName, string path); + + QueryResult> GetGenres(InternalItemsQuery query); + QueryResult> GetMusicGenres(InternalItemsQuery query); + QueryResult> GetGameGenres(InternalItemsQuery query); + QueryResult> GetStudios(InternalItemsQuery query); + QueryResult> GetArtists(InternalItemsQuery query); + QueryResult> GetAlbumArtists(InternalItemsQuery query); } } \ No newline at end of file diff --git a/MediaBrowser.Controller/Persistence/IItemRepository.cs b/MediaBrowser.Controller/Persistence/IItemRepository.cs index 80a6e4042..2ef8b70f0 100644 --- a/MediaBrowser.Controller/Persistence/IItemRepository.cs +++ b/MediaBrowser.Controller/Persistence/IItemRepository.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.Querying; namespace MediaBrowser.Controller.Persistence @@ -161,6 +162,13 @@ namespace MediaBrowser.Controller.Persistence /// The cancellation token. /// Task. Task UpdateInheritedValues(CancellationToken cancellationToken); + + QueryResult> GetGenres(InternalItemsQuery query); + QueryResult> GetMusicGenres(InternalItemsQuery query); + QueryResult> GetGameGenres(InternalItemsQuery query); + QueryResult> GetStudios(InternalItemsQuery query); + QueryResult> GetArtists(InternalItemsQuery query); + QueryResult> GetAlbumArtists(InternalItemsQuery query); } } diff --git a/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj b/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj index f759ffeae..f9d28605e 100644 --- a/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj +++ b/MediaBrowser.Model.Portable/MediaBrowser.Model.Portable.csproj @@ -599,9 +599,6 @@ Entities\Video3DFormat.cs - - Entities\VideoSize.cs - Entities\VideoType.cs diff --git a/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj b/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj index 05bbeb50e..edaa0e027 100644 --- a/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj +++ b/MediaBrowser.Model.net35/MediaBrowser.Model.net35.csproj @@ -573,9 +573,6 @@ Entities\Video3DFormat.cs - - Entities\VideoSize.cs - Entities\VideoType.cs diff --git a/MediaBrowser.Model/Dto/ItemCounts.cs b/MediaBrowser.Model/Dto/ItemCounts.cs index a3a00c341..07ddfa1ac 100644 --- a/MediaBrowser.Model/Dto/ItemCounts.cs +++ b/MediaBrowser.Model/Dto/ItemCounts.cs @@ -60,5 +60,6 @@ /// /// The book count. public int BookCount { get; set; } + public int ItemCount { get; set; } } } diff --git a/MediaBrowser.Model/Entities/MediaUrl.cs b/MediaBrowser.Model/Entities/MediaUrl.cs index 24e3b1492..2e17bba8a 100644 --- a/MediaBrowser.Model/Entities/MediaUrl.cs +++ b/MediaBrowser.Model/Entities/MediaUrl.cs @@ -5,6 +5,5 @@ namespace MediaBrowser.Model.Entities { public string Url { get; set; } public string Name { get; set; } - public VideoSize? VideoSize { get; set; } } } diff --git a/MediaBrowser.Model/Entities/VideoSize.cs b/MediaBrowser.Model/Entities/VideoSize.cs deleted file mode 100644 index 0100f3b90..000000000 --- a/MediaBrowser.Model/Entities/VideoSize.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace MediaBrowser.Model.Entities -{ - public enum VideoSize - { - StandardDefinition, - HighDefinition - } -} \ No newline at end of file diff --git a/MediaBrowser.Model/MediaBrowser.Model.csproj b/MediaBrowser.Model/MediaBrowser.Model.csproj index 522b7d38d..7c9f132db 100644 --- a/MediaBrowser.Model/MediaBrowser.Model.csproj +++ b/MediaBrowser.Model/MediaBrowser.Model.csproj @@ -227,7 +227,6 @@ - diff --git a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs index 3b3065893..a6b6de7e5 100644 --- a/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs +++ b/MediaBrowser.Providers/Movies/GenericMovieDbInfo.cs @@ -326,8 +326,7 @@ namespace MediaBrowser.Providers.Movies hasTrailers.RemoteTrailers = movieData.trailers.youtube.Select(i => new MediaUrl { Url = string.Format("https://www.youtube.com/watch?v={0}", i.source), - Name = i.name, - VideoSize = string.Equals("hd", i.size, StringComparison.OrdinalIgnoreCase) ? VideoSize.HighDefinition : VideoSize.StandardDefinition + Name = i.name }).ToList(); } diff --git a/MediaBrowser.Server.Implementations/Dto/DtoService.cs b/MediaBrowser.Server.Implementations/Dto/DtoService.cs index 95a235109..bb9fcc924 100644 --- a/MediaBrowser.Server.Implementations/Dto/DtoService.cs +++ b/MediaBrowser.Server.Implementations/Dto/DtoService.cs @@ -418,7 +418,7 @@ namespace MediaBrowser.Server.Implementations.Dto var dto = GetBaseItemDtoInternal(item, options, GetSyncedItemProgressDictionary(syncProgress), user); - if (options.Fields.Contains(ItemFields.ItemCounts)) + if (taggedItems != null && options.Fields.Contains(ItemFields.ItemCounts)) { SetItemByNameInfo(item, dto, taggedItems, user); } diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index c0c40aa5b..09dc0400c 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -33,6 +33,7 @@ using System.Net; using System.Threading; using System.Threading.Tasks; using CommonIO; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.Extensions; using MediaBrowser.Model.Library; using MediaBrowser.Model.Net; @@ -1278,7 +1279,7 @@ namespace MediaBrowser.Server.Implementations.Library private bool EnableCaching { - get { return true; } + get { return false; } } public IEnumerable GetItemList(InternalItemsQuery query) @@ -1326,6 +1327,99 @@ namespace MediaBrowser.Server.Implementations.Library return ItemRepository.GetItemIdsList(query); } + public QueryResult> GetStudios(InternalItemsQuery query) + { + if (query.User != null) + { + AddUserToQuery(query, query.User); + } + + SetTopParentOrAncestorIds(query); + return ItemRepository.GetStudios(query); + } + + public QueryResult> GetGenres(InternalItemsQuery query) + { + if (query.User != null) + { + AddUserToQuery(query, query.User); + } + + SetTopParentOrAncestorIds(query); + return ItemRepository.GetGenres(query); + } + + public QueryResult> GetGameGenres(InternalItemsQuery query) + { + if (query.User != null) + { + AddUserToQuery(query, query.User); + } + + SetTopParentOrAncestorIds(query); + return ItemRepository.GetGameGenres(query); + } + + public QueryResult> GetMusicGenres(InternalItemsQuery query) + { + if (query.User != null) + { + AddUserToQuery(query, query.User); + } + + SetTopParentOrAncestorIds(query); + return ItemRepository.GetMusicGenres(query); + } + + public QueryResult> GetArtists(InternalItemsQuery query) + { + if (query.User != null) + { + AddUserToQuery(query, query.User); + } + + SetTopParentOrAncestorIds(query); + return ItemRepository.GetArtists(query); + } + + private void SetTopParentOrAncestorIds(InternalItemsQuery query) + { + if (query.AncestorIds.Length == 0) + { + return; + } + + var parents = query.AncestorIds.Select(i => GetItemById(new Guid(i))).ToList(); + + 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(); + query.AncestorIds = new string[] { }; + } + } + + public QueryResult> GetAlbumArtists(InternalItemsQuery query) + { + if (query.User != null) + { + AddUserToQuery(query, query.User); + } + + SetTopParentOrAncestorIds(query); + return ItemRepository.GetAlbumArtists(query); + } + public IEnumerable GetItemList(InternalItemsQuery query, IEnumerable parentIds) { var parents = parentIds.Select(i => GetItemById(new Guid(i))).Where(i => i != null).ToList(); diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs index 9edd3f83f..703a33856 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -126,7 +126,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers } else { - var videoInfo = parser.ResolveFile(args.Path); + var videoInfo = parser.Resolve(args.Path, false, false); if (videoInfo == null) { diff --git a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj index 066a8c3ca..c69c788c8 100644 --- a/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj +++ b/MediaBrowser.Server.Implementations/MediaBrowser.Server.Implementations.csproj @@ -56,8 +56,8 @@ ..\packages\Interfaces.IO.1.0.0.5\lib\portable-net45+sl4+wp71+win8+wpa81\Interfaces.IO.dll - - ..\packages\MediaBrowser.Naming.1.0.0.51\lib\portable-net45+sl4+wp71+win8+wpa81\MediaBrowser.Naming.dll + + ..\packages\MediaBrowser.Naming.1.0.0.52\lib\portable-net45+sl4+wp71+win8+wpa81\MediaBrowser.Naming.dll True diff --git a/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs b/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs index 2a2f9a09d..b11a3e496 100644 --- a/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs +++ b/MediaBrowser.Server.Implementations/Persistence/CleanDatabaseScheduledTask.cs @@ -15,6 +15,7 @@ using System.Threading.Tasks; using CommonIO; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.LiveTv; using MediaBrowser.Controller.Localization; using MediaBrowser.Controller.Net; using MediaBrowser.Server.Implementations.ScheduledTasks; @@ -145,7 +146,8 @@ namespace MediaBrowser.Server.Implementations.Persistence { var itemIds = _libraryManager.GetItemIds(new InternalItemsQuery { - IsCurrentSchema = false + IsCurrentSchema = false, + ExcludeItemTypes = new[] { typeof(LiveTvProgram).Name } }); var numComplete = 0; @@ -236,14 +238,14 @@ namespace MediaBrowser.Server.Implementations.Persistence // 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, - typeof(Channel).Name, - typeof(AggregateFolder).Name, + 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 } }); @@ -313,8 +315,8 @@ namespace MediaBrowser.Server.Implementations.Persistence public IEnumerable GetDefaultTriggers() { - return new ITaskTrigger[] - { + return new ITaskTrigger[] + { new IntervalTrigger{ Interval = TimeSpan.FromHours(24)} }; } diff --git a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs index 437d16974..121074a6e 100644 --- a/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs +++ b/MediaBrowser.Server.Implementations/Persistence/SqliteItemRepository.cs @@ -22,6 +22,7 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Controller.Channels; using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Playlists; +using MediaBrowser.Model.Dto; using MediaBrowser.Model.LiveTv; namespace MediaBrowser.Server.Implementations.Persistence @@ -94,7 +95,7 @@ namespace MediaBrowser.Server.Implementations.Persistence private IDbCommand _updateInheritedRatingCommand; private IDbCommand _updateInheritedTagsCommand; - public const int LatestSchemaVersion = 92; + public const int LatestSchemaVersion = 95; /// /// Initializes a new instance of the class. @@ -157,7 +158,7 @@ namespace MediaBrowser.Server.Implementations.Persistence "create table if not exists UserDataKeys (ItemId GUID, UserDataKey TEXT, PRIMARY KEY (ItemId, UserDataKey))", "create index if not exists idx_UserDataKeys1 on UserDataKeys(ItemId)", - "create table if not exists ItemValues (ItemId GUID, Type INT, Value TEXT)", + "create table if not exists ItemValues (ItemId GUID, Type INT, Value TEXT, CleanValue TEXT)", "create index if not exists idx_ItemValues on ItemValues(ItemId)", "create index if not exists idx_ItemValues2 on ItemValues(ItemId,Type)", @@ -263,6 +264,7 @@ namespace MediaBrowser.Server.Implementations.Persistence _connection.AddColumn(Logger, "TypedBaseItems", "SeriesName", "Text"); _connection.AddColumn(Logger, "UserDataKeys", "Priority", "INT"); + _connection.AddColumn(Logger, "ItemValues", "CleanValue", "Text"); string[] postQueries = { @@ -568,10 +570,11 @@ namespace MediaBrowser.Server.Implementations.Persistence _deleteItemValuesCommand.Parameters.Add(_deleteItemValuesCommand, "@Id"); _saveItemValuesCommand = _connection.CreateCommand(); - _saveItemValuesCommand.CommandText = "insert into ItemValues (ItemId, Type, Value) values (@ItemId, @Type, @Value)"; + _saveItemValuesCommand.CommandText = "insert into ItemValues (ItemId, Type, Value, CleanValue) values (@ItemId, @Type, @Value, @CleanValue)"; _saveItemValuesCommand.Parameters.Add(_saveItemValuesCommand, "@ItemId"); _saveItemValuesCommand.Parameters.Add(_saveItemValuesCommand, "@Type"); _saveItemValuesCommand.Parameters.Add(_saveItemValuesCommand, "@Value"); + _saveItemValuesCommand.Parameters.Add(_saveItemValuesCommand, "@CleanValue"); // provider ids _deleteProviderIdsCommand = _connection.CreateCommand(); @@ -905,7 +908,7 @@ namespace MediaBrowser.Server.Implementations.Persistence UpdateUserDataKeys(item.Id, item.GetUserDataKeys().Distinct(StringComparer.OrdinalIgnoreCase).ToList(), transaction); UpdateImages(item.Id, item.ImageInfos, transaction); UpdateProviderIds(item.Id, item.ProviderIds, transaction); - UpdateItemValues(item.Id, GetItemValues(item), transaction); + UpdateItemValues(item.Id, GetItemValuesToSave(item), transaction); } transaction.Commit(); @@ -2019,7 +2022,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } if (string.Equals(name, ItemSortBy.SeriesDatePlayed, StringComparison.OrdinalIgnoreCase)) { - return new Tuple("(Select MAX(LastPlayedDate) from TypedBaseItems B"+ GetJoinUserDataText(query) + " where B.Guid in (Select ItemId from AncestorIds where AncestorId in (select guid from typedbaseitems c where C.Type = 'MediaBrowser.Controller.Entities.TV.Series' And C.Guid in (Select AncestorId from AncestorIds where ItemId=A.Guid))))", false); + return new Tuple("(Select MAX(LastPlayedDate) from TypedBaseItems B" + GetJoinUserDataText(query) + " where B.Guid in (Select ItemId from AncestorIds where AncestorId in (select guid from typedbaseitems c where C.Type = 'MediaBrowser.Controller.Entities.TV.Series' And C.Guid in (Select AncestorId from AncestorIds where ItemId=A.Guid))))", false); } return new Tuple(name, false); @@ -2245,7 +2248,7 @@ namespace MediaBrowser.Server.Implementations.Persistence } } - private List GetWhereClauses(InternalItemsQuery query, IDbCommand cmd) + private List GetWhereClauses(InternalItemsQuery query, IDbCommand cmd, string paramSuffix = "") { var whereClauses = new List(); @@ -2321,8 +2324,8 @@ namespace MediaBrowser.Server.Implementations.Persistence var includeTypes = query.IncludeItemTypes.SelectMany(MapIncludeItemTypes).ToArray(); if (includeTypes.Length == 1) { - whereClauses.Add("type=@type"); - cmd.Parameters.Add(cmd, "@type", DbType.String).Value = includeTypes[0]; + whereClauses.Add("type=@type" + paramSuffix); + cmd.Parameters.Add(cmd, "@type" + paramSuffix, DbType.String).Value = includeTypes[0]; } else if (includeTypes.Length > 1) { @@ -2626,8 +2629,8 @@ namespace MediaBrowser.Server.Implementations.Persistence var index = 0; foreach (var artist in query.ArtistNames) { - clauses.Add("@ArtistName" + index + " in (select value from itemvalues where ItemId=Guid and Type <= 1)"); - cmd.Parameters.Add(cmd, "@ArtistName" + index, DbType.String).Value = artist; + clauses.Add("@ArtistName" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type <= 1)"); + cmd.Parameters.Add(cmd, "@ArtistName" + index, DbType.String).Value = artist.RemoveDiacritics(); index++; } var clause = "(" + string.Join(" OR ", clauses.ToArray()) + ")"; @@ -2640,8 +2643,8 @@ namespace MediaBrowser.Server.Implementations.Persistence var index = 0; foreach (var item in query.Genres) { - clauses.Add("@Genre" + index + " in (select value from itemvalues where ItemId=Guid and Type=2)"); - cmd.Parameters.Add(cmd, "@Genre" + index, DbType.String).Value = item; + clauses.Add("@Genre" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type=2)"); + cmd.Parameters.Add(cmd, "@Genre" + index, DbType.String).Value = item.RemoveDiacritics(); index++; } var clause = "(" + string.Join(" OR ", clauses.ToArray()) + ")"; @@ -2654,8 +2657,8 @@ namespace MediaBrowser.Server.Implementations.Persistence var index = 0; foreach (var item in query.Tags) { - clauses.Add("@Tag" + index + " in (select value from itemvalues where ItemId=Guid and Type=4)"); - cmd.Parameters.Add(cmd, "@Tag" + index, DbType.String).Value = item; + clauses.Add("@Tag" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type=4)"); + cmd.Parameters.Add(cmd, "@Tag" + index, DbType.String).Value = item.RemoveDiacritics(); index++; } var clause = "(" + string.Join(" OR ", clauses.ToArray()) + ")"; @@ -2668,8 +2671,8 @@ namespace MediaBrowser.Server.Implementations.Persistence var index = 0; foreach (var item in query.Studios) { - clauses.Add("@Studio" + index + " in (select value from itemvalues where ItemId=Guid and Type=3)"); - cmd.Parameters.Add(cmd, "@Studio" + index, DbType.String).Value = item; + clauses.Add("@Studio" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type=3)"); + cmd.Parameters.Add(cmd, "@Studio" + index, DbType.String).Value = item.RemoveDiacritics(); index++; } var clause = "(" + string.Join(" OR ", clauses.ToArray()) + ")"; @@ -2682,8 +2685,8 @@ namespace MediaBrowser.Server.Implementations.Persistence var index = 0; foreach (var item in query.Keywords) { - clauses.Add("@Keyword" + index + " in (select value from itemvalues where ItemId=Guid and Type=5)"); - cmd.Parameters.Add(cmd, "@Keyword" + index, DbType.String).Value = item; + clauses.Add("@Keyword" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type=5)"); + cmd.Parameters.Add(cmd, "@Keyword" + index, DbType.String).Value = item.RemoveDiacritics(); index++; } var clause = "(" + string.Join(" OR ", clauses.ToArray()) + ")"; @@ -2812,6 +2815,20 @@ namespace MediaBrowser.Server.Implementations.Persistence whereClauses.Add("MediaType in (" + val + ")"); } + if (query.ItemIds.Length > 0) + { + var excludeIds = new List(); + + var index = 0; + foreach (var id in query.ItemIds) + { + excludeIds.Add("Guid = @IncludeId" + index); + cmd.Parameters.Add(cmd, "@IncludeId" + index, DbType.Guid).Value = new Guid(id); + index++; + } + + whereClauses.Add(string.Join(" OR ", excludeIds.ToArray())); + } if (query.ExcludeItemIds.Length > 0) { var excludeIds = new List(); @@ -3478,7 +3495,292 @@ namespace MediaBrowser.Server.Implementations.Persistence } } - private List> GetItemValues(BaseItem item) + public QueryResult> GetArtists(InternalItemsQuery query) + { + return GetItemValues(query, 0, typeof(MusicArtist).FullName); + } + + public QueryResult> GetAlbumArtists(InternalItemsQuery query) + { + return GetItemValues(query, 1, typeof(MusicArtist).FullName); + } + + public QueryResult> GetStudios(InternalItemsQuery query) + { + return GetItemValues(query, 3, typeof(Studio).FullName); + } + + public QueryResult> GetGenres(InternalItemsQuery query) + { + return GetItemValues(query, 2, typeof(Genre).FullName); + } + + public QueryResult> GetGameGenres(InternalItemsQuery query) + { + return GetItemValues(query, 2, typeof(GameGenre).FullName); + } + + public QueryResult> GetMusicGenres(InternalItemsQuery query) + { + return GetItemValues(query, 2, typeof(MusicGenre).FullName); + } + + private QueryResult> GetItemValues(InternalItemsQuery query, int itemValueType, string returnType) + { + if (query == null) + { + throw new ArgumentNullException("query"); + } + + if (!query.Limit.HasValue) + { + query.EnableTotalRecordCount = false; + } + + CheckDisposed(); + + var now = DateTime.UtcNow; + + using (var cmd = _connection.CreateCommand()) + { + var itemCountColumns = new List>(); + + var typesToCount = query.IncludeItemTypes.ToList(); + + if (typesToCount.Count == 0) + { + //typesToCount.Add("Item"); + } + + foreach (var type in typesToCount) + { + var itemCountColumnQuery = "Select Count(Value) from ItemValues where ItemValues.CleanValue=CleanName AND Type=@ItemValueType AND ItemId in ("; + itemCountColumnQuery += "select guid" + GetFromText(); + + var typeSubQuery = new InternalItemsQuery(query.User) + { + ExcludeItemTypes = query.ExcludeItemTypes, + MediaTypes = query.MediaTypes, + AncestorIds = query.AncestorIds, + ExcludeItemIds = query.ExcludeItemIds, + ItemIds = query.ItemIds, + TopParentIds = query.TopParentIds, + ParentId = query.ParentId, + IsPlayed = query.IsPlayed + }; + if (string.Equals(type, "Item", StringComparison.OrdinalIgnoreCase)) + { + typeSubQuery.IncludeItemTypes = query.IncludeItemTypes; + } + else + { + typeSubQuery.IncludeItemTypes = new[] { type }; + } + var whereClauses = GetWhereClauses(typeSubQuery, cmd, type); + + var typeWhereText = whereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", whereClauses.ToArray()); + + itemCountColumnQuery += typeWhereText; + + itemCountColumnQuery += ")"; + + var columnName = type + "Count"; + + itemCountColumns.Add(new Tuple(columnName, "(" + itemCountColumnQuery + ") as " + columnName)); + } + + var columns = _retriveItemColumns.ToList(); + columns.AddRange(itemCountColumns.Select(i => i.Item2).ToArray()); + + cmd.CommandText = "select " + string.Join(",", GetFinalColumnsToSelect(query, columns.ToArray(), cmd)) + GetFromText(); + cmd.CommandText += GetJoinUserDataText(query); + + var innerQuery = new InternalItemsQuery(query.User) + { + ExcludeItemTypes = query.ExcludeItemTypes, + IncludeItemTypes = query.IncludeItemTypes, + MediaTypes = query.MediaTypes, + AncestorIds = query.AncestorIds, + ExcludeItemIds = query.ExcludeItemIds, + ItemIds = query.ItemIds, + TopParentIds = query.TopParentIds, + ParentId = query.ParentId, + IsPlayed = query.IsPlayed + }; + + var innerWhereClauses = GetWhereClauses(innerQuery, cmd); + + var innerWhereText = innerWhereClauses.Count == 0 ? + string.Empty : + " where " + string.Join(" AND ", innerWhereClauses.ToArray()); + + var whereText = " where Type=@SelectType"; + whereText += " And CleanName In (Select CleanValue from ItemValues where Type=@ItemValueType AND ItemId in (select guid from TypedBaseItems" + innerWhereText + "))"; + cmd.CommandText += whereText; + + var outerQuery = new InternalItemsQuery(query.User) + { + IsFavorite = query.IsFavorite, + IsFavoriteOrLiked = query.IsFavoriteOrLiked, + IsLiked = query.IsLiked, + IsLocked = query.IsLocked, + NameLessThan = query.NameLessThan, + NameStartsWith = query.NameStartsWith, + NameStartsWithOrGreater = query.NameStartsWithOrGreater, + AlbumArtistStartsWithOrGreater = query.AlbumArtistStartsWithOrGreater, + Tags = query.Tags, + OfficialRatings = query.OfficialRatings, + Genres = query.GenreIds, + Years = query.Years + }; + + var outerWhereClauses = GetWhereClauses(outerQuery, cmd); + + var outerWhereText = outerWhereClauses.Count == 0 ? + string.Empty : + " AND " + string.Join(" AND ", outerWhereClauses.ToArray()); + cmd.CommandText += outerWhereText; + + cmd.Parameters.Add(cmd, "@SelectType", DbType.String).Value = returnType; + cmd.Parameters.Add(cmd, "@ItemValueType", DbType.Int32).Value = itemValueType; + + if (EnableJoinUserData(query)) + { + cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = query.User.Id; + } + + //cmd.CommandText += GetGroupBy(query); + cmd.CommandText += " group by PresentationUniqueKey"; + + cmd.CommandText += " order by SortName"; + + if (query.Limit.HasValue || query.StartIndex.HasValue) + { + var limit = query.Limit ?? int.MaxValue; + + cmd.CommandText += " LIMIT " + limit.ToString(CultureInfo.InvariantCulture); + + if (query.StartIndex.HasValue) + { + cmd.CommandText += " OFFSET " + query.StartIndex.Value.ToString(CultureInfo.InvariantCulture); + } + } + + cmd.CommandText += ";"; + + var isReturningZeroItems = query.Limit.HasValue && query.Limit <= 0; + + if (isReturningZeroItems) + { + cmd.CommandText = ""; + } + + if (query.EnableTotalRecordCount) + { + cmd.CommandText += "select count (guid)" + GetFromText(); + + cmd.CommandText += GetJoinUserDataText(query); + cmd.CommandText += whereText; + } + else + { + cmd.CommandText = cmd.CommandText.TrimEnd(';'); + } + + var list = new List>(); + var count = 0; + + var commandBehavior = isReturningZeroItems || !query.EnableTotalRecordCount + ? (CommandBehavior.SequentialAccess | CommandBehavior.SingleResult) + : CommandBehavior.SequentialAccess; + + using (var reader = cmd.ExecuteReader(commandBehavior)) + { + LogQueryTime("GetItemValues", cmd, now); + + if (isReturningZeroItems) + { + if (reader.Read()) + { + count = reader.GetInt32(0); + } + } + else + { + while (reader.Read()) + { + var item = GetItem(reader); + if (item != null) + { + var countStartColumn = columns.Count - typesToCount.Count; + + list.Add(new Tuple(item, GetItemCounts(reader, countStartColumn, typesToCount))); + } + } + + if (reader.NextResult() && reader.Read()) + { + count = reader.GetInt32(0); + } + } + } + + if (count == 0) + { + count = list.Count; + } + + return new QueryResult> + { + Items = list.ToArray(), + TotalRecordCount = count + }; + + } + } + + private ItemCounts GetItemCounts(IDataReader reader, int countStartColumn, List typesToCount) + { + var counts = new ItemCounts(); + + for (var i = 0; i < typesToCount.Count; i++) + { + var value = reader.GetInt32(countStartColumn + i); + + var type = typesToCount[i]; + if (string.Equals(type, "Series", StringComparison.OrdinalIgnoreCase)) + { + counts.SeriesCount = value; + } + else if (string.Equals(type, "Episode", StringComparison.OrdinalIgnoreCase)) + { + counts.EpisodeCount = value; + } + else if (string.Equals(type, "Movie", StringComparison.OrdinalIgnoreCase)) + { + counts.MovieCount = value; + } + else if (string.Equals(type, "MusicAlbum", StringComparison.OrdinalIgnoreCase)) + { + counts.AlbumCount = value; + } + else if (string.Equals(type, "Audio", StringComparison.OrdinalIgnoreCase)) + { + counts.SongCount = value; + } + else if (string.Equals(type, "Game", StringComparison.OrdinalIgnoreCase)) + { + counts.GameCount = value; + } + counts.ItemCount += value; + } + + return counts; + } + + private List> GetItemValuesToSave(BaseItem item) { var list = new List>(); @@ -3604,6 +3906,14 @@ namespace MediaBrowser.Server.Implementations.Persistence _saveItemValuesCommand.GetParameter(0).Value = itemId; _saveItemValuesCommand.GetParameter(1).Value = pair.Item1; _saveItemValuesCommand.GetParameter(2).Value = pair.Item2; + if (pair.Item2 == null) + { + _saveItemValuesCommand.GetParameter(3).Value = null; + } + else + { + _saveItemValuesCommand.GetParameter(3).Value = pair.Item2.RemoveDiacritics(); + } _saveItemValuesCommand.Transaction = transaction; _saveItemValuesCommand.ExecuteNonQuery(); diff --git a/MediaBrowser.Server.Implementations/packages.config b/MediaBrowser.Server.Implementations/packages.config index 42fc51a63..326721ff3 100644 --- a/MediaBrowser.Server.Implementations/packages.config +++ b/MediaBrowser.Server.Implementations/packages.config @@ -4,7 +4,7 @@ - + -- cgit v1.2.3 From 0920c9b3a1f02066573b1fb7c4ba186c0558e5c4 Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Fri, 1 Jul 2016 11:51:35 -0400 Subject: next up upgrade fixes --- MediaBrowser.Controller/Entities/BaseItem.cs | 4 +-- MediaBrowser.Controller/Entities/TV/Series.cs | 23 +++++++++++----- .../Entities/UserViewBuilder.cs | 3 ++- MediaBrowser.Controller/Library/ILibraryManager.cs | 7 ----- .../Library/LibraryManager.cs | 10 ------- .../TV/TVSeriesManager.cs | 31 +++++++++++++++------- .../ApplicationHost.cs | 2 +- 7 files changed, 42 insertions(+), 38 deletions(-) (limited to 'MediaBrowser.Controller/Library/ILibraryManager.cs') diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 0dd7b3c83..9d1a45689 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1655,7 +1655,7 @@ namespace MediaBrowser.Controller.Entities if (datePlayed.HasValue) { - // Incremenet + // Increment data.PlayCount++; } @@ -1667,7 +1667,7 @@ namespace MediaBrowser.Controller.Entities data.PlaybackPositionTicks = 0; } - data.LastPlayedDate = datePlayed ?? data.LastPlayedDate; + data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow; data.Played = true; await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false); diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 1cc496b35..09ddbc6b6 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -111,11 +111,20 @@ namespace MediaBrowser.Controller.Entities.TV } } + private static string GetUniqueSeriesKey(BaseItem series) + { + if (ConfigurationManager.Configuration.SchemaVersion < 97) + { + return series.Id.ToString("N"); + } + return series.PresentationUniqueKey; + } + public override int GetChildCount(User user) { var result = LibraryManager.GetItemsResult(new InternalItemsQuery(user) { - AncestorWithPresentationUniqueKey = PresentationUniqueKey, + AncestorWithPresentationUniqueKey = GetUniqueSeriesKey(this), IncludeItemTypes = new[] { typeof(Season).Name }, SortBy = new[] { ItemSortBy.SortName }, IsVirtualItem = false, @@ -202,7 +211,7 @@ namespace MediaBrowser.Controller.Entities.TV if (query.Recursive) { - query.AncestorWithPresentationUniqueKey = PresentationUniqueKey; + query.AncestorWithPresentationUniqueKey = GetUniqueSeriesKey(this); if (query.SortBy.Length == 0) { query.SortBy = new[] { ItemSortBy.SortName }; @@ -228,7 +237,7 @@ namespace MediaBrowser.Controller.Entities.TV seasons = LibraryManager.GetItemList(new InternalItemsQuery(user) { - AncestorWithPresentationUniqueKey = PresentationUniqueKey, + AncestorWithPresentationUniqueKey = GetUniqueSeriesKey(this), IncludeItemTypes = new[] { typeof(Season).Name }, SortBy = new[] { ItemSortBy.SortName } @@ -257,7 +266,7 @@ namespace MediaBrowser.Controller.Entities.TV { var allItems = LibraryManager.GetItemList(new InternalItemsQuery(user) { - AncestorWithPresentationUniqueKey = PresentationUniqueKey, + AncestorWithPresentationUniqueKey = GetUniqueSeriesKey(this), IncludeItemTypes = new[] { typeof(Episode).Name, typeof(Season).Name }, SortBy = new[] { ItemSortBy.SortName } @@ -354,7 +363,7 @@ namespace MediaBrowser.Controller.Entities.TV { return LibraryManager.GetItemList(new InternalItemsQuery(user) { - AncestorWithPresentationUniqueKey = PresentationUniqueKey, + AncestorWithPresentationUniqueKey = GetUniqueSeriesKey(this), IncludeItemTypes = new[] { typeof(Episode).Name }, SortBy = new[] { ItemSortBy.SortName } @@ -423,7 +432,7 @@ namespace MediaBrowser.Controller.Entities.TV public static IEnumerable FilterEpisodesBySeason(IEnumerable episodes, Season parentSeason, bool includeSpecials) { var seasonNumber = parentSeason.IndexNumber; - var seasonPresentationKey = parentSeason.PresentationUniqueKey; + var seasonPresentationKey = GetUniqueSeriesKey(parentSeason); var supportSpecialsInSeason = includeSpecials && seasonNumber.HasValue && seasonNumber.Value != 0; @@ -443,7 +452,7 @@ namespace MediaBrowser.Controller.Entities.TV if (!episode.ParentIndexNumber.HasValue) { var season = episode.Season; - return season != null && string.Equals(season.PresentationUniqueKey, seasonPresentationKey, StringComparison.OrdinalIgnoreCase); + return season != null && string.Equals(GetUniqueSeriesKey(season), seasonPresentationKey, StringComparison.OrdinalIgnoreCase); } return false; diff --git a/MediaBrowser.Controller/Entities/UserViewBuilder.cs b/MediaBrowser.Controller/Entities/UserViewBuilder.cs index 175a7240c..e2228bcaf 100644 --- a/MediaBrowser.Controller/Entities/UserViewBuilder.cs +++ b/MediaBrowser.Controller/Entities/UserViewBuilder.cs @@ -20,6 +20,7 @@ using System.Threading; using System.Threading.Tasks; using MediaBrowser.Controller.Configuration; using MediaBrowser.Model.Configuration; +using MoreLinq; namespace MediaBrowser.Controller.Entities { @@ -1200,7 +1201,7 @@ namespace MediaBrowser.Controller.Entities { var user = query.User; - items = libraryManager.ReplaceVideosWithPrimaryVersions(items); + items = items.DistinctBy(i => i.PresentationUniqueKey, StringComparer.OrdinalIgnoreCase); if (query.SortBy.Length > 0) { diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index 4e641b005..ad38b9ea5 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -308,13 +308,6 @@ namespace MediaBrowser.Controller.Library /// Task. Task DeleteItem(BaseItem item, DeleteOptions options); - /// - /// Replaces the videos with primary versions. - /// - /// The items. - /// IEnumerable{BaseItem}. - IEnumerable ReplaceVideosWithPrimaryVersions(IEnumerable items); - /// /// Gets the named view. /// diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 4c0514035..9d66455e7 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -526,16 +526,6 @@ namespace MediaBrowser.Server.Implementations.Library return key.GetMD5(); } - public IEnumerable ReplaceVideosWithPrimaryVersions(IEnumerable items) - { - if (items == null) - { - throw new ArgumentNullException("items"); - } - - return items.DistinctBy(i => i.PresentationUniqueKey, StringComparer.OrdinalIgnoreCase); - } - /// /// Ensure supplied item has only one instance throughout /// diff --git a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs index b65c030f0..d51f61b9a 100644 --- a/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs +++ b/MediaBrowser.Server.Implementations/TV/TVSeriesManager.cs @@ -7,6 +7,7 @@ using MediaBrowser.Model.Querying; using System; using System.Collections.Generic; using System.Linq; +using MediaBrowser.Controller.Configuration; namespace MediaBrowser.Server.Implementations.TV { @@ -15,12 +16,14 @@ namespace MediaBrowser.Server.Implementations.TV private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; private readonly ILibraryManager _libraryManager; + private readonly IServerConfigurationManager _config; - public TVSeriesManager(IUserManager userManager, IUserDataManager userDataManager, ILibraryManager libraryManager) + public TVSeriesManager(IUserManager userManager, IUserDataManager userDataManager, ILibraryManager libraryManager, IServerConfigurationManager config) { _userManager = userManager; _userDataManager = userDataManager; _libraryManager = libraryManager; + _config = config; } public QueryResult GetNextUp(NextUpQuery request) @@ -42,7 +45,7 @@ namespace MediaBrowser.Server.Implementations.TV if (series != null) { - presentationUniqueKey = series.PresentationUniqueKey; + presentationUniqueKey = GetUniqueSeriesKey(series); limit = 1; } } @@ -81,7 +84,7 @@ namespace MediaBrowser.Server.Implementations.TV if (series != null) { - presentationUniqueKey = series.PresentationUniqueKey; + presentationUniqueKey = GetUniqueSeriesKey(series); limit = 1; } } @@ -115,6 +118,15 @@ namespace MediaBrowser.Server.Implementations.TV .Select(i => i.Item1); } + private string GetUniqueSeriesKey(BaseItem series) + { + if (_config.Configuration.SchemaVersion < 97) + { + return series.Id.ToString("N"); + } + return series.PresentationUniqueKey; + } + /// /// Gets the next up. /// @@ -125,7 +137,7 @@ namespace MediaBrowser.Server.Implementations.TV { var lastWatchedEpisode = _libraryManager.GetItemList(new InternalItemsQuery(user) { - AncestorWithPresentationUniqueKey = series.PresentationUniqueKey, + AncestorWithPresentationUniqueKey = GetUniqueSeriesKey(series), IncludeItemTypes = new[] { typeof(Episode).Name }, SortBy = new[] { ItemSortBy.SortName }, SortOrder = SortOrder.Descending, @@ -138,7 +150,7 @@ namespace MediaBrowser.Server.Implementations.TV var firstUnwatchedEpisode = _libraryManager.GetItemList(new InternalItemsQuery(user) { - AncestorWithPresentationUniqueKey = series.PresentationUniqueKey, + AncestorWithPresentationUniqueKey = GetUniqueSeriesKey(series), IncludeItemTypes = new[] { typeof(Episode).Name }, SortBy = new[] { ItemSortBy.SortName }, SortOrder = SortOrder.Ascending, @@ -150,14 +162,13 @@ namespace MediaBrowser.Server.Implementations.TV }).Cast().FirstOrDefault(); - if (lastWatchedEpisode != null) + if (lastWatchedEpisode != null && firstUnwatchedEpisode != null) { var userData = _userDataManager.GetUserData(user, lastWatchedEpisode); - if (userData.LastPlayedDate.HasValue) - { - return new Tuple(firstUnwatchedEpisode, userData.LastPlayedDate.Value, false); - } + var lastWatchedDate = userData.LastPlayedDate ?? DateTime.MinValue.AddDays(1); + + return new Tuple(firstUnwatchedEpisode, lastWatchedDate, false); } // Return the first episode diff --git a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs index 755dec6da..63bdddac9 100644 --- a/MediaBrowser.Server.Startup.Common/ApplicationHost.cs +++ b/MediaBrowser.Server.Startup.Common/ApplicationHost.cs @@ -477,7 +477,7 @@ namespace MediaBrowser.Server.Startup.Common ImageProcessor = GetImageProcessor(); RegisterSingleInstance(ImageProcessor); - TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager); + TVSeriesManager = new TVSeriesManager(UserManager, UserDataManager, LibraryManager, ServerConfigurationManager); RegisterSingleInstance(TVSeriesManager); SyncManager = new SyncManager(LibraryManager, SyncRepository, ImageProcessor, LogManager.GetLogger("SyncManager"), UserManager, () => DtoService, this, TVSeriesManager, () => MediaEncoder, FileSystemManager, () => SubtitleEncoder, ServerConfigurationManager, UserDataManager, () => MediaSourceManager, JsonSerializer, TaskManager); -- cgit v1.2.3