SqliteUserRepository.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using MediaBrowser.Controller;
  5. using MediaBrowser.Controller.Entities;
  6. using MediaBrowser.Controller.Persistence;
  7. using MediaBrowser.Model.Serialization;
  8. using Microsoft.Extensions.Logging;
  9. using SQLitePCL.pretty;
  10. namespace Emby.Server.Implementations.Data
  11. {
  12. /// <summary>
  13. /// Class SQLiteUserRepository
  14. /// </summary>
  15. public class SqliteUserRepository : BaseSqliteRepository, IUserRepository
  16. {
  17. private readonly IJsonSerializer _jsonSerializer;
  18. public SqliteUserRepository(ILogger logger, IServerApplicationPaths appPaths, IJsonSerializer jsonSerializer)
  19. : base(logger)
  20. {
  21. _jsonSerializer = jsonSerializer;
  22. DbFilePath = Path.Combine(appPaths.DataPath, "users.db");
  23. }
  24. /// <summary>
  25. /// Gets the name of the repository
  26. /// </summary>
  27. /// <value>The name.</value>
  28. public string Name => "SQLite";
  29. /// <summary>
  30. /// Opens the connection to the database
  31. /// </summary>
  32. /// <returns>Task.</returns>
  33. public void Initialize()
  34. {
  35. using (var connection = CreateConnection())
  36. {
  37. RunDefaultInitialization(connection);
  38. var localUsersTableExists = TableExists(connection, "LocalUsersv2");
  39. connection.RunQueries(new[] {
  40. "create table if not exists LocalUsersv2 (Id INTEGER PRIMARY KEY, guid GUID NOT NULL, data BLOB NOT NULL)",
  41. "drop index if exists idx_users"
  42. });
  43. if (!localUsersTableExists && TableExists(connection, "Users"))
  44. {
  45. TryMigrateToLocalUsersTable(connection);
  46. }
  47. }
  48. }
  49. private void TryMigrateToLocalUsersTable(ManagedConnection connection)
  50. {
  51. try
  52. {
  53. connection.RunQueries(new[]
  54. {
  55. "INSERT INTO LocalUsersv2 (guid, data) SELECT guid,data from users"
  56. });
  57. }
  58. catch (Exception ex)
  59. {
  60. Logger.LogError(ex, "Error migrating users database");
  61. }
  62. }
  63. /// <summary>
  64. /// Save a user in the repo
  65. /// </summary>
  66. public void CreateUser(User user)
  67. {
  68. if (user == null)
  69. {
  70. throw new ArgumentNullException(nameof(user));
  71. }
  72. var serialized = _jsonSerializer.SerializeToBytes(user);
  73. using (WriteLock.Write())
  74. {
  75. using (var connection = CreateConnection())
  76. {
  77. connection.RunInTransaction(db =>
  78. {
  79. using (var statement = db.PrepareStatement("insert into LocalUsersv2 (guid, data) values (@guid, @data)"))
  80. {
  81. statement.TryBind("@guid", user.Id.ToGuidBlob());
  82. statement.TryBind("@data", serialized);
  83. statement.MoveNext();
  84. }
  85. var createdUser = GetUser(user.Id, false);
  86. if (createdUser == null)
  87. {
  88. throw new ApplicationException("created user should never be null");
  89. }
  90. user.InternalId = createdUser.InternalId;
  91. }, TransactionMode);
  92. }
  93. }
  94. }
  95. public void UpdateUser(User user)
  96. {
  97. if (user == null)
  98. {
  99. throw new ArgumentNullException(nameof(user));
  100. }
  101. var serialized = _jsonSerializer.SerializeToBytes(user);
  102. using (WriteLock.Write())
  103. {
  104. using (var connection = CreateConnection())
  105. {
  106. connection.RunInTransaction(db =>
  107. {
  108. using (var statement = db.PrepareStatement("update LocalUsersv2 set data=@data where Id=@InternalId"))
  109. {
  110. statement.TryBind("@InternalId", user.InternalId);
  111. statement.TryBind("@data", serialized);
  112. statement.MoveNext();
  113. }
  114. }, TransactionMode);
  115. }
  116. }
  117. }
  118. private User GetUser(Guid guid, bool openLock)
  119. {
  120. using (openLock ? WriteLock.Read() : null)
  121. {
  122. using (var connection = CreateConnection(true))
  123. {
  124. using (var statement = connection.PrepareStatement("select id,guid,data from LocalUsersv2 where guid=@guid"))
  125. {
  126. statement.TryBind("@guid", guid);
  127. foreach (var row in statement.ExecuteQuery())
  128. {
  129. return GetUser(row);
  130. }
  131. }
  132. }
  133. }
  134. return null;
  135. }
  136. private User GetUser(IReadOnlyList<IResultSetValue> row)
  137. {
  138. var id = row[0].ToInt64();
  139. var guid = row[1].ReadGuidFromBlob();
  140. using (var stream = new MemoryStream(row[2].ToBlob()))
  141. {
  142. stream.Position = 0;
  143. var user = _jsonSerializer.DeserializeFromStream<User>(stream);
  144. user.InternalId = id;
  145. user.Id = guid;
  146. return user;
  147. }
  148. }
  149. /// <summary>
  150. /// Retrieve all users from the database
  151. /// </summary>
  152. /// <returns>IEnumerable{User}.</returns>
  153. public List<User> RetrieveAllUsers()
  154. {
  155. var list = new List<User>();
  156. using (WriteLock.Read())
  157. {
  158. using (var connection = CreateConnection(true))
  159. {
  160. foreach (var row in connection.Query("select id,guid,data from LocalUsersv2"))
  161. {
  162. list.Add(GetUser(row));
  163. }
  164. }
  165. }
  166. return list;
  167. }
  168. /// <summary>
  169. /// Deletes the user.
  170. /// </summary>
  171. /// <param name="user">The user.</param>
  172. /// <returns>Task.</returns>
  173. /// <exception cref="ArgumentNullException">user</exception>
  174. public void DeleteUser(User user)
  175. {
  176. if (user == null)
  177. {
  178. throw new ArgumentNullException(nameof(user));
  179. }
  180. using (WriteLock.Write())
  181. {
  182. using (var connection = CreateConnection())
  183. {
  184. connection.RunInTransaction(db =>
  185. {
  186. using (var statement = db.PrepareStatement("delete from LocalUsersv2 where Id=@id"))
  187. {
  188. statement.TryBind("@id", user.InternalId);
  189. statement.MoveNext();
  190. }
  191. }, TransactionMode);
  192. }
  193. }
  194. }
  195. }
  196. }