2013-06-18 09:43:07 +00:00
using MediaBrowser.Common.Configuration ;
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 ;
2013-06-18 09:43:07 +00:00
using System.Threading ;
using System.Threading.Tasks ;
2015-10-04 18:10:50 +00:00
using MediaBrowser.Controller.Channels ;
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
{
2013-09-29 22:00:08 +00:00
private IDbConnection _connection ;
2013-06-18 09:43:07 +00:00
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>
private readonly IApplicationPaths _appPaths ;
/// <summary>
/// The _save item command
/// </summary>
2013-09-29 22:00:08 +00:00
private IDbCommand _saveItemCommand ;
2013-06-18 09:43:07 +00:00
private readonly string _criticReviewsPath ;
2013-09-29 22:00:08 +00:00
private IDbCommand _deleteChildrenCommand ;
private IDbCommand _saveChildrenCommand ;
2014-02-19 18:50:37 +00:00
private IDbCommand _deleteItemCommand ;
2013-09-29 22:00:08 +00:00
2015-06-29 01:10:45 +00:00
private IDbCommand _deletePeopleCommand ;
private IDbCommand _savePersonCommand ;
2015-08-26 05:10:04 +00:00
2015-10-13 16:52:27 +00:00
private IDbCommand _deleteChaptersCommand ;
private IDbCommand _saveChapterCommand ;
2015-10-14 02:41:46 +00:00
private IDbCommand _deleteStreamsCommand ;
private IDbCommand _saveStreamCommand ;
2015-12-27 18:37:06 +00:00
private IDbCommand _deleteAncestorsCommand ;
private IDbCommand _saveAncestorCommand ;
private IDbCommand _updateInheritedRatingCommand ;
2016-02-01 19:54:49 +00:00
private const int LatestSchemaVersion = 44 ;
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>
/// <param name="appPaths">The app paths.</param>
/// <param name="jsonSerializer">The json serializer.</param>
/// <param name="logManager">The log manager.</param>
/// <exception cref="System.ArgumentNullException">
/// appPaths
/// or
/// jsonSerializer
/// </exception>
public SqliteItemRepository ( IApplicationPaths appPaths , IJsonSerializer jsonSerializer , ILogManager logManager )
2016-02-10 18:13:24 +00:00
: base ( logManager )
2013-06-18 09:43:07 +00:00
{
if ( appPaths = = null )
{
throw new ArgumentNullException ( "appPaths" ) ;
}
if ( jsonSerializer = = null )
{
throw new ArgumentNullException ( "jsonSerializer" ) ;
}
_appPaths = appPaths ;
_jsonSerializer = jsonSerializer ;
_criticReviewsPath = Path . Combine ( _appPaths . DataPath , "critic-reviews" ) ;
}
2015-10-13 16:52:27 +00:00
private const string ChaptersTableName = "Chapters2" ;
2013-06-18 09:43:07 +00:00
/// <summary>
/// Opens the connection to the database
/// </summary>
/// <returns>Task.</returns>
public async Task Initialize ( )
{
var dbFile = Path . Combine ( _appPaths . DataPath , "library.db" ) ;
2013-09-29 22:00:08 +00:00
2016-02-10 18:13:24 +00:00
_connection = await SqliteExtensions . ConnectToDb ( dbFile , Logger ) . ConfigureAwait ( false ) ;
2013-06-18 09:43:07 +00:00
2015-10-14 02:41:46 +00:00
var createMediaStreamsTableCommand
2016-01-11 16:52:22 +00:00
= "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, IsCabac BIT NULL, CodecTag TEXT NULL, Comment TEXT NULL, PRIMARY KEY (ItemId, StreamIndex))" ;
2015-10-14 02:41:46 +00:00
2013-06-18 09:43:07 +00:00
string [ ] queries = {
2015-12-27 18:37:06 +00:00
"create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB, ParentId GUID)" ,
2013-06-27 13:31:57 +00:00
"create index if not exists idx_TypedBaseItems on TypedBaseItems(guid)" ,
2015-12-27 18:37:06 +00:00
"create index if not exists idx_ParentIdTypedBaseItems on TypedBaseItems(ParentId)" ,
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)" ,
2013-06-26 16:08:16 +00:00
"create table if not exists ChildrenIds (ParentId GUID, ItemId GUID, PRIMARY KEY (ParentId, ItemId))" ,
"create index if not exists idx_ChildrenIds on ChildrenIds(ParentId,ItemId)" ,
2013-06-20 16:44:24 +00:00
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)" ,
2015-12-27 18:37:06 +00:00
"create index if not exists idxPeopleItemId on People(ItemId)" ,
"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))" ,
"create index if not exists idx_" + ChaptersTableName + " on " + ChaptersTableName + "(ItemId, ChapterIndex)" ,
2015-10-14 02:41:46 +00:00
createMediaStreamsTableCommand ,
"create index if not exists idx_mediastreams on mediastreams(ItemId, StreamIndex)" ,
2013-06-18 09:43:07 +00:00
//pragmas
2013-12-08 01:42:15 +00:00
"pragma temp_store = memory" ,
"pragma shrink_memory"
2013-06-18 09:43:07 +00:00
} ;
2016-02-10 18:13:24 +00:00
_connection . RunQueries ( queries , Logger ) ;
2013-06-18 09:43:07 +00:00
2016-02-10 18:13:24 +00:00
_connection . AddColumn ( Logger , "AncestorIds" , "AncestorIdText" , "Text" ) ;
2015-12-27 18:37:06 +00:00
2016-02-10 18:13:24 +00:00
_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" , "ParentalRatingValue" , "INT" ) ;
_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" ) ;
2015-12-27 18:37:06 +00:00
2013-06-18 09:43:07 +00:00
PrepareStatements ( ) ;
2013-12-08 01:42:15 +00:00
2016-02-10 18:13:24 +00:00
new MediaStreamColumns ( _connection , Logger ) . AddColumns ( ) ;
2015-10-13 16:52:27 +00:00
var chapterDbFile = Path . Combine ( _appPaths . DataPath , "chapters.db" ) ;
if ( File . Exists ( chapterDbFile ) )
{
MigrateChapters ( chapterDbFile ) ;
}
2015-10-14 02:41:46 +00:00
var mediaStreamsDbFile = Path . Combine ( _appPaths . DataPath , "mediainfo.db" ) ;
if ( File . Exists ( mediaStreamsDbFile ) )
{
MigrateMediaStreams ( mediaStreamsDbFile ) ;
}
}
private void MigrateMediaStreams ( string file )
{
2015-10-28 20:24:07 +00:00
try
{
var backupFile = file + ".bak" ;
File . Copy ( file , backupFile , true ) ;
SqliteExtensions . Attach ( _connection , backupFile , "MediaInfoOld" ) ;
2015-10-14 02:41:46 +00:00
2015-10-28 20:24:07 +00:00
var columns = string . Join ( "," , _mediaStreamSaveColumns ) ;
2015-10-14 02:41:46 +00:00
2015-10-28 20:24:07 +00:00
string [ ] queries = {
2015-10-17 15:05:12 +00:00
"REPLACE INTO mediastreams(" + columns + ") SELECT " + columns + " FROM MediaInfoOld.mediastreams;"
2015-10-14 02:41:46 +00:00
} ;
2016-02-10 18:13:24 +00:00
_connection . RunQueries ( queries , Logger ) ;
2015-10-14 02:41:46 +00:00
}
catch ( Exception ex )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Error migrating media info database" , ex ) ;
2015-10-14 02:41:46 +00:00
}
2015-10-28 20:24:07 +00:00
finally
{
TryDeleteFile ( file ) ;
}
2015-10-13 16:52:27 +00:00
}
private void MigrateChapters ( string file )
{
2015-10-28 20:24:07 +00:00
try
{
var backupFile = file + ".bak" ;
File . Copy ( file , backupFile , true ) ;
SqliteExtensions . Attach ( _connection , backupFile , "ChaptersOld" ) ;
2015-10-13 16:52:27 +00:00
2015-10-28 20:24:07 +00:00
string [ ] queries = {
2015-10-17 15:05:12 +00:00
"REPLACE INTO " + ChaptersTableName + "(ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath) SELECT ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath FROM ChaptersOld.Chapters;"
2015-10-13 16:52:27 +00:00
} ;
2016-02-10 18:13:24 +00:00
_connection . RunQueries ( queries , Logger ) ;
2015-10-28 20:24:07 +00:00
}
catch ( Exception ex )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Error migrating chapter database" , ex ) ;
2015-10-28 20:24:07 +00:00
}
finally
{
TryDeleteFile ( file ) ;
}
}
private void TryDeleteFile ( string file )
{
2015-10-13 16:52:27 +00:00
try
{
2015-10-17 15:05:12 +00:00
File . Delete ( file ) ;
2015-10-13 16:52:27 +00:00
}
catch ( Exception ex )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Error deleting file {0}" , ex , file ) ;
2015-10-13 16:52:27 +00:00
}
2013-06-18 09:43:07 +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" ,
"ExternalServiceId"
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" ,
"IsCabac" ,
2016-01-11 16:52:22 +00:00
"CodecTag" ,
"Comment"
2015-10-14 02:41:46 +00:00
} ;
2013-06-18 09:43:07 +00:00
/// <summary>
/// Prepares the statements.
/// </summary>
private void PrepareStatements ( )
{
2015-06-03 03:16:15 +00:00
var saveColumns = new List < string >
{
"guid" ,
"type" ,
"data" ,
2015-06-07 19:24:56 +00:00
"Path" ,
2015-06-03 03:16:15 +00:00
"StartDate" ,
"EndDate" ,
"ChannelId" ,
"IsKids" ,
"IsMovie" ,
"IsSports" ,
2015-09-20 02:06:56 +00:00
"IsSeries" ,
"IsLive" ,
"IsNews" ,
"IsPremiere" ,
2015-09-29 16:29:06 +00:00
"EpisodeTitle" ,
"IsRepeat" ,
2015-06-03 03:16:15 +00:00
"CommunityRating" ,
2015-06-05 05:32:14 +00:00
"CustomRating" ,
"IndexNumber" ,
"IsLocked" ,
"Name" ,
2015-06-21 03:35:22 +00:00
"OfficialRating" ,
"MediaType" ,
"Overview" ,
"ParentIndexNumber" ,
"PremiereDate" ,
2015-07-09 05:52:25 +00:00
"ProductionYear" ,
2015-07-28 12:33:30 +00:00
"ParentId" ,
"Genres" ,
2015-08-26 05:10:04 +00:00
"ParentalRatingValue" ,
2015-12-27 18:37:06 +00:00
"InheritedParentalRatingValue" ,
2015-08-26 18:17:38 +00:00
"SchemaVersion" ,
"SortName" ,
"RunTimeTicks" ,
"OfficialRatingDescription" ,
"HomePageUrl" ,
"VoteCount" ,
"DisplayMediaType" ,
"DateCreated" ,
2015-08-27 01:31:54 +00:00
"DateModified" ,
"ForcedSortName" ,
2015-09-16 17:16:39 +00:00
"IsOffline" ,
2015-09-29 17:35:23 +00:00
"LocationType" ,
"PreferredMetadataLanguage" ,
2015-10-04 18:10:50 +00:00
"PreferredMetadataCountryCode" ,
"IsHD" ,
"ExternalEtag" ,
2015-12-27 18:37:06 +00:00
"DateLastRefreshed" ,
"DateLastSaved" ,
"IsInMixedFolder" ,
"LockedFields" ,
"Studios" ,
"Audio" ,
"ExternalServiceId" ,
"Tags" ,
"IsFolder" ,
"UnratedType" ,
"TopParentId"
2015-06-03 03:16:15 +00:00
} ;
2013-09-29 22:00:08 +00:00
_saveItemCommand = _connection . CreateCommand ( ) ;
2015-08-26 18:17:38 +00:00
_saveItemCommand . CommandText = "replace into TypedBaseItems (" + string . Join ( "," , saveColumns . ToArray ( ) ) + ") values (" ;
2015-06-03 03:16:15 +00:00
for ( var i = 1 ; i < = saveColumns . Count ; i + + )
{
2015-08-26 18:17:38 +00:00
if ( i > 1 )
{
_saveItemCommand . CommandText + = "," ;
}
_saveItemCommand . CommandText + = "@" + i . ToString ( CultureInfo . InvariantCulture ) ;
2015-06-03 03:16:15 +00:00
_saveItemCommand . Parameters . Add ( _saveItemCommand , "@" + i . ToString ( CultureInfo . InvariantCulture ) ) ;
}
2015-08-26 18:17:38 +00:00
_saveItemCommand . CommandText + = ")" ;
2013-09-29 22:00:08 +00:00
_deleteChildrenCommand = _connection . CreateCommand ( ) ;
_deleteChildrenCommand . CommandText = "delete from ChildrenIds where ParentId=@ParentId" ;
_deleteChildrenCommand . Parameters . Add ( _deleteChildrenCommand , "@ParentId" ) ;
2014-02-19 18:50:37 +00:00
_deleteItemCommand = _connection . CreateCommand ( ) ;
_deleteItemCommand . CommandText = "delete from TypedBaseItems where guid=@Id" ;
_deleteItemCommand . Parameters . Add ( _deleteItemCommand , "@Id" ) ;
2015-06-01 14:49:23 +00:00
2013-09-29 22:00:08 +00:00
_saveChildrenCommand = _connection . CreateCommand ( ) ;
_saveChildrenCommand . CommandText = "replace into ChildrenIds (ParentId, ItemId) values (@ParentId, @ItemId)" ;
_saveChildrenCommand . Parameters . Add ( _saveChildrenCommand , "@ParentId" ) ;
_saveChildrenCommand . Parameters . Add ( _saveChildrenCommand , "@ItemId" ) ;
2015-06-29 01:10:45 +00:00
2015-10-14 02:41:46 +00:00
// People
2015-06-29 01:10:45 +00:00
_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" ) ;
2015-11-02 17:25:01 +00:00
2015-12-27 18:37:06 +00:00
// 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" ) ;
2015-10-14 02:41:46 +00:00
// Chapters
2015-10-13 16:52:27 +00:00
_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" ) ;
2015-10-14 02:41:46 +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 ) ;
}
2015-12-27 18:37:06 +00:00
_updateInheritedRatingCommand = _connection . CreateCommand ( ) ;
_updateInheritedRatingCommand . CommandText = "Update TypedBaseItems set InheritedParentalRatingValue=@InheritedParentalRatingValue where Guid=@Guid" ;
_updateInheritedRatingCommand . Parameters . Add ( _updateInheritedRatingCommand , "@InheritedParentalRatingValue" ) ;
_updateInheritedRatingCommand . Parameters . Add ( _updateInheritedRatingCommand , "@Guid" ) ;
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-02-10 18:13:24 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2013-06-18 09:43:07 +00:00
2013-09-29 22:00:08 +00:00
IDbTransaction transaction = null ;
2013-06-18 09:43:07 +00:00
try
{
2013-06-18 19:16:27 +00:00
transaction = _connection . BeginTransaction ( ) ;
2013-06-18 09:43:07 +00:00
foreach ( var item in items )
{
cancellationToken . ThrowIfCancellationRequested ( ) ;
2015-06-03 03:16:15 +00:00
var index = 0 ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . Id ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . GetType ( ) . FullName ;
_saveItemCommand . GetParameter ( index + + ) . Value = _jsonSerializer . SerializeToBytes ( item ) ;
2013-06-18 09:43:07 +00:00
2015-07-08 16:10:34 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . Path ;
2015-06-07 19:24:56 +00:00
2015-07-08 16:10:34 +00:00
var hasStartDate = item as IHasStartDate ;
2015-06-01 14:49:23 +00:00
if ( hasStartDate ! = null )
{
2015-06-03 03:16:15 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = hasStartDate . StartDate ;
2015-06-01 14:49:23 +00:00
}
else
{
2015-06-03 03:16:15 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
2015-06-01 14:49:23 +00:00
}
2015-06-03 03:16:15 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . EndDate ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . ChannelId ;
2015-06-01 14:49:23 +00:00
var hasProgramAttributes = item as IHasProgramAttributes ;
if ( hasProgramAttributes ! = null )
{
2015-06-03 03:16:15 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsKids ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsMovie ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsSports ;
2015-09-20 02:06:56 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsSeries ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsLive ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsNews ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsPremiere ;
2015-09-29 16:29:06 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . EpisodeTitle ;
_saveItemCommand . GetParameter ( index + + ) . Value = hasProgramAttributes . IsRepeat ;
2015-06-01 14:49:23 +00:00
}
else
{
2015-06-03 03:16:15 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
2015-09-20 02:06:56 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
2015-09-29 16:29:06 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
2015-06-01 14:49:23 +00:00
}
2015-06-03 03:16:15 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . CommunityRating ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . CustomRating ;
2015-06-05 05:32:14 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . IndexNumber ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsLocked ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . Name ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . OfficialRating ;
2015-06-21 03:35:22 +00:00
_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 ;
2015-07-08 16:10:34 +00:00
2015-07-09 05:52:25 +00:00
if ( item . ParentId = = Guid . Empty )
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = item . ParentId ;
}
2015-07-28 12:33:30 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = string . Join ( "|" , item . Genres . ToArray ( ) ) ;
2015-12-27 18:37:06 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . GetParentalRatingValue ( ) ? ? 0 ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . GetInheritedParentalRatingValue ( ) ? ? 0 ;
2015-07-28 12:33:30 +00:00
2015-08-26 05:10:04 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = LatestSchemaVersion ;
2015-08-26 18:17:38 +00:00
_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 ;
2015-08-27 01:31:54 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . ForcedSortName ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsOffline ;
2015-09-16 17:16:39 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . LocationType . ToString ( ) ;
2015-08-27 15:58:07 +00:00
2015-09-29 17:35:23 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . PreferredMetadataLanguage ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . PreferredMetadataCountryCode ;
2015-10-04 18:10:50 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsHD ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . ExternalEtag ;
2015-10-14 05:02:30 +00:00
if ( item . DateLastRefreshed = = default ( DateTime ) )
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = item . DateLastRefreshed ;
}
2015-12-27 18:37:06 +00:00
_saveItemCommand . GetParameter ( index + + ) . Value = item . DateLastSaved ;
_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 ;
}
var tvItem = item as ILiveTvItem ;
if ( tvItem ! = null )
{
_saveItemCommand . GetParameter ( index + + ) . Value = tvItem . ServiceName ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
_saveItemCommand . GetParameter ( index + + ) . Value = string . Join ( "|" , item . Tags . ToArray ( ) ) ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . IsFolder ;
_saveItemCommand . GetParameter ( index + + ) . Value = item . GetBlockUnratedType ( ) . ToString ( ) ;
var topParent = item . GetTopParent ( ) ;
if ( topParent ! = null )
{
_saveItemCommand . GetParameter ( index + + ) . Value = topParent . Id . ToString ( "N" ) ;
}
else
{
_saveItemCommand . GetParameter ( index + + ) . Value = null ;
}
2013-06-18 09:43:07 +00:00
_saveItemCommand . Transaction = transaction ;
2013-09-29 22:00:08 +00:00
_saveItemCommand . ExecuteNonQuery ( ) ;
2015-12-27 18:37:06 +00:00
if ( item . SupportsAncestors )
{
UpdateAncestors ( item . Id , item . GetAncestorIds ( ) . Distinct ( ) . ToList ( ) , transaction ) ;
}
2013-06-18 09:43:07 +00:00
}
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
catch ( Exception e )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Failed to save items:" , e ) ;
2013-06-18 09:43:07 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
finally
{
if ( transaction ! = null )
{
transaction . Dispose ( ) ;
}
2016-02-10 18:13:24 +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
2013-06-18 19:16:27 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
2013-06-18 09:43:07 +00:00
{
2015-08-27 15:58:07 +00:00
cmd . CommandText = "select " + string . Join ( "," , _retriveItemColumns ) + " from TypedBaseItems where guid = @guid" ;
2013-09-29 22:00:08 +00:00
cmd . Parameters . Add ( cmd , "@guid" , DbType . Guid ) . Value = id ;
2013-06-18 09:43:07 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult | CommandBehavior . SingleRow ) )
{
if ( reader . Read ( ) )
{
2014-02-20 04:53:15 +00:00
return GetItem ( reader ) ;
}
}
return null ;
}
}
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-02-10 18:13:24 +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 ) )
{
item . OfficialRating = reader . GetString ( 31 ) ;
}
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 ) )
{
var tvItem = item as ILiveTvItem ;
if ( tvItem ! = null )
{
tvItem . ServiceName = reader . GetString ( 43 ) ;
}
}
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" ) ;
}
using ( var cmd = _connection . CreateCommand ( ) )
{
cmd . CommandText = "select StartPositionTicks,Name,ImagePath from " + ChaptersTableName + " where ItemId = @ItemId order by ChapterIndex asc" ;
cmd . Parameters . Add ( cmd , "@ItemId" , DbType . Guid ) . Value = id ;
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
{
yield return GetChapter ( reader ) ;
}
}
}
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" ) ;
}
using ( var cmd = _connection . CreateCommand ( ) )
{
cmd . CommandText = "select StartPositionTicks,Name,ImagePath from " + ChaptersTableName + " where ItemId = @ItemId and ChapterIndex=@ChapterIndex" ;
cmd . Parameters . Add ( cmd , "@ItemId" , DbType . Guid ) . Value = id ;
cmd . Parameters . Add ( cmd , "@ChapterIndex" , DbType . Int32 ) . Value = index ;
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult | CommandBehavior . SingleRow ) )
{
if ( reader . Read ( ) )
{
return GetChapter ( reader ) ;
}
}
return null ;
}
}
/// <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 ) ;
}
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>
2015-10-13 16:52:27 +00:00
public async Task SaveChapters ( Guid id , IEnumerable < 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-02-10 18:13:24 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2015-10-13 16:52:27 +00:00
IDbTransaction transaction = null ;
try
{
transaction = _connection . BeginTransaction ( ) ;
// First delete chapters
_deleteChaptersCommand . GetParameter ( 0 ) . Value = id ;
_deleteChaptersCommand . Transaction = transaction ;
_deleteChaptersCommand . ExecuteNonQuery ( ) ;
var index = 0 ;
foreach ( var chapter in chapters )
{
cancellationToken . ThrowIfCancellationRequested ( ) ;
_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 ;
_saveChapterCommand . Transaction = transaction ;
_saveChapterCommand . ExecuteNonQuery ( ) ;
index + + ;
}
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
catch ( Exception e )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Failed to save chapters:" , e ) ;
2015-10-13 16:52:27 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
finally
{
if ( transaction ! = null )
{
transaction . Dispose ( ) ;
}
2016-02-10 18:13:24 +00:00
WriteLock . Release ( ) ;
2015-10-13 16:52:27 +00:00
}
2013-06-18 19:16:27 +00:00
}
2016-02-10 18:13:24 +00:00
protected override void CloseConnection ( )
2013-06-18 19:16:27 +00:00
{
2016-02-10 18:13:24 +00:00
if ( _connection ! = null )
2015-02-07 03:25:23 +00:00
{
2016-02-10 18:13:24 +00:00
if ( _connection . IsOpen ( ) )
2013-06-18 19:16:27 +00:00
{
2016-02-10 18:13:24 +00:00
_connection . Close ( ) ;
2013-06-18 19:16:27 +00:00
}
2016-02-10 18:13:24 +00:00
_connection . Dispose ( ) ;
_connection = null ;
2013-06-18 19:16:27 +00:00
}
}
2013-06-20 16:44:24 +00:00
2013-06-26 16:08:16 +00:00
public IEnumerable < Guid > GetChildren ( Guid parentId )
2013-06-20 16:44:24 +00:00
{
if ( parentId = = Guid . Empty )
{
throw new ArgumentNullException ( "parentId" ) ;
}
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-06-01 14:49:23 +00:00
2013-06-20 16:44:24 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
{
2013-06-26 16:08:16 +00:00
cmd . CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId" ;
2013-06-20 16:44:24 +00:00
2013-09-29 22:00:08 +00:00
cmd . Parameters . Add ( cmd , "@ParentId" , DbType . Guid ) . Value = parentId ;
2013-06-20 16:44:24 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
{
2013-06-26 16:08:16 +00:00
yield return reader . GetGuid ( 0 ) ;
2013-06-20 16:44:24 +00:00
}
}
}
}
2014-10-23 04:26:01 +00:00
public IEnumerable < BaseItem > GetChildrenItems ( Guid parentId )
{
if ( parentId = = Guid . Empty )
{
throw new ArgumentNullException ( "parentId" ) ;
}
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-06-01 14:49:23 +00:00
2014-10-23 04:26:01 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
{
2015-08-27 15:58:07 +00:00
cmd . CommandText = "select " + string . Join ( "," , _retriveItemColumns ) + " from TypedBaseItems where guid in (select ItemId from ChildrenIds where ParentId = @ParentId)" ;
2014-10-23 04:26:01 +00:00
cmd . Parameters . Add ( cmd , "@ParentId" , DbType . Guid ) . Value = parentId ;
2016-02-10 18:13:24 +00:00
//Logger.Debug(cmd.CommandText);
2015-12-27 18:37:06 +00:00
2014-10-23 04:26:01 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
{
var item = GetItem ( reader ) ;
if ( item ! = null )
{
yield return item ;
}
}
}
}
}
2015-03-25 03:54:32 +00:00
2015-04-16 03:23:13 +00:00
public IEnumerable < BaseItem > GetItemsOfType ( Type type )
2014-02-20 04:53:15 +00:00
{
if ( type = = null )
{
throw new ArgumentNullException ( "type" ) ;
}
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-04-16 03:23:13 +00:00
using ( var cmd = _connection . CreateCommand ( ) )
{
2015-08-27 15:58:07 +00:00
cmd . CommandText = "select " + string . Join ( "," , _retriveItemColumns ) + " from TypedBaseItems where type = @type" ;
2015-04-16 03:23:13 +00:00
cmd . Parameters . Add ( cmd , "@type" , DbType . String ) . Value = type . FullName ;
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
{
var item = GetItem ( reader ) ;
if ( item ! = null )
{
yield return item ;
}
}
}
}
}
2015-12-27 18:37:06 +00:00
public IEnumerable < BaseItem > GetItemList ( InternalItemsQuery query )
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
{
cmd . CommandText = "select " + string . Join ( "," , _retriveItemColumns ) + " from TypedBaseItems" ;
var whereClauses = GetWhereClauses ( query , cmd , true ) ;
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
cmd . CommandText + = whereText ;
cmd . CommandText + = GetOrderByText ( query ) ;
if ( query . Limit . HasValue )
{
cmd . CommandText + = " LIMIT " + query . Limit . Value . ToString ( CultureInfo . InvariantCulture ) ;
}
2016-02-10 18:13:24 +00:00
//Logger.Debug(cmd.CommandText);
2015-12-27 18:37:06 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
{
var item = GetItem ( reader ) ;
if ( item ! = null )
{
yield return item ;
}
}
}
}
}
2015-06-01 14:49:23 +00:00
public QueryResult < BaseItem > GetItems ( InternalItemsQuery query )
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
{
2015-08-27 15:58:07 +00:00
cmd . CommandText = "select " + string . Join ( "," , _retriveItemColumns ) + " from TypedBaseItems" ;
2015-06-01 14:49:23 +00:00
var whereClauses = GetWhereClauses ( query , cmd , false ) ;
var whereTextWithoutPaging = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
whereClauses = GetWhereClauses ( query , cmd , true ) ;
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
cmd . CommandText + = whereText ;
2015-08-25 03:13:04 +00:00
cmd . CommandText + = GetOrderByText ( query ) ;
2015-06-01 14:49:23 +00:00
if ( query . Limit . HasValue )
{
cmd . CommandText + = " LIMIT " + query . Limit . Value . ToString ( CultureInfo . InvariantCulture ) ;
}
cmd . CommandText + = "; select count (guid) from TypedBaseItems" + whereTextWithoutPaging ;
2016-02-10 18:13:24 +00:00
Logger . Debug ( cmd . CommandText ) ;
2015-08-26 18:17:38 +00:00
2015-06-01 14:49:23 +00:00
var list = new List < BaseItem > ( ) ;
var count = 0 ;
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess ) )
{
while ( reader . Read ( ) )
{
2015-07-02 05:08:05 +00:00
var item = GetItem ( reader ) ;
if ( item ! = null )
{
list . Add ( item ) ;
}
2015-06-01 14:49:23 +00:00
}
if ( reader . NextResult ( ) & & reader . Read ( ) )
{
count = reader . GetInt32 ( 0 ) ;
}
}
return new QueryResult < BaseItem > ( )
{
Items = list . ToArray ( ) ,
TotalRecordCount = count
} ;
}
}
2015-08-25 03:13:04 +00:00
private string GetOrderByText ( InternalItemsQuery query )
{
if ( query . SortBy = = null | | query . SortBy . Length = = 0 )
{
return string . Empty ;
}
var sortOrder = query . SortOrder = = SortOrder . Descending ? "DESC" : "ASC" ;
return " ORDER BY " + string . Join ( "," , query . SortBy . Select ( i = > MapOrderByField ( i ) + " " + sortOrder ) . ToArray ( ) ) ;
}
private string MapOrderByField ( string name )
{
2015-12-27 18:37:06 +00:00
if ( string . Equals ( name , "airtime" , StringComparison . OrdinalIgnoreCase ) )
{
// TODO
return "SortName" ;
}
2015-08-25 03:13:04 +00:00
return name ;
}
2015-06-01 14:49:23 +00:00
public List < Guid > GetItemIdsList ( InternalItemsQuery query )
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
{
cmd . CommandText = "select guid from TypedBaseItems" ;
2015-07-07 02:25:23 +00:00
var whereClauses = GetWhereClauses ( query , cmd , true ) ;
2015-06-01 14:49:23 +00:00
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
cmd . CommandText + = whereText ;
2015-08-25 03:13:04 +00:00
cmd . CommandText + = GetOrderByText ( query ) ;
2015-06-01 14:49:23 +00:00
if ( query . Limit . HasValue )
{
cmd . CommandText + = " LIMIT " + query . Limit . Value . ToString ( CultureInfo . InvariantCulture ) ;
}
var list = new List < Guid > ( ) ;
2016-02-10 18:13:24 +00:00
Logger . Debug ( cmd . CommandText ) ;
2015-06-01 14:49:23 +00:00
2015-12-27 18:37:06 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
2015-06-01 14:49:23 +00:00
{
while ( reader . Read ( ) )
{
list . Add ( reader . GetGuid ( 0 ) ) ;
}
}
return list ;
}
}
2015-09-16 17:16:39 +00:00
public QueryResult < Tuple < Guid , string > > GetItemIdsWithPath ( InternalItemsQuery query )
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
{
cmd . CommandText = "select guid,path from TypedBaseItems" ;
var whereClauses = GetWhereClauses ( query , cmd , false ) ;
var whereTextWithoutPaging = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
whereClauses = GetWhereClauses ( query , cmd , true ) ;
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
cmd . CommandText + = whereText ;
cmd . CommandText + = GetOrderByText ( query ) ;
if ( query . Limit . HasValue )
{
cmd . CommandText + = " LIMIT " + query . Limit . Value . ToString ( CultureInfo . InvariantCulture ) ;
}
cmd . CommandText + = "; select count (guid) from TypedBaseItems" + whereTextWithoutPaging ;
var list = new List < Tuple < Guid , string > > ( ) ;
var count = 0 ;
2016-02-10 18:13:24 +00:00
Logger . Debug ( cmd . CommandText ) ;
2015-09-16 17:16:39 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess ) )
{
while ( reader . Read ( ) )
{
var id = reader . GetGuid ( 0 ) ;
string path = null ;
if ( ! reader . IsDBNull ( 1 ) )
{
path = reader . GetString ( 1 ) ;
}
list . Add ( new Tuple < Guid , string > ( id , path ) ) ;
}
if ( reader . NextResult ( ) & & reader . Read ( ) )
{
count = reader . GetInt32 ( 0 ) ;
}
}
return new QueryResult < Tuple < Guid , string > > ( )
{
Items = list . ToArray ( ) ,
TotalRecordCount = count
} ;
}
}
2015-06-01 14:49:23 +00:00
public QueryResult < Guid > GetItemIds ( InternalItemsQuery query )
{
if ( query = = null )
{
throw new ArgumentNullException ( "query" ) ;
}
CheckDisposed ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
{
cmd . CommandText = "select guid from TypedBaseItems" ;
var whereClauses = GetWhereClauses ( query , cmd , false ) ;
var whereTextWithoutPaging = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
whereClauses = GetWhereClauses ( query , cmd , true ) ;
var whereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
cmd . CommandText + = whereText ;
2015-08-25 03:13:04 +00:00
cmd . CommandText + = GetOrderByText ( query ) ;
2015-06-01 14:49:23 +00:00
if ( query . Limit . HasValue )
{
cmd . CommandText + = " LIMIT " + query . Limit . Value . ToString ( CultureInfo . InvariantCulture ) ;
}
cmd . CommandText + = "; select count (guid) from TypedBaseItems" + whereTextWithoutPaging ;
var list = new List < Guid > ( ) ;
var count = 0 ;
2016-02-10 18:13:24 +00:00
Logger . Debug ( cmd . CommandText ) ;
2015-06-01 14:49:23 +00:00
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess ) )
{
while ( reader . Read ( ) )
{
list . Add ( reader . GetGuid ( 0 ) ) ;
}
if ( reader . NextResult ( ) & & reader . Read ( ) )
{
count = reader . GetInt32 ( 0 ) ;
}
}
return new QueryResult < Guid > ( )
{
Items = list . ToArray ( ) ,
TotalRecordCount = count
} ;
}
}
private List < string > GetWhereClauses ( InternalItemsQuery query , IDbCommand cmd , bool addPaging )
{
var whereClauses = new List < string > ( ) ;
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 ;
}
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 ;
}
if ( query . LocationType . HasValue )
{
whereClauses . Add ( "LocationType=@LocationType" ) ;
cmd . Parameters . Add ( cmd , "@LocationType" , DbType . String ) . Value = query . LocationType . Value ;
}
2015-06-01 14:49:23 +00:00
if ( query . IsMovie . HasValue )
{
whereClauses . Add ( "IsMovie=@IsMovie" ) ;
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
var includeTypes = query . IncludeItemTypes . SelectMany ( MapIncludeItemTypes ) . ToArray ( ) ;
if ( includeTypes . Length = = 1 )
2015-06-01 14:49:23 +00:00
{
whereClauses . Add ( "type=@type" ) ;
2015-06-01 17:07:55 +00:00
cmd . Parameters . Add ( cmd , "@type" , DbType . String ) . Value = includeTypes [ 0 ] ;
2015-06-01 14:49:23 +00:00
}
2015-07-18 19:32:59 +00:00
else if ( includeTypes . Length > 1 )
2015-06-01 14:49:23 +00:00
{
2015-06-01 17:07:55 +00:00
var inClause = string . Join ( "," , includeTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
2015-06-01 14:49:23 +00:00
whereClauses . Add ( string . Format ( "type in ({0})" , inClause ) ) ;
}
2015-08-27 01:31:54 +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 ;
}
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 ;
}
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 ;
}
2015-06-01 14:49:23 +00:00
if ( query . MaxStartDate . HasValue )
{
whereClauses . Add ( "StartDate<=@MaxStartDate" ) ;
cmd . Parameters . Add ( cmd , "@MaxStartDate" , DbType . Date ) . Value = query . MaxStartDate . Value ;
}
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
}
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 ;
}
2015-07-18 19:32:59 +00:00
if ( ! string . IsNullOrWhiteSpace ( query . NameContains ) )
{
whereClauses . Add ( "Name like @NameContains" ) ;
cmd . Parameters . Add ( cmd , "@NameContains" , DbType . String ) . Value = "%" + query . NameContains + "%" ;
}
2015-07-28 12:33:30 +00:00
if ( query . Genres . Length > 0 )
{
var genres = new List < string > ( ) ;
var index = 0 ;
foreach ( var genre in query . Genres )
{
genres . Add ( "Genres like @Genres" + index ) ;
cmd . Parameters . Add ( cmd , "@Genres" + index , DbType . String ) . Value = "%" + genre + "%" ;
index + + ;
}
var genreCaluse = "(" + string . Join ( " OR " , genres . ToArray ( ) ) + ")" ;
whereClauses . Add ( genreCaluse ) ;
}
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
}
}
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)" ) ;
}
}
2015-12-27 18:37:06 +00:00
if ( query . ExcludeLocationTypes . Length = = 1 )
{
whereClauses . Add ( "LocationType<>@LocationType" ) ;
cmd . Parameters . Add ( cmd , "@LocationType" , DbType . String ) . Value = query . ExcludeLocationTypes [ 0 ] . ToString ( ) ;
}
if ( query . ExcludeLocationTypes . Length > 1 )
{
var val = string . Join ( "," , query . ExcludeLocationTypes . Select ( i = > "'" + i + "'" ) . ToArray ( ) ) ;
whereClauses . Add ( "LocationType not in (" + val + ")" ) ;
}
2015-08-28 04:19:08 +00:00
2015-12-27 18:37:06 +00:00
if ( query . TopParentIds . Length = = 1 )
{
whereClauses . Add ( "(TopParentId=@TopParentId)" ) ;
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 ( ) ) ;
whereClauses . Add ( "(TopParentId in (" + val + "))" ) ;
}
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 ) ) ;
}
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 ) ) ;
}
//var excludeTagIndex = 0;
//foreach (var excludeTag in query.ExcludeTags)
//{
// whereClauses.Add("Tags not like @excludeTag" + excludeTagIndex);
// cmd.Parameters.Add(cmd, "@excludeTag" + excludeTagIndex, DbType.String).Value = "%" + excludeTag + "%";
// excludeTagIndex++;
//}
2015-06-01 14:49:23 +00:00
if ( addPaging )
{
if ( query . StartIndex . HasValue & & query . StartIndex . Value > 0 )
{
var pagingWhereText = whereClauses . Count = = 0 ?
string . Empty :
" where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
2015-08-25 03:13:04 +00:00
var orderBy = GetOrderByText ( query ) ;
whereClauses . Add ( string . Format ( "guid NOT IN (SELECT guid FROM TypedBaseItems {0}" + orderBy + " LIMIT {1})" ,
2015-06-01 14:49:23 +00:00
pagingWhereText ,
query . StartIndex . Value . ToString ( CultureInfo . InvariantCulture ) ) ) ;
}
}
return whereClauses ;
}
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 ) ,
typeof ( BoxSet ) ,
typeof ( Episode ) ,
2015-10-29 13:28:05 +00:00
typeof ( ChannelVideoItem ) ,
2015-07-18 19:32:59 +00:00
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 )
{
var newValues = new List < Tuple < Guid , int > > ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
{
cmd . CommandText = "select Guid,InheritedParentalRatingValue,(select Max(ParentalRatingValue, (select COALESCE(MAX(ParentalRatingValue),0) from TypedBaseItems where guid in (Select AncestorId from AncestorIds where ItemId=Outer.guid)))) as NewInheritedParentalRatingValue from typedbaseitems as Outer where InheritedParentalRatingValue <> NewInheritedParentalRatingValue" ;
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
{
var id = reader . GetGuid ( 0 ) ;
var newValue = reader . GetInt32 ( 2 ) ;
newValues . Add ( new Tuple < Guid , int > ( id , newValue ) ) ;
}
}
}
if ( newValues . Count = = 0 )
{
return ;
}
2016-02-10 18:13:24 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2015-12-27 18:37:06 +00:00
IDbTransaction transaction = null ;
try
{
transaction = _connection . BeginTransaction ( ) ;
foreach ( var item in newValues )
{
_updateInheritedRatingCommand . GetParameter ( 0 ) . Value = item . Item1 ;
_updateInheritedRatingCommand . GetParameter ( 1 ) . Value = item . Item2 ;
_updateInheritedRatingCommand . Transaction = transaction ;
_updateInheritedRatingCommand . ExecuteNonQuery ( ) ;
_updateInheritedRatingCommand . ExecuteNonQuery ( ) ;
}
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
catch ( Exception e )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Error running query:" , e ) ;
2015-12-27 18:37:06 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
finally
{
if ( transaction ! = null )
{
transaction . Dispose ( ) ;
}
2016-02-10 18:13:24 +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 ( )
{
var dict = new Dictionary < string , string [ ] > ( ) ;
foreach ( var t in KnownTypes )
{
dict [ t . Name ] = new [ ] { t . FullName } ;
}
2015-12-27 18:37:06 +00:00
dict [ "ChannelItem" ] = new [ ] { typeof ( ChannelVideoItem ) . FullName , typeof ( ChannelAudioItem ) . FullName , typeof ( ChannelFolderItem ) . FullName } ;
dict [ "LiveTvItem" ] = new [ ] { typeof ( LiveTvAudioRecording ) . FullName , typeof ( LiveTvVideoRecording ) . FullName , typeof ( LiveTvChannel ) . FullName , typeof ( LiveTvProgram ) . FullName } ;
2015-07-18 19:32:59 +00:00
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-02-10 18:13:24 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2014-02-19 18:50:37 +00:00
IDbTransaction transaction = null ;
try
{
transaction = _connection . BeginTransaction ( ) ;
// First delete children
_deleteChildrenCommand . GetParameter ( 0 ) . Value = id ;
_deleteChildrenCommand . Transaction = transaction ;
_deleteChildrenCommand . ExecuteNonQuery ( ) ;
2015-07-02 05:08:05 +00:00
// Delete people
_deletePeopleCommand . GetParameter ( 0 ) . Value = id ;
_deletePeopleCommand . Transaction = transaction ;
_deletePeopleCommand . ExecuteNonQuery ( ) ;
2015-07-08 16:10:34 +00:00
2015-10-14 02:41:46 +00:00
// Delete chapters
_deleteChaptersCommand . GetParameter ( 0 ) . Value = id ;
_deleteChaptersCommand . Transaction = transaction ;
_deleteChaptersCommand . ExecuteNonQuery ( ) ;
// Delete media streams
_deleteStreamsCommand . GetParameter ( 0 ) . Value = id ;
_deleteStreamsCommand . Transaction = transaction ;
_deleteStreamsCommand . ExecuteNonQuery ( ) ;
2015-11-02 17:25:01 +00:00
2015-12-27 18:37:06 +00:00
// Delete ancestors
_deleteAncestorsCommand . GetParameter ( 0 ) . Value = id ;
_deleteAncestorsCommand . Transaction = transaction ;
_deleteAncestorsCommand . ExecuteNonQuery ( ) ;
2014-02-19 18:50:37 +00:00
// Delete the item
_deleteItemCommand . GetParameter ( 0 ) . Value = id ;
_deleteItemCommand . Transaction = transaction ;
_deleteItemCommand . ExecuteNonQuery ( ) ;
2015-12-27 18:37:06 +00:00
2014-02-19 18:50:37 +00:00
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
catch ( Exception e )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Failed to save children:" , e ) ;
2014-02-19 18:50:37 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
finally
{
if ( transaction ! = null )
{
transaction . Dispose ( ) ;
}
2016-02-10 18:13:24 +00:00
WriteLock . Release ( ) ;
2014-02-19 18:50:37 +00:00
}
}
2013-06-26 16:08:16 +00:00
public async Task SaveChildren ( Guid parentId , IEnumerable < Guid > children , CancellationToken cancellationToken )
2013-06-20 16:44:24 +00:00
{
if ( parentId = = Guid . Empty )
{
throw new ArgumentNullException ( "parentId" ) ;
}
if ( children = = null )
{
throw new ArgumentNullException ( "children" ) ;
}
2015-02-07 03:25:23 +00:00
CheckDisposed ( ) ;
2015-06-01 14:49:23 +00:00
2016-02-10 18:13:24 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2013-06-20 16:44:24 +00:00
2013-09-29 22:00:08 +00:00
IDbTransaction transaction = null ;
2013-06-20 16:44:24 +00:00
try
{
transaction = _connection . BeginTransaction ( ) ;
// First delete
2013-09-29 22:00:08 +00:00
_deleteChildrenCommand . GetParameter ( 0 ) . Value = parentId ;
2013-06-20 16:44:24 +00:00
_deleteChildrenCommand . Transaction = transaction ;
2013-09-29 22:00:08 +00:00
_deleteChildrenCommand . ExecuteNonQuery ( ) ;
2013-06-20 16:44:24 +00:00
2013-06-26 16:08:16 +00:00
foreach ( var id in children )
2013-06-20 16:44:24 +00:00
{
cancellationToken . ThrowIfCancellationRequested ( ) ;
2013-09-29 22:00:08 +00:00
_saveChildrenCommand . GetParameter ( 0 ) . Value = parentId ;
_saveChildrenCommand . GetParameter ( 1 ) . Value = id ;
2013-06-20 16:44:24 +00:00
_saveChildrenCommand . Transaction = transaction ;
2013-09-29 22:00:08 +00:00
_saveChildrenCommand . ExecuteNonQuery ( ) ;
2013-06-20 16:44:24 +00:00
}
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
catch ( Exception e )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Failed to save children:" , e ) ;
2013-06-20 16:44:24 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
finally
{
if ( transaction ! = null )
{
transaction . Dispose ( ) ;
}
2016-02-10 18:13:24 +00:00
WriteLock . Release ( ) ;
2013-06-20 16:44:24 +00:00
}
}
2013-12-06 03:39:44 +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 ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
{
2015-07-08 16:10:34 +00:00
cmd . CommandText = "select Distinct Name from People" ;
2015-07-07 02:25:23 +00:00
2015-07-08 16:10:34 +00:00
var whereClauses = GetPeopleWhereClauses ( query , cmd ) ;
if ( whereClauses . Count > 0 )
{
cmd . CommandText + = " where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
}
cmd . CommandText + = " order by ListOrder" ;
2015-07-07 02:25:23 +00:00
var list = new List < string > ( ) ;
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
{
list . Add ( reader . GetString ( 0 ) ) ;
}
}
return list ;
}
}
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 ( ) ;
using ( var cmd = _connection . CreateCommand ( ) )
{
2015-07-08 16:10:34 +00:00
cmd . CommandText = "select ItemId, Name, Role, PersonType, SortOrder from People" ;
var whereClauses = GetPeopleWhereClauses ( query , cmd ) ;
if ( whereClauses . Count > 0 )
{
cmd . CommandText + = " where " + string . Join ( " AND " , whereClauses . ToArray ( ) ) ;
}
2015-06-29 01:10:45 +00:00
2015-07-08 16:10:34 +00:00
cmd . CommandText + = " order by ListOrder" ;
2015-06-29 01:10:45 +00:00
var list = new List < PersonInfo > ( ) ;
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
{
list . Add ( GetPerson ( reader ) ) ;
}
}
return list ;
}
}
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
}
2015-07-08 16:10:34 +00:00
return whereClauses ;
}
2015-12-27 18:37:06 +00:00
private void UpdateAncestors ( Guid itemId , List < Guid > ancestorIds , IDbTransaction transaction )
{
if ( itemId = = Guid . Empty )
{
throw new ArgumentNullException ( "itemId" ) ;
}
if ( ancestorIds = = null )
{
throw new ArgumentNullException ( "ancestorIds" ) ;
}
CheckDisposed ( ) ;
// First delete
_deleteAncestorsCommand . GetParameter ( 0 ) . Value = itemId ;
_deleteAncestorsCommand . Transaction = transaction ;
_deleteAncestorsCommand . ExecuteNonQuery ( ) ;
foreach ( var ancestorId in ancestorIds )
{
_saveAncestorCommand . GetParameter ( 0 ) . Value = itemId ;
_saveAncestorCommand . GetParameter ( 1 ) . Value = ancestorId ;
_saveAncestorCommand . GetParameter ( 2 ) . Value = ancestorId . ToString ( "N" ) ;
_saveAncestorCommand . Transaction = transaction ;
_saveAncestorCommand . ExecuteNonQuery ( ) ;
}
}
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-02-10 18:13:24 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2015-06-29 01:10:45 +00:00
IDbTransaction transaction = null ;
try
{
transaction = _connection . BeginTransaction ( ) ;
// First delete
_deletePeopleCommand . GetParameter ( 0 ) . Value = itemId ;
_deletePeopleCommand . Transaction = transaction ;
_deletePeopleCommand . ExecuteNonQuery ( ) ;
var listIndex = 0 ;
foreach ( var person in people )
{
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 ;
_savePersonCommand . Transaction = transaction ;
_savePersonCommand . ExecuteNonQuery ( ) ;
listIndex + + ;
}
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
catch ( Exception e )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Failed to save people:" , e ) ;
2015-06-29 01:10:45 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
finally
{
if ( transaction ! = null )
{
transaction . Dispose ( ) ;
}
2016-02-10 18:13:24 +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" ) ;
}
using ( var cmd = _connection . CreateCommand ( ) )
{
var cmdText = "select " + string . Join ( "," , _mediaStreamSaveColumns ) + " from mediastreams where" ;
cmdText + = " ItemId=@ItemId" ;
cmd . Parameters . Add ( cmd , "@ItemId" , DbType . Guid ) . Value = query . ItemId ;
if ( query . Type . HasValue )
{
cmdText + = " AND StreamType=@StreamType" ;
cmd . Parameters . Add ( cmd , "@StreamType" , DbType . String ) . Value = query . Type . Value . ToString ( ) ;
}
if ( query . Index . HasValue )
{
cmdText + = " AND StreamIndex=@StreamIndex" ;
cmd . Parameters . Add ( cmd , "@StreamIndex" , DbType . Int32 ) . Value = query . Index . Value ;
}
cmdText + = " order by StreamIndex ASC" ;
cmd . CommandText = cmdText ;
using ( var reader = cmd . ExecuteReader ( CommandBehavior . SequentialAccess | CommandBehavior . SingleResult ) )
{
while ( reader . Read ( ) )
{
yield return GetMediaStream ( reader ) ;
}
}
}
}
public async Task SaveMediaStreams ( Guid id , IEnumerable < MediaStream > streams , CancellationToken cancellationToken )
{
CheckDisposed ( ) ;
if ( id = = Guid . Empty )
{
throw new ArgumentNullException ( "id" ) ;
}
if ( streams = = null )
{
throw new ArgumentNullException ( "streams" ) ;
}
cancellationToken . ThrowIfCancellationRequested ( ) ;
2016-02-10 18:13:24 +00:00
await WriteLock . WaitAsync ( cancellationToken ) . ConfigureAwait ( false ) ;
2015-10-14 02:41:46 +00:00
IDbTransaction transaction = null ;
try
{
transaction = _connection . BeginTransaction ( ) ;
// First delete chapters
_deleteStreamsCommand . GetParameter ( 0 ) . Value = id ;
_deleteStreamsCommand . Transaction = transaction ;
_deleteStreamsCommand . ExecuteNonQuery ( ) ;
foreach ( var stream in streams )
{
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 ;
_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 . IsCabac ;
2015-12-27 18:37:06 +00:00
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . CodecTag ;
2016-01-11 16:52:22 +00:00
_saveStreamCommand . GetParameter ( index + + ) . Value = stream . Comment ;
2015-11-02 17:25:01 +00:00
2015-10-14 02:41:46 +00:00
_saveStreamCommand . Transaction = transaction ;
_saveStreamCommand . ExecuteNonQuery ( ) ;
}
transaction . Commit ( ) ;
}
catch ( OperationCanceledException )
{
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
catch ( Exception e )
{
2016-02-10 18:13:24 +00:00
Logger . ErrorException ( "Failed to save media streams:" , e ) ;
2015-10-14 02:41:46 +00:00
if ( transaction ! = null )
{
transaction . Rollback ( ) ;
}
throw ;
}
finally
{
if ( transaction ! = null )
{
transaction . Dispose ( ) ;
}
2016-02-10 18:13:24 +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 ) ;
}
if ( ! reader . IsDBNull ( 25 ) )
{
item . IsCabac = reader . GetBoolean ( 25 ) ;
}
if ( ! reader . IsDBNull ( 26 ) )
{
2015-12-27 18:37:06 +00:00
item . CodecTag = reader . GetString ( 26 ) ;
2015-10-27 14:02:30 +00:00
}
2016-01-11 16:52:22 +00:00
if ( ! reader . IsDBNull ( 27 ) )
{
item . Comment = reader . GetString ( 27 ) ;
}
2015-10-14 02:41:46 +00:00
return item ;
}
2013-06-18 09:43:07 +00:00
}
}