SqliteUserRepository.cs 7.3 KB

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