SQLiteDisplayPreferencesRepository.cs 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Persistence;
  3. using MediaBrowser.Model.Entities;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Data;
  8. using System.Data.SQLite;
  9. using System.IO;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Server.Implementations.Sqlite
  13. {
  14. /// <summary>
  15. /// Class SQLiteDisplayPreferencesRepository
  16. /// </summary>
  17. public class SQLiteDisplayPreferencesRepository : SqliteRepository, IDisplayPreferencesRepository
  18. {
  19. /// <summary>
  20. /// The repository name
  21. /// </summary>
  22. public const string RepositoryName = "SQLite";
  23. /// <summary>
  24. /// Gets the name of the repository
  25. /// </summary>
  26. /// <value>The name.</value>
  27. public string Name
  28. {
  29. get
  30. {
  31. return RepositoryName;
  32. }
  33. }
  34. /// <summary>
  35. /// The _json serializer
  36. /// </summary>
  37. private readonly IJsonSerializer _jsonSerializer;
  38. /// <summary>
  39. /// The _app paths
  40. /// </summary>
  41. private readonly IApplicationPaths _appPaths;
  42. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  43. /// <summary>
  44. /// Initializes a new instance of the <see cref="SQLiteUserDataRepository" /> class.
  45. /// </summary>
  46. /// <param name="appPaths">The app paths.</param>
  47. /// <param name="jsonSerializer">The json serializer.</param>
  48. /// <param name="logManager">The log manager.</param>
  49. /// <exception cref="System.ArgumentNullException">
  50. /// jsonSerializer
  51. /// or
  52. /// appPaths
  53. /// </exception>
  54. public SQLiteDisplayPreferencesRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  55. : base(logManager)
  56. {
  57. if (jsonSerializer == null)
  58. {
  59. throw new ArgumentNullException("jsonSerializer");
  60. }
  61. if (appPaths == null)
  62. {
  63. throw new ArgumentNullException("appPaths");
  64. }
  65. _jsonSerializer = jsonSerializer;
  66. _appPaths = appPaths;
  67. }
  68. /// <summary>
  69. /// Opens the connection to the database
  70. /// </summary>
  71. /// <returns>Task.</returns>
  72. public async Task Initialize()
  73. {
  74. var dbFile = Path.Combine(_appPaths.DataPath, "displaypreferences.db");
  75. await ConnectToDb(dbFile).ConfigureAwait(false);
  76. string[] queries = {
  77. "create table if not exists displaypreferences (id GUID, data BLOB)",
  78. "create unique index if not exists displaypreferencesindex on displaypreferences (id)",
  79. "create table if not exists schema_version (table_name primary key, version)",
  80. //pragmas
  81. "pragma temp_store = memory"
  82. };
  83. RunQueries(queries);
  84. }
  85. /// <summary>
  86. /// Save the display preferences associated with an item in the repo
  87. /// </summary>
  88. /// <param name="displayPreferences">The display preferences.</param>
  89. /// <param name="cancellationToken">The cancellation token.</param>
  90. /// <returns>Task.</returns>
  91. /// <exception cref="System.ArgumentNullException">item</exception>
  92. public async Task SaveDisplayPreferences(DisplayPreferences displayPreferences, CancellationToken cancellationToken)
  93. {
  94. if (displayPreferences == null)
  95. {
  96. throw new ArgumentNullException("displayPreferences");
  97. }
  98. if (displayPreferences.Id == Guid.Empty)
  99. {
  100. throw new ArgumentNullException("displayPreferences.Id");
  101. }
  102. if (cancellationToken == null)
  103. {
  104. throw new ArgumentNullException("cancellationToken");
  105. }
  106. cancellationToken.ThrowIfCancellationRequested();
  107. var serialized = _jsonSerializer.SerializeToBytes(displayPreferences);
  108. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  109. SQLiteTransaction transaction = null;
  110. try
  111. {
  112. transaction = Connection.BeginTransaction();
  113. using (var cmd = Connection.CreateCommand())
  114. {
  115. cmd.CommandText = "replace into displaypreferences (id, data) values (@1, @2)";
  116. cmd.AddParam("@1", displayPreferences.Id);
  117. cmd.AddParam("@2", serialized);
  118. cmd.Transaction = transaction;
  119. await cmd.ExecuteNonQueryAsync(cancellationToken);
  120. }
  121. transaction.Commit();
  122. }
  123. catch (OperationCanceledException)
  124. {
  125. if (transaction != null)
  126. {
  127. transaction.Rollback();
  128. }
  129. }
  130. catch (Exception e)
  131. {
  132. Logger.ErrorException("Failed to save display preferences:", e);
  133. if (transaction != null)
  134. {
  135. transaction.Rollback();
  136. }
  137. }
  138. finally
  139. {
  140. if (transaction != null)
  141. {
  142. transaction.Dispose();
  143. }
  144. _writeLock.Release();
  145. }
  146. }
  147. /// <summary>
  148. /// Gets the display preferences.
  149. /// </summary>
  150. /// <param name="displayPreferencesId">The display preferences id.</param>
  151. /// <returns>Task{DisplayPreferences}.</returns>
  152. /// <exception cref="System.ArgumentNullException">item</exception>
  153. public async Task<DisplayPreferences> GetDisplayPreferences(Guid displayPreferencesId)
  154. {
  155. if (displayPreferencesId == Guid.Empty)
  156. {
  157. throw new ArgumentNullException("displayPreferencesId");
  158. }
  159. var cmd = Connection.CreateCommand();
  160. cmd.CommandText = "select data from displaypreferences where id = @id";
  161. var idParam = cmd.Parameters.Add("@id", DbType.Guid);
  162. idParam.Value = displayPreferencesId;
  163. using (var reader = await cmd.ExecuteReaderAsync(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow).ConfigureAwait(false))
  164. {
  165. if (reader.Read())
  166. {
  167. using (var stream = GetStream(reader, 0))
  168. {
  169. return _jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream);
  170. }
  171. }
  172. }
  173. return null;
  174. }
  175. }
  176. }