SqliteItemRepository.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  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. "pragma shrink_memory"
  106. };
  107. _connection.RunQueries(queries, _logger);
  108. PrepareStatements();
  109. _mediaStreamsRepository.Initialize();
  110. _providerInfoRepository.Initialize();
  111. _chapterRepository.Initialize();
  112. _shrinkMemoryTimer = new SqliteShrinkMemoryTimer(_connection, _writeLock, _logger);
  113. }
  114. private SqliteShrinkMemoryTimer _shrinkMemoryTimer;
  115. /// <summary>
  116. /// The _write lock
  117. /// </summary>
  118. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  119. /// <summary>
  120. /// Prepares the statements.
  121. /// </summary>
  122. private void PrepareStatements()
  123. {
  124. _saveItemCommand = _connection.CreateCommand();
  125. _saveItemCommand.CommandText = "replace into TypedBaseItems (guid, type, data) values (@1, @2, @3)";
  126. _saveItemCommand.Parameters.Add(_saveItemCommand, "@1");
  127. _saveItemCommand.Parameters.Add(_saveItemCommand, "@2");
  128. _saveItemCommand.Parameters.Add(_saveItemCommand, "@3");
  129. _deleteChildrenCommand = _connection.CreateCommand();
  130. _deleteChildrenCommand.CommandText = "delete from ChildrenIds where ParentId=@ParentId";
  131. _deleteChildrenCommand.Parameters.Add(_deleteChildrenCommand, "@ParentId");
  132. _saveChildrenCommand = _connection.CreateCommand();
  133. _saveChildrenCommand.CommandText = "replace into ChildrenIds (ParentId, ItemId) values (@ParentId, @ItemId)";
  134. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ParentId");
  135. _saveChildrenCommand.Parameters.Add(_saveChildrenCommand, "@ItemId");
  136. }
  137. /// <summary>
  138. /// Save a standard item in the repo
  139. /// </summary>
  140. /// <param name="item">The item.</param>
  141. /// <param name="cancellationToken">The cancellation token.</param>
  142. /// <returns>Task.</returns>
  143. /// <exception cref="System.ArgumentNullException">item</exception>
  144. public Task SaveItem(BaseItem item, CancellationToken cancellationToken)
  145. {
  146. if (item == null)
  147. {
  148. throw new ArgumentNullException("item");
  149. }
  150. return SaveItems(new[] { item }, cancellationToken);
  151. }
  152. /// <summary>
  153. /// Saves the items.
  154. /// </summary>
  155. /// <param name="items">The items.</param>
  156. /// <param name="cancellationToken">The cancellation token.</param>
  157. /// <returns>Task.</returns>
  158. /// <exception cref="System.ArgumentNullException">
  159. /// items
  160. /// or
  161. /// cancellationToken
  162. /// </exception>
  163. public async Task SaveItems(IEnumerable<BaseItem> items, CancellationToken cancellationToken)
  164. {
  165. if (items == null)
  166. {
  167. throw new ArgumentNullException("items");
  168. }
  169. cancellationToken.ThrowIfCancellationRequested();
  170. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  171. IDbTransaction transaction = null;
  172. try
  173. {
  174. transaction = _connection.BeginTransaction();
  175. foreach (var item in items)
  176. {
  177. cancellationToken.ThrowIfCancellationRequested();
  178. _saveItemCommand.GetParameter(0).Value = item.Id;
  179. _saveItemCommand.GetParameter(1).Value = item.GetType().FullName;
  180. _saveItemCommand.GetParameter(2).Value = _jsonSerializer.SerializeToBytes(item);
  181. _saveItemCommand.Transaction = transaction;
  182. _saveItemCommand.ExecuteNonQuery();
  183. }
  184. transaction.Commit();
  185. }
  186. catch (OperationCanceledException)
  187. {
  188. if (transaction != null)
  189. {
  190. transaction.Rollback();
  191. }
  192. throw;
  193. }
  194. catch (Exception e)
  195. {
  196. _logger.ErrorException("Failed to save items:", e);
  197. if (transaction != null)
  198. {
  199. transaction.Rollback();
  200. }
  201. throw;
  202. }
  203. finally
  204. {
  205. if (transaction != null)
  206. {
  207. transaction.Dispose();
  208. }
  209. _writeLock.Release();
  210. }
  211. }
  212. /// <summary>
  213. /// Internal retrieve from items or users table
  214. /// </summary>
  215. /// <param name="id">The id.</param>
  216. /// <returns>BaseItem.</returns>
  217. /// <exception cref="System.ArgumentNullException">id</exception>
  218. /// <exception cref="System.ArgumentException"></exception>
  219. public BaseItem RetrieveItem(Guid id)
  220. {
  221. if (id == Guid.Empty)
  222. {
  223. throw new ArgumentNullException("id");
  224. }
  225. using (var cmd = _connection.CreateCommand())
  226. {
  227. cmd.CommandText = "select type,data from TypedBaseItems where guid = @guid";
  228. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = id;
  229. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  230. {
  231. if (reader.Read())
  232. {
  233. var typeString = reader.GetString(0);
  234. var type = _typeMapper.GetType(typeString);
  235. if (type == null)
  236. {
  237. _logger.Debug("Unknown type {0}", typeString);
  238. return null;
  239. }
  240. using (var stream = reader.GetMemoryStream(1))
  241. {
  242. return _jsonSerializer.DeserializeFromStream(stream, type) as BaseItem;
  243. }
  244. }
  245. }
  246. return null;
  247. }
  248. }
  249. /// <summary>
  250. /// Gets the critic reviews.
  251. /// </summary>
  252. /// <param name="itemId">The item id.</param>
  253. /// <returns>Task{IEnumerable{ItemReview}}.</returns>
  254. public IEnumerable<ItemReview> GetCriticReviews(Guid itemId)
  255. {
  256. try
  257. {
  258. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  259. return _jsonSerializer.DeserializeFromFile<List<ItemReview>>(path);
  260. }
  261. catch (DirectoryNotFoundException)
  262. {
  263. return new List<ItemReview>();
  264. }
  265. catch (FileNotFoundException)
  266. {
  267. return new List<ItemReview>();
  268. }
  269. }
  270. /// <summary>
  271. /// Saves the critic reviews.
  272. /// </summary>
  273. /// <param name="itemId">The item id.</param>
  274. /// <param name="criticReviews">The critic reviews.</param>
  275. /// <returns>Task.</returns>
  276. public Task SaveCriticReviews(Guid itemId, IEnumerable<ItemReview> criticReviews)
  277. {
  278. Directory.CreateDirectory(_criticReviewsPath);
  279. var path = Path.Combine(_criticReviewsPath, itemId + ".json");
  280. _jsonSerializer.SerializeToFile(criticReviews.ToList(), path);
  281. return Task.FromResult(true);
  282. }
  283. /// <summary>
  284. /// Gets chapters for an item
  285. /// </summary>
  286. /// <param name="id">The id.</param>
  287. /// <returns>IEnumerable{ChapterInfo}.</returns>
  288. /// <exception cref="System.ArgumentNullException">id</exception>
  289. public IEnumerable<ChapterInfo> GetChapters(Guid id)
  290. {
  291. return _chapterRepository.GetChapters(id);
  292. }
  293. /// <summary>
  294. /// Gets a single chapter for an item
  295. /// </summary>
  296. /// <param name="id">The id.</param>
  297. /// <param name="index">The index.</param>
  298. /// <returns>ChapterInfo.</returns>
  299. /// <exception cref="System.ArgumentNullException">id</exception>
  300. public ChapterInfo GetChapter(Guid id, int index)
  301. {
  302. return _chapterRepository.GetChapter(id, index);
  303. }
  304. /// <summary>
  305. /// Saves the chapters.
  306. /// </summary>
  307. /// <param name="id">The id.</param>
  308. /// <param name="chapters">The chapters.</param>
  309. /// <param name="cancellationToken">The cancellation token.</param>
  310. /// <returns>Task.</returns>
  311. /// <exception cref="System.ArgumentNullException">
  312. /// id
  313. /// or
  314. /// chapters
  315. /// or
  316. /// cancellationToken
  317. /// </exception>
  318. public Task SaveChapters(Guid id, IEnumerable<ChapterInfo> chapters, CancellationToken cancellationToken)
  319. {
  320. return _chapterRepository.SaveChapters(id, chapters, cancellationToken);
  321. }
  322. /// <summary>
  323. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  324. /// </summary>
  325. public void Dispose()
  326. {
  327. Dispose(true);
  328. GC.SuppressFinalize(this);
  329. }
  330. private readonly object _disposeLock = new object();
  331. /// <summary>
  332. /// Releases unmanaged and - optionally - managed resources.
  333. /// </summary>
  334. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  335. protected virtual void Dispose(bool dispose)
  336. {
  337. if (dispose)
  338. {
  339. try
  340. {
  341. lock (_disposeLock)
  342. {
  343. if (_shrinkMemoryTimer != null)
  344. {
  345. _shrinkMemoryTimer.Dispose();
  346. _shrinkMemoryTimer = null;
  347. }
  348. if (_connection != null)
  349. {
  350. if (_connection.IsOpen())
  351. {
  352. _connection.Close();
  353. }
  354. _connection.Dispose();
  355. _connection = null;
  356. }
  357. if (_chapterRepository != null)
  358. {
  359. _chapterRepository.Dispose();
  360. _chapterRepository = null;
  361. }
  362. if (_mediaStreamsRepository != null)
  363. {
  364. _mediaStreamsRepository.Dispose();
  365. _mediaStreamsRepository = null;
  366. }
  367. if (_providerInfoRepository != null)
  368. {
  369. _providerInfoRepository.Dispose();
  370. _providerInfoRepository = null;
  371. }
  372. }
  373. }
  374. catch (Exception ex)
  375. {
  376. _logger.ErrorException("Error disposing database", ex);
  377. }
  378. }
  379. }
  380. public IEnumerable<Guid> GetChildren(Guid parentId)
  381. {
  382. if (parentId == Guid.Empty)
  383. {
  384. throw new ArgumentNullException("parentId");
  385. }
  386. using (var cmd = _connection.CreateCommand())
  387. {
  388. cmd.CommandText = "select ItemId from ChildrenIds where ParentId = @ParentId";
  389. cmd.Parameters.Add(cmd, "@ParentId", DbType.Guid).Value = parentId;
  390. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  391. {
  392. while (reader.Read())
  393. {
  394. yield return reader.GetGuid(0);
  395. }
  396. }
  397. }
  398. }
  399. public async Task SaveChildren(Guid parentId, IEnumerable<Guid> children, CancellationToken cancellationToken)
  400. {
  401. if (parentId == Guid.Empty)
  402. {
  403. throw new ArgumentNullException("parentId");
  404. }
  405. if (children == null)
  406. {
  407. throw new ArgumentNullException("children");
  408. }
  409. cancellationToken.ThrowIfCancellationRequested();
  410. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  411. IDbTransaction transaction = null;
  412. try
  413. {
  414. transaction = _connection.BeginTransaction();
  415. // First delete
  416. _deleteChildrenCommand.GetParameter(0).Value = parentId;
  417. _deleteChildrenCommand.Transaction = transaction;
  418. _deleteChildrenCommand.ExecuteNonQuery();
  419. foreach (var id in children)
  420. {
  421. cancellationToken.ThrowIfCancellationRequested();
  422. _saveChildrenCommand.GetParameter(0).Value = parentId;
  423. _saveChildrenCommand.GetParameter(1).Value = id;
  424. _saveChildrenCommand.Transaction = transaction;
  425. _saveChildrenCommand.ExecuteNonQuery();
  426. }
  427. transaction.Commit();
  428. }
  429. catch (OperationCanceledException)
  430. {
  431. if (transaction != null)
  432. {
  433. transaction.Rollback();
  434. }
  435. throw;
  436. }
  437. catch (Exception e)
  438. {
  439. _logger.ErrorException("Failed to save children:", e);
  440. if (transaction != null)
  441. {
  442. transaction.Rollback();
  443. }
  444. throw;
  445. }
  446. finally
  447. {
  448. if (transaction != null)
  449. {
  450. transaction.Dispose();
  451. }
  452. _writeLock.Release();
  453. }
  454. }
  455. public IEnumerable<MediaStream> GetMediaStreams(MediaStreamQuery query)
  456. {
  457. return _mediaStreamsRepository.GetMediaStreams(query);
  458. }
  459. public Task SaveMediaStreams(Guid id, IEnumerable<MediaStream> streams, CancellationToken cancellationToken)
  460. {
  461. return _mediaStreamsRepository.SaveMediaStreams(id, streams, cancellationToken);
  462. }
  463. public IEnumerable<BaseProviderInfo> GetProviderHistory(Guid itemId)
  464. {
  465. return _providerInfoRepository.GetBaseProviderInfos(itemId);
  466. }
  467. public Task SaveProviderHistory(Guid id, IEnumerable<BaseProviderInfo> history, CancellationToken cancellationToken)
  468. {
  469. return _providerInfoRepository.SaveProviderInfos(id, history, cancellationToken);
  470. }
  471. }
  472. }