SqliteDisplayPreferencesRepository.cs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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, _logger).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. "pragma shrink_memory"
  79. };
  80. _connection.RunQueries(queries, _logger);
  81. }
  82. /// <summary>
  83. /// Save the display preferences associated with an item in the repo
  84. /// </summary>
  85. /// <param name="displayPreferences">The display preferences.</param>
  86. /// <param name="userId">The user id.</param>
  87. /// <param name="client">The client.</param>
  88. /// <param name="cancellationToken">The cancellation token.</param>
  89. /// <returns>Task.</returns>
  90. /// <exception cref="System.ArgumentNullException">item</exception>
  91. public async Task SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, CancellationToken cancellationToken)
  92. {
  93. if (displayPreferences == null)
  94. {
  95. throw new ArgumentNullException("displayPreferences");
  96. }
  97. if (displayPreferences.Id == Guid.Empty)
  98. {
  99. throw new ArgumentNullException("displayPreferences.Id");
  100. }
  101. cancellationToken.ThrowIfCancellationRequested();
  102. var serialized = _jsonSerializer.SerializeToBytes(displayPreferences);
  103. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  104. IDbTransaction transaction = null;
  105. try
  106. {
  107. transaction = _connection.BeginTransaction();
  108. using (var cmd = _connection.CreateCommand())
  109. {
  110. cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)";
  111. cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = displayPreferences.Id;
  112. cmd.Parameters.Add(cmd, "@2", DbType.Guid).Value = userId;
  113. cmd.Parameters.Add(cmd, "@3", DbType.String).Value = client;
  114. cmd.Parameters.Add(cmd, "@4", DbType.Binary).Value = serialized;
  115. cmd.Transaction = transaction;
  116. cmd.ExecuteNonQuery();
  117. }
  118. transaction.Commit();
  119. }
  120. catch (OperationCanceledException)
  121. {
  122. if (transaction != null)
  123. {
  124. transaction.Rollback();
  125. }
  126. throw;
  127. }
  128. catch (Exception e)
  129. {
  130. _logger.ErrorException("Failed to save display preferences:", e);
  131. if (transaction != null)
  132. {
  133. transaction.Rollback();
  134. }
  135. throw;
  136. }
  137. finally
  138. {
  139. if (transaction != null)
  140. {
  141. transaction.Dispose();
  142. }
  143. _writeLock.Release();
  144. }
  145. }
  146. /// <summary>
  147. /// Gets the display preferences.
  148. /// </summary>
  149. /// <param name="displayPreferencesId">The display preferences id.</param>
  150. /// <param name="userId">The user id.</param>
  151. /// <param name="client">The client.</param>
  152. /// <returns>Task{DisplayPreferences}.</returns>
  153. /// <exception cref="System.ArgumentNullException">item</exception>
  154. public DisplayPreferences GetDisplayPreferences(Guid displayPreferencesId, Guid userId, string client)
  155. {
  156. if (displayPreferencesId == Guid.Empty)
  157. {
  158. throw new ArgumentNullException("displayPreferencesId");
  159. }
  160. var cmd = _connection.CreateCommand();
  161. cmd.CommandText = "select data from userdisplaypreferences where id = @id and userId=@userId and client=@client";
  162. cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = displayPreferencesId;
  163. cmd.Parameters.Add(cmd, "@userId", DbType.Guid).Value = userId;
  164. cmd.Parameters.Add(cmd, "@client", DbType.String).Value = client;
  165. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  166. {
  167. if (reader.Read())
  168. {
  169. using (var stream = reader.GetMemoryStream(0))
  170. {
  171. return _jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream);
  172. }
  173. }
  174. }
  175. return new DisplayPreferences { Id = displayPreferencesId };
  176. }
  177. /// <summary>
  178. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  179. /// </summary>
  180. public void Dispose()
  181. {
  182. Dispose(true);
  183. GC.SuppressFinalize(this);
  184. }
  185. private readonly object _disposeLock = new object();
  186. /// <summary>
  187. /// Releases unmanaged and - optionally - managed resources.
  188. /// </summary>
  189. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  190. protected virtual void Dispose(bool dispose)
  191. {
  192. if (dispose)
  193. {
  194. try
  195. {
  196. lock (_disposeLock)
  197. {
  198. if (_connection != null)
  199. {
  200. if (_connection.IsOpen())
  201. {
  202. _connection.Close();
  203. }
  204. _connection.Dispose();
  205. _connection = null;
  206. }
  207. }
  208. }
  209. catch (Exception ex)
  210. {
  211. _logger.ErrorException("Error disposing database", ex);
  212. }
  213. }
  214. }
  215. }
  216. }