From 5fdd7ec6725a3acb3365e92c090f2e90bbbf122f Mon Sep 17 00:00:00 2001 From: Luke Pulverenti Date: Sun, 16 Nov 2014 15:44:08 -0500 Subject: [PATCH] add new naming project --- .../Entities/TV/Episode.cs | 6 +- MediaBrowser.Controller/Entities/TV/Season.cs | 2 +- MediaBrowser.Controller/Entities/Video.cs | 6 +- .../Library/ILibraryManager.cs | 52 ++ MediaBrowser.Controller/Library/TVUtils.cs | 441 +---------------- .../MediaBrowser.Controller.csproj | 2 - .../Resolvers/BaseVideoResolver.cs | 137 ------ .../Resolvers/EntityResolutionHelper.cs | 263 ---------- MediaBrowser.Dlna/Didl/DidlBuilder.cs | 2 +- MediaBrowser.Model/Dlna/StreamInfo.cs | 59 ++- .../MediaBrowser.Providers.csproj | 4 + MediaBrowser.Providers/packages.config | 1 + .../Channels/ChannelManager.cs | 7 +- .../Connect/Validator.cs | 15 +- .../FileOrganization/EpisodeFileOrganizer.cs | 12 +- .../FileOrganization/TvFolderOrganizer.cs | 3 +- .../Intros/DefaultIntroProvider.cs | 7 +- .../Library/CoreResolutionIgnoreRule.cs | 6 +- .../Library/EntityResolutionHelper.cs | 104 ++++ .../Library/LibraryManager.cs | 48 ++ .../Library/ResolverHelper.cs | 12 +- .../Library/Resolvers/Audio/AudioResolver.cs | 12 +- .../Resolvers/Audio/MusicAlbumResolver.cs | 65 ++- .../Resolvers/Audio/MusicArtistResolver.cs | 6 +- .../Library/Resolvers/BaseVideoResolver.cs | 96 ++++ .../Library/Resolvers/LocalTrailerResolver.cs | 2 +- .../Library/Resolvers/Movies/MovieResolver.cs | 12 +- .../Library/Resolvers/TV/EpisodeResolver.cs | 6 +- .../Library/Resolvers/TV/SeasonResolver.cs | 4 +- .../Library/Resolvers/TV/SeriesResolver.cs | 460 +++++++++++++++++- .../Library/Resolvers/VideoResolver.cs | 29 ++ .../Library/UserManager.cs | 1 - ...MediaBrowser.Server.Implementations.csproj | 6 + .../packages.config | 1 + MediaBrowser.Tests/MediaBrowser.Tests.csproj | 4 - .../Providers/MovieDbProviderTests.cs | 41 -- .../Resolvers/MovieResolverTests.cs | 63 --- .../Resolvers/MusicResolverTests.cs | 36 -- MediaBrowser.Tests/Resolvers/TvUtilTests.cs | 389 +++++++-------- .../Library/ResolverHelperTests.cs | 17 - 40 files changed, 1128 insertions(+), 1311 deletions(-) delete mode 100644 MediaBrowser.Controller/Resolvers/BaseVideoResolver.cs delete mode 100644 MediaBrowser.Controller/Resolvers/EntityResolutionHelper.cs create mode 100644 MediaBrowser.Server.Implementations/Library/EntityResolutionHelper.cs create mode 100644 MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs delete mode 100644 MediaBrowser.Tests/Providers/MovieDbProviderTests.cs delete mode 100644 MediaBrowser.Tests/Resolvers/MovieResolverTests.cs delete mode 100644 MediaBrowser.Tests/Resolvers/MusicResolverTests.cs delete mode 100644 MediaBrowser.Tests/Server.Implementations/Library/ResolverHelperTests.cs diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index be7867e06c..cc0fc6812c 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -306,7 +306,7 @@ namespace MediaBrowser.Controller.Entities.TV { if (!IndexNumber.HasValue && !string.IsNullOrEmpty(Path)) { - IndexNumber = TVUtils.GetEpisodeNumberFromFile(Path, true); + IndexNumber = LibraryManager.GetEpisodeNumberFromFile(Path, true); // If a change was made record it if (IndexNumber.HasValue) @@ -317,7 +317,7 @@ namespace MediaBrowser.Controller.Entities.TV if (!IndexNumberEnd.HasValue && !string.IsNullOrEmpty(Path)) { - IndexNumberEnd = TVUtils.GetEndingEpisodeNumberFromFile(Path); + IndexNumberEnd = LibraryManager.GetEndingEpisodeNumberFromFile(Path); // If a change was made record it if (IndexNumberEnd.HasValue) @@ -338,7 +338,7 @@ namespace MediaBrowser.Controller.Entities.TV if (!ParentIndexNumber.HasValue && !string.IsNullOrEmpty(Path)) { - ParentIndexNumber = TVUtils.GetSeasonNumberFromEpisodeFile(Path); + ParentIndexNumber = LibraryManager.GetSeasonNumberFromEpisodeFile(Path); } // If a change was made record it diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index 5426281963..2df90244c3 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -298,7 +298,7 @@ namespace MediaBrowser.Controller.Entities.TV { if (!IndexNumber.HasValue && !string.IsNullOrEmpty(Path)) { - IndexNumber = IndexNumber ?? TVUtils.GetSeasonNumberFromPath(Path); + IndexNumber = IndexNumber ?? LibraryManager.GetSeasonNumberFromPath(Path); // If a change was made record it if (IndexNumber.HasValue) diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs index 6550f43b43..f2484aab8a 100644 --- a/MediaBrowser.Controller/Entities/Video.cs +++ b/MediaBrowser.Controller/Entities/Video.cs @@ -347,7 +347,7 @@ namespace MediaBrowser.Controller.Entities { if ((i.Attributes & FileAttributes.Directory) == FileAttributes.Directory) { - return !string.Equals(i.FullName, path, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsMultiPartFolder(i.FullName); + return !string.Equals(i.FullName, path, StringComparison.OrdinalIgnoreCase) && LibraryManager.IsMultiPartFolder(i.FullName); } return false; @@ -362,7 +362,7 @@ namespace MediaBrowser.Controller.Entities return false; } - return !string.Equals(i.FullName, path, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsVideoFile(i.FullName) && EntityResolutionHelper.IsMultiPartFile(i.Name); + return !string.Equals(i.FullName, path, StringComparison.OrdinalIgnoreCase) && LibraryManager.IsVideoFile(i.FullName) && LibraryManager.IsMultiPartFile(i.Name); }); } @@ -472,7 +472,7 @@ namespace MediaBrowser.Controller.Entities } return !string.Equals(i.FullName, path, StringComparison.OrdinalIgnoreCase) && - EntityResolutionHelper.IsVideoFile(i.FullName) && + LibraryManager.IsVideoFile(i.FullName) && i.Name.StartsWith(filenamePrefix + " - ", StringComparison.OrdinalIgnoreCase); }); } diff --git a/MediaBrowser.Controller/Library/ILibraryManager.cs b/MediaBrowser.Controller/Library/ILibraryManager.cs index be43f45279..68b99e4724 100644 --- a/MediaBrowser.Controller/Library/ILibraryManager.cs +++ b/MediaBrowser.Controller/Library/ILibraryManager.cs @@ -353,5 +353,57 @@ namespace MediaBrowser.Controller.Library string viewType, string sortName, CancellationToken cancellationToken); + + /// + /// Determines whether [is video file] [the specified path]. + /// + /// The path. + /// true if [is video file] [the specified path]; otherwise, false. + bool IsVideoFile(string path); + + bool IsAudioFile(string path); + + /// + /// Determines whether [is multi part file] [the specified path]. + /// + /// The path. + /// true if [is multi part file] [the specified path]; otherwise, false. + bool IsMultiPartFile(string path); + + /// + /// Determines whether [is multi part folder] [the specified path]. + /// + /// The path. + /// true if [is multi part folder] [the specified path]; otherwise, false. + bool IsMultiPartFolder(string path); + + /// + /// Gets the season number from path. + /// + /// The path. + /// System.Nullable<System.Int32>. + int? GetSeasonNumberFromPath(string path); + + /// + /// Gets the season number from episode file. + /// + /// The path. + /// System.Nullable<System.Int32>. + int? GetSeasonNumberFromEpisodeFile(string path); + + /// + /// Gets the ending episode number from file. + /// + /// The path. + /// System.Nullable<System.Int32>. + int? GetEndingEpisodeNumberFromFile(string path); + + /// + /// Gets the episode number from file. + /// + /// The path. + /// if set to true [consider seasonless]. + /// System.Nullable<System.Int32>. + int? GetEpisodeNumberFromFile(string path, bool considerSeasonless); } } \ No newline at end of file diff --git a/MediaBrowser.Controller/Library/TVUtils.cs b/MediaBrowser.Controller/Library/TVUtils.cs index 314efcce52..f8039b2cf2 100644 --- a/MediaBrowser.Controller/Library/TVUtils.cs +++ b/MediaBrowser.Controller/Library/TVUtils.cs @@ -1,14 +1,5 @@ -using MediaBrowser.Common.IO; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Providers; -using MediaBrowser.Controller.Resolvers; -using System; +using System; using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; -using MediaBrowser.Model.Logging; namespace MediaBrowser.Controller.Library { @@ -26,436 +17,6 @@ namespace MediaBrowser.Controller.Library /// public static readonly string BannerUrl = "http://www.thetvdb.com/banners/"; - /// - /// A season folder must contain one of these somewhere in the name - /// - private static readonly string[] SeasonFolderNames = - { - "season", - "sæson", - "temporada", - "saison", - "staffel", - "series", - "сезон" - }; - - /// - /// Used to detect paths that represent episodes, need to make sure they don't also - /// match movie titles like "2001 A Space..." - /// Currently we limit the numbers here to 2 digits to try and avoid this - /// - private static readonly Regex[] EpisodeExpressions = - { - new Regex( - @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)[sS](?\d{1,4})[x,X]?[eE](?\d{1,3})[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d{1,3})[^\\\/]*$", - RegexOptions.Compiled) - }; - private static readonly Regex[] MultipleEpisodeExpressions = - { - new Regex( - @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})((-| - )\d{1,4}[eExX](?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})((-| - )\d{1,4}[xX][eE](?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})((-| - )?[xXeE](?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})(-[xE]?[eE]?(?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))((-| - )\d{1,4}[xXeE](?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))((-| - )\d{1,4}[xX][eE](?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))((-| - )?[xXeE](?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))(-[xX]?[eE]?(?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d{1,3})((-| - )?[xXeE](?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d{1,3})(-[xX]?[eE]?(?\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled) - }; - - /// - /// To avoid the following matching movies they are only valid when contained in a folder which has been matched as a being season, or the media type is TV series - /// - private static readonly Regex[] EpisodeExpressionsWithoutSeason = - { - new Regex( - @".*[\\\/](?\d{1,3})(-(?\d{2,3}))*\.\w+$", - RegexOptions.Compiled), - // "01.avi" - new Regex( - @".*(\\|\/)(?\d{1,3})(-(?\d{2,3}))*\s?-\s?[^\\\/]*$", - RegexOptions.Compiled), - // "01 - blah.avi", "01-blah.avi" - new Regex( - @".*(\\|\/)(?\d{1,3})(-(?\d{2,3}))*\.[^\\\/]+$", - RegexOptions.Compiled), - // "01.blah.avi" - new Regex( - @".*[\\\/][^\\\/]* - (?\d{1,3})(-(?\d{2,3}))*[^\\\/]*$", - RegexOptions.Compiled), - // "blah - 01.avi", "blah 2 - 01.avi", "blah - 01 blah.avi", "blah 2 - 01 blah", "blah - 01 - blah.avi", "blah 2 - 01 - blah" - }; - - /// - /// Gets the season number from path. - /// - /// The path. - /// System.Nullable{System.Int32}. - public static int? GetSeasonNumberFromPath(string path) - { - var filename = Path.GetFileName(path); - - if (string.Equals(filename, "specials", StringComparison.OrdinalIgnoreCase)) - { - return 0; - } - - int val; - if (int.TryParse(filename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) - { - return val; - } - - if (filename.StartsWith("s", StringComparison.OrdinalIgnoreCase)) - { - var testFilename = filename.Substring(1); - - if (int.TryParse(testFilename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) - { - return val; - } - } - - // Look for one of the season folder names - foreach (var name in SeasonFolderNames) - { - var index = filename.IndexOf(name, StringComparison.OrdinalIgnoreCase); - - if (index != -1) - { - return GetSeasonNumberFromPathSubstring(filename.Substring(index + name.Length)); - } - } - - return null; - } - - /// - /// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel") - /// - /// The path. - /// System.Nullable{System.Int32}. - private static int? GetSeasonNumberFromPathSubstring(string path) - { - var numericStart = -1; - var length = 0; - - // Find out where the numbers start, and then keep going until they end - for (var i = 0; i < path.Length; i++) - { - if (char.IsNumber(path, i)) - { - if (numericStart == -1) - { - numericStart = i; - } - length++; - } - else if (numericStart != -1) - { - break; - } - } - - if (numericStart == -1) - { - return null; - } - - return int.Parse(path.Substring(numericStart, length), CultureInfo.InvariantCulture); - } - - /// - /// Determines whether [is season folder] [the specified path]. - /// - /// The path. - /// The directory service. - /// The file system. - /// true if [is season folder] [the specified path]; otherwise, false. - private static bool IsSeasonFolder(string path, IDirectoryService directoryService, IFileSystem fileSystem) - { - var seasonNumber = GetSeasonNumberFromPath(path); - var hasSeasonNumber = seasonNumber != null; - - if (!hasSeasonNumber) - { - return false; - } - - //// It's a season folder if it's named as such and does not contain any audio files, apart from theme.mp3 - //foreach (var fileSystemInfo in directoryService.GetFileSystemEntries(path)) - //{ - // var attributes = fileSystemInfo.Attributes; - - // if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) - // { - // continue; - // } - - // // Can't enforce this because files saved by Bitcasa are always marked System - // //if ((attributes & FileAttributes.System) == FileAttributes.System) - // //{ - // // continue; - // //} - - // if ((attributes & FileAttributes.Directory) == FileAttributes.Directory) - // { - // //if (IsBadFolder(fileSystemInfo.Name)) - // //{ - // // return false; - // //} - // } - // else - // { - // if (EntityResolutionHelper.IsAudioFile(fileSystemInfo.FullName) && - // !string.Equals(fileSystem.GetFileNameWithoutExtension(fileSystemInfo), BaseItem.ThemeSongFilename)) - // { - // return false; - // } - // } - //} - - return true; - } - - /// - /// Determines whether [is series folder] [the specified path]. - /// - /// The path. - /// if set to true [consider seasonless entries]. - /// The file system children. - /// The directory service. - /// The file system. - /// true if [is series folder] [the specified path]; otherwise, false. - public static bool IsSeriesFolder(string path, bool considerSeasonlessEntries, IEnumerable fileSystemChildren, IDirectoryService directoryService, IFileSystem fileSystem, ILogger logger) - { - // A folder with more than 3 non-season folders in will not becounted as a series - var nonSeriesFolders = 0; - - foreach (var child in fileSystemChildren) - { - var attributes = child.Attributes; - - if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) - { - //logger.Debug("Igoring series file or folder marked hidden: {0}", child.FullName); - continue; - } - - // Can't enforce this because files saved by Bitcasa are always marked System - //if ((attributes & FileAttributes.System) == FileAttributes.System) - //{ - // logger.Debug("Igoring series subfolder marked system: {0}", child.FullName); - // continue; - //} - - if ((attributes & FileAttributes.Directory) == FileAttributes.Directory) - { - if (IsSeasonFolder(child.FullName, directoryService, fileSystem)) - { - //logger.Debug("{0} is a series because of season folder {1}.", path, child.FullName); - return true; - } - - if (IsBadFolder(child.Name)) - { - logger.Debug("Invalid folder under series: {0}", child.FullName); - - nonSeriesFolders++; - } - - if (nonSeriesFolders >= 3) - { - logger.Debug("{0} not a series due to 3 or more invalid folders.", path); - return false; - } - } - else - { - var fullName = child.FullName; - - if (EntityResolutionHelper.IsVideoFile(fullName) || EntityResolutionHelper.IsVideoPlaceHolder(fullName)) - { - if (GetEpisodeNumberFromFile(fullName, considerSeasonlessEntries).HasValue) - { - return true; - } - } - } - } - - logger.Debug("{0} is not a series folder.", path); - return false; - } - - private static bool IsBadFolder(string name) - { - if (string.Equals(name, BaseItem.ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase)) - { - return false; - } - if (string.Equals(name, BaseItem.ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase)) - { - return false; - } - if (string.Equals(name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - return !EntityResolutionHelper.IgnoreFolders.Contains(name, StringComparer.OrdinalIgnoreCase); - } - - /// - /// Episodes the number from file. - /// - /// The full path. - /// if set to true [is in season]. - /// System.String. - public static int? GetEpisodeNumberFromFile(string fullPath, bool considerSeasonlessNames) - { - string fl = fullPath.ToLower(); - foreach (var r in EpisodeExpressions) - { - Match m = r.Match(fl); - if (m.Success) - return ParseEpisodeNumber(m.Groups["epnumber"].Value); - } - if (considerSeasonlessNames) - { - var match = EpisodeExpressionsWithoutSeason.Select(r => r.Match(fl)) - .FirstOrDefault(m => m.Success); - - if (match != null) - { - return ParseEpisodeNumber(match.Groups["epnumber"].Value); - } - } - - return null; - } - - public static int? GetEndingEpisodeNumberFromFile(string fullPath) - { - var fl = fullPath.ToLower(); - foreach (var r in MultipleEpisodeExpressions) - { - var m = r.Match(fl); - if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value)) - return ParseEpisodeNumber(m.Groups["endingepnumber"].Value); - } - foreach (var r in EpisodeExpressionsWithoutSeason) - { - var m = r.Match(fl); - if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value)) - return ParseEpisodeNumber(m.Groups["endingepnumber"].Value); - } - return null; - } - - private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); - - private static int? ParseEpisodeNumber(string val) - { - int num; - - if (!string.IsNullOrEmpty(val) && int.TryParse(val, NumberStyles.Integer, UsCulture, out num)) - { - return num; - } - - return null; - } - - /// - /// Seasons the number from episode file. - /// - /// The full path. - /// System.String. - public static int? GetSeasonNumberFromEpisodeFile(string fullPath) - { - string fl = fullPath.ToLower(); - foreach (var r in EpisodeExpressions) - { - Match m = r.Match(fl); - if (m.Success) - { - Group g = m.Groups["seasonnumber"]; - if (g != null) - { - var val = g.Value; - - if (!string.IsNullOrWhiteSpace(val)) - { - int num; - - if (int.TryParse(val, NumberStyles.Integer, UsCulture, out num)) - { - return num; - } - } - } - return null; - } - } - return null; - } - - public static string GetSeriesNameFromEpisodeFile(string fullPath) - { - var fl = fullPath.ToLower(); - foreach (var r in EpisodeExpressions) - { - var m = r.Match(fl); - if (m.Success) - { - var g = m.Groups["seriesname"]; - if (g != null) - { - var val = g.Value; - - if (!string.IsNullOrWhiteSpace(val)) - { - return val; - } - } - return null; - } - } - return null; - } - /// /// Gets the air days. /// diff --git a/MediaBrowser.Controller/MediaBrowser.Controller.csproj b/MediaBrowser.Controller/MediaBrowser.Controller.csproj index 72a8f60163..0457ea72e3 100644 --- a/MediaBrowser.Controller/MediaBrowser.Controller.csproj +++ b/MediaBrowser.Controller/MediaBrowser.Controller.csproj @@ -306,7 +306,6 @@ - @@ -325,7 +324,6 @@ - diff --git a/MediaBrowser.Controller/Resolvers/BaseVideoResolver.cs b/MediaBrowser.Controller/Resolvers/BaseVideoResolver.cs deleted file mode 100644 index 5725c64828..0000000000 --- a/MediaBrowser.Controller/Resolvers/BaseVideoResolver.cs +++ /dev/null @@ -1,137 +0,0 @@ -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Entities; -using System; -using System.IO; - -namespace MediaBrowser.Controller.Resolvers -{ - /// - /// Resolves a Path into a Video or Video subclass - /// - /// - public abstract class BaseVideoResolver : ItemResolver - where T : Video, new() - { - /// - /// Resolves the specified args. - /// - /// The args. - /// `0. - protected override T Resolve(ItemResolveArgs args) - { - return ResolveVideo(args); - } - - /// - /// Resolves the video. - /// - /// The type of the T video type. - /// The args. - /// ``0. - protected TVideoType ResolveVideo(ItemResolveArgs args) - where TVideoType : Video, new() - { - // If the path is a file check for a matching extensions - if (!args.IsDirectory) - { - // http://wiki.xbmc.org/index.php?title=Media_stubs - var isPlaceHolder = EntityResolutionHelper.IsVideoPlaceHolder(args.Path); - - var extension = Path.GetExtension(args.Path); - - var isShortcut = string.Equals(extension, ".strm", StringComparison.OrdinalIgnoreCase); - - if (EntityResolutionHelper.IsVideoFile(args.Path) || isPlaceHolder || isShortcut) - { - var type = string.Equals(extension, ".iso", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".img", StringComparison.OrdinalIgnoreCase) ? - VideoType.Iso : VideoType.VideoFile; - - var path = args.Path; - - var video = new TVideoType - { - VideoType = type, - Path = args.Path, - IsInMixedFolder = true, - IsPlaceHolder = isPlaceHolder, - IsShortcut = isShortcut - }; - - if (isPlaceHolder) - { - if (args.Path.EndsWith("dvd.disc", StringComparison.OrdinalIgnoreCase)) - { - video.VideoType = VideoType.Dvd; - } - else if (args.Path.EndsWith("hddvd.disc", StringComparison.OrdinalIgnoreCase)) - { - video.VideoType = VideoType.HdDvd; - } - else if (args.Path.EndsWith("bluray.disc", StringComparison.OrdinalIgnoreCase) || - args.Path.EndsWith("brrip.disc", StringComparison.OrdinalIgnoreCase) || - args.Path.EndsWith("bd25.disc", StringComparison.OrdinalIgnoreCase) || - args.Path.EndsWith("bd50.disc", StringComparison.OrdinalIgnoreCase)) - { - video.VideoType = VideoType.BluRay; - } - } - - return video; - } - } - - return null; - } - - /// - /// Sets the initial item values. - /// - /// The item. - /// The args. - protected override void SetInitialItemValues(T item, ItemResolveArgs args) - { - base.SetInitialItemValues(item, args); - - if (item.Path.IndexOf("[3d]", StringComparison.OrdinalIgnoreCase) != -1 || item.Path.IndexOf("[sbs3d]", StringComparison.OrdinalIgnoreCase) != -1) - { - item.Video3DFormat = Video3DFormat.HalfSideBySide; - } - else if (item.Path.IndexOf("[hsbs]", StringComparison.OrdinalIgnoreCase) != -1) - { - item.Video3DFormat = Video3DFormat.HalfSideBySide; - } - else if (item.Path.IndexOf("[fsbs]", StringComparison.OrdinalIgnoreCase) != -1) - { - item.Video3DFormat = Video3DFormat.FullSideBySide; - } - else if (item.Path.IndexOf("[ftab]", StringComparison.OrdinalIgnoreCase) != -1) - { - item.Video3DFormat = Video3DFormat.FullTopAndBottom; - } - else if (item.Path.IndexOf("[htab]", StringComparison.OrdinalIgnoreCase) != -1) - { - item.Video3DFormat = Video3DFormat.HalfTopAndBottom; - } - else - { - // Support Xbmc conventions: - // http://wiki.xbmc.org/index.php?title=3D - var name = Path.GetFileName(item.Path); - - name = name.Replace('.', ' ').Replace('_', ' ').Replace('-', ' '); - - if (name.IndexOf(" 3d hsbs ", StringComparison.OrdinalIgnoreCase) != -1 || - name.IndexOf(" 3d sbs ", StringComparison.OrdinalIgnoreCase) != -1) - { - item.Video3DFormat = Video3DFormat.HalfSideBySide; - } - else if (name.IndexOf(" 3d htab ", StringComparison.OrdinalIgnoreCase) != -1 || - name.IndexOf(" 3d tab ", StringComparison.OrdinalIgnoreCase) != -1) - { - item.Video3DFormat = Video3DFormat.HalfTopAndBottom; - } - } - } - } -} diff --git a/MediaBrowser.Controller/Resolvers/EntityResolutionHelper.cs b/MediaBrowser.Controller/Resolvers/EntityResolutionHelper.cs deleted file mode 100644 index d37301b9eb..0000000000 --- a/MediaBrowser.Controller/Resolvers/EntityResolutionHelper.cs +++ /dev/null @@ -1,263 +0,0 @@ -using MediaBrowser.Common.IO; -using MediaBrowser.Common.Net; -using MediaBrowser.Controller.Entities; -using MediaBrowser.Controller.Library; -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Text.RegularExpressions; - -namespace MediaBrowser.Controller.Resolvers -{ - /// - /// Class EntityResolutionHelper - /// - public static class EntityResolutionHelper - { - /// - /// Any folder named in this list will be ignored - can be added to at runtime for extensibility - /// - public static readonly List IgnoreFolders = new List - { - "metadata", - "ps3_update", - "ps3_vprm", - "extrafanart", - "extrathumbs", - ".actors", - ".wd_tv" - - }; - - private static readonly Regex MultiFileRegex = new Regex( - @"(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck]|d)[ _.-]*[0-9]+)(.*?)(\.[^.]+)$", - RegexOptions.Compiled | RegexOptions.IgnoreCase); - - private static readonly Regex MultiFolderRegex = new Regex( - @"(.*?)([ _.-]*(?:cd|dvd|p(?:ar)?t|dis[ck]|d)[ _.-]*[0-9]+)$", - RegexOptions.Compiled | RegexOptions.IgnoreCase); - - /// - /// Determines whether [is multi part file] [the specified path]. - /// - /// The path. - /// true if [is multi part file] [the specified path]; otherwise, false. - public static bool IsMultiPartFile(string path) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException("path"); - } - - path = Path.GetFileName(path); - - return MultiFileRegex.Match(path).Success; - } - - public static bool IsMultiPartFolder(string path) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException("path"); - } - - path = Path.GetFileName(path); - - return MultiFolderRegex.Match(path).Success; - } - - /// - /// The audio file extensions - /// - public static readonly string[] AudioFileExtensions = - { - ".mp3", - ".flac", - ".wma", - ".aac", - ".acc", - ".m4a", - ".m4b", - ".wav", - ".ape", - ".ogg", - ".oga" - - //".asf", - //".mp4" - }; - - private static readonly Dictionary AudioFileExtensionsDictionary = AudioFileExtensions.ToDictionary(i => i, StringComparer.OrdinalIgnoreCase); - - /// - /// Determines whether [is audio file] [the specified args]. - /// - /// The path. - /// true if [is audio file] [the specified args]; otherwise, false. - public static bool IsAudioFile(string path) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException("path"); - } - - var extension = Path.GetExtension(path); - - if (string.IsNullOrEmpty(extension)) - { - return false; - } - - return AudioFileExtensionsDictionary.ContainsKey(extension); - } - - /// - /// Determines whether [is video file] [the specified path]. - /// - /// The path. - /// true if [is video file] [the specified path]; otherwise, false. - public static bool IsVideoFile(string path) - { - return MimeTypes.IsVideoFile(path); - } - - /// - /// Determines whether [is place holder] [the specified path]. - /// - /// The path. - /// true if [is place holder] [the specified path]; otherwise, false. - /// path - public static bool IsVideoPlaceHolder(string path) - { - if (string.IsNullOrEmpty(path)) - { - throw new ArgumentNullException("path"); - } - - var extension = Path.GetExtension(path); - - return string.Equals(extension, ".disc", StringComparison.OrdinalIgnoreCase); - } - - /// - /// Determines whether [is multi disc album folder] [the specified path]. - /// - /// The path. - /// true if [is multi disc album folder] [the specified path]; otherwise, false. - public static bool IsMultiDiscAlbumFolder(string path) - { - var filename = Path.GetFileName(path); - - if (string.IsNullOrWhiteSpace(filename)) - { - return false; - } - - // Normalize - // Remove whitespace - filename = filename.Replace("-", " "); - filename = filename.Replace(".", " "); - filename = filename.Replace("(", " "); - filename = filename.Replace(")", " "); - filename = Regex.Replace(filename, @"\s+", " "); - - var prefixes = new[] { "disc", "cd", "disk", "vol", "volume" }; - - filename = filename.TrimStart(); - - foreach (var prefix in prefixes) - { - if (filename.IndexOf(prefix, StringComparison.OrdinalIgnoreCase) == 0) - { - var tmp = filename.Substring(prefix.Length); - - tmp = tmp.Trim().Split(' ').FirstOrDefault() ?? string.Empty; - - int val; - if (int.TryParse(tmp, NumberStyles.Any, CultureInfo.InvariantCulture, out val)) - { - return true; - } - } - } - - return false; - } - - /// - /// Ensures DateCreated and DateModified have values - /// - /// The file system. - /// The item. - /// The args. - /// if set to true [include creation time]. - public static void EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args, bool includeCreationTime) - { - if (fileSystem == null) - { - throw new ArgumentNullException("fileSystem"); - } - if (item == null) - { - throw new ArgumentNullException("item"); - } - if (args == null) - { - throw new ArgumentNullException("args"); - } - - // See if a different path came out of the resolver than what went in - if (!string.Equals(args.Path, item.Path, StringComparison.OrdinalIgnoreCase)) - { - var childData = args.IsDirectory ? args.GetFileSystemEntryByPath(item.Path) : null; - - if (childData != null) - { - if (includeCreationTime) - { - SetDateCreated(item, fileSystem, childData); - } - - item.DateModified = fileSystem.GetLastWriteTimeUtc(childData); - } - else - { - var fileData = fileSystem.GetFileSystemInfo(item.Path); - - if (fileData.Exists) - { - if (includeCreationTime) - { - SetDateCreated(item, fileSystem, fileData); - } - item.DateModified = fileSystem.GetLastWriteTimeUtc(fileData); - } - } - } - else - { - if (includeCreationTime) - { - SetDateCreated(item, fileSystem, args.FileInfo); - } - item.DateModified = fileSystem.GetLastWriteTimeUtc(args.FileInfo); - } - } - - private static void SetDateCreated(BaseItem item, IFileSystem fileSystem, FileSystemInfo info) - { - var config = BaseItem.ConfigurationManager.GetMetadataConfiguration(); - - if (config.UseFileCreationTimeForDateAdded) - { - item.DateCreated = fileSystem.GetCreationTimeUtc(info); - } - else - { - item.DateCreated = DateTime.UtcNow; - } - } - } -} diff --git a/MediaBrowser.Dlna/Didl/DidlBuilder.cs b/MediaBrowser.Dlna/Didl/DidlBuilder.cs index f4afd3c246..565431758f 100644 --- a/MediaBrowser.Dlna/Didl/DidlBuilder.cs +++ b/MediaBrowser.Dlna/Didl/DidlBuilder.cs @@ -161,7 +161,7 @@ namespace MediaBrowser.Dlna.Didl AddVideoResource(container, video, deviceId, filter, contentFeature, streamInfo); } - foreach (var subtitle in streamInfo.GetExternalSubtitles(_serverAddress)) + foreach (var subtitle in streamInfo.GetExternalSubtitles(_serverAddress, false)) { AddSubtitleElement(container, subtitle); } diff --git a/MediaBrowser.Model/Dlna/StreamInfo.cs b/MediaBrowser.Model/Dlna/StreamInfo.cs index e531322f0f..7ca8ab6b06 100644 --- a/MediaBrowser.Model/Dlna/StreamInfo.cs +++ b/MediaBrowser.Model/Dlna/StreamInfo.cs @@ -150,7 +150,7 @@ namespace MediaBrowser.Model.Dlna return string.Format("Params={0}", string.Join(";", list.ToArray())); } - public List GetExternalSubtitles(string baseUrl) + public List GetExternalSubtitles(string baseUrl, bool includeSelectedTrackOnly) { if (string.IsNullOrEmpty(baseUrl)) { @@ -164,40 +164,55 @@ namespace MediaBrowser.Model.Dlna return list; } - if (!SubtitleStreamIndex.HasValue) - { - return list; - } - // HLS will preserve timestamps so we can just grab the full subtitle stream long startPositionTicks = StringHelper.EqualsIgnoreCase(Protocol, "hls") ? 0 : StartPositionTicks; + // First add the selected track + if (SubtitleStreamIndex.HasValue) + { + foreach (MediaStream stream in MediaSource.MediaStreams) + { + if (stream.Type == MediaStreamType.Subtitle && stream.IsTextSubtitleStream && stream.Index == SubtitleStreamIndex.Value) + { + AddSubtitle(list, stream, baseUrl, startPositionTicks); + } + } + } + + if (!includeSelectedTrackOnly) + { + foreach (MediaStream stream in MediaSource.MediaStreams) + { + if (stream.Type == MediaStreamType.Subtitle && stream.IsTextSubtitleStream && (!SubtitleStreamIndex.HasValue || stream.Index != SubtitleStreamIndex.Value)) + { + AddSubtitle(list, stream, baseUrl, startPositionTicks); + } + } + } + + return list; + } + + private void AddSubtitle(List list, MediaStream stream, string baseUrl, long startPositionTicks) + { string url = string.Format("{0}/Videos/{1}/{2}/Subtitles/{3}/{4}/Stream.{5}", baseUrl, ItemId, MediaSourceId, - StringHelper.ToStringCultureInvariant(SubtitleStreamIndex.Value), + StringHelper.ToStringCultureInvariant(stream.Index), StringHelper.ToStringCultureInvariant(startPositionTicks), SubtitleFormat); - foreach (MediaStream stream in MediaSource.MediaStreams) + list.Add(new SubtitleStreamInfo { - if (stream.Type == MediaStreamType.Subtitle && stream.Index == SubtitleStreamIndex.Value) - { - list.Add(new SubtitleStreamInfo - { - Url = url, - IsForced = stream.IsForced, - Language = stream.Language, - Name = stream.Language ?? "Unknown", - Format = SubtitleFormat - }); - } - } - - return list; + Url = url, + IsForced = stream.IsForced, + Language = stream.Language, + Name = stream.Language ?? "Unknown", + Format = SubtitleFormat + }); } /// diff --git a/MediaBrowser.Providers/MediaBrowser.Providers.csproj b/MediaBrowser.Providers/MediaBrowser.Providers.csproj index 0757541078..a9bca3922c 100644 --- a/MediaBrowser.Providers/MediaBrowser.Providers.csproj +++ b/MediaBrowser.Providers/MediaBrowser.Providers.csproj @@ -53,6 +53,10 @@ False ..\packages\MediaBrowser.BdInfo.1.0.0.10\lib\net35\DvdLib.dll + + False + ..\packages\MediaBrowser.Naming.1.0.0.1\lib\portable-net45+sl4+wp71+win8+wpa81\MediaBrowser.Naming.dll + False ..\packages\morelinq.1.1.0\lib\net35\MoreLinq.dll diff --git a/MediaBrowser.Providers/packages.config b/MediaBrowser.Providers/packages.config index be21e92dcf..17c6f08ba1 100644 --- a/MediaBrowser.Providers/packages.config +++ b/MediaBrowser.Providers/packages.config @@ -1,6 +1,7 @@  + \ No newline at end of file diff --git a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs index f1075f77de..b777e8a9c5 100644 --- a/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs +++ b/MediaBrowser.Server.Implementations/Channels/ChannelManager.cs @@ -26,6 +26,7 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Server.Implementations.Library; namespace MediaBrowser.Server.Implementations.Channels { @@ -318,13 +319,13 @@ namespace MediaBrowser.Server.Implementations.Channels if (string.Equals(item.MediaType, MediaType.Video, StringComparison.OrdinalIgnoreCase)) { - files = files.Where(i => EntityResolutionHelper.IsVideoFile(i.FullName)); + files = files.Where(i => _libraryManager.IsVideoFile(i.FullName)); } else { - files = files.Where(i => EntityResolutionHelper.IsAudioFile(i.FullName)); + files = files.Where(i => _libraryManager.IsAudioFile(i.FullName)); } - + var file = files .FirstOrDefault(i => i.Name.StartsWith(filenamePrefix, StringComparison.OrdinalIgnoreCase)); diff --git a/MediaBrowser.Server.Implementations/Connect/Validator.cs b/MediaBrowser.Server.Implementations/Connect/Validator.cs index b217da32ac..8cdfc4a6b3 100644 --- a/MediaBrowser.Server.Implementations/Connect/Validator.cs +++ b/MediaBrowser.Server.Implementations/Connect/Validator.cs @@ -1,15 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; +using System.Text.RegularExpressions; namespace MediaBrowser.Server.Implementations.Connect { public static class Validator { - static Regex ValidEmailRegex = CreateValidEmailRegex(); + static readonly Regex ValidEmailRegex = CreateValidEmailRegex(); /// /// Taken from http://haacked.com/archive/2007/08/21/i-knew-how-to-validate-an-email-address-until-i.aspx @@ -17,9 +12,9 @@ namespace MediaBrowser.Server.Implementations.Connect /// private static Regex CreateValidEmailRegex() { - string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" - + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(? EntityResolutionHelper.IsVideoFile(i) && string.Equals(_fileSystem.GetFileNameWithoutExtension(i), targetFileNameWithoutExtension, StringComparison.OrdinalIgnoreCase)); + .Where(i => _libraryManager.IsVideoFile(i) && string.Equals(_fileSystem.GetFileNameWithoutExtension(i), targetFileNameWithoutExtension, StringComparison.OrdinalIgnoreCase)); episodePaths.AddRange(filesOfOtherExtensions); } diff --git a/MediaBrowser.Server.Implementations/FileOrganization/TvFolderOrganizer.cs b/MediaBrowser.Server.Implementations/FileOrganization/TvFolderOrganizer.cs index 82bb9862c9..c41aebb694 100644 --- a/MediaBrowser.Server.Implementations/FileOrganization/TvFolderOrganizer.cs +++ b/MediaBrowser.Server.Implementations/FileOrganization/TvFolderOrganizer.cs @@ -13,6 +13,7 @@ using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; +using MediaBrowser.Server.Implementations.Library; namespace MediaBrowser.Server.Implementations.FileOrganization { @@ -45,7 +46,7 @@ namespace MediaBrowser.Server.Implementations.FileOrganization var eligibleFiles = watchLocations.SelectMany(GetFilesToOrganize) .OrderBy(_fileSystem.GetCreationTimeUtc) - .Where(i => EntityResolutionHelper.IsVideoFile(i.FullName) && i.Length >= minFileBytes) + .Where(i => _libraryManager.IsVideoFile(i.FullName) && i.Length >= minFileBytes) .ToList(); progress.Report(10); diff --git a/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs b/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs index 2e1e54ad67..2d991abba4 100644 --- a/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs +++ b/MediaBrowser.Server.Implementations/Intros/DefaultIntroProvider.cs @@ -6,7 +6,6 @@ using MediaBrowser.Controller.Entities.Movies; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Localization; -using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Channels; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; @@ -25,13 +24,15 @@ namespace MediaBrowser.Server.Implementations.Intros private readonly IChannelManager _channelManager; private readonly ILocalizationManager _localization; private readonly IConfigurationManager _serverConfig; + private readonly ILibraryManager _libraryManager; - public DefaultIntroProvider(ISecurityManager security, IChannelManager channelManager, ILocalizationManager localization, IConfigurationManager serverConfig) + public DefaultIntroProvider(ISecurityManager security, IChannelManager channelManager, ILocalizationManager localization, IConfigurationManager serverConfig, ILibraryManager libraryManager) { _security = security; _channelManager = channelManager; _localization = localization; _serverConfig = serverConfig; + _libraryManager = libraryManager; } public async Task> GetIntros(BaseItem item, User user) @@ -226,7 +227,7 @@ namespace MediaBrowser.Server.Implementations.Intros } return Directory.EnumerateFiles(options.CustomIntroPath, "*", SearchOption.AllDirectories) - .Where(EntityResolutionHelper.IsVideoFile); + .Where(_libraryManager.IsVideoFile); } private bool FilterByParentalRating(int? ratingLevel, BaseItem item) diff --git a/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs b/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs index d3d71e0f93..0fc04c5046 100644 --- a/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs +++ b/MediaBrowser.Server.Implementations/Library/CoreResolutionIgnoreRule.cs @@ -14,10 +14,12 @@ namespace MediaBrowser.Server.Implementations.Library public class CoreResolutionIgnoreRule : IResolverIgnoreRule { private readonly IFileSystem _fileSystem; + private readonly ILibraryManager _libraryManager; - public CoreResolutionIgnoreRule(IFileSystem fileSystem) + public CoreResolutionIgnoreRule(IFileSystem fileSystem, ILibraryManager libraryManager) { _fileSystem = fileSystem; + _libraryManager = libraryManager; } /// @@ -89,7 +91,7 @@ namespace MediaBrowser.Server.Implementations.Library if (args.Parent != null) { // Don't resolve these into audio files - if (string.Equals(_fileSystem.GetFileNameWithoutExtension(filename), BaseItem.ThemeSongFilename) && EntityResolutionHelper.IsAudioFile(filename)) + if (string.Equals(_fileSystem.GetFileNameWithoutExtension(filename), BaseItem.ThemeSongFilename) && _libraryManager.IsAudioFile(filename)) { return true; } diff --git a/MediaBrowser.Server.Implementations/Library/EntityResolutionHelper.cs b/MediaBrowser.Server.Implementations/Library/EntityResolutionHelper.cs new file mode 100644 index 0000000000..fdb0b35a1f --- /dev/null +++ b/MediaBrowser.Server.Implementations/Library/EntityResolutionHelper.cs @@ -0,0 +1,104 @@ +using MediaBrowser.Common.IO; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using System; +using System.Collections.Generic; +using System.IO; + +namespace MediaBrowser.Server.Implementations.Library +{ + /// + /// Class EntityResolutionHelper + /// + public static class EntityResolutionHelper + { + /// + /// Any folder named in this list will be ignored - can be added to at runtime for extensibility + /// + public static readonly List IgnoreFolders = new List + { + "metadata", + "ps3_update", + "ps3_vprm", + "extrafanart", + "extrathumbs", + ".actors", + ".wd_tv" + + }; + + /// + /// Ensures DateCreated and DateModified have values + /// + /// The file system. + /// The item. + /// The args. + /// if set to true [include creation time]. + public static void EnsureDates(IFileSystem fileSystem, BaseItem item, ItemResolveArgs args, bool includeCreationTime) + { + if (fileSystem == null) + { + throw new ArgumentNullException("fileSystem"); + } + if (item == null) + { + throw new ArgumentNullException("item"); + } + if (args == null) + { + throw new ArgumentNullException("args"); + } + + // See if a different path came out of the resolver than what went in + if (!string.Equals(args.Path, item.Path, StringComparison.OrdinalIgnoreCase)) + { + var childData = args.IsDirectory ? args.GetFileSystemEntryByPath(item.Path) : null; + + if (childData != null) + { + if (includeCreationTime) + { + SetDateCreated(item, fileSystem, childData); + } + + item.DateModified = fileSystem.GetLastWriteTimeUtc(childData); + } + else + { + var fileData = fileSystem.GetFileSystemInfo(item.Path); + + if (fileData.Exists) + { + if (includeCreationTime) + { + SetDateCreated(item, fileSystem, fileData); + } + item.DateModified = fileSystem.GetLastWriteTimeUtc(fileData); + } + } + } + else + { + if (includeCreationTime) + { + SetDateCreated(item, fileSystem, args.FileInfo); + } + item.DateModified = fileSystem.GetLastWriteTimeUtc(args.FileInfo); + } + } + + private static void SetDateCreated(BaseItem item, IFileSystem fileSystem, FileSystemInfo info) + { + var config = BaseItem.ConfigurationManager.GetMetadataConfiguration(); + + if (config.UseFileCreationTimeForDateAdded) + { + item.DateCreated = fileSystem.GetCreationTimeUtc(info); + } + else + { + item.DateCreated = DateTime.UtcNow; + } + } + } +} diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 9f87123845..3ed6820023 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -15,6 +15,10 @@ using MediaBrowser.Controller.Sorting; using MediaBrowser.Model.Configuration; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; +using MediaBrowser.Naming.Audio; +using MediaBrowser.Naming.IO; +using MediaBrowser.Naming.Video; +using MediaBrowser.Server.Implementations.Library.Resolvers.TV; using MediaBrowser.Server.Implementations.Library.Validators; using MediaBrowser.Server.Implementations.ScheduledTasks; using MoreLinq; @@ -1628,5 +1632,49 @@ namespace MediaBrowser.Server.Implementations.Library return item; } + + public bool IsVideoFile(string path) + { + var parser = new VideoFileParser(new ExpandedVideoOptions(), new Naming.Logging.NullLogger()); + return parser.IsVideoFile(path); + } + + public bool IsAudioFile(string path) + { + var parser = new AudioFileParser(new AudioOptions()); + return parser.IsAudioFile(path); + } + + public bool IsMultiPartFile(string path) + { + var parser = new MultiPartParser(new ExpandedVideoOptions(), new Naming.Logging.NullLogger()); + return parser.Parse(path, FileInfoType.File).IsMultiPart; + } + + public bool IsMultiPartFolder(string path) + { + var parser = new MultiPartParser(new ExpandedVideoOptions(), new Naming.Logging.NullLogger()); + return parser.Parse(path, FileInfoType.Directory).IsMultiPart; + } + + public int? GetSeasonNumberFromPath(string path) + { + return SeriesResolver.GetSeasonNumberFromPath(path); + } + + public int? GetSeasonNumberFromEpisodeFile(string path) + { + return SeriesResolver.GetSeasonNumberFromEpisodeFile(path); + } + + public int? GetEndingEpisodeNumberFromFile(string path) + { + return SeriesResolver.GetEndingEpisodeNumberFromFile(path); + } + + public int? GetEpisodeNumberFromFile(string path, bool considerSeasonless) + { + return SeriesResolver.GetEpisodeNumberFromFile(path, considerSeasonless); + } } } diff --git a/MediaBrowser.Server.Implementations/Library/ResolverHelper.cs b/MediaBrowser.Server.Implementations/Library/ResolverHelper.cs index 10c9cf7332..b9fbd6f8c4 100644 --- a/MediaBrowser.Server.Implementations/Library/ResolverHelper.cs +++ b/MediaBrowser.Server.Implementations/Library/ResolverHelper.cs @@ -2,7 +2,6 @@ using MediaBrowser.Common.IO; using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; -using MediaBrowser.Controller.Resolvers; using System; using System.IO; using System.Linq; @@ -63,14 +62,14 @@ namespace MediaBrowser.Server.Implementations.Library if (string.IsNullOrEmpty(item.Name) && !string.IsNullOrEmpty(item.Path)) { //we use our resolve args name here to get the name of the containg folder, not actual video file - item.Name = GetMBName(args.FileInfo.Name, (args.FileInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory); + item.Name = GetMbName(args.FileInfo.Name, (args.FileInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory); } } /// /// The MB name regex /// - private static readonly Regex MBNameRegex = new Regex(@"(\[.*?\])", RegexOptions.Compiled); + private static readonly Regex MbNameRegex = new Regex(@"(\[.*?\])", RegexOptions.Compiled); /// /// Strip out attribute items and return just the name we will use for items @@ -78,7 +77,7 @@ namespace MediaBrowser.Server.Implementations.Library /// Assumed to be a file or directory path /// if set to true [is directory]. /// The cleaned name - private static string GetMBName(string path, bool isDirectory) + private static string GetMbName(string path, bool isDirectory) { //first just get the file or directory name var fn = isDirectory ? Path.GetFileName(path) : Path.GetFileNameWithoutExtension(path); @@ -89,8 +88,9 @@ namespace MediaBrowser.Server.Implementations.Library return fn; } - public static string StripBrackets(string inputString) { - var output = MBNameRegex.Replace(inputString, string.Empty).Trim(); + private static string StripBrackets(string inputString) + { + var output = MbNameRegex.Replace(inputString, string.Empty).Trim(); return Regex.Replace(output, @"\s+", " "); } diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs index dec6908f96..62eb1f47d4 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/AudioResolver.cs @@ -10,6 +10,13 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio /// public class AudioResolver : ItemResolver { + private readonly ILibraryManager _libraryManager; + + public AudioResolver(ILibraryManager libraryManager) + { + _libraryManager = libraryManager; + } + /// /// Gets the priority. /// @@ -30,15 +37,14 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio if (!args.IsDirectory) { - if (EntityResolutionHelper.IsAudioFile(args.Path)) + if (_libraryManager.IsAudioFile(args.Path)) { var collectionType = args.GetCollectionType(); var isStandalone = args.Parent == null; if (isStandalone || - string.Equals(collectionType, CollectionType.Music, StringComparison.OrdinalIgnoreCase) || - string.IsNullOrEmpty(collectionType)) + string.Equals(collectionType, CollectionType.Music, StringComparison.OrdinalIgnoreCase)) { return new Controller.Entities.Audio.Audio(); } diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index 1f9dc56f95..a500594610 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -8,6 +8,7 @@ using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; +using MediaBrowser.Naming.Audio; using System; using System.Collections.Generic; using System.IO; @@ -21,11 +22,13 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio { private readonly ILogger _logger; private readonly IFileSystem _fileSystem; + private readonly ILibraryManager _libraryManager; - public MusicAlbumResolver(ILogger logger, IFileSystem fileSystem) + public MusicAlbumResolver(ILogger logger, IFileSystem fileSystem, ILibraryManager libraryManager) { _logger = logger; _fileSystem = fileSystem; + _libraryManager = libraryManager; } /// @@ -68,7 +71,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio return null; } - return IsMusicAlbum(args, isMusicMediaFolder) ? new MusicAlbum() : null; + return IsMusicAlbum(args) ? new MusicAlbum() : null; } @@ -76,29 +79,29 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio /// Determine if the supplied file data points to a music album /// /// The path. - /// if set to true [is music media folder]. /// The directory service. /// The logger. /// The file system. + /// The library manager. /// true if [is music album] [the specified data]; otherwise, false. - public static bool IsMusicAlbum(string path, bool isMusicMediaFolder, IDirectoryService directoryService, ILogger logger, IFileSystem fileSystem) + public static bool IsMusicAlbum(string path, IDirectoryService directoryService, ILogger logger, IFileSystem fileSystem, + ILibraryManager libraryManager) { - return ContainsMusic(directoryService.GetFileSystemEntries(path), isMusicMediaFolder, true, directoryService, logger, fileSystem); + return ContainsMusic(directoryService.GetFileSystemEntries(path), true, directoryService, logger, fileSystem, libraryManager); } /// /// Determine if the supplied resolve args should be considered a music album /// /// The args. - /// if set to true [is music media folder]. /// true if [is music album] [the specified args]; otherwise, false. - private bool IsMusicAlbum(ItemResolveArgs args, bool isMusicMediaFolder) + private bool IsMusicAlbum(ItemResolveArgs args) { // Args points to an album if parent is an Artist folder or it directly contains music if (args.IsDirectory) { //if (args.Parent is MusicArtist) return true; //saves us from testing children twice - if (ContainsMusic(args.FileSystemChildren, isMusicMediaFolder, true, args.DirectoryService, _logger, _fileSystem)) return true; + if (ContainsMusic(args.FileSystemChildren, true, args.DirectoryService, _logger, _fileSystem, _libraryManager)) return true; } return false; @@ -108,41 +111,34 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio /// Determine if the supplied list contains what we should consider music /// /// The list. - /// if set to true [is music media folder]. /// if set to true [allow subfolders]. /// The directory service. /// The logger. /// The file system. + /// The library manager. /// true if the specified list contains music; otherwise, false. private static bool ContainsMusic(IEnumerable list, - bool isMusicMediaFolder, bool allowSubfolders, IDirectoryService directoryService, ILogger logger, - IFileSystem fileSystem) + IFileSystem fileSystem, + ILibraryManager libraryManager) { - // If list contains at least 2 audio files or at least one and no video files consider it to contain music - var foundAudio = 0; - var discSubfolderCount = 0; foreach (var fileSystemInfo in list) { if ((fileSystemInfo.Attributes & FileAttributes.Directory) == FileAttributes.Directory) { - if (isMusicMediaFolder && allowSubfolders && IsAlbumSubfolder(fileSystemInfo, true, directoryService, logger, fileSystem)) + if (allowSubfolders && IsAlbumSubfolder(fileSystemInfo, directoryService, logger, fileSystem, libraryManager)) { discSubfolderCount++; } - if (!IsAdditionalSubfolderAllowed(fileSystemInfo)) - { - return false; - } } var fullName = fileSystemInfo.FullName; - if (EntityResolutionHelper.IsAudioFile(fullName)) + if (libraryManager.IsAudioFile(fullName)) { // Don't resolve these into audio files if (string.Equals(fileSystem.GetFileNameWithoutExtension(fullName), BaseItem.ThemeSongFilename)) @@ -150,22 +146,14 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio continue; } - foundAudio++; - } - else if (EntityResolutionHelper.IsVideoFile(fullName)) return false; - else if (EntityResolutionHelper.IsVideoPlaceHolder(fullName)) return false; - - if (foundAudio >= 2) - { return true; } } - // or a single audio file and no video files - return foundAudio > 0 || discSubfolderCount > 0; + return discSubfolderCount > 0; } - private static bool IsAlbumSubfolder(FileSystemInfo directory, bool isMusicMediaFolder, IDirectoryService directoryService, ILogger logger, IFileSystem fileSystem) + private static bool IsAlbumSubfolder(FileSystemInfo directory, IDirectoryService directoryService, ILogger logger, IFileSystem fileSystem, ILibraryManager libraryManager) { var path = directory.FullName; @@ -173,7 +161,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio { logger.Debug("Found multi-disc folder: " + path); - return ContainsMusic(directoryService.GetFileSystemEntries(path), isMusicMediaFolder, false, directoryService, logger, fileSystem); + return ContainsMusic(directoryService.GetFileSystemEntries(path), false, directoryService, logger, fileSystem, libraryManager); } return false; @@ -181,13 +169,20 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio public static bool IsMultiDiscFolder(string path) { - return EntityResolutionHelper.IsMultiDiscAlbumFolder(path); + return IsMultiDiscAlbumFolder(path); } - private static bool IsAdditionalSubfolderAllowed(FileSystemInfo directory) + /// + /// Determines whether [is multi disc album folder] [the specified path]. + /// + /// The path. + /// true if [is multi disc album folder] [the specified path]; otherwise, false. + private static bool IsMultiDiscAlbumFolder(string path) { - // Resolver will ignore them based on rules engine - return true; + var parser = new AlbumParser(new AudioOptions(), new Naming.Logging.NullLogger()); + var result = parser.ParseMultiPart(path); + + return result.IsMultiPart; } } } diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs index 2417d5dcb8..53063b35ec 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs @@ -19,11 +19,13 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio { private readonly ILogger _logger; private readonly IFileSystem _fileSystem; + private readonly ILibraryManager _libraryManager; - public MusicArtistResolver(ILogger logger, IFileSystem fileSystem) + public MusicArtistResolver(ILogger logger, IFileSystem fileSystem, ILibraryManager libraryManager) { _logger = logger; _fileSystem = fileSystem; + _libraryManager = libraryManager; } /// @@ -74,7 +76,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio var directoryService = args.DirectoryService; // If we contain an album assume we are an artist folder - return args.FileSystemChildren.Where(i => (i.Attributes & FileAttributes.Directory) == FileAttributes.Directory).Any(i => MusicAlbumResolver.IsMusicAlbum(i.FullName, isMusicMediaFolder, directoryService, _logger, _fileSystem)) ? new MusicArtist() : null; + return args.FileSystemChildren.Where(i => (i.Attributes & FileAttributes.Directory) == FileAttributes.Directory).Any(i => MusicAlbumResolver.IsMusicAlbum(i.FullName, directoryService, _logger, _fileSystem, _libraryManager)) ? new MusicArtist() : null; } } diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs new file mode 100644 index 0000000000..9ff1223b08 --- /dev/null +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/BaseVideoResolver.cs @@ -0,0 +1,96 @@ +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Model.Entities; +using MediaBrowser.Naming.Video; +using System; + +namespace MediaBrowser.Server.Implementations.Library.Resolvers +{ + /// + /// Resolves a Path into a Video or Video subclass + /// + /// + public abstract class BaseVideoResolver : Controller.Resolvers.ItemResolver + where T : Video, new() + { + protected readonly ILibraryManager LibraryManager; + + protected BaseVideoResolver(ILibraryManager libraryManager) + { + LibraryManager = libraryManager; + } + + /// + /// Resolves the specified args. + /// + /// The args. + /// `0. + protected override T Resolve(ItemResolveArgs args) + { + return ResolveVideo(args); + } + + /// + /// Resolves the video. + /// + /// The type of the T video type. + /// The args. + /// ``0. + protected TVideoType ResolveVideo(ItemResolveArgs args) + where TVideoType : Video, new() + { + // If the path is a file check for a matching extensions + if (!args.IsDirectory) + { + var parser = new VideoFileParser(new ExpandedVideoOptions(), new Naming.Logging.NullLogger()); + var videoInfo = parser.ParseFile(args.Path); + + if (videoInfo == null) + { + return null; + } + + var isShortcut = string.Equals(videoInfo.Container, "strm", StringComparison.OrdinalIgnoreCase); + + if (LibraryManager.IsVideoFile(args.Path) || videoInfo.IsStub || isShortcut) + { + var type = string.Equals(videoInfo.Container, "iso", StringComparison.OrdinalIgnoreCase) || string.Equals(videoInfo.Container, "img", StringComparison.OrdinalIgnoreCase) ? + VideoType.Iso : + VideoType.VideoFile; + + var path = args.Path; + + var video = new TVideoType + { + VideoType = type, + Path = path, + IsInMixedFolder = true, + IsPlaceHolder = videoInfo.IsStub, + IsShortcut = isShortcut, + Name = videoInfo.Name + }; + + if (videoInfo.IsStub) + { + if (string.Equals(videoInfo.StubType, "dvd", StringComparison.OrdinalIgnoreCase)) + { + video.VideoType = VideoType.Dvd; + } + else if (string.Equals(videoInfo.StubType, "hddvd", StringComparison.OrdinalIgnoreCase)) + { + video.VideoType = VideoType.HdDvd; + } + else if (string.Equals(videoInfo.StubType, "bluray", StringComparison.OrdinalIgnoreCase)) + { + video.VideoType = VideoType.BluRay; + } + } + + return video; + } + } + + return null; + } + } +} diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/LocalTrailerResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/LocalTrailerResolver.cs index 662a9e87c3..dfeefb74fc 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/LocalTrailerResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/LocalTrailerResolver.cs @@ -16,7 +16,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers { private readonly IFileSystem _fileSystem; - public LocalTrailerResolver(IFileSystem fileSystem) + public LocalTrailerResolver(ILibraryManager libraryManager, IFileSystem fileSystem) : base(libraryManager) { _fileSystem = fileSystem; } diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 231b807d8e..b7a414b9de 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -21,14 +21,12 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies public class MovieResolver : BaseVideoResolver public class EpisodeResolver : BaseVideoResolver { + public EpisodeResolver(ILibraryManager libraryManager) : base(libraryManager) + { + } + /// /// Resolves the specified args. /// @@ -73,7 +77,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV if (episode.ParentIndexNumber == null) { - episode.ParentIndexNumber = TVUtils.GetSeasonNumberFromEpisodeFile(args.Path); + episode.ParentIndexNumber = SeriesResolver.GetSeasonNumberFromEpisodeFile(args.Path); } } diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs index 70280d8d3d..d3580aaf83 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs @@ -34,9 +34,9 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV { var season = new Season { - IndexNumber = TVUtils.GetSeasonNumberFromPath(args.Path) + IndexNumber = SeriesResolver.GetSeasonNumberFromPath(args.Path) }; - + if (season.IndexNumber.HasValue && season.IndexNumber.Value == 0) { season.Name = _config.Configuration.SeasonZeroDisplayName; diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index d3aad582a3..30eaf3198d 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -1,13 +1,19 @@ using MediaBrowser.Common.Extensions; using MediaBrowser.Common.IO; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Providers; using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; using MediaBrowser.Model.Logging; using System; +using System.Collections.Generic; +using System.Globalization; using System.IO; +using System.Linq; +using System.Text.RegularExpressions; namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV { @@ -18,11 +24,13 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV { private readonly IFileSystem _fileSystem; private readonly ILogger _logger; + private readonly ILibraryManager _libraryManager; - public SeriesResolver(IFileSystem fileSystem, ILogger logger) + public SeriesResolver(IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager) { _fileSystem = fileSystem; _logger = logger; + _libraryManager = libraryManager; } /// @@ -71,7 +79,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV return null; } - if (TVUtils.IsSeriesFolder(args.Path, isTvShowsFolder, args.FileSystemChildren, args.DirectoryService, _fileSystem, _logger)) + if (IsSeriesFolder(args.Path, isTvShowsFolder, args.FileSystemChildren, args.DirectoryService, _fileSystem, _logger, _libraryManager)) { return new Series(); } @@ -80,6 +88,454 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV return null; } + /// + /// Determines whether [is series folder] [the specified path]. + /// + /// The path. + /// if set to true [consider seasonless entries]. + /// The file system children. + /// The directory service. + /// The file system. + /// true if [is series folder] [the specified path]; otherwise, false. + public static bool IsSeriesFolder(string path, bool considerSeasonlessEntries, IEnumerable fileSystemChildren, IDirectoryService directoryService, IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager) + { + // A folder with more than 3 non-season folders in will not becounted as a series + var nonSeriesFolders = 0; + + foreach (var child in fileSystemChildren) + { + var attributes = child.Attributes; + + if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) + { + //logger.Debug("Igoring series file or folder marked hidden: {0}", child.FullName); + continue; + } + + // Can't enforce this because files saved by Bitcasa are always marked System + //if ((attributes & FileAttributes.System) == FileAttributes.System) + //{ + // logger.Debug("Igoring series subfolder marked system: {0}", child.FullName); + // continue; + //} + + if ((attributes & FileAttributes.Directory) == FileAttributes.Directory) + { + if (IsSeasonFolder(child.FullName, directoryService, fileSystem)) + { + //logger.Debug("{0} is a series because of season folder {1}.", path, child.FullName); + return true; + } + + if (IsBadFolder(child.Name)) + { + logger.Debug("Invalid folder under series: {0}", child.FullName); + + nonSeriesFolders++; + } + + if (nonSeriesFolders >= 3) + { + logger.Debug("{0} not a series due to 3 or more invalid folders.", path); + return false; + } + } + else + { + var fullName = child.FullName; + + if (libraryManager.IsVideoFile(fullName) || IsVideoPlaceHolder(fullName)) + { + if (GetEpisodeNumberFromFile(fullName, considerSeasonlessEntries).HasValue) + { + return true; + } + } + } + } + + logger.Debug("{0} is not a series folder.", path); + return false; + } + + /// + /// Determines whether [is place holder] [the specified path]. + /// + /// The path. + /// true if [is place holder] [the specified path]; otherwise, false. + /// path + private static bool IsVideoPlaceHolder(string path) + { + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentNullException("path"); + } + + var extension = Path.GetExtension(path); + + return string.Equals(extension, ".disc", StringComparison.OrdinalIgnoreCase); + } + + private static bool IsBadFolder(string name) + { + if (string.Equals(name, BaseItem.ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + if (string.Equals(name, BaseItem.ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + if (string.Equals(name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + return !EntityResolutionHelper.IgnoreFolders.Contains(name, StringComparer.OrdinalIgnoreCase); + } + + /// + /// Determines whether [is season folder] [the specified path]. + /// + /// The path. + /// The directory service. + /// The file system. + /// true if [is season folder] [the specified path]; otherwise, false. + private static bool IsSeasonFolder(string path, IDirectoryService directoryService, IFileSystem fileSystem) + { + var seasonNumber = GetSeasonNumberFromPath(path); + var hasSeasonNumber = seasonNumber != null; + + if (!hasSeasonNumber) + { + return false; + } + + //// It's a season folder if it's named as such and does not contain any audio files, apart from theme.mp3 + //foreach (var fileSystemInfo in directoryService.GetFileSystemEntries(path)) + //{ + // var attributes = fileSystemInfo.Attributes; + + // if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden) + // { + // continue; + // } + + // // Can't enforce this because files saved by Bitcasa are always marked System + // //if ((attributes & FileAttributes.System) == FileAttributes.System) + // //{ + // // continue; + // //} + + // if ((attributes & FileAttributes.Directory) == FileAttributes.Directory) + // { + // //if (IsBadFolder(fileSystemInfo.Name)) + // //{ + // // return false; + // //} + // } + // else + // { + // if (EntityResolutionHelper.IsAudioFile(fileSystemInfo.FullName) && + // !string.Equals(fileSystem.GetFileNameWithoutExtension(fileSystemInfo), BaseItem.ThemeSongFilename)) + // { + // return false; + // } + // } + //} + + return true; + } + + /// + /// A season folder must contain one of these somewhere in the name + /// + private static readonly string[] SeasonFolderNames = + { + "season", + "sæson", + "temporada", + "saison", + "staffel", + "series", + "сезон" + }; + + /// + /// Used to detect paths that represent episodes, need to make sure they don't also + /// match movie titles like "2001 A Space..." + /// Currently we limit the numbers here to 2 digits to try and avoid this + /// + private static readonly Regex[] EpisodeExpressions = + { + new Regex( + @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)[sS](?\d{1,4})[x,X]?[eE](?\d{1,3})[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d{1,3})[^\\\/]*$", + RegexOptions.Compiled) + }; + private static readonly Regex[] MultipleEpisodeExpressions = + { + new Regex( + @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})((-| - )\d{1,4}[eExX](?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})((-| - )\d{1,4}[xX][eE](?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})((-| - )?[xXeE](?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)[sS]?(?\d{1,4})[xX](?\d{1,3})(-[xE]?[eE]?(?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))((-| - )\d{1,4}[xXeE](?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))((-| - )\d{1,4}[xX][eE](?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))((-| - )?[xXeE](?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)(?((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?\d{1,4})[xX](?\d{1,3}))(-[xX]?[eE]?(?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d{1,3})((-| - )?[xXeE](?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled), + new Regex( + @".*(\\|\/)(?[^\\\/]*)[sS](?\d{1,4})[xX\.]?[eE](?\d{1,3})(-[xX]?[eE]?(?\d{1,3}))+[^\\\/]*$", + RegexOptions.Compiled) + }; + + /// + /// To avoid the following matching movies they are only valid when contained in a folder which has been matched as a being season, or the media type is TV series + /// + private static readonly Regex[] EpisodeExpressionsWithoutSeason = + { + new Regex( + @".*[\\\/](?\d{1,3})(-(?\d{2,3}))*\.\w+$", + RegexOptions.Compiled), + // "01.avi" + new Regex( + @".*(\\|\/)(?\d{1,3})(-(?\d{2,3}))*\s?-\s?[^\\\/]*$", + RegexOptions.Compiled), + // "01 - blah.avi", "01-blah.avi" + new Regex( + @".*(\\|\/)(?\d{1,3})(-(?\d{2,3}))*\.[^\\\/]+$", + RegexOptions.Compiled), + // "01.blah.avi" + new Regex( + @".*[\\\/][^\\\/]* - (?\d{1,3})(-(?\d{2,3}))*[^\\\/]*$", + RegexOptions.Compiled), + // "blah - 01.avi", "blah 2 - 01.avi", "blah - 01 blah.avi", "blah 2 - 01 blah", "blah - 01 - blah.avi", "blah 2 - 01 - blah" + }; + + /// + /// Gets the season number from path. + /// + /// The path. + /// System.Nullable{System.Int32}. + public static int? GetSeasonNumberFromPath(string path) + { + var filename = Path.GetFileName(path); + + if (string.Equals(filename, "specials", StringComparison.OrdinalIgnoreCase)) + { + return 0; + } + + int val; + if (int.TryParse(filename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) + { + return val; + } + + if (filename.StartsWith("s", StringComparison.OrdinalIgnoreCase)) + { + var testFilename = filename.Substring(1); + + if (int.TryParse(testFilename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val)) + { + return val; + } + } + + // Look for one of the season folder names + foreach (var name in SeasonFolderNames) + { + var index = filename.IndexOf(name, StringComparison.OrdinalIgnoreCase); + + if (index != -1) + { + return GetSeasonNumberFromPathSubstring(filename.Substring(index + name.Length)); + } + } + + return null; + } + + /// + /// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel") + /// + /// The path. + /// System.Nullable{System.Int32}. + private static int? GetSeasonNumberFromPathSubstring(string path) + { + var numericStart = -1; + var length = 0; + + // Find out where the numbers start, and then keep going until they end + for (var i = 0; i < path.Length; i++) + { + if (char.IsNumber(path, i)) + { + if (numericStart == -1) + { + numericStart = i; + } + length++; + } + else if (numericStart != -1) + { + break; + } + } + + if (numericStart == -1) + { + return null; + } + + return int.Parse(path.Substring(numericStart, length), CultureInfo.InvariantCulture); + } + + /// + /// Episodes the number from file. + /// + /// The full path. + /// if set to true [is in season]. + /// System.String. + public static int? GetEpisodeNumberFromFile(string fullPath, bool considerSeasonlessNames) + { + string fl = fullPath.ToLower(); + foreach (var r in EpisodeExpressions) + { + Match m = r.Match(fl); + if (m.Success) + return ParseEpisodeNumber(m.Groups["epnumber"].Value); + } + if (considerSeasonlessNames) + { + var match = EpisodeExpressionsWithoutSeason.Select(r => r.Match(fl)) + .FirstOrDefault(m => m.Success); + + if (match != null) + { + return ParseEpisodeNumber(match.Groups["epnumber"].Value); + } + } + + return null; + } + + public static int? GetEndingEpisodeNumberFromFile(string fullPath) + { + var fl = fullPath.ToLower(); + foreach (var r in MultipleEpisodeExpressions) + { + var m = r.Match(fl); + if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value)) + return ParseEpisodeNumber(m.Groups["endingepnumber"].Value); + } + foreach (var r in EpisodeExpressionsWithoutSeason) + { + var m = r.Match(fl); + if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value)) + return ParseEpisodeNumber(m.Groups["endingepnumber"].Value); + } + return null; + } + + /// + /// Seasons the number from episode file. + /// + /// The full path. + /// System.String. + public static int? GetSeasonNumberFromEpisodeFile(string fullPath) + { + string fl = fullPath.ToLower(); + foreach (var r in EpisodeExpressions) + { + Match m = r.Match(fl); + if (m.Success) + { + Group g = m.Groups["seasonnumber"]; + if (g != null) + { + var val = g.Value; + + if (!string.IsNullOrWhiteSpace(val)) + { + int num; + + if (int.TryParse(val, NumberStyles.Integer, UsCulture, out num)) + { + return num; + } + } + } + return null; + } + } + return null; + } + + public static string GetSeriesNameFromEpisodeFile(string fullPath) + { + var fl = fullPath.ToLower(); + foreach (var r in EpisodeExpressions) + { + var m = r.Match(fl); + if (m.Success) + { + var g = m.Groups["seriesname"]; + if (g != null) + { + var val = g.Value; + + if (!string.IsNullOrWhiteSpace(val)) + { + return val; + } + } + return null; + } + } + return null; + } + + private static readonly CultureInfo UsCulture = new CultureInfo("en-US"); + + private static int? ParseEpisodeNumber(string val) + { + int num; + + if (!string.IsNullOrEmpty(val) && int.TryParse(val, NumberStyles.Integer, UsCulture, out num)) + { + return num; + } + + return null; + } + /// /// Sets the initial item values. /// diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/VideoResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/VideoResolver.cs index 391a3d9484..cde75aea29 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/VideoResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/VideoResolver.cs @@ -1,5 +1,9 @@ using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; +using MediaBrowser.Model.Entities; +using System; +using System.Linq; namespace MediaBrowser.Server.Implementations.Library.Resolvers { @@ -8,6 +12,31 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers /// public class VideoResolver : BaseVideoResolver