2013-06-18 09:43:07 +00:00
using MediaBrowser.Controller.Entities ;
2015-07-18 19:32:59 +00:00
using MediaBrowser.Controller.Entities.Audio ;
using MediaBrowser.Controller.Entities.Movies ;
2015-07-07 02:25:23 +00:00
using MediaBrowser.Controller.Entities.TV ;
2015-06-01 14:49:23 +00:00
using MediaBrowser.Controller.LiveTv ;
2013-06-18 09:43:07 +00:00
using MediaBrowser.Controller.Persistence ;
using MediaBrowser.Model.Entities ;
using MediaBrowser.Model.Logging ;
2015-06-01 14:49:23 +00:00
using MediaBrowser.Model.Querying ;
2013-06-18 09:43:07 +00:00
using MediaBrowser.Model.Serialization ;
using System ;
using System.Collections.Generic ;
using System.Data ;
2015-06-01 14:49:23 +00:00
using System.Globalization ;
2013-06-18 09:43:07 +00:00
using System.IO ;
using System.Linq ;
2015-07-09 05:52:25 +00:00
using System.Runtime.Serialization ;
2016-06-01 05:50:00 +00:00
using System.Text ;
2013-06-18 09:43:07 +00:00
using System.Threading ;
using System.Threading.Tasks ;
2016-04-30 19:47:47 +00:00
using MediaBrowser.Common.Extensions ;
2015-10-04 18:10:50 +00:00
using MediaBrowser.Controller.Channels ;
2016-05-01 22:11:24 +00:00
using MediaBrowser.Controller.Configuration ;
2016-03-20 18:39:20 +00:00
using MediaBrowser.Controller.Playlists ;
2016-06-17 13:06:13 +00:00
using MediaBrowser.Model.Dto ;
2015-12-27 18:37:06 +00:00
using MediaBrowser.Model.LiveTv ;
2013-06-18 09:43:07 +00:00
namespace MediaBrowser.Server.Implementations.Persistence
{
/// <summary>
/// Class SQLiteItemRepository
/// </summary>
2016-02-10 18:13:24 +00:00
public class SqliteItemRepository : BaseSqliteRepository , IItemRepository
2013-06-18 09:43:07 +00:00
{
2016-06-12 23:33:11 +00:00
private IDbConnection _connection ;
2013-09-17 15:14:22 +00:00
private readonly TypeMapper _typeMapper = new TypeMapper ( ) ;
2013-09-29 22:00:08 +00:00
2013-06-18 09:43:07 +00:00
/// <summary>
/// Gets the name of the repository
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
2013-06-18 19:16:27 +00:00
return "SQLite" ;
2013-06-18 09:43:07 +00:00
}
}
/// <summary>
/// Gets the json serializer.
/// </summary>
/// <value>The json serializer.</value>
private readonly IJsonSerializer _jsonSerializer ;
/// <summary>
/// The _app paths
/// </summary>
2016-05-01 22:11:24 +00:00
private readonly IServerConfigurationManager _config ;
2013-06-18 09:43:07 +00:00
2016-06-12 23:33:11 +00:00
/// <summary>
/// The _save item command
/// </summary>
private IDbCommand _saveItemCommand ;
2013-06-18 09:43:07 +00:00
private readonly string _criticReviewsPath ;
2016-06-12 23:33:11 +00:00
private IDbCommand _deleteItemCommand ;
2016-06-12 05:03:52 +00:00
2016-06-12 23:33:11 +00:00
private IDbCommand _deletePeopleCommand ;
private IDbCommand _savePersonCommand ;
private IDbCommand _deleteChaptersCommand ;
private IDbCommand _saveChapterCommand ;
private IDbCommand _deleteStreamsCommand ;
private IDbCommand _saveStreamCommand ;
private IDbCommand _deleteAncestorsCommand ;
private IDbCommand _saveAncestorCommand ;
private IDbCommand _deleteUserDataKeysCommand ;
private IDbCommand _saveUserDataKeysCommand ;
private IDbCommand _deleteItemValuesCommand ;
private IDbCommand _saveItemValuesCommand ;
private IDbCommand _deleteProviderIdsCommand ;
private IDbCommand _saveProviderIdsCommand ;
private IDbCommand _deleteImagesCommand ;
private IDbCommand _saveImagesCommand ;
private IDbCommand _updateInheritedRatingCommand ;
private IDbCommand _updateInheritedTagsCommand ;
2016-08-06 20:59:31 +00:00
public const int LatestSchemaVersion = 109 ;
2015-08-26 05:10:04 +00:00
2013-06-18 09:43:07 +00:00
/// <summary>
/// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
/// </summary>
2016-06-11 15:55:05 +00:00
public SqliteItemRepository ( IServerConfigurationManager config , IJsonSerializer jsonSerializer , ILogManager logManager , IDbConnector connector )
: base ( logManager , connector )
2013-06-18 09:43:07 +00:00
{
2016-05-01 22:11:24 +00:00
if ( config = = null )
2013-06-18 09:43:07 +00:00
{
2016-05-01 22:11:24 +00:00
throw new ArgumentNullException ( "config" ) ;
2013-06-18 09:43:07 +00:00
}
if ( jsonSerializer = = null )
{
throw new ArgumentNullException ( "jsonSerializer" ) ;
}
2016-05-01 22:11:24 +00:00
_config = config ;
2013-06-18 09:43:07 +00:00
_jsonSerializer = jsonSerializer ;
2016-05-01 22:11:24 +00:00
_criticReviewsPath = Path . Combine ( _config . ApplicationPaths . DataPath , "critic-reviews" ) ;
2016-06-11 20:12:01 +00:00
DbFilePath = Path . Combine ( _config . ApplicationPaths . DataPath , "library.db" ) ;
}
2016-06-12 23:33:11 +00:00
private const string ChaptersTableName = "Chapters2" ;
2016-06-11 20:12:01 +00:00
protected override async Task < IDbConnection > CreateConnection ( bool isReadOnly = false )
{
2016-07-04 00:14:28 +00:00
var cacheSize = _config . Configuration . SqliteCacheSize ;
2016-07-03 23:05:13 +00:00
if ( cacheSize < = 0 )
{
cacheSize = Math . Min ( Environment . ProcessorCount * 50000 , 200000 ) ;
}
var connection = await DbConnector . Connect ( DbFilePath , false , false , 0 - cacheSize ) . ConfigureAwait ( false ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
connection . RunQueries ( new [ ]
{
2016-06-23 17:04:18 +00:00
"pragma temp_store = memory" ,
2016-06-24 06:32:51 +00:00
"pragma default_temp_store = memory" ,
"PRAGMA locking_mode=EXCLUSIVE"
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
} , Logger ) ;
2016-06-11 20:12:01 +00:00
return connection ;
2013-06-18 09:43:07 +00:00
}
/// <summary>
/// Opens the connection to the database
/// </summary>
/// <returns>Task.</returns>
2016-06-24 06:32:51 +00:00
public async Task Initialize ( SqliteUserDataRepository userDataRepo )
2013-06-18 09:43:07 +00:00
{
2016-06-12 23:33:11 +00:00
_connection = await CreateConnection ( false ) . ConfigureAwait ( false ) ;
2016-06-12 05:03:52 +00:00
2016-06-12 23:33:11 +00:00
var createMediaStreamsTableCommand
= "create table if not exists mediastreams (ItemId GUID, StreamIndex INT, StreamType TEXT, Codec TEXT, Language TEXT, ChannelLayout TEXT, Profile TEXT, AspectRatio TEXT, Path TEXT, IsInterlaced BIT, BitRate INT NULL, Channels INT NULL, SampleRate INT NULL, IsDefault BIT, IsForced BIT, IsExternal BIT, Height INT NULL, Width INT NULL, AverageFrameRate FLOAT NULL, RealFrameRate FLOAT NULL, Level FLOAT NULL, PixelFormat TEXT, BitDepth INT NULL, IsAnamorphic BIT NULL, RefFrames INT NULL, CodecTag TEXT NULL, Comment TEXT NULL, NalLengthSize TEXT NULL, IsAvc BIT NULL, Title TEXT NULL, TimeBase TEXT NULL, CodecTimeBase TEXT NULL, PRIMARY KEY (ItemId, StreamIndex))" ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
string [ ] queries = {
2013-06-18 09:43:07 +00:00
2016-03-04 02:52:41 +00:00
"create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB, ParentId GUID, Path TEXT)" ,
2013-06-18 19:16:27 +00:00
2015-12-27 18:37:06 +00:00
"create table if not exists AncestorIds (ItemId GUID, AncestorId GUID, AncestorIdText TEXT, PRIMARY KEY (ItemId, AncestorId))" ,
"create index if not exists idx_AncestorIds1 on AncestorIds(AncestorId)" ,
"create index if not exists idx_AncestorIds2 on AncestorIds(AncestorIdText)" ,
2016-04-15 02:39:39 +00:00
2016-06-20 03:34:47 +00:00
"create table if not exists UserDataKeys (ItemId GUID, UserDataKey TEXT Priority INT, PRIMARY KEY (ItemId, UserDataKey))" ,
2016-05-08 06:31:08 +00:00
2016-06-17 13:06:13 +00:00
"create table if not exists ItemValues (ItemId GUID, Type INT, Value TEXT, CleanValue TEXT)" ,
2016-05-18 05:34:10 +00:00
2016-06-02 16:17:35 +00:00
"create table if not exists ProviderIds (ItemId GUID, Name TEXT, Value TEXT, PRIMARY KEY (ItemId, Name))" ,
2016-06-24 06:32:51 +00:00
// covering index
"create index if not exists Idx_ProviderIds1 on ProviderIds(ItemId,Name,Value)" ,
2016-06-02 04:41:12 +00:00
2016-06-03 16:24:04 +00:00
"create table if not exists Images (ItemId GUID NOT NULL, Path TEXT NOT NULL, ImageType INT NOT NULL, DateModified DATETIME, IsPlaceHolder BIT NOT NULL, SortOrder INT)" ,
"create index if not exists idx_Images on Images(ItemId)" ,
2015-06-29 01:10:45 +00:00
"create table if not exists People (ItemId GUID, Name TEXT NOT NULL, Role TEXT, PersonType TEXT, SortOrder int, ListOrder int)" ,
2016-06-24 06:32:51 +00:00
"drop index if exists idxPeopleItemId" ,
2016-06-20 04:56:06 +00:00
"create index if not exists idxPeopleItemId1 on People(ItemId,ListOrder)" ,
2015-12-27 18:37:06 +00:00
"create index if not exists idxPeopleName on People(Name)" ,
2015-06-29 01:10:45 +00:00
2015-10-13 16:52:27 +00:00
"create table if not exists " + ChaptersTableName + " (ItemId GUID, ChapterIndex INT, StartPositionTicks BIGINT, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))" ,
2015-10-14 02:41:46 +00:00
createMediaStreamsTableCommand ,
2016-06-24 06:32:51 +00:00
2016-05-08 06:31:08 +00:00
"create index if not exists idx_mediastreams1 on mediastreams(ItemId)" ,
2016-06-12 23:33:11 +00:00
2013-06-18 09:43:07 +00:00
} ;
2016-06-12 23:33:11 +00:00
_connection . RunQueries ( queries , Logger ) ;
_connection . AddColumn ( Logger , "AncestorIds" , "AncestorIdText" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "Path" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "StartDate" , "DATETIME" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "EndDate" , "DATETIME" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "ChannelId" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsMovie" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsSports" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsKids" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "CommunityRating" , "Float" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "CustomRating" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IndexNumber" , "INT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsLocked" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "Name" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "OfficialRating" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "MediaType" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "Overview" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "ParentIndexNumber" , "INT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "PremiereDate" , "DATETIME" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "ProductionYear" , "INT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "ParentId" , "GUID" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "Genres" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "SchemaVersion" , "INT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "SortName" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "RunTimeTicks" , "BIGINT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "OfficialRatingDescription" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "HomePageUrl" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "VoteCount" , "INT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "DisplayMediaType" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "DateCreated" , "DATETIME" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "DateModified" , "DATETIME" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "ForcedSortName" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsOffline" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "LocationType" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsSeries" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsLive" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsNews" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsPremiere" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "EpisodeTitle" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsRepeat" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "PreferredMetadataLanguage" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "PreferredMetadataCountryCode" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsHD" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "ExternalEtag" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "DateLastRefreshed" , "DATETIME" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "DateLastSaved" , "DATETIME" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsInMixedFolder" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "LockedFields" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "Studios" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "Audio" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "ExternalServiceId" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "Tags" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsFolder" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "InheritedParentalRatingValue" , "INT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "UnratedType" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "TopParentId" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsItemByName" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "SourceType" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "TrailerTypes" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "CriticRating" , "Float" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "CriticRatingSummary" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "InheritedTags" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "CleanName" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "PresentationUniqueKey" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "SlugName" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "OriginalTitle" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "PrimaryVersionId" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "DateLastMediaAdded" , "DATETIME" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "Album" , "Text" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "IsVirtualItem" , "BIT" ) ;
_connection . AddColumn ( Logger , "TypedBaseItems" , "SeriesName" , "Text" ) ;
2016-06-24 15:12:03 +00:00
_connection . AddColumn ( Logger , "TypedBaseItems" , "UserDataKey" , "Text" ) ;
2016-07-04 20:11:30 +00:00
_connection . AddColumn ( Logger , "TypedBaseItems" , "SeasonName" , "Text" ) ;
2016-07-05 05:40:18 +00:00
_connection . AddColumn ( Logger , "TypedBaseItems" , "SeasonId" , "GUID" ) ;
2016-07-05 06:01:31 +00:00
_connection . AddColumn ( Logger , "TypedBaseItems" , "SeriesId" , "GUID" ) ;
2016-07-10 15:44:53 +00:00
_connection . AddColumn ( Logger , "TypedBaseItems" , "SeriesSortName" , "Text" ) ;
2016-06-12 23:33:11 +00:00
_connection . AddColumn ( Logger , "UserDataKeys" , "Priority" , "INT" ) ;
2016-06-17 13:06:13 +00:00
_connection . AddColumn ( Logger , "ItemValues" , "CleanValue" , "Text" ) ;
2016-06-12 23:33:11 +00:00
2016-07-06 17:44:44 +00:00
_connection . AddColumn ( Logger , ChaptersTableName , "ImageDateModified" , "DATETIME" ) ;
2016-06-12 23:33:11 +00:00
string [ ] postQueries =
2016-06-24 06:32:51 +00:00
2016-06-12 23:33:11 +00:00
{
2016-06-24 06:32:51 +00:00
// obsolete
"drop index if exists idx_TypedBaseItems" ,
"drop index if exists idx_mediastreams" ,
"drop index if exists idx_" + ChaptersTableName ,
"drop index if exists idx_UserDataKeys1" ,
"drop index if exists idx_UserDataKeys2" ,
"drop index if exists idx_TypeTopParentId3" ,
"drop index if exists idx_TypeTopParentId2" ,
"drop index if exists idx_TypeTopParentId4" ,
"drop index if exists idx_Type" ,
"drop index if exists idx_TypeTopParentId" ,
"drop index if exists idx_GuidType" ,
"drop index if exists idx_TopParentId" ,
"drop index if exists idx_TypeTopParentId6" ,
"drop index if exists idx_ItemValues2" ,
"drop index if exists Idx_ProviderIds" ,
2016-06-26 16:21:10 +00:00
"drop index if exists idx_ItemValues3" ,
"drop index if exists idx_ItemValues4" ,
"drop index if exists idx_ItemValues5" ,
2016-06-24 06:32:51 +00:00
2016-07-08 03:21:35 +00:00
"create index if not exists idx_PathTypedBaseItems on TypedBaseItems(Path)" ,
"create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)" ,
2016-05-01 22:11:24 +00:00
"create index if not exists idx_PresentationUniqueKey on TypedBaseItems(PresentationUniqueKey)" ,
2016-06-24 06:32:51 +00:00
"create index if not exists idx_GuidTypeIsFolderIsVirtualItem on TypedBaseItems(Guid,Type,IsFolder,IsVirtualItem)" ,
//"create index if not exists idx_GuidMediaTypeIsFolderIsVirtualItem on TypedBaseItems(Guid,MediaType,IsFolder,IsVirtualItem)",
2016-06-20 03:34:47 +00:00
"create index if not exists idx_CleanNameType on TypedBaseItems(CleanName,Type)" ,
2016-06-24 06:32:51 +00:00
// covering index
"create index if not exists idx_TopParentIdGuid on TypedBaseItems(TopParentId,Guid)" ,
2016-06-20 04:56:06 +00:00
2016-06-20 17:07:53 +00:00
// live tv programs
"create index if not exists idx_TypeTopParentIdStartDate on TypedBaseItems(Type,TopParentId,StartDate)" ,
2016-06-26 16:21:10 +00:00
// covering index for getitemvalues
"create index if not exists idx_TypeTopParentIdGuid on TypedBaseItems(Type,TopParentId,Guid)" ,
2016-06-20 04:56:06 +00:00
// used by movie suggestions
"create index if not exists idx_TypeTopParentIdGroup on TypedBaseItems(Type,TopParentId,PresentationUniqueKey)" ,
2016-06-20 04:14:47 +00:00
"create index if not exists idx_TypeTopParentId5 on TypedBaseItems(TopParentId,IsVirtualItem)" ,
2016-06-20 04:56:06 +00:00
// latest items
"create index if not exists idx_TypeTopParentId9 on TypedBaseItems(TopParentId,Type,IsVirtualItem,PresentationUniqueKey,DateCreated)" ,
2016-06-20 17:07:53 +00:00
"create index if not exists idx_TypeTopParentId8 on TypedBaseItems(TopParentId,IsFolder,IsVirtualItem,PresentationUniqueKey,DateCreated)" ,
// resume
2016-06-20 04:14:47 +00:00
"create index if not exists idx_TypeTopParentId7 on TypedBaseItems(TopParentId,MediaType,IsVirtualItem,PresentationUniqueKey)" ,
2016-06-20 17:07:53 +00:00
// items by name
2016-06-26 16:21:10 +00:00
"create index if not exists idx_ItemValues6 on ItemValues(ItemId,Type,CleanValue)" ,
2016-06-28 04:47:30 +00:00
"create index if not exists idx_ItemValues7 on ItemValues(Type,CleanValue,ItemId)" ,
2016-06-21 01:59:26 +00:00
2016-06-24 06:32:51 +00:00
// covering index
"create index if not exists idx_UserDataKeys3 on UserDataKeys(ItemId,Priority,UserDataKey)"
2016-06-11 20:12:01 +00:00
} ;
2016-05-01 22:11:24 +00:00
2016-06-12 23:33:11 +00:00
_connection . RunQueries ( postQueries , Logger ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
PrepareStatements ( ) ;
2013-12-08 01:42:15 +00:00
2016-06-12 23:33:11 +00:00
new MediaStreamColumns ( _connection , Logger ) . AddColumns ( ) ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
DataExtensions . Attach ( _connection , Path . Combine ( _config . ApplicationPaths . DataPath , "userdata_v2.db" ) , "UserDataDb" ) ;
2016-06-25 05:16:54 +00:00
await userDataRepo . Initialize ( _connection , WriteLock ) . ConfigureAwait ( false ) ;
2016-06-24 06:32:51 +00:00
//await Vacuum(_connection).ConfigureAwait(false);
2015-10-14 02:41:46 +00:00
}
2015-09-10 03:22:52 +00:00
private readonly string [ ] _retriveItemColumns =
2015-08-27 15:58:07 +00:00
{
"type" ,
"data" ,
2015-09-10 18:28:22 +00:00
"StartDate" ,
2015-09-10 03:22:52 +00:00
"EndDate" ,
"IsOffline" ,
"ChannelId" ,
"IsMovie" ,
"IsSports" ,
2015-09-11 16:26:06 +00:00
"IsKids" ,
2015-09-20 02:06:56 +00:00
"IsSeries" ,
"IsLive" ,
"IsNews" ,
"IsPremiere" ,
2015-09-29 16:29:06 +00:00
"EpisodeTitle" ,
"IsRepeat" ,
2015-09-11 16:26:06 +00:00
"CommunityRating" ,
"CustomRating" ,
"IndexNumber" ,
2015-09-29 17:35:23 +00:00
"IsLocked" ,
"PreferredMetadataLanguage" ,
2015-10-04 18:10:50 +00:00
"PreferredMetadataCountryCode" ,
"IsHD" ,
"ExternalEtag" ,
2015-12-27 18:37:06 +00:00
"DateLastRefreshed" ,
"Name" ,
"Path" ,
"PremiereDate" ,
"Overview" ,
"ParentIndexNumber" ,
"ProductionYear" ,
"OfficialRating" ,
"OfficialRatingDescription" ,
"HomePageUrl" ,
"DisplayMediaType" ,
"ForcedSortName" ,
"RunTimeTicks" ,
"VoteCount" ,
"DateCreated" ,
"DateModified" ,
"guid" ,
"Genres" ,
"ParentId" ,
"Audio" ,
2016-03-18 06:36:58 +00:00
"ExternalServiceId" ,
"IsInMixedFolder" ,
"DateLastSaved" ,
"LockedFields" ,
"Studios" ,
2016-03-19 05:04:38 +00:00
"Tags" ,
2016-03-19 19:32:37 +00:00
"SourceType" ,
2016-04-08 18:32:38 +00:00
"TrailerTypes" ,
2016-05-06 04:50:39 +00:00
"OriginalTitle" ,
2016-05-09 03:13:38 +00:00
"PrimaryVersionId" ,
"DateLastMediaAdded" ,
2016-05-12 19:21:43 +00:00
"Album" ,
"CriticRating" ,
2016-05-20 21:32:43 +00:00
"CriticRatingSummary" ,
2016-07-04 20:11:30 +00:00
"IsVirtualItem" ,
"SeriesName" ,
2016-07-05 05:40:18 +00:00
"SeasonName" ,
2016-07-05 06:01:31 +00:00
"SeasonId" ,
2016-07-10 15:44:53 +00:00
"SeriesId" ,
2016-08-12 19:11:45 +00:00
"SeriesSortName" ,
"PresentationUniqueKey"
2015-08-27 15:58:07 +00:00
} ;
2015-10-14 02:41:46 +00:00
private readonly string [ ] _mediaStreamSaveColumns =
{
"ItemId" ,
"StreamIndex" ,
"StreamType" ,
"Codec" ,
"Language" ,
"ChannelLayout" ,
"Profile" ,
"AspectRatio" ,
"Path" ,
"IsInterlaced" ,
"BitRate" ,
"Channels" ,
"SampleRate" ,
"IsDefault" ,
"IsForced" ,
"IsExternal" ,
"Height" ,
"Width" ,
"AverageFrameRate" ,
"RealFrameRate" ,
"Level" ,
"PixelFormat" ,
"BitDepth" ,
"IsAnamorphic" ,
"RefFrames" ,
2016-01-11 16:52:22 +00:00
"CodecTag" ,
2016-04-18 03:50:44 +00:00
"Comment" ,
2016-04-27 19:23:05 +00:00
"NalLengthSize" ,
2016-05-14 18:02:06 +00:00
"IsAvc" ,
2016-06-06 21:13:00 +00:00
"Title" ,
"TimeBase" ,
"CodecTimeBase"
2015-10-14 02:41:46 +00:00
} ;
2016-06-12 23:33:11 +00:00
/// <summary>
/// Prepares the statements.
/// </summary>
private void PrepareStatements ( )
{
var saveColumns = new List < string >
{
"guid" ,
"type" ,
"data" ,
"Path" ,
"StartDate" ,
"EndDate" ,
"ChannelId" ,
"IsKids" ,
"IsMovie" ,
"IsSports" ,
"IsSeries" ,
"IsLive" ,
"IsNews" ,
"IsPremiere" ,
"EpisodeTitle" ,
"IsRepeat" ,
"CommunityRating" ,
"CustomRating" ,
"IndexNumber" ,
"IsLocked" ,
"Name" ,
"OfficialRating" ,
"MediaType" ,
"Overview" ,
"ParentIndexNumber" ,
"PremiereDate" ,
"ProductionYear" ,
"ParentId" ,
"Genres" ,
"InheritedParentalRatingValue" ,
"SchemaVersion" ,
"SortName" ,
"RunTimeTicks" ,
"OfficialRatingDescription" ,
"HomePageUrl" ,
"VoteCount" ,
"DisplayMediaType" ,
"DateCreated" ,
"DateModified" ,
"ForcedSortName" ,
"IsOffline" ,
"LocationType" ,
"PreferredMetadataLanguage" ,
"PreferredMetadataCountryCode" ,
"IsHD" ,
"ExternalEtag" ,
"DateLastRefreshed" ,
"DateLastSaved" ,
"IsInMixedFolder" ,
"LockedFields" ,
"Studios" ,
"Audio" ,
"ExternalServiceId" ,
"Tags" ,
"IsFolder" ,
"UnratedType" ,
"TopParentId" ,
"IsItemByName" ,
"SourceType" ,
"TrailerTypes" ,
"CriticRating" ,
"CriticRatingSummary" ,
"InheritedTags" ,
"CleanName" ,
"PresentationUniqueKey" ,
"SlugName" ,
"OriginalTitle" ,
"PrimaryVersionId" ,
"DateLastMediaAdded" ,
"Album" ,
"IsVirtualItem" ,
2016-06-24 15:12:03 +00:00
"SeriesName" ,
2016-07-04 20:11:30 +00:00
"UserDataKey" ,
2016-07-05 05:40:18 +00:00
"SeasonName" ,
2016-07-05 06:01:31 +00:00
"SeasonId" ,
2016-07-10 15:44:53 +00:00
"SeriesId" ,
"SeriesSortName"
2016-06-12 23:33:11 +00:00
} ;
_saveItemCommand = _connection . CreateCommand ( ) ;
_saveItemCommand . CommandText = "replace into TypedBaseItems (" + string . Join ( "," , saveColumns . ToArray ( ) ) + ") values (" ;
for ( var i = 1 ; i < = saveColumns . Count ; i + + )
{
if ( i > 1 )
{
_saveItemCommand . CommandText + = "," ;
}
_saveItemCommand . CommandText + = "@" + i . ToString ( CultureInfo . InvariantCulture ) ;
_saveItemCommand . Parameters . Add ( _saveItemCommand , "@" + i . ToString ( CultureInfo . InvariantCulture ) ) ;
}
_saveItemCommand . CommandText + = ")" ;
_deleteItemCommand = _connection . CreateCommand ( ) ;
_deleteItemCommand . CommandText = "delete from TypedBaseItems where guid=@Id" ;
_deleteItemCommand . Parameters . Add ( _deleteItemCommand , "@Id" ) ;
// People
_deletePeopleCommand = _connection . CreateCommand ( ) ;
_deletePeopleCommand . CommandText = "delete from People where ItemId=@Id" ;
_deletePeopleCommand . Parameters . Add ( _deletePeopleCommand , "@Id" ) ;
_savePersonCommand = _connection . CreateCommand ( ) ;
_savePersonCommand . CommandText = "insert into People (ItemId, Name, Role, PersonType, SortOrder, ListOrder) values (@ItemId, @Name, @Role, @PersonType, @SortOrder, @ListOrder)" ;
_savePersonCommand . Parameters . Add ( _savePersonCommand , "@ItemId" ) ;
_savePersonCommand . Parameters . Add ( _savePersonCommand , "@Name" ) ;
_savePersonCommand . Parameters . Add ( _savePersonCommand , "@Role" ) ;
_savePersonCommand . Parameters . Add ( _savePersonCommand , "@PersonType" ) ;
_savePersonCommand . Parameters . Add ( _savePersonCommand , "@SortOrder" ) ;
_savePersonCommand . Parameters . Add ( _savePersonCommand , "@ListOrder" ) ;
// Ancestors
_deleteAncestorsCommand = _connection . CreateCommand ( ) ;
_deleteAncestorsCommand . CommandText = "delete from AncestorIds where ItemId=@Id" ;
_deleteAncestorsCommand . Parameters . Add ( _deleteAncestorsCommand , "@Id" ) ;
_saveAncestorCommand = _connection . CreateCommand ( ) ;
_saveAncestorCommand . CommandText = "insert into AncestorIds (ItemId, AncestorId, AncestorIdText) values (@ItemId, @AncestorId, @AncestorIdText)" ;
_saveAncestorCommand . Parameters . Add ( _saveAncestorCommand , "@ItemId" ) ;
_saveAncestorCommand . Parameters . Add ( _saveAncestorCommand , "@AncestorId" ) ;
_saveAncestorCommand . Parameters . Add ( _saveAncestorCommand , "@AncestorIdText" ) ;
// Chapters
_deleteChaptersCommand = _connection . CreateCommand ( ) ;
_deleteChaptersCommand . CommandText = "delete from " + ChaptersTableName + " where ItemId=@ItemId" ;
_deleteChaptersCommand . Parameters . Add ( _deleteChaptersCommand , "@ItemId" ) ;
_saveChapterCommand = _connection . CreateCommand ( ) ;
_saveChapterCommand . CommandText = "replace into " + ChaptersTableName + " (ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath) values (@ItemId, @ChapterIndex, @StartPositionTicks, @Name, @ImagePath)" ;
_saveChapterCommand . Parameters . Add ( _saveChapterCommand , "@ItemId" ) ;
_saveChapterCommand . Parameters . Add ( _saveChapterCommand , "@ChapterIndex" ) ;
_saveChapterCommand . Parameters . Add ( _saveChapterCommand , "@StartPositionTicks" ) ;
_saveChapterCommand . Parameters . Add ( _saveChapterCommand , "@Name" ) ;
_saveChapterCommand . Parameters . Add ( _saveChapterCommand , "@ImagePath" ) ;
2016-07-06 17:44:44 +00:00
_saveChapterCommand . Parameters . Add ( _saveChapterCommand , "@ImageDateModified" ) ;
2016-06-12 23:33:11 +00:00
// MediaStreams
_deleteStreamsCommand = _connection . CreateCommand ( ) ;
_deleteStreamsCommand . CommandText = "delete from mediastreams where ItemId=@ItemId" ;
_deleteStreamsCommand . Parameters . Add ( _deleteStreamsCommand , "@ItemId" ) ;
_saveStreamCommand = _connection . CreateCommand ( ) ;
_saveStreamCommand . CommandText = string . Format ( "replace into mediastreams ({0}) values ({1})" ,
string . Join ( "," , _mediaStreamSaveColumns ) ,
string . Join ( "," , _mediaStreamSaveColumns . Select ( i = > "@" + i ) . ToArray ( ) ) ) ;
foreach ( var col in _mediaStreamSaveColumns )
{
_saveStreamCommand . Parameters . Add ( _saveStreamCommand , "@" + col ) ;
}
_updateInheritedRatingCommand = _connection . CreateCommand ( ) ;
_updateInheritedRatingCommand . CommandText = "Update TypedBaseItems set InheritedParentalRatingValue=@InheritedParentalRatingValue where Guid=@Guid" ;
_updateInheritedRatingCommand . Parameters . Add ( _updateInheritedRatingCommand , "@Guid" ) ;
_updateInheritedRatingCommand . Parameters . Add ( _updateInheritedRatingCommand , "@InheritedParentalRatingValue" ) ;
_updateInheritedTagsCommand = _connection . CreateCommand ( ) ;
_updateInheritedTagsCommand . CommandText = "Update TypedBaseItems set InheritedTags=@InheritedTags where Guid=@Guid" ;
_updateInheritedTagsCommand . Parameters . Add ( _updateInheritedTagsCommand , "@Guid" ) ;
_updateInheritedTagsCommand . Parameters . Add ( _updateInheritedTagsCommand , "@InheritedTags" ) ;
// user data
_deleteUserDataKeysCommand = _connection . CreateCommand ( ) ;
_deleteUserDataKeysCommand . CommandText = "delete from UserDataKeys where ItemId=@Id" ;
_deleteUserDataKeysCommand . Parameters . Add ( _deleteUserDataKeysCommand , "@Id" ) ;
_saveUserDataKeysCommand = _connection . CreateCommand ( ) ;
_saveUserDataKeysCommand . CommandText = "insert into UserDataKeys (ItemId, UserDataKey, Priority) values (@ItemId, @UserDataKey, @Priority)" ;
_saveUserDataKeysCommand . Parameters . Add ( _saveUserDataKeysCommand , "@ItemId" ) ;
_saveUserDataKeysCommand . Parameters . Add ( _saveUserDataKeysCommand , "@UserDataKey" ) ;
_saveUserDataKeysCommand . Parameters . Add ( _saveUserDataKeysCommand , "@Priority" ) ;
// item values
_deleteItemValuesCommand = _connection . CreateCommand ( ) ;
_deleteItemValuesCommand . CommandText = "delete from ItemValues where ItemId=@Id" ;
_deleteItemValuesCommand . Parameters . Add ( _deleteItemValuesCommand , "@Id" ) ;
_saveItemValuesCommand = _connection . CreateCommand ( ) ;
2016-06-17 13:06:13 +00:00
_saveItemValuesCommand . CommandText = "insert into ItemValues (ItemId, Type, Value, CleanValue) values (@ItemId, @Type, @Value, @CleanValue)" ;
2016-06-12 23:33:11 +00:00
_saveItemValuesCommand . Parameters . Add ( _saveItemValuesCommand , "@ItemId" ) ;
_saveItemValuesCommand . Parameters . Add ( _saveItemValuesCommand , "@Type" ) ;
_saveItemValuesCommand . Parameters . Add ( _saveItemValuesCommand , "@Value" ) ;
2016-06-17 13:06:13 +00:00
_saveItemValuesCommand . Parameters . Add ( _saveItemValuesCommand , "@CleanValue" ) ;
2016-06-12 23:33:11 +00:00
// provider ids
_deleteProviderIdsCommand = _connection . CreateCommand ( ) ;
_deleteProviderIdsCommand . CommandText = "delete from ProviderIds where ItemId=@Id" ;
_deleteProviderIdsCommand . Parameters . Add ( _deleteProviderIdsCommand , "@Id" ) ;
_saveProviderIdsCommand = _connection . CreateCommand ( ) ;
_saveProviderIdsCommand . CommandText = "insert into ProviderIds (ItemId, Name, Value) values (@ItemId, @Name, @Value)" ;
_saveProviderIdsCommand . Parameters . Add ( _saveProviderIdsCommand , "@ItemId" ) ;
_saveProviderIdsCommand . Parameters . Add ( _saveProviderIdsCommand , "@Name" ) ;
_saveProviderIdsCommand . Parameters . Add ( _saveProviderIdsCommand , "@Value" ) ;
// images
_deleteImagesCommand = _connection . CreateCommand ( ) ;
_deleteImagesCommand . CommandText = "delete from Images where ItemId=@Id" ;
_deleteImagesCommand . Parameters . Add ( _deleteImagesCommand , "@Id" ) ;
_saveImagesCommand = _connection . CreateCommand ( ) ;
_saveImagesCommand . CommandText = "insert into Images (ItemId, ImageType, Path, DateModified, IsPlaceHolder, SortOrder) values (@ItemId, @ImageType, @Path, @DateModified, @IsPlaceHolder, @SortOrder)" ;
_saveImagesCommand . Parameters . Add ( _saveImagesCommand , "@ItemId" ) ;
_saveImagesCommand . Parameters . Add ( _saveImagesCommand , "@ImageType" ) ;
_saveImagesCommand . Parameters . Add ( _saveImagesCommand , "@Path" ) ;
_saveImagesCommand . Parameters . Add ( _saveImagesCommand , "@DateModified" ) ;
_saveImagesCommand . Parameters . Add ( _saveImagesCommand , "@IsPlaceHolder" ) ;
_saveImagesCommand . Parameters . Add ( _saveImagesCommand , "@SortOrder" ) ;
}
2013-06-18 09:43:07 +00:00
/// <summary>
/// Save a standard item in the repo
/// </summary>
/// <param name="item">The item.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">item</exception>
public Task SaveItem ( BaseItem item , CancellationToken cancellationToken )
{
if ( item = = null )
{
throw new ArgumentNullException ( "item" ) ;
}
return SaveItems ( new [ ] { item } , cancellationToken ) ;
}
/// <summary>
/// Saves the items.
/// </summary>
/// <param name="items">The items.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">
/// items
/// or
/// cancellationToken
/// </exception>
public async Task SaveItems ( IEnumerable < BaseItem > items , CancellationToken cancellationToken )
{
if ( items = = null )
{
throw new ArgumentNullException ( "items" ) ;
}
cancellationToken . ThrowIfCancellationRequested ( ) ;
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
IDbTransaction transaction = null ;
try
2013-06-18 09:43:07 +00:00
{
2016-06-12 23:33:11 +00:00
transaction = _connection . BeginTransaction ( ) ;
2013-06-18 09:43:07 +00:00
2016-06-12 23:33:11 +00:00
foreach ( var item in items )
2013-06-18 09:43:07 +00:00
{
2016-06-12 23:33:11 +00:00
cancellationToken . ThrowIfCancellationRequested ( ) ;
var index = 0 ;
2016-03-19 19:32:37 +00:00
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . Id ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . GetType ( ) . FullName ;
_saveItemCommand . GetParameter ( index + + ) . Value = _jsonSerializer . SerializeToBytes ( item ) ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . Path ;
var hasStartDate = item as IHasStartDate ;
if ( hasStartDate ! = null )
2016-04-30 19:47:47 +00:00
{
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = hasStartDate . StartDate ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
2016-05-09 03:13:38 +00:00
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . EndDate ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . ChannelId ;
2016-05-20 21:32:43 +00:00
2016-06-12 23:33:11 +00:00
var hasProgramAttributes = item as IHasProgramAttributes ;
if ( hasProgramAttributes ! = null )
{
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsKids ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsMovie ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsSports ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsSeries ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsLive ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsNews ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsPremiere ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . EpisodeTitle ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsRepeat ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
2016-05-23 04:11:37 +00:00
}
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . CommunityRating ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . CustomRating ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . IndexNumber ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsLocked ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . Name ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . OfficialRating ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . MediaType ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . Overview ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . ParentIndexNumber ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . PremiereDate ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . ProductionYear ;
if ( item . ParentId = = Guid . Empty )
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
else
2015-12-27 18:37:06 +00:00
{
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . ParentId ;
2015-12-27 18:37:06 +00:00
}
2016-05-08 06:31:08 +00:00
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = string . Join ( "|" , item . Genres . ToArray ( ) ) ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . GetInheritedParentalRatingValue ( ) ? ? 0 ;
_saveItemCommand . GetParameter ( index + + ) . Value = LatestSchemaVersion ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . SortName ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . RunTimeTicks ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . OfficialRatingDescription ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . HomePageUrl ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . VoteCount ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . DisplayMediaType ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . DateCreated ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . DateModified ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . ForcedSortName ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsOffline ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . LocationType . ToString ( ) ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . PreferredMetadataLanguage ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . PreferredMetadataCountryCode ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsHD ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . ExternalEtag ;
if ( item . DateLastRefreshed = = default ( DateTime ) )
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = item . DateLastRefreshed ;
}
2013-06-18 09:43:07 +00:00
2016-06-12 23:33:11 +00:00
if ( item . DateLastSaved = = default ( DateTime ) )
2016-06-11 20:12:01 +00:00
{
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = item . DateLastSaved ;
2016-06-11 20:12:01 +00:00
}
2013-06-18 09:43:07 +00:00
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsInMixedFolder ;
_saveItemCommand . GetParameter ( index + + ) . Value = string . Join ( "|" , item . LockedFields . Select ( i = > i . ToString ( ) ) . ToArray ( ) ) ;
_saveItemCommand . GetParameter ( index + + ) . Value = string . Join ( "|" , item . Studios . ToArray ( ) ) ;
if ( item . Audio . HasValue )
{
_saveItemCommand . GetParameter ( index + + ) . Value = item . Audio . Value . ToString ( ) ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
_saveItemCommand . GetParameter ( index + + ) . Value = item . ServiceName ;
if ( item . Tags . Count > 0 )
{
_saveItemCommand . GetParameter ( index + + ) . Value = string . Join ( "|" , item . Tags . ToArray ( ) ) ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsFolder ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . GetBlockUnratedType ( ) . ToString ( ) ;
var topParent = item . GetTopParent ( ) ;
if ( topParent ! = null )
{
//Logger.Debug("Item {0} has top parent {1}", item.Id, topParent.Id);
_saveItemCommand . GetParameter ( index + + ) . Value = topParent . Id . ToString ( "N" ) ;
}
else
{
//Logger.Debug("Item {0} has null top parent", item.Id);
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
var isByName = false ;
var byName = item as IItemByName ;
if ( byName ! = null )
{
var dualAccess = item as IHasDualAccess ;
isByName = dualAccess = = null | | dualAccess . IsAccessedByName ;
}
_saveItemCommand . GetParameter ( index + + ) . Value = isByName ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . SourceType . ToString ( ) ;
var trailer = item as Trailer ;
if ( trailer ! = null & & trailer . TrailerTypes . Count > 0 )
{
_saveItemCommand . GetParameter ( index + + ) . Value = string . Join ( "|" , trailer . TrailerTypes . Select ( i = > i . ToString ( ) ) . ToArray ( ) ) ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
_saveItemCommand . GetParameter ( index + + ) . Value = item . CriticRating ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . CriticRatingSummary ;
var inheritedTags = item . GetInheritedTags ( ) ;
if ( inheritedTags . Count > 0 )
2016-06-11 20:12:01 +00:00
{
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = string . Join ( "|" , inheritedTags . ToArray ( ) ) ;
2016-06-11 20:12:01 +00:00
}
2016-06-12 23:33:11 +00:00
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
if ( string . IsNullOrWhiteSpace ( item . Name ) )
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
else
{
2016-08-06 20:59:31 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = GetCleanValue ( item . Name ) ;
2016-06-12 23:33:11 +00:00
}
2016-08-12 19:11:45 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . GetPresentationUniqueKey ( ) ;
2016-06-12 23:33:11 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . SlugName ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . OriginalTitle ;
var video = item as Video ;
if ( video ! = null )
{
_saveItemCommand . GetParameter ( index + + ) . Value = video . PrimaryVersionId ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
var folder = item as Folder ;
if ( folder ! = null & & folder . DateLastMediaAdded . HasValue )
{
_saveItemCommand . GetParameter ( index + + ) . Value = folder . DateLastMediaAdded . Value ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
_saveItemCommand . GetParameter ( index + + ) . Value = item . Album ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsVirtualItem | | ( ! item . IsFolder & & item . LocationType = = LocationType . Virtual ) ;
var hasSeries = item as IHasSeries ;
if ( hasSeries ! = null )
{
2016-07-04 20:11:30 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = hasSeries . FindSeriesName ( ) ;
2016-06-12 23:33:11 +00:00
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
2016-06-24 15:12:03 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . GetUserDataKeys ( ) . FirstOrDefault ( ) ;
2016-07-04 20:11:30 +00:00
var episode = item as Episode ;
if ( episode ! = null )
{
_saveItemCommand . GetParameter ( index + + ) . Value = episode . FindSeasonName ( ) ;
2016-07-05 05:40:18 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = episode . FindSeasonId ( ) ;
2016-07-04 20:11:30 +00:00
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
2016-07-05 05:40:18 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
2016-07-04 20:11:30 +00:00
}
2016-07-05 06:01:31 +00:00
if ( hasSeries ! = null )
{
_saveItemCommand . GetParameter ( index + + ) . Value = hasSeries . FindSeriesId ( ) ;
2016-07-10 15:44:53 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = hasSeries . FindSeriesSortName ( ) ;
2016-07-05 06:01:31 +00:00
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
2016-07-10 15:44:53 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
2016-07-05 06:01:31 +00:00
}
2016-06-12 23:33:11 +00:00
_saveItemCommand . Transaction = transaction ;
_saveItemCommand . ExecuteNonQuery ( ) ;
if ( item . SupportsAncestors )
{
UpdateAncestors ( item . Id , item . GetAncestorIds ( ) . Distinct ( ) . ToList ( ) , transaction ) ;
}
UpdateUserDataKeys ( item . Id , item . GetUserDataKeys ( ) . Distinct ( StringComparer . OrdinalIgnoreCase ) . ToList ( ) , transaction ) ;
UpdateImages ( item . Id , item . ImageInfos , transaction ) ;
UpdateProviderIds ( item . Id , item . ProviderIds , transaction ) ;
2016-06-17 13:06:13 +00:00
UpdateItemValues ( item . Id , GetItemValuesToSave ( item ) , transaction ) ;
2016-06-12 23:33:11 +00:00
}
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
catch ( Exception e )
{
Logger . ErrorException ( "Failed to save items:" , e ) ;
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
finally
{
if ( transaction ! = null )
{
transaction . Dispose ( ) ;
2013-06-18 09:43:07 +00:00
}
2016-06-12 23:33:11 +00:00
WriteLock . Release ( ) ;
2013-06-18 09:43:07 +00:00
}
}
2015-06-01 14:49:23 +00:00
2013-06-18 09:43:07 +00:00
/// <summary>
/// Internal retrieve from items or users table
/// </summary>
/// <param name="id">The id.</param>
/// <returns>BaseItem.</returns>
/// <exception cref="System.ArgumentNullException">id</exception>
/// <exception cref="System.ArgumentException"></exception>
2013-06-26 16:08:16 +00:00
public BaseItem RetrieveItem ( Guid id )
2013-06-18 09:43:07 +00:00
{
if ( id = = Guid . Empty )
{
throw new ArgumentNullException ( "id" ) ;
}
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2013-06-18 09:43:07 +00:00
{
2016-06-12 23:33:11 +00:00
cmd . CommandText = "select " + string . Join ( "," , _retriveItemColumns ) + " from TypedBaseItems where guid = @guid" ;
cmd . Parameters . Add ( cmd , "@guid" , DbType . Guid ) . Value = id ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult | CommandBehavior . SingleRow ) )
{
if ( reader . Read ( ) )
2013-06-18 09:43:07 +00:00
{
2016-06-12 23:33:11 +00:00
return GetItem ( reader ) ;
2014-02-20 04:53:15 +00:00
}
}
2016-06-12 23:33:11 +00:00
return null ;
2014-02-20 04:53:15 +00:00
}
}
2013-06-26 16:08:16 +00:00
2014-02-20 04:53:15 +00:00
private BaseItem GetItem ( IDataReader reader )
{
var typeString = reader . GetString ( 0 ) ;
2013-06-26 16:08:16 +00:00
2014-02-20 04:53:15 +00:00
var type = _typeMapper . GetType ( typeString ) ;
2013-06-26 16:08:16 +00:00
2014-02-20 04:53:15 +00:00
if ( type = = null )
{
2016-06-05 00:17:35 +00:00
//Logger.Debug("Unknown type {0}", typeString);
2013-06-26 16:08:16 +00:00
2013-06-18 09:43:07 +00:00
return null ;
}
2014-02-20 04:53:15 +00:00
2015-12-27 18:37:06 +00:00
BaseItem item = null ;
2015-08-27 15:58:07 +00:00
2014-02-20 04:53:15 +00:00
using ( var stream = reader . GetMemoryStream ( 1 ) )
{
2015-07-02 05:08:05 +00:00
try
{
2015-08-27 15:58:07 +00:00
item = _jsonSerializer . DeserializeFromStream ( stream , type ) as BaseItem ;
2015-12-27 18:37:06 +00:00
}
catch ( SerializationException ex )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Error deserializing item" , ex ) ;
2015-12-27 18:37:06 +00:00
}
2015-08-27 15:58:07 +00:00
2015-12-27 18:37:06 +00:00
if ( item = = null )
{
try
{
item = Activator . CreateInstance ( type ) as BaseItem ;
}
catch
2015-08-27 15:58:07 +00:00
{
}
2015-07-02 05:08:05 +00:00
}
2015-12-27 18:37:06 +00:00
if ( item = = null )
2015-07-02 05:08:05 +00:00
{
return null ;
}
2014-02-20 04:53:15 +00:00
}
2015-08-27 15:58:07 +00:00
if ( ! reader . IsDBNull ( 2 ) )
{
2015-09-10 18:28:22 +00:00
var hasStartDate = item as IHasStartDate ;
if ( hasStartDate ! = null )
{
hasStartDate . StartDate = reader . GetDateTime ( 2 ) . ToUniversalTime ( ) ;
}
2015-09-10 03:22:52 +00:00
}
if ( ! reader . IsDBNull ( 3 ) )
{
2015-09-10 18:28:22 +00:00
item . EndDate = reader . GetDateTime ( 3 ) . ToUniversalTime ( ) ;
2015-09-10 03:22:52 +00:00
}
if ( ! reader . IsDBNull ( 4 ) )
{
2015-09-10 18:28:22 +00:00
item . IsOffline = reader . GetBoolean ( 4 ) ;
}
if ( ! reader . IsDBNull ( 5 ) )
{
item . ChannelId = reader . GetString ( 5 ) ;
2015-09-10 03:22:52 +00:00
}
var hasProgramAttributes = item as IHasProgramAttributes ;
if ( hasProgramAttributes ! = null )
{
2015-09-10 18:28:22 +00:00
if ( ! reader . IsDBNull ( 6 ) )
2015-09-10 03:22:52 +00:00
{
2015-09-10 18:28:22 +00:00
hasProgramAttributes . IsMovie = reader . GetBoolean ( 6 ) ;
2015-09-10 03:22:52 +00:00
}
2015-09-10 18:28:22 +00:00
if ( ! reader . IsDBNull ( 7 ) )
2015-09-10 03:22:52 +00:00
{
2015-09-10 18:28:22 +00:00
hasProgramAttributes . IsSports = reader . GetBoolean ( 7 ) ;
2015-09-10 03:22:52 +00:00
}
2015-09-10 18:28:22 +00:00
if ( ! reader . IsDBNull ( 8 ) )
2015-09-10 03:22:52 +00:00
{
2015-09-10 18:28:22 +00:00
hasProgramAttributes . IsKids = reader . GetBoolean ( 8 ) ;
2015-09-10 03:22:52 +00:00
}
2015-09-20 02:06:56 +00:00
if ( ! reader . IsDBNull ( 9 ) )
{
hasProgramAttributes . IsSeries = reader . GetBoolean ( 9 ) ;
}
if ( ! reader . IsDBNull ( 10 ) )
{
hasProgramAttributes . IsLive = reader . GetBoolean ( 10 ) ;
}
if ( ! reader . IsDBNull ( 11 ) )
{
hasProgramAttributes . IsNews = reader . GetBoolean ( 11 ) ;
}
if ( ! reader . IsDBNull ( 12 ) )
{
hasProgramAttributes . IsPremiere = reader . GetBoolean ( 12 ) ;
}
2015-09-29 16:29:06 +00:00
if ( ! reader . IsDBNull ( 13 ) )
{
hasProgramAttributes . EpisodeTitle = reader . GetString ( 13 ) ;
}
if ( ! reader . IsDBNull ( 14 ) )
{
hasProgramAttributes . IsRepeat = reader . GetBoolean ( 14 ) ;
}
2015-08-27 15:58:07 +00:00
}
2015-09-29 16:29:06 +00:00
if ( ! reader . IsDBNull ( 15 ) )
2015-09-11 16:26:06 +00:00
{
2015-09-29 16:29:06 +00:00
item . CommunityRating = reader . GetFloat ( 15 ) ;
2015-09-11 16:26:06 +00:00
}
2015-09-29 16:29:06 +00:00
if ( ! reader . IsDBNull ( 16 ) )
2015-09-11 16:26:06 +00:00
{
2015-09-29 16:29:06 +00:00
item . CustomRating = reader . GetString ( 16 ) ;
2015-09-11 16:26:06 +00:00
}
2015-09-29 16:29:06 +00:00
if ( ! reader . IsDBNull ( 17 ) )
2015-09-11 16:26:06 +00:00
{
2015-09-29 16:29:06 +00:00
item . IndexNumber = reader . GetInt32 ( 17 ) ;
2015-09-11 16:26:06 +00:00
}
2015-09-29 16:29:06 +00:00
if ( ! reader . IsDBNull ( 18 ) )
2015-09-11 16:26:06 +00:00
{
2015-09-29 16:29:06 +00:00
item . IsLocked = reader . GetBoolean ( 18 ) ;
2015-09-11 16:26:06 +00:00
}
2015-09-29 17:35:23 +00:00
if ( ! reader . IsDBNull ( 19 ) )
{
item . PreferredMetadataLanguage = reader . GetString ( 19 ) ;
}
if ( ! reader . IsDBNull ( 20 ) )
{
item . PreferredMetadataCountryCode = reader . GetString ( 20 ) ;
}
2015-10-04 18:10:50 +00:00
if ( ! reader . IsDBNull ( 21 ) )
{
item . IsHD = reader . GetBoolean ( 21 ) ;
}
if ( ! reader . IsDBNull ( 22 ) )
{
item . ExternalEtag = reader . GetString ( 22 ) ;
}
if ( ! reader . IsDBNull ( 23 ) )
{
2015-10-25 17:13:30 +00:00
item . DateLastRefreshed = reader . GetDateTime ( 23 ) . ToUniversalTime ( ) ;
2015-10-14 05:02:30 +00:00
}
2015-12-27 18:37:06 +00:00
if ( ! reader . IsDBNull ( 24 ) )
{
item . Name = reader . GetString ( 24 ) ;
}
if ( ! reader . IsDBNull ( 25 ) )
{
item . Path = reader . GetString ( 25 ) ;
}
if ( ! reader . IsDBNull ( 26 ) )
{
item . PremiereDate = reader . GetDateTime ( 26 ) . ToUniversalTime ( ) ;
}
if ( ! reader . IsDBNull ( 27 ) )
{
item . Overview = reader . GetString ( 27 ) ;
}
if ( ! reader . IsDBNull ( 28 ) )
{
item . ParentIndexNumber = reader . GetInt32 ( 28 ) ;
}
if ( ! reader . IsDBNull ( 29 ) )
{
item . ProductionYear = reader . GetInt32 ( 29 ) ;
}
if ( ! reader . IsDBNull ( 30 ) )
{
item . OfficialRating = reader . GetString ( 30 ) ;
}
if ( ! reader . IsDBNull ( 31 ) )
{
2016-02-21 17:22:31 +00:00
item . OfficialRatingDescription = reader . GetString ( 31 ) ;
2015-12-27 18:37:06 +00:00
}
if ( ! reader . IsDBNull ( 32 ) )
{
item . HomePageUrl = reader . GetString ( 32 ) ;
}
if ( ! reader . IsDBNull ( 33 ) )
{
item . DisplayMediaType = reader . GetString ( 33 ) ;
}
if ( ! reader . IsDBNull ( 34 ) )
{
item . ForcedSortName = reader . GetString ( 34 ) ;
}
if ( ! reader . IsDBNull ( 35 ) )
{
item . RunTimeTicks = reader . GetInt64 ( 35 ) ;
}
if ( ! reader . IsDBNull ( 36 ) )
{
item . VoteCount = reader . GetInt32 ( 36 ) ;
}
if ( ! reader . IsDBNull ( 37 ) )
{
item . DateCreated = reader . GetDateTime ( 37 ) . ToUniversalTime ( ) ;
}
if ( ! reader . IsDBNull ( 38 ) )
{
item . DateModified = reader . GetDateTime ( 38 ) . ToUniversalTime ( ) ;
}
item . Id = reader . GetGuid ( 39 ) ;
if ( ! reader . IsDBNull ( 40 ) )
{
item . Genres = reader . GetString ( 40 ) . Split ( '|' ) . Where ( i = > ! string . IsNullOrWhiteSpace ( i ) ) . ToList ( ) ;
}
if ( ! reader . IsDBNull ( 41 ) )
{
item . ParentId = reader . GetGuid ( 41 ) ;
}
if ( ! reader . IsDBNull ( 42 ) )
{
item . Audio = ( ProgramAudio ) Enum . Parse ( typeof ( ProgramAudio ) , reader . GetString ( 42 ) , true ) ;
}
if ( ! reader . IsDBNull ( 43 ) )
{
2016-03-19 21:17:08 +00:00
item . ServiceName = reader . GetString ( 43 ) ;
2015-12-27 18:37:06 +00:00
}
2016-03-18 06:36:58 +00:00
if ( ! reader . IsDBNull ( 44 ) )
{
item . IsInMixedFolder = reader . GetBoolean ( 44 ) ;
}
if ( ! reader . IsDBNull ( 45 ) )
{
item . DateLastSaved = reader . GetDateTime ( 45 ) . ToUniversalTime ( ) ;
}
if ( ! reader . IsDBNull ( 46 ) )
{
item . LockedFields = reader . GetString ( 46 ) . Split ( '|' ) . Where ( i = > ! string . IsNullOrWhiteSpace ( i ) ) . Select ( i = > ( MetadataFields ) Enum . Parse ( typeof ( MetadataFields ) , i , true ) ) . ToList ( ) ;
}
if ( ! reader . IsDBNull ( 47 ) )
{
item . Studios = reader . GetString ( 47 ) . Split ( '|' ) . Where ( i = > ! string . IsNullOrWhiteSpace ( i ) ) . ToList ( ) ;
}
if ( ! reader . IsDBNull ( 48 ) )
{
item . Tags = reader . GetString ( 48 ) . Split ( '|' ) . Where ( i = > ! string . IsNullOrWhiteSpace ( i ) ) . ToList ( ) ;
}
2016-03-19 05:04:38 +00:00
if ( ! reader . IsDBNull ( 49 ) )
{
item . SourceType = ( SourceType ) Enum . Parse ( typeof ( SourceType ) , reader . GetString ( 49 ) , true ) ;
}
2016-03-19 19:32:37 +00:00
var trailer = item as Trailer ;
if ( trailer ! = null )
{
if ( ! reader . IsDBNull ( 50 ) )
{
trailer . TrailerTypes = reader . GetString ( 50 ) . Split ( '|' ) . Where ( i = > ! string . IsNullOrWhiteSpace ( i ) ) . Select ( i = > ( TrailerType ) Enum . Parse ( typeof ( TrailerType ) , i , true ) ) . ToList ( ) ;
}
}
2016-07-24 16:46:17 +00:00
var index = 51 ;
2016-04-08 18:32:38 +00:00
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-05-06 04:50:39 +00:00
{
2016-07-24 16:46:17 +00:00
item . OriginalTitle = reader . GetString ( index ) ;
2016-05-06 04:50:39 +00:00
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-05-06 04:50:39 +00:00
var video = item as Video ;
if ( video ! = null )
{
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-05-06 04:50:39 +00:00
{
2016-07-24 16:46:17 +00:00
video . PrimaryVersionId = reader . GetString ( index ) ;
2016-05-06 04:50:39 +00:00
}
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-05-06 04:50:39 +00:00
2016-05-09 03:13:38 +00:00
var folder = item as Folder ;
2016-07-24 16:46:17 +00:00
if ( folder ! = null & & ! reader . IsDBNull ( index ) )
2016-05-09 03:13:38 +00:00
{
2016-07-24 16:46:17 +00:00
folder . DateLastMediaAdded = reader . GetDateTime ( index ) . ToUniversalTime ( ) ;
2016-05-09 03:13:38 +00:00
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-05-09 03:13:38 +00:00
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-05-09 03:13:38 +00:00
{
2016-07-24 16:46:17 +00:00
item . Album = reader . GetString ( index ) ;
2016-05-09 03:13:38 +00:00
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-05-09 03:13:38 +00:00
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-05-12 19:21:43 +00:00
{
2016-07-24 16:46:17 +00:00
item . CriticRating = reader . GetFloat ( index ) ;
2016-05-12 19:21:43 +00:00
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-05-12 19:21:43 +00:00
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-05-12 19:21:43 +00:00
{
2016-07-24 16:46:17 +00:00
item . CriticRatingSummary = reader . GetString ( index ) ;
2016-05-12 19:21:43 +00:00
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-05-12 19:21:43 +00:00
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-05-20 21:32:43 +00:00
{
2016-07-24 16:46:17 +00:00
item . IsVirtualItem = reader . GetBoolean ( index ) ;
2016-05-20 21:32:43 +00:00
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-05-20 21:32:43 +00:00
2016-07-04 20:11:30 +00:00
var hasSeries = item as IHasSeries ;
if ( hasSeries ! = null )
{
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-07-04 20:11:30 +00:00
{
2016-07-24 16:46:17 +00:00
hasSeries . SeriesName = reader . GetString ( index ) ;
2016-07-04 20:11:30 +00:00
}
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-07-04 20:11:30 +00:00
var episode = item as Episode ;
if ( episode ! = null )
{
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-07-04 20:11:30 +00:00
{
2016-07-24 16:46:17 +00:00
episode . SeasonName = reader . GetString ( index ) ;
2016-07-04 20:11:30 +00:00
}
2016-07-24 16:46:17 +00:00
index + + ;
if ( ! reader . IsDBNull ( index ) )
2016-07-05 05:40:18 +00:00
{
2016-07-24 16:46:17 +00:00
episode . SeasonId = reader . GetGuid ( index ) ;
2016-07-05 05:40:18 +00:00
}
2016-07-04 20:11:30 +00:00
}
2016-07-24 16:46:17 +00:00
else
{
index + + ;
}
index + + ;
2016-07-04 20:11:30 +00:00
2016-07-05 06:01:31 +00:00
if ( hasSeries ! = null )
{
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-07-05 06:01:31 +00:00
{
2016-07-24 16:46:17 +00:00
hasSeries . SeriesId = reader . GetGuid ( index ) ;
2016-07-05 06:01:31 +00:00
}
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-07-05 06:01:31 +00:00
2016-07-10 15:44:53 +00:00
if ( hasSeries ! = null )
{
2016-07-24 16:46:17 +00:00
if ( ! reader . IsDBNull ( index ) )
2016-07-10 15:44:53 +00:00
{
2016-07-24 16:46:17 +00:00
hasSeries . SeriesSortName = reader . GetString ( index ) ;
2016-07-10 15:44:53 +00:00
}
}
2016-07-24 16:46:17 +00:00
index + + ;
2016-07-10 15:44:53 +00:00
2016-08-12 19:11:45 +00:00
if ( ! reader . IsDBNull ( index ) )
{
item . PresentationUniqueKey = reader . GetString ( index ) ;
}
index + + ;
2015-08-27 15:58:07 +00:00
return item ;
2013-06-18 09:43:07 +00:00
}
/// <summary>
/// Gets the critic reviews.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <returns>Task{IEnumerable{ItemReview}}.</returns>
2013-09-17 15:14:22 +00:00
public IEnumerable < ItemReview > GetCriticReviews ( Guid itemId )
2013-06-18 09:43:07 +00:00
{
2013-09-17 15:14:22 +00:00
try
2013-06-18 09:43:07 +00:00
{
2013-09-17 15:14:22 +00:00
var path = Path . Combine ( _criticReviewsPath , itemId + ".json" ) ;
2013-06-18 09:43:07 +00:00
2013-09-17 15:14:22 +00:00
return _jsonSerializer . DeserializeFromFile < List < ItemReview > > ( path ) ;
}
catch ( DirectoryNotFoundException )
{
return new List < ItemReview > ( ) ;
}
catch ( FileNotFoundException )
{
return new List < ItemReview > ( ) ;
}
2013-06-18 09:43:07 +00:00
}
2014-02-03 17:44:13 +00:00
private readonly Task _cachedTask = Task . FromResult ( true ) ;
2013-06-18 09:43:07 +00:00
/// <summary>
/// Saves the critic reviews.
/// </summary>
/// <param name="itemId">The item id.</param>
/// <param name="criticReviews">The critic reviews.</param>
/// <returns>Task.</returns>
public Task SaveCriticReviews ( Guid itemId , IEnumerable < ItemReview > criticReviews )
{
2015-09-16 17:16:39 +00:00
Directory . CreateDirectory ( _criticReviewsPath ) ;
2013-06-18 09:43:07 +00:00
2013-09-24 15:08:51 +00:00
var path = Path . Combine ( _criticReviewsPath , itemId + ".json" ) ;
_jsonSerializer . SerializeToFile ( criticReviews . ToList ( ) , path ) ;
2013-06-18 09:43:07 +00:00
2014-02-03 17:44:13 +00:00
return _cachedTask ;
2013-06-18 09:43:07 +00:00
}
2013-06-18 19:16:27 +00:00
/// <summary>
/// Gets chapters for an item
/// </summary>
/// <param name="id">The id.</param>
/// <returns>IEnumerable{ChapterInfo}.</returns>
/// <exception cref="System.ArgumentNullException">id</exception>
public IEnumerable < ChapterInfo > GetChapters ( Guid id )
{
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-10-13 16:52:27 +00:00
if ( id = = Guid . Empty )
{
throw new ArgumentNullException ( "id" ) ;
}
2016-05-10 18:13:26 +00:00
var list = new List < ChapterInfo > ( ) ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-10-13 16:52:27 +00:00
{
2016-07-06 17:44:44 +00:00
cmd . CommandText = "select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId order by ChapterIndex asc" ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
cmd . Parameters . Add ( cmd , "@ItemId" , DbType . Guid ) . Value = id ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
2015-10-13 16:52:27 +00:00
{
2016-06-12 23:33:11 +00:00
list . Add ( GetChapter ( reader ) ) ;
2015-10-13 16:52:27 +00:00
}
}
2016-06-11 20:12:01 +00:00
}
2016-06-12 23:33:11 +00:00
return list ;
2013-06-18 19:16:27 +00:00
}
/// <summary>
/// Gets a single chapter for an item
/// </summary>
/// <param name="id">The id.</param>
/// <param name="index">The index.</param>
/// <returns>ChapterInfo.</returns>
/// <exception cref="System.ArgumentNullException">id</exception>
public ChapterInfo GetChapter ( Guid id , int index )
{
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-10-13 16:52:27 +00:00
if ( id = = Guid . Empty )
{
throw new ArgumentNullException ( "id" ) ;
}
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-10-13 16:52:27 +00:00
{
2016-07-06 17:44:44 +00:00
cmd . CommandText = "select StartPositionTicks,Name,ImagePath,ImageDateModified from " + ChaptersTableName + " where ItemId = @ItemId and ChapterIndex=@ChapterIndex" ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
cmd . Parameters . Add ( cmd , "@ItemId" , DbType . Guid ) . Value = id ;
cmd . Parameters . Add ( cmd , "@ChapterIndex" , DbType . Int32 ) . Value = index ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult | CommandBehavior . SingleRow ) )
{
if ( reader . Read ( ) )
2015-10-13 16:52:27 +00:00
{
2016-06-12 23:33:11 +00:00
return GetChapter ( reader ) ;
2015-10-13 16:52:27 +00:00
}
}
2016-06-12 23:33:11 +00:00
return null ;
2015-10-13 16:52:27 +00:00
}
}
/// <summary>
/// Gets the chapter.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>ChapterInfo.</returns>
private ChapterInfo GetChapter ( IDataReader reader )
{
var chapter = new ChapterInfo
{
StartPositionTicks = reader . GetInt64 ( 0 )
} ;
if ( ! reader . IsDBNull ( 1 ) )
{
chapter . Name = reader . GetString ( 1 ) ;
}
if ( ! reader . IsDBNull ( 2 ) )
{
chapter . ImagePath = reader . GetString ( 2 ) ;
}
2016-07-06 17:44:44 +00:00
if ( ! reader . IsDBNull ( 3 ) )
{
chapter . ImageDateModified = reader . GetDateTime ( 3 ) . ToUniversalTime ( ) ;
}
2015-10-13 16:52:27 +00:00
return chapter ;
2013-06-18 19:16:27 +00:00
}
/// <summary>
/// Saves the chapters.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="chapters">The chapters.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>Task.</returns>
/// <exception cref="System.ArgumentNullException">
/// id
/// or
/// chapters
/// or
/// cancellationToken
/// </exception>
2016-06-11 20:12:01 +00:00
public async Task SaveChapters ( Guid id , List < ChapterInfo > chapters , CancellationToken cancellationToken )
2013-06-18 19:16:27 +00:00
{
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-10-13 16:52:27 +00:00
if ( id = = Guid . Empty )
{
throw new ArgumentNullException ( "id" ) ;
}
if ( chapters = = null )
{
throw new ArgumentNullException ( "chapters" ) ;
}
cancellationToken . ThrowIfCancellationRequested ( ) ;
2016-06-12 23:33:11 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
IDbTransaction transaction = null ;
try
2015-10-13 16:52:27 +00:00
{
2016-06-12 23:33:11 +00:00
transaction = _connection . BeginTransaction ( ) ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
// First delete chapters
_deleteChaptersCommand . GetParameter ( 0 ) . Value = id ;
_deleteChaptersCommand . Transaction = transaction ;
_deleteChaptersCommand . ExecuteNonQuery ( ) ;
var index = 0 ;
foreach ( var chapter in chapters )
2015-10-13 16:52:27 +00:00
{
2016-06-12 23:33:11 +00:00
cancellationToken . ThrowIfCancellationRequested ( ) ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
_saveChapterCommand . GetParameter ( 0 ) . Value = id ;
_saveChapterCommand . GetParameter ( 1 ) . Value = index ;
_saveChapterCommand . GetParameter ( 2 ) . Value = chapter . StartPositionTicks ;
_saveChapterCommand . GetParameter ( 3 ) . Value = chapter . Name ;
_saveChapterCommand . GetParameter ( 4 ) . Value = chapter . ImagePath ;
2016-07-06 17:44:44 +00:00
_saveChapterCommand . GetParameter ( 5 ) . Value = chapter . ImageDateModified ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
_saveChapterCommand . Transaction = transaction ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
_saveChapterCommand . ExecuteNonQuery ( ) ;
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
index + + ;
2015-10-13 16:52:27 +00:00
}
2016-06-12 23:33:11 +00:00
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
2015-10-13 16:52:27 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Rollback ( ) ;
}
throw ;
}
catch ( Exception e )
{
Logger . ErrorException ( "Failed to save chapters:" , e ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
2015-10-13 16:52:27 +00:00
}
2016-06-12 23:33:11 +00:00
throw ;
}
finally
{
if ( transaction ! = null )
2016-06-11 20:12:01 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Dispose ( ) ;
}
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
WriteLock . Release ( ) ;
}
}
2015-10-13 16:52:27 +00:00
2016-06-12 23:33:11 +00:00
protected override void CloseConnection ( )
{
if ( _connection ! = null )
{
if ( _connection . IsOpen ( ) )
2015-10-13 16:52:27 +00:00
{
2016-06-12 23:33:11 +00:00
_connection . Close ( ) ;
2015-10-13 16:52:27 +00:00
}
2016-06-12 23:33:11 +00:00
_connection . Dispose ( ) ;
_connection = null ;
2015-10-13 16:52:27 +00:00
}
2013-06-18 19:16:27 +00:00
}
2016-06-11 20:12:01 +00:00
private bool EnableJoinUserData ( InternalItemsQuery query )
2013-06-18 19:16:27 +00:00
{
2016-06-11 20:12:01 +00:00
if ( query . User = = null )
2016-05-08 06:31:08 +00:00
{
return false ;
}
2015-04-16 03:23:13 +00:00
2016-06-29 03:17:27 +00:00
if ( query . SimilarTo ! = null & & query . User ! = null )
2016-06-01 06:20:21 +00:00
{
return true ;
}
2016-05-08 06:31:08 +00:00
if ( query . SortBy ! = null & & query . SortBy . Length > 0 )
{
if ( query . SortBy . Contains ( ItemSortBy . IsFavoriteOrLiked , StringComparer . OrdinalIgnoreCase ) )
{
return true ;
}
if ( query . SortBy . Contains ( ItemSortBy . IsPlayed , StringComparer . OrdinalIgnoreCase ) )
{
return true ;
}
if ( query . SortBy . Contains ( ItemSortBy . IsUnplayed , StringComparer . OrdinalIgnoreCase ) )
{
return true ;
}
if ( query . SortBy . Contains ( ItemSortBy . PlayCount , StringComparer . OrdinalIgnoreCase ) )
{
return true ;
}
if ( query . SortBy . Contains ( ItemSortBy . DatePlayed , StringComparer . OrdinalIgnoreCase ) )
{
return true ;
}
}
if ( query . IsFavoriteOrLiked . HasValue )
{
return true ;
}
if ( query . IsFavorite . HasValue )
2015-04-16 03:23:13 +00:00
{
2016-05-08 06:31:08 +00:00
return true ;
}
2015-04-16 03:23:13 +00:00
2016-05-08 06:31:08 +00:00
if ( query . IsResumable . HasValue )
{
return true ;
}
2015-04-16 03:23:13 +00:00
2016-05-08 06:31:08 +00:00
if ( query . IsPlayed . HasValue )
{
return true ;
}
2015-04-16 03:23:13 +00:00
2016-05-08 06:31:08 +00:00
if ( query . IsLiked . HasValue )
{
return true ;
}
return false ;
}
2016-06-01 05:50:00 +00:00
private string [ ] GetFinalColumnsToSelect ( InternalItemsQuery query , string [ ] startColumns , IDbCommand cmd )
2016-05-08 06:31:08 +00:00
{
var list = startColumns . ToList ( ) ;
if ( EnableJoinUserData ( query ) )
{
2016-06-12 23:33:11 +00:00
list . Add ( "UserDataDb.UserData.UserId" ) ;
list . Add ( "UserDataDb.UserData.lastPlayedDate" ) ;
list . Add ( "UserDataDb.UserData.playbackPositionTicks" ) ;
list . Add ( "UserDataDb.UserData.playcount" ) ;
list . Add ( "UserDataDb.UserData.isFavorite" ) ;
list . Add ( "UserDataDb.UserData.played" ) ;
list . Add ( "UserDataDb.UserData.rating" ) ;
2016-05-08 06:31:08 +00:00
}
2016-06-01 05:50:00 +00:00
if ( query . SimilarTo ! = null )
{
var item = query . SimilarTo ;
var builder = new StringBuilder ( ) ;
2016-06-03 16:24:04 +00:00
builder . Append ( "(" ) ;
builder . Append ( "((OfficialRating=@ItemOfficialRating) * 10)" ) ;
//builder.Append("+ ((ProductionYear=@ItemProductionYear) * 10)");
2016-06-01 05:50:00 +00:00
2016-06-03 16:24:04 +00:00
builder . Append ( "+(Select Case When Abs(COALESCE(ProductionYear, 0) - @ItemProductionYear) < 10 Then 2 Else 0 End )" ) ;
builder . Append ( "+(Select Case When Abs(COALESCE(ProductionYear, 0) - @ItemProductionYear) < 5 Then 2 Else 0 End )" ) ;
2016-06-01 05:50:00 +00:00
2016-06-03 16:24:04 +00:00
//// genres
2016-06-26 16:21:10 +00:00
builder . Append ( "+ ((Select count(CleanValue) from ItemValues where ItemId=Guid and Type=2 and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId and type=2)) * 10)" ) ;
2016-06-01 05:50:00 +00:00
2016-06-03 16:24:04 +00:00
//// tags
2016-06-26 16:21:10 +00:00
builder . Append ( "+ ((Select count(CleanValue) from ItemValues where ItemId=Guid and Type=4 and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId and type=4)) * 10)" ) ;
2016-06-01 05:50:00 +00:00
2016-06-26 16:21:10 +00:00
builder . Append ( "+ ((Select count(CleanValue) from ItemValues where ItemId=Guid and Type=5 and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId and type=5)) * 10)" ) ;
2016-06-01 05:50:00 +00:00
2016-06-26 16:21:10 +00:00
builder . Append ( "+ ((Select count(CleanValue) from ItemValues where ItemId=Guid and Type=3 and CleanValue in (select CleanValue from itemvalues where ItemId=@SimilarItemId and type=3)) * 3)" ) ;
2016-06-01 05:50:00 +00:00
2016-06-03 16:24:04 +00:00
//builder.Append("+ ((Select count(Name) from People where ItemId=Guid and Name in (select Name from People where ItemId=@SimilarItemId)) * 3)");
2016-06-02 19:32:15 +00:00
2016-06-03 16:24:04 +00:00
////builder.Append("(select group_concat((Select Name from People where ItemId=Guid and Name in (Select Name from People where ItemId=@SimilarItemId)), '|'))");
2016-06-02 19:32:15 +00:00
2016-06-01 05:50:00 +00:00
builder . Append ( ") as SimilarityScore" ) ;
list . Add ( builder . ToString ( ) ) ;
cmd . Parameters . Add ( cmd , "@ItemOfficialRating" , DbType . String ) . Value = item . OfficialRating ;
2016-06-03 16:24:04 +00:00
cmd . Parameters . Add ( cmd , "@ItemProductionYear" , DbType . Int32 ) . Value = item . ProductionYear ? ? 0 ;
2016-06-02 19:32:15 +00:00
cmd . Parameters . Add ( cmd , "@SimilarItemId" , DbType . Guid ) . Value = item . Id ;
2016-06-01 05:50:00 +00:00
var excludeIds = query . ExcludeItemIds . ToList ( ) ;
excludeIds . Add ( item . Id . ToString ( "N" ) ) ;
query . ExcludeItemIds = excludeIds . ToArray ( ) ;
2016-06-02 04:41:12 +00:00
query . ExcludeProviderIds = item . ProviderIds ;
2016-06-01 05:50:00 +00:00
}
2016-05-08 06:31:08 +00:00
return list . ToArray ( ) ;
}
private string GetJoinUserDataText ( InternalItemsQuery query )
{
if ( ! EnableJoinUserData ( query ) )
{
return string . Empty ;
2015-04-16 03:23:13 +00:00
}
2016-05-08 06:31:08 +00:00
2016-06-24 15:12:03 +00:00
if ( _config . Configuration . SchemaVersion > = 96 )
{
return " left join UserDataDb.UserData on UserDataKey=UserDataDb.UserData.Key And (UserId=@UserId)" ;
}
2016-06-21 01:59:26 +00:00
return " left join UserDataDb.UserData on (select UserDataKey from UserDataKeys where ItemId=Guid order by Priority LIMIT 1)=UserDataDb.UserData.Key And (UserId=@UserId)" ;
2015-04-16 03:23:13 +00:00
}
2016-06-15 02:15:51 +00:00
private string GetGroupBy ( InternalItemsQuery query )
{
var groups = new List < string > ( ) ;
if ( EnableGroupByPresentationUniqueKey ( query ) )
{
groups . Add ( "PresentationUniqueKey" ) ;
}
if ( groups . Count > 0 )
{
return " Group by " + string . Join ( "," , groups . ToArray ( ) ) ;
}
return string . Empty ;
}
2016-06-28 04:47:30 +00:00
private string GetFromText ( string alias = "A" )
2016-06-15 02:15:51 +00:00
{
2016-06-28 04:47:30 +00:00
return " from TypedBaseItems " + alias ;
2016-06-15 02:15:51 +00:00
}
2016-06-20 22:07:18 +00:00
public List < BaseItem > GetItemList ( InternalItemsQuery query )
2015-12-27 18:37:06 +00:00
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
2016-05-01 22:11:24 +00:00
var now = DateTime . UtcNow ;
2016-06-18 17:26:42 +00:00
var list = new List < BaseItem > ( ) ;
2016-06-29 03:17:27 +00:00
// Hack for right now since we currently don't support filtering out these duplicates within a query
if ( query . Limit . HasValue & & query . EnableGroupByMetadataKey )
{
query . Limit = query . Limit . Value + 4 ;
}
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-12-27 18:37:06 +00:00
{
2016-06-15 02:15:51 +00:00
cmd . CommandText = "select " + string . Join ( "," , GetFinalColumnsToSelect ( query , _retriveItemColumns , cmd ) ) + GetFromText ( ) ;
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetJoinUserDataText ( query ) ;
2016-05-08 06:31:08 +00:00
if ( EnableJoinUserData ( query ) )
{
2016-06-12 23:33:11 +00:00
cmd . Parameters . Add ( cmd , "@UserId" , DbType . Guid ) . Value = query . User . Id ;
2016-05-08 06:31:08 +00:00
}
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
var whereClauses = GetWhereClauses ( query , cmd ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = whereText ;
2015-12-27 18:37:06 +00:00
2016-06-15 02:15:51 +00:00
cmd . CommandText + = GetGroupBy ( query ) ;
2016-05-01 22:11:24 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetOrderByText ( query ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
if ( query . Limit . HasValue | | query . StartIndex . HasValue )
{
2016-06-22 20:08:07 +00:00
var offset = query . StartIndex ? ? 0 ;
2016-05-08 06:31:08 +00:00
2016-06-22 20:08:07 +00:00
if ( query . Limit . HasValue | | offset > 0 )
{
cmd . CommandText + = " LIMIT " + ( query . Limit ? ? int . MaxValue ) . ToString ( CultureInfo . InvariantCulture ) ;
}
2016-05-08 06:31:08 +00:00
2016-06-22 20:08:07 +00:00
if ( offset > 0 )
2016-05-08 06:31:08 +00:00
{
2016-06-22 20:08:07 +00:00
cmd . CommandText + = " OFFSET " + offset . ToString ( CultureInfo . InvariantCulture ) ;
2016-06-11 20:12:01 +00:00
}
2016-06-12 23:33:11 +00:00
}
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
LogQueryTime ( "GetItemList" , cmd , now ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
while ( reader . Read ( ) )
{
var item = GetItem ( reader ) ;
if ( item ! = null )
2015-12-27 18:37:06 +00:00
{
2016-06-18 17:26:42 +00:00
list . Add ( item ) ;
2015-12-27 18:37:06 +00:00
}
}
}
}
2016-06-18 17:26:42 +00:00
2016-06-29 03:17:27 +00:00
// Hack for right now since we currently don't support filtering out these duplicates within a query
if ( query . EnableGroupByMetadataKey )
{
var limit = query . Limit ? ? int . MaxValue ;
limit - = 4 ;
var newList = new List < BaseItem > ( ) ;
foreach ( var item in list )
{
AddItem ( newList , item ) ;
if ( newList . Count > = limit )
{
break ;
}
}
list = newList ;
}
2016-06-18 17:26:42 +00:00
return list ;
2015-12-27 18:37:06 +00:00
}
2016-06-29 03:17:27 +00:00
private void AddItem ( List < BaseItem > items , BaseItem newItem )
{
var providerIds = newItem . ProviderIds . ToList ( ) ;
for ( var i = 0 ; i < items . Count ; i + + )
{
var item = items [ i ] ;
foreach ( var providerId in providerIds )
{
if ( providerId . Key = = MetadataProviders . TmdbCollection . ToString ( ) )
{
continue ;
}
if ( item . GetProviderId ( providerId . Key ) = = providerId . Value )
{
if ( newItem . SourceType = = SourceType . Library )
{
items [ i ] = newItem ;
}
return ;
}
}
}
items . Add ( newItem ) ;
}
2016-05-15 18:52:36 +00:00
private void LogQueryTime ( string methodName , IDbCommand cmd , DateTime startDate )
{
var elapsed = ( DateTime . UtcNow - startDate ) . TotalMilliseconds ;
2016-05-25 00:22:41 +00:00
var slowThreshold = 1000 ;
#if DEBUG
2016-06-24 15:12:03 +00:00
slowThreshold = 50 ;
2016-05-25 00:22:41 +00:00
#endif
if ( elapsed > = slowThreshold )
2016-05-15 18:52:36 +00:00
{
Logger . Debug ( "{2} query time (slow): {0}ms. Query: {1}" ,
Convert . ToInt32 ( elapsed ) ,
cmd . CommandText ,
methodName ) ;
}
else
{
2016-06-26 16:23:27 +00:00
//Logger.Debug("{2} query time: {0}ms. Query: {1}",
// Convert.ToInt32(elapsed),
// cmd.CommandText,
// methodName);
2016-05-15 18:52:36 +00:00
}
}
2015-06-01 14:49:23 +00:00
public QueryResult < BaseItem > GetItems ( InternalItemsQuery query )
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
2016-06-20 22:07:18 +00:00
if ( ! query . EnableTotalRecordCount | | ( ! query . Limit . HasValue & & ( query . StartIndex ? ? 0 ) = = 0 ) )
{
var list = GetItemList ( query ) ;
return new QueryResult < BaseItem >
{
Items = list . ToArray ( ) ,
TotalRecordCount = list . Count
} ;
}
2016-05-01 22:11:24 +00:00
var now = DateTime . UtcNow ;
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-06-01 14:49:23 +00:00
{
2016-06-15 02:15:51 +00:00
cmd . CommandText = "select " + string . Join ( "," , GetFinalColumnsToSelect ( query , _retriveItemColumns , cmd ) ) + GetFromText ( ) ;
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetJoinUserDataText ( query ) ;
2016-05-08 06:31:08 +00:00
if ( EnableJoinUserData ( query ) )
{
2016-06-12 23:33:11 +00:00
cmd . Parameters . Add ( cmd , "@UserId" , DbType . Guid ) . Value = query . User . Id ;
2016-05-08 06:31:08 +00:00
}
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
var whereClauses = GetWhereClauses ( query , cmd ) ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
var whereTextWithoutPaging = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = whereText ;
2016-06-11 20:12:01 +00:00
2016-06-15 02:15:51 +00:00
cmd . CommandText + = GetGroupBy ( query ) ;
2015-08-25 03:13:04 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetOrderByText ( query ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
if ( query . Limit . HasValue | | query . StartIndex . HasValue )
{
2016-06-22 20:08:07 +00:00
var offset = query . StartIndex ? ? 0 ;
2016-05-08 06:31:08 +00:00
2016-06-22 20:08:07 +00:00
if ( query . Limit . HasValue | | offset > 0 )
{
cmd . CommandText + = " LIMIT " + ( query . Limit ? ? int . MaxValue ) . ToString ( CultureInfo . InvariantCulture ) ;
}
2016-05-08 06:31:08 +00:00
2016-06-22 20:08:07 +00:00
if ( offset > 0 )
2016-05-08 06:31:08 +00:00
{
2016-06-22 20:08:07 +00:00
cmd . CommandText + = " OFFSET " + offset . ToString ( CultureInfo . InvariantCulture ) ;
2016-05-08 06:31:08 +00:00
}
2016-06-12 23:33:11 +00:00
}
2015-06-01 14:49:23 +00:00
2016-06-15 18:56:37 +00:00
cmd . CommandText + = ";" ;
var isReturningZeroItems = query . Limit . HasValue & & query . Limit < = 0 ;
if ( isReturningZeroItems )
{
cmd . CommandText = "" ;
}
2016-06-12 23:33:11 +00:00
if ( EnableGroupByPresentationUniqueKey ( query ) )
{
2016-06-15 18:56:37 +00:00
cmd . CommandText + = " select count (distinct PresentationUniqueKey)" + GetFromText ( ) ;
2016-06-12 23:33:11 +00:00
}
else
{
2016-06-15 18:56:37 +00:00
cmd . CommandText + = " select count (guid)" + GetFromText ( ) ;
2016-06-12 23:33:11 +00:00
}
2015-08-26 18:17:38 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetJoinUserDataText ( query ) ;
cmd . CommandText + = whereTextWithoutPaging ;
2016-05-08 06:31:08 +00:00
2016-06-12 23:33:11 +00:00
var list = new List < BaseItem > ( ) ;
var count = 0 ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess ) )
{
LogQueryTime ( "GetItems" , cmd , now ) ;
2016-05-01 22:11:24 +00:00
2016-06-15 18:56:37 +00:00
if ( isReturningZeroItems )
2016-06-12 23:33:11 +00:00
{
2016-06-15 18:56:37 +00:00
if ( reader . Read ( ) )
2015-07-02 05:08:05 +00:00
{
2016-06-15 18:56:37 +00:00
count = reader . GetInt32 ( 0 ) ;
2015-07-02 05:08:05 +00:00
}
2015-06-01 14:49:23 +00:00
}
2016-06-15 18:56:37 +00:00
else
2015-06-01 14:49:23 +00:00
{
2016-06-15 18:56:37 +00:00
while ( reader . Read ( ) )
{
var item = GetItem ( reader ) ;
if ( item ! = null )
{
list . Add ( item ) ;
}
}
if ( reader . NextResult ( ) & & reader . Read ( ) )
{
count = reader . GetInt32 ( 0 ) ;
}
2016-06-12 23:33:11 +00:00
}
2015-06-01 14:49:23 +00:00
}
2016-06-12 23:33:11 +00:00
return new QueryResult < BaseItem > ( )
{
Items = list . ToArray ( ) ,
TotalRecordCount = count
} ;
2015-06-01 14:49:23 +00:00
}
}
2015-08-25 03:13:04 +00:00
private string GetOrderByText ( InternalItemsQuery query )
{
2016-06-01 05:50:00 +00:00
if ( query . SimilarTo ! = null )
{
if ( query . SortBy = = null | | query . SortBy . Length = = 0 )
{
2016-06-01 06:20:21 +00:00
if ( query . User ! = null )
{
2016-08-16 00:22:59 +00:00
query . SortBy = new [ ] { "SimilarityScore" , ItemSortBy . Random } ;
2016-06-01 06:20:21 +00:00
}
else
{
2016-06-21 01:59:26 +00:00
query . SortBy = new [ ] { "SimilarityScore" , ItemSortBy . Random } ;
2016-06-01 06:20:21 +00:00
}
2016-06-01 05:50:00 +00:00
query . SortOrder = SortOrder . Descending ;
}
}
2015-08-25 03:13:04 +00:00
if ( query . SortBy = = null | | query . SortBy . Length = = 0 )
{
return string . Empty ;
}
2016-05-08 06:31:08 +00:00
var isAscending = query . SortOrder ! = SortOrder . Descending ;
2015-08-25 03:13:04 +00:00
2016-05-08 06:31:08 +00:00
return " ORDER BY " + string . Join ( "," , query . SortBy . Select ( i = >
{
2016-06-15 03:12:32 +00:00
var columnMap = MapOrderByField ( i , query ) ;
2016-05-08 06:31:08 +00:00
var columnAscending = isAscending ;
if ( columnMap . Item2 )
{
columnAscending = ! columnAscending ;
}
var sortOrder = columnAscending ? "ASC" : "DESC" ;
return columnMap . Item1 + " " + sortOrder ;
} ) . ToArray ( ) ) ;
2015-08-25 03:13:04 +00:00
}
2016-06-15 03:12:32 +00:00
private Tuple < string , bool > MapOrderByField ( string name , InternalItemsQuery query )
2015-08-25 03:13:04 +00:00
{
2016-03-20 06:46:51 +00:00
if ( string . Equals ( name , ItemSortBy . AirTime , StringComparison . OrdinalIgnoreCase ) )
2015-12-27 18:37:06 +00:00
{
// TODO
2016-05-08 06:31:08 +00:00
return new Tuple < string , bool > ( "SortName" , false ) ;
2015-12-27 18:37:06 +00:00
}
2016-03-20 06:46:51 +00:00
if ( string . Equals ( name , ItemSortBy . Runtime , StringComparison . OrdinalIgnoreCase ) )
{
2016-05-08 06:31:08 +00:00
return new Tuple < string , bool > ( "RuntimeTicks" , false ) ;
}
if ( string . Equals ( name , ItemSortBy . Random , StringComparison . OrdinalIgnoreCase ) )
{
return new Tuple < string , bool > ( "RANDOM()" , false ) ;
}
if ( string . Equals ( name , ItemSortBy . DatePlayed , StringComparison . OrdinalIgnoreCase ) )
{
return new Tuple < string , bool > ( "LastPlayedDate" , false ) ;
}
if ( string . Equals ( name , ItemSortBy . PlayCount , StringComparison . OrdinalIgnoreCase ) )
{
return new Tuple < string , bool > ( "PlayCount" , false ) ;
}
if ( string . Equals ( name , ItemSortBy . IsFavoriteOrLiked , StringComparison . OrdinalIgnoreCase ) )
{
return new Tuple < string , bool > ( "IsFavorite" , true ) ;
2016-03-20 06:46:51 +00:00
}
2016-04-27 17:52:43 +00:00
if ( string . Equals ( name , ItemSortBy . IsFolder , StringComparison . OrdinalIgnoreCase ) )
{
2016-05-08 06:31:08 +00:00
return new Tuple < string , bool > ( "IsFolder" , true ) ;
2016-04-27 17:52:43 +00:00
}
2016-05-08 06:31:08 +00:00
if ( string . Equals ( name , ItemSortBy . IsPlayed , StringComparison . OrdinalIgnoreCase ) )
{
return new Tuple < string , bool > ( "played" , true ) ;
}
if ( string . Equals ( name , ItemSortBy . IsUnplayed , StringComparison . OrdinalIgnoreCase ) )
2016-03-20 17:52:36 +00:00
{
2016-05-08 06:31:08 +00:00
return new Tuple < string , bool > ( "played" , false ) ;
2016-03-20 17:52:36 +00:00
}
2016-05-09 03:13:38 +00:00
if ( string . Equals ( name , ItemSortBy . DateLastContentAdded , StringComparison . OrdinalIgnoreCase ) )
{
return new Tuple < string , bool > ( "DateLastMediaAdded" , false ) ;
}
2016-05-18 05:34:10 +00:00
if ( string . Equals ( name , ItemSortBy . Artist , StringComparison . OrdinalIgnoreCase ) )
{
2016-06-26 16:21:10 +00:00
return new Tuple < string , bool > ( "(select CleanValue from itemvalues where ItemId=Guid and Type=0 LIMIT 1)" , false ) ;
2016-05-18 05:34:10 +00:00
}
if ( string . Equals ( name , ItemSortBy . AlbumArtist , StringComparison . OrdinalIgnoreCase ) )
{
2016-06-26 16:21:10 +00:00
return new Tuple < string , bool > ( "(select CleanValue from itemvalues where ItemId=Guid and Type=1 LIMIT 1)" , false ) ;
2016-05-18 05:34:10 +00:00
}
2016-06-01 06:01:43 +00:00
if ( string . Equals ( name , ItemSortBy . OfficialRating , StringComparison . OrdinalIgnoreCase ) )
{
2016-08-10 19:16:09 +00:00
return new Tuple < string , bool > ( "InheritedParentalRatingValue" , false ) ;
2016-06-01 06:01:43 +00:00
}
if ( string . Equals ( name , ItemSortBy . Studio , StringComparison . OrdinalIgnoreCase ) )
{
2016-06-26 16:21:10 +00:00
return new Tuple < string , bool > ( "(select CleanValue from itemvalues where ItemId=Guid and Type=3 LIMIT 1)" , false ) ;
2016-06-01 06:01:43 +00:00
}
2016-06-15 03:12:32 +00:00
if ( string . Equals ( name , ItemSortBy . SeriesDatePlayed , StringComparison . OrdinalIgnoreCase ) )
{
2016-06-17 13:06:13 +00:00
return new Tuple < string , bool > ( "(Select MAX(LastPlayedDate) from TypedBaseItems B" + GetJoinUserDataText ( query ) + " where B.Guid in (Select ItemId from AncestorIds where AncestorId in (select guid from typedbaseitems c where C.Type = 'MediaBrowser.Controller.Entities.TV.Series' And C.Guid in (Select AncestorId from AncestorIds where ItemId=A.Guid))))" , false ) ;
2016-06-15 03:12:32 +00:00
}
2015-12-27 18:37:06 +00:00
2016-05-08 06:31:08 +00:00
return new Tuple < string , bool > ( name , false ) ;
2015-08-25 03:13:04 +00:00
}
2015-06-01 14:49:23 +00:00
public List < Guid > GetItemIdsList ( InternalItemsQuery query )
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
2016-05-01 22:11:24 +00:00
var now = DateTime . UtcNow ;
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-06-01 14:49:23 +00:00
{
2016-06-15 02:15:51 +00:00
cmd . CommandText = "select " + string . Join ( "," , GetFinalColumnsToSelect ( query , new [ ] { "guid" } , cmd ) ) + GetFromText ( ) ;
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetJoinUserDataText ( query ) ;
2016-05-08 06:31:08 +00:00
if ( EnableJoinUserData ( query ) )
{
2016-06-12 23:33:11 +00:00
cmd . Parameters . Add ( cmd , "@UserId" , DbType . Guid ) . Value = query . User . Id ;
2016-05-08 06:31:08 +00:00
}
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
var whereClauses = GetWhereClauses ( query , cmd ) ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = whereText ;
2015-06-01 14:49:23 +00:00
2016-06-15 02:15:51 +00:00
cmd . CommandText + = GetGroupBy ( query ) ;
2016-05-01 22:11:24 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetOrderByText ( query ) ;
2015-08-25 03:13:04 +00:00
2016-06-12 23:33:11 +00:00
if ( query . Limit . HasValue | | query . StartIndex . HasValue )
{
2016-06-22 20:08:07 +00:00
var offset = query . StartIndex ? ? 0 ;
2016-05-08 06:31:08 +00:00
2016-06-22 20:08:07 +00:00
if ( query . Limit . HasValue | | offset > 0 )
{
cmd . CommandText + = " LIMIT " + ( query . Limit ? ? int . MaxValue ) . ToString ( CultureInfo . InvariantCulture ) ;
}
2016-05-08 06:31:08 +00:00
2016-06-22 20:08:07 +00:00
if ( offset > 0 )
2016-05-08 06:31:08 +00:00
{
2016-06-22 20:08:07 +00:00
cmd . CommandText + = " OFFSET " + offset . ToString ( CultureInfo . InvariantCulture ) ;
2016-06-11 20:12:01 +00:00
}
2016-06-12 23:33:11 +00:00
}
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
var list = new List < Guid > ( ) ;
2016-05-01 22:11:24 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
LogQueryTime ( "GetItemIdsList" , cmd , now ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
while ( reader . Read ( ) )
{
list . Add ( reader . GetGuid ( 0 ) ) ;
2015-06-01 14:49:23 +00:00
}
2016-06-11 20:12:01 +00:00
}
2016-06-12 23:33:11 +00:00
return list ;
2015-06-01 14:49:23 +00:00
}
}
2015-09-16 17:16:39 +00:00
public QueryResult < Tuple < Guid , string > > GetItemIdsWithPath ( InternalItemsQuery query )
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-09-16 17:16:39 +00:00
{
2016-06-12 23:33:11 +00:00
cmd . CommandText = "select guid,path from TypedBaseItems" ;
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
var whereClauses = GetWhereClauses ( query , cmd ) ;
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
var whereTextWithoutPaging = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = whereText ;
2015-09-16 17:16:39 +00:00
2016-06-15 02:15:51 +00:00
cmd . CommandText + = GetGroupBy ( query ) ;
2016-05-01 22:11:24 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetOrderByText ( query ) ;
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
if ( query . Limit . HasValue | | query . StartIndex . HasValue )
{
2016-06-22 20:08:07 +00:00
var offset = query . StartIndex ? ? 0 ;
2016-05-08 06:31:08 +00:00
2016-06-22 20:08:07 +00:00
if ( query . Limit . HasValue | | offset > 0 )
{
cmd . CommandText + = " LIMIT " + ( query . Limit ? ? int . MaxValue ) . ToString ( CultureInfo . InvariantCulture ) ;
}
2016-05-08 06:31:08 +00:00
2016-06-22 20:08:07 +00:00
if ( offset > 0 )
2016-06-12 23:33:11 +00:00
{
2016-06-22 20:08:07 +00:00
cmd . CommandText + = " OFFSET " + offset . ToString ( CultureInfo . InvariantCulture ) ;
2016-05-08 06:31:08 +00:00
}
2016-06-12 23:33:11 +00:00
}
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = "; select count (guid) from TypedBaseItems" + whereTextWithoutPaging ;
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
var list = new List < Tuple < Guid , string > > ( ) ;
var count = 0 ;
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
Logger . Debug ( cmd . CommandText ) ;
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess ) )
{
while ( reader . Read ( ) )
2015-09-16 17:16:39 +00:00
{
2016-06-12 23:33:11 +00:00
var id = reader . GetGuid ( 0 ) ;
string path = null ;
2015-09-16 17:16:39 +00:00
2016-06-12 23:33:11 +00:00
if ( ! reader . IsDBNull ( 1 ) )
2015-09-16 17:16:39 +00:00
{
2016-06-12 23:33:11 +00:00
path = reader . GetString ( 1 ) ;
2015-09-16 17:16:39 +00:00
}
2016-06-12 23:33:11 +00:00
list . Add ( new Tuple < Guid , string > ( id , path ) ) ;
2015-09-16 17:16:39 +00:00
}
2016-06-12 23:33:11 +00:00
if ( reader . NextResult ( ) & & reader . Read ( ) )
2015-09-16 17:16:39 +00:00
{
2016-06-12 23:33:11 +00:00
count = reader . GetInt32 ( 0 ) ;
}
2015-09-16 17:16:39 +00:00
}
2016-06-12 23:33:11 +00:00
return new QueryResult < Tuple < Guid , string > > ( )
{
Items = list . ToArray ( ) ,
TotalRecordCount = count
} ;
2015-09-16 17:16:39 +00:00
}
}
2015-06-01 14:49:23 +00:00
public QueryResult < Guid > GetItemIds ( InternalItemsQuery query )
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
2016-06-20 22:07:18 +00:00
if ( ! query . EnableTotalRecordCount | | ( ! query . Limit . HasValue & & ( query . StartIndex ? ? 0 ) = = 0 ) )
{
var list = GetItemIdsList ( query ) ;
return new QueryResult < Guid >
{
Items = list . ToArray ( ) ,
TotalRecordCount = list . Count
} ;
}
2016-05-01 22:11:24 +00:00
var now = DateTime . UtcNow ;
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-06-01 14:49:23 +00:00
{
2016-06-15 02:15:51 +00:00
cmd . CommandText = "select " + string . Join ( "," , GetFinalColumnsToSelect ( query , new [ ] { "guid" } , cmd ) ) + GetFromText ( ) ;
2016-06-12 23:33:11 +00:00
var whereClauses = GetWhereClauses ( query , cmd ) ;
cmd . CommandText + = GetJoinUserDataText ( query ) ;
2016-05-08 06:31:08 +00:00
if ( EnableJoinUserData ( query ) )
{
2016-06-12 23:33:11 +00:00
cmd . Parameters . Add ( cmd , "@UserId" , DbType . Guid ) . Value = query . User . Id ;
2016-05-08 06:31:08 +00:00
}
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
2016-05-01 22:11:24 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = whereText ;
2015-08-25 03:13:04 +00:00
2016-06-15 02:15:51 +00:00
cmd . CommandText + = GetGroupBy ( query ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetOrderByText ( query ) ;
2016-05-08 06:31:08 +00:00
2016-06-12 23:33:11 +00:00
if ( query . Limit . HasValue | | query . StartIndex . HasValue )
{
2016-06-22 20:08:07 +00:00
var offset = query . StartIndex ? ? 0 ;
2016-06-12 23:33:11 +00:00
2016-06-22 20:08:07 +00:00
if ( query . Limit . HasValue | | offset > 0 )
{
cmd . CommandText + = " LIMIT " + ( query . Limit ? ? int . MaxValue ) . ToString ( CultureInfo . InvariantCulture ) ;
}
2016-05-08 06:31:08 +00:00
2016-06-22 20:08:07 +00:00
if ( offset > 0 )
2016-05-08 06:31:08 +00:00
{
2016-06-22 20:08:07 +00:00
cmd . CommandText + = " OFFSET " + offset . ToString ( CultureInfo . InvariantCulture ) ;
2016-05-08 06:31:08 +00:00
}
2016-06-12 23:33:11 +00:00
}
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
if ( EnableGroupByPresentationUniqueKey ( query ) )
{
2016-06-15 02:15:51 +00:00
cmd . CommandText + = "; select count (distinct PresentationUniqueKey)" + GetFromText ( ) ;
2016-06-12 23:33:11 +00:00
}
else
{
2016-06-15 02:15:51 +00:00
cmd . CommandText + = "; select count (guid)" + GetFromText ( ) ;
2016-06-12 23:33:11 +00:00
}
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = GetJoinUserDataText ( query ) ;
cmd . CommandText + = whereText ;
2016-05-08 06:31:08 +00:00
2016-06-12 23:33:11 +00:00
var list = new List < Guid > ( ) ;
var count = 0 ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess ) )
{
LogQueryTime ( "GetItemIds" , cmd , now ) ;
2016-05-01 22:11:24 +00:00
2016-06-12 23:33:11 +00:00
while ( reader . Read ( ) )
2016-06-11 20:12:01 +00:00
{
2016-06-12 23:33:11 +00:00
list . Add ( reader . GetGuid ( 0 ) ) ;
2016-06-11 20:12:01 +00:00
}
2016-06-12 23:33:11 +00:00
if ( reader . NextResult ( ) & & reader . Read ( ) )
2015-06-01 14:49:23 +00:00
{
2016-06-12 23:33:11 +00:00
count = reader . GetInt32 ( 0 ) ;
2015-06-01 14:49:23 +00:00
}
2016-06-11 20:12:01 +00:00
}
2016-06-12 23:33:11 +00:00
return new QueryResult < Guid > ( )
{
Items = list . ToArray ( ) ,
TotalRecordCount = count
} ;
2015-06-01 14:49:23 +00:00
}
}
2016-06-17 13:06:13 +00:00
private List < string > GetWhereClauses ( InternalItemsQuery query , IDbCommand cmd , string paramSuffix = "" )
2015-06-01 14:49:23 +00:00
{
var whereClauses = new List < string > ( ) ;
2016-05-09 04:56:41 +00:00
if ( EnableJoinUserData ( query ) )
{
2016-06-21 01:59:26 +00:00
//whereClauses.Add("(UserId is null or UserId=@UserId)");
2016-05-09 04:56:41 +00:00
}
2015-08-26 05:10:04 +00:00
if ( query . IsCurrentSchema . HasValue )
{
if ( query . IsCurrentSchema . Value )
{
whereClauses . Add ( "(SchemaVersion not null AND SchemaVersion=@SchemaVersion)" ) ;
}
else
{
whereClauses . Add ( "(SchemaVersion is null or SchemaVersion<>@SchemaVersion)" ) ;
}
cmd . Parameters . Add ( cmd , "@SchemaVersion" , DbType . Int32 ) . Value = LatestSchemaVersion ;
}
2016-03-20 06:46:51 +00:00
if ( query . IsHD . HasValue )
{
whereClauses . Add ( "IsHD=@IsHD" ) ;
cmd . Parameters . Add ( cmd , "@IsHD" , DbType . Boolean ) . Value = query . IsHD ;
}
if ( query . IsLocked . HasValue )
{
whereClauses . Add ( "IsLocked=@IsLocked" ) ;
cmd . Parameters . Add ( cmd , "@IsLocked" , DbType . Boolean ) . Value = query . IsLocked ;
}
2015-09-16 17:16:39 +00:00
if ( query . IsOffline . HasValue )
{
whereClauses . Add ( "IsOffline=@IsOffline" ) ;
cmd . Parameters . Add ( cmd , "@IsOffline" , DbType . Boolean ) . Value = query . IsOffline ;
}
2015-06-01 14:49:23 +00:00
if ( query . IsMovie . HasValue )
{
2016-05-30 18:16:44 +00:00
var alternateTypes = new List < string > ( ) ;
if ( query . IncludeItemTypes . Length = = 0 | | query . IncludeItemTypes . Contains ( typeof ( Movie ) . Name ) )
{
alternateTypes . Add ( typeof ( Movie ) . FullName ) ;
}
if ( query . IncludeItemTypes . Length = = 0 | | query . IncludeItemTypes . Contains ( typeof ( Trailer ) . Name ) )
{
alternateTypes . Add ( typeof ( Trailer ) . FullName ) ;
}
if ( alternateTypes . Count = = 0 )
{
whereClauses . Add ( "IsMovie=@IsMovie" ) ;
}
else
{
2016-06-01 05:50:00 +00:00
whereClauses . Add ( "(IsMovie is null OR IsMovie=@IsMovie)" ) ;
2016-05-30 18:16:44 +00:00
}
2015-06-01 14:49:23 +00:00
cmd . Parameters . Add ( cmd , "@IsMovie" , DbType . Boolean ) . Value = query . IsMovie ;
}
2015-06-01 17:49:11 +00:00
if ( query . IsKids . HasValue )
{
whereClauses . Add ( "IsKids=@IsKids" ) ;
cmd . Parameters . Add ( cmd , "@IsKids" , DbType . Boolean ) . Value = query . IsKids ;
}
2015-06-01 14:49:23 +00:00
if ( query . IsSports . HasValue )
{
whereClauses . Add ( "IsSports=@IsSports" ) ;
cmd . Parameters . Add ( cmd , "@IsSports" , DbType . Boolean ) . Value = query . IsSports ;
}
2015-12-27 18:37:06 +00:00
if ( query . IsFolder . HasValue )
{
whereClauses . Add ( "IsFolder=@IsFolder" ) ;
cmd . Parameters . Add ( cmd , "@IsFolder" , DbType . Boolean ) . Value = query . IsFolder ;
}
2015-06-01 17:07:55 +00:00
2016-06-12 05:03:52 +00:00
var includeTypes = query . IncludeItemTypes . SelectMany ( MapIncludeItemTypes ) . ToArray ( ) ;
if ( includeTypes . Length = = 1 )
{
2016-06-17 13:06:13 +00:00
whereClauses . Add ( "type=@type" + paramSuffix ) ;
cmd . Parameters . Add ( cmd , "@type" + paramSuffix , DbType . String ) . Value = includeTypes [ 0 ] ;
2016-06-12 05:03:52 +00:00
}
else if ( includeTypes . Length > 1 )
{
var inClause = string . Join ( "," , includeTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( string . Format ( "type in ({0})" , inClause ) ) ;
}
2016-06-12 23:33:11 +00:00
var excludeTypes = query . ExcludeItemTypes . SelectMany ( MapIncludeItemTypes ) . ToArray ( ) ;
if ( excludeTypes . Length = = 1 )
{
whereClauses . Add ( "type<>@type" ) ;
cmd . Parameters . Add ( cmd , "@type" , DbType . String ) . Value = excludeTypes [ 0 ] ;
}
else if ( excludeTypes . Length > 1 )
{
var inClause = string . Join ( "," , excludeTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( string . Format ( "type not in ({0})" , inClause ) ) ;
}
2015-06-01 14:49:23 +00:00
if ( query . ChannelIds . Length = = 1 )
{
whereClauses . Add ( "ChannelId=@ChannelId" ) ;
cmd . Parameters . Add ( cmd , "@ChannelId" , DbType . String ) . Value = query . ChannelIds [ 0 ] ;
}
if ( query . ChannelIds . Length > 1 )
{
var inClause = string . Join ( "," , query . ChannelIds . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( string . Format ( "ChannelId in ({0})" , inClause ) ) ;
}
2015-09-24 02:31:40 +00:00
if ( query . ParentId . HasValue )
{
whereClauses . Add ( "ParentId=@ParentId" ) ;
cmd . Parameters . Add ( cmd , "@ParentId" , DbType . Guid ) . Value = query . ParentId . Value ;
}
2016-03-01 19:39:46 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . Path ) )
{
whereClauses . Add ( "Path=@Path" ) ;
cmd . Parameters . Add ( cmd , "@Path" , DbType . String ) . Value = query . Path ;
}
2016-05-02 05:32:04 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . PresentationUniqueKey ) )
{
whereClauses . Add ( "PresentationUniqueKey=@PresentationUniqueKey" ) ;
cmd . Parameters . Add ( cmd , "@PresentationUniqueKey" , DbType . String ) . Value = query . PresentationUniqueKey ;
}
2016-03-20 06:46:51 +00:00
if ( query . MinCommunityRating . HasValue )
{
whereClauses . Add ( "CommunityRating>=@MinCommunityRating" ) ;
cmd . Parameters . Add ( cmd , "@MinCommunityRating" , DbType . Double ) . Value = query . MinCommunityRating . Value ;
}
if ( query . MinIndexNumber . HasValue )
{
whereClauses . Add ( "IndexNumber>=@MinIndexNumber" ) ;
cmd . Parameters . Add ( cmd , "@MinIndexNumber" , DbType . Int32 ) . Value = query . MinIndexNumber . Value ;
}
//if (query.MinPlayers.HasValue)
//{
// whereClauses.Add("Players>=@MinPlayers");
// cmd.Parameters.Add(cmd, "@MinPlayers", DbType.Int32).Value = query.MinPlayers.Value;
//}
//if (query.MaxPlayers.HasValue)
//{
// whereClauses.Add("Players<=@MaxPlayers");
// cmd.Parameters.Add(cmd, "@MaxPlayers", DbType.Int32).Value = query.MaxPlayers.Value;
//}
2016-05-04 16:32:34 +00:00
if ( query . IndexNumber . HasValue )
{
whereClauses . Add ( "IndexNumber=@IndexNumber" ) ;
cmd . Parameters . Add ( cmd , "@IndexNumber" , DbType . Int32 ) . Value = query . IndexNumber . Value ;
}
2016-03-20 19:53:22 +00:00
if ( query . ParentIndexNumber . HasValue )
{
2016-05-04 16:32:34 +00:00
whereClauses . Add ( "ParentIndexNumber=@ParentIndexNumber" ) ;
2016-03-20 19:53:22 +00:00
cmd . Parameters . Add ( cmd , "@ParentIndexNumber" , DbType . Int32 ) . Value = query . ParentIndexNumber . Value ;
}
2016-06-15 02:15:51 +00:00
if ( query . ParentIndexNumberNotEquals . HasValue )
{
2016-06-15 18:56:37 +00:00
whereClauses . Add ( "(ParentIndexNumber<>@ParentIndexNumberNotEquals or ParentIndexNumber is null)" ) ;
cmd . Parameters . Add ( cmd , "@ParentIndexNumberNotEquals" , DbType . Int32 ) . Value = query . ParentIndexNumberNotEquals . Value ;
2016-06-15 02:15:51 +00:00
}
2015-06-01 14:49:23 +00:00
if ( query . MinEndDate . HasValue )
{
whereClauses . Add ( "EndDate>=@MinEndDate" ) ;
cmd . Parameters . Add ( cmd , "@MinEndDate" , DbType . Date ) . Value = query . MinEndDate . Value ;
}
if ( query . MaxEndDate . HasValue )
{
whereClauses . Add ( "EndDate<=@MaxEndDate" ) ;
cmd . Parameters . Add ( cmd , "@MaxEndDate" , DbType . Date ) . Value = query . MaxEndDate . Value ;
}
if ( query . MinStartDate . HasValue )
{
whereClauses . Add ( "StartDate>=@MinStartDate" ) ;
cmd . Parameters . Add ( cmd , "@MinStartDate" , DbType . Date ) . Value = query . MinStartDate . Value ;
}
2016-03-20 06:46:51 +00:00
if ( query . MaxStartDate . HasValue )
{
whereClauses . Add ( "StartDate<=@MaxStartDate" ) ;
cmd . Parameters . Add ( cmd , "@MaxStartDate" , DbType . Date ) . Value = query . MaxStartDate . Value ;
}
2015-12-27 18:37:06 +00:00
if ( query . MinPremiereDate . HasValue )
{
whereClauses . Add ( "PremiereDate>=@MinPremiereDate" ) ;
cmd . Parameters . Add ( cmd , "@MinPremiereDate" , DbType . Date ) . Value = query . MinPremiereDate . Value ;
}
2016-03-20 06:46:51 +00:00
if ( query . MaxPremiereDate . HasValue )
2015-06-01 14:49:23 +00:00
{
2016-03-20 06:46:51 +00:00
whereClauses . Add ( "PremiereDate<=@MaxPremiereDate" ) ;
cmd . Parameters . Add ( cmd , "@MaxPremiereDate" , DbType . Date ) . Value = query . MaxPremiereDate . Value ;
2015-06-01 14:49:23 +00:00
}
2016-03-19 05:04:38 +00:00
if ( query . SourceTypes . Length = = 1 )
{
whereClauses . Add ( "SourceType=@SourceType" ) ;
cmd . Parameters . Add ( cmd , "@SourceType" , DbType . String ) . Value = query . SourceTypes [ 0 ] ;
}
else if ( query . SourceTypes . Length > 1 )
{
var inClause = string . Join ( "," , query . SourceTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( string . Format ( "SourceType in ({0})" , inClause ) ) ;
}
2016-03-19 15:38:05 +00:00
if ( query . ExcludeSourceTypes . Length = = 1 )
{
whereClauses . Add ( "SourceType<>@SourceType" ) ;
cmd . Parameters . Add ( cmd , "@SourceType" , DbType . String ) . Value = query . SourceTypes [ 0 ] ;
}
else if ( query . ExcludeSourceTypes . Length > 1 )
{
var inClause = string . Join ( "," , query . ExcludeSourceTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( string . Format ( "SourceType not in ({0})" , inClause ) ) ;
}
2016-03-19 19:32:37 +00:00
if ( query . TrailerTypes . Length > 0 )
{
var clauses = new List < string > ( ) ;
var index = 0 ;
foreach ( var type in query . TrailerTypes )
{
clauses . Add ( "TrailerTypes like @TrailerTypes" + index ) ;
cmd . Parameters . Add ( cmd , "@TrailerTypes" + index , DbType . String ) . Value = "%" + type + "%" ;
index + + ;
}
var clause = "(" + string . Join ( " OR " , clauses . ToArray ( ) ) + ")" ;
whereClauses . Add ( clause ) ;
}
2015-06-01 14:49:23 +00:00
if ( query . IsAiring . HasValue )
{
if ( query . IsAiring . Value )
{
whereClauses . Add ( "StartDate<=@MaxStartDate" ) ;
cmd . Parameters . Add ( cmd , "@MaxStartDate" , DbType . Date ) . Value = DateTime . UtcNow ;
whereClauses . Add ( "EndDate>=@MinEndDate" ) ;
cmd . Parameters . Add ( cmd , "@MinEndDate" , DbType . Date ) . Value = DateTime . UtcNow ;
}
else
{
whereClauses . Add ( "(StartDate>@IsAiringDate OR EndDate < @IsAiringDate)" ) ;
cmd . Parameters . Add ( cmd , "@IsAiringDate" , DbType . Date ) . Value = DateTime . UtcNow ;
2015-06-01 17:07:55 +00:00
}
2015-06-01 14:49:23 +00:00
}
2016-06-26 16:21:10 +00:00
if ( query . PersonIds . Length > 0 )
{
// Todo: improve without having to do this
query . Person = query . PersonIds . Select ( i = > RetrieveItem ( new Guid ( i ) ) ) . Where ( i = > i ! = null ) . Select ( i = > i . Name ) . FirstOrDefault ( ) ;
}
2015-07-07 02:25:23 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . Person ) )
{
whereClauses . Add ( "Guid in (select ItemId from People where Name=@PersonName)" ) ;
cmd . Parameters . Add ( cmd , "@PersonName" , DbType . String ) . Value = query . Person ;
}
2016-05-04 16:32:34 +00:00
2016-05-06 04:50:39 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . SlugName ) )
{
2016-05-22 18:53:37 +00:00
whereClauses . Add ( "SlugName=@SlugName" ) ;
2016-05-06 04:50:39 +00:00
cmd . Parameters . Add ( cmd , "@SlugName" , DbType . String ) . Value = query . SlugName ;
}
2016-06-29 16:31:01 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . MinSortName ) )
{
whereClauses . Add ( "SortName>=@MinSortName" ) ;
cmd . Parameters . Add ( cmd , "@MinSortName" , DbType . String ) . Value = query . MinSortName ;
}
2016-05-04 16:32:34 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . Name ) )
{
2016-05-22 18:53:37 +00:00
whereClauses . Add ( "CleanName=@Name" ) ;
2016-08-06 20:59:31 +00:00
cmd . Parameters . Add ( cmd , "@Name" , DbType . String ) . Value = GetCleanValue ( query . Name ) ;
2016-05-04 16:32:34 +00:00
}
2015-07-07 02:25:23 +00:00
2015-07-18 19:32:59 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . NameContains ) )
{
2016-05-22 18:53:37 +00:00
whereClauses . Add ( "CleanName like @NameContains" ) ;
2016-08-06 20:59:31 +00:00
cmd . Parameters . Add ( cmd , "@NameContains" , DbType . String ) . Value = "%" + GetCleanValue ( query . NameContains ) + "%" ;
2015-07-18 19:32:59 +00:00
}
2016-05-02 01:46:08 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . NameStartsWith ) )
{
2016-05-06 02:31:35 +00:00
whereClauses . Add ( "SortName like @NameStartsWith" ) ;
2016-05-02 01:46:08 +00:00
cmd . Parameters . Add ( cmd , "@NameStartsWith" , DbType . String ) . Value = query . NameStartsWith + "%" ;
}
if ( ! string . IsNullOrWhiteSpace ( query . NameStartsWithOrGreater ) )
{
whereClauses . Add ( "SortName >= @NameStartsWithOrGreater" ) ;
// lowercase this because SortName is stored as lowercase
cmd . Parameters . Add ( cmd , "@NameStartsWithOrGreater" , DbType . String ) . Value = query . NameStartsWithOrGreater . ToLower ( ) ;
}
if ( ! string . IsNullOrWhiteSpace ( query . NameLessThan ) )
{
whereClauses . Add ( "SortName < @NameLessThan" ) ;
// lowercase this because SortName is stored as lowercase
cmd . Parameters . Add ( cmd , "@NameLessThan" , DbType . String ) . Value = query . NameLessThan . ToLower ( ) ;
}
2015-07-28 12:33:30 +00:00
2016-06-03 16:24:04 +00:00
if ( query . ImageTypes . Length > 0 & & _config . Configuration . SchemaVersion > = 87 )
{
var requiredImageIndex = 0 ;
foreach ( var requiredImage in query . ImageTypes )
{
var paramName = "@RequiredImageType" + requiredImageIndex ;
whereClauses . Add ( "(select path from images where ItemId=Guid and ImageType=" + paramName + " limit 1) not null" ) ;
cmd . Parameters . Add ( cmd , paramName , DbType . Int32 ) . Value = ( int ) requiredImage ;
requiredImageIndex + + ;
}
}
2016-05-08 06:31:08 +00:00
if ( query . IsLiked . HasValue )
{
if ( query . IsLiked . Value )
{
whereClauses . Add ( "rating>=@UserRating" ) ;
cmd . Parameters . Add ( cmd , "@UserRating" , DbType . Double ) . Value = UserItemData . MinLikeValue ;
}
else
{
whereClauses . Add ( "(rating is null or rating<@UserRating)" ) ;
cmd . Parameters . Add ( cmd , "@UserRating" , DbType . Double ) . Value = UserItemData . MinLikeValue ;
}
}
if ( query . IsFavoriteOrLiked . HasValue )
{
if ( query . IsFavoriteOrLiked . Value )
{
2016-05-10 03:36:43 +00:00
whereClauses . Add ( "IsFavorite=@IsFavoriteOrLiked" ) ;
2016-05-08 06:31:08 +00:00
}
else
{
2016-05-10 03:36:43 +00:00
whereClauses . Add ( "(IsFavorite is null or IsFavorite=@IsFavoriteOrLiked)" ) ;
2016-05-08 06:31:08 +00:00
}
2016-05-10 03:36:43 +00:00
cmd . Parameters . Add ( cmd , "@IsFavoriteOrLiked" , DbType . Boolean ) . Value = query . IsFavoriteOrLiked . Value ;
2016-05-08 06:31:08 +00:00
}
if ( query . IsFavorite . HasValue )
{
2016-05-10 03:36:43 +00:00
if ( query . IsFavorite . Value )
{
whereClauses . Add ( "IsFavorite=@IsFavorite" ) ;
}
else
{
whereClauses . Add ( "(IsFavorite is null or IsFavorite=@IsFavorite)" ) ;
}
2016-05-08 06:31:08 +00:00
cmd . Parameters . Add ( cmd , "@IsFavorite" , DbType . Boolean ) . Value = query . IsFavorite . Value ;
}
2016-05-17 20:04:20 +00:00
if ( EnableJoinUserData ( query ) )
2016-05-08 06:31:08 +00:00
{
2016-05-17 20:04:20 +00:00
if ( query . IsPlayed . HasValue )
2016-05-10 03:36:43 +00:00
{
2016-05-17 20:04:20 +00:00
if ( query . IsPlayed . Value )
{
whereClauses . Add ( "(played=@IsPlayed)" ) ;
}
else
{
whereClauses . Add ( "(played is null or played=@IsPlayed)" ) ;
}
cmd . Parameters . Add ( cmd , "@IsPlayed" , DbType . Boolean ) . Value = query . IsPlayed . Value ;
2016-05-10 03:36:43 +00:00
}
2016-05-08 06:31:08 +00:00
}
if ( query . IsResumable . HasValue )
{
if ( query . IsResumable . Value )
{
whereClauses . Add ( "playbackPositionTicks > 0" ) ;
}
else
{
whereClauses . Add ( "(playbackPositionTicks is null or playbackPositionTicks = 0)" ) ;
}
}
2016-05-18 05:34:10 +00:00
if ( query . ArtistNames . Length > 0 )
{
var clauses = new List < string > ( ) ;
var index = 0 ;
foreach ( var artist in query . ArtistNames )
{
2016-06-17 13:06:13 +00:00
clauses . Add ( "@ArtistName" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type <= 1)" ) ;
2016-08-06 20:59:31 +00:00
cmd . Parameters . Add ( cmd , "@ArtistName" + index , DbType . String ) . Value = GetCleanValue ( artist ) ;
2016-05-18 05:34:10 +00:00
index + + ;
}
var clause = "(" + string . Join ( " OR " , clauses . ToArray ( ) ) + ")" ;
whereClauses . Add ( clause ) ;
}
2016-07-22 17:54:43 +00:00
2016-07-22 22:10:39 +00:00
if ( query . ExcludeArtistIds . Length > 0 )
2016-07-22 17:54:43 +00:00
{
var clauses = new List < string > ( ) ;
var index = 0 ;
2016-07-22 22:10:39 +00:00
foreach ( var artistId in query . ExcludeArtistIds )
2016-07-22 17:54:43 +00:00
{
2016-07-22 22:10:39 +00:00
var artistItem = RetrieveItem ( new Guid ( artistId ) ) ;
if ( artistItem ! = null )
{
clauses . Add ( "@ExcludeArtistName" + index + " not in (select CleanValue from itemvalues where ItemId=Guid and Type <= 1)" ) ;
2016-08-06 20:59:31 +00:00
cmd . Parameters . Add ( cmd , "@ExcludeArtistName" + index , DbType . String ) . Value = GetCleanValue ( artistItem . Name ) ;
2016-07-22 22:10:39 +00:00
index + + ;
}
2016-07-22 17:54:43 +00:00
}
var clause = "(" + string . Join ( " AND " , clauses . ToArray ( ) ) + ")" ;
whereClauses . Add ( clause ) ;
}
2016-05-18 05:34:10 +00:00
2016-06-26 16:21:10 +00:00
if ( query . GenreIds . Length > 0 )
{
// Todo: improve without having to do this
query . Genres = query . GenreIds . Select ( i = > RetrieveItem ( new Guid ( i ) ) ) . Where ( i = > i ! = null ) . Select ( i = > i . Name ) . ToArray ( ) ;
}
2015-07-28 12:33:30 +00:00
if ( query . Genres . Length > 0 )
{
2016-03-20 06:46:51 +00:00
var clauses = new List < string > ( ) ;
var index = 0 ;
foreach ( var item in query . Genres )
{
2016-06-17 13:06:13 +00:00
clauses . Add ( "@Genre" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type=2)" ) ;
2016-08-06 20:59:31 +00:00
cmd . Parameters . Add ( cmd , "@Genre" + index , DbType . String ) . Value = GetCleanValue ( item ) ;
2016-03-20 06:46:51 +00:00
index + + ;
}
var clause = "(" + string . Join ( " OR " , clauses . ToArray ( ) ) + ")" ;
whereClauses . Add ( clause ) ;
}
if ( query . Tags . Length > 0 )
{
var clauses = new List < string > ( ) ;
var index = 0 ;
foreach ( var item in query . Tags )
{
2016-06-17 13:06:13 +00:00
clauses . Add ( "@Tag" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type=4)" ) ;
2016-08-06 20:59:31 +00:00
cmd . Parameters . Add ( cmd , "@Tag" + index , DbType . String ) . Value = GetCleanValue ( item ) ;
2016-03-20 06:46:51 +00:00
index + + ;
}
var clause = "(" + string . Join ( " OR " , clauses . ToArray ( ) ) + ")" ;
whereClauses . Add ( clause ) ;
}
2016-06-26 16:21:10 +00:00
if ( query . StudioIds . Length > 0 )
{
// Todo: improve without having to do this
query . Studios = query . StudioIds . Select ( i = > RetrieveItem ( new Guid ( i ) ) ) . Where ( i = > i ! = null ) . Select ( i = > i . Name ) . ToArray ( ) ;
}
2016-03-20 06:46:51 +00:00
if ( query . Studios . Length > 0 )
{
var clauses = new List < string > ( ) ;
2015-07-28 12:33:30 +00:00
var index = 0 ;
2016-03-20 06:46:51 +00:00
foreach ( var item in query . Studios )
2015-07-28 12:33:30 +00:00
{
2016-06-17 13:06:13 +00:00
clauses . Add ( "@Studio" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type=3)" ) ;
2016-08-06 20:59:31 +00:00
cmd . Parameters . Add ( cmd , "@Studio" + index , DbType . String ) . Value = GetCleanValue ( item ) ;
2016-05-31 18:07:54 +00:00
index + + ;
}
var clause = "(" + string . Join ( " OR " , clauses . ToArray ( ) ) + ")" ;
whereClauses . Add ( clause ) ;
}
if ( query . Keywords . Length > 0 )
{
var clauses = new List < string > ( ) ;
var index = 0 ;
foreach ( var item in query . Keywords )
{
2016-06-17 13:06:13 +00:00
clauses . Add ( "@Keyword" + index + " in (select CleanValue from itemvalues where ItemId=Guid and Type=5)" ) ;
2016-08-06 20:59:31 +00:00
cmd . Parameters . Add ( cmd , "@Keyword" + index , DbType . String ) . Value = GetCleanValue ( item ) ;
2015-07-28 12:33:30 +00:00
index + + ;
}
2016-03-20 06:46:51 +00:00
var clause = "(" + string . Join ( " OR " , clauses . ToArray ( ) ) + ")" ;
whereClauses . Add ( clause ) ;
2015-07-28 12:33:30 +00:00
}
2016-06-01 06:01:43 +00:00
if ( query . OfficialRatings . Length > 0 )
{
var clauses = new List < string > ( ) ;
var index = 0 ;
foreach ( var item in query . OfficialRatings )
{
clauses . Add ( "OfficialRating=@OfficialRating" + index ) ;
cmd . Parameters . Add ( cmd , "@OfficialRating" + index , DbType . String ) . Value = item ;
index + + ;
}
var clause = "(" + string . Join ( " OR " , clauses . ToArray ( ) ) + ")" ;
whereClauses . Add ( clause ) ;
}
2016-03-21 03:10:37 +00:00
if ( query . MinParentalRating . HasValue )
{
whereClauses . Add ( "InheritedParentalRatingValue<=@MinParentalRating" ) ;
cmd . Parameters . Add ( cmd , "@MinParentalRating" , DbType . Int32 ) . Value = query . MinParentalRating . Value ;
}
2015-07-28 12:33:30 +00:00
if ( query . MaxParentalRating . HasValue )
{
2015-12-27 18:37:06 +00:00
whereClauses . Add ( "InheritedParentalRatingValue<=@MaxParentalRating" ) ;
2015-07-28 12:33:30 +00:00
cmd . Parameters . Add ( cmd , "@MaxParentalRating" , DbType . Int32 ) . Value = query . MaxParentalRating . Value ;
}
if ( query . HasParentalRating . HasValue )
{
if ( query . HasParentalRating . Value )
{
2015-12-27 18:37:06 +00:00
whereClauses . Add ( "InheritedParentalRatingValue > 0" ) ;
2015-07-28 12:33:30 +00:00
}
else
{
2015-12-27 18:37:06 +00:00
whereClauses . Add ( "InheritedParentalRatingValue = 0" ) ;
2015-07-28 12:33:30 +00:00
}
}
2016-03-21 03:04:44 +00:00
if ( query . HasOverview . HasValue )
{
if ( query . HasOverview . Value )
{
whereClauses . Add ( "(Overview not null AND Overview<>'')" ) ;
}
else
{
whereClauses . Add ( "(Overview is null OR Overview='')" ) ;
}
}
2015-08-28 04:19:08 +00:00
if ( query . HasDeadParentId . HasValue )
{
if ( query . HasDeadParentId . Value )
{
whereClauses . Add ( "ParentId NOT NULL AND ParentId NOT IN (select guid from TypedBaseItems)" ) ;
}
}
2016-03-20 19:53:22 +00:00
if ( query . Years . Length = = 1 )
{
whereClauses . Add ( "ProductionYear=@Years" ) ;
cmd . Parameters . Add ( cmd , "@Years" , DbType . Int32 ) . Value = query . Years [ 0 ] . ToString ( ) ;
}
else if ( query . Years . Length > 1 )
{
var val = string . Join ( "," , query . Years . ToArray ( ) ) ;
whereClauses . Add ( "ProductionYear in (" + val + ")" ) ;
}
if ( query . LocationTypes . Length = = 1 )
{
2016-06-12 05:03:52 +00:00
if ( query . LocationTypes [ 0 ] = = LocationType . Virtual & & _config . Configuration . SchemaVersion > = 90 )
{
query . IsVirtualItem = true ;
}
else
{
whereClauses . Add ( "LocationType=@LocationType" ) ;
cmd . Parameters . Add ( cmd , "@LocationType" , DbType . String ) . Value = query . LocationTypes [ 0 ] . ToString ( ) ;
}
2016-03-20 19:53:22 +00:00
}
else if ( query . LocationTypes . Length > 1 )
{
var val = string . Join ( "," , query . LocationTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( "LocationType in (" + val + ")" ) ;
}
2015-12-27 18:37:06 +00:00
if ( query . ExcludeLocationTypes . Length = = 1 )
{
2016-06-12 05:03:52 +00:00
if ( query . ExcludeLocationTypes [ 0 ] = = LocationType . Virtual & & _config . Configuration . SchemaVersion > = 90 )
{
query . IsVirtualItem = false ;
}
else
{
whereClauses . Add ( "LocationType<>@ExcludeLocationTypes" ) ;
cmd . Parameters . Add ( cmd , "@ExcludeLocationTypes" , DbType . String ) . Value = query . ExcludeLocationTypes [ 0 ] . ToString ( ) ;
}
2015-12-27 18:37:06 +00:00
}
2016-03-20 19:53:22 +00:00
else if ( query . ExcludeLocationTypes . Length > 1 )
2015-12-27 18:37:06 +00:00
{
var val = string . Join ( "," , query . ExcludeLocationTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( "LocationType not in (" + val + ")" ) ;
}
2016-06-12 05:03:52 +00:00
if ( query . IsVirtualItem . HasValue )
{
2016-07-03 23:54:19 +00:00
if ( _config . Configuration . SchemaVersion > = 90 )
{
whereClauses . Add ( "IsVirtualItem=@IsVirtualItem" ) ;
cmd . Parameters . Add ( cmd , "@IsVirtualItem" , DbType . Boolean ) . Value = query . IsVirtualItem . Value ;
}
else if ( ! query . IsVirtualItem . Value )
{
whereClauses . Add ( "LocationType<>'Virtual'" ) ;
}
2016-06-12 05:03:52 +00:00
}
2016-08-18 05:56:10 +00:00
if ( query . IsSpecialSeason . HasValue )
{
if ( query . IsSpecialSeason . Value )
{
whereClauses . Add ( "IndexNumber = 0" ) ;
}
else
{
whereClauses . Add ( "IndexNumber <> 0" ) ;
}
}
2016-07-10 15:44:53 +00:00
if ( query . IsUnaired . HasValue )
{
if ( query . IsUnaired . Value )
{
whereClauses . Add ( "PremiereDate >= DATETIME('now')" ) ;
}
else
{
whereClauses . Add ( "PremiereDate < DATETIME('now')" ) ;
}
}
if ( query . IsMissing . HasValue & & _config . Configuration . SchemaVersion > = 90 )
{
if ( query . IsMissing . Value )
{
whereClauses . Add ( "(IsVirtualItem=1 AND PremiereDate < DATETIME('now'))" ) ;
}
else
{
whereClauses . Add ( "(IsVirtualItem=0 OR PremiereDate >= DATETIME('now'))" ) ;
}
}
if ( query . IsVirtualUnaired . HasValue & & _config . Configuration . SchemaVersion > = 90 )
{
if ( query . IsVirtualUnaired . Value )
{
whereClauses . Add ( "(IsVirtualItem=1 AND PremiereDate >= DATETIME('now'))" ) ;
}
else
{
whereClauses . Add ( "(IsVirtualItem=0 OR PremiereDate < DATETIME('now'))" ) ;
}
}
2016-03-20 06:46:51 +00:00
if ( query . MediaTypes . Length = = 1 )
{
whereClauses . Add ( "MediaType=@MediaTypes" ) ;
2016-05-09 03:13:38 +00:00
cmd . Parameters . Add ( cmd , "@MediaTypes" , DbType . String ) . Value = query . MediaTypes [ 0 ] ;
2016-03-20 06:46:51 +00:00
}
if ( query . MediaTypes . Length > 1 )
{
var val = string . Join ( "," , query . MediaTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( "MediaType in (" + val + ")" ) ;
}
2016-06-17 13:06:13 +00:00
if ( query . ItemIds . Length > 0 )
{
2016-08-18 16:45:36 +00:00
var includeIds = new List < string > ( ) ;
2016-06-17 13:06:13 +00:00
var index = 0 ;
foreach ( var id in query . ItemIds )
{
2016-08-18 16:45:36 +00:00
includeIds . Add ( "Guid = @IncludeId" + index ) ;
2016-06-17 13:06:13 +00:00
cmd . Parameters . Add ( cmd , "@IncludeId" + index , DbType . Guid ) . Value = new Guid ( id ) ;
index + + ;
}
2016-08-18 16:45:36 +00:00
whereClauses . Add ( string . Join ( " OR " , includeIds . ToArray ( ) ) ) ;
2016-06-17 13:06:13 +00:00
}
2016-05-31 18:45:37 +00:00
if ( query . ExcludeItemIds . Length > 0 )
{
var excludeIds = new List < string > ( ) ;
var index = 0 ;
foreach ( var id in query . ExcludeItemIds )
{
excludeIds . Add ( "Guid <> @ExcludeId" + index ) ;
cmd . Parameters . Add ( cmd , "@ExcludeId" + index , DbType . Guid ) . Value = new Guid ( id ) ;
index + + ;
}
whereClauses . Add ( string . Join ( " AND " , excludeIds . ToArray ( ) ) ) ;
}
2015-08-28 04:19:08 +00:00
2016-06-02 04:41:12 +00:00
if ( query . ExcludeProviderIds . Count > 0 )
{
var excludeIds = new List < string > ( ) ;
var index = 0 ;
foreach ( var pair in query . ExcludeProviderIds )
{
2016-06-03 16:24:04 +00:00
if ( string . Equals ( pair . Key , MetadataProviders . TmdbCollection . ToString ( ) , StringComparison . OrdinalIgnoreCase ) )
{
continue ;
}
2016-06-02 04:41:12 +00:00
var paramName = "@ExcludeProviderId" + index ;
2016-06-03 16:24:04 +00:00
excludeIds . Add ( "(COALESCE((select value from ProviderIds where ItemId=Guid and Name = '" + pair . Key + "'), '') <> " + paramName + ")" ) ;
2016-06-02 04:41:12 +00:00
cmd . Parameters . Add ( cmd , paramName , DbType . String ) . Value = pair . Value ;
index + + ;
}
whereClauses . Add ( string . Join ( " AND " , excludeIds . ToArray ( ) ) ) ;
}
if ( query . HasImdbId . HasValue )
{
2016-06-02 04:43:13 +00:00
var fn = query . HasImdbId . Value ? "<>" : "=" ;
whereClauses . Add ( "(COALESCE((select value from ProviderIds where ItemId=Guid and Name = 'Imdb'), '') " + fn + " '')" ) ;
2016-06-02 04:41:12 +00:00
}
if ( query . HasTmdbId . HasValue )
{
2016-06-02 04:43:13 +00:00
var fn = query . HasTmdbId . Value ? "<>" : "=" ;
whereClauses . Add ( "(COALESCE((select value from ProviderIds where ItemId=Guid and Name = 'Tmdb'), '') " + fn + " '')" ) ;
2016-06-02 04:41:12 +00:00
}
if ( query . HasTvdbId . HasValue )
{
2016-06-02 04:43:13 +00:00
var fn = query . HasTvdbId . Value ? "<>" : "=" ;
whereClauses . Add ( "(COALESCE((select value from ProviderIds where ItemId=Guid and Name = 'Tvdb'), '') " + fn + " '')" ) ;
2016-06-02 04:41:12 +00:00
}
2016-05-09 03:13:38 +00:00
if ( query . AlbumNames . Length > 0 )
{
var clause = "(" ;
var index = 0 ;
foreach ( var name in query . AlbumNames )
{
if ( index > 0 )
{
clause + = " OR " ;
}
clause + = "Album=@AlbumName" + index ;
cmd . Parameters . Add ( cmd , "@AlbumName" + index , DbType . String ) . Value = name ;
2016-05-15 18:52:36 +00:00
index + + ;
2016-05-09 03:13:38 +00:00
}
clause + = ")" ;
whereClauses . Add ( clause ) ;
}
2016-05-01 22:11:24 +00:00
//var enableItemsByName = query.IncludeItemsByName ?? query.IncludeItemTypes.Length > 0;
var enableItemsByName = query . IncludeItemsByName ? ? false ;
2016-02-14 17:58:31 +00:00
2015-12-27 18:37:06 +00:00
if ( query . TopParentIds . Length = = 1 )
{
2016-02-14 17:58:31 +00:00
if ( enableItemsByName )
{
whereClauses . Add ( "(TopParentId=@TopParentId or IsItemByName=@IsItemByName)" ) ;
cmd . Parameters . Add ( cmd , "@IsItemByName" , DbType . Boolean ) . Value = true ;
}
else
{
whereClauses . Add ( "(TopParentId=@TopParentId)" ) ;
}
2015-12-27 18:37:06 +00:00
cmd . Parameters . Add ( cmd , "@TopParentId" , DbType . String ) . Value = query . TopParentIds [ 0 ] ;
}
if ( query . TopParentIds . Length > 1 )
{
var val = string . Join ( "," , query . TopParentIds . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
2016-03-20 19:53:22 +00:00
2016-02-14 17:58:31 +00:00
if ( enableItemsByName )
{
whereClauses . Add ( "(IsItemByName=@IsItemByName or TopParentId in (" + val + "))" ) ;
cmd . Parameters . Add ( cmd , "@IsItemByName" , DbType . Boolean ) . Value = true ;
}
else
{
whereClauses . Add ( "(TopParentId in (" + val + "))" ) ;
}
2015-12-27 18:37:06 +00:00
}
if ( query . AncestorIds . Length = = 1 )
{
whereClauses . Add ( "Guid in (select itemId from AncestorIds where AncestorId=@AncestorId)" ) ;
cmd . Parameters . Add ( cmd , "@AncestorId" , DbType . Guid ) . Value = new Guid ( query . AncestorIds [ 0 ] ) ;
}
if ( query . AncestorIds . Length > 1 )
{
var inClause = string . Join ( "," , query . AncestorIds . Select ( i = > "'" + new Guid ( i ) . ToString ( "N" ) + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( string . Format ( "Guid in (select itemId from AncestorIds where AncestorIdText in ({0}))" , inClause ) ) ;
}
2016-05-07 17:47:41 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . AncestorWithPresentationUniqueKey ) )
{
var inClause = "select guid from TypedBaseItems where PresentationUniqueKey=@AncestorWithPresentationUniqueKey" ;
whereClauses . Add ( string . Format ( "Guid in (select itemId from AncestorIds where AncestorId in ({0}))" , inClause ) ) ;
cmd . Parameters . Add ( cmd , "@AncestorWithPresentationUniqueKey" , DbType . String ) . Value = query . AncestorWithPresentationUniqueKey ;
}
2015-12-27 18:37:06 +00:00
if ( query . BlockUnratedItems . Length = = 1 )
{
whereClauses . Add ( "(InheritedParentalRatingValue > 0 or UnratedType <> @UnratedType)" ) ;
cmd . Parameters . Add ( cmd , "@UnratedType" , DbType . String ) . Value = query . BlockUnratedItems [ 0 ] . ToString ( ) ;
}
if ( query . BlockUnratedItems . Length > 1 )
{
var inClause = string . Join ( "," , query . BlockUnratedItems . Select ( i = > "'" + i . ToString ( ) + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( string . Format ( "(InheritedParentalRatingValue > 0 or UnratedType not in ({0}))" , inClause ) ) ;
}
2016-02-15 03:18:46 +00:00
var excludeTagIndex = 0 ;
foreach ( var excludeTag in query . ExcludeTags )
{
2016-04-17 04:07:06 +00:00
whereClauses . Add ( "(Tags is null OR Tags not like @excludeTag" + excludeTagIndex + ")" ) ;
2016-02-15 03:18:46 +00:00
cmd . Parameters . Add ( cmd , "@excludeTag" + excludeTagIndex , DbType . String ) . Value = "%" + excludeTag + "%" ;
excludeTagIndex + + ;
}
2016-03-20 19:53:22 +00:00
2016-04-15 02:39:39 +00:00
excludeTagIndex = 0 ;
foreach ( var excludeTag in query . ExcludeInheritedTags )
{
2016-05-01 22:11:24 +00:00
whereClauses . Add ( "(InheritedTags is null OR InheritedTags not like @excludeInheritedTag" + excludeTagIndex + ")" ) ;
2016-04-15 02:39:39 +00:00
cmd . Parameters . Add ( cmd , "@excludeInheritedTag" + excludeTagIndex , DbType . String ) . Value = "%" + excludeTag + "%" ;
excludeTagIndex + + ;
}
2015-06-01 14:49:23 +00:00
return whereClauses ;
}
2016-08-06 20:59:31 +00:00
private string GetCleanValue ( string value )
{
if ( string . IsNullOrWhiteSpace ( value ) )
{
return value ;
}
return value . RemoveDiacritics ( ) . ToLower ( ) ;
}
2016-05-01 22:11:24 +00:00
private bool EnableGroupByPresentationUniqueKey ( InternalItemsQuery query )
{
2016-05-06 04:50:39 +00:00
if ( ! query . GroupByPresentationUniqueKey )
{
return false ;
}
2016-05-02 05:32:04 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . PresentationUniqueKey ) )
{
return false ;
}
2016-05-06 06:02:10 +00:00
if ( query . User = = null )
{
return false ;
}
2016-05-01 22:11:24 +00:00
if ( query . IncludeItemTypes . Length = = 0 )
{
return true ;
}
var types = new [ ] {
typeof ( Episode ) . Name ,
typeof ( Video ) . Name ,
typeof ( Movie ) . Name ,
typeof ( MusicVideo ) . Name ,
2016-05-02 05:32:04 +00:00
typeof ( Series ) . Name ,
typeof ( Season ) . Name } ;
2016-05-01 22:11:24 +00:00
if ( types . Any ( i = > query . IncludeItemTypes . Contains ( i , StringComparer . OrdinalIgnoreCase ) ) )
{
return true ;
}
return false ;
}
2015-07-18 19:32:59 +00:00
private static readonly Type [ ] KnownTypes =
{
typeof ( LiveTvProgram ) ,
typeof ( LiveTvChannel ) ,
typeof ( LiveTvVideoRecording ) ,
typeof ( LiveTvAudioRecording ) ,
typeof ( Series ) ,
typeof ( Audio ) ,
typeof ( MusicAlbum ) ,
typeof ( MusicArtist ) ,
typeof ( MusicGenre ) ,
typeof ( MusicVideo ) ,
typeof ( Movie ) ,
2016-03-20 18:39:20 +00:00
typeof ( Playlist ) ,
typeof ( AudioPodcast ) ,
2016-03-18 06:36:58 +00:00
typeof ( Trailer ) ,
2015-07-18 19:32:59 +00:00
typeof ( BoxSet ) ,
typeof ( Episode ) ,
typeof ( Season ) ,
typeof ( Series ) ,
typeof ( Book ) ,
typeof ( CollectionFolder ) ,
typeof ( Folder ) ,
typeof ( Game ) ,
typeof ( GameGenre ) ,
typeof ( GameSystem ) ,
typeof ( Genre ) ,
typeof ( Person ) ,
typeof ( Photo ) ,
typeof ( PhotoAlbum ) ,
typeof ( Studio ) ,
typeof ( UserRootFolder ) ,
typeof ( UserView ) ,
typeof ( Video ) ,
2015-10-04 18:10:50 +00:00
typeof ( Year ) ,
2015-11-11 15:46:30 +00:00
typeof ( Channel ) ,
typeof ( AggregateFolder )
2015-07-18 19:32:59 +00:00
} ;
2015-12-27 18:37:06 +00:00
public async Task UpdateInheritedValues ( CancellationToken cancellationToken )
2016-04-15 02:39:39 +00:00
{
await UpdateInheritedParentalRating ( cancellationToken ) . ConfigureAwait ( false ) ;
await UpdateInheritedTags ( cancellationToken ) . ConfigureAwait ( false ) ;
}
private async Task UpdateInheritedTags ( CancellationToken cancellationToken )
{
2016-06-12 23:33:11 +00:00
var newValues = new List < Tuple < Guid , string > > ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
2016-04-15 02:39:39 +00:00
{
2016-06-12 23:33:11 +00:00
cmd . CommandText = "select Guid,InheritedTags,(select group_concat(Tags, '|') from TypedBaseItems where (guid=outer.guid) OR (guid in (Select AncestorId from AncestorIds where ItemId=Outer.guid))) as NewInheritedTags from typedbaseitems as Outer where NewInheritedTags <> InheritedTags" ;
2016-04-15 02:39:39 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
2016-04-15 02:39:39 +00:00
{
2016-06-12 23:33:11 +00:00
while ( reader . Read ( ) )
2016-04-15 02:39:39 +00:00
{
2016-06-12 23:33:11 +00:00
var id = reader . GetGuid ( 0 ) ;
string value = reader . IsDBNull ( 2 ) ? null : reader . GetString ( 2 ) ;
2016-04-15 02:39:39 +00:00
2016-06-12 23:33:11 +00:00
newValues . Add ( new Tuple < Guid , string > ( id , value ) ) ;
2016-04-15 02:39:39 +00:00
}
}
2016-06-12 23:33:11 +00:00
}
2016-04-15 02:39:39 +00:00
2016-06-12 23:33:11 +00:00
Logger . Debug ( "UpdateInheritedTags - {0} rows" , newValues . Count ) ;
if ( newValues . Count = = 0 )
{
return ;
}
2016-05-01 22:11:24 +00:00
2016-06-12 23:33:11 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2016-04-15 02:39:39 +00:00
2016-06-12 23:33:11 +00:00
IDbTransaction transaction = null ;
2016-04-15 02:39:39 +00:00
2016-06-12 23:33:11 +00:00
try
{
transaction = _connection . BeginTransaction ( ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
foreach ( var item in newValues )
2016-04-15 02:39:39 +00:00
{
2016-06-12 23:33:11 +00:00
_updateInheritedTagsCommand . GetParameter ( 0 ) . Value = item . Item1 ;
_updateInheritedTagsCommand . GetParameter ( 1 ) . Value = item . Item2 ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
_updateInheritedTagsCommand . Transaction = transaction ;
_updateInheritedTagsCommand . ExecuteNonQuery ( ) ;
2016-04-15 02:39:39 +00:00
}
2016-06-12 23:33:11 +00:00
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
2016-06-11 20:12:01 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Rollback ( ) ;
}
2016-04-15 02:39:39 +00:00
2016-06-12 23:33:11 +00:00
throw ;
}
catch ( Exception e )
{
Logger . ErrorException ( "Error running query:" , e ) ;
2016-04-15 02:39:39 +00:00
2016-06-12 23:33:11 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
2016-04-15 02:39:39 +00:00
}
2016-06-12 23:33:11 +00:00
throw ;
}
finally
{
if ( transaction ! = null )
2016-04-15 02:39:39 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Dispose ( ) ;
2016-04-15 02:39:39 +00:00
}
2016-06-12 23:33:11 +00:00
WriteLock . Release ( ) ;
2016-04-15 02:39:39 +00:00
}
}
private async Task UpdateInheritedParentalRating ( CancellationToken cancellationToken )
2015-12-27 18:37:06 +00:00
{
var newValues = new List < Tuple < Guid , int > > ( ) ;
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-12-27 18:37:06 +00:00
{
2016-08-10 19:16:09 +00:00
cmd . CommandText = "select Guid,InheritedParentalRatingValue,(select Max(InheritedParentalRatingValue, (select COALESCE(MAX(InheritedParentalRatingValue),0) from TypedBaseItems where guid in (Select AncestorId from AncestorIds where ItemId=Outer.guid)))) as NewInheritedParentalRatingValue from typedbaseitems as Outer where InheritedParentalRatingValue <> NewInheritedParentalRatingValue" ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
2015-12-27 18:37:06 +00:00
{
2016-06-12 23:33:11 +00:00
var id = reader . GetGuid ( 0 ) ;
var newValue = reader . GetInt32 ( 2 ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
newValues . Add ( new Tuple < Guid , int > ( id , newValue ) ) ;
2015-12-27 18:37:06 +00:00
}
}
2016-06-12 23:33:11 +00:00
}
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
Logger . Debug ( "UpdateInheritedParentalRatings - {0} rows" , newValues . Count ) ;
if ( newValues . Count = = 0 )
{
return ;
}
2016-03-20 19:53:22 +00:00
2016-06-12 23:33:11 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
IDbTransaction transaction = null ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
try
{
transaction = _connection . BeginTransaction ( ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
foreach ( var item in newValues )
{
_updateInheritedRatingCommand . GetParameter ( 0 ) . Value = item . Item1 ;
_updateInheritedRatingCommand . GetParameter ( 1 ) . Value = item . Item2 ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
_updateInheritedRatingCommand . Transaction = transaction ;
_updateInheritedRatingCommand . ExecuteNonQuery ( ) ;
}
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
throw ;
}
catch ( Exception e )
{
Logger . ErrorException ( "Error running query:" , e ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
throw ;
}
finally
{
if ( transaction ! = null )
{
transaction . Dispose ( ) ;
2015-12-27 18:37:06 +00:00
}
2016-06-12 23:33:11 +00:00
WriteLock . Release ( ) ;
2015-12-27 18:37:06 +00:00
}
}
2015-07-18 19:32:59 +00:00
private static Dictionary < string , string [ ] > GetTypeMapDictionary ( )
{
2016-04-06 03:14:39 +00:00
var dict = new Dictionary < string , string [ ] > ( StringComparer . OrdinalIgnoreCase ) ;
2015-07-18 19:32:59 +00:00
foreach ( var t in KnownTypes )
{
dict [ t . Name ] = new [ ] { t . FullName } ;
}
dict [ "Recording" ] = new [ ] { typeof ( LiveTvAudioRecording ) . FullName , typeof ( LiveTvVideoRecording ) . FullName } ;
2015-07-20 03:43:13 +00:00
dict [ "Program" ] = new [ ] { typeof ( LiveTvProgram ) . FullName } ;
dict [ "TvChannel" ] = new [ ] { typeof ( LiveTvChannel ) . FullName } ;
2015-07-18 19:32:59 +00:00
return dict ;
}
2015-06-01 14:49:23 +00:00
// Not crazy about having this all the way down here, but at least it's in one place
2015-07-18 19:32:59 +00:00
readonly Dictionary < string , string [ ] > _types = GetTypeMapDictionary ( ) ;
2015-06-01 14:49:23 +00:00
2015-06-01 17:07:55 +00:00
private IEnumerable < string > MapIncludeItemTypes ( string value )
2015-06-01 14:49:23 +00:00
{
2015-06-01 17:07:55 +00:00
string [ ] result ;
2015-06-01 14:49:23 +00:00
if ( _types . TryGetValue ( value , out result ) )
{
return result ;
}
2015-06-01 17:07:55 +00:00
return new [ ] { value } ;
2015-06-01 14:49:23 +00:00
}
2014-02-19 18:50:37 +00:00
public async Task DeleteItem ( Guid id , CancellationToken cancellationToken )
{
if ( id = = Guid . Empty )
{
throw new ArgumentNullException ( "id" ) ;
}
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-06-01 14:49:23 +00:00
2016-06-12 23:33:11 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
IDbTransaction transaction = null ;
try
2014-02-19 18:50:37 +00:00
{
2016-06-12 23:33:11 +00:00
transaction = _connection . BeginTransaction ( ) ;
2014-02-19 18:50:37 +00:00
2016-06-12 23:33:11 +00:00
// Delete people
_deletePeopleCommand . GetParameter ( 0 ) . Value = id ;
_deletePeopleCommand . Transaction = transaction ;
_deletePeopleCommand . ExecuteNonQuery ( ) ;
2015-07-08 16:10:34 +00:00
2016-06-12 23:33:11 +00:00
// Delete chapters
_deleteChaptersCommand . GetParameter ( 0 ) . Value = id ;
_deleteChaptersCommand . Transaction = transaction ;
_deleteChaptersCommand . ExecuteNonQuery ( ) ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
// Delete media streams
_deleteStreamsCommand . GetParameter ( 0 ) . Value = id ;
_deleteStreamsCommand . Transaction = transaction ;
_deleteStreamsCommand . ExecuteNonQuery ( ) ;
2015-11-02 17:25:01 +00:00
2016-06-12 23:33:11 +00:00
// Delete ancestors
_deleteAncestorsCommand . GetParameter ( 0 ) . Value = id ;
_deleteAncestorsCommand . Transaction = transaction ;
_deleteAncestorsCommand . ExecuteNonQuery ( ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
// Delete user data keys
_deleteUserDataKeysCommand . GetParameter ( 0 ) . Value = id ;
_deleteUserDataKeysCommand . Transaction = transaction ;
_deleteUserDataKeysCommand . ExecuteNonQuery ( ) ;
2016-05-08 06:31:08 +00:00
2016-06-12 23:33:11 +00:00
// Delete item values
_deleteItemValuesCommand . GetParameter ( 0 ) . Value = id ;
_deleteItemValuesCommand . Transaction = transaction ;
_deleteItemValuesCommand . ExecuteNonQuery ( ) ;
2016-05-18 05:34:10 +00:00
2016-06-12 23:33:11 +00:00
// Delete provider ids
_deleteProviderIdsCommand . GetParameter ( 0 ) . Value = id ;
_deleteProviderIdsCommand . Transaction = transaction ;
_deleteProviderIdsCommand . ExecuteNonQuery ( ) ;
2016-06-02 04:41:12 +00:00
2016-06-12 23:33:11 +00:00
// Delete images
_deleteImagesCommand . GetParameter ( 0 ) . Value = id ;
_deleteImagesCommand . Transaction = transaction ;
_deleteImagesCommand . ExecuteNonQuery ( ) ;
2016-06-03 16:24:04 +00:00
2016-06-12 23:33:11 +00:00
// Delete the item
_deleteItemCommand . GetParameter ( 0 ) . Value = id ;
_deleteItemCommand . Transaction = transaction ;
_deleteItemCommand . ExecuteNonQuery ( ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
2014-02-19 18:50:37 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Rollback ( ) ;
2014-02-19 18:50:37 +00:00
}
2016-06-12 23:33:11 +00:00
throw ;
}
catch ( Exception e )
{
Logger . ErrorException ( "Failed to save children:" , e ) ;
2014-02-19 18:50:37 +00:00
2016-06-12 23:33:11 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
2014-02-19 18:50:37 +00:00
}
2016-06-12 23:33:11 +00:00
throw ;
}
finally
{
if ( transaction ! = null )
2014-02-19 18:50:37 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Dispose ( ) ;
2014-02-19 18:50:37 +00:00
}
2016-06-12 23:33:11 +00:00
WriteLock . Release ( ) ;
2014-02-19 18:50:37 +00:00
}
}
2015-07-08 16:10:34 +00:00
public List < string > GetPeopleNames ( InternalPeopleQuery query )
2015-07-07 02:25:23 +00:00
{
2015-07-08 16:10:34 +00:00
if ( query = = null )
2015-07-07 02:25:23 +00:00
{
2015-07-08 16:10:34 +00:00
throw new ArgumentNullException ( "query" ) ;
2015-07-07 02:25:23 +00:00
}
CheckDisposed ( ) ;
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-07-07 02:25:23 +00:00
{
2016-06-12 23:33:11 +00:00
cmd . CommandText = "select Distinct Name from People" ;
2015-07-07 02:25:23 +00:00
2016-06-12 23:33:11 +00:00
var whereClauses = GetPeopleWhereClauses ( query , cmd ) ;
2015-07-08 16:10:34 +00:00
2016-06-12 23:33:11 +00:00
if ( whereClauses . Count > 0 )
{
cmd . CommandText + = " where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
}
2015-07-08 16:10:34 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = " order by ListOrder" ;
2015-07-07 02:25:23 +00:00
2016-06-12 23:33:11 +00:00
var list = new List < string > ( ) ;
2015-07-07 02:25:23 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
2015-07-07 02:25:23 +00:00
{
2016-06-12 23:33:11 +00:00
list . Add ( reader . GetString ( 0 ) ) ;
2015-07-07 02:25:23 +00:00
}
2016-06-11 20:12:01 +00:00
}
2016-06-12 23:33:11 +00:00
return list ;
2015-07-07 02:25:23 +00:00
}
}
2015-06-29 01:10:45 +00:00
2015-07-08 16:10:34 +00:00
public List < PersonInfo > GetPeople ( InternalPeopleQuery query )
2015-06-29 01:10:45 +00:00
{
2015-07-08 16:10:34 +00:00
if ( query = = null )
2015-06-29 01:10:45 +00:00
{
2015-07-08 16:10:34 +00:00
throw new ArgumentNullException ( "query" ) ;
2015-06-29 01:10:45 +00:00
}
CheckDisposed ( ) ;
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-06-29 01:10:45 +00:00
{
2016-06-12 23:33:11 +00:00
cmd . CommandText = "select ItemId, Name, Role, PersonType, SortOrder from People" ;
2015-07-08 16:10:34 +00:00
2016-06-12 23:33:11 +00:00
var whereClauses = GetPeopleWhereClauses ( query , cmd ) ;
2015-07-08 16:10:34 +00:00
2016-06-12 23:33:11 +00:00
if ( whereClauses . Count > 0 )
{
cmd . CommandText + = " where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
}
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText + = " order by ListOrder" ;
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
var list = new List < PersonInfo > ( ) ;
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
2015-06-29 01:10:45 +00:00
{
2016-06-12 23:33:11 +00:00
list . Add ( GetPerson ( reader ) ) ;
2015-06-29 01:10:45 +00:00
}
2016-06-11 20:12:01 +00:00
}
2016-06-12 23:33:11 +00:00
return list ;
2015-06-29 01:10:45 +00:00
}
}
2015-07-08 16:10:34 +00:00
private List < string > GetPeopleWhereClauses ( InternalPeopleQuery query , IDbCommand cmd )
{
var whereClauses = new List < string > ( ) ;
if ( query . ItemId ! = Guid . Empty )
{
whereClauses . Add ( "ItemId=@ItemId" ) ;
cmd . Parameters . Add ( cmd , "@ItemId" , DbType . Guid ) . Value = query . ItemId ;
}
if ( query . AppearsInItemId ! = Guid . Empty )
{
whereClauses . Add ( "Name in (Select Name from People where ItemId=@AppearsInItemId)" ) ;
cmd . Parameters . Add ( cmd , "@AppearsInItemId" , DbType . Guid ) . Value = query . AppearsInItemId ;
}
if ( query . PersonTypes . Count = = 1 )
{
whereClauses . Add ( "PersonType=@PersonType" ) ;
cmd . Parameters . Add ( cmd , "@PersonType" , DbType . String ) . Value = query . PersonTypes [ 0 ] ;
}
if ( query . PersonTypes . Count > 1 )
{
var val = string . Join ( "," , query . PersonTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( "PersonType in (" + val + ")" ) ;
}
if ( query . ExcludePersonTypes . Count = = 1 )
{
whereClauses . Add ( "PersonType<>@PersonType" ) ;
cmd . Parameters . Add ( cmd , "@PersonType" , DbType . String ) . Value = query . ExcludePersonTypes [ 0 ] ;
}
if ( query . ExcludePersonTypes . Count > 1 )
{
var val = string . Join ( "," , query . ExcludePersonTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( "PersonType not in (" + val + ")" ) ;
}
if ( query . MaxListOrder . HasValue )
{
whereClauses . Add ( "ListOrder<=@MaxListOrder" ) ;
cmd . Parameters . Add ( cmd , "@MaxListOrder" , DbType . Int32 ) . Value = query . MaxListOrder . Value ;
}
2015-07-10 03:00:03 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . NameContains ) )
{
whereClauses . Add ( "Name like @NameContains" ) ;
2015-07-18 19:32:59 +00:00
cmd . Parameters . Add ( cmd , "@NameContains" , DbType . String ) . Value = "%" + query . NameContains + "%" ;
2015-07-10 03:00:03 +00:00
}
2016-08-04 04:38:58 +00:00
if ( query . SourceTypes . Length = = 1 )
{
whereClauses . Add ( "(select sourcetype from typedbaseitems where guid=ItemId) = @SourceTypes" ) ;
cmd . Parameters . Add ( cmd , "@SourceTypes" , DbType . String ) . Value = query . SourceTypes [ 0 ] . ToString ( ) ;
}
2015-07-08 16:10:34 +00:00
return whereClauses ;
}
2016-06-12 23:33:11 +00:00
private void UpdateAncestors ( Guid itemId , List < Guid > ancestorIds , IDbTransaction transaction )
2015-12-27 18:37:06 +00:00
{
if ( itemId = = Guid . Empty )
{
throw new ArgumentNullException ( "itemId" ) ;
}
if ( ancestorIds = = null )
{
throw new ArgumentNullException ( "ancestorIds" ) ;
}
CheckDisposed ( ) ;
// First delete
2016-06-12 23:33:11 +00:00
_deleteAncestorsCommand . GetParameter ( 0 ) . Value = itemId ;
_deleteAncestorsCommand . Transaction = transaction ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
_deleteAncestorsCommand . ExecuteNonQuery ( ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
foreach ( var ancestorId in ancestorIds )
{
_saveAncestorCommand . GetParameter ( 0 ) . Value = itemId ;
_saveAncestorCommand . GetParameter ( 1 ) . Value = ancestorId ;
_saveAncestorCommand . GetParameter ( 2 ) . Value = ancestorId . ToString ( "N" ) ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
_saveAncestorCommand . Transaction = transaction ;
2015-12-27 18:37:06 +00:00
2016-06-12 23:33:11 +00:00
_saveAncestorCommand . ExecuteNonQuery ( ) ;
2015-12-27 18:37:06 +00:00
}
}
2016-08-06 04:38:01 +00:00
public QueryResult < Tuple < BaseItem , ItemCounts > > GetAllArtists ( InternalItemsQuery query )
{
return GetItemValues ( query , new [ ] { 0 , 1 } , typeof ( MusicArtist ) . FullName ) ;
}
2016-06-17 13:06:13 +00:00
public QueryResult < Tuple < BaseItem , ItemCounts > > GetArtists ( InternalItemsQuery query )
{
2016-08-06 04:38:01 +00:00
return GetItemValues ( query , new [ ] { 0 } , typeof ( MusicArtist ) . FullName ) ;
2016-06-17 13:06:13 +00:00
}
public QueryResult < Tuple < BaseItem , ItemCounts > > GetAlbumArtists ( InternalItemsQuery query )
{
2016-08-06 04:38:01 +00:00
return GetItemValues ( query , new [ ] { 1 } , typeof ( MusicArtist ) . FullName ) ;
2016-06-17 13:06:13 +00:00
}
public QueryResult < Tuple < BaseItem , ItemCounts > > GetStudios ( InternalItemsQuery query )
{
2016-08-06 04:38:01 +00:00
return GetItemValues ( query , new [ ] { 3 } , typeof ( Studio ) . FullName ) ;
2016-06-17 13:06:13 +00:00
}
public QueryResult < Tuple < BaseItem , ItemCounts > > GetGenres ( InternalItemsQuery query )
{
2016-08-06 04:38:01 +00:00
return GetItemValues ( query , new [ ] { 2 } , typeof ( Genre ) . FullName ) ;
2016-06-17 13:06:13 +00:00
}
public QueryResult < Tuple < BaseItem , ItemCounts > > GetGameGenres ( InternalItemsQuery query )
{
2016-08-06 04:38:01 +00:00
return GetItemValues ( query , new [ ] { 2 } , typeof ( GameGenre ) . FullName ) ;
2016-06-17 13:06:13 +00:00
}
public QueryResult < Tuple < BaseItem , ItemCounts > > GetMusicGenres ( InternalItemsQuery query )
{
2016-08-06 04:38:01 +00:00
return GetItemValues ( query , new [ ] { 2 } , typeof ( MusicGenre ) . FullName ) ;
2016-06-17 13:06:13 +00:00
}
2016-08-18 15:13:18 +00:00
public List < string > GetStudioNames ( )
{
2016-08-19 05:58:35 +00:00
return GetItemValueNames ( new [ ] { 3 } , new List < string > ( ) , new List < string > ( ) ) ;
2016-08-18 15:13:18 +00:00
}
public List < string > GetAllArtistNames ( )
{
2016-08-19 05:58:35 +00:00
return GetItemValueNames ( new [ ] { 0 , 1 } , new List < string > ( ) , new List < string > ( ) ) ;
2016-08-18 15:13:18 +00:00
}
2016-08-19 05:58:35 +00:00
public List < string > GetMusicGenreNames ( )
{
return GetItemValueNames ( new [ ] { 2 } , new List < string > { "Audio" , "MusicVideo" , "MusicAlbum" , "MusicArtist" } , new List < string > ( ) ) ;
}
public List < string > GetGameGenreNames ( )
{
return GetItemValueNames ( new [ ] { 2 } , new List < string > { "Game" } , new List < string > ( ) ) ;
}
public List < string > GetGenreNames ( )
{
return GetItemValueNames ( new [ ] { 2 } , new List < string > ( ) , new List < string > { "Audio" , "MusicVideo" , "MusicAlbum" , "MusicArtist" , "Game" , "GameSystem" } ) ;
}
private List < string > GetItemValueNames ( int [ ] itemValueTypes , List < string > withItemTypes , List < string > excludeItemTypes )
2016-08-18 15:13:18 +00:00
{
CheckDisposed ( ) ;
2016-08-19 05:58:35 +00:00
withItemTypes = withItemTypes . SelectMany ( MapIncludeItemTypes ) . ToList ( ) ;
excludeItemTypes = excludeItemTypes . SelectMany ( MapIncludeItemTypes ) . ToList ( ) ;
2016-08-18 15:13:18 +00:00
var now = DateTime . UtcNow ;
var typeClause = itemValueTypes . Length = = 1 ?
( "Type=" + itemValueTypes [ 0 ] . ToString ( CultureInfo . InvariantCulture ) ) :
( "Type in (" + string . Join ( "," , itemValueTypes . Select ( i = > i . ToString ( CultureInfo . InvariantCulture ) ) . ToArray ( ) ) + ")" ) ;
var list = new List < string > ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
{
2016-08-19 05:58:35 +00:00
cmd . CommandText = "Select Value From ItemValues where " + typeClause ;
if ( withItemTypes . Count > 0 )
{
var typeString = string . Join ( "," , withItemTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
cmd . CommandText + = " AND ItemId In (select guid from typedbaseitems where type in (" + typeString + "))" ;
}
if ( excludeItemTypes . Count > 0 )
{
var typeString = string . Join ( "," , excludeItemTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
cmd . CommandText + = " AND ItemId not In (select guid from typedbaseitems where type in (" + typeString + "))" ;
}
cmd . CommandText + = " Group By CleanValue" ;
2016-08-18 15:13:18 +00:00
var commandBehavior = CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ;
using ( var reader = cmd . ExecuteReader ( commandBehavior ) )
{
LogQueryTime ( "GetItemValueNames" , cmd , now ) ;
while ( reader . Read ( ) )
{
if ( ! reader . IsDBNull ( 0 ) )
{
list . Add ( reader . GetString ( 0 ) ) ;
}
}
}
}
return list ;
}
2016-08-06 04:38:01 +00:00
private QueryResult < Tuple < BaseItem , ItemCounts > > GetItemValues ( InternalItemsQuery query , int [ ] itemValueTypes , string returnType )
2016-06-17 13:06:13 +00:00
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
if ( ! query . Limit . HasValue )
{
query . EnableTotalRecordCount = false ;
}
CheckDisposed ( ) ;
var now = DateTime . UtcNow ;
2016-08-06 04:38:01 +00:00
var typeClause = itemValueTypes . Length = = 1 ?
( "Type=" + itemValueTypes [ 0 ] . ToString ( CultureInfo . InvariantCulture ) ) :
( "Type in (" + string . Join ( "," , itemValueTypes . Select ( i = > i . ToString ( CultureInfo . InvariantCulture ) ) . ToArray ( ) ) + ")" ) ;
2016-06-17 13:06:13 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
{
var itemCountColumns = new List < Tuple < string , string > > ( ) ;
var typesToCount = query . IncludeItemTypes . ToList ( ) ;
2016-06-28 04:47:30 +00:00
if ( typesToCount . Count > 0 )
2016-06-17 13:06:13 +00:00
{
2016-06-28 04:47:30 +00:00
var itemCountColumnQuery = "select group_concat(type, '|')" + GetFromText ( "B" ) ;
2016-06-17 13:06:13 +00:00
var typeSubQuery = new InternalItemsQuery ( query . User )
{
ExcludeItemTypes = query . ExcludeItemTypes ,
2016-06-28 04:47:30 +00:00
IncludeItemTypes = query . IncludeItemTypes ,
2016-06-17 13:06:13 +00:00
MediaTypes = query . MediaTypes ,
AncestorIds = query . AncestorIds ,
ExcludeItemIds = query . ExcludeItemIds ,
ItemIds = query . ItemIds ,
TopParentIds = query . TopParentIds ,
ParentId = query . ParentId ,
IsPlayed = query . IsPlayed
} ;
2016-06-28 04:47:30 +00:00
var whereClauses = GetWhereClauses ( typeSubQuery , cmd , "itemTypes" ) ;
2016-08-06 04:38:01 +00:00
whereClauses . Add ( "guid in (select ItemId from ItemValues where ItemValues.CleanValue=A.CleanName AND " + typeClause + ")" ) ;
2016-06-17 13:06:13 +00:00
var typeWhereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
itemCountColumnQuery + = typeWhereText ;
2016-06-28 04:47:30 +00:00
//itemCountColumnQuery += ")";
2016-06-17 13:06:13 +00:00
2016-06-28 04:47:30 +00:00
itemCountColumns . Add ( new Tuple < string , string > ( "itemTypes" , "(" + itemCountColumnQuery + ") as itemTypes" ) ) ;
2016-06-17 13:06:13 +00:00
}
var columns = _retriveItemColumns . ToList ( ) ;
columns . AddRange ( itemCountColumns . Select ( i = > i . Item2 ) . ToArray ( ) ) ;
cmd . CommandText = "select " + string . Join ( "," , GetFinalColumnsToSelect ( query , columns . ToArray ( ) , cmd ) ) + GetFromText ( ) ;
cmd . CommandText + = GetJoinUserDataText ( query ) ;
var innerQuery = new InternalItemsQuery ( query . User )
{
ExcludeItemTypes = query . ExcludeItemTypes ,
IncludeItemTypes = query . IncludeItemTypes ,
MediaTypes = query . MediaTypes ,
AncestorIds = query . AncestorIds ,
ExcludeItemIds = query . ExcludeItemIds ,
ItemIds = query . ItemIds ,
TopParentIds = query . TopParentIds ,
ParentId = query . ParentId ,
IsPlayed = query . IsPlayed
} ;
var innerWhereClauses = GetWhereClauses ( innerQuery , cmd ) ;
var innerWhereText = innerWhereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , innerWhereClauses . ToArray ( ) ) ;
var whereText = " where Type=@SelectType" ;
2016-06-28 04:47:30 +00:00
if ( typesToCount . Count = = 0 )
{
2016-08-06 04:38:01 +00:00
whereText + = " And CleanName In (Select CleanValue from ItemValues where " + typeClause + " AND ItemId in (select guid from TypedBaseItems" + innerWhereText + "))" ;
2016-06-28 04:47:30 +00:00
}
else
{
2016-06-29 16:31:01 +00:00
//whereText += " And itemTypes not null";
2016-08-06 04:38:01 +00:00
whereText + = " And CleanName In (Select CleanValue from ItemValues where " + typeClause + " AND ItemId in (select guid from TypedBaseItems" + innerWhereText + "))" ;
2016-06-28 04:47:30 +00:00
}
2016-06-17 13:06:13 +00:00
var outerQuery = new InternalItemsQuery ( query . User )
{
IsFavorite = query . IsFavorite ,
IsFavoriteOrLiked = query . IsFavoriteOrLiked ,
IsLiked = query . IsLiked ,
IsLocked = query . IsLocked ,
NameLessThan = query . NameLessThan ,
NameStartsWith = query . NameStartsWith ,
NameStartsWithOrGreater = query . NameStartsWithOrGreater ,
AlbumArtistStartsWithOrGreater = query . AlbumArtistStartsWithOrGreater ,
Tags = query . Tags ,
OfficialRatings = query . OfficialRatings ,
2016-08-13 20:54:29 +00:00
GenreIds = query . GenreIds ,
Genres = query . Genres ,
2016-06-17 13:06:13 +00:00
Years = query . Years
} ;
var outerWhereClauses = GetWhereClauses ( outerQuery , cmd ) ;
2016-06-18 00:52:04 +00:00
whereText + = outerWhereClauses . Count = = 0 ?
2016-06-17 13:06:13 +00:00
string . Empty :
" AND " + string . Join ( " AND " , outerWhereClauses . ToArray ( ) ) ;
2016-06-18 00:52:04 +00:00
//cmd.CommandText += GetGroupBy(query);
cmd . CommandText + = whereText ;
cmd . CommandText + = " group by PresentationUniqueKey" ;
2016-06-17 13:06:13 +00:00
cmd . Parameters . Add ( cmd , "@SelectType" , DbType . String ) . Value = returnType ;
if ( EnableJoinUserData ( query ) )
{
cmd . Parameters . Add ( cmd , "@UserId" , DbType . Guid ) . Value = query . User . Id ;
}
cmd . CommandText + = " order by SortName" ;
if ( query . Limit . HasValue | | query . StartIndex . HasValue )
{
2016-06-22 20:08:07 +00:00
var offset = query . StartIndex ? ? 0 ;
2016-06-17 13:06:13 +00:00
2016-06-22 20:08:07 +00:00
if ( query . Limit . HasValue | | offset > 0 )
{
cmd . CommandText + = " LIMIT " + ( query . Limit ? ? int . MaxValue ) . ToString ( CultureInfo . InvariantCulture ) ;
}
2016-06-17 13:06:13 +00:00
2016-06-22 20:08:07 +00:00
if ( offset > 0 )
2016-06-17 13:06:13 +00:00
{
2016-06-22 20:08:07 +00:00
cmd . CommandText + = " OFFSET " + offset . ToString ( CultureInfo . InvariantCulture ) ;
2016-06-17 13:06:13 +00:00
}
}
cmd . CommandText + = ";" ;
var isReturningZeroItems = query . Limit . HasValue & & query . Limit < = 0 ;
if ( isReturningZeroItems )
{
cmd . CommandText = "" ;
}
if ( query . EnableTotalRecordCount )
{
2016-06-18 00:52:04 +00:00
cmd . CommandText + = "select count (distinct PresentationUniqueKey)" + GetFromText ( ) ;
2016-06-17 13:06:13 +00:00
cmd . CommandText + = GetJoinUserDataText ( query ) ;
cmd . CommandText + = whereText ;
}
else
{
cmd . CommandText = cmd . CommandText . TrimEnd ( ';' ) ;
}
var list = new List < Tuple < BaseItem , ItemCounts > > ( ) ;
var count = 0 ;
var commandBehavior = isReturningZeroItems | | ! query . EnableTotalRecordCount
? ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult )
: CommandBehavior . SequentialAccess ;
2016-08-13 05:49:00 +00:00
//Logger.Debug("GetItemValues: " + cmd.CommandText);
2016-06-28 04:47:30 +00:00
2016-06-17 13:06:13 +00:00
using ( var reader = cmd . ExecuteReader ( commandBehavior ) )
{
LogQueryTime ( "GetItemValues" , cmd , now ) ;
if ( isReturningZeroItems )
{
if ( reader . Read ( ) )
{
count = reader . GetInt32 ( 0 ) ;
}
}
else
{
while ( reader . Read ( ) )
{
var item = GetItem ( reader ) ;
if ( item ! = null )
{
2016-06-28 04:47:30 +00:00
var countStartColumn = columns . Count - 1 ;
2016-06-17 13:06:13 +00:00
list . Add ( new Tuple < BaseItem , ItemCounts > ( item , GetItemCounts ( reader , countStartColumn , typesToCount ) ) ) ;
}
}
if ( reader . NextResult ( ) & & reader . Read ( ) )
{
count = reader . GetInt32 ( 0 ) ;
}
}
}
if ( count = = 0 )
{
count = list . Count ;
}
return new QueryResult < Tuple < BaseItem , ItemCounts > >
{
Items = list . ToArray ( ) ,
TotalRecordCount = count
} ;
}
}
private ItemCounts GetItemCounts ( IDataReader reader , int countStartColumn , List < string > typesToCount )
{
var counts = new ItemCounts ( ) ;
2016-06-28 04:47:30 +00:00
if ( typesToCount . Count = = 0 )
{
return counts ;
}
var typeString = reader . IsDBNull ( countStartColumn ) ? null : reader . GetString ( countStartColumn ) ;
if ( string . IsNullOrWhiteSpace ( typeString ) )
2016-06-17 13:06:13 +00:00
{
2016-06-28 04:47:30 +00:00
return counts ;
}
2016-06-17 13:06:13 +00:00
2016-06-29 03:17:27 +00:00
var allTypes = typeString . Split ( new [ ] { '|' } , StringSplitOptions . RemoveEmptyEntries )
2016-06-28 04:47:30 +00:00
. ToLookup ( i = > i ) . ToList ( ) ;
foreach ( var type in allTypes )
{
var value = type . ToList ( ) . Count ;
var typeName = type . Key ;
if ( string . Equals ( typeName , typeof ( Series ) . FullName , StringComparison . OrdinalIgnoreCase ) )
2016-06-17 13:06:13 +00:00
{
counts . SeriesCount = value ;
}
2016-06-28 04:47:30 +00:00
else if ( string . Equals ( typeName , typeof ( Episode ) . FullName , StringComparison . OrdinalIgnoreCase ) )
2016-06-17 13:06:13 +00:00
{
counts . EpisodeCount = value ;
}
2016-06-28 04:47:30 +00:00
else if ( string . Equals ( typeName , typeof ( Movie ) . FullName , StringComparison . OrdinalIgnoreCase ) )
2016-06-17 13:06:13 +00:00
{
counts . MovieCount = value ;
}
2016-06-28 04:47:30 +00:00
else if ( string . Equals ( typeName , typeof ( MusicAlbum ) . FullName , StringComparison . OrdinalIgnoreCase ) )
2016-06-17 13:06:13 +00:00
{
counts . AlbumCount = value ;
}
2016-08-13 20:54:29 +00:00
else if ( string . Equals ( typeName , typeof ( MusicArtist ) . FullName , StringComparison . OrdinalIgnoreCase ) )
{
counts . ArtistCount = value ;
}
2016-06-28 04:47:30 +00:00
else if ( string . Equals ( typeName , typeof ( Audio ) . FullName , StringComparison . OrdinalIgnoreCase ) )
2016-06-17 13:06:13 +00:00
{
counts . SongCount = value ;
}
2016-06-28 04:47:30 +00:00
else if ( string . Equals ( typeName , typeof ( Game ) . FullName , StringComparison . OrdinalIgnoreCase ) )
2016-06-17 13:06:13 +00:00
{
counts . GameCount = value ;
}
2016-06-28 04:47:30 +00:00
else if ( string . Equals ( typeName , typeof ( Trailer ) . FullName , StringComparison . OrdinalIgnoreCase ) )
{
counts . TrailerCount = value ;
}
2016-06-17 13:06:13 +00:00
counts . ItemCount + = value ;
}
return counts ;
}
private List < Tuple < int , string > > GetItemValuesToSave ( BaseItem item )
2016-05-18 05:34:10 +00:00
{
var list = new List < Tuple < int , string > > ( ) ;
var hasArtist = item as IHasArtist ;
if ( hasArtist ! = null )
{
list . AddRange ( hasArtist . Artists . Select ( i = > new Tuple < int , string > ( 0 , i ) ) ) ;
}
var hasAlbumArtist = item as IHasAlbumArtist ;
if ( hasAlbumArtist ! = null )
{
list . AddRange ( hasAlbumArtist . AlbumArtists . Select ( i = > new Tuple < int , string > ( 1 , i ) ) ) ;
}
2016-05-31 18:07:54 +00:00
list . AddRange ( item . Genres . Select ( i = > new Tuple < int , string > ( 2 , i ) ) ) ;
list . AddRange ( item . Studios . Select ( i = > new Tuple < int , string > ( 3 , i ) ) ) ;
list . AddRange ( item . Tags . Select ( i = > new Tuple < int , string > ( 4 , i ) ) ) ;
list . AddRange ( item . Keywords . Select ( i = > new Tuple < int , string > ( 5 , i ) ) ) ;
2016-05-18 05:34:10 +00:00
return list ;
}
2016-06-12 23:33:11 +00:00
private void UpdateImages ( Guid itemId , List < ItemImageInfo > images , IDbTransaction transaction )
2016-06-03 16:24:04 +00:00
{
if ( itemId = = Guid . Empty )
{
throw new ArgumentNullException ( "itemId" ) ;
}
if ( images = = null )
{
throw new ArgumentNullException ( "images" ) ;
}
CheckDisposed ( ) ;
// First delete
2016-06-12 23:33:11 +00:00
_deleteImagesCommand . GetParameter ( 0 ) . Value = itemId ;
_deleteImagesCommand . Transaction = transaction ;
2016-06-03 16:24:04 +00:00
2016-06-12 23:33:11 +00:00
_deleteImagesCommand . ExecuteNonQuery ( ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
var index = 0 ;
foreach ( var image in images )
{
2016-08-20 21:58:44 +00:00
if ( string . IsNullOrWhiteSpace ( image . Path ) )
{
// Invalid
continue ;
}
2016-06-12 23:33:11 +00:00
_saveImagesCommand . GetParameter ( 0 ) . Value = itemId ;
_saveImagesCommand . GetParameter ( 1 ) . Value = image . Type ;
_saveImagesCommand . GetParameter ( 2 ) . Value = image . Path ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
if ( image . DateModified = = default ( DateTime ) )
{
_saveImagesCommand . GetParameter ( 3 ) . Value = null ;
}
else
{
_saveImagesCommand . GetParameter ( 3 ) . Value = image . DateModified ;
2016-06-03 16:24:04 +00:00
}
2016-06-12 23:33:11 +00:00
_saveImagesCommand . GetParameter ( 4 ) . Value = image . IsPlaceholder ;
_saveImagesCommand . GetParameter ( 5 ) . Value = index ;
2016-06-03 16:24:04 +00:00
2016-06-12 23:33:11 +00:00
_saveImagesCommand . Transaction = transaction ;
2016-06-03 16:24:04 +00:00
2016-06-12 23:33:11 +00:00
_saveImagesCommand . ExecuteNonQuery ( ) ;
index + + ;
2016-06-03 16:24:04 +00:00
}
}
2016-06-12 23:33:11 +00:00
private void UpdateProviderIds ( Guid itemId , Dictionary < string , string > values , IDbTransaction transaction )
2016-06-02 04:41:12 +00:00
{
if ( itemId = = Guid . Empty )
{
throw new ArgumentNullException ( "itemId" ) ;
}
if ( values = = null )
{
2016-06-03 16:24:04 +00:00
throw new ArgumentNullException ( "values" ) ;
2016-06-02 04:41:12 +00:00
}
2016-07-15 17:14:20 +00:00
// Just in case there might be case-insensitive duplicates, strip them out now
var newValues = new Dictionary < string , string > ( StringComparer . OrdinalIgnoreCase ) ;
foreach ( var pair in values )
{
newValues [ pair . Key ] = pair . Value ;
}
2016-06-02 04:41:12 +00:00
CheckDisposed ( ) ;
// First delete
2016-06-12 23:33:11 +00:00
_deleteProviderIdsCommand . GetParameter ( 0 ) . Value = itemId ;
_deleteProviderIdsCommand . Transaction = transaction ;
2016-06-02 04:41:12 +00:00
2016-06-12 23:33:11 +00:00
_deleteProviderIdsCommand . ExecuteNonQuery ( ) ;
2016-06-02 04:41:12 +00:00
2016-07-15 17:14:20 +00:00
foreach ( var pair in newValues )
2016-06-02 04:41:12 +00:00
{
2016-06-12 23:33:11 +00:00
_saveProviderIdsCommand . GetParameter ( 0 ) . Value = itemId ;
_saveProviderIdsCommand . GetParameter ( 1 ) . Value = pair . Key ;
_saveProviderIdsCommand . GetParameter ( 2 ) . Value = pair . Value ;
_saveProviderIdsCommand . Transaction = transaction ;
2016-06-02 04:41:12 +00:00
2016-06-12 23:33:11 +00:00
_saveProviderIdsCommand . ExecuteNonQuery ( ) ;
2016-06-02 04:41:12 +00:00
}
}
2016-06-12 23:33:11 +00:00
private void UpdateItemValues ( Guid itemId , List < Tuple < int , string > > values , IDbTransaction transaction )
2016-05-18 05:34:10 +00:00
{
if ( itemId = = Guid . Empty )
{
throw new ArgumentNullException ( "itemId" ) ;
}
if ( values = = null )
{
throw new ArgumentNullException ( "keys" ) ;
}
CheckDisposed ( ) ;
// First delete
2016-06-12 23:33:11 +00:00
_deleteItemValuesCommand . GetParameter ( 0 ) . Value = itemId ;
_deleteItemValuesCommand . Transaction = transaction ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
_deleteItemValuesCommand . ExecuteNonQuery ( ) ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
foreach ( var pair in values )
2016-05-18 05:34:10 +00:00
{
2016-06-12 23:33:11 +00:00
_saveItemValuesCommand . GetParameter ( 0 ) . Value = itemId ;
_saveItemValuesCommand . GetParameter ( 1 ) . Value = pair . Item1 ;
_saveItemValuesCommand . GetParameter ( 2 ) . Value = pair . Item2 ;
2016-06-17 13:06:13 +00:00
if ( pair . Item2 = = null )
{
_saveItemValuesCommand . GetParameter ( 3 ) . Value = null ;
}
else
{
2016-08-06 20:59:31 +00:00
_saveItemValuesCommand . GetParameter ( 3 ) . Value = GetCleanValue ( pair . Item2 ) ;
2016-06-17 13:06:13 +00:00
}
2016-06-12 23:33:11 +00:00
_saveItemValuesCommand . Transaction = transaction ;
2016-05-18 05:34:10 +00:00
2016-06-12 23:33:11 +00:00
_saveItemValuesCommand . ExecuteNonQuery ( ) ;
2016-05-18 05:34:10 +00:00
}
}
2016-06-12 23:33:11 +00:00
private void UpdateUserDataKeys ( Guid itemId , List < string > keys , IDbTransaction transaction )
2016-05-08 06:31:08 +00:00
{
if ( itemId = = Guid . Empty )
{
throw new ArgumentNullException ( "itemId" ) ;
}
if ( keys = = null )
{
throw new ArgumentNullException ( "keys" ) ;
}
CheckDisposed ( ) ;
// First delete
2016-06-12 23:33:11 +00:00
_deleteUserDataKeysCommand . GetParameter ( 0 ) . Value = itemId ;
_deleteUserDataKeysCommand . Transaction = transaction ;
2016-05-08 06:31:08 +00:00
2016-06-12 23:33:11 +00:00
_deleteUserDataKeysCommand . ExecuteNonQuery ( ) ;
2016-05-08 06:31:08 +00:00
var index = 0 ;
2016-06-12 23:33:11 +00:00
foreach ( var key in keys )
2016-06-11 20:12:01 +00:00
{
2016-06-12 23:33:11 +00:00
_saveUserDataKeysCommand . GetParameter ( 0 ) . Value = itemId ;
_saveUserDataKeysCommand . GetParameter ( 1 ) . Value = key ;
_saveUserDataKeysCommand . GetParameter ( 2 ) . Value = index ;
index + + ;
_saveUserDataKeysCommand . Transaction = transaction ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
_saveUserDataKeysCommand . ExecuteNonQuery ( ) ;
2016-05-08 06:31:08 +00:00
}
}
2015-06-29 01:10:45 +00:00
public async Task UpdatePeople ( Guid itemId , List < PersonInfo > people )
{
if ( itemId = = Guid . Empty )
{
throw new ArgumentNullException ( "itemId" ) ;
}
if ( people = = null )
{
throw new ArgumentNullException ( "people" ) ;
}
CheckDisposed ( ) ;
var cancellationToken = CancellationToken . None ;
2016-06-12 23:33:11 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
IDbTransaction transaction = null ;
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
try
{
transaction = _connection . BeginTransaction ( ) ;
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
// First delete
_deletePeopleCommand . GetParameter ( 0 ) . Value = itemId ;
_deletePeopleCommand . Transaction = transaction ;
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
_deletePeopleCommand . ExecuteNonQuery ( ) ;
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
var listIndex = 0 ;
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
foreach ( var person in people )
2015-06-29 01:10:45 +00:00
{
2016-06-12 23:33:11 +00:00
cancellationToken . ThrowIfCancellationRequested ( ) ;
_savePersonCommand . GetParameter ( 0 ) . Value = itemId ;
_savePersonCommand . GetParameter ( 1 ) . Value = person . Name ;
_savePersonCommand . GetParameter ( 2 ) . Value = person . Role ;
_savePersonCommand . GetParameter ( 3 ) . Value = person . Type ;
_savePersonCommand . GetParameter ( 4 ) . Value = person . SortOrder ;
_savePersonCommand . GetParameter ( 5 ) . Value = listIndex ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
_savePersonCommand . Transaction = transaction ;
_savePersonCommand . ExecuteNonQuery ( ) ;
listIndex + + ;
2015-06-29 01:10:45 +00:00
}
2016-06-12 23:33:11 +00:00
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
2016-06-11 20:12:01 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Rollback ( ) ;
}
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
throw ;
}
catch ( Exception e )
{
Logger . ErrorException ( "Failed to save people:" , e ) ;
2015-06-29 01:10:45 +00:00
2016-06-12 23:33:11 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
2015-06-29 01:10:45 +00:00
}
2016-06-12 23:33:11 +00:00
throw ;
}
finally
{
if ( transaction ! = null )
2015-06-29 01:10:45 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Dispose ( ) ;
2015-06-29 01:10:45 +00:00
}
2016-06-12 23:33:11 +00:00
WriteLock . Release ( ) ;
2015-06-29 01:10:45 +00:00
}
}
private PersonInfo GetPerson ( IDataReader reader )
{
var item = new PersonInfo ( ) ;
2015-07-08 16:10:34 +00:00
item . ItemId = reader . GetGuid ( 0 ) ;
2015-06-29 01:10:45 +00:00
item . Name = reader . GetString ( 1 ) ;
if ( ! reader . IsDBNull ( 2 ) )
{
item . Role = reader . GetString ( 2 ) ;
}
if ( ! reader . IsDBNull ( 3 ) )
{
item . Type = reader . GetString ( 3 ) ;
}
if ( ! reader . IsDBNull ( 4 ) )
{
item . SortOrder = reader . GetInt32 ( 4 ) ;
}
return item ;
}
2015-10-14 02:41:46 +00:00
public IEnumerable < MediaStream > GetMediaStreams ( MediaStreamQuery query )
{
CheckDisposed ( ) ;
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
2016-05-10 18:13:26 +00:00
var list = new List < MediaStream > ( ) ;
2016-06-12 23:33:11 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2015-10-14 02:41:46 +00:00
{
2016-06-12 23:33:11 +00:00
var cmdText = "select " + string . Join ( "," , _mediaStreamSaveColumns ) + " from mediastreams where" ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
cmdText + = " ItemId=@ItemId" ;
cmd . Parameters . Add ( cmd , "@ItemId" , DbType . Guid ) . Value = query . ItemId ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
if ( query . Type . HasValue )
{
cmdText + = " AND StreamType=@StreamType" ;
cmd . Parameters . Add ( cmd , "@StreamType" , DbType . String ) . Value = query . Type . Value . ToString ( ) ;
}
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
if ( query . Index . HasValue )
{
cmdText + = " AND StreamIndex=@StreamIndex" ;
cmd . Parameters . Add ( cmd , "@StreamIndex" , DbType . Int32 ) . Value = query . Index . Value ;
}
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
cmdText + = " order by StreamIndex ASC" ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
cmd . CommandText = cmdText ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
2015-10-14 02:41:46 +00:00
{
2016-06-12 23:33:11 +00:00
list . Add ( GetMediaStream ( reader ) ) ;
2015-10-14 02:41:46 +00:00
}
}
}
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
return list ;
2015-10-14 02:41:46 +00:00
}
2016-06-11 20:12:01 +00:00
public async Task SaveMediaStreams ( Guid id , List < MediaStream > streams , CancellationToken cancellationToken )
2015-10-14 02:41:46 +00:00
{
CheckDisposed ( ) ;
if ( id = = Guid . Empty )
{
throw new ArgumentNullException ( "id" ) ;
}
if ( streams = = null )
{
throw new ArgumentNullException ( "streams" ) ;
}
cancellationToken . ThrowIfCancellationRequested ( ) ;
2016-06-12 23:33:11 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
IDbTransaction transaction = null ;
try
2015-10-14 02:41:46 +00:00
{
2016-06-12 23:33:11 +00:00
transaction = _connection . BeginTransaction ( ) ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
// First delete chapters
_deleteStreamsCommand . GetParameter ( 0 ) . Value = id ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
_deleteStreamsCommand . Transaction = transaction ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
_deleteStreamsCommand . ExecuteNonQuery ( ) ;
2016-06-06 21:13:00 +00:00
2016-06-12 23:33:11 +00:00
foreach ( var stream in streams )
2015-10-14 02:41:46 +00:00
{
2016-06-12 23:33:11 +00:00
cancellationToken . ThrowIfCancellationRequested ( ) ;
var index = 0 ;
_saveStreamCommand . GetParameter ( index + + ) . Value = id ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Index ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Type . ToString ( ) ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Codec ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Language ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . ChannelLayout ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Profile ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . AspectRatio ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Path ;
2016-06-11 20:12:01 +00:00
2016-06-12 23:33:11 +00:00
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . IsInterlaced ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . BitRate ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Channels ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . SampleRate ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . IsDefault ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . IsForced ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . IsExternal ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Width ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Height ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . AverageFrameRate ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . RealFrameRate ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Level ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . PixelFormat ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . BitDepth ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . IsAnamorphic ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . RefFrames ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . CodecTag ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Comment ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . NalLengthSize ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . IsAVC ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Title ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . TimeBase ;
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . CodecTimeBase ;
_saveStreamCommand . Transaction = transaction ;
_saveStreamCommand . ExecuteNonQuery ( ) ;
2015-10-14 02:41:46 +00:00
}
2016-06-12 23:33:11 +00:00
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
2016-06-11 20:12:01 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Rollback ( ) ;
}
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
throw ;
}
catch ( Exception e )
{
Logger . ErrorException ( "Failed to save media streams:" , e ) ;
2015-10-14 02:41:46 +00:00
2016-06-12 23:33:11 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
2015-10-14 02:41:46 +00:00
}
2016-06-12 23:33:11 +00:00
throw ;
}
finally
{
if ( transaction ! = null )
2015-10-14 02:41:46 +00:00
{
2016-06-12 23:33:11 +00:00
transaction . Dispose ( ) ;
2015-10-14 02:41:46 +00:00
}
2016-06-12 23:33:11 +00:00
WriteLock . Release ( ) ;
2015-10-14 02:41:46 +00:00
}
}
/// <summary>
/// Gets the chapter.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>ChapterInfo.</returns>
private MediaStream GetMediaStream ( IDataReader reader )
{
var item = new MediaStream
{
Index = reader . GetInt32 ( 1 )
} ;
item . Type = ( MediaStreamType ) Enum . Parse ( typeof ( MediaStreamType ) , reader . GetString ( 2 ) , true ) ;
if ( ! reader . IsDBNull ( 3 ) )
{
item . Codec = reader . GetString ( 3 ) ;
}
if ( ! reader . IsDBNull ( 4 ) )
{
item . Language = reader . GetString ( 4 ) ;
}
if ( ! reader . IsDBNull ( 5 ) )
{
item . ChannelLayout = reader . GetString ( 5 ) ;
}
if ( ! reader . IsDBNull ( 6 ) )
{
item . Profile = reader . GetString ( 6 ) ;
}
if ( ! reader . IsDBNull ( 7 ) )
{
item . AspectRatio = reader . GetString ( 7 ) ;
}
if ( ! reader . IsDBNull ( 8 ) )
{
item . Path = reader . GetString ( 8 ) ;
}
item . IsInterlaced = reader . GetBoolean ( 9 ) ;
if ( ! reader . IsDBNull ( 10 ) )
{
item . BitRate = reader . GetInt32 ( 10 ) ;
}
if ( ! reader . IsDBNull ( 11 ) )
{
item . Channels = reader . GetInt32 ( 11 ) ;
}
if ( ! reader . IsDBNull ( 12 ) )
{
item . SampleRate = reader . GetInt32 ( 12 ) ;
}
item . IsDefault = reader . GetBoolean ( 13 ) ;
item . IsForced = reader . GetBoolean ( 14 ) ;
item . IsExternal = reader . GetBoolean ( 15 ) ;
if ( ! reader . IsDBNull ( 16 ) )
{
item . Width = reader . GetInt32 ( 16 ) ;
}
if ( ! reader . IsDBNull ( 17 ) )
{
item . Height = reader . GetInt32 ( 17 ) ;
}
if ( ! reader . IsDBNull ( 18 ) )
{
item . AverageFrameRate = reader . GetFloat ( 18 ) ;
}
if ( ! reader . IsDBNull ( 19 ) )
{
item . RealFrameRate = reader . GetFloat ( 19 ) ;
}
if ( ! reader . IsDBNull ( 20 ) )
{
item . Level = reader . GetFloat ( 20 ) ;
}
if ( ! reader . IsDBNull ( 21 ) )
{
item . PixelFormat = reader . GetString ( 21 ) ;
}
if ( ! reader . IsDBNull ( 22 ) )
{
item . BitDepth = reader . GetInt32 ( 22 ) ;
}
if ( ! reader . IsDBNull ( 23 ) )
{
item . IsAnamorphic = reader . GetBoolean ( 23 ) ;
}
if ( ! reader . IsDBNull ( 24 ) )
{
item . RefFrames = reader . GetInt32 ( 24 ) ;
}
2016-04-18 04:25:12 +00:00
if ( ! reader . IsDBNull ( 25 ) )
2015-10-14 02:41:46 +00:00
{
2016-04-18 04:25:12 +00:00
item . CodecTag = reader . GetString ( 25 ) ;
2015-10-27 14:02:30 +00:00
}
2016-04-18 04:25:12 +00:00
if ( ! reader . IsDBNull ( 26 ) )
2016-01-11 16:52:22 +00:00
{
2016-04-18 04:25:12 +00:00
item . Comment = reader . GetString ( 26 ) ;
2016-01-11 16:52:22 +00:00
}
2016-04-18 04:25:12 +00:00
if ( ! reader . IsDBNull ( 27 ) )
2016-04-18 03:50:44 +00:00
{
2016-04-18 04:25:12 +00:00
item . NalLengthSize = reader . GetString ( 27 ) ;
2016-04-18 03:50:44 +00:00
}
2016-04-27 19:23:05 +00:00
if ( ! reader . IsDBNull ( 28 ) )
{
item . IsAVC = reader . GetBoolean ( 28 ) ;
}
2016-05-14 18:02:06 +00:00
if ( ! reader . IsDBNull ( 29 ) )
{
item . Title = reader . GetString ( 29 ) ;
}
2016-06-06 21:13:00 +00:00
if ( ! reader . IsDBNull ( 30 ) )
{
item . TimeBase = reader . GetString ( 30 ) ;
}
if ( ! reader . IsDBNull ( 31 ) )
{
item . CodecTimeBase = reader . GetString ( 31 ) ;
}
2015-10-14 02:41:46 +00:00
return item ;
}
2013-06-18 09:43:07 +00:00
}
}