2
0

SqliteDisplayPreferencesRepository.cs 8.9 KB

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