SqliteItemRepository.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Persistence;
  4. using MediaBrowser.Controller.Providers;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Data;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. namespace MediaBrowser.Server.Implementations.Persistence
  16. {
  17. /// <summary>
  18. /// Class SQLiteItemRepository
  19. /// </summary>
  20. public class SqliteItemRepository : IItemRepository
  21. {
  22. private IDbConnection _connection;
  23. private readonly ILogger _logger;
  24. private readonly TypeMapper _typeMapper = new TypeMapper();
  25. /// <summary>
  26. /// Gets the name of the repository
  27. /// </summary>
  28. /// <value>The name.</value>
  29. public string Name
  30. {
  31. get
  32. {
  33. return "SQLite";
  34. }
  35. }
  36. /// <summary>
  37. /// Gets the json serializer.
  38. /// </summary>
  39. /// <value>The json serializer.</value>
  40. private readonly IJsonSerializer _jsonSerializer;
  41. /// <summary>
  42. /// The _app paths
  43. /// </summary>
  44. private readonly IApplicationPaths _appPaths;
  45. /// <summary>
  46. /// The _save item command
  47. /// </summary>
  48. private IDbCommand _saveItemCommand;
  49. private readonly string _criticReviewsPath;
  50. private SqliteChapterRepository _chapterRepository;
  51. private SqliteMediaStreamsRepository _mediaStreamsRepository;
  52. private SqliteProviderInfoRepository _providerInfoRepository;
  53. private IDbCommand _deleteChildrenCommand;
  54. private IDbCommand _saveChildrenCommand;
  55. /// <summary>
  56. /// Initializes a new instance of the <see cref="SqliteItemRepository"/> class.
  57. /// </summary>
  58. /// <param name="appPaths">The app paths.</param>
  59. /// <param name="jsonSerializer">The json serializer.</param>
  60. /// <param name="logManager">The log manager.</param>
  61. /// <exception cref="System.ArgumentNullException">
  62. /// appPaths
  63. /// or
  64. /// jsonSerializer
  65. /// </exception>
  66. public SqliteItemRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  67. {
  68. if (appPaths == null)
  69. {
  70. throw new ArgumentNullException("appPaths");
  71. }
  72. if (jsonSerializer == null)
  73. {
  74. throw new ArgumentNullException("jsonSerializer");
  75. }
  76. _appPaths = appPaths;
  77. _jsonSerializer = jsonSerializer;
  78. _criticReviewsPath = Path.Combine(_appPaths.DataPath, "critic-reviews");
  79. _logger = logManager.GetLogger(GetType().Name);
  80. var chapterDbFile = Path.Combine(_appPaths.DataPath, "chapters.db");
  81. var chapterConnection = SqliteExtensions.ConnectToDb(chapterDbFile, _logger).Result;
  82. _chapterRepository = new SqliteChapterRepository(chapterConnection, logManager);
  83. var mediaStreamsDbFile = Path.Combine(_appPaths.DataPath, "mediainfo.db");
  84. var mediaStreamsConnection = SqliteExtensions.ConnectToDb(mediaStreamsDbFile, _logger).Result;
  85. _mediaStreamsRepository = new SqliteMediaStreamsRepository(mediaStreamsConnection, logManager);
  86. var providerInfosDbFile = Path.Combine(_appPaths.DataPath, "providerinfo.db");
  87. var providerInfoConnection = SqliteExtensions.ConnectToDb(providerInfosDbFile, _logger).Result;
  88. _providerInfoRepository = new SqliteProviderInfoRepository(providerInfoConnection, logManager);
  89. }
  90. /// <summary>
  91. /// Opens the connection to the database
  92. /// </summary>
  93. /// <returns>Task.</returns>
  94. public async Task Initialize()
  95. {
  96. var dbFile = Path.Combine(_appPaths.DataPath, "library.db");
  97. _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false);
  98. string[] queries = {
  99. "create table if not exists TypedBaseItems (guid GUID primary key, type TEXT, data BLOB)",
  100. "create index if not exists idx_TypedBaseItems on TypedBaseItems(guid)",
  101. "create table if not exists ChildrenIds (ParentId GUID, ItemId GUID, PRIMARY KEY (ParentId, ItemId))",
  102. "create index if not exists idx_ChildrenIds on ChildrenIds(ParentId,ItemId)",
  103. //pragmas
  104. "pragma temp_store = memory"
  105. };
  106. _connection.RunQueries(queries, _logger);
  107. PrepareStatements();
  108. _mediaStreamsRepository.Initialize();
  109. _providerInfoRepository.Initialize();
  110. _chapterRepository.Initialize();
  111. }
  112. /// <summary>
  113. /// The _write lock
  114. /// </summary>
  115. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  116. /// <summary>
  117. /// Prepares the statements.
  118. /// </summary>
  119. private void PrepareStatements()
  120. {
  121. _saveItemCommand = _connection.CreateCommand();
  122. _saveItemCommand.CommandText = "replace into TypedBaseItems (guid, type, data) values (@1, @2, @3)";
  123. _saveItemCommand.Parameters.Add(_saveItemCommand, "@1");
  124. _saveItemCommand.Parameters.Add(_saveItemCommand, "@2");
  125. _saveItemCommand.Parameters.Add(_saveItemCommand, "@3");
  126. _deleteChildrenCommand = _connection.CreateCommand();
  127. _deleteChildrenCommand.CommandText = "delete from ChildrenIds where ParentId=@ParentId";
  128. _deleteChildrenCommand.Parameters.Add(_deleteChildrenCommand, "@ParentId");
  129. _saveChildrenCommand = _connection.CreateCommand();
  130. _saveChildrenCommand.CommandText = "replace into ChildrenIds (ParentId, ItemId) values (@ParentId, @ItemId)";
  131. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ParentId");
  132. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ItemId");
  133. }
  134. /// <summary>
  135. /// Save a standard item in the repo
  136. /// </summary>
  137. /// <param name="item">The item.</param>
  138. /// <param name="cancellationToken">The cancellation token.</param>
  139. /// <returns>Task.</returns>
  140. /// <exception cref="System.ArgumentNullException">item</exception>
  141. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  142. {
  143. if (item == null)
  144. {
  145. throw new ArgumentNullException("item");
  146. }
  147. return SaveItems(new[] { item }, cancellationToken);
  148. }
  149. /// <summary>
  150. /// Saves the items.
  151. /// </summary>
  152. /// <param name="items">The items.</param>
  153. /// <param name="cancellationToken">The cancellation token.</param>
  154. /// <returns>Task.</returns>
  155. /// <exception cref="System.ArgumentNullException">
  156. /// items
  157. /// or
  158. /// cancellationToken
  159. /// </exception>
  160. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  161. {
  162. if (items == null)
  163. {
  164. throw new ArgumentNullException("items");
  165. }
  166. cancellationToken.ThrowIfCancellationRequested();
  167. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  168. IDbTransaction transaction = null;
  169. try
  170. {
  171. transaction = _connection.BeginTransaction();
  172. foreach (var item in items)
  173. {
  174. cancellationToken.ThrowIfCancellationRequested();
  175. _saveItemCommand.GetParameter(0).Value = item.Id;
  176. _saveItemCommand.GetParameter(1).Value = item.GetType().FullName;
  177. _saveItemCommand.GetParameter(2).Value = _jsonSerializer.SerializeToBytes(item);
  178. _saveItemCommand.Transaction = transaction;
  179. _saveItemCommand.ExecuteNonQuery();
  180. }
  181. transaction.Commit();
  182. }
  183. catch (OperationCanceledException)
  184. {
  185. if (transaction != null)
  186. {
  187. transaction.Rollback();
  188. }
  189. throw;
  190. }
  191. catch (Exception e)
  192. {
  193. _logger.ErrorException("Failed to save items:", e);
  194. if (transaction != null)
  195. {
  196. transaction.Rollback();
  197. }
  198. throw;
  199. }
  200. finally
  201. {
  202. if (transaction != null)
  203. {
  204. transaction.Dispose();
  205. }
  206. _writeLock.Release();
  207. }
  208. }
  209. /// <summary>
  210. /// Internal retrieve from items or users table
  211. /// </summary>
  212. /// <param name="id">The id.</param>
  213. /// <returns>BaseItem.</returns>
  214. /// <exception cref="System.ArgumentNullException">id</exception>
  215. /// <exception cref="System.ArgumentException"></exception>
  216. public BaseItem RetrieveItem(Guid id)
  217. {
  218. if (id == Guid.Empty)
  219. {
  220. throw new ArgumentNullException("id");
  221. }
  222. using (var cmd = _connection.CreateCommand())
  223. {
  224. cmd.CommandText = "select type,data from TypedBaseItems where guid = @guid";
  225. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = id;
  226. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  227. {
  228. if (reader.Read())
  229. {
  230. var typeString = reader.GetString(0);
  231. var type = _typeMapper.GetType(typeString);
  232. if (type == null)
  233. {
  234. _logger.Debug("Unknown type {0}", typeString);
  235. return null;
  236. }
  237. using (var stream = reader.GetMemoryStream(1))
  238. {
  239. return _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
  240. }
  241. }
  242. }
  243. return null;
  244. }
  245. }
  246. /// <summary>
  247. /// Gets the critic reviews.
  248. /// </summary>
  249. /// <param name="itemId">The item id.</param>
  250. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  251. public IEnumerable<ItemReview> GetCriticReviews(Guid itemId)
  252. {
  253. try
  254. {
  255. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  256. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  257. }
  258. catch (DirectoryNotFoundException)
  259. {
  260. return new List<ItemReview>();
  261. }
  262. catch (FileNotFoundException)
  263. {
  264. return new List<ItemReview>();
  265. }
  266. }
  267. /// <summary>
  268. /// Saves the critic reviews.
  269. /// </summary>
  270. /// <param name="itemId">The item id.</param>
  271. /// <param name="criticReviews">The critic reviews.</param>
  272. /// <returns>Task.</returns>
  273. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  274. {
  275. Directory.CreateDirectory(_criticReviewsPath);
  276. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  277. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  278. return Task.FromResult(true);
  279. }
  280. /// <summary>
  281. /// Gets chapters for an item
  282. /// </summary>
  283. /// <param name="id">The id.</param>
  284. /// <returns>IEnumerable{ChapterInfo}.</returns>
  285. /// <exception cref="System.ArgumentNullException">id</exception>
  286. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  287. {
  288. return _chapterRepository.GetChapters(id);
  289. }
  290. /// <summary>
  291. /// Gets a single chapter for an item
  292. /// </summary>
  293. /// <param name="id">The id.</param>
  294. /// <param name="index">The index.</param>
  295. /// <returns>ChapterInfo.</returns>
  296. /// <exception cref="System.ArgumentNullException">id</exception>
  297. public ChapterInfo GetChapter(Guid id, int index)
  298. {
  299. return _chapterRepository.GetChapter(id, index);
  300. }
  301. /// <summary>
  302. /// Saves the chapters.
  303. /// </summary>
  304. /// <param name="id">The id.</param>
  305. /// <param name="chapters">The chapters.</param>
  306. /// <param name="cancellationToken">The cancellation token.</param>
  307. /// <returns>Task.</returns>
  308. /// <exception cref="System.ArgumentNullException">
  309. /// id
  310. /// or
  311. /// chapters
  312. /// or
  313. /// cancellationToken
  314. /// </exception>
  315. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  316. {
  317. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  318. }
  319. /// <summary>
  320. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  321. /// </summary>
  322. public void Dispose()
  323. {
  324. Dispose(true);
  325. GC.SuppressFinalize(this);
  326. }
  327. private readonly object _disposeLock = new object();
  328. /// <summary>
  329. /// Releases unmanaged and - optionally - managed resources.
  330. /// </summary>
  331. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  332. protected virtual void Dispose(bool dispose)
  333. {
  334. if (dispose)
  335. {
  336. try
  337. {
  338. lock (_disposeLock)
  339. {
  340. if (_connection != null)
  341. {
  342. if (_connection.IsOpen())
  343. {
  344. _connection.Close();
  345. }
  346. _connection.Dispose();
  347. _connection = null;
  348. }
  349. }
  350. }
  351. catch (Exception ex)
  352. {
  353. _logger.ErrorException("Error disposing database", ex);
  354. }
  355. if (_chapterRepository != null)
  356. {
  357. _chapterRepository.Dispose();
  358. _chapterRepository = null;
  359. }
  360. if (_mediaStreamsRepository != null)
  361. {
  362. _mediaStreamsRepository.Dispose();
  363. _mediaStreamsRepository = null;
  364. }
  365. if (_providerInfoRepository != null)
  366. {
  367. _providerInfoRepository.Dispose();
  368. _providerInfoRepository = null;
  369. }
  370. }
  371. }
  372. public IEnumerable<Guid> GetChildren(Guid parentId)
  373. {
  374. if (parentId == Guid.Empty)
  375. {
  376. throw new ArgumentNullException("parentId");
  377. }
  378. using (var cmd = _connection.CreateCommand())
  379. {
  380. cmd.CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId";
  381. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  382. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  383. {
  384. while (reader.Read())
  385. {
  386. yield return reader.GetGuid(0);
  387. }
  388. }
  389. }
  390. }
  391. public async Task SaveChildren(Guid parentId, IEnumerable<Guid> children, CancellationToken cancellationToken)
  392. {
  393. if (parentId == Guid.Empty)
  394. {
  395. throw new ArgumentNullException("parentId");
  396. }
  397. if (children == null)
  398. {
  399. throw new ArgumentNullException("children");
  400. }
  401. cancellationToken.ThrowIfCancellationRequested();
  402. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  403. IDbTransaction transaction = null;
  404. try
  405. {
  406. transaction = _connection.BeginTransaction();
  407. // First delete
  408. _deleteChildrenCommand.GetParameter(0).Value = parentId;
  409. _deleteChildrenCommand.Transaction = transaction;
  410. _deleteChildrenCommand.ExecuteNonQuery();
  411. foreach (var id in children)
  412. {
  413. cancellationToken.ThrowIfCancellationRequested();
  414. _saveChildrenCommand.GetParameter(0).Value = parentId;
  415. _saveChildrenCommand.GetParameter(1).Value = id;
  416. _saveChildrenCommand.Transaction = transaction;
  417. _saveChildrenCommand.ExecuteNonQuery();
  418. }
  419. transaction.Commit();
  420. }
  421. catch (OperationCanceledException)
  422. {
  423. if (transaction != null)
  424. {
  425. transaction.Rollback();
  426. }
  427. throw;
  428. }
  429. catch (Exception e)
  430. {
  431. _logger.ErrorException("Failed to save children:", e);
  432. if (transaction != null)
  433. {
  434. transaction.Rollback();
  435. }
  436. throw;
  437. }
  438. finally
  439. {
  440. if (transaction != null)
  441. {
  442. transaction.Dispose();
  443. }
  444. _writeLock.Release();
  445. }
  446. }
  447. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  448. {
  449. return _mediaStreamsRepository.GetMediaStreams(query);
  450. }
  451. public Task SaveMediaStreams(Guid id, IEnumerable<MediaStream> streams, CancellationToken cancellationToken)
  452. {
  453. return _mediaStreamsRepository.SaveMediaStreams(id, streams, cancellationToken);
  454. }
  455. public IEnumerable<BaseProviderInfo> GetProviderHistory(Guid itemId)
  456. {
  457. return _providerInfoRepository.GetBaseProviderInfos(itemId);
  458. }
  459. public Task SaveProviderHistory(Guid id, IEnumerable<BaseProviderInfo> history, CancellationToken cancellationToken)
  460. {
  461. return _providerInfoRepository.SaveProviderInfos(id, history, cancellationToken);
  462. }
  463. }
  464. }