SqliteUserRepository.cs 7.2 KB

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