SqliteUserRepository.cs 7.4 KB

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