SqliteDisplayPreferencesRepository.cs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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.IO;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. namespace MediaBrowser.Server.Implementations.Persistence
  12. {
  13. /// <summary>
  14. /// Class SQLiteDisplayPreferencesRepository
  15. /// </summary>
  16. public class SqliteDisplayPreferencesRepository : IDisplayPreferencesRepository
  17. {
  18. private IDbConnection _connection;
  19. private readonly ILogger _logger;
  20. /// <summary>
  21. /// Gets the name of the repository
  22. /// </summary>
  23. /// <value>The name.</value>
  24. public string Name
  25. {
  26. get
  27. {
  28. return "SQLite";
  29. }
  30. }
  31. /// <summary>
  32. /// The _json serializer
  33. /// </summary>
  34. private readonly IJsonSerializer _jsonSerializer;
  35. /// <summary>
  36. /// The _app paths
  37. /// </summary>
  38. private readonly IApplicationPaths _appPaths;
  39. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  40. /// <summary>
  41. /// Initializes a new instance of the <see cref="SqliteDisplayPreferencesRepository" /> class.
  42. /// </summary>
  43. /// <param name="appPaths">The app paths.</param>
  44. /// <param name="jsonSerializer">The json serializer.</param>
  45. /// <param name="logManager">The log manager.</param>
  46. /// <exception cref="System.ArgumentNullException">
  47. /// jsonSerializer
  48. /// or
  49. /// appPaths
  50. /// </exception>
  51. public SqliteDisplayPreferencesRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  52. {
  53. if (jsonSerializer == null)
  54. {
  55. throw new ArgumentNullException("jsonSerializer");
  56. }
  57. if (appPaths == null)
  58. {
  59. throw new ArgumentNullException("appPaths");
  60. }
  61. _jsonSerializer = jsonSerializer;
  62. _appPaths = appPaths;
  63. _logger = logManager.GetLogger(GetType().Name);
  64. }
  65. /// <summary>
  66. /// Opens the connection to the database
  67. /// </summary>
  68. /// <returns>Task.</returns>
  69. public async Task Initialize()
  70. {
  71. var dbFile = Path.Combine(_appPaths.DataPath, "displaypreferences.db");
  72. _connection = await SqliteExtensions.ConnectToDb(dbFile).ConfigureAwait(false);
  73. string[] queries = {
  74. "create table if not exists userdisplaypreferences (id GUID, userId GUID, client text, data BLOB)",
  75. "create unique index if not exists userdisplaypreferencesindex on userdisplaypreferences (id, userId, client)",
  76. //pragmas
  77. "pragma temp_store = memory"
  78. };
  79. _connection.RunQueries(queries, _logger);
  80. }
  81. /// <summary>
  82. /// Save the display preferences associated with an item in the repo
  83. /// </summary>
  84. /// <param name="displayPreferences">The display preferences.</param>
  85. /// <param name="userId">The user id.</param>
  86. /// <param name="client">The client.</param>
  87. /// <param name="cancellationToken">The cancellation token.</param>
  88. /// <returns>Task.</returns>
  89. /// <exception cref="System.ArgumentNullException">item</exception>
  90. public async Task SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, CancellationToken cancellationToken)
  91. {
  92. if (displayPreferences == null)
  93. {
  94. throw new ArgumentNullException("displayPreferences");
  95. }
  96. if (displayPreferences.Id == Guid.Empty)
  97. {
  98. throw new ArgumentNullException("displayPreferences.Id");
  99. }
  100. if (cancellationToken == null)
  101. {
  102. throw new ArgumentNullException("cancellationToken");
  103. }
  104. cancellationToken.ThrowIfCancellationRequested();
  105. var serialized = _jsonSerializer.SerializeToBytes(displayPreferences);
  106. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  107. IDbTransaction transaction = null;
  108. try
  109. {
  110. transaction = _connection.BeginTransaction();
  111. using (var cmd = _connection.CreateCommand())
  112. {
  113. cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)";
  114. cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = displayPreferences.Id;
  115. cmd.Parameters.Add(cmd, "@2", DbType.Guid).Value = userId;
  116. cmd.Parameters.Add(cmd, "@3", DbType.String).Value = client;
  117. cmd.Parameters.Add(cmd, "@4", DbType.Binary).Value = serialized;
  118. cmd.Transaction = transaction;
  119. cmd.ExecuteNonQuery();
  120. }
  121. transaction.Commit();
  122. }
  123. catch (OperationCanceledException)
  124. {
  125. if (transaction != null)
  126. {
  127. transaction.Rollback();
  128. }
  129. throw;
  130. }
  131. catch (Exception e)
  132. {
  133. _logger.ErrorException("Failed to save display preferences:", e);
  134. if (transaction != null)
  135. {
  136. transaction.Rollback();
  137. }
  138. throw;
  139. }
  140. finally
  141. {
  142. if (transaction != null)
  143. {
  144. transaction.Dispose();
  145. }
  146. _writeLock.Release();
  147. }
  148. }
  149. /// <summary>
  150. /// Gets the display preferences.
  151. /// </summary>
  152. /// <param name="displayPreferencesId">The display preferences id.</param>
  153. /// <param name="userId">The user id.</param>
  154. /// <param name="client">The client.</param>
  155. /// <returns>Task{DisplayPreferences}.</returns>
  156. /// <exception cref="System.ArgumentNullException">item</exception>
  157. public DisplayPreferences GetDisplayPreferences(Guid displayPreferencesId, Guid userId, string client)
  158. {
  159. if (displayPreferencesId == Guid.Empty)
  160. {
  161. throw new ArgumentNullException("displayPreferencesId");
  162. }
  163. var cmd = _connection.CreateCommand();
  164. cmd.CommandText = "select data from userdisplaypreferences where id = @id and userId=@userId and client=@client";
  165. cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = displayPreferencesId;
  166. cmd.Parameters.Add(cmd, "@userId", DbType.Guid).Value = userId;
  167. cmd.Parameters.Add(cmd, "@client", DbType.String).Value = client;
  168. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  169. {
  170. if (reader.Read())
  171. {
  172. using (var stream = reader.GetMemoryStream(0))
  173. {
  174. return _jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream);
  175. }
  176. }
  177. }
  178. return new DisplayPreferences { Id = displayPreferencesId };
  179. }
  180. /// <summary>
  181. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  182. /// </summary>
  183. public void Dispose()
  184. {
  185. Dispose(true);
  186. GC.SuppressFinalize(this);
  187. }
  188. private readonly object _disposeLock = new object();
  189. /// <summary>
  190. /// Releases unmanaged and - optionally - managed resources.
  191. /// </summary>
  192. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  193. protected virtual void Dispose(bool dispose)
  194. {
  195. if (dispose)
  196. {
  197. try
  198. {
  199. lock (_disposeLock)
  200. {
  201. if (_connection != null)
  202. {
  203. if (_connection.IsOpen())
  204. {
  205. _connection.Close();
  206. }
  207. _connection.Dispose();
  208. _connection = null;
  209. }
  210. }
  211. }
  212. catch (Exception ex)
  213. {
  214. _logger.ErrorException("Error disposing database", ex);
  215. }
  216. }
  217. }
  218. }
  219. }