diff options
Diffstat (limited to 'MediaBrowser.Server.Implementations/Library')
12 files changed, 531 insertions, 548 deletions
diff --git a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs index 4cb39778c..66125784c 100644 --- a/MediaBrowser.Server.Implementations/Library/LibraryManager.cs +++ b/MediaBrowser.Server.Implementations/Library/LibraryManager.cs @@ -18,8 +18,8 @@ using MediaBrowser.Model.Logging; using MediaBrowser.Naming.Audio; using MediaBrowser.Naming.Common; using MediaBrowser.Naming.IO; +using MediaBrowser.Naming.TV; using MediaBrowser.Naming.Video; -using MediaBrowser.Server.Implementations.Library.Resolvers.TV; using MediaBrowser.Server.Implementations.Library.Validators; using MediaBrowser.Server.Implementations.ScheduledTasks; using System; @@ -560,10 +560,9 @@ namespace MediaBrowser.Server.Implementations.Library } public BaseItem ResolvePath(FileSystemInfo fileInfo, - Folder parent = null, - string collectionType = null) + Folder parent = null) { - return ResolvePath(fileInfo, new DirectoryService(_logger), parent, collectionType); + return ResolvePath(fileInfo, new DirectoryService(_logger), parent); } private BaseItem ResolvePath(FileSystemInfo fileInfo, IDirectoryService directoryService, Folder parent = null, string collectionType = null) @@ -573,10 +572,17 @@ namespace MediaBrowser.Server.Implementations.Library throw new ArgumentNullException("fileInfo"); } + var fullPath = fileInfo.FullName; + + if (string.IsNullOrWhiteSpace(collectionType)) + { + collectionType = GetConfiguredContentType(fullPath); + } + var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, this, directoryService) { Parent = parent, - Path = fileInfo.FullName, + Path = fullPath, FileInfo = fileInfo, CollectionType = collectionType }; @@ -862,7 +868,7 @@ namespace MediaBrowser.Server.Implementations.Library var type = typeof(T); - if (type == typeof(Person) && ConfigurationManager.Configuration.EnablePeoplePrefixSubFolders) + if (type == typeof(Person)) { subFolderPrefix = validFilename.Substring(0, 1); } @@ -1546,12 +1552,48 @@ namespace MediaBrowser.Server.Implementations.Library return ItemRepository.RetrieveItem(id); } - /// <summary> - /// Finds the type of the collection. - /// </summary> - /// <param name="item">The item.</param> - /// <returns>System.String.</returns> - public string FindCollectionType(BaseItem item) + public string GetContentType(BaseItem item) + { + // Types cannot be overridden, so go from the top down until we find a configured content type + + var type = GetTopFolderContentType(item); + + if (!string.IsNullOrWhiteSpace(type)) + { + return type; + } + + type = GetInheritedContentType(item); + + if (!string.IsNullOrWhiteSpace(type)) + { + return type; + } + + return GetConfiguredContentType(item); + } + + public string GetInheritedContentType(BaseItem item) + { + return item.Parents + .Select(GetConfiguredContentType) + .LastOrDefault(i => !string.IsNullOrWhiteSpace(i)); + } + + private string GetConfiguredContentType(BaseItem item) + { + return GetConfiguredContentType(item.ContainingFolderPath); + } + + private string GetConfiguredContentType(string path) + { + var type = ConfigurationManager.Configuration.ContentTypes + .FirstOrDefault(i => string.Equals(i.Name, path, StringComparison.OrdinalIgnoreCase) || _fileSystem.ContainsSubPath(i.Name, path)); + + return type == null ? null : type.Value; + } + + private string GetTopFolderContentType(BaseItem item) { while (!(item.Parent is AggregateFolder) && item.Parent != null) { @@ -1563,14 +1605,11 @@ namespace MediaBrowser.Server.Implementations.Library return null; } - var collectionTypes = GetUserRootFolder().Children + return GetUserRootFolder().Children .OfType<ICollectionFolder>() - .Where(i => !string.IsNullOrEmpty(i.CollectionType) && (string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path))) + .Where(i => string.Equals(i.Path, item.Path, StringComparison.OrdinalIgnoreCase) || i.PhysicalLocations.Contains(item.Path)) .Select(i => i.CollectionType) - .Distinct() - .ToList(); - - return collectionTypes.Count == 1 ? collectionTypes[0] : null; + .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i)); } public async Task<UserView> GetNamedView(string name, @@ -1708,22 +1747,127 @@ namespace MediaBrowser.Server.Implementations.Library public int? GetSeasonNumberFromPath(string path) { - return SeriesResolver.GetSeasonNumberFromPath(path, CollectionType.TvShows); + return new SeasonPathParser(new ExtendedNamingOptions(), new RegexProvider()).Parse(path, true).SeasonNumber; } - public int? GetSeasonNumberFromEpisodeFile(string path) + public bool FillMissingEpisodeNumbersFromPath(Episode episode) { - return SeriesResolver.GetSeasonNumberFromEpisodeFile(path); - } + var resolver = new EpisodeResolver(new ExtendedNamingOptions(), + new Naming.Logging.NullLogger()); - public int? GetEndingEpisodeNumberFromFile(string path) - { - return SeriesResolver.GetEndingEpisodeNumberFromFile(path); - } + var fileType = episode.VideoType == VideoType.BluRay || episode.VideoType == VideoType.Dvd || episode.VideoType == VideoType.HdDvd ? + FileInfoType.Directory : + FileInfoType.File; - public int? GetEpisodeNumberFromFile(string path, bool considerSeasonless) - { - return SeriesResolver.GetEpisodeNumberFromFile(path, considerSeasonless); + var locationType = episode.LocationType; + + var episodeInfo = locationType == LocationType.FileSystem || locationType == LocationType.Offline ? + resolver.Resolve(episode.Path, fileType) : + new Naming.TV.EpisodeInfo(); + + if (episodeInfo == null) + { + episodeInfo = new Naming.TV.EpisodeInfo(); + } + + var changed = false; + + if (episodeInfo.IsByDate) + { + if (episode.IndexNumber.HasValue) + { + episode.IndexNumber = null; + changed = true; + } + + if (episode.IndexNumberEnd.HasValue) + { + episode.IndexNumberEnd = null; + changed = true; + } + + if (!episode.PremiereDate.HasValue) + { + if (episodeInfo.Year.HasValue && episodeInfo.Month.HasValue && episodeInfo.Day.HasValue) + { + episode.PremiereDate = new DateTime(episodeInfo.Year.Value, episodeInfo.Month.Value, episodeInfo.Day.Value).ToUniversalTime(); + } + + if (episode.PremiereDate.HasValue) + { + changed = true; + } + } + + if (!episode.ProductionYear.HasValue) + { + episode.ProductionYear = episodeInfo.Year; + + if (episode.ProductionYear.HasValue) + { + changed = true; + } + } + + if (!episode.ParentIndexNumber.HasValue) + { + var season = episode.Season; + + if (season != null) + { + episode.ParentIndexNumber = season.IndexNumber; + } + + if (episode.ParentIndexNumber.HasValue) + { + changed = true; + } + } + } + else + { + if (!episode.IndexNumber.HasValue) + { + episode.IndexNumber = episodeInfo.EpisodeNumber; + + if (episode.IndexNumber.HasValue) + { + changed = true; + } + } + + if (!episode.IndexNumberEnd.HasValue) + { + episode.IndexNumberEnd = episodeInfo.EndingEpsiodeNumber; + + if (episode.IndexNumberEnd.HasValue) + { + changed = true; + } + } + + if (!episode.ParentIndexNumber.HasValue) + { + episode.ParentIndexNumber = episodeInfo.SeasonNumber; + + if (!episode.ParentIndexNumber.HasValue) + { + var season = episode.Season; + + if (season != null) + { + episode.ParentIndexNumber = season.IndexNumber; + } + } + + if (episode.ParentIndexNumber.HasValue) + { + changed = true; + } + } + } + + return changed; } public ItemLookupInfo ParseName(string name) diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs index f32ed2b20..05ff270fc 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicAlbumResolver.cs @@ -37,7 +37,11 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio /// <value>The priority.</value> public override ResolverPriority Priority { - get { return ResolverPriority.Third; } // we need to be ahead of the generic folder resolver but behind the movie one + get + { + // Behind special folder resolver + return ResolverPriority.Second; + } } /// <summary> @@ -49,21 +53,13 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio { if (!args.IsDirectory) return null; - //Avoid mis-identifying top folders - if (args.Parent == null) return null; + // Avoid mis-identifying top folders if (args.Parent.IsRoot) return null; if (args.HasParent<MusicAlbum>()) return null; - // Optimization - if (args.HasParent<BoxSet>() || args.HasParent<Series>() || args.HasParent<Season>()) - { - return null; - } - var collectionType = args.GetCollectionType(); - var isMusicMediaFolder = string.Equals(collectionType, CollectionType.Music, - StringComparison.OrdinalIgnoreCase); + var isMusicMediaFolder = string.Equals(collectionType, CollectionType.Music, StringComparison.OrdinalIgnoreCase); // If there's a collection type and it's not music, don't allow it. if (!isMusicMediaFolder) diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs index 71b6c0843..edbc87415 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/Audio/MusicArtistResolver.cs @@ -34,7 +34,11 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio /// <value>The priority.</value> public override ResolverPriority Priority { - get { return ResolverPriority.Third; } // we need to be ahead of the generic folder resolver but behind the movie one + get + { + // Behind special folder resolver + return ResolverPriority.Second; + } } /// <summary> @@ -46,8 +50,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio { if (!args.IsDirectory) return null; - //Avoid mis-identifying top folders - if (args.Parent == null) return null; + // Avoid mis-identifying top folders if (args.Parent.IsRoot) return null; // Don't allow nested artists @@ -56,16 +59,9 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Audio return null; } - // Optimization - if (args.HasParent<BoxSet>() || args.HasParent<Series>() || args.HasParent<Season>()) - { - return null; - } - var collectionType = args.GetCollectionType(); - var isMusicMediaFolder = string.Equals(collectionType, CollectionType.Music, - StringComparison.OrdinalIgnoreCase); + var isMusicMediaFolder = string.Equals(collectionType, CollectionType.Music, StringComparison.OrdinalIgnoreCase); // If there's a collection type and it's not music, it can't be a series if (!isMusicMediaFolder) diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/FolderResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/FolderResolver.cs index 166465f72..34237622d 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/FolderResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/FolderResolver.cs @@ -1,10 +1,6 @@ -using MediaBrowser.Common.IO; -using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; using MediaBrowser.Controller.Resolvers; -using System; -using System.IO; -using System.Linq; namespace MediaBrowser.Server.Implementations.Library.Resolvers { @@ -13,13 +9,6 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers /// </summary> public class FolderResolver : FolderResolver<Folder> { - private readonly IFileSystem _fileSystem; - - public FolderResolver(IFileSystem fileSystem) - { - _fileSystem = fileSystem; - } - /// <summary> /// Gets the priority. /// </summary> @@ -38,48 +27,11 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers { if (args.IsDirectory) { - if (args.IsPhysicalRoot) - { - return new AggregateFolder(); - } - if (args.IsRoot) - { - return new UserRootFolder(); //if we got here and still a root - must be user root - } - if (args.IsVf) - { - return new CollectionFolder - { - CollectionType = GetCollectionType(args) - }; - } - return new Folder(); } return null; } - - private string GetCollectionType(ItemResolveArgs args) - { - return args.FileSystemChildren - .Where(i => - { - - try - { - return (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && - string.Equals(".collection", i.Extension, StringComparison.OrdinalIgnoreCase); - } - catch (IOException) - { - return false; - } - - }) - .Select(i => _fileSystem.GetFileNameWithoutExtension(i)) - .FirstOrDefault(); - } } /// <summary> diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs index 276b99d3a..01dc4db8a 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/Movies/MovieResolver.cs @@ -79,11 +79,10 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies return ResolveVideos<Video>(parent, files, directoryService, collectionType); } - return ResolveVideos<Movie>(parent, files, directoryService, collectionType); + return ResolveVideos<Video>(parent, files, directoryService, collectionType); } - if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase) || - string.Equals(collectionType, CollectionType.BoxSets, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase)) { return ResolveVideos<Movie>(parent, files, directoryService, collectionType); } @@ -117,7 +116,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies FullName = i.FullName, Type = FileInfoType.File - }).ToList()).ToList(); + }).ToList(), false).ToList(); var result = new MultiItemResolverResult { @@ -168,12 +167,12 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies { if (string.Equals(collectionType, CollectionType.MusicVideos, StringComparison.OrdinalIgnoreCase)) { - return FindMovie<MusicVideo>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType, false); + return FindMovie<MusicVideo>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); } if (string.Equals(collectionType, CollectionType.HomeVideos, StringComparison.OrdinalIgnoreCase)) { - return FindMovie<Video>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType, false); + return FindMovie<Video>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); } if (string.IsNullOrEmpty(collectionType)) @@ -184,17 +183,10 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies return FindMovie<Video>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); } - // Since the looping is expensive, this is an optimization to help us avoid it - if (args.ContainsMetaFileByName("series.xml")) - { - return null; - } - return FindMovie<Movie>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); } - if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase) || - string.Equals(collectionType, CollectionType.BoxSets, StringComparison.OrdinalIgnoreCase)) + if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase)) { return FindMovie<Movie>(args.Path, args.Parent, args.FileSystemChildren.ToList(), args.DirectoryService, collectionType); } @@ -216,8 +208,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies } // To find a movie file, the collection type must be movies or boxsets - else if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase) || - string.Equals(collectionType, CollectionType.BoxSets, StringComparison.OrdinalIgnoreCase)) + else if (string.Equals(collectionType, CollectionType.Movies, StringComparison.OrdinalIgnoreCase)) { item = ResolveVideo<Movie>(args, true); } @@ -228,7 +219,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies } else if (string.IsNullOrEmpty(collectionType)) { - item = ResolveVideo<Movie>(args, false); + item = ResolveVideo<Video>(args, false); } if (item != null) @@ -277,9 +268,8 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies /// <param name="fileSystemEntries">The file system entries.</param> /// <param name="directoryService">The directory service.</param> /// <param name="collectionType">Type of the collection.</param> - /// <param name="supportMultiVersion">if set to <c>true</c> [support multi version].</param> /// <returns>Movie.</returns> - private T FindMovie<T>(string path, Folder parent, List<FileSystemInfo> fileSystemEntries, IDirectoryService directoryService, string collectionType, bool supportMultiVersion = true) + private T FindMovie<T>(string path, Folder parent, List<FileSystemInfo> fileSystemEntries, IDirectoryService directoryService, string collectionType) where T : Video, new() { var multiDiscFolders = new List<FileSystemInfo>(); @@ -328,8 +318,11 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies var result = ResolveVideos<T>(parent, fileSystemEntries, directoryService, collectionType); + var supportsMultiVersion = !string.Equals(collectionType, CollectionType.HomeVideos) && + !string.Equals(collectionType, CollectionType.MusicVideos); + // Test for multi-editions - if (result.Items.Count > 1 && supportMultiVersion) + if (result.Items.Count > 1 && supportsMultiVersion) { var filenamePrefix = Path.GetFileName(path); @@ -474,7 +467,6 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.Movies CollectionType.Movies, CollectionType.HomeVideos, CollectionType.MusicVideos, - CollectionType.BoxSets, CollectionType.Movies }; diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs index 2fcfd7086..acae5b801 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/PhotoAlbumResolver.cs @@ -1,5 +1,6 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Resolvers; using MediaBrowser.Model.Entities; using System; using System.IO; @@ -17,7 +18,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers protected override PhotoAlbum Resolve(ItemResolveArgs args) { // Must be an image file within a photo collection - if (!args.IsRoot && args.IsDirectory && string.Equals(args.GetCollectionType(), CollectionType.Photos, StringComparison.OrdinalIgnoreCase)) + if (args.IsDirectory && string.Equals(args.GetCollectionType(), CollectionType.Photos, StringComparison.OrdinalIgnoreCase)) { if (HasPhotos(args)) { @@ -35,5 +36,14 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers { return args.FileSystemChildren.Any(i => ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory) && PhotoResolver.IsImageFile(i.FullName)); } + + public override ResolverPriority Priority + { + get + { + // Behind special folder resolver + return ResolverPriority.Second; + } + } } } diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs new file mode 100644 index 000000000..0a41a6c04 --- /dev/null +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/SpecialFolderResolver.cs @@ -0,0 +1,79 @@ +using MediaBrowser.Common.IO; +using MediaBrowser.Controller.Entities; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Resolvers; +using System; +using System.IO; +using System.Linq; + +namespace MediaBrowser.Server.Implementations.Library.Resolvers +{ + class SpecialFolderResolver : FolderResolver<Folder> + { + private readonly IFileSystem _fileSystem; + + public SpecialFolderResolver(IFileSystem fileSystem) + { + _fileSystem = fileSystem; + } + + /// <summary> + /// Gets the priority. + /// </summary> + /// <value>The priority.</value> + public override ResolverPriority Priority + { + get { return ResolverPriority.First; } + } + + /// <summary> + /// Resolves the specified args. + /// </summary> + /// <param name="args">The args.</param> + /// <returns>Folder.</returns> + protected override Folder Resolve(ItemResolveArgs args) + { + if (args.IsDirectory) + { + if (args.IsPhysicalRoot) + { + return new AggregateFolder(); + } + if (args.IsRoot) + { + return new UserRootFolder(); //if we got here and still a root - must be user root + } + if (args.IsVf) + { + return new CollectionFolder + { + CollectionType = GetCollectionType(args) + }; + } + } + + return null; + } + + private string GetCollectionType(ItemResolveArgs args) + { + return args.FileSystemChildren + .Where(i => + { + + try + { + return (i.Attributes & FileAttributes.Directory) != FileAttributes.Directory && + string.Equals(".collection", i.Extension, StringComparison.OrdinalIgnoreCase); + } + catch (IOException) + { + return false; + } + + }) + .Select(i => _fileSystem.GetFileNameWithoutExtension(i)) + .FirstOrDefault(); + } + } +} diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs index 057425ca9..1a873f01e 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/EpisodeResolver.cs @@ -37,23 +37,10 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV } // If the parent is a Season or Series, then this is an Episode if the VideoResolver returns something - if (season != null || parent is Series || parent.Parents.OfType<Series>().Any()) + if (season != null || args.HasParent<Series>()) { var episode = ResolveVideo<Episode>(args, false); - if (episode != null) - { - if (season != null) - { - episode.ParentIndexNumber = season.IndexNumber; - } - - if (episode.ParentIndexNumber == null) - { - episode.ParentIndexNumber = SeriesResolver.GetSeasonNumberFromEpisodeFile(args.Path); - } - } - return episode; } diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs index 058fb1489..80477e567 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeasonResolver.cs @@ -1,7 +1,8 @@ using MediaBrowser.Controller.Configuration; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; -using MediaBrowser.Model.Entities; +using MediaBrowser.Naming.Common; +using MediaBrowser.Naming.TV; namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV { @@ -35,7 +36,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV { var season = new Season { - IndexNumber = SeriesResolver.GetSeasonNumberFromPath(args.Path, CollectionType.TvShows) + IndexNumber = new SeasonPathParser(new ExtendedNamingOptions(), new RegexProvider()).Parse(args.Path, true).SeasonNumber }; if (season.IndexNumber.HasValue && season.IndexNumber.Value == 0) diff --git a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs index 72c0bae53..00bed4086 100644 --- a/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs +++ b/MediaBrowser.Server.Implementations/Library/Resolvers/TV/SeriesResolver.cs @@ -1,5 +1,4 @@ using MediaBrowser.Common.IO; -using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; @@ -9,10 +8,10 @@ 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; +using MediaBrowser.Naming.Common; +using MediaBrowser.Naming.IO; +using MediaBrowser.Naming.TV; namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV { @@ -54,26 +53,22 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV if (args.IsDirectory) { // Avoid expensive tests against VF's and all their children by not allowing this - if (args.Parent == null || args.Parent.IsRoot) - { - return null; - } - - // Optimization to avoid running these tests against Seasons - if (args.HasParent<Series>() || args.HasParent<Season>() || args.HasParent<MusicArtist>() || args.HasParent<MusicAlbum>()) + if (args.Parent.IsRoot) { return null; } var collectionType = args.GetCollectionType(); - var isTvShowsFolder = string.Equals(collectionType, CollectionType.TvShows, - StringComparison.OrdinalIgnoreCase); + var isTvShowsFolder = string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase); // If there's a collection type and it's not tv, it can't be a series - if (!string.IsNullOrEmpty(collectionType) && - !isTvShowsFolder && - !string.Equals(collectionType, CollectionType.BoxSets, StringComparison.OrdinalIgnoreCase)) + if (!isTvShowsFolder) + { + return null; + } + + if (args.HasParent<Series>() || args.HasParent<Season>()) { return null; } @@ -123,7 +118,7 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV if ((attributes & FileAttributes.Directory) == FileAttributes.Directory) { - if (IsSeasonFolder(child.FullName, collectionType, directoryService, fileSystem)) + if (IsSeasonFolder(child.FullName, collectionType)) { //logger.Debug("{0} is a series because of season folder {1}.", path, child.FullName); return true; @@ -137,7 +132,17 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV { var isTvShowsFolder = string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase); - if (GetEpisodeNumberFromFile(fullName, isTvShowsFolder).HasValue) + // We can fast track this for known tv folders + if (isTvShowsFolder) + { + return true; + } + + var resolver = new Naming.TV.EpisodeResolver(new ExtendedNamingOptions(), new Naming.Logging.NullLogger()); + + var episodeInfo = resolver.Resolve(fullName, FileInfoType.File, isTvShowsFolder, false); + + if (episodeInfo != null && (episodeInfo.EpisodeNumber.HasValue || episodeInfo.IsByDate)) { return true; } @@ -172,351 +177,13 @@ namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV /// </summary> /// <param name="path">The path.</param> /// <param name="collectionType">Type of the collection.</param> - /// <param name="directoryService">The directory service.</param> - /// <param name="fileSystem">The file system.</param> /// <returns><c>true</c> if [is season folder] [the specified path]; otherwise, <c>false</c>.</returns> - private static bool IsSeasonFolder(string path, string collectionType, IDirectoryService directoryService, IFileSystem fileSystem) - { - var seasonNumber = GetSeasonNumberFromPath(path, collectionType); - 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; - } - - /// <summary> - /// A season folder must contain one of these somewhere in the name - /// </summary> - private static readonly string[] SeasonFolderNames = - { - "season", - "sæson", - "temporada", - "saison", - "staffel", - "series", - "сезон" - }; - - /// <summary> - /// 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 - /// </summary> - private static readonly Regex[] EpisodeExpressions = - { - new Regex( - @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)[sS](?<seasonnumber>\d{1,4})[x,X]?[eE](?<epnumber>\d{1,3})[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})[^\\\/]*$", - RegexOptions.Compiled) - }; - private static readonly Regex[] MultipleEpisodeExpressions = - { - new Regex( - @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )\d{1,4}[eExX](?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )\d{1,4}[xX][eE](?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})(-[xE]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )\d{1,4}[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )\d{1,4}[xX][eE](?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))(-[xX]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled), - new Regex( - @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})(-[xX]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$", - RegexOptions.Compiled) - }; - - /// <summary> - /// 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 - /// </summary> - private static readonly Regex[] EpisodeExpressionsWithoutSeason = - { - new Regex( - @".*[\\\/](?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\.\w+$", - RegexOptions.Compiled), - // "01.avi" - new Regex( - @".*(\\|\/)(?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\s?-\s?[^\\\/]*$", - RegexOptions.Compiled), - // "01 - blah.avi", "01-blah.avi" - new Regex( - @".*(\\|\/)(?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\.[^\\\/]+$", - RegexOptions.Compiled), - // "01.blah.avi" - new Regex( - @".*[\\\/][^\\\/]* - (?<epnumber>\d{1,3})(-(?<endingepnumber>\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" - }; - - public static int? GetSeasonNumberFromPath(string path) - { - return GetSeasonNumberFromPath(path, CollectionType.TvShows); - } - - /// <summary> - /// Gets the season number from path. - /// </summary> - /// <param name="path">The path.</param> - /// <param name="collectionType">Type of the collection.</param> - /// <returns>System.Nullable{System.Int32}.</returns> - public static int? GetSeasonNumberFromPath(string path, string collectionType) - { - var filename = Path.GetFileName(path); - - if (string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase)) - { - 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; - } - - /// <summary> - /// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel") - /// </summary> - /// <param name="path">The path.</param> - /// <returns>System.Nullable{System.Int32}.</returns> - private static int? GetSeasonNumberFromPathSubstring(string path) + private static bool IsSeasonFolder(string path, string collectionType) { - var numericStart = -1; - var length = 0; + var isTvFolder = string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase); + var seasonNumber = new SeasonPathParser(new ExtendedNamingOptions(), new RegexProvider()).Parse(path, isTvFolder).SeasonNumber; - // 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); - } - - /// <summary> - /// Episodes the number from file. - /// </summary> - /// <param name="fullPath">The full path.</param> - /// <param name="considerSeasonlessNames">if set to <c>true</c> [is in season].</param> - /// <returns>System.String.</returns> - 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; - } - - /// <summary> - /// Seasons the number from episode file. - /// </summary> - /// <param name="fullPath">The full path.</param> - /// <returns>System.String.</returns> - 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; + return seasonNumber.HasValue; } /// <summary> diff --git a/MediaBrowser.Server.Implementations/Library/SearchEngine.cs b/MediaBrowser.Server.Implementations/Library/SearchEngine.cs index bd845ef4a..071031b25 100644 --- a/MediaBrowser.Server.Implementations/Library/SearchEngine.cs +++ b/MediaBrowser.Server.Implementations/Library/SearchEngine.cs @@ -1,5 +1,6 @@ using MediaBrowser.Controller.Entities; using MediaBrowser.Controller.Entities.Audio; +using MediaBrowser.Controller.Entities.TV; using MediaBrowser.Controller.Library; using MediaBrowser.Model.Logging; using MediaBrowser.Model.Querying; @@ -105,7 +106,7 @@ namespace MediaBrowser.Server.Implementations.Library if (query.IncludeMedia) { // Add search hints based on item name - hints.AddRange(items.Where(i => !string.IsNullOrWhiteSpace(i.Name)).Select(item => + hints.AddRange(items.Where(i => !string.IsNullOrWhiteSpace(i.Name) && IncludeInSearch(i)).Select(item => { var index = GetIndex(item.Name, searchTerm, terms); @@ -289,6 +290,20 @@ namespace MediaBrowser.Server.Implementations.Library return Task.FromResult(returnValue); } + private bool IncludeInSearch(BaseItem item) + { + var episode = item as Episode; + + if (episode != null) + { + if (episode.IsVirtualUnaired || episode.IsMissingEpisode) + { + return false; + } + } + return true; + } + /// <summary> /// Gets the index. /// </summary> diff --git a/MediaBrowser.Server.Implementations/Library/UserManager.cs b/MediaBrowser.Server.Implementations/Library/UserManager.cs index 791cae553..1a45d35a0 100644 --- a/MediaBrowser.Server.Implementations/Library/UserManager.cs +++ b/MediaBrowser.Server.Implementations/Library/UserManager.cs @@ -1,5 +1,4 @@ -using System.Collections.Concurrent; -using MediaBrowser.Common.Events; +using MediaBrowser.Common.Events; using MediaBrowser.Common.Extensions; using MediaBrowser.Common.Net; using MediaBrowser.Controller; @@ -63,6 +62,7 @@ namespace MediaBrowser.Server.Implementations.Library public event EventHandler<GenericEventArgs<User>> UserPasswordChanged; private readonly IXmlSerializer _xmlSerializer; + private readonly IJsonSerializer _jsonSerializer; private readonly INetworkManager _networkManager; @@ -71,13 +71,7 @@ namespace MediaBrowser.Server.Implementations.Library private readonly Func<IConnectManager> _connectFactory; private readonly IServerApplicationHost _appHost; - /// <summary> - /// Initializes a new instance of the <see cref="UserManager" /> class. - /// </summary> - /// <param name="logger">The logger.</param> - /// <param name="configurationManager">The configuration manager.</param> - /// <param name="userRepository">The user repository.</param> - public UserManager(ILogger logger, IServerConfigurationManager configurationManager, IUserRepository userRepository, IXmlSerializer xmlSerializer, INetworkManager networkManager, Func<IImageProcessor> imageProcessorFactory, Func<IDtoService> dtoServiceFactory, Func<IConnectManager> connectFactory, IServerApplicationHost appHost) + public UserManager(ILogger logger, IServerConfigurationManager configurationManager, IUserRepository userRepository, IXmlSerializer xmlSerializer, INetworkManager networkManager, Func<IImageProcessor> imageProcessorFactory, Func<IDtoService> dtoServiceFactory, Func<IConnectManager> connectFactory, IServerApplicationHost appHost, IJsonSerializer jsonSerializer) { _logger = logger; UserRepository = userRepository; @@ -87,6 +81,7 @@ namespace MediaBrowser.Server.Implementations.Library _dtoServiceFactory = dtoServiceFactory; _connectFactory = connectFactory; _appHost = appHost; + _jsonSerializer = jsonSerializer; ConfigurationManager = configurationManager; Users = new List<User>(); @@ -164,6 +159,11 @@ namespace MediaBrowser.Server.Implementations.Library public async Task Initialize() { Users = await LoadUsers().ConfigureAwait(false); + + foreach (var user in Users.ToList()) + { + await DoPolicyMigration(user).ConfigureAwait(false); + } } public Task<bool> AuthenticateUser(string username, string passwordSha1, string remoteEndPoint) @@ -171,6 +171,38 @@ namespace MediaBrowser.Server.Implementations.Library return AuthenticateUser(username, passwordSha1, null, remoteEndPoint); } + public bool IsValidUsername(string username) + { + // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.) + return username.All(IsValidCharacter); + } + + private bool IsValidCharacter(char i) + { + return char.IsLetterOrDigit(i) || char.Equals(i, '-') || char.Equals(i, '_') || char.Equals(i, '\'') || + char.Equals(i, '.'); + } + + public string MakeValidUsername(string username) + { + if (IsValidUsername(username)) + { + return username; + } + + // Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.) + var builder = new StringBuilder(); + + foreach (var c in username) + { + if (IsValidCharacter(c)) + { + builder.Append(c); + } + } + return builder.ToString(); + } + public async Task<bool> AuthenticateUser(string username, string passwordSha1, string passwordMd5, string remoteEndPoint) { if (string.IsNullOrWhiteSpace(username)) @@ -178,14 +210,15 @@ namespace MediaBrowser.Server.Implementations.Library throw new ArgumentNullException("username"); } - var user = Users.FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase)); + var user = Users + .FirstOrDefault(i => string.Equals(username, i.Name, StringComparison.OrdinalIgnoreCase)); if (user == null) { throw new SecurityException("Invalid username or password entered."); } - if (user.Configuration.IsDisabled) + if (user.Policy.IsDisabled) { throw new SecurityException(string.Format("The {0} account is currently disabled. Please consult with your administrator.", user.Name)); } @@ -203,20 +236,6 @@ namespace MediaBrowser.Server.Implementations.Library } } - // Maybe user accidently entered connect credentials. let's be flexible - if (!success && user.ConnectLinkType.HasValue && !string.IsNullOrWhiteSpace(passwordMd5)) - { - try - { - await _connectFactory().Authenticate(user.ConnectUserName, passwordMd5).ConfigureAwait(false); - success = true; - } - catch - { - - } - } - // Update LastActivityDate and LastLoginDate, then save if (success) { @@ -273,7 +292,7 @@ namespace MediaBrowser.Server.Implementations.Library // There always has to be at least one user. if (users.Count == 0) { - var name = Environment.UserName; + var name = MakeValidUsername(Environment.UserName); var user = InstantiateNewUser(name, false); @@ -283,14 +302,42 @@ namespace MediaBrowser.Server.Implementations.Library users.Add(user); - user.Configuration.IsAdministrator = true; - user.Configuration.EnableRemoteControlOfOtherUsers = true; - UpdateConfiguration(user, user.Configuration); + user.Policy.IsAdministrator = true; + user.Policy.EnableRemoteControlOfOtherUsers = true; + await UpdateUserPolicy(user, user.Policy, false).ConfigureAwait(false); } return users; } + private async Task DoPolicyMigration(User user) + { + if (!user.Configuration.HasMigratedToPolicy) + { + user.Policy.AccessSchedules = user.Configuration.AccessSchedules; + user.Policy.BlockedChannels = user.Configuration.BlockedChannels; + user.Policy.BlockedMediaFolders = user.Configuration.BlockedMediaFolders; + user.Policy.BlockedTags = user.Configuration.BlockedTags; + user.Policy.BlockUnratedItems = user.Configuration.BlockUnratedItems; + user.Policy.EnableContentDeletion = user.Configuration.EnableContentDeletion; + user.Policy.EnableLiveTvAccess = user.Configuration.EnableLiveTvAccess; + user.Policy.EnableLiveTvManagement = user.Configuration.EnableLiveTvManagement; + user.Policy.EnableMediaPlayback = user.Configuration.EnableMediaPlayback; + user.Policy.EnableRemoteControlOfOtherUsers = user.Configuration.EnableRemoteControlOfOtherUsers; + user.Policy.EnableSharedDeviceControl = user.Configuration.EnableSharedDeviceControl; + user.Policy.EnableUserPreferenceAccess = user.Configuration.EnableUserPreferenceAccess; + user.Policy.IsAdministrator = user.Configuration.IsAdministrator; + user.Policy.IsDisabled = user.Configuration.IsDisabled; + user.Policy.IsHidden = user.Configuration.IsHidden; + user.Policy.MaxParentalRating = user.Configuration.MaxParentalRating; + + await UpdateUserPolicy(user.Id.ToString("N"), user.Policy); + + user.Configuration.HasMigratedToPolicy = true; + await UpdateConfiguration(user, user.Configuration, true).ConfigureAwait(false); + } + } + public UserDto GetUserDto(User user, string remoteEndPoint = null) { if (user == null) @@ -449,6 +496,11 @@ namespace MediaBrowser.Server.Implementations.Library throw new ArgumentNullException("name"); } + if (!IsValidUsername(name)) + { + throw new ArgumentException("Usernames can contain letters (a-z), numbers (0-9), dashes (-), underscores (_), apostrophes ('), and periods (.)"); + } + if (Users.Any(u => u.Name.Equals(name, StringComparison.OrdinalIgnoreCase))) { throw new ArgumentException(string.Format("A user with the name '{0}' already exists.", name)); @@ -509,7 +561,7 @@ namespace MediaBrowser.Server.Implementations.Library throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one user in the system.", user.Name)); } - if (user.Configuration.IsAdministrator && allUsers.Count(i => i.Configuration.IsAdministrator) == 1) + if (user.Policy.IsAdministrator && allUsers.Count(i => i.Policy.IsAdministrator) == 1) { throw new ArgumentException(string.Format("The user '{0}' cannot be deleted because there must be at least one admin user in the system.", user.Name)); } @@ -518,17 +570,17 @@ namespace MediaBrowser.Server.Implementations.Library try { - await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false); + var configPath = GetConfigurationFilePath(user); - var path = user.ConfigurationFilePath; + await UserRepository.DeleteUser(user, CancellationToken.None).ConfigureAwait(false); try { - File.Delete(path); + File.Delete(configPath); } catch (IOException ex) { - _logger.ErrorException("Error deleting file {0}", ex, path); + _logger.ErrorException("Error deleting file {0}", ex, configPath); } DeleteUserPolicy(user); @@ -613,15 +665,6 @@ namespace MediaBrowser.Server.Implementations.Library }; } - public void UpdateConfiguration(User user, UserConfiguration newConfiguration) - { - var xmlPath = user.ConfigurationFilePath; - Directory.CreateDirectory(Path.GetDirectoryName(xmlPath)); - _xmlSerializer.SerializeToFile(newConfiguration, xmlPath); - - EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger); - } - private string PasswordResetFile { get { return Path.Combine(ConfigurationManager.ApplicationPaths.ProgramDataPath, "passwordreset.txt"); } @@ -689,7 +732,7 @@ namespace MediaBrowser.Server.Implementations.Library string pinFile = null; DateTime? expirationDate = null; - if (user != null && !user.Configuration.IsAdministrator) + if (user != null && !user.Policy.IsAdministrator) { action = ForgotPasswordAction.ContactAdmin; } @@ -784,28 +827,65 @@ namespace MediaBrowser.Server.Implementations.Library return (UserPolicy)_xmlSerializer.DeserializeFromFile(typeof(UserPolicy), path); } } + catch (DirectoryNotFoundException) + { + return GetDefaultPolicy(user); + } + catch (FileNotFoundException) + { + return GetDefaultPolicy(user); + } catch (Exception ex) { _logger.ErrorException("Error reading policy file: {0}", ex, path); - return new UserPolicy - { - EnableSync = !user.ConnectLinkType.HasValue || user.ConnectLinkType.Value != UserLinkType.Guest - }; + return GetDefaultPolicy(user); } } + private UserPolicy GetDefaultPolicy(User user) + { + return new UserPolicy + { + EnableSync = true + }; + } + private readonly object _policySyncLock = new object(); - public async Task UpdateUserPolicy(string userId, UserPolicy userPolicy) + public Task UpdateUserPolicy(string userId, UserPolicy userPolicy) { var user = GetUserById(userId); + return UpdateUserPolicy(user, userPolicy, true); + } + + private async Task UpdateUserPolicy(User user, UserPolicy userPolicy, bool fireEvent) + { + var updateConfig = user.Policy.IsAdministrator != userPolicy.IsAdministrator || + user.Policy.EnableLiveTvManagement != userPolicy.EnableLiveTvManagement || + user.Policy.EnableLiveTvAccess != userPolicy.EnableLiveTvAccess || + user.Policy.EnableMediaPlayback != userPolicy.EnableMediaPlayback || + user.Policy.EnableContentDeletion != userPolicy.EnableContentDeletion; + var path = GetPolifyFilePath(user); + Directory.CreateDirectory(Path.GetDirectoryName(path)); + lock (_policySyncLock) { _xmlSerializer.SerializeToFile(userPolicy, path); user.Policy = userPolicy; } + + if (updateConfig) + { + user.Configuration.IsAdministrator = user.Policy.IsAdministrator; + user.Configuration.EnableLiveTvManagement = user.Policy.EnableLiveTvManagement; + user.Configuration.EnableLiveTvAccess = user.Policy.EnableLiveTvAccess; + user.Configuration.EnableMediaPlayback = user.Policy.EnableMediaPlayback; + user.Configuration.EnableContentDeletion = user.Policy.EnableContentDeletion; + + await UpdateConfiguration(user, user.Configuration, true).ConfigureAwait(false); + } } private void DeleteUserPolicy(User user) @@ -833,5 +913,69 @@ namespace MediaBrowser.Server.Implementations.Library { return Path.Combine(user.ConfigurationDirectoryPath, "policy.xml"); } + + private string GetConfigurationFilePath(User user) + { + return Path.Combine(user.ConfigurationDirectoryPath, "config.xml"); + } + + public UserConfiguration GetUserConfiguration(User user) + { + var path = GetConfigurationFilePath(user); + + try + { + lock (_configSyncLock) + { + return (UserConfiguration)_xmlSerializer.DeserializeFromFile(typeof(UserConfiguration), path); + } + } + catch (DirectoryNotFoundException) + { + return new UserConfiguration(); + } + catch (FileNotFoundException) + { + return new UserConfiguration(); + } + catch (Exception ex) + { + _logger.ErrorException("Error reading policy file: {0}", ex, path); + + return new UserConfiguration(); + } + } + + private readonly object _configSyncLock = new object(); + public Task UpdateConfiguration(string userId, UserConfiguration config) + { + var user = GetUserById(userId); + return UpdateConfiguration(user, config, true); + } + + private async Task UpdateConfiguration(User user, UserConfiguration config, bool fireEvent) + { + var path = GetConfigurationFilePath(user); + + // The xml serializer will output differently if the type is not exact + if (config.GetType() != typeof (UserConfiguration)) + { + var json = _jsonSerializer.SerializeToString(config); + config = _jsonSerializer.DeserializeFromString<UserConfiguration>(json); + } + + Directory.CreateDirectory(Path.GetDirectoryName(path)); + + lock (_configSyncLock) + { + _xmlSerializer.SerializeToFile(config, path); + user.Configuration = config; + } + + if (fireEvent) + { + EventHelper.FireEventIfNotNull(UserConfigurationUpdated, this, new GenericEventArgs<User> { Argument = user }, _logger); + } + } } } |
