SqliteUserRepository.cs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Persistence;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Data;
  9. using System.IO;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. using MediaBrowser.Common.IO;
  13. using MediaBrowser.Model.IO;
  14. namespace MediaBrowser.Server.Implementations.Persistence
  15. {
  16. /// <summary>
  17. /// Class SQLiteUserRepository
  18. /// </summary>
  19. public class SqliteUserRepository : BaseSqliteRepository, IUserRepository
  20. {
  21. private readonly IJsonSerializer _jsonSerializer;
  22. private readonly IMemoryStreamFactory _memoryStreamProvider;
  23. public SqliteUserRepository(ILogManager logManager, IServerApplicationPaths appPaths, IJsonSerializer jsonSerializer, IDbConnector dbConnector, IMemoryStreamFactory memoryStreamProvider) : base(logManager, dbConnector)
  24. {
  25. _jsonSerializer = jsonSerializer;
  26. _memoryStreamProvider = memoryStreamProvider;
  27. DbFilePath = Path.Combine(appPaths.DataPath, "users.db");
  28. }
  29. /// <summary>
  30. /// Gets the name of the repository
  31. /// </summary>
  32. /// <value>The name.</value>
  33. public string Name
  34. {
  35. get
  36. {
  37. return "SQLite";
  38. }
  39. }
  40. /// <summary>
  41. /// Opens the connection to the database
  42. /// </summary>
  43. /// <returns>Task.</returns>
  44. public async Task Initialize()
  45. {
  46. using (var connection = await CreateConnection().ConfigureAwait(false))
  47. {
  48. string[] queries = {
  49. "create table if not exists users (guid GUID primary key, data BLOB)",
  50. "create index if not exists idx_users on users(guid)",
  51. "create table if not exists schema_version (table_name primary key, version)",
  52. "pragma shrink_memory"
  53. };
  54. connection.RunQueries(queries, Logger);
  55. }
  56. }
  57. /// <summary>
  58. /// Save a user in the repo
  59. /// </summary>
  60. /// <param name="user">The user.</param>
  61. /// <param name="cancellationToken">The cancellation token.</param>
  62. /// <returns>Task.</returns>
  63. /// <exception cref="System.ArgumentNullException">user</exception>
  64. public async Task SaveUser(User user, CancellationToken cancellationToken)
  65. {
  66. if (user == null)
  67. {
  68. throw new ArgumentNullException("user");
  69. }
  70. cancellationToken.ThrowIfCancellationRequested();
  71. var serialized = _jsonSerializer.SerializeToBytes(user, _memoryStreamProvider);
  72. cancellationToken.ThrowIfCancellationRequested();
  73. using (var connection = await CreateConnection().ConfigureAwait(false))
  74. {
  75. IDbTransaction transaction = null;
  76. try
  77. {
  78. transaction = connection.BeginTransaction();
  79. using (var cmd = connection.CreateCommand())
  80. {
  81. cmd.CommandText = "replace into users (guid, data) values (@1, @2)";
  82. cmd.Parameters.Add(cmd, "@1", DbType.Guid).Value = user.Id;
  83. cmd.Parameters.Add(cmd, "@2", DbType.Binary).Value = serialized;
  84. cmd.Transaction = transaction;
  85. cmd.ExecuteNonQuery();
  86. }
  87. transaction.Commit();
  88. }
  89. catch (OperationCanceledException)
  90. {
  91. if (transaction != null)
  92. {
  93. transaction.Rollback();
  94. }
  95. throw;
  96. }
  97. catch (Exception e)
  98. {
  99. Logger.ErrorException("Failed to save user:", e);
  100. if (transaction != null)
  101. {
  102. transaction.Rollback();
  103. }
  104. throw;
  105. }
  106. finally
  107. {
  108. if (transaction != null)
  109. {
  110. transaction.Dispose();
  111. }
  112. }
  113. }
  114. }
  115. /// <summary>
  116. /// Retrieve all users from the database
  117. /// </summary>
  118. /// <returns>IEnumerable{User}.</returns>
  119. public IEnumerable<User> RetrieveAllUsers()
  120. {
  121. var list = new List<User>();
  122. using (var connection = CreateConnection(true).Result)
  123. {
  124. using (var cmd = connection.CreateCommand())
  125. {
  126. cmd.CommandText = "select guid,data from users";
  127. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  128. {
  129. while (reader.Read())
  130. {
  131. var id = reader.GetGuid(0);
  132. using (var stream = reader.GetMemoryStream(1, _memoryStreamProvider))
  133. {
  134. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  135. user.Id = id;
  136. list.Add(user);
  137. }
  138. }
  139. }
  140. }
  141. }
  142. return list;
  143. }
  144. /// <summary>
  145. /// Deletes the user.
  146. /// </summary>
  147. /// <param name="user">The user.</param>
  148. /// <param name="cancellationToken">The cancellation token.</param>
  149. /// <returns>Task.</returns>
  150. /// <exception cref="System.ArgumentNullException">user</exception>
  151. public async Task DeleteUser(User user, CancellationToken cancellationToken)
  152. {
  153. if (user == null)
  154. {
  155. throw new ArgumentNullException("user");
  156. }
  157. cancellationToken.ThrowIfCancellationRequested();
  158. using (var connection = await CreateConnection().ConfigureAwait(false))
  159. {
  160. IDbTransaction transaction = null;
  161. try
  162. {
  163. transaction = connection.BeginTransaction();
  164. using (var cmd = connection.CreateCommand())
  165. {
  166. cmd.CommandText = "delete from users where guid=@guid";
  167. cmd.Parameters.Add(cmd, "@guid", DbType.Guid).Value = user.Id;
  168. cmd.Transaction = transaction;
  169. cmd.ExecuteNonQuery();
  170. }
  171. transaction.Commit();
  172. }
  173. catch (OperationCanceledException)
  174. {
  175. if (transaction != null)
  176. {
  177. transaction.Rollback();
  178. }
  179. throw;
  180. }
  181. catch (Exception e)
  182. {
  183. Logger.ErrorException("Failed to delete user:", e);
  184. if (transaction != null)
  185. {
  186. transaction.Rollback();
  187. }
  188. throw;
  189. }
  190. finally
  191. {
  192. if (transaction != null)
  193. {
  194. transaction.Dispose();
  195. }
  196. }
  197. }
  198. }
  199. }
  200. }