SqliteItemRepository.cs 83 KB

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