SqliteItemRepository.cs 87 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Entities.Movies;
  5. using MediaBrowser.Controller.Entities.TV;
  6. using MediaBrowser.Controller.LiveTv;
  7. using MediaBrowser.Controller.Persistence;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using MediaBrowser.Model.Querying;
  11. using MediaBrowser.Model.Serialization;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Data;
  15. using System.Globalization;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Runtime.Serialization;
  19. using System.Threading;
  20. using System.Threading.Tasks;
  21. using MediaBrowser.Controller.Channels;
  22. namespace MediaBrowser.Server.Implementations.Persistence
  23. {
  24. /// <summary>
  25. /// Class SQLiteItemRepository
  26. /// </summary>
  27. public class SqliteItemRepository : IItemRepository
  28. {
  29. private IDbConnection _connection;
  30. private readonly ILogger _logger;
  31. private readonly TypeMapper _typeMapper = new TypeMapper();
  32. /// <summary>
  33. /// Gets the name of the repository
  34. /// </summary>
  35. /// <value>The name.</value>
  36. public string Name
  37. {
  38. get
  39. {
  40. return "SQLite";
  41. }
  42. }
  43. /// <summary>
  44. /// Gets the json serializer.
  45. /// </summary>
  46. /// <value>The json serializer.</value>
  47. private readonly IJsonSerializer _jsonSerializer;
  48. /// <summary>
  49. /// The _app paths
  50. /// </summary>
  51. private readonly IApplicationPaths _appPaths;
  52. /// <summary>
  53. /// The _save item command
  54. /// </summary>
  55. private IDbCommand _saveItemCommand;
  56. private readonly string _criticReviewsPath;
  57. private IDbCommand _deleteChildrenCommand;
  58. private IDbCommand _saveChildrenCommand;
  59. private IDbCommand _deleteItemCommand;
  60. private IDbCommand _deletePeopleCommand;
  61. private IDbCommand _savePersonCommand;
  62. private IDbCommand _deleteChaptersCommand;
  63. private IDbCommand _saveChapterCommand;
  64. private IDbCommand _deleteStreamsCommand;
  65. private IDbCommand _saveStreamCommand;
  66. private const int LatestSchemaVersion = 16;
  67. /// <summary>
  68. /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
  69. /// </summary>
  70. /// <param name="appPaths">The app paths.</param>
  71. /// <param name="jsonSerializer">The json serializer.</param>
  72. /// <param name="logManager">The log manager.</param>
  73. /// <exception cref="System.ArgumentNullException">
  74. /// appPaths
  75. /// or
  76. /// jsonSerializer
  77. /// </exception>
  78. public SqliteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  79. {
  80. if (appPaths == null)
  81. {
  82. throw new ArgumentNullException("appPaths");
  83. }
  84. if (jsonSerializer == null)
  85. {
  86. throw new ArgumentNullException("jsonSerializer");
  87. }
  88. _appPaths = appPaths;
  89. _jsonSerializer = jsonSerializer;
  90. _criticReviewsPath = Path.Combine(_appPaths.DataPath, "critic-reviews");
  91. _logger = logManager.GetLogger(GetType().Name);
  92. }
  93. private const string ChaptersTableName = "Chapters2";
  94. /// <summary>
  95. /// Opens the connection to the database
  96. /// </summary>
  97. /// <returns>Task.</returns>
  98. public async Task Initialize()
  99. {
  100. var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
  101. _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false);
  102. var createMediaStreamsTableCommand
  103. = "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, KeyFrames TEXT NULL, CodecTag TEXT NULL, PRIMARY KEY (ItemId, StreamIndex))";
  104. string[] queries = {
  105. "create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB)",
  106. "create index if not exists idx_TypedBaseItems on TypedBaseItems(guid)",
  107. "create table if not exists ChildrenIds (ParentId GUID, ItemId GUID, PRIMARY KEY (ParentId, ItemId))",
  108. "create index if not exists idx_ChildrenIds on ChildrenIds(ParentId,ItemId)",
  109. "create table if not exists People (ItemId GUID, Name TEXT NOT NULL, Role TEXT, PersonType TEXT, SortOrder int, ListOrder int)",
  110. "create table if not exists "+ChaptersTableName+" (ItemId GUID, ChapterIndex INT, StartPositionTicks BIGINT, Name TEXT, ImagePath TEXT, PRIMARY KEY (ItemId, ChapterIndex))",
  111. "create index if not exists idx_"+ChaptersTableName+" on "+ChaptersTableName+"(ItemId, ChapterIndex)",
  112. createMediaStreamsTableCommand,
  113. "create index if not exists idx_mediastreams on mediastreams(ItemId, StreamIndex)",
  114. //pragmas
  115. "pragma temp_store = memory",
  116. "pragma shrink_memory"
  117. };
  118. _connection.RunQueries(queries, _logger);
  119. _connection.AddColumn(_logger, "TypedBaseItems", "Path", "Text");
  120. _connection.AddColumn(_logger, "TypedBaseItems", "StartDate", "DATETIME");
  121. _connection.AddColumn(_logger, "TypedBaseItems", "EndDate", "DATETIME");
  122. _connection.AddColumn(_logger, "TypedBaseItems", "ChannelId", "Text");
  123. _connection.AddColumn(_logger, "TypedBaseItems", "IsMovie", "BIT");
  124. _connection.AddColumn(_logger, "TypedBaseItems", "IsSports", "BIT");
  125. _connection.AddColumn(_logger, "TypedBaseItems", "IsKids", "BIT");
  126. _connection.AddColumn(_logger, "TypedBaseItems", "CommunityRating", "Float");
  127. _connection.AddColumn(_logger, "TypedBaseItems", "CustomRating", "Text");
  128. _connection.AddColumn(_logger, "TypedBaseItems", "IndexNumber", "INT");
  129. _connection.AddColumn(_logger, "TypedBaseItems", "IsLocked", "BIT");
  130. _connection.AddColumn(_logger, "TypedBaseItems", "Name", "Text");
  131. _connection.AddColumn(_logger, "TypedBaseItems", "OfficialRating", "Text");
  132. _connection.AddColumn(_logger, "TypedBaseItems", "MediaType", "Text");
  133. _connection.AddColumn(_logger, "TypedBaseItems", "Overview", "Text");
  134. _connection.AddColumn(_logger, "TypedBaseItems", "ParentIndexNumber", "INT");
  135. _connection.AddColumn(_logger, "TypedBaseItems", "PremiereDate", "DATETIME");
  136. _connection.AddColumn(_logger, "TypedBaseItems", "ProductionYear", "INT");
  137. _connection.AddColumn(_logger, "TypedBaseItems", "ParentId", "GUID");
  138. _connection.AddColumn(_logger, "TypedBaseItems", "Genres", "Text");
  139. _connection.AddColumn(_logger, "TypedBaseItems", "ParentalRatingValue", "INT");
  140. _connection.AddColumn(_logger, "TypedBaseItems", "SchemaVersion", "INT");
  141. _connection.AddColumn(_logger, "TypedBaseItems", "SortName", "Text");
  142. _connection.AddColumn(_logger, "TypedBaseItems", "RunTimeTicks", "BIGINT");
  143. _connection.AddColumn(_logger, "TypedBaseItems", "OfficialRatingDescription", "Text");
  144. _connection.AddColumn(_logger, "TypedBaseItems", "HomePageUrl", "Text");
  145. _connection.AddColumn(_logger, "TypedBaseItems", "VoteCount", "INT");
  146. _connection.AddColumn(_logger, "TypedBaseItems", "DisplayMediaType", "Text");
  147. _connection.AddColumn(_logger, "TypedBaseItems", "DateCreated", "DATETIME");
  148. _connection.AddColumn(_logger, "TypedBaseItems", "DateModified", "DATETIME");
  149. _connection.AddColumn(_logger, "TypedBaseItems", "ForcedSortName", "Text");
  150. _connection.AddColumn(_logger, "TypedBaseItems", "IsOffline", "BIT");
  151. _connection.AddColumn(_logger, "TypedBaseItems", "LocationType", "Text");
  152. _connection.AddColumn(_logger, "TypedBaseItems", "IsSeries", "BIT");
  153. _connection.AddColumn(_logger, "TypedBaseItems", "IsLive", "BIT");
  154. _connection.AddColumn(_logger, "TypedBaseItems", "IsNews", "BIT");
  155. _connection.AddColumn(_logger, "TypedBaseItems", "IsPremiere", "BIT");
  156. _connection.AddColumn(_logger, "TypedBaseItems", "EpisodeTitle", "Text");
  157. _connection.AddColumn(_logger, "TypedBaseItems", "IsRepeat", "BIT");
  158. _connection.AddColumn(_logger, "TypedBaseItems", "PreferredMetadataLanguage", "Text");
  159. _connection.AddColumn(_logger, "TypedBaseItems", "PreferredMetadataCountryCode", "Text");
  160. _connection.AddColumn(_logger, "TypedBaseItems", "IsHD", "BIT");
  161. _connection.AddColumn(_logger, "TypedBaseItems", "ExternalEtag", "Text");
  162. _connection.AddColumn(_logger, "TypedBaseItems", "DateLastRefreshed", "DATETIME");
  163. _connection.AddColumn(_logger, "TypedBaseItems", "DateLastSaved", "DATETIME");
  164. _connection.AddColumn(_logger, "TypedBaseItems", "IsInMixedFolder", "BIT");
  165. _connection.AddColumn(_logger, "TypedBaseItems", "LockedFields", "Text");
  166. PrepareStatements();
  167. new MediaStreamColumns(_connection, _logger).AddColumns();
  168. var chapterDbFile = Path.Combine(_appPaths.DataPath, "chapters.db");
  169. if (File.Exists(chapterDbFile))
  170. {
  171. MigrateChapters(chapterDbFile);
  172. }
  173. var mediaStreamsDbFile = Path.Combine(_appPaths.DataPath, "mediainfo.db");
  174. if (File.Exists(mediaStreamsDbFile))
  175. {
  176. MigrateMediaStreams(mediaStreamsDbFile);
  177. }
  178. }
  179. private void MigrateMediaStreams(string file)
  180. {
  181. var backupFile = file + ".bak";
  182. File.Copy(file, backupFile, true);
  183. SqliteExtensions.Attach(_connection, backupFile, "MediaInfoOld");
  184. var columns = string.Join(",", _mediaStreamSaveColumns);
  185. string[] queries = {
  186. "REPLACE INTO mediastreams("+columns+") SELECT "+columns+" FROM MediaInfoOld.mediastreams;"
  187. };
  188. try
  189. {
  190. _connection.RunQueries(queries, _logger);
  191. File.Delete(file);
  192. }
  193. catch (Exception ex)
  194. {
  195. _logger.ErrorException("Error migrating media info database", ex);
  196. }
  197. }
  198. private void MigrateChapters(string file)
  199. {
  200. var backupFile = file + ".bak";
  201. File.Copy(file, backupFile, true);
  202. SqliteExtensions.Attach(_connection, backupFile, "ChaptersOld");
  203. string[] queries = {
  204. "REPLACE INTO "+ChaptersTableName+"(ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath) SELECT ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath FROM ChaptersOld.Chapters;"
  205. };
  206. try
  207. {
  208. _connection.RunQueries(queries, _logger);
  209. File.Delete(file);
  210. }
  211. catch (Exception ex)
  212. {
  213. _logger.ErrorException("Error migrating chapter database", ex);
  214. }
  215. }
  216. /// <summary>
  217. /// The _write lock
  218. /// </summary>
  219. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  220. private readonly string[] _retriveItemColumns =
  221. {
  222. "type",
  223. "data",
  224. "StartDate",
  225. "EndDate",
  226. "IsOffline",
  227. "ChannelId",
  228. "IsMovie",
  229. "IsSports",
  230. "IsKids",
  231. "IsSeries",
  232. "IsLive",
  233. "IsNews",
  234. "IsPremiere",
  235. "EpisodeTitle",
  236. "IsRepeat",
  237. "CommunityRating",
  238. "CustomRating",
  239. "IndexNumber",
  240. "IsLocked",
  241. "PreferredMetadataLanguage",
  242. "PreferredMetadataCountryCode",
  243. "IsHD",
  244. "ExternalEtag",
  245. "DateLastRefreshed",
  246. "Name",
  247. "Path",
  248. "PremiereDate",
  249. "Overview",
  250. "ParentIndexNumber",
  251. "ProductionYear",
  252. "OfficialRating",
  253. "OfficialRatingDescription",
  254. "HomePageUrl",
  255. "DisplayMediaType",
  256. "ForcedSortName",
  257. "RunTimeTicks",
  258. "VoteCount",
  259. "DateCreated",
  260. "DateModified",
  261. "guid",
  262. "Genres"
  263. };
  264. private readonly string[] _mediaStreamSaveColumns =
  265. {
  266. "ItemId",
  267. "StreamIndex",
  268. "StreamType",
  269. "Codec",
  270. "Language",
  271. "ChannelLayout",
  272. "Profile",
  273. "AspectRatio",
  274. "Path",
  275. "IsInterlaced",
  276. "BitRate",
  277. "Channels",
  278. "SampleRate",
  279. "IsDefault",
  280. "IsForced",
  281. "IsExternal",
  282. "Height",
  283. "Width",
  284. "AverageFrameRate",
  285. "RealFrameRate",
  286. "Level",
  287. "PixelFormat",
  288. "BitDepth",
  289. "IsAnamorphic",
  290. "RefFrames",
  291. "IsCabac",
  292. "KeyFrames",
  293. "CodecTag"
  294. };
  295. /// <summary>
  296. /// Prepares the statements.
  297. /// </summary>
  298. private void PrepareStatements()
  299. {
  300. var saveColumns = new List<string>
  301. {
  302. "guid",
  303. "type",
  304. "data",
  305. "Path",
  306. "StartDate",
  307. "EndDate",
  308. "ChannelId",
  309. "IsKids",
  310. "IsMovie",
  311. "IsSports",
  312. "IsSeries",
  313. "IsLive",
  314. "IsNews",
  315. "IsPremiere",
  316. "EpisodeTitle",
  317. "IsRepeat",
  318. "CommunityRating",
  319. "CustomRating",
  320. "IndexNumber",
  321. "IsLocked",
  322. "Name",
  323. "OfficialRating",
  324. "MediaType",
  325. "Overview",
  326. "ParentIndexNumber",
  327. "PremiereDate",
  328. "ProductionYear",
  329. "ParentId",
  330. "Genres",
  331. "ParentalRatingValue",
  332. "SchemaVersion",
  333. "SortName",
  334. "RunTimeTicks",
  335. "OfficialRatingDescription",
  336. "HomePageUrl",
  337. "VoteCount",
  338. "DisplayMediaType",
  339. "DateCreated",
  340. "DateModified",
  341. "ForcedSortName",
  342. "IsOffline",
  343. "LocationType",
  344. "PreferredMetadataLanguage",
  345. "PreferredMetadataCountryCode",
  346. "IsHD",
  347. "ExternalEtag",
  348. "DateLastRefreshed",
  349. "DateLastSaved",
  350. "IsInMixedFolder",
  351. "LockedFields"
  352. };
  353. _saveItemCommand = _connection.CreateCommand();
  354. _saveItemCommand.CommandText = "replace into TypedBaseItems (" + string.Join(",", saveColumns.ToArray()) + ") values (";
  355. for (var i = 1; i <= saveColumns.Count; i++)
  356. {
  357. if (i > 1)
  358. {
  359. _saveItemCommand.CommandText += ",";
  360. }
  361. _saveItemCommand.CommandText += "@" + i.ToString(CultureInfo.InvariantCulture);
  362. _saveItemCommand.Parameters.Add(_saveItemCommand, "@" + i.ToString(CultureInfo.InvariantCulture));
  363. }
  364. _saveItemCommand.CommandText += ")";
  365. _deleteChildrenCommand = _connection.CreateCommand();
  366. _deleteChildrenCommand.CommandText = "delete from ChildrenIds where ParentId=@ParentId";
  367. _deleteChildrenCommand.Parameters.Add(_deleteChildrenCommand, "@ParentId");
  368. _deleteItemCommand = _connection.CreateCommand();
  369. _deleteItemCommand.CommandText = "delete from TypedBaseItems where guid=@Id";
  370. _deleteItemCommand.Parameters.Add(_deleteItemCommand, "@Id");
  371. _saveChildrenCommand = _connection.CreateCommand();
  372. _saveChildrenCommand.CommandText = "replace into ChildrenIds (ParentId, ItemId) values (@ParentId, @ItemId)";
  373. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ParentId");
  374. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ItemId");
  375. // People
  376. _deletePeopleCommand = _connection.CreateCommand();
  377. _deletePeopleCommand.CommandText = "delete from People where ItemId=@Id";
  378. _deletePeopleCommand.Parameters.Add(_deletePeopleCommand, "@Id");
  379. _savePersonCommand = _connection.CreateCommand();
  380. _savePersonCommand.CommandText = "insert into People (ItemId, Name, Role, PersonType, SortOrder, ListOrder) values (@ItemId, @Name, @Role, @PersonType, @SortOrder, @ListOrder)";
  381. _savePersonCommand.Parameters.Add(_savePersonCommand, "@ItemId");
  382. _savePersonCommand.Parameters.Add(_savePersonCommand, "@Name");
  383. _savePersonCommand.Parameters.Add(_savePersonCommand, "@Role");
  384. _savePersonCommand.Parameters.Add(_savePersonCommand, "@PersonType");
  385. _savePersonCommand.Parameters.Add(_savePersonCommand, "@SortOrder");
  386. _savePersonCommand.Parameters.Add(_savePersonCommand, "@ListOrder");
  387. // Chapters
  388. _deleteChaptersCommand = _connection.CreateCommand();
  389. _deleteChaptersCommand.CommandText = "delete from " + ChaptersTableName + " where ItemId=@ItemId";
  390. _deleteChaptersCommand.Parameters.Add(_deleteChaptersCommand, "@ItemId");
  391. _saveChapterCommand = _connection.CreateCommand();
  392. _saveChapterCommand.CommandText = "replace into " + ChaptersTableName + " (ItemId, ChapterIndex, StartPositionTicks, Name, ImagePath) values (@ItemId, @ChapterIndex, @StartPositionTicks, @Name, @ImagePath)";
  393. _saveChapterCommand.Parameters.Add(_saveChapterCommand, "@ItemId");
  394. _saveChapterCommand.Parameters.Add(_saveChapterCommand, "@ChapterIndex");
  395. _saveChapterCommand.Parameters.Add(_saveChapterCommand, "@StartPositionTicks");
  396. _saveChapterCommand.Parameters.Add(_saveChapterCommand, "@Name");
  397. _saveChapterCommand.Parameters.Add(_saveChapterCommand, "@ImagePath");
  398. // MediaStreams
  399. _deleteStreamsCommand = _connection.CreateCommand();
  400. _deleteStreamsCommand.CommandText = "delete from mediastreams where ItemId=@ItemId";
  401. _deleteStreamsCommand.Parameters.Add(_deleteStreamsCommand, "@ItemId");
  402. _saveStreamCommand = _connection.CreateCommand();
  403. _saveStreamCommand.CommandText = string.Format("replace into mediastreams ({0}) values ({1})",
  404. string.Join(",", _mediaStreamSaveColumns),
  405. string.Join(",", _mediaStreamSaveColumns.Select(i => "@" + i).ToArray()));
  406. foreach (var col in _mediaStreamSaveColumns)
  407. {
  408. _saveStreamCommand.Parameters.Add(_saveStreamCommand, "@" + col);
  409. }
  410. }
  411. /// <summary>
  412. /// Save a standard item in the repo
  413. /// </summary>
  414. /// <param name="item">The item.</param>
  415. /// <param name="cancellationToken">The cancellation token.</param>
  416. /// <returns>Task.</returns>
  417. /// <exception cref="System.ArgumentNullException">item</exception>
  418. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  419. {
  420. if (item == null)
  421. {
  422. throw new ArgumentNullException("item");
  423. }
  424. return SaveItems(new[] { item }, cancellationToken);
  425. }
  426. /// <summary>
  427. /// Saves the items.
  428. /// </summary>
  429. /// <param name="items">The items.</param>
  430. /// <param name="cancellationToken">The cancellation token.</param>
  431. /// <returns>Task.</returns>
  432. /// <exception cref="System.ArgumentNullException">
  433. /// items
  434. /// or
  435. /// cancellationToken
  436. /// </exception>
  437. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  438. {
  439. if (items == null)
  440. {
  441. throw new ArgumentNullException("items");
  442. }
  443. cancellationToken.ThrowIfCancellationRequested();
  444. CheckDisposed();
  445. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  446. IDbTransaction transaction = null;
  447. try
  448. {
  449. transaction = _connection.BeginTransaction();
  450. foreach (var item in items)
  451. {
  452. cancellationToken.ThrowIfCancellationRequested();
  453. var index = 0;
  454. _saveItemCommand.GetParameter(index++).Value = item.Id;
  455. _saveItemCommand.GetParameter(index++).Value = item.GetType().FullName;
  456. _saveItemCommand.GetParameter(index++).Value = _jsonSerializer.SerializeToBytes(item);
  457. _saveItemCommand.GetParameter(index++).Value = item.Path;
  458. var hasStartDate = item as IHasStartDate;
  459. if (hasStartDate != null)
  460. {
  461. _saveItemCommand.GetParameter(index++).Value = hasStartDate.StartDate;
  462. }
  463. else
  464. {
  465. _saveItemCommand.GetParameter(index++).Value = null;
  466. }
  467. _saveItemCommand.GetParameter(index++).Value = item.EndDate;
  468. _saveItemCommand.GetParameter(index++).Value = item.ChannelId;
  469. var hasProgramAttributes = item as IHasProgramAttributes;
  470. if (hasProgramAttributes != null)
  471. {
  472. _saveItemCommand.GetParameter(index++).Value = hasProgramAttributes.IsKids;
  473. _saveItemCommand.GetParameter(index++).Value = hasProgramAttributes.IsMovie;
  474. _saveItemCommand.GetParameter(index++).Value = hasProgramAttributes.IsSports;
  475. _saveItemCommand.GetParameter(index++).Value = hasProgramAttributes.IsSeries;
  476. _saveItemCommand.GetParameter(index++).Value = hasProgramAttributes.IsLive;
  477. _saveItemCommand.GetParameter(index++).Value = hasProgramAttributes.IsNews;
  478. _saveItemCommand.GetParameter(index++).Value = hasProgramAttributes.IsPremiere;
  479. _saveItemCommand.GetParameter(index++).Value = hasProgramAttributes.EpisodeTitle;
  480. _saveItemCommand.GetParameter(index++).Value = hasProgramAttributes.IsRepeat;
  481. }
  482. else
  483. {
  484. _saveItemCommand.GetParameter(index++).Value = null;
  485. _saveItemCommand.GetParameter(index++).Value = null;
  486. _saveItemCommand.GetParameter(index++).Value = null;
  487. _saveItemCommand.GetParameter(index++).Value = null;
  488. _saveItemCommand.GetParameter(index++).Value = null;
  489. _saveItemCommand.GetParameter(index++).Value = null;
  490. _saveItemCommand.GetParameter(index++).Value = null;
  491. _saveItemCommand.GetParameter(index++).Value = null;
  492. _saveItemCommand.GetParameter(index++).Value = null;
  493. }
  494. _saveItemCommand.GetParameter(index++).Value = item.CommunityRating;
  495. _saveItemCommand.GetParameter(index++).Value = item.CustomRating;
  496. _saveItemCommand.GetParameter(index++).Value = item.IndexNumber;
  497. _saveItemCommand.GetParameter(index++).Value = item.IsLocked;
  498. _saveItemCommand.GetParameter(index++).Value = item.Name;
  499. _saveItemCommand.GetParameter(index++).Value = item.OfficialRating;
  500. _saveItemCommand.GetParameter(index++).Value = item.MediaType;
  501. _saveItemCommand.GetParameter(index++).Value = item.Overview;
  502. _saveItemCommand.GetParameter(index++).Value = item.ParentIndexNumber;
  503. _saveItemCommand.GetParameter(index++).Value = item.PremiereDate;
  504. _saveItemCommand.GetParameter(index++).Value = item.ProductionYear;
  505. if (item.ParentId == Guid.Empty)
  506. {
  507. _saveItemCommand.GetParameter(index++).Value = null;
  508. }
  509. else
  510. {
  511. _saveItemCommand.GetParameter(index++).Value = item.ParentId;
  512. }
  513. _saveItemCommand.GetParameter(index++).Value = string.Join("|", item.Genres.ToArray());
  514. _saveItemCommand.GetParameter(index++).Value = item.GetParentalRatingValue();
  515. _saveItemCommand.GetParameter(index++).Value = LatestSchemaVersion;
  516. _saveItemCommand.GetParameter(index++).Value = item.SortName;
  517. _saveItemCommand.GetParameter(index++).Value = item.RunTimeTicks;
  518. _saveItemCommand.GetParameter(index++).Value = item.OfficialRatingDescription;
  519. _saveItemCommand.GetParameter(index++).Value = item.HomePageUrl;
  520. _saveItemCommand.GetParameter(index++).Value = item.VoteCount;
  521. _saveItemCommand.GetParameter(index++).Value = item.DisplayMediaType;
  522. _saveItemCommand.GetParameter(index++).Value = item.DateCreated;
  523. _saveItemCommand.GetParameter(index++).Value = item.DateModified;
  524. _saveItemCommand.GetParameter(index++).Value = item.ForcedSortName;
  525. _saveItemCommand.GetParameter(index++).Value = item.IsOffline;
  526. _saveItemCommand.GetParameter(index++).Value = item.LocationType.ToString();
  527. _saveItemCommand.GetParameter(index++).Value = item.PreferredMetadataLanguage;
  528. _saveItemCommand.GetParameter(index++).Value = item.PreferredMetadataCountryCode;
  529. _saveItemCommand.GetParameter(index++).Value = item.IsHD;
  530. _saveItemCommand.GetParameter(index++).Value = item.ExternalEtag;
  531. if (item.DateLastRefreshed == default(DateTime))
  532. {
  533. _saveItemCommand.GetParameter(index++).Value = null;
  534. }
  535. else
  536. {
  537. _saveItemCommand.GetParameter(index++).Value = item.DateLastRefreshed;
  538. }
  539. _saveItemCommand.GetParameter(index++).Value = item.DateLastSaved;
  540. _saveItemCommand.GetParameter(index++).Value = item.IsInMixedFolder;
  541. _saveItemCommand.GetParameter(index++).Value = string.Join("|", item.LockedFields.Select(i => i.ToString()).ToArray());
  542. _saveItemCommand.Transaction = transaction;
  543. _saveItemCommand.ExecuteNonQuery();
  544. }
  545. transaction.Commit();
  546. }
  547. catch (OperationCanceledException)
  548. {
  549. if (transaction != null)
  550. {
  551. transaction.Rollback();
  552. }
  553. throw;
  554. }
  555. catch (Exception e)
  556. {
  557. _logger.ErrorException("Failed to save items:", e);
  558. if (transaction != null)
  559. {
  560. transaction.Rollback();
  561. }
  562. throw;
  563. }
  564. finally
  565. {
  566. if (transaction != null)
  567. {
  568. transaction.Dispose();
  569. }
  570. _writeLock.Release();
  571. }
  572. }
  573. /// <summary>
  574. /// Internal retrieve from items or users table
  575. /// </summary>
  576. /// <param name="id">The id.</param>
  577. /// <returns>BaseItem.</returns>
  578. /// <exception cref="System.ArgumentNullException">id</exception>
  579. /// <exception cref="System.ArgumentException"></exception>
  580. public BaseItem RetrieveItem(Guid id)
  581. {
  582. if (id == Guid.Empty)
  583. {
  584. throw new ArgumentNullException("id");
  585. }
  586. CheckDisposed();
  587. using (var cmd = _connection.CreateCommand())
  588. {
  589. cmd.CommandText = "select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems where guid = @guid";
  590. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = id;
  591. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  592. {
  593. if (reader.Read())
  594. {
  595. return GetItem(reader);
  596. }
  597. }
  598. return null;
  599. }
  600. }
  601. private BaseItem GetItem(IDataReader reader)
  602. {
  603. var typeString = reader.GetString(0);
  604. var type = _typeMapper.GetType(typeString);
  605. if (type == null)
  606. {
  607. _logger.Debug("Unknown type {0}", typeString);
  608. return null;
  609. }
  610. BaseItem item;
  611. using (var stream = reader.GetMemoryStream(1))
  612. {
  613. try
  614. {
  615. item = _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
  616. if (item == null)
  617. {
  618. return null;
  619. }
  620. }
  621. catch (SerializationException ex)
  622. {
  623. _logger.ErrorException("Error deserializing item", ex);
  624. return null;
  625. }
  626. }
  627. if (!reader.IsDBNull(2))
  628. {
  629. var hasStartDate = item as IHasStartDate;
  630. if (hasStartDate != null)
  631. {
  632. hasStartDate.StartDate = reader.GetDateTime(2).ToUniversalTime();
  633. }
  634. }
  635. if (!reader.IsDBNull(3))
  636. {
  637. item.EndDate = reader.GetDateTime(3).ToUniversalTime();
  638. }
  639. if (!reader.IsDBNull(4))
  640. {
  641. item.IsOffline = reader.GetBoolean(4);
  642. }
  643. if (!reader.IsDBNull(5))
  644. {
  645. item.ChannelId = reader.GetString(5);
  646. }
  647. var hasProgramAttributes = item as IHasProgramAttributes;
  648. if (hasProgramAttributes != null)
  649. {
  650. if (!reader.IsDBNull(6))
  651. {
  652. hasProgramAttributes.IsMovie = reader.GetBoolean(6);
  653. }
  654. if (!reader.IsDBNull(7))
  655. {
  656. hasProgramAttributes.IsSports = reader.GetBoolean(7);
  657. }
  658. if (!reader.IsDBNull(8))
  659. {
  660. hasProgramAttributes.IsKids = reader.GetBoolean(8);
  661. }
  662. if (!reader.IsDBNull(9))
  663. {
  664. hasProgramAttributes.IsSeries = reader.GetBoolean(9);
  665. }
  666. if (!reader.IsDBNull(10))
  667. {
  668. hasProgramAttributes.IsLive = reader.GetBoolean(10);
  669. }
  670. if (!reader.IsDBNull(11))
  671. {
  672. hasProgramAttributes.IsNews = reader.GetBoolean(11);
  673. }
  674. if (!reader.IsDBNull(12))
  675. {
  676. hasProgramAttributes.IsPremiere = reader.GetBoolean(12);
  677. }
  678. if (!reader.IsDBNull(13))
  679. {
  680. hasProgramAttributes.EpisodeTitle = reader.GetString(13);
  681. }
  682. if (!reader.IsDBNull(14))
  683. {
  684. hasProgramAttributes.IsRepeat = reader.GetBoolean(14);
  685. }
  686. }
  687. if (!reader.IsDBNull(15))
  688. {
  689. item.CommunityRating = reader.GetFloat(15);
  690. }
  691. if (!reader.IsDBNull(16))
  692. {
  693. item.CustomRating = reader.GetString(16);
  694. }
  695. if (!reader.IsDBNull(17))
  696. {
  697. item.IndexNumber = reader.GetInt32(17);
  698. }
  699. if (!reader.IsDBNull(18))
  700. {
  701. item.IsLocked = reader.GetBoolean(18);
  702. }
  703. if (!reader.IsDBNull(19))
  704. {
  705. item.PreferredMetadataLanguage = reader.GetString(19);
  706. }
  707. if (!reader.IsDBNull(20))
  708. {
  709. item.PreferredMetadataCountryCode = reader.GetString(20);
  710. }
  711. if (!reader.IsDBNull(21))
  712. {
  713. item.IsHD = reader.GetBoolean(21);
  714. }
  715. if (!reader.IsDBNull(22))
  716. {
  717. item.ExternalEtag = reader.GetString(22);
  718. }
  719. if (!reader.IsDBNull(23))
  720. {
  721. item.DateLastRefreshed = reader.GetDateTime(23).ToUniversalTime();
  722. }
  723. if (!reader.IsDBNull(24))
  724. {
  725. item.Name = reader.GetString(24);
  726. }
  727. if (!reader.IsDBNull(25))
  728. {
  729. item.Path = reader.GetString(25);
  730. }
  731. if (!reader.IsDBNull(26))
  732. {
  733. item.PremiereDate = reader.GetDateTime(26).ToUniversalTime();
  734. }
  735. if (!reader.IsDBNull(27))
  736. {
  737. item.Overview = reader.GetString(27);
  738. }
  739. if (!reader.IsDBNull(28))
  740. {
  741. item.ParentIndexNumber = reader.GetInt32(28);
  742. }
  743. if (!reader.IsDBNull(29))
  744. {
  745. item.ProductionYear = reader.GetInt32(29);
  746. }
  747. if (!reader.IsDBNull(30))
  748. {
  749. item.OfficialRating = reader.GetString(30);
  750. }
  751. if (!reader.IsDBNull(31))
  752. {
  753. item.OfficialRating = reader.GetString(31);
  754. }
  755. if (!reader.IsDBNull(32))
  756. {
  757. item.HomePageUrl = reader.GetString(32);
  758. }
  759. if (!reader.IsDBNull(33))
  760. {
  761. item.DisplayMediaType = reader.GetString(33);
  762. }
  763. if (!reader.IsDBNull(34))
  764. {
  765. item.ForcedSortName = reader.GetString(34);
  766. }
  767. if (!reader.IsDBNull(35))
  768. {
  769. item.RunTimeTicks = reader.GetInt64(35);
  770. }
  771. if (!reader.IsDBNull(36))
  772. {
  773. item.VoteCount = reader.GetInt32(36);
  774. }
  775. if (!reader.IsDBNull(37))
  776. {
  777. item.DateCreated = reader.GetDateTime(37).ToUniversalTime();
  778. }
  779. if (!reader.IsDBNull(38))
  780. {
  781. item.DateModified = reader.GetDateTime(38).ToUniversalTime();
  782. }
  783. item.Id = reader.GetGuid(39);
  784. if (!reader.IsDBNull(40))
  785. {
  786. item.Genres = reader.GetString(40).Split('|').Where(i => !string.IsNullOrWhiteSpace(i)).ToList();
  787. }
  788. return item;
  789. }
  790. /// <summary>
  791. /// Gets the critic reviews.
  792. /// </summary>
  793. /// <param name="itemId">The item id.</param>
  794. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  795. public IEnumerable<ItemReview> GetCriticReviews(Guid itemId)
  796. {
  797. try
  798. {
  799. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  800. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  801. }
  802. catch (DirectoryNotFoundException)
  803. {
  804. return new List<ItemReview>();
  805. }
  806. catch (FileNotFoundException)
  807. {
  808. return new List<ItemReview>();
  809. }
  810. }
  811. private readonly Task _cachedTask = Task.FromResult(true);
  812. /// <summary>
  813. /// Saves the critic reviews.
  814. /// </summary>
  815. /// <param name="itemId">The item id.</param>
  816. /// <param name="criticReviews">The critic reviews.</param>
  817. /// <returns>Task.</returns>
  818. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  819. {
  820. Directory.CreateDirectory(_criticReviewsPath);
  821. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  822. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  823. return _cachedTask;
  824. }
  825. /// <summary>
  826. /// Gets chapters for an item
  827. /// </summary>
  828. /// <param name="id">The id.</param>
  829. /// <returns>IEnumerable{ChapterInfo}.</returns>
  830. /// <exception cref="System.ArgumentNullException">id</exception>
  831. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  832. {
  833. CheckDisposed();
  834. if (id == Guid.Empty)
  835. {
  836. throw new ArgumentNullException("id");
  837. }
  838. using (var cmd = _connection.CreateCommand())
  839. {
  840. cmd.CommandText = "select StartPositionTicks,Name,ImagePath from " + ChaptersTableName + " where ItemId = @ItemId order by ChapterIndex asc";
  841. cmd.Parameters.Add(cmd, "@ItemId", DbType.Guid).Value = id;
  842. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  843. {
  844. while (reader.Read())
  845. {
  846. yield return GetChapter(reader);
  847. }
  848. }
  849. }
  850. }
  851. /// <summary>
  852. /// Gets a single chapter for an item
  853. /// </summary>
  854. /// <param name="id">The id.</param>
  855. /// <param name="index">The index.</param>
  856. /// <returns>ChapterInfo.</returns>
  857. /// <exception cref="System.ArgumentNullException">id</exception>
  858. public ChapterInfo GetChapter(Guid id, int index)
  859. {
  860. CheckDisposed();
  861. if (id == Guid.Empty)
  862. {
  863. throw new ArgumentNullException("id");
  864. }
  865. using (var cmd = _connection.CreateCommand())
  866. {
  867. cmd.CommandText = "select StartPositionTicks,Name,ImagePath from " + ChaptersTableName + " where ItemId = @ItemId and ChapterIndex=@ChapterIndex";
  868. cmd.Parameters.Add(cmd, "@ItemId", DbType.Guid).Value = id;
  869. cmd.Parameters.Add(cmd, "@ChapterIndex", DbType.Int32).Value = index;
  870. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  871. {
  872. if (reader.Read())
  873. {
  874. return GetChapter(reader);
  875. }
  876. }
  877. return null;
  878. }
  879. }
  880. /// <summary>
  881. /// Gets the chapter.
  882. /// </summary>
  883. /// <param name="reader">The reader.</param>
  884. /// <returns>ChapterInfo.</returns>
  885. private ChapterInfo GetChapter(IDataReader reader)
  886. {
  887. var chapter = new ChapterInfo
  888. {
  889. StartPositionTicks = reader.GetInt64(0)
  890. };
  891. if (!reader.IsDBNull(1))
  892. {
  893. chapter.Name = reader.GetString(1);
  894. }
  895. if (!reader.IsDBNull(2))
  896. {
  897. chapter.ImagePath = reader.GetString(2);
  898. }
  899. return chapter;
  900. }
  901. /// <summary>
  902. /// Saves the chapters.
  903. /// </summary>
  904. /// <param name="id">The id.</param>
  905. /// <param name="chapters">The chapters.</param>
  906. /// <param name="cancellationToken">The cancellation token.</param>
  907. /// <returns>Task.</returns>
  908. /// <exception cref="System.ArgumentNullException">
  909. /// id
  910. /// or
  911. /// chapters
  912. /// or
  913. /// cancellationToken
  914. /// </exception>
  915. public async Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  916. {
  917. CheckDisposed();
  918. if (id == Guid.Empty)
  919. {
  920. throw new ArgumentNullException("id");
  921. }
  922. if (chapters == null)
  923. {
  924. throw new ArgumentNullException("chapters");
  925. }
  926. cancellationToken.ThrowIfCancellationRequested();
  927. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  928. IDbTransaction transaction = null;
  929. try
  930. {
  931. transaction = _connection.BeginTransaction();
  932. // First delete chapters
  933. _deleteChaptersCommand.GetParameter(0).Value = id;
  934. _deleteChaptersCommand.Transaction = transaction;
  935. _deleteChaptersCommand.ExecuteNonQuery();
  936. var index = 0;
  937. foreach (var chapter in chapters)
  938. {
  939. cancellationToken.ThrowIfCancellationRequested();
  940. _saveChapterCommand.GetParameter(0).Value = id;
  941. _saveChapterCommand.GetParameter(1).Value = index;
  942. _saveChapterCommand.GetParameter(2).Value = chapter.StartPositionTicks;
  943. _saveChapterCommand.GetParameter(3).Value = chapter.Name;
  944. _saveChapterCommand.GetParameter(4).Value = chapter.ImagePath;
  945. _saveChapterCommand.Transaction = transaction;
  946. _saveChapterCommand.ExecuteNonQuery();
  947. index++;
  948. }
  949. transaction.Commit();
  950. }
  951. catch (OperationCanceledException)
  952. {
  953. if (transaction != null)
  954. {
  955. transaction.Rollback();
  956. }
  957. throw;
  958. }
  959. catch (Exception e)
  960. {
  961. _logger.ErrorException("Failed to save chapters:", e);
  962. if (transaction != null)
  963. {
  964. transaction.Rollback();
  965. }
  966. throw;
  967. }
  968. finally
  969. {
  970. if (transaction != null)
  971. {
  972. transaction.Dispose();
  973. }
  974. _writeLock.Release();
  975. }
  976. }
  977. /// <summary>
  978. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  979. /// </summary>
  980. public void Dispose()
  981. {
  982. Dispose(true);
  983. GC.SuppressFinalize(this);
  984. }
  985. private readonly object _disposeLock = new object();
  986. private bool _disposed;
  987. private void CheckDisposed()
  988. {
  989. if (_disposed)
  990. {
  991. throw new ObjectDisposedException(GetType().Name + " has been disposed and cannot be accessed.");
  992. }
  993. }
  994. /// <summary>
  995. /// Releases unmanaged and - optionally - managed resources.
  996. /// </summary>
  997. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  998. protected virtual void Dispose(bool dispose)
  999. {
  1000. if (dispose)
  1001. {
  1002. _disposed = true;
  1003. try
  1004. {
  1005. lock (_disposeLock)
  1006. {
  1007. _writeLock.Wait();
  1008. if (_connection != null)
  1009. {
  1010. if (_connection.IsOpen())
  1011. {
  1012. _connection.Close();
  1013. }
  1014. _connection.Dispose();
  1015. _connection = null;
  1016. }
  1017. }
  1018. }
  1019. catch (Exception ex)
  1020. {
  1021. _logger.ErrorException("Error disposing database", ex);
  1022. }
  1023. }
  1024. }
  1025. public IEnumerable<Guid> GetChildren(Guid parentId)
  1026. {
  1027. if (parentId == Guid.Empty)
  1028. {
  1029. throw new ArgumentNullException("parentId");
  1030. }
  1031. CheckDisposed();
  1032. using (var cmd = _connection.CreateCommand())
  1033. {
  1034. cmd.CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId";
  1035. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  1036. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  1037. {
  1038. while (reader.Read())
  1039. {
  1040. yield return reader.GetGuid(0);
  1041. }
  1042. }
  1043. }
  1044. }
  1045. public IEnumerable<BaseItem> GetChildrenItems(Guid parentId)
  1046. {
  1047. if (parentId == Guid.Empty)
  1048. {
  1049. throw new ArgumentNullException("parentId");
  1050. }
  1051. CheckDisposed();
  1052. using (var cmd = _connection.CreateCommand())
  1053. {
  1054. cmd.CommandText = "select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems where guid in (select ItemId from ChildrenIds where ParentId = @ParentId)";
  1055. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  1056. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  1057. {
  1058. while (reader.Read())
  1059. {
  1060. var item = GetItem(reader);
  1061. if (item != null)
  1062. {
  1063. yield return item;
  1064. }
  1065. }
  1066. }
  1067. }
  1068. }
  1069. public IEnumerable<BaseItem> GetItemsOfType(Type type)
  1070. {
  1071. if (type == null)
  1072. {
  1073. throw new ArgumentNullException("type");
  1074. }
  1075. CheckDisposed();
  1076. using (var cmd = _connection.CreateCommand())
  1077. {
  1078. cmd.CommandText = "select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems where type = @type";
  1079. cmd.Parameters.Add(cmd, "@type", DbType.String).Value = type.FullName;
  1080. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  1081. {
  1082. while (reader.Read())
  1083. {
  1084. var item = GetItem(reader);
  1085. if (item != null)
  1086. {
  1087. yield return item;
  1088. }
  1089. }
  1090. }
  1091. }
  1092. }
  1093. public QueryResult<BaseItem> GetItems(InternalItemsQuery query)
  1094. {
  1095. if (query == null)
  1096. {
  1097. throw new ArgumentNullException("query");
  1098. }
  1099. CheckDisposed();
  1100. using (var cmd = _connection.CreateCommand())
  1101. {
  1102. cmd.CommandText = "select " + string.Join(",", _retriveItemColumns) + " from TypedBaseItems";
  1103. var whereClauses = GetWhereClauses(query, cmd, false);
  1104. var whereTextWithoutPaging = whereClauses.Count == 0 ?
  1105. string.Empty :
  1106. " where " + string.Join(" AND ", whereClauses.ToArray());
  1107. whereClauses = GetWhereClauses(query, cmd, true);
  1108. var whereText = whereClauses.Count == 0 ?
  1109. string.Empty :
  1110. " where " + string.Join(" AND ", whereClauses.ToArray());
  1111. cmd.CommandText += whereText;
  1112. cmd.CommandText += GetOrderByText(query);
  1113. if (query.Limit.HasValue)
  1114. {
  1115. cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(CultureInfo.InvariantCulture);
  1116. }
  1117. cmd.CommandText += "; select count (guid) from TypedBaseItems" + whereTextWithoutPaging;
  1118. _logger.Debug(cmd.CommandText);
  1119. var list = new List<BaseItem>();
  1120. var count = 0;
  1121. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
  1122. {
  1123. while (reader.Read())
  1124. {
  1125. var item = GetItem(reader);
  1126. if (item != null)
  1127. {
  1128. list.Add(item);
  1129. }
  1130. }
  1131. if (reader.NextResult() && reader.Read())
  1132. {
  1133. count = reader.GetInt32(0);
  1134. }
  1135. }
  1136. return new QueryResult<BaseItem>()
  1137. {
  1138. Items = list.ToArray(),
  1139. TotalRecordCount = count
  1140. };
  1141. }
  1142. }
  1143. private string GetOrderByText(InternalItemsQuery query)
  1144. {
  1145. if (query.SortBy == null || query.SortBy.Length == 0)
  1146. {
  1147. return string.Empty;
  1148. }
  1149. var sortOrder = query.SortOrder == SortOrder.Descending ? "DESC" : "ASC";
  1150. return " ORDER BY " + string.Join(",", query.SortBy.Select(i => MapOrderByField(i) + " " + sortOrder).ToArray());
  1151. }
  1152. private string MapOrderByField(string name)
  1153. {
  1154. return name;
  1155. }
  1156. public List<Guid> GetItemIdsList(InternalItemsQuery query)
  1157. {
  1158. if (query == null)
  1159. {
  1160. throw new ArgumentNullException("query");
  1161. }
  1162. CheckDisposed();
  1163. using (var cmd = _connection.CreateCommand())
  1164. {
  1165. cmd.CommandText = "select guid from TypedBaseItems";
  1166. var whereClauses = GetWhereClauses(query, cmd, true);
  1167. var whereText = whereClauses.Count == 0 ?
  1168. string.Empty :
  1169. " where " + string.Join(" AND ", whereClauses.ToArray());
  1170. cmd.CommandText += whereText;
  1171. cmd.CommandText += GetOrderByText(query);
  1172. if (query.Limit.HasValue)
  1173. {
  1174. cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(CultureInfo.InvariantCulture);
  1175. }
  1176. var list = new List<Guid>();
  1177. _logger.Debug(cmd.CommandText);
  1178. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
  1179. {
  1180. while (reader.Read())
  1181. {
  1182. list.Add(reader.GetGuid(0));
  1183. }
  1184. }
  1185. return list;
  1186. }
  1187. }
  1188. public QueryResult<Tuple<Guid, string>> GetItemIdsWithPath(InternalItemsQuery query)
  1189. {
  1190. if (query == null)
  1191. {
  1192. throw new ArgumentNullException("query");
  1193. }
  1194. CheckDisposed();
  1195. using (var cmd = _connection.CreateCommand())
  1196. {
  1197. cmd.CommandText = "select guid,path from TypedBaseItems";
  1198. var whereClauses = GetWhereClauses(query, cmd, false);
  1199. var whereTextWithoutPaging = whereClauses.Count == 0 ?
  1200. string.Empty :
  1201. " where " + string.Join(" AND ", whereClauses.ToArray());
  1202. whereClauses = GetWhereClauses(query, cmd, true);
  1203. var whereText = whereClauses.Count == 0 ?
  1204. string.Empty :
  1205. " where " + string.Join(" AND ", whereClauses.ToArray());
  1206. cmd.CommandText += whereText;
  1207. cmd.CommandText += GetOrderByText(query);
  1208. if (query.Limit.HasValue)
  1209. {
  1210. cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(CultureInfo.InvariantCulture);
  1211. }
  1212. cmd.CommandText += "; select count (guid) from TypedBaseItems" + whereTextWithoutPaging;
  1213. var list = new List<Tuple<Guid, string>>();
  1214. var count = 0;
  1215. _logger.Debug(cmd.CommandText);
  1216. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
  1217. {
  1218. while (reader.Read())
  1219. {
  1220. var id = reader.GetGuid(0);
  1221. string path = null;
  1222. if (!reader.IsDBNull(1))
  1223. {
  1224. path = reader.GetString(1);
  1225. }
  1226. list.Add(new Tuple<Guid, string>(id, path));
  1227. }
  1228. if (reader.NextResult() && reader.Read())
  1229. {
  1230. count = reader.GetInt32(0);
  1231. }
  1232. }
  1233. return new QueryResult<Tuple<Guid, string>>()
  1234. {
  1235. Items = list.ToArray(),
  1236. TotalRecordCount = count
  1237. };
  1238. }
  1239. }
  1240. public QueryResult<Guid> GetItemIds(InternalItemsQuery query)
  1241. {
  1242. if (query == null)
  1243. {
  1244. throw new ArgumentNullException("query");
  1245. }
  1246. CheckDisposed();
  1247. using (var cmd = _connection.CreateCommand())
  1248. {
  1249. cmd.CommandText = "select guid from TypedBaseItems";
  1250. var whereClauses = GetWhereClauses(query, cmd, false);
  1251. var whereTextWithoutPaging = whereClauses.Count == 0 ?
  1252. string.Empty :
  1253. " where " + string.Join(" AND ", whereClauses.ToArray());
  1254. whereClauses = GetWhereClauses(query, cmd, true);
  1255. var whereText = whereClauses.Count == 0 ?
  1256. string.Empty :
  1257. " where " + string.Join(" AND ", whereClauses.ToArray());
  1258. cmd.CommandText += whereText;
  1259. cmd.CommandText += GetOrderByText(query);
  1260. if (query.Limit.HasValue)
  1261. {
  1262. cmd.CommandText += " LIMIT " + query.Limit.Value.ToString(CultureInfo.InvariantCulture);
  1263. }
  1264. cmd.CommandText += "; select count (guid) from TypedBaseItems" + whereTextWithoutPaging;
  1265. var list = new List<Guid>();
  1266. var count = 0;
  1267. _logger.Debug(cmd.CommandText);
  1268. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
  1269. {
  1270. while (reader.Read())
  1271. {
  1272. list.Add(reader.GetGuid(0));
  1273. }
  1274. if (reader.NextResult() && reader.Read())
  1275. {
  1276. count = reader.GetInt32(0);
  1277. }
  1278. }
  1279. return new QueryResult<Guid>()
  1280. {
  1281. Items = list.ToArray(),
  1282. TotalRecordCount = count
  1283. };
  1284. }
  1285. }
  1286. private List<string> GetWhereClauses(InternalItemsQuery query, IDbCommand cmd, bool addPaging)
  1287. {
  1288. var whereClauses = new List<string>();
  1289. if (query.IsCurrentSchema.HasValue)
  1290. {
  1291. if (query.IsCurrentSchema.Value)
  1292. {
  1293. whereClauses.Add("(SchemaVersion not null AND SchemaVersion=@SchemaVersion)");
  1294. }
  1295. else
  1296. {
  1297. whereClauses.Add("(SchemaVersion is null or SchemaVersion<>@SchemaVersion)");
  1298. }
  1299. cmd.Parameters.Add(cmd, "@SchemaVersion", DbType.Int32).Value = LatestSchemaVersion;
  1300. }
  1301. if (query.IsOffline.HasValue)
  1302. {
  1303. whereClauses.Add("IsOffline=@IsOffline");
  1304. cmd.Parameters.Add(cmd, "@IsOffline", DbType.Boolean).Value = query.IsOffline;
  1305. }
  1306. if (query.LocationType.HasValue)
  1307. {
  1308. whereClauses.Add("LocationType=@LocationType");
  1309. cmd.Parameters.Add(cmd, "@LocationType", DbType.String).Value = query.LocationType.Value;
  1310. }
  1311. if (query.IsMovie.HasValue)
  1312. {
  1313. whereClauses.Add("IsMovie=@IsMovie");
  1314. cmd.Parameters.Add(cmd, "@IsMovie", DbType.Boolean).Value = query.IsMovie;
  1315. }
  1316. if (query.IsKids.HasValue)
  1317. {
  1318. whereClauses.Add("IsKids=@IsKids");
  1319. cmd.Parameters.Add(cmd, "@IsKids", DbType.Boolean).Value = query.IsKids;
  1320. }
  1321. if (query.IsSports.HasValue)
  1322. {
  1323. whereClauses.Add("IsSports=@IsSports");
  1324. cmd.Parameters.Add(cmd, "@IsSports", DbType.Boolean).Value = query.IsSports;
  1325. }
  1326. var includeTypes = query.IncludeItemTypes.SelectMany(MapIncludeItemTypes).ToArray();
  1327. if (includeTypes.Length == 1)
  1328. {
  1329. whereClauses.Add("type=@type");
  1330. cmd.Parameters.Add(cmd, "@type", DbType.String).Value = includeTypes[0];
  1331. }
  1332. else if (includeTypes.Length > 1)
  1333. {
  1334. var inClause = string.Join(",", includeTypes.Select(i => "'" + i + "'").ToArray());
  1335. whereClauses.Add(string.Format("type in ({0})", inClause));
  1336. }
  1337. var excludeTypes = query.ExcludeItemTypes.SelectMany(MapIncludeItemTypes).ToArray();
  1338. if (excludeTypes.Length == 1)
  1339. {
  1340. whereClauses.Add("type<>@type");
  1341. cmd.Parameters.Add(cmd, "@type", DbType.String).Value = excludeTypes[0];
  1342. }
  1343. else if (excludeTypes.Length > 1)
  1344. {
  1345. var inClause = string.Join(",", excludeTypes.Select(i => "'" + i + "'").ToArray());
  1346. whereClauses.Add(string.Format("type not in ({0})", inClause));
  1347. }
  1348. if (query.ChannelIds.Length == 1)
  1349. {
  1350. whereClauses.Add("ChannelId=@ChannelId");
  1351. cmd.Parameters.Add(cmd, "@ChannelId", DbType.String).Value = query.ChannelIds[0];
  1352. }
  1353. if (query.ChannelIds.Length > 1)
  1354. {
  1355. var inClause = string.Join(",", query.ChannelIds.Select(i => "'" + i + "'").ToArray());
  1356. whereClauses.Add(string.Format("ChannelId in ({0})", inClause));
  1357. }
  1358. if (query.ParentId.HasValue)
  1359. {
  1360. whereClauses.Add("ParentId=@ParentId");
  1361. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = query.ParentId.Value;
  1362. }
  1363. if (query.MinEndDate.HasValue)
  1364. {
  1365. whereClauses.Add("EndDate>=@MinEndDate");
  1366. cmd.Parameters.Add(cmd, "@MinEndDate", DbType.Date).Value = query.MinEndDate.Value;
  1367. }
  1368. if (query.MaxEndDate.HasValue)
  1369. {
  1370. whereClauses.Add("EndDate<=@MaxEndDate");
  1371. cmd.Parameters.Add(cmd, "@MaxEndDate", DbType.Date).Value = query.MaxEndDate.Value;
  1372. }
  1373. if (query.MinStartDate.HasValue)
  1374. {
  1375. whereClauses.Add("StartDate>=@MinStartDate");
  1376. cmd.Parameters.Add(cmd, "@MinStartDate", DbType.Date).Value = query.MinStartDate.Value;
  1377. }
  1378. if (query.MaxStartDate.HasValue)
  1379. {
  1380. whereClauses.Add("StartDate<=@MaxStartDate");
  1381. cmd.Parameters.Add(cmd, "@MaxStartDate", DbType.Date).Value = query.MaxStartDate.Value;
  1382. }
  1383. if (query.IsAiring.HasValue)
  1384. {
  1385. if (query.IsAiring.Value)
  1386. {
  1387. whereClauses.Add("StartDate<=@MaxStartDate");
  1388. cmd.Parameters.Add(cmd, "@MaxStartDate", DbType.Date).Value = DateTime.UtcNow;
  1389. whereClauses.Add("EndDate>=@MinEndDate");
  1390. cmd.Parameters.Add(cmd, "@MinEndDate", DbType.Date).Value = DateTime.UtcNow;
  1391. }
  1392. else
  1393. {
  1394. whereClauses.Add("(StartDate>@IsAiringDate OR EndDate < @IsAiringDate)");
  1395. cmd.Parameters.Add(cmd, "@IsAiringDate", DbType.Date).Value = DateTime.UtcNow;
  1396. }
  1397. }
  1398. if (!string.IsNullOrWhiteSpace(query.Person))
  1399. {
  1400. whereClauses.Add("Guid in (select ItemId from People where Name=@PersonName)");
  1401. cmd.Parameters.Add(cmd, "@PersonName", DbType.String).Value = query.Person;
  1402. }
  1403. if (!string.IsNullOrWhiteSpace(query.NameContains))
  1404. {
  1405. whereClauses.Add("Name like @NameContains");
  1406. cmd.Parameters.Add(cmd, "@NameContains", DbType.String).Value = "%" + query.NameContains + "%";
  1407. }
  1408. if (query.Genres.Length > 0)
  1409. {
  1410. var genres = new List<string>();
  1411. var index = 0;
  1412. foreach (var genre in query.Genres)
  1413. {
  1414. genres.Add("Genres like @Genres" + index);
  1415. cmd.Parameters.Add(cmd, "@Genres" + index, DbType.String).Value = "%" + genre + "%";
  1416. index++;
  1417. }
  1418. var genreCaluse = "(" + string.Join(" OR ", genres.ToArray()) + ")";
  1419. whereClauses.Add(genreCaluse);
  1420. }
  1421. if (query.MaxParentalRating.HasValue)
  1422. {
  1423. whereClauses.Add("(ParentalRatingValue is NULL OR ParentalRatingValue<=@MaxParentalRating)");
  1424. cmd.Parameters.Add(cmd, "@MaxParentalRating", DbType.Int32).Value = query.MaxParentalRating.Value;
  1425. }
  1426. if (query.HasParentalRating.HasValue)
  1427. {
  1428. if (query.HasParentalRating.Value)
  1429. {
  1430. whereClauses.Add("ParentalRatingValue NOT NULL");
  1431. }
  1432. else
  1433. {
  1434. whereClauses.Add("ParentalRatingValue IS NULL");
  1435. }
  1436. }
  1437. if (query.HasDeadParentId.HasValue)
  1438. {
  1439. if (query.HasDeadParentId.Value)
  1440. {
  1441. whereClauses.Add("ParentId NOT NULL AND ParentId NOT IN (select guid from TypedBaseItems)");
  1442. }
  1443. }
  1444. if (addPaging)
  1445. {
  1446. if (query.StartIndex.HasValue && query.StartIndex.Value > 0)
  1447. {
  1448. var pagingWhereText = whereClauses.Count == 0 ?
  1449. string.Empty :
  1450. " where " + string.Join(" AND ", whereClauses.ToArray());
  1451. var orderBy = GetOrderByText(query);
  1452. whereClauses.Add(string.Format("guid NOT IN (SELECT guid FROM TypedBaseItems {0}" + orderBy + " LIMIT {1})",
  1453. pagingWhereText,
  1454. query.StartIndex.Value.ToString(CultureInfo.InvariantCulture)));
  1455. }
  1456. }
  1457. return whereClauses;
  1458. }
  1459. private static readonly Type[] KnownTypes =
  1460. {
  1461. typeof(LiveTvProgram),
  1462. typeof(LiveTvChannel),
  1463. typeof(LiveTvVideoRecording),
  1464. typeof(LiveTvAudioRecording),
  1465. typeof(Series),
  1466. typeof(Audio),
  1467. typeof(MusicAlbum),
  1468. typeof(MusicArtist),
  1469. typeof(MusicGenre),
  1470. typeof(MusicVideo),
  1471. typeof(Movie),
  1472. typeof(BoxSet),
  1473. typeof(Episode),
  1474. typeof(Season),
  1475. typeof(Series),
  1476. typeof(Book),
  1477. typeof(CollectionFolder),
  1478. typeof(Folder),
  1479. typeof(Game),
  1480. typeof(GameGenre),
  1481. typeof(GameSystem),
  1482. typeof(Genre),
  1483. typeof(Person),
  1484. typeof(Photo),
  1485. typeof(PhotoAlbum),
  1486. typeof(Studio),
  1487. typeof(UserRootFolder),
  1488. typeof(UserView),
  1489. typeof(Video),
  1490. typeof(Year),
  1491. typeof(Channel)
  1492. };
  1493. private static Dictionary<string, string[]> GetTypeMapDictionary()
  1494. {
  1495. var dict = new Dictionary<string, string[]>();
  1496. foreach (var t in KnownTypes)
  1497. {
  1498. dict[t.Name] = new[] { t.FullName };
  1499. }
  1500. dict["Recording"] = new[] { typeof(LiveTvAudioRecording).FullName, typeof(LiveTvVideoRecording).FullName };
  1501. dict["Program"] = new[] { typeof(LiveTvProgram).FullName };
  1502. dict["TvChannel"] = new[] { typeof(LiveTvChannel).FullName };
  1503. return dict;
  1504. }
  1505. // Not crazy about having this all the way down here, but at least it's in one place
  1506. readonly Dictionary<string, string[]> _types = GetTypeMapDictionary();
  1507. private IEnumerable<string> MapIncludeItemTypes(string value)
  1508. {
  1509. string[] result;
  1510. if (_types.TryGetValue(value, out result))
  1511. {
  1512. return result;
  1513. }
  1514. return new[] { value };
  1515. }
  1516. public async Task DeleteItem(Guid id, CancellationToken cancellationToken)
  1517. {
  1518. if (id == Guid.Empty)
  1519. {
  1520. throw new ArgumentNullException("id");
  1521. }
  1522. CheckDisposed();
  1523. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  1524. IDbTransaction transaction = null;
  1525. try
  1526. {
  1527. transaction = _connection.BeginTransaction();
  1528. // First delete children
  1529. _deleteChildrenCommand.GetParameter(0).Value = id;
  1530. _deleteChildrenCommand.Transaction = transaction;
  1531. _deleteChildrenCommand.ExecuteNonQuery();
  1532. // Delete people
  1533. _deletePeopleCommand.GetParameter(0).Value = id;
  1534. _deletePeopleCommand.Transaction = transaction;
  1535. _deletePeopleCommand.ExecuteNonQuery();
  1536. // Delete chapters
  1537. _deleteChaptersCommand.GetParameter(0).Value = id;
  1538. _deleteChaptersCommand.Transaction = transaction;
  1539. _deleteChaptersCommand.ExecuteNonQuery();
  1540. // Delete media streams
  1541. _deleteStreamsCommand.GetParameter(0).Value = id;
  1542. _deleteStreamsCommand.Transaction = transaction;
  1543. _deleteStreamsCommand.ExecuteNonQuery();
  1544. // Delete the item
  1545. _deleteItemCommand.GetParameter(0).Value = id;
  1546. _deleteItemCommand.Transaction = transaction;
  1547. _deleteItemCommand.ExecuteNonQuery();
  1548. transaction.Commit();
  1549. }
  1550. catch (OperationCanceledException)
  1551. {
  1552. if (transaction != null)
  1553. {
  1554. transaction.Rollback();
  1555. }
  1556. throw;
  1557. }
  1558. catch (Exception e)
  1559. {
  1560. _logger.ErrorException("Failed to save children:", e);
  1561. if (transaction != null)
  1562. {
  1563. transaction.Rollback();
  1564. }
  1565. throw;
  1566. }
  1567. finally
  1568. {
  1569. if (transaction != null)
  1570. {
  1571. transaction.Dispose();
  1572. }
  1573. _writeLock.Release();
  1574. }
  1575. }
  1576. public async Task SaveChildren(Guid parentId, IEnumerable<Guid> children, CancellationToken cancellationToken)
  1577. {
  1578. if (parentId == Guid.Empty)
  1579. {
  1580. throw new ArgumentNullException("parentId");
  1581. }
  1582. if (children == null)
  1583. {
  1584. throw new ArgumentNullException("children");
  1585. }
  1586. CheckDisposed();
  1587. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  1588. IDbTransaction transaction = null;
  1589. try
  1590. {
  1591. transaction = _connection.BeginTransaction();
  1592. // First delete
  1593. _deleteChildrenCommand.GetParameter(0).Value = parentId;
  1594. _deleteChildrenCommand.Transaction = transaction;
  1595. _deleteChildrenCommand.ExecuteNonQuery();
  1596. foreach (var id in children)
  1597. {
  1598. cancellationToken.ThrowIfCancellationRequested();
  1599. _saveChildrenCommand.GetParameter(0).Value = parentId;
  1600. _saveChildrenCommand.GetParameter(1).Value = id;
  1601. _saveChildrenCommand.Transaction = transaction;
  1602. _saveChildrenCommand.ExecuteNonQuery();
  1603. }
  1604. transaction.Commit();
  1605. }
  1606. catch (OperationCanceledException)
  1607. {
  1608. if (transaction != null)
  1609. {
  1610. transaction.Rollback();
  1611. }
  1612. throw;
  1613. }
  1614. catch (Exception e)
  1615. {
  1616. _logger.ErrorException("Failed to save children:", e);
  1617. if (transaction != null)
  1618. {
  1619. transaction.Rollback();
  1620. }
  1621. throw;
  1622. }
  1623. finally
  1624. {
  1625. if (transaction != null)
  1626. {
  1627. transaction.Dispose();
  1628. }
  1629. _writeLock.Release();
  1630. }
  1631. }
  1632. public List<string> GetPeopleNames(InternalPeopleQuery query)
  1633. {
  1634. if (query == null)
  1635. {
  1636. throw new ArgumentNullException("query");
  1637. }
  1638. CheckDisposed();
  1639. using (var cmd = _connection.CreateCommand())
  1640. {
  1641. cmd.CommandText = "select Distinct Name from People";
  1642. var whereClauses = GetPeopleWhereClauses(query, cmd);
  1643. if (whereClauses.Count > 0)
  1644. {
  1645. cmd.CommandText += " where " + string.Join(" AND ", whereClauses.ToArray());
  1646. }
  1647. cmd.CommandText += " order by ListOrder";
  1648. var list = new List<string>();
  1649. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  1650. {
  1651. while (reader.Read())
  1652. {
  1653. list.Add(reader.GetString(0));
  1654. }
  1655. }
  1656. return list;
  1657. }
  1658. }
  1659. public List<PersonInfo> GetPeople(InternalPeopleQuery query)
  1660. {
  1661. if (query == null)
  1662. {
  1663. throw new ArgumentNullException("query");
  1664. }
  1665. CheckDisposed();
  1666. using (var cmd = _connection.CreateCommand())
  1667. {
  1668. cmd.CommandText = "select ItemId, Name, Role, PersonType, SortOrder from People";
  1669. var whereClauses = GetPeopleWhereClauses(query, cmd);
  1670. if (whereClauses.Count > 0)
  1671. {
  1672. cmd.CommandText += " where " + string.Join(" AND ", whereClauses.ToArray());
  1673. }
  1674. cmd.CommandText += " order by ListOrder";
  1675. var list = new List<PersonInfo>();
  1676. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  1677. {
  1678. while (reader.Read())
  1679. {
  1680. list.Add(GetPerson(reader));
  1681. }
  1682. }
  1683. return list;
  1684. }
  1685. }
  1686. private List<string> GetPeopleWhereClauses(InternalPeopleQuery query, IDbCommand cmd)
  1687. {
  1688. var whereClauses = new List<string>();
  1689. if (query.ItemId != Guid.Empty)
  1690. {
  1691. whereClauses.Add("ItemId=@ItemId");
  1692. cmd.Parameters.Add(cmd, "@ItemId", DbType.Guid).Value = query.ItemId;
  1693. }
  1694. if (query.AppearsInItemId != Guid.Empty)
  1695. {
  1696. whereClauses.Add("Name in (Select Name from People where ItemId=@AppearsInItemId)");
  1697. cmd.Parameters.Add(cmd, "@AppearsInItemId", DbType.Guid).Value = query.AppearsInItemId;
  1698. }
  1699. if (query.PersonTypes.Count == 1)
  1700. {
  1701. whereClauses.Add("PersonType=@PersonType");
  1702. cmd.Parameters.Add(cmd, "@PersonType", DbType.String).Value = query.PersonTypes[0];
  1703. }
  1704. if (query.PersonTypes.Count > 1)
  1705. {
  1706. var val = string.Join(",", query.PersonTypes.Select(i => "'" + i + "'").ToArray());
  1707. whereClauses.Add("PersonType in (" + val + ")");
  1708. }
  1709. if (query.ExcludePersonTypes.Count == 1)
  1710. {
  1711. whereClauses.Add("PersonType<>@PersonType");
  1712. cmd.Parameters.Add(cmd, "@PersonType", DbType.String).Value = query.ExcludePersonTypes[0];
  1713. }
  1714. if (query.ExcludePersonTypes.Count > 1)
  1715. {
  1716. var val = string.Join(",", query.ExcludePersonTypes.Select(i => "'" + i + "'").ToArray());
  1717. whereClauses.Add("PersonType not in (" + val + ")");
  1718. }
  1719. if (query.MaxListOrder.HasValue)
  1720. {
  1721. whereClauses.Add("ListOrder<=@MaxListOrder");
  1722. cmd.Parameters.Add(cmd, "@MaxListOrder", DbType.Int32).Value = query.MaxListOrder.Value;
  1723. }
  1724. if (!string.IsNullOrWhiteSpace(query.NameContains))
  1725. {
  1726. whereClauses.Add("Name like @NameContains");
  1727. cmd.Parameters.Add(cmd, "@NameContains", DbType.String).Value = "%" + query.NameContains + "%";
  1728. }
  1729. return whereClauses;
  1730. }
  1731. public async Task UpdatePeople(Guid itemId, List<PersonInfo> people)
  1732. {
  1733. if (itemId == Guid.Empty)
  1734. {
  1735. throw new ArgumentNullException("itemId");
  1736. }
  1737. if (people == null)
  1738. {
  1739. throw new ArgumentNullException("people");
  1740. }
  1741. CheckDisposed();
  1742. var cancellationToken = CancellationToken.None;
  1743. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  1744. IDbTransaction transaction = null;
  1745. try
  1746. {
  1747. transaction = _connection.BeginTransaction();
  1748. // First delete
  1749. _deletePeopleCommand.GetParameter(0).Value = itemId;
  1750. _deletePeopleCommand.Transaction = transaction;
  1751. _deletePeopleCommand.ExecuteNonQuery();
  1752. var listIndex = 0;
  1753. foreach (var person in people)
  1754. {
  1755. cancellationToken.ThrowIfCancellationRequested();
  1756. _savePersonCommand.GetParameter(0).Value = itemId;
  1757. _savePersonCommand.GetParameter(1).Value = person.Name;
  1758. _savePersonCommand.GetParameter(2).Value = person.Role;
  1759. _savePersonCommand.GetParameter(3).Value = person.Type;
  1760. _savePersonCommand.GetParameter(4).Value = person.SortOrder;
  1761. _savePersonCommand.GetParameter(5).Value = listIndex;
  1762. _savePersonCommand.Transaction = transaction;
  1763. _savePersonCommand.ExecuteNonQuery();
  1764. listIndex++;
  1765. }
  1766. transaction.Commit();
  1767. }
  1768. catch (OperationCanceledException)
  1769. {
  1770. if (transaction != null)
  1771. {
  1772. transaction.Rollback();
  1773. }
  1774. throw;
  1775. }
  1776. catch (Exception e)
  1777. {
  1778. _logger.ErrorException("Failed to save people:", e);
  1779. if (transaction != null)
  1780. {
  1781. transaction.Rollback();
  1782. }
  1783. throw;
  1784. }
  1785. finally
  1786. {
  1787. if (transaction != null)
  1788. {
  1789. transaction.Dispose();
  1790. }
  1791. _writeLock.Release();
  1792. }
  1793. }
  1794. private PersonInfo GetPerson(IDataReader reader)
  1795. {
  1796. var item = new PersonInfo();
  1797. item.ItemId = reader.GetGuid(0);
  1798. item.Name = reader.GetString(1);
  1799. if (!reader.IsDBNull(2))
  1800. {
  1801. item.Role = reader.GetString(2);
  1802. }
  1803. if (!reader.IsDBNull(3))
  1804. {
  1805. item.Type = reader.GetString(3);
  1806. }
  1807. if (!reader.IsDBNull(4))
  1808. {
  1809. item.SortOrder = reader.GetInt32(4);
  1810. }
  1811. return item;
  1812. }
  1813. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  1814. {
  1815. CheckDisposed();
  1816. if (query == null)
  1817. {
  1818. throw new ArgumentNullException("query");
  1819. }
  1820. using (var cmd = _connection.CreateCommand())
  1821. {
  1822. var cmdText = "select " + string.Join(",", _mediaStreamSaveColumns) + " from mediastreams where";
  1823. cmdText += " ItemId=@ItemId";
  1824. cmd.Parameters.Add(cmd, "@ItemId", DbType.Guid).Value = query.ItemId;
  1825. if (query.Type.HasValue)
  1826. {
  1827. cmdText += " AND StreamType=@StreamType";
  1828. cmd.Parameters.Add(cmd, "@StreamType", DbType.String).Value = query.Type.Value.ToString();
  1829. }
  1830. if (query.Index.HasValue)
  1831. {
  1832. cmdText += " AND StreamIndex=@StreamIndex";
  1833. cmd.Parameters.Add(cmd, "@StreamIndex", DbType.Int32).Value = query.Index.Value;
  1834. }
  1835. cmdText += " order by StreamIndex ASC";
  1836. cmd.CommandText = cmdText;
  1837. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  1838. {
  1839. while (reader.Read())
  1840. {
  1841. yield return GetMediaStream(reader);
  1842. }
  1843. }
  1844. }
  1845. }
  1846. public async Task SaveMediaStreams(Guid id, IEnumerable<MediaStream> streams, CancellationToken cancellationToken)
  1847. {
  1848. CheckDisposed();
  1849. if (id == Guid.Empty)
  1850. {
  1851. throw new ArgumentNullException("id");
  1852. }
  1853. if (streams == null)
  1854. {
  1855. throw new ArgumentNullException("streams");
  1856. }
  1857. cancellationToken.ThrowIfCancellationRequested();
  1858. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  1859. IDbTransaction transaction = null;
  1860. try
  1861. {
  1862. transaction = _connection.BeginTransaction();
  1863. // First delete chapters
  1864. _deleteStreamsCommand.GetParameter(0).Value = id;
  1865. _deleteStreamsCommand.Transaction = transaction;
  1866. _deleteStreamsCommand.ExecuteNonQuery();
  1867. foreach (var stream in streams)
  1868. {
  1869. cancellationToken.ThrowIfCancellationRequested();
  1870. var index = 0;
  1871. _saveStreamCommand.GetParameter(index++).Value = id;
  1872. _saveStreamCommand.GetParameter(index++).Value = stream.Index;
  1873. _saveStreamCommand.GetParameter(index++).Value = stream.Type.ToString();
  1874. _saveStreamCommand.GetParameter(index++).Value = stream.Codec;
  1875. _saveStreamCommand.GetParameter(index++).Value = stream.Language;
  1876. _saveStreamCommand.GetParameter(index++).Value = stream.ChannelLayout;
  1877. _saveStreamCommand.GetParameter(index++).Value = stream.Profile;
  1878. _saveStreamCommand.GetParameter(index++).Value = stream.AspectRatio;
  1879. _saveStreamCommand.GetParameter(index++).Value = stream.Path;
  1880. _saveStreamCommand.GetParameter(index++).Value = stream.IsInterlaced;
  1881. _saveStreamCommand.GetParameter(index++).Value = stream.BitRate;
  1882. _saveStreamCommand.GetParameter(index++).Value = stream.Channels;
  1883. _saveStreamCommand.GetParameter(index++).Value = stream.SampleRate;
  1884. _saveStreamCommand.GetParameter(index++).Value = stream.IsDefault;
  1885. _saveStreamCommand.GetParameter(index++).Value = stream.IsForced;
  1886. _saveStreamCommand.GetParameter(index++).Value = stream.IsExternal;
  1887. _saveStreamCommand.GetParameter(index++).Value = stream.Width;
  1888. _saveStreamCommand.GetParameter(index++).Value = stream.Height;
  1889. _saveStreamCommand.GetParameter(index++).Value = stream.AverageFrameRate;
  1890. _saveStreamCommand.GetParameter(index++).Value = stream.RealFrameRate;
  1891. _saveStreamCommand.GetParameter(index++).Value = stream.Level;
  1892. _saveStreamCommand.GetParameter(index++).Value = stream.PixelFormat;
  1893. _saveStreamCommand.GetParameter(index++).Value = stream.BitDepth;
  1894. _saveStreamCommand.GetParameter(index++).Value = stream.IsAnamorphic;
  1895. _saveStreamCommand.GetParameter(index++).Value = stream.RefFrames;
  1896. _saveStreamCommand.GetParameter(index++).Value = stream.IsCabac;
  1897. if (stream.KeyFrames == null || stream.KeyFrames.Count == 0)
  1898. {
  1899. _saveStreamCommand.GetParameter(index++).Value = null;
  1900. }
  1901. else
  1902. {
  1903. _saveStreamCommand.GetParameter(index++).Value = string.Join(",", stream.KeyFrames.Select(i => i.ToString(CultureInfo.InvariantCulture)).ToArray());
  1904. }
  1905. _saveStreamCommand.GetParameter(index++).Value = stream.CodecTag;
  1906. _saveStreamCommand.Transaction = transaction;
  1907. _saveStreamCommand.ExecuteNonQuery();
  1908. }
  1909. transaction.Commit();
  1910. }
  1911. catch (OperationCanceledException)
  1912. {
  1913. if (transaction != null)
  1914. {
  1915. transaction.Rollback();
  1916. }
  1917. throw;
  1918. }
  1919. catch (Exception e)
  1920. {
  1921. _logger.ErrorException("Failed to save media streams:", e);
  1922. if (transaction != null)
  1923. {
  1924. transaction.Rollback();
  1925. }
  1926. throw;
  1927. }
  1928. finally
  1929. {
  1930. if (transaction != null)
  1931. {
  1932. transaction.Dispose();
  1933. }
  1934. _writeLock.Release();
  1935. }
  1936. }
  1937. /// <summary>
  1938. /// Gets the chapter.
  1939. /// </summary>
  1940. /// <param name="reader">The reader.</param>
  1941. /// <returns>ChapterInfo.</returns>
  1942. private MediaStream GetMediaStream(IDataReader reader)
  1943. {
  1944. var item = new MediaStream
  1945. {
  1946. Index = reader.GetInt32(1)
  1947. };
  1948. item.Type = (MediaStreamType)Enum.Parse(typeof(MediaStreamType), reader.GetString(2), true);
  1949. if (!reader.IsDBNull(3))
  1950. {
  1951. item.Codec = reader.GetString(3);
  1952. }
  1953. if (!reader.IsDBNull(4))
  1954. {
  1955. item.Language = reader.GetString(4);
  1956. }
  1957. if (!reader.IsDBNull(5))
  1958. {
  1959. item.ChannelLayout = reader.GetString(5);
  1960. }
  1961. if (!reader.IsDBNull(6))
  1962. {
  1963. item.Profile = reader.GetString(6);
  1964. }
  1965. if (!reader.IsDBNull(7))
  1966. {
  1967. item.AspectRatio = reader.GetString(7);
  1968. }
  1969. if (!reader.IsDBNull(8))
  1970. {
  1971. item.Path = reader.GetString(8);
  1972. }
  1973. item.IsInterlaced = reader.GetBoolean(9);
  1974. if (!reader.IsDBNull(10))
  1975. {
  1976. item.BitRate = reader.GetInt32(10);
  1977. }
  1978. if (!reader.IsDBNull(11))
  1979. {
  1980. item.Channels = reader.GetInt32(11);
  1981. }
  1982. if (!reader.IsDBNull(12))
  1983. {
  1984. item.SampleRate = reader.GetInt32(12);
  1985. }
  1986. item.IsDefault = reader.GetBoolean(13);
  1987. item.IsForced = reader.GetBoolean(14);
  1988. item.IsExternal = reader.GetBoolean(15);
  1989. if (!reader.IsDBNull(16))
  1990. {
  1991. item.Width = reader.GetInt32(16);
  1992. }
  1993. if (!reader.IsDBNull(17))
  1994. {
  1995. item.Height = reader.GetInt32(17);
  1996. }
  1997. if (!reader.IsDBNull(18))
  1998. {
  1999. item.AverageFrameRate = reader.GetFloat(18);
  2000. }
  2001. if (!reader.IsDBNull(19))
  2002. {
  2003. item.RealFrameRate = reader.GetFloat(19);
  2004. }
  2005. if (!reader.IsDBNull(20))
  2006. {
  2007. item.Level = reader.GetFloat(20);
  2008. }
  2009. if (!reader.IsDBNull(21))
  2010. {
  2011. item.PixelFormat = reader.GetString(21);
  2012. }
  2013. if (!reader.IsDBNull(22))
  2014. {
  2015. item.BitDepth = reader.GetInt32(22);
  2016. }
  2017. if (!reader.IsDBNull(23))
  2018. {
  2019. item.IsAnamorphic = reader.GetBoolean(23);
  2020. }
  2021. if (!reader.IsDBNull(24))
  2022. {
  2023. item.RefFrames = reader.GetInt32(24);
  2024. }
  2025. if (!reader.IsDBNull(25))
  2026. {
  2027. item.IsCabac = reader.GetBoolean(25);
  2028. }
  2029. if (!reader.IsDBNull(26))
  2030. {
  2031. var frames = reader.GetString(26);
  2032. if (!string.IsNullOrWhiteSpace(frames))
  2033. {
  2034. item.KeyFrames = frames.Split(',').Select(i => int.Parse(i, CultureInfo.InvariantCulture)).ToList();
  2035. }
  2036. }
  2037. if (!reader.IsDBNull(27))
  2038. {
  2039. item.CodecTag = reader.GetString(27);
  2040. }
  2041. return item;
  2042. }
  2043. }
  2044. }