SqliteUserRepository.cs 7.2 KB

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