SqliteUserRepository.cs 7.6 KB

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