diff options
| author | LukePulverenti <luke.pulverenti@gmail.com> | 2013-02-20 20:33:05 -0500 |
|---|---|---|
| committer | LukePulverenti <luke.pulverenti@gmail.com> | 2013-02-20 20:33:05 -0500 |
| commit | 767cdc1f6f6a63ce997fc9476911e2c361f9d402 (patch) | |
| tree | 49add55976f895441167c66cfa95e5c7688d18ce /MediaBrowser.Controller/Entities | |
| parent | 845554722efaed872948a9e0f7202e3ef52f1b6e (diff) | |
Pushing missing changes
Diffstat (limited to 'MediaBrowser.Controller/Entities')
28 files changed, 4563 insertions, 1174 deletions
diff --git a/MediaBrowser.Controller/Entities/AggregateFolder.cs b/MediaBrowser.Controller/Entities/AggregateFolder.cs new file mode 100644 index 0000000000..c4fda4fa27 --- /dev/null +++ b/MediaBrowser.Controller/Entities/AggregateFolder.cs @@ -0,0 +1,68 @@ +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Specialized folder that can have items added to it's children by external entities. + /// Used for our RootFolder so plug-ins can add items. + /// </summary> + public class AggregateFolder : Folder + { + /// <summary> + /// The _virtual children + /// </summary> + private readonly ConcurrentBag<BaseItem> _virtualChildren = new ConcurrentBag<BaseItem>(); + + /// <summary> + /// Gets the virtual children. + /// </summary> + /// <value>The virtual children.</value> + public ConcurrentBag<BaseItem> VirtualChildren + { + get { return _virtualChildren; } + } + + /// <summary> + /// Adds the virtual child. + /// </summary> + /// <param name="child">The child.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddVirtualChild(BaseItem child) + { + if (child == null) + { + throw new ArgumentNullException(); + } + + _virtualChildren.Add(child); + } + + /// <summary> + /// Get the children of this folder from the actual file system + /// </summary> + /// <returns>IEnumerable{BaseItem}.</returns> + protected override IEnumerable<BaseItem> GetNonCachedChildren() + { + return base.GetNonCachedChildren().Concat(_virtualChildren); + } + + /// <summary> + /// Finds the virtual child. + /// </summary> + /// <param name="id">The id.</param> + /// <returns>BaseItem.</returns> + /// <exception cref="System.ArgumentNullException">id</exception> + public BaseItem FindVirtualChild(Guid id) + { + if (id == Guid.Empty) + { + throw new ArgumentNullException("id"); + } + + return _virtualChildren.FirstOrDefault(i => i.Id == id); + } + } +} diff --git a/MediaBrowser.Controller/Entities/Audio.cs b/MediaBrowser.Controller/Entities/Audio.cs deleted file mode 100644 index 61e901dd22..0000000000 --- a/MediaBrowser.Controller/Entities/Audio.cs +++ /dev/null @@ -1,14 +0,0 @@ -
-namespace MediaBrowser.Controller.Entities
-{
- public class Audio : BaseItem
- {
- public int BitRate { get; set; }
- public int Channels { get; set; }
- public int SampleRate { get; set; }
-
- public string Artist { get; set; }
- public string Album { get; set; }
- public string AlbumArtist { get; set; }
- }
-}
diff --git a/MediaBrowser.Controller/Entities/Audio/Audio.cs b/MediaBrowser.Controller/Entities/Audio/Audio.cs new file mode 100644 index 0000000000..511b589e53 --- /dev/null +++ b/MediaBrowser.Controller/Entities/Audio/Audio.cs @@ -0,0 +1,78 @@ +using MediaBrowser.Model.Entities; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace MediaBrowser.Controller.Entities.Audio +{ + /// <summary> + /// Class Audio + /// </summary> + public class Audio : BaseItem, IHasMediaStreams + { + /// <summary> + /// Gets or sets the media streams. + /// </summary> + /// <value>The media streams.</value> + public List<MediaStream> MediaStreams { get; set; } + + /// <summary> + /// Override this to true if class should be grouped under a container in indicies + /// The container class should be defined via IndexContainer + /// </summary> + /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool GroupInIndex + { + get + { + return true; + } + } + + /// <summary> + /// The unknown album + /// </summary> + private static readonly MusicAlbum UnknownAlbum = new MusicAlbum {Name = "<Unknown>"}; + /// <summary> + /// Override this to return the folder that should be used to construct a container + /// for this item in an index. GroupInIndex should be true as well. + /// </summary> + /// <value>The index container.</value> + [IgnoreDataMember] + public override Folder IndexContainer + { + get + { + return Parent is MusicAlbum ? Parent : Album != null ? new MusicAlbum {Name = Album, PrimaryImagePath = PrimaryImagePath } : UnknownAlbum; + } + } + + /// <summary> + /// Gets or sets the artist. + /// </summary> + /// <value>The artist.</value> + public string Artist { get; set; } + /// <summary> + /// Gets or sets the album. + /// </summary> + /// <value>The album.</value> + public string Album { get; set; } + /// <summary> + /// Gets or sets the album artist. + /// </summary> + /// <value>The album artist.</value> + public string AlbumArtist { get; set; } + + /// <summary> + /// Gets the type of the media. + /// </summary> + /// <value>The type of the media.</value> + public override string MediaType + { + get + { + return Model.Entities.MediaType.Audio; + } + } + } +} diff --git a/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs new file mode 100644 index 0000000000..9e4e3c5424 --- /dev/null +++ b/MediaBrowser.Controller/Entities/Audio/MusicAlbum.cs @@ -0,0 +1,133 @@ +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; + +namespace MediaBrowser.Controller.Entities.Audio +{ + /// <summary> + /// Class MusicAlbum + /// </summary> + public class MusicAlbum : Folder + { + /// <summary> + /// Songs will group into us so don't also include us in the index + /// </summary> + /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool IncludeInIndex + { + get + { + return false; + } + } + + /// <summary> + /// Override this to true if class should be grouped under a container in indicies + /// The container class should be defined via IndexContainer + /// </summary> + /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool GroupInIndex + { + get + { + return true; + } + } + + /// <summary> + /// The unknwon artist + /// </summary> + private static readonly MusicArtist UnknwonArtist = new MusicArtist {Name = "<Unknown>"}; + + /// <summary> + /// Override this to return the folder that should be used to construct a container + /// for this item in an index. GroupInIndex should be true as well. + /// </summary> + /// <value>The index container.</value> + [IgnoreDataMember] + public override Folder IndexContainer + { + get { return Parent as MusicArtist ?? UnknwonArtist; } + } + + /// <summary> + /// Override to point to first child (song) if not explicitly defined + /// </summary> + /// <value>The primary image path.</value> + [IgnoreDataMember] + public override string PrimaryImagePath + { + get + { + if (base.PrimaryImagePath == null) + { + var child = Children.FirstOrDefault(); + + return child == null ? base.PrimaryImagePath : child.PrimaryImagePath; + } + + return base.PrimaryImagePath; + } + set + { + base.PrimaryImagePath = value; + } + } + + /// <summary> + /// Override to point to first child (song) + /// </summary> + /// <value>The production year.</value> + public override int? ProductionYear + { + get + { + var child = Children.FirstOrDefault(); + + return child == null ? base.ProductionYear : child.ProductionYear; + } + set + { + base.ProductionYear = value; + } + } + + /// <summary> + /// Override to point to first child (song) + /// </summary> + /// <value>The genres.</value> + public override List<string> Genres + { + get + { + var child = Children.FirstOrDefault(); + + return child == null ? base.Genres : child.Genres; + } + set + { + base.Genres = value; + } + } + + /// <summary> + /// Override to point to first child (song) + /// </summary> + /// <value>The studios.</value> + public override List<string> Studios + { + get + { + var child = Children.FirstOrDefault(); + + return child == null ? base.Studios : child.Studios; + } + set + { + base.Studios = value; + } + } + } +} diff --git a/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs new file mode 100644 index 0000000000..b2fc04873f --- /dev/null +++ b/MediaBrowser.Controller/Entities/Audio/MusicArtist.cs @@ -0,0 +1,10 @@ + +namespace MediaBrowser.Controller.Entities.Audio +{ + /// <summary> + /// Class MusicArtist + /// </summary> + public class MusicArtist : Folder + { + } +} diff --git a/MediaBrowser.Controller/Entities/BaseEntity.cs b/MediaBrowser.Controller/Entities/BaseEntity.cs deleted file mode 100644 index 5b4a360c1f..0000000000 --- a/MediaBrowser.Controller/Entities/BaseEntity.cs +++ /dev/null @@ -1,94 +0,0 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.IO;
-using MediaBrowser.Controller.Providers;
-
-namespace MediaBrowser.Controller.Entities
-{
- /// <summary>
- /// Provides a base entity for all of our types
- /// </summary>
- public abstract class BaseEntity
- {
- public string Name { get; set; }
-
- public Guid Id { get; set; }
-
- public string Path { get; set; }
-
- public Folder Parent { get; set; }
-
- public string PrimaryImagePath { get; set; }
-
- public DateTime DateCreated { get; set; }
-
- public DateTime DateModified { get; set; }
-
- public override string ToString()
- {
- return Name;
- }
- protected Dictionary<Guid, BaseProviderInfo> _providerData;
- /// <summary>
- /// Holds persistent data for providers like last refresh date.
- /// Providers can use this to determine if they need to refresh.
- /// The BaseProviderInfo class can be extended to hold anything a provider may need.
- ///
- /// Keyed by a unique provider ID.
- /// </summary>
- public Dictionary<Guid, BaseProviderInfo> ProviderData
- {
- get
- {
- if (_providerData == null) _providerData = new Dictionary<Guid, BaseProviderInfo>();
- return _providerData;
- }
- set
- {
- _providerData = value;
- }
- }
-
- protected ItemResolveEventArgs _resolveArgs;
- /// <summary>
- /// We attach these to the item so that we only ever have to hit the file system once
- /// (this includes the children of the containing folder)
- /// Use ResolveArgs.FileSystemChildren to check for the existence of files instead of File.Exists
- /// </summary>
- public ItemResolveEventArgs ResolveArgs
- {
- get
- {
- if (_resolveArgs == null)
- {
- _resolveArgs = new ItemResolveEventArgs()
- {
- FileInfo = FileData.GetFileData(this.Path),
- Parent = this.Parent,
- Cancel = false,
- Path = this.Path
- };
- _resolveArgs = FileSystemHelper.FilterChildFileSystemEntries(_resolveArgs, (this.Parent != null && this.Parent.IsRoot));
- }
- return _resolveArgs;
- }
- set
- {
- _resolveArgs = value;
- }
- }
-
- /// <summary>
- /// Refresh metadata on us by execution our provider chain
- /// </summary>
- /// <returns>true if a provider reports we changed</returns>
- public bool RefreshMetadata()
- {
- Kernel.Instance.ExecuteMetadataProviders(this).ConfigureAwait(false);
- return true;
- }
-
- }
-}
diff --git a/MediaBrowser.Controller/Entities/BaseItem.cs b/MediaBrowser.Controller/Entities/BaseItem.cs index 4c9008b22c..e583e3a6a0 100644 --- a/MediaBrowser.Controller/Entities/BaseItem.cs +++ b/MediaBrowser.Controller/Entities/BaseItem.cs @@ -1,202 +1,1382 @@ -using MediaBrowser.Model.Entities;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Controller.IO;
-using System;
-using System.Threading.Tasks;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace MediaBrowser.Controller.Entities
-{
- public abstract class BaseItem : BaseEntity, IHasProviderIds
- {
-
- public IEnumerable<string> PhysicalLocations
- {
- get
- {
- return _resolveArgs.PhysicalLocations;
- }
- }
-
- public string SortName { get; set; }
-
- /// <summary>
- /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
- /// </summary>
- public DateTime? PremiereDate { get; set; }
-
- public string LogoImagePath { get; set; }
-
- public string ArtImagePath { get; set; }
-
- public string ThumbnailImagePath { get; set; }
-
- public string BannerImagePath { get; set; }
-
- public IEnumerable<string> BackdropImagePaths { get; set; }
-
- public string OfficialRating { get; set; }
-
- public string CustomRating { get; set; }
- public string CustomPin { get; set; }
-
- public string Language { get; set; }
- public string Overview { get; set; }
- public List<string> Taglines { get; set; }
-
- /// <summary>
- /// Using a Dictionary to prevent duplicates
- /// </summary>
- public Dictionary<string,PersonInfo> People { get; set; }
-
- public List<string> Studios { get; set; }
-
- public List<string> Genres { get; set; }
-
- public string DisplayMediaType { get; set; }
-
- public float? CommunityRating { get; set; }
- public long? RunTimeTicks { get; set; }
-
- public string AspectRatio { get; set; }
- public int? ProductionYear { get; set; }
-
- /// <summary>
- /// If the item is part of a series, this is it's number in the series.
- /// This could be episode number, album track number, etc.
- /// </summary>
- public int? IndexNumber { get; set; }
-
- /// <summary>
- /// For an episode this could be the season number, or for a song this could be the disc number.
- /// </summary>
- public int? ParentIndexNumber { get; set; }
-
- public IEnumerable<Video> LocalTrailers { get; set; }
-
- public string TrailerUrl { get; set; }
-
- public Dictionary<string, string> ProviderIds { get; set; }
-
- public Dictionary<Guid, UserItemData> UserData { get; set; }
-
- public UserItemData GetUserData(User user, bool createIfNull)
- {
- if (UserData == null || !UserData.ContainsKey(user.Id))
- {
- if (createIfNull)
- {
- AddUserData(user, new UserItemData());
- }
- else
- {
- return null;
- }
- }
-
- return UserData[user.Id];
- }
-
- private void AddUserData(User user, UserItemData data)
- {
- if (UserData == null)
- {
- UserData = new Dictionary<Guid, UserItemData>();
- }
-
- UserData[user.Id] = data;
- }
-
- /// <summary>
- /// Determines if a given user has access to this item
- /// </summary>
- internal bool IsParentalAllowed(User user)
- {
- return true;
- }
-
- /// <summary>
- /// Finds an item by ID, recursively
- /// </summary>
- public virtual BaseItem FindItemById(Guid id)
- {
- if (Id == id)
- {
- return this;
- }
-
- if (LocalTrailers != null)
- {
- return LocalTrailers.FirstOrDefault(i => i.Id == id);
- }
-
- return null;
- }
-
- public virtual bool IsFolder
- {
- get
- {
- return false;
- }
- }
-
- /// <summary>
- /// Determine if we have changed vs the passed in copy
- /// </summary>
- /// <param name="copy"></param>
- /// <returns></returns>
- public virtual bool IsChanged(BaseItem copy)
- {
- bool changed = copy.DateModified != this.DateModified;
- if (changed) MediaBrowser.Common.Logging.Logger.LogDebugInfo(this.Name + " changed - original creation: " + this.DateCreated + " new creation: " + copy.DateCreated + " original modified: " + this.DateModified + " new modified: " + copy.DateModified);
- return changed;
- }
-
- /// <summary>
- /// Determines if the item is considered new based on user settings
- /// </summary>
- public bool IsRecentlyAdded(User user)
- {
- return (DateTime.UtcNow - DateCreated).TotalDays < user.RecentItemDays;
- }
-
- public void AddPerson(PersonInfo person)
- {
- if (People == null)
- {
- People = new Dictionary<string, PersonInfo>(StringComparer.OrdinalIgnoreCase);
- }
-
- People[person.Name] = person;
- }
-
- /// <summary>
- /// Marks the item as either played or unplayed
- /// </summary>
- public virtual void SetPlayedStatus(User user, bool wasPlayed)
- {
- UserItemData data = GetUserData(user, true);
-
- if (wasPlayed)
- {
- data.PlayCount = Math.Max(data.PlayCount, 1);
- }
- else
- {
- data.PlayCount = 0;
- data.PlaybackPositionTicks = 0;
- }
- }
-
- /// <summary>
- /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
- /// </summary>
- /// <returns></returns>
- public virtual Task ChangedExternally()
- {
- return Task.Run(() => RefreshMetadata());
- }
- }
-}
+using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.IO; +using MediaBrowser.Common.Logging; +using MediaBrowser.Common.Win32; +using MediaBrowser.Controller.IO; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Localization; +using MediaBrowser.Controller.Providers; +using MediaBrowser.Controller.Resolvers; +using MediaBrowser.Model.Entities; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class BaseItem + /// </summary> + public abstract class BaseItem : IHasProviderIds + { + /// <summary> + /// The trailer folder name + /// </summary> + public const string TrailerFolderName = "trailers"; + + /// <summary> + /// Gets or sets the name. + /// </summary> + /// <value>The name.</value> + public virtual string Name { get; set; } + + /// <summary> + /// Gets or sets the id. + /// </summary> + /// <value>The id.</value> + public virtual Guid Id { get; set; } + + /// <summary> + /// Gets or sets the path. + /// </summary> + /// <value>The path.</value> + public virtual string Path { get; set; } + + /// <summary> + /// Gets or sets the type of the location. + /// </summary> + /// <value>The type of the location.</value> + public virtual LocationType LocationType + { + get + { + if (string.IsNullOrEmpty(Path)) + { + return LocationType.Virtual; + } + + return System.IO.Path.IsPathRooted(Path) ? LocationType.FileSystem : LocationType.Remote; + } + } + + /// <summary> + /// This is just a helper for convenience + /// </summary> + /// <value>The primary image path.</value> + [IgnoreDataMember] + public virtual string PrimaryImagePath + { + get { return GetImage(ImageType.Primary); } + set { SetImage(ImageType.Primary, value); } + } + + /// <summary> + /// Gets or sets the images. + /// </summary> + /// <value>The images.</value> + public Dictionary<string, string> Images { get; set; } + + /// <summary> + /// Gets or sets the date created. + /// </summary> + /// <value>The date created.</value> + public DateTime DateCreated { get; set; } + + /// <summary> + /// Gets or sets the date modified. + /// </summary> + /// <value>The date modified.</value> + public DateTime DateModified { get; set; } + + /// <summary> + /// Returns a <see cref="System.String" /> that represents this instance. + /// </summary> + /// <returns>A <see cref="System.String" /> that represents this instance.</returns> + public override string ToString() + { + return Name; + } + + /// <summary> + /// Returns true if this item should not attempt to fetch metadata + /// </summary> + /// <value><c>true</c> if [dont fetch meta]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public virtual bool DontFetchMeta + { + get + { + if (Path != null) + { + return Path.IndexOf("[dontfetchmeta]", StringComparison.OrdinalIgnoreCase) != -1; + } + + return false; + } + } + + /// <summary> + /// Determines whether the item has a saved local image of the specified name (jpg or png). + /// </summary> + /// <param name="name">The name.</param> + /// <returns><c>true</c> if [has local image] [the specified item]; otherwise, <c>false</c>.</returns> + /// <exception cref="System.ArgumentNullException">name</exception> + public bool HasLocalImage(string name) + { + if (string.IsNullOrEmpty(name)) + { + throw new ArgumentNullException("name"); + } + + return ResolveArgs.ContainsMetaFileByName(name + ".jpg") || + ResolveArgs.ContainsMetaFileByName(name + ".png"); + } + + /// <summary> + /// Should be overridden to return the proper folder where metadata lives + /// </summary> + /// <value>The meta location.</value> + [IgnoreDataMember] + public virtual string MetaLocation + { + get + { + return Path ?? ""; + } + } + + /// <summary> + /// The _provider data + /// </summary> + private Dictionary<Guid, BaseProviderInfo> _providerData; + /// <summary> + /// Holds persistent data for providers like last refresh date. + /// Providers can use this to determine if they need to refresh. + /// The BaseProviderInfo class can be extended to hold anything a provider may need. + /// Keyed by a unique provider ID. + /// </summary> + /// <value>The provider data.</value> + public Dictionary<Guid, BaseProviderInfo> ProviderData + { + get + { + return _providerData ?? (_providerData = new Dictionary<Guid, BaseProviderInfo>()); + } + set + { + _providerData = value; + } + } + + /// <summary> + /// The _file system stamp + /// </summary> + private Guid? _fileSystemStamp; + /// <summary> + /// Gets a directory stamp, in the form of a string, that can be used for + /// comparison purposes to determine if the file system entries for this item have changed. + /// </summary> + /// <value>The file system stamp.</value> + [IgnoreDataMember] + public Guid FileSystemStamp + { + get + { + if (!_fileSystemStamp.HasValue) + { + _fileSystemStamp = GetFileSystemStamp(); + } + + return _fileSystemStamp.Value; + } + } + + /// <summary> + /// Gets the type of the media. + /// </summary> + /// <value>The type of the media.</value> + [IgnoreDataMember] + public virtual string MediaType + { + get + { + return null; + } + } + + /// <summary> + /// Gets a directory stamp, in the form of a string, that can be used for + /// comparison purposes to determine if the file system entries for this item have changed. + /// </summary> + /// <returns>Guid.</returns> + private Guid GetFileSystemStamp() + { + // If there's no path or the item is a file, there's nothing to do + if (LocationType != LocationType.FileSystem || !ResolveArgs.IsDirectory) + { + return Guid.Empty; + } + + var sb = new StringBuilder(); + + // Record the name of each file + // Need to sort these because accoring to msdn docs, our i/o methods are not guaranteed in any order + foreach (var file in ResolveArgs.FileSystemChildren.OrderBy(f => f.cFileName)) + { + sb.Append(file.cFileName); + } + foreach (var file in ResolveArgs.MetadataFiles.OrderBy(f => f.cFileName)) + { + sb.Append(file.cFileName); + } + + return sb.ToString().GetMD5(); + } + + /// <summary> + /// The _resolve args + /// </summary> + private ItemResolveArgs _resolveArgs; + /// <summary> + /// The _resolve args initialized + /// </summary> + private bool _resolveArgsInitialized; + /// <summary> + /// The _resolve args sync lock + /// </summary> + private object _resolveArgsSyncLock = new object(); + /// <summary> + /// We attach these to the item so that we only ever have to hit the file system once + /// (this includes the children of the containing folder) + /// Use ResolveArgs.FileSystemDictionary to check for the existence of files instead of File.Exists + /// </summary> + /// <value>The resolve args.</value> + [IgnoreDataMember] + public ItemResolveArgs ResolveArgs + { + get + { + try + { + LazyInitializer.EnsureInitialized(ref _resolveArgs, ref _resolveArgsInitialized, ref _resolveArgsSyncLock, () => CreateResolveArgs()); + + } + catch (IOException ex) + { + Logger.LogException("Error creating resolve args for ", ex, Path); + + throw; + } + + return _resolveArgs; + } + set + { + _resolveArgs = value; + _resolveArgsInitialized = value != null; + + // Null this out so that it can be lazy loaded again + _fileSystemStamp = null; + } + } + + /// <summary> + /// Resets the resolve args. + /// </summary> + /// <param name="pathInfo">The path info.</param> + public void ResetResolveArgs(WIN32_FIND_DATA? pathInfo) + { + ResolveArgs = CreateResolveArgs(pathInfo); + } + + /// <summary> + /// Creates ResolveArgs on demand + /// </summary> + /// <param name="pathInfo">The path info.</param> + /// <returns>ItemResolveArgs.</returns> + /// <exception cref="System.IO.IOException">Unable to retrieve file system info for + path</exception> + protected internal virtual ItemResolveArgs CreateResolveArgs(WIN32_FIND_DATA? pathInfo = null) + { + var path = Path; + + // non file-system entries will not have a path + if (string.IsNullOrEmpty(path)) + { + return new ItemResolveArgs + { + FileInfo = new WIN32_FIND_DATA() + }; + } + + if (UseParentPathToCreateResolveArgs) + { + path = System.IO.Path.GetDirectoryName(path); + } + + pathInfo = pathInfo ?? FileSystem.GetFileData(path); + + if (!pathInfo.HasValue) + { + throw new IOException("Unable to retrieve file system info for " + path); + } + + var args = new ItemResolveArgs + { + FileInfo = pathInfo.Value, + Path = path, + Parent = Parent + }; + + // Gather child folder and files + + if (args.IsDirectory) + { + // When resolving the root, we need it's grandchildren (children of user views) + var flattenFolderDepth = args.IsPhysicalRoot ? 2 : 0; + + args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, flattenFolderDepth: flattenFolderDepth, args: args); + } + + //update our dates + EntityResolutionHelper.EnsureDates(this, args); + + return args; + } + + /// <summary> + /// Some subclasses will stop resolving at a directory and point their Path to a file within. This will help ensure the on-demand resolve args are identical to the + /// original ones. + /// </summary> + /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + protected virtual bool UseParentPathToCreateResolveArgs + { + get + { + return false; + } + } + + /// <summary> + /// Gets or sets the name of the sort. + /// </summary> + /// <value>The name of the sort.</value> + public string SortName { get; set; } + + /// <summary> + /// Gets or sets the parent. + /// </summary> + /// <value>The parent.</value> + [IgnoreDataMember] + public Folder Parent { get; set; } + + /// <summary> + /// Gets the collection folder parent. + /// </summary> + /// <value>The collection folder parent.</value> + [IgnoreDataMember] + public Folder CollectionFolder + { + get + { + if (this is AggregateFolder) + { + return null; + } + + if (IsFolder) + { + var iCollectionFolder = this as ICollectionFolder; + + if (iCollectionFolder != null) + { + return (Folder)this; + } + } + + var parent = Parent; + + while (parent != null) + { + var iCollectionFolder = parent as ICollectionFolder; + + if (iCollectionFolder != null) + { + return parent; + } + + parent = parent.Parent; + } + + return null; + } + } + + /// <summary> + /// When the item first debuted. For movies this could be premiere date, episodes would be first aired + /// </summary> + /// <value>The premiere date.</value> + public DateTime? PremiereDate { get; set; } + + /// <summary> + /// Gets or sets the display type of the media. + /// </summary> + /// <value>The display type of the media.</value> + public virtual string DisplayMediaType { get; set; } + + /// <summary> + /// Gets or sets the backdrop image paths. + /// </summary> + /// <value>The backdrop image paths.</value> + public List<string> BackdropImagePaths { get; set; } + + /// <summary> + /// Gets or sets the screenshot image paths. + /// </summary> + /// <value>The screenshot image paths.</value> + public List<string> ScreenshotImagePaths { get; set; } + + /// <summary> + /// Gets or sets the official rating. + /// </summary> + /// <value>The official rating.</value> + public string OfficialRating { get; set; } + + /// <summary> + /// Gets or sets the custom rating. + /// </summary> + /// <value>The custom rating.</value> + public string CustomRating { get; set; } + + /// <summary> + /// Gets or sets the language. + /// </summary> + /// <value>The language.</value> + public string Language { get; set; } + /// <summary> + /// Gets or sets the overview. + /// </summary> + /// <value>The overview.</value> + public string Overview { get; set; } + /// <summary> + /// Gets or sets the taglines. + /// </summary> + /// <value>The taglines.</value> + public List<string> Taglines { get; set; } + + /// <summary> + /// Gets or sets the people. + /// </summary> + /// <value>The people.</value> + public List<PersonInfo> People { get; set; } + + /// <summary> + /// Override this if you need to combine/collapse person information + /// </summary> + /// <value>All people.</value> + [IgnoreDataMember] + public virtual IEnumerable<PersonInfo> AllPeople + { + get { return People; } + } + + /// <summary> + /// Gets or sets the studios. + /// </summary> + /// <value>The studios.</value> + public virtual List<string> Studios { get; set; } + + /// <summary> + /// Gets or sets the genres. + /// </summary> + /// <value>The genres.</value> + public virtual List<string> Genres { get; set; } + + /// <summary> + /// Gets or sets the community rating. + /// </summary> + /// <value>The community rating.</value> + public float? CommunityRating { get; set; } + /// <summary> + /// Gets or sets the run time ticks. + /// </summary> + /// <value>The run time ticks.</value> + public long? RunTimeTicks { get; set; } + + /// <summary> + /// Gets or sets the aspect ratio. + /// </summary> + /// <value>The aspect ratio.</value> + public string AspectRatio { get; set; } + /// <summary> + /// Gets or sets the production year. + /// </summary> + /// <value>The production year.</value> + public virtual int? ProductionYear { get; set; } + + /// <summary> + /// If the item is part of a series, this is it's number in the series. + /// This could be episode number, album track number, etc. + /// </summary> + /// <value>The index number.</value> + public int? IndexNumber { get; set; } + + /// <summary> + /// For an episode this could be the season number, or for a song this could be the disc number. + /// </summary> + /// <value>The parent index number.</value> + public int? ParentIndexNumber { get; set; } + + /// <summary> + /// The _local trailers + /// </summary> + private List<Video> _localTrailers; + /// <summary> + /// The _local trailers initialized + /// </summary> + private bool _localTrailersInitialized; + /// <summary> + /// The _local trailers sync lock + /// </summary> + private object _localTrailersSyncLock = new object(); + /// <summary> + /// Gets the local trailers. + /// </summary> + /// <value>The local trailers.</value> + [IgnoreDataMember] + public List<Video> LocalTrailers + { + get + { + LazyInitializer.EnsureInitialized(ref _localTrailers, ref _localTrailersInitialized, ref _localTrailersSyncLock, LoadLocalTrailers); + return _localTrailers; + } + private set + { + _localTrailers = value; + + if (value == null) + { + _localTrailersInitialized = false; + } + } + } + + /// <summary> + /// Loads local trailers from the file system + /// </summary> + /// <returns>List{Video}.</returns> + private List<Video> LoadLocalTrailers() + { + ItemResolveArgs resolveArgs; + + try + { + resolveArgs = ResolveArgs; + } + catch (IOException ex) + { + Logger.LogException("Error getting ResolveArgs for {0}", ex, Path); + return new List<Video> { }; + } + + if (!resolveArgs.IsDirectory) + { + return new List<Video> { }; + } + + var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName); + + // Path doesn't exist. No biggie + if (folder == null) + { + return new List<Video> { }; + } + + IEnumerable<WIN32_FIND_DATA> files; + + try + { + files = FileSystem.GetFiles(folder.Value.Path); + } + catch (IOException ex) + { + Logger.LogException("Error loading trailers for {0}", ex, Name); + return new List<Video> { }; + } + + return Kernel.Instance.LibraryManager.GetItems<Video>(files, null).Select(video => + { + // Try to retrieve it from the db. If we don't find it, use the resolved version + var dbItem = Kernel.Instance.ItemRepository.RetrieveItem(video.Id) as Video; + + if (dbItem != null) + { + dbItem.ResolveArgs = video.ResolveArgs; + video = dbItem; + } + + return video; + }).ToList(); + } + + /// <summary> + /// Overrides the base implementation to refresh metadata for local trailers + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="forceSave">if set to <c>true</c> [is new item].</param> + /// <param name="forceRefresh">if set to <c>true</c> [force].</param> + /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param> + /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param> + /// <returns>true if a provider reports we changed</returns> + public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true) + { + if (resetResolveArgs) + { + ResolveArgs = null; + } + + // Lazy load these again + LocalTrailers = null; + + // Refresh for the item + var itemRefreshTask = Kernel.Instance.ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders); + + cancellationToken.ThrowIfCancellationRequested(); + + // Refresh metadata for local trailers + var trailerTasks = LocalTrailers.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders)); + + cancellationToken.ThrowIfCancellationRequested(); + + // Await the trailer tasks + await Task.WhenAll(trailerTasks).ConfigureAwait(false); + + cancellationToken.ThrowIfCancellationRequested(); + + // Get the result from the item task + var changed = await itemRefreshTask.ConfigureAwait(false); + + if (changed || forceSave) + { + cancellationToken.ThrowIfCancellationRequested(); + + await Kernel.Instance.ItemRepository.SaveItem(this, cancellationToken).ConfigureAwait(false); + } + + return changed; + } + + /// <summary> + /// Clear out all metadata properties. Extend for sub-classes. + /// </summary> + public virtual void ClearMetaValues() + { + Images = null; + SortName = null; + PremiereDate = null; + BackdropImagePaths = null; + OfficialRating = null; + CustomRating = null; + Overview = null; + Taglines = null; + Language = null; + Studios = null; + Genres = null; + CommunityRating = null; + RunTimeTicks = null; + AspectRatio = null; + ProductionYear = null; + ProviderIds = null; + DisplayMediaType = GetType().Name; + ResolveArgs = null; + } + + /// <summary> + /// Gets or sets the trailer URL. + /// </summary> + /// <value>The trailer URL.</value> + public List<string> TrailerUrls { get; set; } + + /// <summary> + /// Gets or sets the provider ids. + /// </summary> + /// <value>The provider ids.</value> + public Dictionary<string, string> ProviderIds { get; set; } + + /// <summary> + /// Override this to false if class should be ignored for indexing purposes + /// </summary> + /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public virtual bool IncludeInIndex + { + get { return true; } + } + + /// <summary> + /// Override this to true if class should be grouped under a container in indicies + /// The container class should be defined via IndexContainer + /// </summary> + /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public virtual bool GroupInIndex + { + get { return false; } + } + + /// <summary> + /// Override this to return the folder that should be used to construct a container + /// for this item in an index. GroupInIndex should be true as well. + /// </summary> + /// <value>The index container.</value> + [IgnoreDataMember] + public virtual Folder IndexContainer + { + get { return null; } + } + + /// <summary> + /// The _user data + /// </summary> + private IEnumerable<UserItemData> _userData; + /// <summary> + /// The _user data initialized + /// </summary> + private bool _userDataInitialized; + /// <summary> + /// The _user data sync lock + /// </summary> + private object _userDataSyncLock = new object(); + /// <summary> + /// Gets the user data. + /// </summary> + /// <value>The user data.</value> + [IgnoreDataMember] + public IEnumerable<UserItemData> UserData + { + get + { + // Call ToList to exhaust the stream because we'll be iterating over this multiple times + LazyInitializer.EnsureInitialized(ref _userData, ref _userDataInitialized, ref _userDataSyncLock, () => Kernel.Instance.UserDataRepository.RetrieveUserData(this).ToList()); + return _userData; + } + private set + { + _userData = value; + + if (value == null) + { + _userDataInitialized = false; + } + } + } + + /// <summary> + /// Gets the user data. + /// </summary> + /// <param name="user">The user.</param> + /// <param name="createIfNull">if set to <c>true</c> [create if null].</param> + /// <returns>UserItemData.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public UserItemData GetUserData(User user, bool createIfNull) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + if (UserData == null) + { + if (!createIfNull) + { + return null; + } + + AddOrUpdateUserData(user, new UserItemData { UserId = user.Id }); + } + + var data = UserData.FirstOrDefault(u => u.UserId == user.Id); + + if (data == null && createIfNull) + { + data = new UserItemData { UserId = user.Id }; + AddOrUpdateUserData(user, data); + } + + return data; + } + + /// <summary> + /// Adds the or update user data. + /// </summary> + /// <param name="user">The user.</param> + /// <param name="data">The data.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddOrUpdateUserData(User user, UserItemData data) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + if (data == null) + { + throw new ArgumentNullException(); + } + + data.UserId = user.Id; + + if (UserData == null) + { + UserData = new[] { data }; + } + else + { + var list = UserData.Where(u => u.UserId != user.Id).ToList(); + list.Add(data); + UserData = list; + } + } + + /// <summary> + /// The _user data id + /// </summary> + protected Guid _userDataId; //cache this so it doesn't have to be re-constructed on every reference + /// <summary> + /// Return the id that should be used to key user data for this item. + /// Default is just this Id but subclasses can use provider Ids for transportability. + /// </summary> + /// <value>The user data id.</value> + [IgnoreDataMember] + public virtual Guid UserDataId + { + get + { + return _userDataId == Guid.Empty ? (_userDataId = Id) : _userDataId; + } + } + + /// <summary> + /// Determines if a given user has access to this item + /// </summary> + /// <param name="user">The user.</param> + /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public bool IsParentalAllowed(User user) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + return user.Configuration.MaxParentalRating == null || Ratings.Level(CustomRating ?? OfficialRating) <= user.Configuration.MaxParentalRating; + } + + /// <summary> + /// Determines if this folder should be visible to a given user. + /// Default is just parental allowed. Can be overridden for more functionality. + /// </summary> + /// <param name="user">The user.</param> + /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns> + /// <exception cref="System.ArgumentNullException">user</exception> + public virtual bool IsVisible(User user) + { + if (user == null) + { + throw new ArgumentNullException("user"); + } + + return IsParentalAllowed(user); + } + + /// <summary> + /// Finds an item by ID, recursively + /// </summary> + /// <param name="id">The id.</param> + /// <param name="user">The user.</param> + /// <returns>BaseItem.</returns> + /// <exception cref="System.ArgumentNullException">id</exception> + public virtual BaseItem FindItemById(Guid id, User user) + { + if (id == Guid.Empty) + { + throw new ArgumentNullException("id"); + } + + if (Id == id) + { + return this; + } + + if (LocalTrailers != null) + { + return LocalTrailers.FirstOrDefault(i => i.Id == id); + } + + return null; + } + + /// <summary> + /// Finds the particular item by searching through our parents and, if not found there, loading from repo + /// </summary> + /// <param name="id">The id.</param> + /// <returns>BaseItem.</returns> + /// <exception cref="System.ArgumentException"></exception> + protected BaseItem FindParentItem(Guid id) + { + if (id == Guid.Empty) + { + throw new ArgumentException(); + } + + var parent = Parent; + while (parent != null && !parent.IsRoot) + { + if (parent.Id == id) return parent; + parent = parent.Parent; + } + + //not found - load from repo + return Kernel.Instance.ItemRepository.RetrieveItem(id); + } + + /// <summary> + /// Gets a value indicating whether this instance is folder. + /// </summary> + /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public virtual bool IsFolder + { + get + { + return false; + } + } + + /// <summary> + /// Determine if we have changed vs the passed in copy + /// </summary> + /// <param name="copy">The copy.</param> + /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public virtual bool HasChanged(BaseItem copy) + { + if (copy == null) + { + throw new ArgumentNullException(); + } + + var changed = copy.DateModified != DateModified; + if (changed) + { + Logger.LogDebugInfo(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified); + } + return changed; + } + + /// <summary> + /// Determines if the item is considered new based on user settings + /// </summary> + /// <param name="user">The user.</param> + /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public bool IsRecentlyAdded(User user) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + return (DateTime.UtcNow - DateCreated).TotalDays < Kernel.Instance.Configuration.RecentItemDays; + } + + /// <summary> + /// Determines if the item is considered recently played on user settings + /// </summary> + /// <param name="user">The user.</param> + /// <returns><c>true</c> if [is recently played] [the specified user]; otherwise, <c>false</c>.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public bool IsRecentlyPlayed(User user) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + var data = GetUserData(user, false); + + if (data == null || data.LastPlayedDate == null || data.PlayCount == 0) + { + return false; + } + + return (DateTime.UtcNow - data.LastPlayedDate.Value).TotalDays < Kernel.Instance.Configuration.RecentlyPlayedDays; + } + + /// <summary> + /// Adds people to the item + /// </summary> + /// <param name="people">The people.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddPeople(IEnumerable<PersonInfo> people) + { + if (people == null) + { + throw new ArgumentNullException(); + } + + foreach (var person in people) + { + AddPerson(person); + } + } + + /// <summary> + /// Adds a person to the item + /// </summary> + /// <param name="person">The person.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddPerson(PersonInfo person) + { + if (person == null) + { + throw new ArgumentNullException(); + } + + if (string.IsNullOrWhiteSpace(person.Name)) + { + throw new ArgumentNullException(); + } + + if (People == null) + { + People = new List<PersonInfo>(); + } + + // Check for dupes based on the combination of Name and Type + + if (!People.Any(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(person.Type, StringComparison.OrdinalIgnoreCase))) + { + People.Add(person); + } + } + + /// <summary> + /// Adds studios to the item + /// </summary> + /// <param name="studios">The studios.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddStudios(IEnumerable<string> studios) + { + if (studios == null) + { + throw new ArgumentNullException(); + } + + foreach (var name in studios) + { + AddStudio(name); + } + } + + /// <summary> + /// Adds a studio to the item + /// </summary> + /// <param name="name">The name.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddStudio(string name) + { + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentNullException(); + } + + if (Studios == null) + { + Studios = new List<string>(); + } + + if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase)) + { + Studios.Add(name); + } + } + + /// <summary> + /// Adds a tagline to the item + /// </summary> + /// <param name="name">The name.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddTagline(string name) + { + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentNullException(); + } + + if (Taglines == null) + { + Taglines = new List<string>(); + } + + if (!Taglines.Contains(name, StringComparer.OrdinalIgnoreCase)) + { + Taglines.Add(name); + } + } + + /// <summary> + /// Adds a TrailerUrl to the item + /// </summary> + /// <param name="url">The URL.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddTrailerUrl(string url) + { + if (string.IsNullOrWhiteSpace(url)) + { + throw new ArgumentNullException(); + } + + if (TrailerUrls == null) + { + TrailerUrls = new List<string>(); + } + + if (!TrailerUrls.Contains(url, StringComparer.OrdinalIgnoreCase)) + { + TrailerUrls.Add(url); + } + } + + /// <summary> + /// Adds a genre to the item + /// </summary> + /// <param name="name">The name.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddGenre(string name) + { + if (string.IsNullOrWhiteSpace(name)) + { + throw new ArgumentNullException(); + } + + if (Genres == null) + { + Genres = new List<string>(); + } + + if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase)) + { + Genres.Add(name); + } + } + + /// <summary> + /// Adds genres to the item + /// </summary> + /// <param name="genres">The genres.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddGenres(IEnumerable<string> genres) + { + if (genres == null) + { + throw new ArgumentNullException(); + } + + foreach (var name in genres) + { + AddGenre(name); + } + } + + /// <summary> + /// Marks the item as either played or unplayed + /// </summary> + /// <param name="user">The user.</param> + /// <param name="wasPlayed">if set to <c>true</c> [was played].</param> + /// <returns>Task.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public virtual Task SetPlayedStatus(User user, bool wasPlayed) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + var data = GetUserData(user, true); + + if (wasPlayed) + { + data.PlayCount = Math.Max(data.PlayCount, 1); + + if (!data.LastPlayedDate.HasValue) + { + data.LastPlayedDate = DateTime.UtcNow; + } + } + else + { + //I think it is okay to do this here. + // if this is only called when a user is manually forcing something to un-played + // then it probably is what we want to do... + data.PlayCount = 0; + data.PlaybackPositionTicks = 0; + data.LastPlayedDate = null; + } + + data.Played = wasPlayed; + + return Kernel.Instance.UserDataManager.SaveUserDataForItem(user, this, data); + } + + /// <summary> + /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed. + /// </summary> + /// <returns>Task.</returns> + public virtual Task ChangedExternally() + { + return RefreshMetadata(CancellationToken.None); + } + + /// <summary> + /// Finds a parent of a given type + /// </summary> + /// <typeparam name="T"></typeparam> + /// <returns>``0.</returns> + public T FindParent<T>() + where T : Folder + { + var parent = Parent; + + while (parent != null) + { + var result = parent as T; + if (result != null) + { + return result; + } + + parent = parent.Parent; + } + + return null; + } + + /// <summary> + /// Gets an image + /// </summary> + /// <param name="type">The type.</param> + /// <returns>System.String.</returns> + /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception> + public string GetImage(ImageType type) + { + if (type == ImageType.Backdrop) + { + throw new ArgumentException("Backdrops should be accessed using Item.Backdrops"); + } + if (type == ImageType.Screenshot) + { + throw new ArgumentException("Screenshots should be accessed using Item.Screenshots"); + } + + if (Images == null) + { + return null; + } + + string val; + Images.TryGetValue(type.ToString(), out val); + return val; + } + + /// <summary> + /// Gets an image + /// </summary> + /// <param name="type">The type.</param> + /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns> + /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception> + public bool HasImage(ImageType type) + { + if (type == ImageType.Backdrop) + { + throw new ArgumentException("Backdrops should be accessed using Item.Backdrops"); + } + if (type == ImageType.Screenshot) + { + throw new ArgumentException("Screenshots should be accessed using Item.Screenshots"); + } + + return !string.IsNullOrEmpty(GetImage(type)); + } + + /// <summary> + /// Sets an image + /// </summary> + /// <param name="type">The type.</param> + /// <param name="path">The path.</param> + /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception> + public void SetImage(ImageType type, string path) + { + if (type == ImageType.Backdrop) + { + throw new ArgumentException("Backdrops should be accessed using Item.Backdrops"); + } + if (type == ImageType.Screenshot) + { + throw new ArgumentException("Screenshots should be accessed using Item.Screenshots"); + } + + var typeKey = type.ToString(); + + // If it's null remove the key from the dictionary + if (string.IsNullOrEmpty(path)) + { + if (Images != null) + { + if (Images.ContainsKey(typeKey)) + { + Images.Remove(typeKey); + } + } + } + else + { + // Ensure it exists + if (Images == null) + { + Images = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); + } + + Images[typeKey] = path; + } + } + + /// <summary> + /// Deletes the image. + /// </summary> + /// <param name="type">The type.</param> + /// <returns>Task.</returns> + public async Task DeleteImage(ImageType type) + { + if (!HasImage(type)) + { + return; + } + + // Delete the source file + File.Delete(GetImage(type)); + + // Remove it from the item + SetImage(type, null); + + // Refresh metadata + await RefreshMetadata(CancellationToken.None).ConfigureAwait(false); + } + } +} diff --git a/MediaBrowser.Controller/Entities/BasePluginFolder.cs b/MediaBrowser.Controller/Entities/BasePluginFolder.cs new file mode 100644 index 0000000000..7cabcf9f01 --- /dev/null +++ b/MediaBrowser.Controller/Entities/BasePluginFolder.cs @@ -0,0 +1,49 @@ +using MediaBrowser.Common.Extensions; +using System; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Plugins derive from and export this class to create a folder that will appear in the root along + /// with all the other actual physical folders in the system. + /// </summary> + public abstract class BasePluginFolder : Folder, ICollectionFolder + { + /// <summary> + /// Gets or sets the id. + /// </summary> + /// <value>The id.</value> + public override Guid Id + { + get + { + // This doesn't get populated through the normal resolving process + if (base.Id == Guid.Empty) + { + base.Id = (Path ?? Name).GetMBId(GetType()); + } + return base.Id; + } + set + { + base.Id = value; + } + } + + /// <summary> + /// We don't resolve normally so need to fill this in + /// </summary> + public override string DisplayMediaType + { + get + { + return "CollectionFolder"; // Plug-in folders are collection folders + } + set + { + base.DisplayMediaType = value; + } + } + + } +} diff --git a/MediaBrowser.Controller/Entities/CollectionFolder.cs b/MediaBrowser.Controller/Entities/CollectionFolder.cs new file mode 100644 index 0000000000..5684f8e802 --- /dev/null +++ b/MediaBrowser.Controller/Entities/CollectionFolder.cs @@ -0,0 +1,100 @@ +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Logging; +using MediaBrowser.Model.Tasks; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Specialized Folder class that points to a subset of the physical folders in the system. + /// It is created from the user-specific folders within the system root + /// </summary> + public class CollectionFolder : Folder, ICollectionFolder + { + /// <summary> + /// Gets a value indicating whether this instance is virtual folder. + /// </summary> + /// <value><c>true</c> if this instance is virtual folder; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool IsVirtualFolder + { + get + { + return true; + } + } + + /// <summary> + /// Allow different display preferences for each collection folder + /// </summary> + /// <value>The display prefs id.</value> + public override Guid DisplayPrefsId + { + get + { + return Id; + } + } + + // Cache this since it will be used a lot + /// <summary> + /// The null task result + /// </summary> + private static readonly Task NullTaskResult = Task.FromResult<object>(null); + + /// <summary> + /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes + /// ***Currently does not contain logic to maintain items that are unavailable in the file system*** + /// </summary> + /// <param name="progress">The progress.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="recursive">if set to <c>true</c> [recursive].</param> + /// <returns>Task.</returns> + protected override Task ValidateChildrenInternal(IProgress<TaskProgress> progress, CancellationToken cancellationToken, bool? recursive = null) + { + //we don't directly validate our children + //but we do need to clear out the index cache... + IndexCache = new ConcurrentDictionary<string, List<BaseItem>>(StringComparer.OrdinalIgnoreCase); + + return NullTaskResult; + } + + /// <summary> + /// Our children are actually just references to the ones in the physical root... + /// </summary> + /// <value>The actual children.</value> + protected override ConcurrentBag<BaseItem> ActualChildren + { + get + { + IEnumerable<Guid> folderIds; + + try + { + // Accessing ResolveArgs could involve file system access + folderIds = ResolveArgs.PhysicalLocations.Select(f => (f.GetMBId(typeof(Folder)))); + } + catch (IOException ex) + { + Logger.LogException("Error creating FolderIds for {0}", ex, Path); + + folderIds = new Guid[] {}; + } + + var ourChildren = + Kernel.Instance.RootFolder.Children.OfType<Folder>() + .Where(i => folderIds.Contains(i.Id)) + .SelectMany(c => c.Children); + + return new ConcurrentBag<BaseItem>(ourChildren); + } + } + } +} diff --git a/MediaBrowser.Controller/Entities/Folder.cs b/MediaBrowser.Controller/Entities/Folder.cs index 07529c80f6..cef79fe560 100644 --- a/MediaBrowser.Controller/Entities/Folder.cs +++ b/MediaBrowser.Controller/Entities/Folder.cs @@ -1,619 +1,1047 @@ -using MediaBrowser.Model.Entities;
-using MediaBrowser.Controller.IO;
-using MediaBrowser.Controller.Library;
-using MediaBrowser.Common.Logging;
-using MediaBrowser.Controller.Resolvers;
-using System;
-using System.Threading.Tasks;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace MediaBrowser.Controller.Entities
-{
- public class Folder : BaseItem
- {
- #region Events
- /// <summary>
- /// Fires whenever a validation routine updates our children. The added and removed children are properties of the args.
- /// *** Will fire asynchronously. ***
- /// </summary>
- public event EventHandler<ChildrenChangedEventArgs> ChildrenChanged;
- protected void OnChildrenChanged(ChildrenChangedEventArgs args)
- {
- if (ChildrenChanged != null)
- {
- Task.Run( () =>
- {
- ChildrenChanged(this, args);
- Kernel.Instance.OnLibraryChanged(args);
- });
- }
- }
-
- #endregion
-
- public override bool IsFolder
- {
- get
- {
- return true;
- }
- }
-
- public bool IsRoot { get; set; }
-
- public bool IsVirtualFolder
- {
- get
- {
- return Parent != null && Parent.IsRoot;
- }
- }
- protected object childLock = new object();
- protected List<BaseItem> children;
- protected virtual List<BaseItem> ActualChildren
- {
- get
- {
- if (children == null)
- {
- LoadChildren();
- }
- return children;
- }
-
- set
- {
- children = value;
- }
- }
-
- /// <summary>
- /// thread-safe access to the actual children of this folder - without regard to user
- /// </summary>
- public IEnumerable<BaseItem> Children
- {
- get
- {
- lock (childLock)
- return ActualChildren.ToList();
- }
- }
-
- /// <summary>
- /// thread-safe access to all recursive children of this folder - without regard to user
- /// </summary>
- public IEnumerable<BaseItem> RecursiveChildren
- {
- get
- {
- foreach (var item in Children)
- {
- yield return item;
-
- var subFolder = item as Folder;
-
- if (subFolder != null)
- {
- foreach (var subitem in subFolder.RecursiveChildren)
- {
- yield return subitem;
- }
- }
- }
- }
- }
-
-
- /// <summary>
- /// Loads and validates our children
- /// </summary>
- protected virtual void LoadChildren()
- {
- //first - load our children from the repo
- lock (childLock)
- children = GetCachedChildren();
-
- //then kick off a validation against the actual file system
- Task.Run(() => ValidateChildren());
- }
-
- protected bool ChildrenValidating = false;
-
- /// <summary>
- /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes
- /// ***Currently does not contain logic to maintain items that are unavailable in the file system***
- /// </summary>
- /// <returns></returns>
- protected async virtual void ValidateChildren()
- {
- if (ChildrenValidating) return; //only ever want one of these going at once and don't want them to fire off in sequence so don't use lock
- ChildrenValidating = true;
- bool changed = false; //this will save us a little time at the end if nothing changes
- var changedArgs = new ChildrenChangedEventArgs(this);
- //get the current valid children from filesystem (or wherever)
- var nonCachedChildren = await GetNonCachedChildren();
- if (nonCachedChildren == null) return; //nothing to validate
- //build a dictionary of the current children we have now by Id so we can compare quickly and easily
- Dictionary<Guid, BaseItem> currentChildren;
- lock (childLock)
- currentChildren = ActualChildren.ToDictionary(i => i.Id);
-
- //create a list for our validated children
- var validChildren = new List<BaseItem>();
- //now traverse the valid children and find any changed or new items
- foreach (var child in nonCachedChildren)
- {
- BaseItem currentChild;
- currentChildren.TryGetValue(child.Id, out currentChild);
- if (currentChild == null)
- {
- //brand new item - needs to be added
- changed = true;
- changedArgs.ItemsAdded.Add(child);
- //refresh it
- child.RefreshMetadata();
- Logger.LogInfo("New Item Added to Library: ("+child.GetType().Name+") "+ child.Name + " (" + child.Path + ")");
- //save it in repo...
-
- //and add it to our valid children
- validChildren.Add(child);
- //fire an added event...?
- //if it is a folder we need to validate its children as well
- Folder folder = child as Folder;
- if (folder != null)
- {
- folder.ValidateChildren();
- //probably need to refresh too...
- }
- }
- else
- {
- //existing item - check if it has changed
- if (currentChild.IsChanged(child))
- {
- changed = true;
- //update resolve args and refresh meta
- // Note - we are refreshing the existing child instead of the newly found one so the "Except" operation below
- // will identify this item as the same one
- currentChild.ResolveArgs = child.ResolveArgs;
- currentChild.RefreshMetadata();
- Logger.LogInfo("Item Changed: ("+currentChild.GetType().Name+") "+ currentChild.Name + " (" + currentChild.Path + ")");
- //save it in repo...
- validChildren.Add(currentChild);
- }
- else
- {
- //current child that didn't change - just put it in the valid children
- validChildren.Add(currentChild);
- }
- }
- }
-
- //that's all the new and changed ones - now see if there are any that are missing
- changedArgs.ItemsRemoved = currentChildren.Values.Except(validChildren);
- changed |= changedArgs.ItemsRemoved != null;
-
- //now, if anything changed - replace our children
- if (changed)
- {
- if (changedArgs.ItemsRemoved != null) foreach (var item in changedArgs.ItemsRemoved) Logger.LogDebugInfo("** " + item.Name + " Removed from library.");
-
- lock (childLock)
- ActualChildren = validChildren;
- //and save children in repo...
-
- //and fire event
- this.OnChildrenChanged(changedArgs);
- }
- ChildrenValidating = false;
-
- }
-
- /// <summary>
- /// Get the children of this folder from the actual file system
- /// </summary>
- /// <returns></returns>
- protected async virtual Task<IEnumerable<BaseItem>> GetNonCachedChildren()
- {
- ItemResolveEventArgs args = new ItemResolveEventArgs()
- {
- FileInfo = FileData.GetFileData(this.Path),
- Parent = this.Parent,
- Cancel = false,
- Path = this.Path
- };
-
- // Gather child folder and files
- if (args.IsDirectory)
- {
- args.FileSystemChildren = FileData.GetFileSystemEntries(this.Path, "*").ToArray();
-
- bool isVirtualFolder = Parent != null && Parent.IsRoot;
- args = FileSystemHelper.FilterChildFileSystemEntries(args, isVirtualFolder);
- }
- else
- {
- Logger.LogError("Folder has a path that is not a directory: " + this.Path);
- return null;
- }
-
- if (!EntityResolutionHelper.ShouldResolvePathContents(args))
- {
- return null;
- }
- return (await Task.WhenAll<BaseItem>(GetChildren(args.FileSystemChildren)).ConfigureAwait(false))
- .Where(i => i != null).OrderBy(f =>
- {
- return string.IsNullOrEmpty(f.SortName) ? f.Name : f.SortName;
-
- });
-
- }
-
- /// <summary>
- /// Resolves a path into a BaseItem
- /// </summary>
- protected async Task<BaseItem> GetChild(string path, WIN32_FIND_DATA? fileInfo = null)
- {
- ItemResolveEventArgs args = new ItemResolveEventArgs()
- {
- FileInfo = fileInfo ?? FileData.GetFileData(path),
- Parent = this,
- Cancel = false,
- Path = path
- };
-
- args.FileSystemChildren = FileData.GetFileSystemEntries(path, "*").ToArray();
- args = FileSystemHelper.FilterChildFileSystemEntries(args, false);
-
- return Kernel.Instance.ResolveItem(args);
-
- }
-
- /// <summary>
- /// Finds child BaseItems for us
- /// </summary>
- protected Task<BaseItem>[] GetChildren(WIN32_FIND_DATA[] fileSystemChildren)
- {
- Task<BaseItem>[] tasks = new Task<BaseItem>[fileSystemChildren.Length];
-
- for (int i = 0; i < fileSystemChildren.Length; i++)
- {
- var child = fileSystemChildren[i];
-
- tasks[i] = GetChild(child.Path, child);
- }
-
- return tasks;
- }
-
-
- /// <summary>
- /// Get our children from the repo - stubbed for now
- /// </summary>
- /// <returns></returns>
- protected virtual List<BaseItem> GetCachedChildren()
- {
- return new List<BaseItem>();
- }
-
- /// <summary>
- /// Gets allowed children of an item
- /// </summary>
- public IEnumerable<BaseItem> GetChildren(User user)
- {
- lock(childLock)
- return ActualChildren.Where(c => c.IsParentalAllowed(user));
- }
-
- /// <summary>
- /// Gets allowed recursive children of an item
- /// </summary>
- public IEnumerable<BaseItem> GetRecursiveChildren(User user)
- {
- foreach (var item in GetChildren(user))
- {
- yield return item;
-
- var subFolder = item as Folder;
-
- if (subFolder != null)
- {
- foreach (var subitem in subFolder.GetRecursiveChildren(user))
- {
- yield return subitem;
- }
- }
- }
- }
-
- /// <summary>
- /// Folders need to validate and refresh
- /// </summary>
- /// <returns></returns>
- public override Task ChangedExternally()
- {
- return Task.Run(() =>
- {
- if (this.IsRoot)
- {
- Kernel.Instance.ReloadRoot().ConfigureAwait(false);
- }
- else
- {
- RefreshMetadata();
- ValidateChildren();
- }
- });
- }
-
- /// <summary>
- /// Since it can be slow to make all of these calculations at once, this method will provide a way to get them all back together
- /// </summary>
- public ItemSpecialCounts GetSpecialCounts(User user)
- {
- var counts = new ItemSpecialCounts();
-
- IEnumerable<BaseItem> recursiveChildren = GetRecursiveChildren(user);
-
- var recentlyAddedItems = GetRecentlyAddedItems(recursiveChildren, user);
-
- counts.RecentlyAddedItemCount = recentlyAddedItems.Count;
- counts.RecentlyAddedUnPlayedItemCount = GetRecentlyAddedUnplayedItems(recentlyAddedItems, user).Count;
- counts.InProgressItemCount = GetInProgressItems(recursiveChildren, user).Count;
- counts.PlayedPercentage = GetPlayedPercentage(recursiveChildren, user);
-
- return counts;
- }
-
- /// <summary>
- /// Finds all recursive items within a top-level parent that contain the given genre and are allowed for the current user
- /// </summary>
- public IEnumerable<BaseItem> GetItemsWithGenre(string genre, User user)
- {
- return GetRecursiveChildren(user).Where(f => f.Genres != null && f.Genres.Any(s => s.Equals(genre, StringComparison.OrdinalIgnoreCase)));
- }
-
- /// <summary>
- /// Finds all recursive items within a top-level parent that contain the given year and are allowed for the current user
- /// </summary>
- public IEnumerable<BaseItem> GetItemsWithYear(int year, User user)
- {
- return GetRecursiveChildren(user).Where(f => f.ProductionYear.HasValue && f.ProductionYear == year);
- }
-
- /// <summary>
- /// Finds all recursive items within a top-level parent that contain the given studio and are allowed for the current user
- /// </summary>
- public IEnumerable<BaseItem> GetItemsWithStudio(string studio, User user)
- {
- return GetRecursiveChildren(user).Where(f => f.Studios != null && f.Studios.Any(s => s.Equals(studio, StringComparison.OrdinalIgnoreCase)));
- }
-
- /// <summary>
- /// Finds all recursive items within a top-level parent that the user has marked as a favorite
- /// </summary>
- public IEnumerable<BaseItem> GetFavoriteItems(User user)
- {
- return GetRecursiveChildren(user).Where(c =>
- {
- UserItemData data = c.GetUserData(user, false);
-
- if (data != null)
- {
- return data.IsFavorite;
- }
-
- return false;
- });
- }
-
- /// <summary>
- /// Finds all recursive items within a top-level parent that contain the given person and are allowed for the current user
- /// </summary>
- public IEnumerable<BaseItem> GetItemsWithPerson(string person, User user)
- {
- return GetRecursiveChildren(user).Where(c =>
- {
- if (c.People != null)
- {
- return c.People.ContainsKey(person);
- }
-
- return false;
- });
- }
-
- /// <summary>
- /// Finds all recursive items within a top-level parent that contain the given person and are allowed for the current user
- /// </summary>
- /// <param name="personType">Specify this to limit results to a specific PersonType</param>
- public IEnumerable<BaseItem> GetItemsWithPerson(string person, string personType, User user)
- {
- return GetRecursiveChildren(user).Where(c =>
- {
- if (c.People != null)
- {
- return c.People.ContainsKey(person) && c.People[person].Type.Equals(personType, StringComparison.OrdinalIgnoreCase);
- }
-
- return false;
- });
- }
-
- /// <summary>
- /// Gets all recently added items (recursive) within a folder, based on configuration and parental settings
- /// </summary>
- public List<BaseItem> GetRecentlyAddedItems(User user)
- {
- return GetRecentlyAddedItems(GetRecursiveChildren(user), user);
- }
-
- /// <summary>
- /// Gets all recently added unplayed items (recursive) within a folder, based on configuration and parental settings
- /// </summary>
- public List<BaseItem> GetRecentlyAddedUnplayedItems(User user)
- {
- return GetRecentlyAddedUnplayedItems(GetRecursiveChildren(user), user);
- }
-
- /// <summary>
- /// Gets all in-progress items (recursive) within a folder
- /// </summary>
- public List<BaseItem> GetInProgressItems(User user)
- {
- return GetInProgressItems(GetRecursiveChildren(user), user);
- }
-
- /// <summary>
- /// Takes a list of items and returns the ones that are recently added
- /// </summary>
- private static List<BaseItem> GetRecentlyAddedItems(IEnumerable<BaseItem> itemSet, User user)
- {
- var list = new List<BaseItem>();
-
- foreach (var item in itemSet)
- {
- if (!item.IsFolder && item.IsRecentlyAdded(user))
- {
- list.Add(item);
- }
- }
-
- return list;
- }
-
- /// <summary>
- /// Takes a list of items and returns the ones that are recently added and unplayed
- /// </summary>
- private static List<BaseItem> GetRecentlyAddedUnplayedItems(IEnumerable<BaseItem> itemSet, User user)
- {
- var list = new List<BaseItem>();
-
- foreach (var item in itemSet)
- {
- if (!item.IsFolder && item.IsRecentlyAdded(user))
- {
- var userdata = item.GetUserData(user, false);
-
- if (userdata == null || userdata.PlayCount == 0)
- {
- list.Add(item);
- }
- }
- }
-
- return list;
- }
-
- /// <summary>
- /// Takes a list of items and returns the ones that are in progress
- /// </summary>
- private static List<BaseItem> GetInProgressItems(IEnumerable<BaseItem> itemSet, User user)
- {
- var list = new List<BaseItem>();
-
- foreach (var item in itemSet)
- {
- if (!item.IsFolder)
- {
- var userdata = item.GetUserData(user, false);
-
- if (userdata != null && userdata.PlaybackPositionTicks > 0)
- {
- list.Add(item);
- }
- }
- }
-
- return list;
- }
-
- /// <summary>
- /// Gets the total played percentage for a set of items
- /// </summary>
- private static decimal GetPlayedPercentage(IEnumerable<BaseItem> itemSet, User user)
- {
- itemSet = itemSet.Where(i => !(i.IsFolder));
-
- decimal totalPercent = 0;
-
- int count = 0;
-
- foreach (BaseItem item in itemSet)
- {
- count++;
-
- UserItemData data = item.GetUserData(user, false);
-
- if (data == null)
- {
- continue;
- }
-
- if (data.PlayCount > 0)
- {
- totalPercent += 100;
- }
- else if (data.PlaybackPositionTicks > 0 && item.RunTimeTicks.HasValue)
- {
- decimal itemPercent = data.PlaybackPositionTicks;
- itemPercent /= item.RunTimeTicks.Value;
- totalPercent += itemPercent;
- }
- }
-
- if (count == 0)
- {
- return 0;
- }
-
- return totalPercent / count;
- }
-
- /// <summary>
- /// Marks the item as either played or unplayed
- /// </summary>
- public override void SetPlayedStatus(User user, bool wasPlayed)
- {
- base.SetPlayedStatus(user, wasPlayed);
-
- // Now sweep through recursively and update status
- foreach (BaseItem item in GetChildren(user))
- {
- item.SetPlayedStatus(user, wasPlayed);
- }
- }
-
- /// <summary>
- /// Finds an item by ID, recursively
- /// </summary>
- public override BaseItem FindItemById(Guid id)
- {
- var result = base.FindItemById(id);
-
- if (result != null)
- {
- return result;
- }
-
- //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
- return RecursiveChildren.FirstOrDefault(i => i.Id == id);
- }
-
- /// <summary>
- /// Finds an item by path, recursively
- /// </summary>
- public BaseItem FindByPath(string path)
- {
- if (PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase))
- {
- return this;
- }
-
- //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy
- return RecursiveChildren.FirstOrDefault(i => i.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase));
- }
- }
-}
+using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Logging; +using MediaBrowser.Common.Win32; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Localization; +using MediaBrowser.Controller.Resolvers; +using MediaBrowser.Controller.Sorting; +using MediaBrowser.Model.Entities; +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Threading; +using System.Threading.Tasks; +using MediaBrowser.Model.Tasks; +using SortOrder = MediaBrowser.Controller.Sorting.SortOrder; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class Folder + /// </summary> + public class Folder : BaseItem + { + /// <summary> + /// Gets a value indicating whether this instance is folder. + /// </summary> + /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool IsFolder + { + get + { + return true; + } + } + + /// <summary> + /// Gets or sets a value indicating whether this instance is physical root. + /// </summary> + /// <value><c>true</c> if this instance is physical root; otherwise, <c>false</c>.</value> + public bool IsPhysicalRoot { get; set; } + /// <summary> + /// Gets or sets a value indicating whether this instance is root. + /// </summary> + /// <value><c>true</c> if this instance is root; otherwise, <c>false</c>.</value> + public bool IsRoot { get; set; } + + /// <summary> + /// Gets a value indicating whether this instance is virtual folder. + /// </summary> + /// <value><c>true</c> if this instance is virtual folder; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public virtual bool IsVirtualFolder + { + get + { + return false; + } + } + + /// <summary> + /// Return the id that should be used to key display prefs for this item. + /// Default is based on the type for everything except actual generic folders. + /// </summary> + /// <value>The display prefs id.</value> + [IgnoreDataMember] + public virtual Guid DisplayPrefsId + { + get + { + var thisType = GetType(); + return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5(); + } + } + + /// <summary> + /// The _display prefs + /// </summary> + private IEnumerable<DisplayPreferences> _displayPrefs; + /// <summary> + /// The _display prefs initialized + /// </summary> + private bool _displayPrefsInitialized; + /// <summary> + /// The _display prefs sync lock + /// </summary> + private object _displayPrefsSyncLock = new object(); + /// <summary> + /// Gets the display prefs. + /// </summary> + /// <value>The display prefs.</value> + [IgnoreDataMember] + public IEnumerable<DisplayPreferences> DisplayPrefs + { + get + { + // Call ToList to exhaust the stream because we'll be iterating over this multiple times + LazyInitializer.EnsureInitialized(ref _displayPrefs, ref _displayPrefsInitialized, ref _displayPrefsSyncLock, () => Kernel.Instance.DisplayPreferencesRepository.RetrieveDisplayPrefs(this).ToList()); + return _displayPrefs; + } + private set + { + _displayPrefs = value; + + if (value == null) + { + _displayPrefsInitialized = false; + } + } + } + + /// <summary> + /// Gets the display prefs. + /// </summary> + /// <param name="user">The user.</param> + /// <param name="createIfNull">if set to <c>true</c> [create if null].</param> + /// <returns>DisplayPreferences.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public DisplayPreferences GetDisplayPrefs(User user, bool createIfNull) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + if (DisplayPrefs == null) + { + if (!createIfNull) + { + return null; + } + + AddOrUpdateDisplayPrefs(user, new DisplayPreferences { UserId = user.Id }); + } + + var data = DisplayPrefs.FirstOrDefault(u => u.UserId == user.Id); + + if (data == null && createIfNull) + { + data = new DisplayPreferences { UserId = user.Id }; + AddOrUpdateDisplayPrefs(user, data); + } + + return data; + } + + /// <summary> + /// Adds the or update display prefs. + /// </summary> + /// <param name="user">The user.</param> + /// <param name="data">The data.</param> + /// <exception cref="System.ArgumentNullException"></exception> + public void AddOrUpdateDisplayPrefs(User user, DisplayPreferences data) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + if (data == null) + { + throw new ArgumentNullException(); + } + + data.UserId = user.Id; + + if (DisplayPrefs == null) + { + DisplayPrefs = new[] { data }; + } + else + { + var list = DisplayPrefs.Where(u => u.UserId != user.Id).ToList(); + list.Add(data); + DisplayPrefs = list; + } + } + + #region Sorting + + /// <summary> + /// The _sort by options + /// </summary> + private Dictionary<string, IComparer<BaseItem>> _sortByOptions; + /// <summary> + /// Dictionary of sort options - consists of a display value (localized) and an IComparer of BaseItem + /// </summary> + /// <value>The sort by options.</value> + [IgnoreDataMember] + public Dictionary<string, IComparer<BaseItem>> SortByOptions + { + get { return _sortByOptions ?? (_sortByOptions = GetSortByOptions()); } + } + + /// <summary> + /// Returns the valid set of sort by options for this folder type. + /// Override or extend to modify. + /// </summary> + /// <returns>Dictionary{System.StringIComparer{BaseItem}}.</returns> + protected virtual Dictionary<string, IComparer<BaseItem>> GetSortByOptions() + { + return new Dictionary<string, IComparer<BaseItem>> { + {LocalizedStrings.Instance.GetString("NameDispPref"), new BaseItemComparer(SortOrder.Name)}, + {LocalizedStrings.Instance.GetString("DateDispPref"), new BaseItemComparer(SortOrder.Date)}, + {LocalizedStrings.Instance.GetString("RatingDispPref"), new BaseItemComparer(SortOrder.Rating)}, + {LocalizedStrings.Instance.GetString("RuntimeDispPref"), new BaseItemComparer(SortOrder.Runtime)}, + {LocalizedStrings.Instance.GetString("YearDispPref"), new BaseItemComparer(SortOrder.Year)} + }; + + } + + /// <summary> + /// Get a sorting comparer by name + /// </summary> + /// <param name="name">The name.</param> + /// <returns>IComparer{BaseItem}.</returns> + private IComparer<BaseItem> GetSortingFunction(string name) + { + IComparer<BaseItem> sorting; + SortByOptions.TryGetValue(name ?? "", out sorting); + return sorting ?? new BaseItemComparer(SortOrder.Name); + } + + /// <summary> + /// Get the list of sort by choices for this folder (localized). + /// </summary> + /// <value>The sort by option strings.</value> + [IgnoreDataMember] + public IEnumerable<string> SortByOptionStrings + { + get { return SortByOptions.Keys; } + } + + #endregion + + #region Indexing + + /// <summary> + /// The _index by options + /// </summary> + private Dictionary<string, Func<User, IEnumerable<BaseItem>>> _indexByOptions; + /// <summary> + /// Dictionary of index options - consists of a display value and an indexing function + /// which takes User as a parameter and returns an IEnum of BaseItem + /// </summary> + /// <value>The index by options.</value> + [IgnoreDataMember] + public Dictionary<string, Func<User, IEnumerable<BaseItem>>> IndexByOptions + { + get { return _indexByOptions ?? (_indexByOptions = GetIndexByOptions()); } + } + + /// <summary> + /// Returns the valid set of index by options for this folder type. + /// Override or extend to modify. + /// </summary> + /// <returns>Dictionary{System.StringFunc{UserIEnumerable{BaseItem}}}.</returns> + protected virtual Dictionary<string, Func<User, IEnumerable<BaseItem>>> GetIndexByOptions() + { + return new Dictionary<string, Func<User, IEnumerable<BaseItem>>> { + {LocalizedStrings.Instance.GetString("NoneDispPref"), null}, + {LocalizedStrings.Instance.GetString("PerformerDispPref"), GetIndexByPerformer}, + {LocalizedStrings.Instance.GetString("GenreDispPref"), GetIndexByGenre}, + {LocalizedStrings.Instance.GetString("DirectorDispPref"), GetIndexByDirector}, + {LocalizedStrings.Instance.GetString("YearDispPref"), GetIndexByYear}, + {LocalizedStrings.Instance.GetString("OfficialRatingDispPref"), null}, + {LocalizedStrings.Instance.GetString("StudioDispPref"), GetIndexByStudio} + }; + + } + + /// <summary> + /// Gets the index by actor. + /// </summary> + /// <param name="user">The user.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + protected IEnumerable<BaseItem> GetIndexByPerformer(User user) + { + return GetIndexByPerson(user, new List<string> { PersonType.Actor, PersonType.MusicArtist }, LocalizedStrings.Instance.GetString("PerformerDispPref")); + } + + /// <summary> + /// Gets the index by director. + /// </summary> + /// <param name="user">The user.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + protected IEnumerable<BaseItem> GetIndexByDirector(User user) + { + return GetIndexByPerson(user, new List<string> { PersonType.Director }, LocalizedStrings.Instance.GetString("DirectorDispPref")); + } + + /// <summary> + /// Gets the index by person. + /// </summary> + /// <param name="user">The user.</param> + /// <param name="personTypes">The person types we should match on</param> + /// <param name="indexName">Name of the index.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + protected IEnumerable<BaseItem> GetIndexByPerson(User user, List<string> personTypes, string indexName) + { + + // Even though this implementation means multiple iterations over the target list - it allows us to defer + // the retrieval of the individual children for each index value until they are requested. + using (new Profiler(indexName + " Index Build for " + Name)) + { + // Put this in a local variable to avoid an implicitly captured closure + var currentIndexName = indexName; + + var us = this; + var candidates = RecursiveChildren.Where(i => i.IncludeInIndex && i.AllPeople != null).ToList(); + + return candidates.AsParallel().SelectMany(i => i.AllPeople.Where(p => personTypes.Contains(p.Type)) + .Select(a => a.Name)) + .Distinct() + .Select(i => + { + try + { + return Kernel.Instance.LibraryManager.GetPerson(i).Result; + } + catch (IOException ex) + { + Logger.LogException("Error getting person {0}", ex, i); + return null; + } + catch (AggregateException ex) + { + Logger.LogException("Error getting person {0}", ex, i); + return null; + } + }) + .Where(i => i != null) + .Select(a => new IndexFolder(us, a, + candidates.Where(i => i.AllPeople.Any(p => personTypes.Contains(p.Type) && p.Name.Equals(a.Name, StringComparison.OrdinalIgnoreCase)) + ), currentIndexName)); + + } + } + + /// <summary> + /// Gets the index by studio. + /// </summary> + /// <param name="user">The user.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + protected IEnumerable<BaseItem> GetIndexByStudio(User user) + { + // Even though this implementation means multiple iterations over the target list - it allows us to defer + // the retrieval of the individual children for each index value until they are requested. + using (new Profiler("Studio Index Build for " + Name)) + { + var indexName = LocalizedStrings.Instance.GetString("StudioDispPref"); + + var candidates = RecursiveChildren.Where(i => i.IncludeInIndex && i.Studios != null).ToList(); + + return candidates.AsParallel().SelectMany(i => i.Studios) + .Distinct() + .Select(i => + { + try + { + return Kernel.Instance.LibraryManager.GetStudio(i).Result; + } + catch (IOException ex) + { + Logger.LogException("Error getting studio {0}", ex, i); + return null; + } + catch (AggregateException ex) + { + Logger.LogException("Error getting studio {0}", ex, i); + return null; + } + }) + .Where(i => i != null) + .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.Studios.Any(s => s.Equals(ndx.Name, StringComparison.OrdinalIgnoreCase))), indexName)); + } + } + + /// <summary> + /// Gets the index by genre. + /// </summary> + /// <param name="user">The user.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + protected IEnumerable<BaseItem> GetIndexByGenre(User user) + { + // Even though this implementation means multiple iterations over the target list - it allows us to defer + // the retrieval of the individual children for each index value until they are requested. + using (new Profiler("Genre Index Build for " + Name)) + { + var indexName = LocalizedStrings.Instance.GetString("GenreDispPref"); + + //we need a copy of this so we don't double-recurse + var candidates = RecursiveChildren.Where(i => i.IncludeInIndex && i.Genres != null).ToList(); + + return candidates.AsParallel().SelectMany(i => i.Genres) + .Distinct() + .Select(i => + { + try + { + return Kernel.Instance.LibraryManager.GetGenre(i).Result; + } + catch (IOException ex) + { + Logger.LogException("Error getting genre {0}", ex, i); + return null; + } + catch (AggregateException ex) + { + Logger.LogException("Error getting genre {0}", ex, i); + return null; + } + }) + .Where(i => i != null) + .Select(genre => new IndexFolder(this, genre, candidates.Where(i => i.Genres.Any(g => g.Equals(genre.Name, StringComparison.OrdinalIgnoreCase))), indexName) + ); + } + } + + /// <summary> + /// Gets the index by year. + /// </summary> + /// <param name="user">The user.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + protected IEnumerable<BaseItem> GetIndexByYear(User user) + { + // Even though this implementation means multiple iterations over the target list - it allows us to defer + // the retrieval of the individual children for each index value until they are requested. + using (new Profiler("Production Year Index Build for " + Name)) + { + var indexName = LocalizedStrings.Instance.GetString("YearDispPref"); + + //we need a copy of this so we don't double-recurse + var candidates = RecursiveChildren.Where(i => i.IncludeInIndex && i.ProductionYear.HasValue).ToList(); + + return candidates.AsParallel().Select(i => i.ProductionYear.Value) + .Distinct() + .Select(i => + { + try + { + return Kernel.Instance.LibraryManager.GetYear(i).Result; + } + catch (IOException ex) + { + Logger.LogException("Error getting year {0}", ex, i); + return null; + } + catch (AggregateException ex) + { + Logger.LogException("Error getting year {0}", ex, i); + return null; + } + }) + .Where(i => i != null) + + .Select(ndx => new IndexFolder(this, ndx, candidates.Where(i => i.ProductionYear == int.Parse(ndx.Name)), indexName)); + + } + } + + /// <summary> + /// Returns the indexed children for this user from the cache. Caches them if not already there. + /// </summary> + /// <param name="user">The user.</param> + /// <param name="indexBy">The index by.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + private IEnumerable<BaseItem> GetIndexedChildren(User user, string indexBy) + { + List<BaseItem> result; + var cacheKey = user.Name + indexBy; + IndexCache.TryGetValue(cacheKey, out result); + + if (result == null) + { + //not cached - cache it + Func<User, IEnumerable<BaseItem>> indexing; + IndexByOptions.TryGetValue(indexBy, out indexing); + result = BuildIndex(indexBy, indexing, user); + } + return result; + } + + /// <summary> + /// Get the list of indexy by choices for this folder (localized). + /// </summary> + /// <value>The index by option strings.</value> + [IgnoreDataMember] + public IEnumerable<string> IndexByOptionStrings + { + get { return IndexByOptions.Keys; } + } + + /// <summary> + /// The index cache + /// </summary> + protected ConcurrentDictionary<string, List<BaseItem>> IndexCache = new ConcurrentDictionary<string, List<BaseItem>>(StringComparer.OrdinalIgnoreCase); + + /// <summary> + /// Builds the index. + /// </summary> + /// <param name="indexKey">The index key.</param> + /// <param name="indexFunction">The index function.</param> + /// <param name="user">The user.</param> + /// <returns>List{BaseItem}.</returns> + protected virtual List<BaseItem> BuildIndex(string indexKey, Func<User, IEnumerable<BaseItem>> indexFunction, User user) + { + return indexFunction != null + ? IndexCache[user.Name + indexKey] = indexFunction(user).ToList() + : null; + } + + #endregion + + /// <summary> + /// The children + /// </summary> + private ConcurrentBag<BaseItem> _children; + /// <summary> + /// The _children initialized + /// </summary> + private bool _childrenInitialized; + /// <summary> + /// The _children sync lock + /// </summary> + private object _childrenSyncLock = new object(); + /// <summary> + /// Gets or sets the actual children. + /// </summary> + /// <value>The actual children.</value> + protected virtual ConcurrentBag<BaseItem> ActualChildren + { + get + { + LazyInitializer.EnsureInitialized(ref _children, ref _childrenInitialized, ref _childrenSyncLock, LoadChildren); + return _children; + } + private set + { + _children = value; + + if (value == null) + { + _childrenInitialized = false; + } + } + } + + /// <summary> + /// thread-safe access to the actual children of this folder - without regard to user + /// </summary> + /// <value>The children.</value> + [IgnoreDataMember] + public ConcurrentBag<BaseItem> Children + { + get + { + return ActualChildren; + } + } + + /// <summary> + /// thread-safe access to all recursive children of this folder - without regard to user + /// </summary> + /// <value>The recursive children.</value> + [IgnoreDataMember] + public IEnumerable<BaseItem> RecursiveChildren + { + get + { + foreach (var item in Children) + { + yield return item; + + if (item.IsFolder) + { + var subFolder = (Folder)item; + + foreach (var subitem in subFolder.RecursiveChildren) + { + yield return subitem; + } + } + } + } + } + + + /// <summary> + /// Loads our children. Validation will occur externally. + /// We want this sychronous. + /// </summary> + /// <returns>ConcurrentBag{BaseItem}.</returns> + protected virtual ConcurrentBag<BaseItem> LoadChildren() + { + //just load our children from the repo - the library will be validated and maintained in other processes + return new ConcurrentBag<BaseItem>(GetCachedChildren()); + } + + /// <summary> + /// Gets or sets the current validation cancellation token source. + /// </summary> + /// <value>The current validation cancellation token source.</value> + private CancellationTokenSource CurrentValidationCancellationTokenSource { get; set; } + + /// <summary> + /// Validates that the children of the folder still exist + /// </summary> + /// <param name="progress">The progress.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="recursive">if set to <c>true</c> [recursive].</param> + /// <returns>Task.</returns> + public async Task ValidateChildren(IProgress<TaskProgress> progress, CancellationToken cancellationToken, bool? recursive = null) + { + cancellationToken.ThrowIfCancellationRequested(); + + // Cancel the current validation, if any + if (CurrentValidationCancellationTokenSource != null) + { + CurrentValidationCancellationTokenSource.Cancel(); + } + + // Create an inner cancellation token. This can cancel all validations from this level on down, + // but nothing above this + var innerCancellationTokenSource = new CancellationTokenSource(); + + try + { + CurrentValidationCancellationTokenSource = innerCancellationTokenSource; + + var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(innerCancellationTokenSource.Token, cancellationToken); + + await ValidateChildrenInternal(progress, linkedCancellationTokenSource.Token, recursive).ConfigureAwait(false); + } + catch (OperationCanceledException ex) + { + Logger.LogInfo("ValidateChildren cancelled for " + Name); + + // If the outer cancelletion token in the cause for the cancellation, throw it + if (cancellationToken.IsCancellationRequested && ex.CancellationToken == cancellationToken) + { + throw; + } + } + finally + { + // Null out the token source + if (CurrentValidationCancellationTokenSource == innerCancellationTokenSource) + { + CurrentValidationCancellationTokenSource = null; + } + + innerCancellationTokenSource.Dispose(); + } + } + + /// <summary> + /// Compare our current children (presumably just read from the repo) with the current state of the file system and adjust for any changes + /// ***Currently does not contain logic to maintain items that are unavailable in the file system*** + /// </summary> + /// <param name="progress">The progress.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="recursive">if set to <c>true</c> [recursive].</param> + /// <returns>Task.</returns> + protected async virtual Task ValidateChildrenInternal(IProgress<TaskProgress> progress, CancellationToken cancellationToken, bool? recursive = null) + { + // Nothing to do here + if (LocationType != LocationType.FileSystem) + { + return; + } + + cancellationToken.ThrowIfCancellationRequested(); + + var changedArgs = new ChildrenChangedEventArgs(this); + + //get the current valid children from filesystem (or wherever) + var nonCachedChildren = GetNonCachedChildren(); + + if (nonCachedChildren == null) return; //nothing to validate + + progress.Report(new TaskProgress { PercentComplete = 5 }); + + //build a dictionary of the current children we have now by Id so we can compare quickly and easily + var currentChildren = ActualChildren.ToDictionary(i => i.Id); + + //create a list for our validated children + var validChildren = new ConcurrentBag<Tuple<BaseItem, bool>>(); + + cancellationToken.ThrowIfCancellationRequested(); + + Parallel.ForEach(nonCachedChildren, child => + { + BaseItem currentChild; + + if (currentChildren.TryGetValue(child.Id, out currentChild)) + { + currentChild.ResolveArgs = child.ResolveArgs; + + //existing item - check if it has changed + if (currentChild.HasChanged(child)) + { + EntityResolutionHelper.EnsureDates(currentChild, child.ResolveArgs); + + changedArgs.AddUpdatedItem(currentChild); + validChildren.Add(new Tuple<BaseItem, bool>(currentChild, true)); + } + else + { + validChildren.Add(new Tuple<BaseItem, bool>(currentChild, false)); + } + } + else + { + //brand new item - needs to be added + changedArgs.AddNewItem(child); + + validChildren.Add(new Tuple<BaseItem, bool>(child, true)); + } + }); + + // If any items were added or removed.... + if (!changedArgs.ItemsAdded.IsEmpty || currentChildren.Count != validChildren.Count) + { + var newChildren = validChildren.Select(c => c.Item1).ToList(); + + //that's all the new and changed ones - now see if there are any that are missing + changedArgs.ItemsRemoved = currentChildren.Values.Except(newChildren).ToList(); + + foreach (var item in changedArgs.ItemsRemoved) + { + Logger.LogInfo("** " + item.Name + " Removed from library."); + } + + var childrenReplaced = false; + + if (changedArgs.ItemsRemoved.Count > 0) + { + ActualChildren = new ConcurrentBag<BaseItem>(newChildren); + childrenReplaced = true; + } + + var saveTasks = new List<Task>(); + + foreach (var item in changedArgs.ItemsAdded) + { + Logger.LogInfo("** " + item.Name + " Added to library."); + + if (!childrenReplaced) + { + _children.Add(item); + } + + saveTasks.Add(Kernel.Instance.ItemRepository.SaveItem(item, CancellationToken.None)); + } + + await Task.WhenAll(saveTasks).ConfigureAwait(false); + + //and save children in repo... + Logger.LogInfo("*** Saving " + newChildren.Count + " children for " + Name); + await Kernel.Instance.ItemRepository.SaveChildren(Id, newChildren, CancellationToken.None).ConfigureAwait(false); + } + + if (changedArgs.HasChange) + { + //force the indexes to rebuild next time + IndexCache.Clear(); + + //and fire event + Kernel.Instance.LibraryManager.OnLibraryChanged(changedArgs); + } + + progress.Report(new TaskProgress { PercentComplete = 15 }); + + cancellationToken.ThrowIfCancellationRequested(); + + await RefreshChildren(validChildren, progress, cancellationToken, recursive).ConfigureAwait(false); + + progress.Report(new TaskProgress { PercentComplete = 100 }); + } + + /// <summary> + /// Refreshes the children. + /// </summary> + /// <param name="children">The children.</param> + /// <param name="progress">The progress.</param> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="recursive">if set to <c>true</c> [recursive].</param> + /// <returns>Task.</returns> + private Task RefreshChildren(IEnumerable<Tuple<BaseItem, bool>> children, IProgress<TaskProgress> progress, CancellationToken cancellationToken, bool? recursive) + { + var numComplete = 0; + + var list = children.ToList(); + + var tasks = list.Select(tuple => Task.Run(async () => + { + cancellationToken.ThrowIfCancellationRequested(); + + var child = tuple.Item1; + + //refresh it + await child.RefreshMetadata(cancellationToken, resetResolveArgs: child.IsFolder).ConfigureAwait(false); + + //and add it to our valid children + //fire an added event...? + //if it is a folder we need to validate its children as well + + // Refresh children if a folder and the item changed or recursive is set to true + var refreshChildren = child.IsFolder && (tuple.Item2 || (recursive.HasValue && recursive.Value)); + + if (refreshChildren) + { + // Don't refresh children if explicitly set to false + if (recursive.HasValue && recursive.Value == false) + { + refreshChildren = false; + } + } + + if (refreshChildren) + { + cancellationToken.ThrowIfCancellationRequested(); + + await ((Folder)child).ValidateChildren(new Progress<TaskProgress> { }, cancellationToken, recursive: recursive).ConfigureAwait(false); + } + + lock (progress) + { + numComplete++; + + double percent = numComplete; + percent /= list.Count; + + progress.Report(new TaskProgress { PercentComplete = (85 * percent) + 15 }); + } + })); + + cancellationToken.ThrowIfCancellationRequested(); + + return Task.WhenAll(tasks); + } + + /// <summary> + /// Get the children of this folder from the actual file system + /// </summary> + /// <returns>IEnumerable{BaseItem}.</returns> + protected virtual IEnumerable<BaseItem> GetNonCachedChildren() + { + IEnumerable<WIN32_FIND_DATA> fileSystemChildren; + + try + { + fileSystemChildren = ResolveArgs.FileSystemChildren; + } + catch (IOException ex) + { + Logger.LogException("Error getting ResolveArgs for {0}", ex, Path); + return new List<BaseItem> { }; + } + + return Kernel.Instance.LibraryManager.GetItems<BaseItem>(fileSystemChildren, this); + } + + /// <summary> + /// Get our children from the repo - stubbed for now + /// </summary> + /// <returns>IEnumerable{BaseItem}.</returns> + protected virtual IEnumerable<BaseItem> GetCachedChildren() + { + return Kernel.Instance.ItemRepository.RetrieveChildren(this); + } + + /// <summary> + /// Gets allowed children of an item + /// </summary> + /// <param name="user">The user.</param> + /// <param name="indexBy">The index by.</param> + /// <param name="sortBy">The sort by.</param> + /// <param name="sortOrder">The sort order.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public virtual IEnumerable<BaseItem> GetChildren(User user, string indexBy = null, string sortBy = null, Model.Entities.SortOrder? sortOrder = null) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + //the true root should return our users root folder children + if (IsPhysicalRoot) return user.RootFolder.GetChildren(user, indexBy, sortBy, sortOrder); + + IEnumerable<BaseItem> result = null; + + if (!string.IsNullOrEmpty(indexBy)) + { + result = GetIndexedChildren(user, indexBy); + } + + // If indexed is false or the indexing function is null + if (result == null) + { + result = ActualChildren.Where(c => c.IsVisible(user)); + } + + if (string.IsNullOrEmpty(sortBy)) + { + return result; + } + + return sortOrder.HasValue && sortOrder.Value == Model.Entities.SortOrder.Descending + ? result.OrderByDescending(i => i, GetSortingFunction(sortBy)) + : result.OrderBy(i => i, GetSortingFunction(sortBy)); + } + + /// <summary> + /// Gets allowed recursive children of an item + /// </summary> + /// <param name="user">The user.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public IEnumerable<BaseItem> GetRecursiveChildren(User user) + { + if (user == null) + { + throw new ArgumentNullException(); + } + + foreach (var item in GetChildren(user)) + { + yield return item; + + var subFolder = item as Folder; + + if (subFolder != null) + { + foreach (var subitem in subFolder.GetRecursiveChildren(user)) + { + yield return subitem; + } + } + } + } + + /// <summary> + /// Folders need to validate and refresh + /// </summary> + /// <returns>Task.</returns> + public override async Task ChangedExternally() + { + await base.ChangedExternally().ConfigureAwait(false); + + var progress = new Progress<TaskProgress> { }; + + await ValidateChildren(progress, CancellationToken.None).ConfigureAwait(false); + } + + /// <summary> + /// Marks the item as either played or unplayed + /// </summary> + /// <param name="user">The user.</param> + /// <param name="wasPlayed">if set to <c>true</c> [was played].</param> + /// <returns>Task.</returns> + public override async Task SetPlayedStatus(User user, bool wasPlayed) + { + await base.SetPlayedStatus(user, wasPlayed).ConfigureAwait(false); + + // Now sweep through recursively and update status + var tasks = GetChildren(user).Select(c => c.SetPlayedStatus(user, wasPlayed)); + + await Task.WhenAll(tasks).ConfigureAwait(false); + } + + /// <summary> + /// Finds an item by ID, recursively + /// </summary> + /// <param name="id">The id.</param> + /// <param name="user">The user.</param> + /// <returns>BaseItem.</returns> + public override BaseItem FindItemById(Guid id, User user) + { + var result = base.FindItemById(id, user); + + if (result != null) + { + return result; + } + + var children = user == null ? ActualChildren : GetChildren(user); + + foreach (var child in children) + { + result = child.FindItemById(id, user); + + if (result != null) + { + return result; + } + } + + return null; + } + + /// <summary> + /// Finds an item by path, recursively + /// </summary> + /// <param name="path">The path.</param> + /// <returns>BaseItem.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public BaseItem FindByPath(string path) + { + if (string.IsNullOrEmpty(path)) + { + throw new ArgumentNullException(); + } + + try + { + if (ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase)) + { + return this; + } + } + catch (IOException ex) + { + Logger.LogException("Error getting ResolveArgs for {0}", ex, Path); + } + + //this should be functionally equivilent to what was here since it is IEnum and works on a thread-safe copy + return RecursiveChildren.FirstOrDefault(i => + { + try + { + return i.ResolveArgs.PhysicalLocations.Contains(path, StringComparer.OrdinalIgnoreCase); + } + catch (IOException ex) + { + Logger.LogException("Error getting ResolveArgs for {0}", ex, Path); + return false; + } + }); + } + } +} diff --git a/MediaBrowser.Controller/Entities/Genre.cs b/MediaBrowser.Controller/Entities/Genre.cs index ba343a2bc6..d5e8afb202 100644 --- a/MediaBrowser.Controller/Entities/Genre.cs +++ b/MediaBrowser.Controller/Entities/Genre.cs @@ -1,7 +1,10 @@ -
-namespace MediaBrowser.Controller.Entities
-{
- public class Genre : BaseEntity
- {
- }
-}
+ +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class Genre + /// </summary> + public class Genre : BaseItem + { + } +} diff --git a/MediaBrowser.Controller/Entities/ICollectionFolder.cs b/MediaBrowser.Controller/Entities/ICollectionFolder.cs new file mode 100644 index 0000000000..4ea531331e --- /dev/null +++ b/MediaBrowser.Controller/Entities/ICollectionFolder.cs @@ -0,0 +1,10 @@ + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// This is just a marker interface to denote top level folders + /// </summary> + public interface ICollectionFolder + { + } +} diff --git a/MediaBrowser.Controller/Entities/ISupportsSpecialFeatures.cs b/MediaBrowser.Controller/Entities/ISupportsSpecialFeatures.cs new file mode 100644 index 0000000000..9b52c2f7fc --- /dev/null +++ b/MediaBrowser.Controller/Entities/ISupportsSpecialFeatures.cs @@ -0,0 +1,105 @@ +using MediaBrowser.Common.IO; +using MediaBrowser.Common.Logging; +using MediaBrowser.Common.Win32; +using MediaBrowser.Controller.Library; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Allows some code sharing between entities that support special features + /// </summary> + public interface ISupportsSpecialFeatures + { + /// <summary> + /// Gets the path. + /// </summary> + /// <value>The path.</value> + string Path { get; } + + /// <summary> + /// Gets the name. + /// </summary> + /// <value>The name.</value> + string Name { get; } + + /// <summary> + /// Gets the resolve args. + /// </summary> + /// <value>The resolve args.</value> + ItemResolveArgs ResolveArgs { get; } + + /// <summary> + /// Gets the special features. + /// </summary> + /// <value>The special features.</value> + List<Video> SpecialFeatures { get; } + } + + /// <summary> + /// Class SpecialFeatures + /// </summary> + public static class SpecialFeatures + { + /// <summary> + /// Loads special features from the file system + /// </summary> + /// <param name="entity">The entity.</param> + /// <returns>List{Video}.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + public static IEnumerable<Video> LoadSpecialFeatures(ISupportsSpecialFeatures entity) + { + if (entity == null) + { + throw new ArgumentNullException(); + } + + WIN32_FIND_DATA? folder; + + try + { + folder = entity.ResolveArgs.GetFileSystemEntryByName("specials"); + } + catch (IOException ex) + { + Logger.LogException("Error getting ResolveArgs for {0}", ex, entity.Path); + return new List<Video> { }; + } + + // Path doesn't exist. No biggie + if (folder == null) + { + return new List<Video> {}; + } + + IEnumerable<WIN32_FIND_DATA> files; + + try + { + files = FileSystem.GetFiles(folder.Value.Path); + } + catch (IOException ex) + { + Logger.LogException("Error loading trailers for {0}", ex, entity.Name); + return new List<Video> { }; + } + + return Kernel.Instance.LibraryManager.GetItems<Video>(files, null).Select(video => + { + // Try to retrieve it from the db. If we don't find it, use the resolved version + var dbItem = Kernel.Instance.ItemRepository.RetrieveItem(video.Id) as Video; + + if (dbItem != null) + { + dbItem.ResolveArgs = video.ResolveArgs; + video = dbItem; + } + + return video; + }); + } + } +} diff --git a/MediaBrowser.Controller/Entities/IndexFolder.cs b/MediaBrowser.Controller/Entities/IndexFolder.cs new file mode 100644 index 0000000000..013db48536 --- /dev/null +++ b/MediaBrowser.Controller/Entities/IndexFolder.cs @@ -0,0 +1,204 @@ +using MediaBrowser.Common.Extensions; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class IndexFolder + /// </summary> + public class IndexFolder : Folder + { + /// <summary> + /// Initializes a new instance of the <see cref="IndexFolder" /> class. + /// </summary> + /// <param name="parent">The parent.</param> + /// <param name="shadow">The shadow.</param> + /// <param name="children">The children.</param> + /// <param name="indexName">Name of the index.</param> + /// <param name="groupContents">if set to <c>true</c> [group contents].</param> + public IndexFolder(Folder parent, BaseItem shadow, IEnumerable<BaseItem> children, string indexName, bool groupContents = true) + { + ChildSource = children; + ShadowItem = shadow; + GroupContents = groupContents; + if (shadow == null) + { + Name = SortName = "<Unknown>"; + } + else + { + SetShadowValues(); + } + Id = (parent.Id.ToString() + Name).GetMBId(typeof(IndexFolder)); + + IndexName = indexName; + Parent = parent; + } + + /// <summary> + /// Resets the parent. + /// </summary> + /// <param name="parent">The parent.</param> + public void ResetParent(Folder parent) + { + Parent = parent; + Id = (parent.Id.ToString() + Name).GetMBId(typeof(IndexFolder)); + } + + /// <summary> + /// Override this to true if class should be grouped under a container in indicies + /// The container class should be defined via IndexContainer + /// </summary> + /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool GroupInIndex + { + get + { + return ShadowItem != null && ShadowItem.GroupInIndex; + } + } + + /// <summary> + /// Override this to return the folder that should be used to construct a container + /// for this item in an index. GroupInIndex should be true as well. + /// </summary> + /// <value>The index container.</value> + [IgnoreDataMember] + public override Folder IndexContainer + { + get { return ShadowItem != null ? ShadowItem.IndexContainer : new IndexFolder(this, null, null, "<Unknown>", false); } + } + + /// <summary> + /// Gets or sets a value indicating whether [group contents]. + /// </summary> + /// <value><c>true</c> if [group contents]; otherwise, <c>false</c>.</value> + protected bool GroupContents { get; set; } + /// <summary> + /// Gets or sets the child source. + /// </summary> + /// <value>The child source.</value> + protected IEnumerable<BaseItem> ChildSource { get; set; } + /// <summary> + /// Gets or sets our children. + /// </summary> + /// <value>Our children.</value> + protected ConcurrentBag<BaseItem> OurChildren { get; set; } + /// <summary> + /// Gets the name of the index. + /// </summary> + /// <value>The name of the index.</value> + public string IndexName { get; private set; } + + /// <summary> + /// Override to return the children defined to us when we were created + /// </summary> + /// <value>The actual children.</value> + protected override ConcurrentBag<BaseItem> LoadChildren() + { + var originalChildSource = ChildSource.ToList(); + + var kids = originalChildSource; + if (GroupContents) + { + // Recursively group up the chain + var group = true; + var isSubsequentLoop = false; + + while (group) + { + kids = isSubsequentLoop || kids.Any(i => i.GroupInIndex) + ? GroupedSource(kids).ToList() + : originalChildSource; + + group = kids.Any(i => i.GroupInIndex); + isSubsequentLoop = true; + } + } + + // Now - since we built the index grouping from the bottom up - we now need to properly set Parents from the top down + SetParents(this, kids.OfType<IndexFolder>()); + + return new ConcurrentBag<BaseItem>(kids); + } + + /// <summary> + /// Sets the parents. + /// </summary> + /// <param name="parent">The parent.</param> + /// <param name="kids">The kids.</param> + private void SetParents(Folder parent, IEnumerable<IndexFolder> kids) + { + foreach (var child in kids) + { + child.ResetParent(parent); + child.SetParents(child, child.Children.OfType<IndexFolder>()); + } + } + + /// <summary> + /// Groupeds the source. + /// </summary> + /// <param name="source">The source.</param> + /// <returns>IEnumerable{BaseItem}.</returns> + protected IEnumerable<BaseItem> GroupedSource(IEnumerable<BaseItem> source) + { + return source.GroupBy(i => i.IndexContainer).Select(container => new IndexFolder(this, container.Key, container, null, false)); + } + + /// <summary> + /// The item we are shadowing as a folder (Genre, Actor, etc.) + /// We inherit the images and other meta from this item + /// </summary> + /// <value>The shadow item.</value> + protected BaseItem ShadowItem { get; set; } + + /// <summary> + /// Sets the shadow values. + /// </summary> + protected void SetShadowValues() + { + if (ShadowItem != null) + { + Name = ShadowItem.Name; + SortName = ShadowItem.SortName; + Genres = ShadowItem.Genres; + Studios = ShadowItem.Studios; + OfficialRating = ShadowItem.OfficialRating; + BackdropImagePaths = ShadowItem.BackdropImagePaths; + Images = ShadowItem.Images; + Overview = ShadowItem.Overview; + DisplayMediaType = ShadowItem.GetType().Name; + } + } + + /// <summary> + /// Overrides the base implementation to refresh metadata for local trailers + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="forceSave">if set to <c>true</c> [is new item].</param> + /// <param name="forceRefresh">if set to <c>true</c> [force].</param> + /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param> + /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param> + /// <returns>Task{System.Boolean}.</returns> + public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true) + { + if (ShadowItem != null) + { + var changed = await ShadowItem.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false); + + cancellationToken.ThrowIfCancellationRequested(); + + SetShadowValues(); + return changed; + } + return false; + } + } +} diff --git a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs index cb841530ee..34f09b4b09 100644 --- a/MediaBrowser.Controller/Entities/Movies/BoxSet.cs +++ b/MediaBrowser.Controller/Entities/Movies/BoxSet.cs @@ -1,7 +1,11 @@ -
-namespace MediaBrowser.Controller.Entities.Movies
-{
- public class BoxSet : Folder
- {
- }
-}
+ +namespace MediaBrowser.Controller.Entities.Movies +{ + /// <summary> + /// Class BoxSet + /// </summary> + public class BoxSet : Folder + { + + } +} diff --git a/MediaBrowser.Controller/Entities/Movies/Movie.cs b/MediaBrowser.Controller/Entities/Movies/Movie.cs index 2d98fa06e8..114e10d37a 100644 --- a/MediaBrowser.Controller/Entities/Movies/Movie.cs +++ b/MediaBrowser.Controller/Entities/Movies/Movie.cs @@ -1,31 +1,144 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-
-namespace MediaBrowser.Controller.Entities.Movies
-{
- public class Movie : Video
- {
- public IEnumerable<Video> SpecialFeatures { get; set; }
-
- /// <summary>
- /// Finds an item by ID, recursively
- /// </summary>
- public override BaseItem FindItemById(Guid id)
- {
- var item = base.FindItemById(id);
-
- if (item != null)
- {
- return item;
- }
-
- if (SpecialFeatures != null)
- {
- return SpecialFeatures.FirstOrDefault(i => i.Id == id);
- }
-
- return null;
- }
- }
-}
+using MediaBrowser.Common.Extensions; +using MediaBrowser.Model.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.Entities.Movies +{ + /// <summary> + /// Class Movie + /// </summary> + public class Movie : Video, ISupportsSpecialFeatures + { + /// <summary> + /// Should be overridden to return the proper folder where metadata lives + /// </summary> + /// <value>The meta location.</value> + [IgnoreDataMember] + public override string MetaLocation + { + get + { + return VideoType == VideoType.VideoFile || VideoType == VideoType.Iso ? System.IO.Path.GetDirectoryName(Path) : Path; + } + } + + /// <summary> + /// Override to use tmdb or imdb id so it will stick if the item moves physical locations + /// </summary> + /// <value>The user data id.</value> + [IgnoreDataMember] + public override Guid UserDataId + { + get + { + if (_userDataId == Guid.Empty) + { + var baseId = this.GetProviderId(MetadataProviders.Tmdb) ?? this.GetProviderId(MetadataProviders.Imdb); + _userDataId = baseId != null ? baseId.GetMD5() : Id; + } + return _userDataId; + } + } + + /// <summary> + /// The _special features + /// </summary> + private List<Video> _specialFeatures; + /// <summary> + /// The _special features initialized + /// </summary> + private bool _specialFeaturesInitialized; + /// <summary> + /// The _special features sync lock + /// </summary> + private object _specialFeaturesSyncLock = new object(); + /// <summary> + /// Gets the special features. + /// </summary> + /// <value>The special features.</value> + [IgnoreDataMember] + public List<Video> SpecialFeatures + { + get + { + LazyInitializer.EnsureInitialized(ref _specialFeatures, ref _specialFeaturesInitialized, ref _specialFeaturesSyncLock, () => Entities.SpecialFeatures.LoadSpecialFeatures(this).ToList()); + return _specialFeatures; + } + private set + { + _specialFeatures = value; + + if (value == null) + { + _specialFeaturesInitialized = false; + } + } + } + + /// <summary> + /// Needed because the resolver stops at the movie folder and we find the video inside. + /// </summary> + /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value> + protected override bool UseParentPathToCreateResolveArgs + { + get + { + return VideoType == VideoType.VideoFile || VideoType == VideoType.Iso; + } + } + + /// <summary> + /// Overrides the base implementation to refresh metadata for special features + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="forceSave">if set to <c>true</c> [is new item].</param> + /// <param name="forceRefresh">if set to <c>true</c> [force].</param> + /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param> + /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param> + /// <returns>Task{System.Boolean}.</returns> + public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true) + { + // Lazy load these again + SpecialFeatures = null; + + // Kick off a task to refresh the main item + var result = await base.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs).ConfigureAwait(false); + + var tasks = SpecialFeatures.Select(item => item.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders)); + + await Task.WhenAll(tasks).ConfigureAwait(false); + + cancellationToken.ThrowIfCancellationRequested(); + + return result; + } + + /// <summary> + /// Finds an item by ID, recursively + /// </summary> + /// <param name="id">The id.</param> + /// <param name="user">The user.</param> + /// <returns>BaseItem.</returns> + public override BaseItem FindItemById(Guid id, User user) + { + var item = base.FindItemById(id, user); + + if (item != null) + { + return item; + } + + if (SpecialFeatures != null) + { + return SpecialFeatures.FirstOrDefault(i => i.Id == id); + } + + return null; + } + } +} diff --git a/MediaBrowser.Controller/Entities/Person.cs b/MediaBrowser.Controller/Entities/Person.cs index a12b9e38e2..5c92c019b8 100644 --- a/MediaBrowser.Controller/Entities/Person.cs +++ b/MediaBrowser.Controller/Entities/Person.cs @@ -1,25 +1,41 @@ -
-namespace MediaBrowser.Controller.Entities
-{
- /// <summary>
- /// This is the full Person object that can be retrieved with all of it's data.
- /// </summary>
- public class Person : BaseEntity
- {
- }
-
- /// <summary>
- /// This is the small Person stub that is attached to BaseItems
- /// </summary>
- public class PersonInfo
- {
- public string Name { get; set; }
- public string Overview { get; set; }
- public string Type { get; set; }
-
- public override string ToString()
- {
- return Name;
- }
- }
-}
+ +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// This is the full Person object that can be retrieved with all of it's data. + /// </summary> + public class Person : BaseItem + { + } + + /// <summary> + /// This is the small Person stub that is attached to BaseItems + /// </summary> + public class PersonInfo + { + /// <summary> + /// Gets or sets the name. + /// </summary> + /// <value>The name.</value> + public string Name { get; set; } + /// <summary> + /// Gets or sets the role. + /// </summary> + /// <value>The role.</value> + public string Role { get; set; } + /// <summary> + /// Gets or sets the type. + /// </summary> + /// <value>The type.</value> + public string Type { get; set; } + + /// <summary> + /// Returns a <see cref="System.String" /> that represents this instance. + /// </summary> + /// <returns>A <see cref="System.String" /> that represents this instance.</returns> + public override string ToString() + { + return Name; + } + } +} diff --git a/MediaBrowser.Controller/Entities/PlaybackProgressEventArgs.cs b/MediaBrowser.Controller/Entities/PlaybackProgressEventArgs.cs new file mode 100644 index 0000000000..bbec606ae2 --- /dev/null +++ b/MediaBrowser.Controller/Entities/PlaybackProgressEventArgs.cs @@ -0,0 +1,13 @@ +using MediaBrowser.Common.Events; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Holds information about a playback progress event + /// </summary> + public class PlaybackProgressEventArgs : GenericEventArgs<BaseItem> + { + public User User { get; set; } + public long? PlaybackPositionTicks { get; set; } + } +} diff --git a/MediaBrowser.Controller/Entities/Studio.cs b/MediaBrowser.Controller/Entities/Studio.cs index b7c6e6aa43..a255849e61 100644 --- a/MediaBrowser.Controller/Entities/Studio.cs +++ b/MediaBrowser.Controller/Entities/Studio.cs @@ -1,7 +1,10 @@ -
-namespace MediaBrowser.Controller.Entities
-{
- public class Studio : BaseEntity
- {
- }
-}
+ +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class Studio + /// </summary> + public class Studio : BaseItem + { + } +} diff --git a/MediaBrowser.Controller/Entities/TV/Episode.cs b/MediaBrowser.Controller/Entities/TV/Episode.cs index 5d599fca7f..854b9d0183 100644 --- a/MediaBrowser.Controller/Entities/TV/Episode.cs +++ b/MediaBrowser.Controller/Entities/TV/Episode.cs @@ -1,7 +1,163 @@ -
-namespace MediaBrowser.Controller.Entities.TV
-{
- public class Episode : Video
- {
- }
-}
+using MediaBrowser.Common.Extensions; +using MediaBrowser.Model.Entities; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.Serialization; + +namespace MediaBrowser.Controller.Entities.TV +{ + /// <summary> + /// Class Episode + /// </summary> + public class Episode : Video + { + /// <summary> + /// Episodes have a special Metadata folder + /// </summary> + /// <value>The meta location.</value> + [IgnoreDataMember] + public override string MetaLocation + { + get + { + return System.IO.Path.Combine(Parent.Path, "metadata"); + } + } + + /// <summary> + /// We want to group into series not show individually in an index + /// </summary> + /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool GroupInIndex + { + get { return true; } + } + + /// <summary> + /// We roll up into series + /// </summary> + /// <value>The index container.</value> + [IgnoreDataMember] + public override Folder IndexContainer + { + get + { + return Season; + } + } + + /// <summary> + /// Override to use the provider Ids + season and episode number so it will be portable + /// </summary> + /// <value>The user data id.</value> + [IgnoreDataMember] + public override Guid UserDataId + { + get + { + if (_userDataId == Guid.Empty) + { + var baseId = Series != null ? Series.GetProviderId(MetadataProviders.Tvdb) ?? Series.GetProviderId(MetadataProviders.Tvcom) : null; + if (baseId != null) + { + var seasonNo = Season != null ? Season.IndexNumber ?? 0 : 0; + var epNo = IndexNumber ?? 0; + baseId = baseId + seasonNo.ToString("000") + epNo.ToString("000"); + } + _userDataId = baseId != null ? baseId.GetMD5() : Id; + } + return _userDataId; + } + } + + /// <summary> + /// Override this if you need to combine/collapse person information + /// </summary> + /// <value>All people.</value> + [IgnoreDataMember] + public override IEnumerable<PersonInfo> AllPeople + { + get + { + if (People == null) return Series != null ? Series.People : People; + return Series != null && Series.People != null ? People.Concat(Series.People) : base.AllPeople; + } + } + + /// <summary> + /// Gets or sets the studios. + /// </summary> + /// <value>The studios.</value> + [IgnoreDataMember] + public override List<string> Studios + { + get + { + return Series != null ? Series.Studios : null; + } + set + { + base.Studios = value; + } + } + + /// <summary> + /// Gets or sets the genres. + /// </summary> + /// <value>The genres.</value> + [IgnoreDataMember] + public override List<string> Genres + { + get { return Series != null ? Series.Genres : null; } + set + { + base.Genres = value; + } + } + + /// <summary> + /// We persist the MB Id of our series object so we can always find it no matter + /// what context we happen to be loaded from. + /// </summary> + /// <value>The series item id.</value> + public Guid SeriesItemId { get; set; } + + /// <summary> + /// We persist the MB Id of our season object so we can always find it no matter + /// what context we happen to be loaded from. + /// </summary> + /// <value>The season item id.</value> + public Guid SeasonItemId { get; set; } + + /// <summary> + /// The _series + /// </summary> + private Series _series; + /// <summary> + /// This Episode's Series Instance + /// </summary> + /// <value>The series.</value> + [IgnoreDataMember] + public Series Series + { + get { return _series ?? (_series = FindParent<Series>()); } + } + + /// <summary> + /// The _season + /// </summary> + private Season _season; + /// <summary> + /// This Episode's Season Instance + /// </summary> + /// <value>The season.</value> + [IgnoreDataMember] + public Season Season + { + get { return _season ?? (_season = FindParent<Season>()); } + } + + } +} diff --git a/MediaBrowser.Controller/Entities/TV/Season.cs b/MediaBrowser.Controller/Entities/TV/Season.cs index f9c7fecb32..140c90814e 100644 --- a/MediaBrowser.Controller/Entities/TV/Season.cs +++ b/MediaBrowser.Controller/Entities/TV/Season.cs @@ -1,34 +1,143 @@ -using System;
-
-namespace MediaBrowser.Controller.Entities.TV
-{
- public class Season : Folder
- {
- /// <summary>
- /// Store these to reduce disk access in Episode Resolver
- /// </summary>
- public string[] MetadataFiles
- {
- get
- {
- return ResolveArgs.MetadataFiles ?? new string[] { };
- }
- }
-
- /// <summary>
- /// Determines if the metafolder contains a given file
- /// </summary>
- public bool ContainsMetadataFile(string file)
- {
- for (int i = 0; i < MetadataFiles.Length; i++)
- {
- if (MetadataFiles[i].Equals(file, StringComparison.OrdinalIgnoreCase))
- {
- return true;
- }
- }
-
- return false;
- }
- }
-}
+using System.Collections.Generic; +using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.IO; +using MediaBrowser.Common.Win32; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Localization; +using MediaBrowser.Model.Entities; +using System; +using System.Runtime.Serialization; + +namespace MediaBrowser.Controller.Entities.TV +{ + /// <summary> + /// Class Season + /// </summary> + public class Season : Folder + { + + /// <summary> + /// Seasons are just containers + /// </summary> + /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool IncludeInIndex + { + get + { + return false; + } + } + + /// <summary> + /// We want to group into our Series + /// </summary> + /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool GroupInIndex + { + get + { + return true; + } + } + + /// <summary> + /// Override this to return the folder that should be used to construct a container + /// for this item in an index. GroupInIndex should be true as well. + /// </summary> + /// <value>The index container.</value> + [IgnoreDataMember] + public override Folder IndexContainer + { + get + { + return Series; + } + } + + // Genre, Rating and Stuido will all be the same + protected override Dictionary<string, Func<User, IEnumerable<BaseItem>>> GetIndexByOptions() + { + return new Dictionary<string, Func<User, IEnumerable<BaseItem>>> { + {LocalizedStrings.Instance.GetString("NoneDispPref"), null}, + {LocalizedStrings.Instance.GetString("PerformerDispPref"), GetIndexByPerformer}, + {LocalizedStrings.Instance.GetString("DirectorDispPref"), GetIndexByDirector}, + {LocalizedStrings.Instance.GetString("YearDispPref"), GetIndexByYear}, + }; + } + + /// <summary> + /// Override to use the provider Ids + season number so it will be portable + /// </summary> + /// <value>The user data id.</value> + [IgnoreDataMember] + public override Guid UserDataId + { + get + { + if (_userDataId == Guid.Empty) + { + var baseId = Series != null ? Series.GetProviderId(MetadataProviders.Tvdb) ?? Series.GetProviderId(MetadataProviders.Tvcom) : null; + if (baseId != null) + { + var seasonNo = IndexNumber ?? 0; + baseId = baseId + seasonNo.ToString("000"); + } + + _userDataId = baseId != null ? baseId.GetMD5() : Id; + } + return _userDataId; + } + } + + /// <summary> + /// We persist the MB Id of our series object so we can always find it no matter + /// what context we happen to be loaded from. + /// </summary> + /// <value>The series item id.</value> + public Guid SeriesItemId { get; set; } + + /// <summary> + /// The _series + /// </summary> + private Series _series; + /// <summary> + /// This Episode's Series Instance + /// </summary> + /// <value>The series.</value> + [IgnoreDataMember] + public Series Series + { + get { return _series ?? (_series = FindParent<Series>()); } + } + + /// <summary> + /// Add files from the metadata folder to ResolveArgs + /// </summary> + /// <param name="args">The args.</param> + internal static void AddMetadataFiles(ItemResolveArgs args) + { + var folder = args.GetFileSystemEntryByName("metadata"); + + if (folder.HasValue) + { + args.AddMetadataFiles(FileSystem.GetFiles(folder.Value.Path)); + } + } + + /// <summary> + /// Creates ResolveArgs on demand + /// </summary> + /// <param name="pathInfo">The path info.</param> + /// <returns>ItemResolveArgs.</returns> + protected internal override ItemResolveArgs CreateResolveArgs(WIN32_FIND_DATA? pathInfo = null) + { + var args = base.CreateResolveArgs(pathInfo); + + AddMetadataFiles(args); + + return args; + } + } +} diff --git a/MediaBrowser.Controller/Entities/TV/Series.cs b/MediaBrowser.Controller/Entities/TV/Series.cs index 7c228a53df..152dcbac87 100644 --- a/MediaBrowser.Controller/Entities/TV/Series.cs +++ b/MediaBrowser.Controller/Entities/TV/Series.cs @@ -1,12 +1,89 @@ -using System;
-using System.Collections.Generic;
-
-namespace MediaBrowser.Controller.Entities.TV
-{
- public class Series : Folder
- {
- public string Status { get; set; }
- public IEnumerable<DayOfWeek> AirDays { get; set; }
- public string AirTime { get; set; }
- }
-}
+using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.Win32; +using MediaBrowser.Controller.Library; +using MediaBrowser.Controller.Localization; +using MediaBrowser.Model.Entities; +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace MediaBrowser.Controller.Entities.TV +{ + /// <summary> + /// Class Series + /// </summary> + public class Series : Folder + { + /// <summary> + /// Gets or sets the status. + /// </summary> + /// <value>The status.</value> + public SeriesStatus? Status { get; set; } + /// <summary> + /// Gets or sets the air days. + /// </summary> + /// <value>The air days.</value> + public List<DayOfWeek> AirDays { get; set; } + /// <summary> + /// Gets or sets the air time. + /// </summary> + /// <value>The air time.</value> + public string AirTime { get; set; } + + /// <summary> + /// Series aren't included directly in indices - Their Episodes will roll up to them + /// </summary> + /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public override bool IncludeInIndex + { + get + { + return false; + } + } + + /// <summary> + /// Override to use the provider Ids so it will be portable + /// </summary> + /// <value>The user data id.</value> + [IgnoreDataMember] + public override Guid UserDataId + { + get + { + if (_userDataId == Guid.Empty) + { + var baseId = this.GetProviderId(MetadataProviders.Tvdb) ?? this.GetProviderId(MetadataProviders.Tvcom); + _userDataId = baseId != null ? baseId.GetMD5() : Id; + } + return _userDataId; + } + } + + // Studio, Genre and Rating will all be the same so makes no sense to index by these + protected override Dictionary<string, Func<User, IEnumerable<BaseItem>>> GetIndexByOptions() + { + return new Dictionary<string, Func<User, IEnumerable<BaseItem>>> { + {LocalizedStrings.Instance.GetString("NoneDispPref"), null}, + {LocalizedStrings.Instance.GetString("PerformerDispPref"), GetIndexByPerformer}, + {LocalizedStrings.Instance.GetString("DirectorDispPref"), GetIndexByDirector}, + {LocalizedStrings.Instance.GetString("YearDispPref"), GetIndexByYear}, + }; + } + + /// <summary> + /// Creates ResolveArgs on demand + /// </summary> + /// <param name="pathInfo">The path info.</param> + /// <returns>ItemResolveArgs.</returns> + protected internal override ItemResolveArgs CreateResolveArgs(WIN32_FIND_DATA? pathInfo = null) + { + var args = base.CreateResolveArgs(pathInfo); + + Season.AddMetadataFiles(args); + + return args; + } + } +} diff --git a/MediaBrowser.Controller/Entities/Trailer.cs b/MediaBrowser.Controller/Entities/Trailer.cs new file mode 100644 index 0000000000..ed20d05b04 --- /dev/null +++ b/MediaBrowser.Controller/Entities/Trailer.cs @@ -0,0 +1,51 @@ +using System.Runtime.Serialization; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class Trailer + /// </summary> + public class Trailer : Video + { + /// <summary> + /// Gets a value indicating whether this instance is local trailer. + /// </summary> + /// <value><c>true</c> if this instance is local trailer; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public bool IsLocalTrailer + { + get + { + // Local trailers are not part of children + return Parent == null; + } + } + + /// <summary> + /// Should be overridden to return the proper folder where metadata lives + /// </summary> + /// <value>The meta location.</value> + [IgnoreDataMember] + public override string MetaLocation + { + get + { + if (!IsLocalTrailer) + { + return System.IO.Path.GetDirectoryName(Path); + } + + return base.MetaLocation; + } + } + + /// <summary> + /// Needed because the resolver stops at the trailer folder and we find the video inside. + /// </summary> + /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value> + protected override bool UseParentPathToCreateResolveArgs + { + get { return !IsLocalTrailer; } + } + } +} diff --git a/MediaBrowser.Controller/Entities/User.cs b/MediaBrowser.Controller/Entities/User.cs index 01eadfafb2..92e268d4c5 100644 --- a/MediaBrowser.Controller/Entities/User.cs +++ b/MediaBrowser.Controller/Entities/User.cs @@ -1,21 +1,446 @@ -using System;
-
-namespace MediaBrowser.Controller.Entities
-{
- public class User : BaseEntity
- {
- public string Password { get; set; }
-
- public string MaxParentalRating { get; set; }
-
- public int RecentItemDays { get; set; }
-
- public User()
- {
- RecentItemDays = 14;
- }
-
- public DateTime? LastLoginDate { get; set; }
- public DateTime? LastActivityDate { get; set; }
- }
-}
+using MediaBrowser.Common.Extensions; +using MediaBrowser.Common.IO; +using MediaBrowser.Common.Logging; +using MediaBrowser.Common.Serialization; +using MediaBrowser.Model.Configuration; +using MediaBrowser.Model.Tasks; +using System; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Threading; +using System.Threading.Tasks; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class User + /// </summary> + public class User : BaseItem + { + /// <summary> + /// The _root folder path + /// </summary> + private string _rootFolderPath; + /// <summary> + /// Gets the root folder path. + /// </summary> + /// <value>The root folder path.</value> + [IgnoreDataMember] + public string RootFolderPath + { + get + { + if (_rootFolderPath == null) + { + if (Configuration.UseCustomLibrary) + { + _rootFolderPath = GetRootFolderPath(Name); + + if (!Directory.Exists(_rootFolderPath)) + { + Directory.CreateDirectory(_rootFolderPath); + } + } + else + { + _rootFolderPath = Kernel.Instance.ApplicationPaths.DefaultUserViewsPath; + } + } + return _rootFolderPath; + } + } + + /// <summary> + /// Gets the root folder path based on a given username + /// </summary> + /// <param name="username">The username.</param> + /// <returns>System.String.</returns> + private string GetRootFolderPath(string username) + { + var safeFolderName = FileSystem.GetValidFilename(username); + + return System.IO.Path.Combine(Kernel.Instance.ApplicationPaths.RootFolderPath, safeFolderName); + } + + /// <summary> + /// Gets or sets the password. + /// </summary> + /// <value>The password.</value> + public string Password { get; set; } + + /// <summary> + /// Gets or sets the path. + /// </summary> + /// <value>The path.</value> + public override string Path + { + get + { + // Return this so that metadata providers will look in here + return ConfigurationDirectoryPath; + } + set + { + base.Path = value; + } + } + + /// <summary> + /// Ensure this has a value + /// </summary> + /// <value>The display type of the media.</value> + public override string DisplayMediaType + { + get + { + return base.DisplayMediaType ?? GetType().Name; + } + set + { + base.DisplayMediaType = value; + } + } + + /// <summary> + /// The _root folder + /// </summary> + private UserRootFolder _rootFolder; + /// <summary> + /// The _user root folder initialized + /// </summary> + private bool _userRootFolderInitialized; + /// <summary> + /// The _user root folder sync lock + /// </summary> + private object _userRootFolderSyncLock = new object(); + /// <summary> + /// Gets the root folder. + /// </summary> + /// <value>The root folder.</value> + [IgnoreDataMember] + public UserRootFolder RootFolder + { + get + { + LazyInitializer.EnsureInitialized(ref _rootFolder, ref _userRootFolderInitialized, ref _userRootFolderSyncLock, () => (UserRootFolder)Kernel.Instance.LibraryManager.GetItem(RootFolderPath)); + return _rootFolder; + } + private set + { + _rootFolder = value; + + if (_rootFolder == null) + { + _userRootFolderInitialized = false; + } + } + } + + /// <summary> + /// Gets or sets the last login date. + /// </summary> + /// <value>The last login date.</value> + public DateTime? LastLoginDate { get; set; } + /// <summary> + /// Gets or sets the last activity date. + /// </summary> + /// <value>The last activity date.</value> + public DateTime? LastActivityDate { get; set; } + + /// <summary> + /// The _configuration + /// </summary> + private UserConfiguration _configuration; + /// <summary> + /// The _configuration initialized + /// </summary> + private bool _configurationInitialized; + /// <summary> + /// The _configuration sync lock + /// </summary> + private object _configurationSyncLock = new object(); + /// <summary> + /// Gets the user's configuration + /// </summary> + /// <value>The configuration.</value> + [IgnoreDataMember] + public UserConfiguration Configuration + { + get + { + // Lazy load + LazyInitializer.EnsureInitialized(ref _configuration, ref _configurationInitialized, ref _configurationSyncLock, () => XmlSerializer.GetXmlConfiguration<UserConfiguration>(ConfigurationFilePath)); + return _configuration; + } + private set + { + _configuration = value; + + if (value == null) + { + _configurationInitialized = false; + } + } + } + + /// <summary> + /// Gets the last date modified of the configuration + /// </summary> + /// <value>The configuration date last modified.</value> + [IgnoreDataMember] + public DateTime ConfigurationDateLastModified + { + get + { + // Ensure it's been lazy loaded + var config = Configuration; + + return File.GetLastWriteTimeUtc(ConfigurationFilePath); + } + } + + /// <summary> + /// Reloads the root media folder + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="progress">The progress.</param> + /// <returns>Task.</returns> + public async Task ValidateMediaLibrary(IProgress<TaskProgress> progress, CancellationToken cancellationToken) + { + Logger.LogInfo("Validating media library for {0}", Name); + await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false); + + cancellationToken.ThrowIfCancellationRequested(); + + await RootFolder.ValidateChildren(progress, cancellationToken).ConfigureAwait(false); + } + + /// <summary> + /// Validates only the collection folders for a User and goes no further + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="progress">The progress.</param> + /// <returns>Task.</returns> + public async Task ValidateCollectionFolders(IProgress<TaskProgress> progress, CancellationToken cancellationToken) + { + Logger.LogInfo("Validating collection folders for {0}", Name); + await RootFolder.RefreshMetadata(cancellationToken).ConfigureAwait(false); + + cancellationToken.ThrowIfCancellationRequested(); + + await RootFolder.ValidateChildren(progress, cancellationToken, recursive: false).ConfigureAwait(false); + } + + /// <summary> + /// Renames the user. + /// </summary> + /// <param name="newName">The new name.</param> + /// <returns>Task.</returns> + /// <exception cref="System.ArgumentNullException"></exception> + internal Task Rename(string newName) + { + if (string.IsNullOrEmpty(newName)) + { + throw new ArgumentNullException(); + } + + // If only the casing is changing, leave the file system alone + if (!newName.Equals(Name, StringComparison.OrdinalIgnoreCase)) + { + // Move configuration + var newConfigDirectory = GetConfigurationDirectoryPath(newName); + + // Exceptions will be thrown if these paths already exist + if (Directory.Exists(newConfigDirectory)) + { + Directory.Delete(newConfigDirectory, true); + } + Directory.Move(ConfigurationDirectoryPath, newConfigDirectory); + + var customLibraryPath = GetRootFolderPath(Name); + + // Move the root folder path if using a custom library + if (Directory.Exists(customLibraryPath)) + { + var newRootFolderPath = GetRootFolderPath(newName); + if (Directory.Exists(newRootFolderPath)) + { + Directory.Delete(newRootFolderPath, true); + } + Directory.Move(customLibraryPath, newRootFolderPath); + } + } + + Name = newName; + + // Force these to be lazy loaded again + _configurationDirectoryPath = null; + _rootFolderPath = null; + RootFolder = null; + + // Kick off a task to validate the media library + Task.Run(() => ValidateMediaLibrary(new Progress<TaskProgress> { }, CancellationToken.None)); + + return RefreshMetadata(CancellationToken.None, forceSave: true, forceRefresh: true); + } + + /// <summary> + /// The _configuration directory path + /// </summary> + private string _configurationDirectoryPath; + /// <summary> + /// Gets the path to the user's configuration directory + /// </summary> + /// <value>The configuration directory path.</value> + private string ConfigurationDirectoryPath + { + get + { + if (_configurationDirectoryPath == null) + { + _configurationDirectoryPath = GetConfigurationDirectoryPath(Name); + + if (!Directory.Exists(_configurationDirectoryPath)) + { + Directory.CreateDirectory(_configurationDirectoryPath); + } + } + + return _configurationDirectoryPath; + } + } + + /// <summary> + /// Gets the configuration directory path. + /// </summary> + /// <param name="username">The username.</param> + /// <returns>System.String.</returns> + private string GetConfigurationDirectoryPath(string username) + { + var safeFolderName = FileSystem.GetValidFilename(username); + + return System.IO.Path.Combine(Kernel.Instance.ApplicationPaths.UserConfigurationDirectoryPath, safeFolderName); + } + + /// <summary> + /// Gets the path to the user's configuration file + /// </summary> + /// <value>The configuration file path.</value> + private string ConfigurationFilePath + { + get + { + return System.IO.Path.Combine(ConfigurationDirectoryPath, "config.xml"); + } + } + + /// <summary> + /// Saves the current configuration to the file system + /// </summary> + public void SaveConfiguration() + { + XmlSerializer.SerializeToFile(Configuration, ConfigurationFilePath); + } + + /// <summary> + /// Refresh metadata on us by execution our provider chain + /// The item will be persisted if a change is made by a provider, or if it's new or changed. + /// </summary> + /// <param name="cancellationToken">The cancellation token.</param> + /// <param name="forceSave">if set to <c>true</c> [is new item].</param> + /// <param name="forceRefresh">if set to <c>true</c> [force].</param> + /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param> + /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param> + /// <returns>true if a provider reports we changed</returns> + public override async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true) + { + if (resetResolveArgs) + { + ResolveArgs = null; + } + + var changed = await Kernel.Instance.ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders).ConfigureAwait(false); + + if (changed || forceSave) + { + cancellationToken.ThrowIfCancellationRequested(); + + await Kernel.Instance.UserManager.UpdateUser(this).ConfigureAwait(false); + } + + return changed; + } + + /// <summary> + /// Updates the configuration. + /// </summary> + /// <param name="config">The config.</param> + /// <exception cref="System.ArgumentNullException">config</exception> + public void UpdateConfiguration(UserConfiguration config) + { + if (config == null) + { + throw new ArgumentNullException("config"); + } + + var customLibraryChanged = config.UseCustomLibrary != Configuration.UseCustomLibrary; + + Configuration = config; + SaveConfiguration(); + + // Force these to be lazy loaded again + if (customLibraryChanged) + { + _rootFolderPath = null; + RootFolder = null; + + if (config.UseCustomLibrary) + { + CopyDefaultLibraryPathsIfNeeded(); + } + } + } + + /// <summary> + /// Copies the default library paths if needed. + /// </summary> + private void CopyDefaultLibraryPathsIfNeeded() + { + var userPath = RootFolderPath; + + var defaultPath = Kernel.Instance.ApplicationPaths.DefaultUserViewsPath; + + if (userPath.Equals(defaultPath, StringComparison.OrdinalIgnoreCase)) + { + return; + } + + if (!Directory.EnumerateFileSystemEntries(userPath, "*.lnk", SearchOption.AllDirectories).Any()) + { + FileSystem.CopyAll(defaultPath, userPath); + } + } + + /// <summary> + /// Resets the password by clearing it. + /// </summary> + /// <returns>Task.</returns> + public Task ResetPassword() + { + return ChangePassword(string.Empty); + } + + /// <summary> + /// Changes the password. + /// </summary> + /// <param name="newPassword">The new password.</param> + /// <returns>Task.</returns> + public Task ChangePassword(string newPassword) + { + Password = string.IsNullOrEmpty(newPassword) ? string.Empty : newPassword.GetMD5().ToString(); + + return Kernel.Instance.UserManager.UpdateUser(this); + } + } +} diff --git a/MediaBrowser.Controller/Entities/UserItemData.cs b/MediaBrowser.Controller/Entities/UserItemData.cs index bb4950046b..3e960d5275 100644 --- a/MediaBrowser.Controller/Entities/UserItemData.cs +++ b/MediaBrowser.Controller/Entities/UserItemData.cs @@ -1,67 +1,116 @@ -using System;
-using System.Runtime.Serialization;
-
-namespace MediaBrowser.Controller.Entities
-{
- public class UserItemData
- {
- private float? _rating;
- /// <summary>
- /// Gets or sets the users 0-10 rating
- /// </summary>
- public float? Rating
- {
- get
- {
- return _rating;
- }
- set
- {
- if (value.HasValue)
- {
- if (value.Value < 0 || value.Value > 10)
- {
- throw new InvalidOperationException("A 0-10 rating is required for UserItemData.");
- }
- }
-
- _rating = value;
- }
- }
-
- public long PlaybackPositionTicks { get; set; }
-
- public int PlayCount { get; set; }
-
- public bool IsFavorite { get; set; }
-
- /// <summary>
- /// This is an interpreted property to indicate likes or dislikes
- /// This should never be serialized.
- /// </summary>
- [IgnoreDataMember]
- public bool? Likes
- {
- get
- {
- if (Rating != null)
- {
- return Rating >= 6.5;
- }
-
- return null;
- }
- set
- {
- if (value.HasValue)
- {
- Rating = value.Value ? 10 : 1;
- }
- else
- {
- Rating = null;
- }
- }
- }
- }
-}
+using ProtoBuf; +using System; +using System.Runtime.Serialization; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class UserItemData + /// </summary> + [ProtoContract] + public class UserItemData + { + /// <summary> + /// Gets or sets the user id. + /// </summary> + /// <value>The user id.</value> + [ProtoMember(1)] + public Guid UserId { get; set; } + + /// <summary> + /// The _rating + /// </summary> + private float? _rating; + /// <summary> + /// Gets or sets the users 0-10 rating + /// </summary> + /// <value>The rating.</value> + /// <exception cref="System.ArgumentOutOfRangeException">A 0-10 rating is required for UserItemData.</exception> + /// <exception cref="System.InvalidOperationException">A 0-10 rating is required for UserItemData.</exception> + [ProtoMember(2)] + public float? Rating + { + get + { + return _rating; + } + set + { + if (value.HasValue) + { + if (value.Value < 0 || value.Value > 10) + { + throw new ArgumentOutOfRangeException("A 0-10 rating is required for UserItemData."); + } + } + + _rating = value; + } + } + + /// <summary> + /// Gets or sets the playback position ticks. + /// </summary> + /// <value>The playback position ticks.</value> + [ProtoMember(3)] + public long PlaybackPositionTicks { get; set; } + + /// <summary> + /// Gets or sets the play count. + /// </summary> + /// <value>The play count.</value> + [ProtoMember(4)] + public int PlayCount { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether this instance is favorite. + /// </summary> + /// <value><c>true</c> if this instance is favorite; otherwise, <c>false</c>.</value> + [ProtoMember(5)] + public bool IsFavorite { get; set; } + + /// <summary> + /// Gets or sets the last played date. + /// </summary> + /// <value>The last played date.</value> + [ProtoMember(6)] + public DateTime? LastPlayedDate { get; set; } + + /// <summary> + /// Gets or sets a value indicating whether this <see cref="UserItemData" /> is played. + /// </summary> + /// <value><c>true</c> if played; otherwise, <c>false</c>.</value> + [ProtoMember(7)] + public bool Played { get; set; } + + /// <summary> + /// This is an interpreted property to indicate likes or dislikes + /// This should never be serialized. + /// </summary> + /// <value><c>null</c> if [likes] contains no value, <c>true</c> if [likes]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public bool? Likes + { + get + { + if (Rating != null) + { + return Rating >= 6.5; + } + + return null; + } + set + { + if (value.HasValue) + { + Rating = value.Value ? 10 : 1; + } + else + { + Rating = null; + } + } + } + } +} diff --git a/MediaBrowser.Controller/Entities/UserRootFolder.cs b/MediaBrowser.Controller/Entities/UserRootFolder.cs new file mode 100644 index 0000000000..4ffd3468d9 --- /dev/null +++ b/MediaBrowser.Controller/Entities/UserRootFolder.cs @@ -0,0 +1,21 @@ +using System.Collections.Generic; +using System.Linq; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Special class used for User Roots. Children contain actual ones defined for this user + /// PLUS the virtual folders from the physical root (added by plug-ins). + /// </summary> + public class UserRootFolder : Folder + { + /// <summary> + /// Get the children of this folder from the actual file system + /// </summary> + /// <returns>IEnumerable{BaseItem}.</returns> + protected override IEnumerable<BaseItem> GetNonCachedChildren() + { + return base.GetNonCachedChildren().Concat(Kernel.Instance.RootFolder.VirtualChildren); + } + } +} diff --git a/MediaBrowser.Controller/Entities/Video.cs b/MediaBrowser.Controller/Entities/Video.cs index 8dd82fab99..b3ed21b19a 100644 --- a/MediaBrowser.Controller/Entities/Video.cs +++ b/MediaBrowser.Controller/Entities/Video.cs @@ -1,20 +1,109 @@ -using MediaBrowser.Model.Entities;
-using System.Collections.Generic;
-
-namespace MediaBrowser.Controller.Entities
-{
- public class Video : BaseItem
- {
- public VideoType VideoType { get; set; }
-
- public List<SubtitleStream> Subtitles { get; set; }
- public List<AudioStream> AudioStreams { get; set; }
-
- public int Height { get; set; }
- public int Width { get; set; }
- public string ScanType { get; set; }
- public float FrameRate { get; set; }
- public int BitRate { get; set; }
- public string Codec { get; set; }
- }
-}
+using MediaBrowser.Model.Entities; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; + +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class Video + /// </summary> + public class Video : BaseItem, IHasMediaStreams + { + /// <summary> + /// Gets or sets the type of the video. + /// </summary> + /// <value>The type of the video.</value> + public VideoType VideoType { get; set; } + + /// <summary> + /// Gets or sets the type of the iso. + /// </summary> + /// <value>The type of the iso.</value> + public IsoType? IsoType { get; set; } + + /// <summary> + /// Gets or sets the format of the video. + /// </summary> + /// <value>The format of the video.</value> + public VideoFormat VideoFormat { get; set; } + + /// <summary> + /// Gets or sets the media streams. + /// </summary> + /// <value>The media streams.</value> + public List<MediaStream> MediaStreams { get; set; } + + /// <summary> + /// Gets or sets the chapters. + /// </summary> + /// <value>The chapters.</value> + public List<ChapterInfo> Chapters { get; set; } + + /// <summary> + /// If the video is a folder-rip, this will hold the file list for the largest playlist + /// </summary> + public List<string> PlayableStreamFileNames { get; set; } + + /// <summary> + /// Gets the playable stream files. + /// </summary> + /// <returns>List{System.String}.</returns> + public List<string> GetPlayableStreamFiles() + { + return GetPlayableStreamFiles(Path); + } + + /// <summary> + /// Gets the playable stream files. + /// </summary> + /// <param name="rootPath">The root path.</param> + /// <returns>List{System.String}.</returns> + public List<string> GetPlayableStreamFiles(string rootPath) + { + if (PlayableStreamFileNames == null) + { + return null; + } + + var allFiles = Directory.EnumerateFiles(rootPath, "*", SearchOption.AllDirectories).ToList(); + + return PlayableStreamFileNames.Select(name => allFiles.FirstOrDefault(f => string.Equals(System.IO.Path.GetFileName(f), name, System.StringComparison.OrdinalIgnoreCase))) + .Where(f => !string.IsNullOrEmpty(f)) + .ToList(); + } + + /// <summary> + /// The default video stream for this video. Use this to determine media info for this item. + /// </summary> + /// <value>The default video stream.</value> + [IgnoreDataMember] + public MediaStream DefaultVideoStream + { + get { return MediaStreams != null ? MediaStreams.FirstOrDefault(s => s.Type == MediaStreamType.Video) : null; } + } + + /// <summary> + /// Gets a value indicating whether [is3 D]. + /// </summary> + /// <value><c>true</c> if [is3 D]; otherwise, <c>false</c>.</value> + [IgnoreDataMember] + public bool Is3D + { + get { return VideoFormat > 0; } + } + + /// <summary> + /// Gets the type of the media. + /// </summary> + /// <value>The type of the media.</value> + public override string MediaType + { + get + { + return Model.Entities.MediaType.Video; + } + } + } +} diff --git a/MediaBrowser.Controller/Entities/Year.cs b/MediaBrowser.Controller/Entities/Year.cs index d0b29de56c..9150057c82 100644 --- a/MediaBrowser.Controller/Entities/Year.cs +++ b/MediaBrowser.Controller/Entities/Year.cs @@ -1,7 +1,10 @@ -
-namespace MediaBrowser.Controller.Entities
-{
- public class Year : BaseEntity
- {
- }
-}
+ +namespace MediaBrowser.Controller.Entities +{ + /// <summary> + /// Class Year + /// </summary> + public class Year : BaseItem + { + } +} |
