SqliteUserDataRepository.cs 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Persistence;
  4. using MediaBrowser.Model.Logging;
  5. using MediaBrowser.Model.Serialization;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Data;
  9. using System.Data.SQLite;
  10. using System.IO;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace MediaBrowser.Server.Implementations.Persistence
  14. {
  15. public class SqliteUserDataRepository : SqliteRepository, IUserDataRepository
  16. {
  17. private readonly ConcurrentDictionary<string, UserItemData> _userData = new ConcurrentDictionary<string, UserItemData>();
  18. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  19. /// <summary>
  20. /// The repository name
  21. /// </summary>
  22. public const string RepositoryName = "SQLite";
  23. /// <summary>
  24. /// Gets the name of the repository
  25. /// </summary>
  26. /// <value>The name.</value>
  27. public string Name
  28. {
  29. get
  30. {
  31. return RepositoryName;
  32. }
  33. }
  34. private readonly IJsonSerializer _jsonSerializer;
  35. /// <summary>
  36. /// The _app paths
  37. /// </summary>
  38. private readonly IApplicationPaths _appPaths;
  39. /// <summary>
  40. /// Initializes a new instance of the <see cref="SqliteUserDataRepository"/> class.
  41. /// </summary>
  42. /// <param name="appPaths">The app paths.</param>
  43. /// <param name="jsonSerializer">The json serializer.</param>
  44. /// <param name="logManager">The log manager.</param>
  45. /// <exception cref="System.ArgumentNullException">
  46. /// jsonSerializer
  47. /// or
  48. /// appPaths
  49. /// </exception>
  50. public SqliteUserDataRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  51. : base(logManager)
  52. {
  53. if (jsonSerializer == null)
  54. {
  55. throw new ArgumentNullException("jsonSerializer");
  56. }
  57. if (appPaths == null)
  58. {
  59. throw new ArgumentNullException("appPaths");
  60. }
  61. _jsonSerializer = jsonSerializer;
  62. _appPaths = appPaths;
  63. }
  64. /// <summary>
  65. /// Opens the connection to the database
  66. /// </summary>
  67. /// <returns>Task.</returns>
  68. public async Task Initialize()
  69. {
  70. var dbFile = Path.Combine(_appPaths.DataPath, "userdata.db");
  71. await ConnectToDb(dbFile).ConfigureAwait(false);
  72. string[] queries = {
  73. "create table if not exists userdata (key nvarchar, userId GUID, data BLOB)",
  74. "create unique index if not exists userdataindex on userdata (key, userId)",
  75. "create table if not exists schema_version (table_name primary key, version)",
  76. //pragmas
  77. "pragma temp_store = memory"
  78. };
  79. RunQueries(queries);
  80. }
  81. /// <summary>
  82. /// Saves the user data.
  83. /// </summary>
  84. /// <param name="userId">The user id.</param>
  85. /// <param name="key">The key.</param>
  86. /// <param name="userData">The user data.</param>
  87. /// <param name="cancellationToken">The cancellation token.</param>
  88. /// <returns>Task.</returns>
  89. /// <exception cref="System.ArgumentNullException">userData
  90. /// or
  91. /// cancellationToken
  92. /// or
  93. /// userId
  94. /// or
  95. /// userDataId</exception>
  96. public async Task SaveUserData(Guid userId, string key, UserItemData userData, CancellationToken cancellationToken)
  97. {
  98. if (userData == null)
  99. {
  100. throw new ArgumentNullException("userData");
  101. }
  102. if (cancellationToken == null)
  103. {
  104. throw new ArgumentNullException("cancellationToken");
  105. }
  106. if (userId == Guid.Empty)
  107. {
  108. throw new ArgumentNullException("userId");
  109. }
  110. if (string.IsNullOrEmpty(key))
  111. {
  112. throw new ArgumentNullException("key");
  113. }
  114. cancellationToken.ThrowIfCancellationRequested();
  115. try
  116. {
  117. await PersistUserData(userId, key, userData, cancellationToken).ConfigureAwait(false);
  118. var newValue = userData;
  119. // Once it succeeds, put it into the dictionary to make it available to everyone else
  120. _userData.AddOrUpdate(GetInternalKey(userId, key), newValue, delegate { return newValue; });
  121. }
  122. catch (Exception ex)
  123. {
  124. Logger.ErrorException("Error saving user data", ex);
  125. throw;
  126. }
  127. }
  128. /// <summary>
  129. /// Gets the internal key.
  130. /// </summary>
  131. /// <param name="userId">The user id.</param>
  132. /// <param name="key">The key.</param>
  133. /// <returns>System.String.</returns>
  134. private string GetInternalKey(Guid userId, string key)
  135. {
  136. return userId + key;
  137. }
  138. /// <summary>
  139. /// Persists the user data.
  140. /// </summary>
  141. /// <param name="userId">The user id.</param>
  142. /// <param name="key">The key.</param>
  143. /// <param name="userData">The user data.</param>
  144. /// <param name="cancellationToken">The cancellation token.</param>
  145. /// <returns>Task.</returns>
  146. public async Task PersistUserData(Guid userId, string key, UserItemData userData, CancellationToken cancellationToken)
  147. {
  148. cancellationToken.ThrowIfCancellationRequested();
  149. var serialized = _jsonSerializer.SerializeToBytes(userData);
  150. cancellationToken.ThrowIfCancellationRequested();
  151. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  152. SQLiteTransaction transaction = null;
  153. try
  154. {
  155. transaction = Connection.BeginTransaction();
  156. using (var cmd = Connection.CreateCommand())
  157. {
  158. cmd.CommandText = "replace into userdata (key, userId, data) values (@1, @2, @3)";
  159. cmd.AddParam("@1", key);
  160. cmd.AddParam("@2", userId);
  161. cmd.AddParam("@3", serialized);
  162. cmd.Transaction = transaction;
  163. await cmd.ExecuteNonQueryAsync(cancellationToken);
  164. }
  165. transaction.Commit();
  166. }
  167. catch (OperationCanceledException)
  168. {
  169. if (transaction != null)
  170. {
  171. transaction.Rollback();
  172. }
  173. throw;
  174. }
  175. catch (Exception e)
  176. {
  177. Logger.ErrorException("Failed to save user data:", e);
  178. if (transaction != null)
  179. {
  180. transaction.Rollback();
  181. }
  182. throw;
  183. }
  184. finally
  185. {
  186. if (transaction != null)
  187. {
  188. transaction.Dispose();
  189. }
  190. _writeLock.Release();
  191. }
  192. }
  193. /// <summary>
  194. /// Gets the user data.
  195. /// </summary>
  196. /// <param name="userId">The user id.</param>
  197. /// <param name="key">The key.</param>
  198. /// <returns>Task{UserItemData}.</returns>
  199. /// <exception cref="System.ArgumentNullException">
  200. /// userId
  201. /// or
  202. /// key
  203. /// </exception>
  204. public UserItemData GetUserData(Guid userId, string key)
  205. {
  206. if (userId == Guid.Empty)
  207. {
  208. throw new ArgumentNullException("userId");
  209. }
  210. if (string.IsNullOrEmpty(key))
  211. {
  212. throw new ArgumentNullException("key");
  213. }
  214. return _userData.GetOrAdd(GetInternalKey(userId, key), keyName => RetrieveUserData(userId, key));
  215. }
  216. /// <summary>
  217. /// Retrieves the user data.
  218. /// </summary>
  219. /// <param name="userId">The user id.</param>
  220. /// <param name="key">The key.</param>
  221. /// <returns>Task{UserItemData}.</returns>
  222. private UserItemData RetrieveUserData(Guid userId, string key)
  223. {
  224. using (var cmd = Connection.CreateCommand())
  225. {
  226. cmd.CommandText = "select data from userdata where key = @key and userId=@userId";
  227. var idParam = cmd.Parameters.Add("@key", DbType.String);
  228. idParam.Value = key;
  229. var userIdParam = cmd.Parameters.Add("@userId", DbType.Guid);
  230. userIdParam.Value = userId;
  231. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  232. {
  233. if (reader.Read())
  234. {
  235. using (var stream = GetStream(reader, 0))
  236. {
  237. return _jsonSerializer.DeserializeFromStream<UserItemData>(stream);
  238. }
  239. }
  240. }
  241. return new UserItemData();
  242. }
  243. }
  244. }
  245. }