SqliteDisplayPreferencesRepository.cs 8.9 KB

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