2013-05-15 18:56:38 +02:00
using MediaBrowser.Controller.Dto ;
using MediaBrowser.Controller.Entities ;
2013-05-14 07:36:36 +02:00
using MediaBrowser.Controller.Entities.Audio ;
using MediaBrowser.Controller.Entities.Movies ;
using MediaBrowser.Controller.Entities.TV ;
2013-05-13 03:46:36 +02:00
using MediaBrowser.Controller.Library ;
using MediaBrowser.Controller.Persistence ;
2013-05-14 07:36:36 +02:00
using MediaBrowser.Model.Dto ;
2013-05-16 00:55:24 +02:00
using MediaBrowser.Model.Entities ;
2013-05-11 06:10:58 +02:00
using MediaBrowser.Model.Querying ;
using ServiceStack.ServiceHost ;
using System ;
2013-05-14 07:36:36 +02:00
using System.Collections.Generic ;
2013-05-22 16:44:51 +02:00
using System.IO ;
2013-05-11 06:10:58 +02:00
using System.Linq ;
2013-05-14 07:36:36 +02:00
using System.Threading ;
2013-05-11 06:10:58 +02:00
using System.Threading.Tasks ;
namespace MediaBrowser.Api
{
2013-08-28 16:26:19 +02:00
[Route("/Items/{Id}/File", "GET")]
[Api(Description = "Gets the original file of an item")]
public class GetFile
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get ; set ; }
}
2013-05-11 06:10:58 +02:00
/// <summary>
/// Class GetCriticReviews
/// </summary>
[Route("/Items/{Id}/CriticReviews", "GET")]
[Api(Description = "Gets critic reviews for an item")]
public class GetCriticReviews : IReturn < ItemReviewsResult >
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get ; set ; }
/// <summary>
/// Skips over a given number of items within the results. Use for paging.
/// </summary>
/// <value>The start index.</value>
[ApiMember(Name = "StartIndex", Description = "Optional. The record index to start at. All items with a lower index will be dropped from the results.", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? StartIndex { get ; set ; }
/// <summary>
/// The maximum number of items to return
/// </summary>
/// <value>The limit.</value>
[ApiMember(Name = "Limit", Description = "Optional. The maximum number of records to return", IsRequired = false, DataType = "int", ParameterType = "query", Verb = "GET")]
public int? Limit { get ; set ; }
}
2013-05-15 18:56:38 +02:00
/// <summary>
/// Class GetThemeSongs
/// </summary>
[Route("/Items/{Id}/ThemeSongs", "GET")]
[Api(Description = "Gets theme songs for an item")]
2013-07-10 22:06:11 +02:00
public class GetThemeSongs : IReturn < ThemeMediaResult >
2013-05-15 18:56:38 +02:00
{
/// <summary>
/// Gets or sets the user id.
/// </summary>
/// <value>The user id.</value>
[ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public Guid ? UserId { get ; set ; }
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get ; set ; }
2013-07-10 22:06:11 +02:00
[ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public bool InheritFromParent { get ; set ; }
2013-05-15 18:56:38 +02:00
}
/// <summary>
/// Class GetThemeVideos
/// </summary>
[Route("/Items/{Id}/ThemeVideos", "GET")]
2013-07-10 22:06:11 +02:00
[Api(Description = "Gets theme videos for an item")]
public class GetThemeVideos : IReturn < ThemeMediaResult >
2013-05-15 18:56:38 +02:00
{
/// <summary>
/// Gets or sets the user id.
/// </summary>
/// <value>The user id.</value>
[ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public Guid ? UserId { get ; set ; }
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get ; set ; }
2013-07-10 22:06:11 +02:00
[ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public bool InheritFromParent { get ; set ; }
}
/// <summary>
/// Class GetThemeVideos
/// </summary>
[Route("/Items/{Id}/ThemeMedia", "GET")]
[Api(Description = "Gets theme videos and songs for an item")]
public class GetThemeMedia : IReturn < ThemeMediaResult >
{
/// <summary>
/// Gets or sets the user id.
/// </summary>
/// <value>The user id.</value>
[ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public Guid ? UserId { get ; set ; }
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get ; set ; }
[ApiMember(Name = "InheritFromParent", Description = "Determines whether or not parent items should be searched for theme media.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public bool InheritFromParent { get ; set ; }
2013-05-15 18:56:38 +02:00
}
2013-05-13 03:46:36 +02:00
[Route("/Library/Refresh", "POST")]
[Api(Description = "Starts a library scan")]
public class RefreshLibrary : IReturnVoid
{
}
2013-05-14 07:36:36 +02:00
2013-05-22 16:44:51 +02:00
[Route("/Items/{Id}", "DELETE")]
[Api(Description = "Deletes an item from the library and file system")]
public class DeleteItem : IReturnVoid
{
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "DELETE")]
public string Id { get ; set ; }
}
2013-05-14 07:36:36 +02:00
[Route("/Items/Counts", "GET")]
[Api(Description = "Gets counts of various item types")]
public class GetItemCounts : IReturn < ItemCounts >
{
[ApiMember(Name = "UserId", Description = "Optional. Get counts from a specific user's library.", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public Guid ? UserId { get ; set ; }
}
2013-07-10 22:06:11 +02:00
2013-08-02 22:36:44 +02:00
[Route("/Items/{Id}/Ancestors", "GET")]
[Api(Description = "Gets all parents of an item")]
public class GetAncestors : IReturn < BaseItemDto [ ] >
{
/// <summary>
/// Gets or sets the user id.
/// </summary>
/// <value>The user id.</value>
[ApiMember(Name = "UserId", Description = "Optional. Filter by user id, and attach user data", IsRequired = false, DataType = "string", ParameterType = "query", Verb = "GET")]
public Guid ? UserId { get ; set ; }
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
[ApiMember(Name = "Id", Description = "Item Id", IsRequired = true, DataType = "string", ParameterType = "path", Verb = "GET")]
public string Id { get ; set ; }
}
2013-05-11 06:10:58 +02:00
/// <summary>
/// Class LibraryService
/// </summary>
public class LibraryService : BaseApiService
{
/// <summary>
/// The _item repo
/// </summary>
private readonly IItemRepository _itemRepo ;
2013-05-13 03:46:36 +02:00
private readonly ILibraryManager _libraryManager ;
2013-05-14 07:36:36 +02:00
private readonly IUserManager _userManager ;
2013-09-04 19:02:19 +02:00
private readonly IDtoService _dtoService ;
2013-05-13 03:46:36 +02:00
2013-05-11 06:10:58 +02:00
/// <summary>
2013-05-13 03:46:36 +02:00
/// Initializes a new instance of the <see cref="LibraryService" /> class.
2013-05-11 06:10:58 +02:00
/// </summary>
2013-05-22 21:49:12 +02:00
public LibraryService ( IItemRepository itemRepo , ILibraryManager libraryManager , IUserManager userManager ,
2013-09-04 19:02:19 +02:00
IDtoService dtoService )
2013-05-11 06:10:58 +02:00
{
_itemRepo = itemRepo ;
2013-05-13 03:46:36 +02:00
_libraryManager = libraryManager ;
2013-05-14 07:36:36 +02:00
_userManager = userManager ;
2013-09-04 19:02:19 +02:00
_dtoService = dtoService ;
2013-05-11 06:10:58 +02:00
}
2013-08-28 16:26:19 +02:00
public object Get ( GetFile request )
{
2013-09-04 19:02:19 +02:00
var item = _dtoService . GetItemByDtoId ( request . Id ) ;
2013-08-28 16:26:19 +02:00
if ( item . LocationType = = LocationType . Remote | | item . LocationType = = LocationType . Virtual )
{
throw new ArgumentException ( "This command cannot be used for remote or virtual items." ) ;
}
if ( Directory . Exists ( item . Path ) )
{
throw new ArgumentException ( "This command cannot be used for directories." ) ;
}
return ToStaticFileResult ( item . Path ) ;
}
2013-08-02 22:36:44 +02:00
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get ( GetAncestors request )
{
var result = GetAncestors ( request ) . Result ;
return ToOptimizedResult ( result ) ;
}
/// <summary>
/// Gets the ancestors.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task{BaseItemDto[]}.</returns>
public async Task < BaseItemDto [ ] > GetAncestors ( GetAncestors request )
{
2013-09-04 19:02:19 +02:00
var item = _dtoService . GetItemByDtoId ( request . Id ) ;
2013-08-02 22:36:44 +02:00
var tasks = new List < Task < BaseItemDto > > ( ) ;
var user = request . UserId . HasValue ? _userManager . GetUserById ( request . UserId . Value ) : null ;
// Get everything
var fields = Enum . GetNames ( typeof ( ItemFields ) )
. Select ( i = > ( ItemFields ) Enum . Parse ( typeof ( ItemFields ) , i , true ) )
. ToList ( ) ;
BaseItem parent = item . Parent ;
while ( parent ! = null )
{
if ( user ! = null )
{
parent = TranslateParentItem ( parent , user ) ;
}
2013-09-04 19:02:19 +02:00
tasks . Add ( _dtoService . GetBaseItemDto ( parent , fields , user ) ) ;
2013-08-02 22:36:44 +02:00
if ( parent is UserRootFolder )
{
break ;
}
parent = parent . Parent ;
}
return await Task . WhenAll ( tasks ) . ConfigureAwait ( false ) ;
}
private BaseItem TranslateParentItem ( BaseItem item , User user )
{
if ( item . Parent is AggregateFolder )
{
return user . RootFolder . GetChildren ( user , true ) . FirstOrDefault ( i = >
{
try
{
return i . LocationType = = LocationType . FileSystem & &
i . ResolveArgs . PhysicalLocations . Contains ( item . Path ) ;
}
catch ( Exception ex )
{
Logger . ErrorException ( "Error getting ResolveArgs for {0}" , ex , i . Path ) ;
return false ;
}
} ) ;
}
return item ;
}
2013-05-11 06:10:58 +02:00
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get ( GetCriticReviews request )
{
var result = GetCriticReviewsAsync ( request ) . Result ;
return ToOptimizedResult ( result ) ;
}
2013-05-14 07:36:36 +02:00
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get ( GetItemCounts request )
{
var items = GetItems ( request . UserId ) . ToList ( ) ;
var counts = new ItemCounts
2013-05-27 18:53:10 +02:00
{
AlbumCount = items . OfType < MusicAlbum > ( ) . Count ( ) ,
EpisodeCount = items . OfType < Episode > ( ) . Count ( ) ,
2013-06-23 17:02:53 +02:00
GameCount = items . OfType < Game > ( ) . Count ( ) ,
2013-05-27 18:53:10 +02:00
MovieCount = items . OfType < Movie > ( ) . Count ( ) ,
SeriesCount = items . OfType < Series > ( ) . Count ( ) ,
SongCount = items . OfType < Audio > ( ) . Count ( ) ,
2013-05-28 03:59:26 +02:00
TrailerCount = items . OfType < Trailer > ( ) . Count ( ) ,
2013-07-16 20:47:05 +02:00
MusicVideoCount = items . OfType < MusicVideo > ( ) . Count ( ) ,
2013-08-09 03:28:32 +02:00
AdultVideoCount = items . OfType < AdultVideo > ( ) . Count ( ) ,
BoxSetCount = items . OfType < BoxSet > ( ) . Count ( )
2013-05-27 18:53:10 +02:00
} ;
2013-05-14 07:36:36 +02:00
return ToOptimizedResult ( counts ) ;
}
protected IEnumerable < BaseItem > GetItems ( Guid ? userId )
{
if ( userId . HasValue )
{
var user = _userManager . GetUserById ( userId . Value ) ;
return _userManager . GetUserById ( userId . Value ) . RootFolder . GetRecursiveChildren ( user ) ;
}
return _libraryManager . RootFolder . RecursiveChildren ;
}
2013-05-13 03:46:36 +02:00
/// <summary>
/// Posts the specified request.
/// </summary>
/// <param name="request">The request.</param>
2013-05-22 16:44:51 +02:00
public async void Post ( RefreshLibrary request )
2013-05-13 03:46:36 +02:00
{
2013-05-22 16:44:51 +02:00
try
{
2013-08-02 22:36:44 +02:00
await _libraryManager . ValidateMediaLibrary ( new Progress < double > ( ) , CancellationToken . None )
2013-05-22 21:49:12 +02:00
. ConfigureAwait ( false ) ;
2013-05-22 16:44:51 +02:00
}
catch ( Exception ex )
{
Logger . ErrorException ( "Error refreshing library" , ex ) ;
}
}
/// <summary>
/// Deletes the specified request.
/// </summary>
/// <param name="request">The request.</param>
2013-06-06 14:08:46 +02:00
public void Delete ( DeleteItem request )
{
var task = DeleteItem ( request ) ;
Task . WaitAll ( task ) ;
}
private async Task DeleteItem ( DeleteItem request )
2013-05-22 16:44:51 +02:00
{
2013-09-04 19:02:19 +02:00
var item = _dtoService . GetItemByDtoId ( request . Id ) ;
2013-05-22 16:44:51 +02:00
var parent = item . Parent ;
2013-07-07 01:08:32 +02:00
if ( item . LocationType = = LocationType . Offline )
{
throw new InvalidOperationException ( string . Format ( "{0} is currently offline." , item . Name ) ) ;
}
2013-07-10 22:06:11 +02:00
2013-05-22 16:44:51 +02:00
if ( item . LocationType = = LocationType . FileSystem )
{
if ( Directory . Exists ( item . Path ) )
{
Directory . Delete ( item . Path , true ) ;
}
else if ( File . Exists ( item . Path ) )
{
File . Delete ( item . Path ) ;
}
if ( parent ! = null )
{
try
{
2013-05-22 21:49:12 +02:00
await
parent . ValidateChildren ( new Progress < double > ( ) , CancellationToken . None )
. ConfigureAwait ( false ) ;
2013-05-22 16:44:51 +02:00
}
catch ( Exception ex )
{
Logger . ErrorException ( "Error refreshing item" , ex ) ;
}
}
}
else if ( parent ! = null )
{
try
{
await parent . RemoveChild ( item , CancellationToken . None ) . ConfigureAwait ( false ) ;
}
catch ( Exception ex )
{
Logger . ErrorException ( "Error removing item" , ex ) ;
}
}
else
{
throw new InvalidOperationException ( "Don't know how to delete " + item . Name ) ;
}
2013-05-13 03:46:36 +02:00
}
2013-05-11 06:10:58 +02:00
/// <summary>
/// Gets the critic reviews async.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>Task{ItemReviewsResult}.</returns>
private async Task < ItemReviewsResult > GetCriticReviewsAsync ( GetCriticReviews request )
{
var reviews = await _itemRepo . GetCriticReviews ( new Guid ( request . Id ) ) . ConfigureAwait ( false ) ;
var reviewsArray = reviews . ToArray ( ) ;
var result = new ItemReviewsResult
2013-05-22 21:49:12 +02:00
{
TotalRecordCount = reviewsArray . Length
} ;
2013-05-11 06:10:58 +02:00
if ( request . StartIndex . HasValue )
{
reviewsArray = reviewsArray . Skip ( request . StartIndex . Value ) . ToArray ( ) ;
}
if ( request . Limit . HasValue )
{
reviewsArray = reviewsArray . Take ( request . Limit . Value ) . ToArray ( ) ;
}
result . ItemReviews = reviewsArray ;
return result ;
}
2013-05-15 18:56:38 +02:00
2013-07-10 22:06:11 +02:00
public object Get ( GetThemeMedia request )
{
var themeSongs = GetThemeSongs ( new GetThemeSongs
{
InheritFromParent = request . InheritFromParent ,
Id = request . Id ,
UserId = request . UserId
} ) . Result ;
var themeVideos = GetThemeVideos ( new GetThemeVideos
{
InheritFromParent = request . InheritFromParent ,
Id = request . Id ,
UserId = request . UserId
} ) . Result ;
return ToOptimizedResult ( new AllThemeMediaResult
{
ThemeSongsResult = themeSongs ,
ThemeVideosResult = themeVideos
} ) ;
}
2013-05-15 18:56:38 +02:00
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get ( GetThemeSongs request )
2013-07-10 22:06:11 +02:00
{
var result = GetThemeSongs ( request ) . Result ;
return ToOptimizedResult ( result ) ;
}
private async Task < ThemeMediaResult > GetThemeSongs ( GetThemeSongs request )
2013-05-15 18:56:38 +02:00
{
var user = request . UserId . HasValue ? _userManager . GetUserById ( request . UserId . Value ) : null ;
2013-05-22 21:49:12 +02:00
var item = string . IsNullOrEmpty ( request . Id )
? ( request . UserId . HasValue
? user . RootFolder
: ( Folder ) _libraryManager . RootFolder )
2013-09-04 19:02:19 +02:00
: _dtoService . GetItemByDtoId ( request . Id , request . UserId ) ;
2013-05-15 18:56:38 +02:00
2013-07-10 22:06:11 +02:00
while ( item . ThemeSongIds . Count = = 0 & & request . InheritFromParent & & item . Parent ! = null )
{
item = item . Parent ;
}
2013-05-15 18:56:38 +02:00
// Get everything
2013-06-12 23:46:50 +02:00
var fields = Enum . GetNames ( typeof ( ItemFields ) )
2013-05-22 21:49:12 +02:00
. Select ( i = > ( ItemFields ) Enum . Parse ( typeof ( ItemFields ) , i , true ) )
. ToList ( ) ;
2013-05-15 18:56:38 +02:00
2013-07-10 22:06:11 +02:00
var tasks = item . ThemeSongIds . Select ( _itemRepo . RetrieveItem )
. OrderBy ( i = > i . SortName )
2013-09-04 19:02:19 +02:00
. Select ( i = > _dtoService . GetBaseItemDto ( i , fields , user , item ) ) ;
2013-07-10 22:06:11 +02:00
var items = await Task . WhenAll ( tasks ) . ConfigureAwait ( false ) ;
2013-05-15 18:56:38 +02:00
2013-07-10 22:06:11 +02:00
return new ThemeMediaResult
2013-06-12 23:46:50 +02:00
{
Items = items ,
TotalRecordCount = items . Length ,
2013-09-04 19:02:19 +02:00
OwnerId = _dtoService . GetDtoId ( item )
2013-06-12 23:46:50 +02:00
} ;
2013-05-15 18:56:38 +02:00
}
/// <summary>
/// Gets the specified request.
/// </summary>
/// <param name="request">The request.</param>
/// <returns>System.Object.</returns>
public object Get ( GetThemeVideos request )
2013-07-10 22:06:11 +02:00
{
var result = GetThemeVideos ( request ) . Result ;
return ToOptimizedResult ( result ) ;
}
public async Task < ThemeMediaResult > GetThemeVideos ( GetThemeVideos request )
2013-05-15 18:56:38 +02:00
{
var user = request . UserId . HasValue ? _userManager . GetUserById ( request . UserId . Value ) : null ;
2013-05-22 21:49:12 +02:00
var item = string . IsNullOrEmpty ( request . Id )
? ( request . UserId . HasValue
? user . RootFolder
: ( Folder ) _libraryManager . RootFolder )
2013-09-04 19:02:19 +02:00
: _dtoService . GetItemByDtoId ( request . Id , request . UserId ) ;
2013-05-15 18:56:38 +02:00
2013-07-10 22:06:11 +02:00
while ( item . ThemeVideoIds . Count = = 0 & & request . InheritFromParent & & item . Parent ! = null )
{
item = item . Parent ;
}
2013-05-15 18:56:38 +02:00
// Get everything
2013-05-22 21:49:12 +02:00
var fields =
Enum . GetNames ( typeof ( ItemFields ) )
. Select ( i = > ( ItemFields ) Enum . Parse ( typeof ( ItemFields ) , i , true ) )
. ToList ( ) ;
2013-05-15 18:56:38 +02:00
2013-07-10 22:06:11 +02:00
var tasks = item . ThemeVideoIds . Select ( _itemRepo . RetrieveItem )
. OrderBy ( i = > i . SortName )
2013-09-04 19:02:19 +02:00
. Select ( i = > _dtoService . GetBaseItemDto ( i , fields , user , item ) ) ;
2013-05-15 18:56:38 +02:00
2013-07-10 22:06:11 +02:00
var items = await Task . WhenAll ( tasks ) . ConfigureAwait ( false ) ;
2013-05-15 18:56:38 +02:00
2013-07-10 22:06:11 +02:00
return new ThemeMediaResult
{
Items = items ,
TotalRecordCount = items . Length ,
2013-09-04 19:02:19 +02:00
OwnerId = _dtoService . GetDtoId ( item )
2013-07-10 22:06:11 +02:00
} ;
2013-05-15 18:56:38 +02:00
}
2013-05-11 06:10:58 +02:00
}
}