SqliteDisplayPreferencesRepository.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. using System.Collections.Generic;
  2. using MediaBrowser.Common.Configuration;
  3. using MediaBrowser.Common.Extensions;
  4. using MediaBrowser.Controller.Persistence;
  5. using MediaBrowser.Model.Entities;
  6. using MediaBrowser.Model.Logging;
  7. using MediaBrowser.Model.Serialization;
  8. using System;
  9. using System.Data;
  10. using System.IO;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Server.Implementations.Persistence
  14. {
  15. /// <summary>
  16. /// Class SQLiteDisplayPreferencesRepository
  17. /// </summary>
  18. public class SqliteDisplayPreferencesRepository : IDisplayPreferencesRepository
  19. {
  20. private IDbConnection _connection;
  21. private readonly ILogger _logger;
  22. /// <summary>
  23. /// Gets the name of the repository
  24. /// </summary>
  25. /// <value>The name.</value>
  26. public string Name
  27. {
  28. get
  29. {
  30. return "SQLite";
  31. }
  32. }
  33. /// <summary>
  34. /// The _json serializer
  35. /// </summary>
  36. private readonly IJsonSerializer _jsonSerializer;
  37. /// <summary>
  38. /// The _app paths
  39. /// </summary>
  40. private readonly IApplicationPaths _appPaths;
  41. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  42. /// <summary>
  43. /// Initializes a new instance of the <see cref="SqliteDisplayPreferencesRepository" /> class.
  44. /// </summary>
  45. /// <param name="appPaths">The app paths.</param>
  46. /// <param name="jsonSerializer">The json serializer.</param>
  47. /// <param name="logManager">The log manager.</param>
  48. /// <exception cref="System.ArgumentNullException">
  49. /// jsonSerializer
  50. /// or
  51. /// appPaths
  52. /// </exception>
  53. public SqliteDisplayPreferencesRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  54. {
  55. if (jsonSerializer == null)
  56. {
  57. throw new ArgumentNullException("jsonSerializer");
  58. }
  59. if (appPaths == null)
  60. {
  61. throw new ArgumentNullException("appPaths");
  62. }
  63. _jsonSerializer = jsonSerializer;
  64. _appPaths = appPaths;
  65. _logger = logManager.GetLogger(GetType().Name);
  66. }
  67. /// <summary>
  68. /// Opens the connection to the database
  69. /// </summary>
  70. /// <returns>Task.</returns>
  71. public async Task Initialize()
  72. {
  73. var dbFile = Path.Combine(_appPaths.DataPath, "displaypreferences.db");
  74. _connection = await SqliteExtensions.ConnectToDb(dbFile, _logger).ConfigureAwait(false);
  75. string[] queries = {
  76. "create table if not exists userdisplaypreferences (id GUID, userId GUID, client text, data BLOB)",
  77. "create unique index if not exists userdisplaypreferencesindex on userdisplaypreferences (id, userId, client)",
  78. //pragmas
  79. "pragma temp_store = memory",
  80. "pragma shrink_memory"
  81. };
  82. _connection.RunQueries(queries, _logger);
  83. }
  84. /// <summary>
  85. /// Save the display preferences associated with an item in the repo
  86. /// </summary>
  87. /// <param name="displayPreferences">The display preferences.</param>
  88. /// <param name="userId">The user id.</param>
  89. /// <param name="client">The client.</param>
  90. /// <param name="cancellationToken">The cancellation token.</param>
  91. /// <returns>Task.</returns>
  92. /// <exception cref="System.ArgumentNullException">item</exception>
  93. public async Task SaveDisplayPreferences(DisplayPreferences displayPreferences, Guid userId, string client, CancellationToken cancellationToken)
  94. {
  95. if (displayPreferences == null)
  96. {
  97. throw new ArgumentNullException("displayPreferences");
  98. }
  99. if (string.IsNullOrWhiteSpace(displayPreferences.Id))
  100. {
  101. throw new ArgumentNullException("displayPreferences.Id");
  102. }
  103. cancellationToken.ThrowIfCancellationRequested();
  104. var serialized = _jsonSerializer.SerializeToBytes(displayPreferences);
  105. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  106. IDbTransaction transaction = null;
  107. try
  108. {
  109. transaction = _connection.BeginTransaction();
  110. using (var cmd = _connection.CreateCommand())
  111. {
  112. cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)";
  113. cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = new Guid(displayPreferences.Id);
  114. cmd.Parameters.Add(cmd, "@2", DbType.Guid).Value = userId;
  115. cmd.Parameters.Add(cmd, "@3", DbType.String).Value = client;
  116. cmd.Parameters.Add(cmd, "@4", DbType.Binary).Value = serialized;
  117. cmd.Transaction = transaction;
  118. cmd.ExecuteNonQuery();
  119. }
  120. transaction.Commit();
  121. }
  122. catch (OperationCanceledException)
  123. {
  124. if (transaction != null)
  125. {
  126. transaction.Rollback();
  127. }
  128. throw;
  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. throw;
  138. }
  139. finally
  140. {
  141. if (transaction != null)
  142. {
  143. transaction.Dispose();
  144. }
  145. _writeLock.Release();
  146. }
  147. }
  148. /// <summary>
  149. /// Save all display preferences associated with a user in the repo
  150. /// </summary>
  151. /// <param name="displayPreferences">The display preferences.</param>
  152. /// <param name="userId">The user id.</param>
  153. /// <param name="cancellationToken">The cancellation token.</param>
  154. /// <returns>Task.</returns>
  155. /// <exception cref="System.ArgumentNullException">item</exception>
  156. public async Task SaveAllDisplayPreferences(IEnumerable<DisplayPreferences> displayPreferences, Guid userId, CancellationToken cancellationToken)
  157. {
  158. if (displayPreferences == null)
  159. {
  160. throw new ArgumentNullException("displayPreferences");
  161. }
  162. cancellationToken.ThrowIfCancellationRequested();
  163. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  164. IDbTransaction transaction = null;
  165. try
  166. {
  167. transaction = _connection.BeginTransaction();
  168. foreach (var displayPreference in displayPreferences)
  169. {
  170. var serialized = _jsonSerializer.SerializeToBytes(displayPreference);
  171. using (var cmd = _connection.CreateCommand())
  172. {
  173. cmd.CommandText = "replace into userdisplaypreferences (id, userid, client, data) values (@1, @2, @3, @4)";
  174. cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = new Guid(displayPreference.Id);
  175. cmd.Parameters.Add(cmd, "@2", DbType.Guid).Value = userId;
  176. cmd.Parameters.Add(cmd, "@3", DbType.String).Value = displayPreference.Client;
  177. cmd.Parameters.Add(cmd, "@4", DbType.Binary).Value = serialized;
  178. cmd.Transaction = transaction;
  179. cmd.ExecuteNonQuery();
  180. }
  181. }
  182. transaction.Commit();
  183. }
  184. catch (OperationCanceledException)
  185. {
  186. if (transaction != null)
  187. {
  188. transaction.Rollback();
  189. }
  190. throw;
  191. }
  192. catch (Exception e)
  193. {
  194. _logger.ErrorException("Failed to save display preferences:", e);
  195. if (transaction != null)
  196. {
  197. transaction.Rollback();
  198. }
  199. throw;
  200. }
  201. finally
  202. {
  203. if (transaction != null)
  204. {
  205. transaction.Dispose();
  206. }
  207. _writeLock.Release();
  208. }
  209. }
  210. /// <summary>
  211. /// Gets the display preferences.
  212. /// </summary>
  213. /// <param name="displayPreferencesId">The display preferences id.</param>
  214. /// <param name="userId">The user id.</param>
  215. /// <param name="client">The client.</param>
  216. /// <returns>Task{DisplayPreferences}.</returns>
  217. /// <exception cref="System.ArgumentNullException">item</exception>
  218. public DisplayPreferences GetDisplayPreferences(string displayPreferencesId, Guid userId, string client)
  219. {
  220. if (string.IsNullOrWhiteSpace(displayPreferencesId))
  221. {
  222. throw new ArgumentNullException("displayPreferencesId");
  223. }
  224. var guidId = displayPreferencesId.GetMD5();
  225. var cmd = _connection.CreateCommand();
  226. cmd.CommandText = "select data from userdisplaypreferences where id = @id and userId=@userId and client=@client";
  227. cmd.Parameters.Add(cmd, "@id", DbType.Guid).Value = guidId;
  228. cmd.Parameters.Add(cmd, "@userId", DbType.Guid).Value = userId;
  229. cmd.Parameters.Add(cmd, "@client", DbType.String).Value = client;
  230. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  231. {
  232. if (reader.Read())
  233. {
  234. using (var stream = reader.GetMemoryStream(0))
  235. {
  236. return _jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream);
  237. }
  238. }
  239. }
  240. return new DisplayPreferences
  241. {
  242. Id = guidId.ToString("N")
  243. };
  244. }
  245. /// <summary>
  246. /// Gets all display preferences for the given user.
  247. /// </summary>
  248. /// <param name="userId">The user id.</param>
  249. /// <returns>Task{DisplayPreferences}.</returns>
  250. /// <exception cref="System.ArgumentNullException">item</exception>
  251. public IEnumerable<DisplayPreferences> GetAllDisplayPreferences(Guid userId)
  252. {
  253. var cmd = _connection.CreateCommand();
  254. cmd.CommandText = "select data from userdisplaypreferences where userId=@userId";
  255. cmd.Parameters.Add(cmd, "@userId", DbType.Guid).Value = userId;
  256. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  257. {
  258. while (reader.Read())
  259. {
  260. using (var stream = reader.GetMemoryStream(0))
  261. {
  262. yield return _jsonSerializer.DeserializeFromStream<DisplayPreferences>(stream);
  263. }
  264. }
  265. }
  266. }
  267. /// <summary>
  268. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  269. /// </summary>
  270. public void Dispose()
  271. {
  272. Dispose(true);
  273. GC.SuppressFinalize(this);
  274. }
  275. private readonly object _disposeLock = new object();
  276. /// <summary>
  277. /// Releases unmanaged and - optionally - managed resources.
  278. /// </summary>
  279. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  280. protected virtual void Dispose(bool dispose)
  281. {
  282. if (dispose)
  283. {
  284. try
  285. {
  286. lock (_disposeLock)
  287. {
  288. if (_connection != null)
  289. {
  290. if (_connection.IsOpen())
  291. {
  292. _connection.Close();
  293. }
  294. _connection.Dispose();
  295. _connection = null;
  296. }
  297. }
  298. }
  299. catch (Exception ex)
  300. {
  301. _logger.ErrorException("Error disposing database", ex);
  302. }
  303. }
  304. }
  305. }
  306. }