SqliteUserDataRepository.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 : IUserDataRepository
  16. {
  17. private readonly ILogger _logger;
  18. private readonly ConcurrentDictionary<string, UserItemData> _userData = new ConcurrentDictionary<string, UserItemData>();
  19. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  20. private SQLiteConnection _connection;
  21. /// <summary>
  22. /// Gets the name of the repository
  23. /// </summary>
  24. /// <value>The name.</value>
  25. public string Name
  26. {
  27. get
  28. {
  29. return "SQLite";
  30. }
  31. }
  32. private readonly IJsonSerializer _jsonSerializer;
  33. /// <summary>
  34. /// The _app paths
  35. /// </summary>
  36. private readonly IApplicationPaths _appPaths;
  37. /// <summary>
  38. /// Initializes a new instance of the <see cref="SqliteUserDataRepository"/> class.
  39. /// </summary>
  40. /// <param name="appPaths">The app paths.</param>
  41. /// <param name="jsonSerializer">The json serializer.</param>
  42. /// <param name="logManager">The log manager.</param>
  43. /// <exception cref="System.ArgumentNullException">
  44. /// jsonSerializer
  45. /// or
  46. /// appPaths
  47. /// </exception>
  48. public SqliteUserDataRepository(IApplicationPaths appPaths, IJsonSerializer jsonSerializer, ILogManager logManager)
  49. {
  50. if (jsonSerializer == null)
  51. {
  52. throw new ArgumentNullException("jsonSerializer");
  53. }
  54. if (appPaths == null)
  55. {
  56. throw new ArgumentNullException("appPaths");
  57. }
  58. _jsonSerializer = jsonSerializer;
  59. _appPaths = appPaths;
  60. _logger = logManager.GetLogger(GetType().Name);
  61. }
  62. /// <summary>
  63. /// Opens the connection to the database
  64. /// </summary>
  65. /// <returns>Task.</returns>
  66. public async Task Initialize()
  67. {
  68. var dbFile = Path.Combine(_appPaths.DataPath, "userdata.db");
  69. _connection = await SqliteExtensions.ConnectToDb(dbFile).ConfigureAwait(false);
  70. string[] queries = {
  71. "create table if not exists userdata (key nvarchar, userId GUID, data BLOB)",
  72. "create unique index if not exists userdataindex on userdata (key, userId)",
  73. "create table if not exists schema_version (table_name primary key, version)",
  74. //pragmas
  75. "pragma temp_store = memory"
  76. };
  77. _connection.RunQueries(queries, _logger);
  78. }
  79. /// <summary>
  80. /// Saves the user data.
  81. /// </summary>
  82. /// <param name="userId">The user id.</param>
  83. /// <param name="key">The key.</param>
  84. /// <param name="userData">The user data.</param>
  85. /// <param name="cancellationToken">The cancellation token.</param>
  86. /// <returns>Task.</returns>
  87. /// <exception cref="System.ArgumentNullException">userData
  88. /// or
  89. /// cancellationToken
  90. /// or
  91. /// userId
  92. /// or
  93. /// userDataId</exception>
  94. public async Task SaveUserData(Guid userId, string key, UserItemData userData, CancellationToken cancellationToken)
  95. {
  96. if (userData == null)
  97. {
  98. throw new ArgumentNullException("userData");
  99. }
  100. if (cancellationToken == null)
  101. {
  102. throw new ArgumentNullException("cancellationToken");
  103. }
  104. if (userId == Guid.Empty)
  105. {
  106. throw new ArgumentNullException("userId");
  107. }
  108. if (string.IsNullOrEmpty(key))
  109. {
  110. throw new ArgumentNullException("key");
  111. }
  112. cancellationToken.ThrowIfCancellationRequested();
  113. try
  114. {
  115. await PersistUserData(userId, key, userData, cancellationToken).ConfigureAwait(false);
  116. var newValue = userData;
  117. // Once it succeeds, put it into the dictionary to make it available to everyone else
  118. _userData.AddOrUpdate(GetInternalKey(userId, key), newValue, delegate { return newValue; });
  119. }
  120. catch (Exception ex)
  121. {
  122. _logger.ErrorException("Error saving user data", ex);
  123. throw;
  124. }
  125. }
  126. /// <summary>
  127. /// Gets the internal key.
  128. /// </summary>
  129. /// <param name="userId">The user id.</param>
  130. /// <param name="key">The key.</param>
  131. /// <returns>System.String.</returns>
  132. private string GetInternalKey(Guid userId, string key)
  133. {
  134. return userId + key;
  135. }
  136. /// <summary>
  137. /// Persists the user data.
  138. /// </summary>
  139. /// <param name="userId">The user id.</param>
  140. /// <param name="key">The key.</param>
  141. /// <param name="userData">The user data.</param>
  142. /// <param name="cancellationToken">The cancellation token.</param>
  143. /// <returns>Task.</returns>
  144. public async Task PersistUserData(Guid userId, string key, UserItemData userData, CancellationToken cancellationToken)
  145. {
  146. cancellationToken.ThrowIfCancellationRequested();
  147. var serialized = _jsonSerializer.SerializeToBytes(userData);
  148. cancellationToken.ThrowIfCancellationRequested();
  149. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  150. SQLiteTransaction transaction = null;
  151. try
  152. {
  153. transaction = _connection.BeginTransaction();
  154. using (var cmd = _connection.CreateCommand())
  155. {
  156. cmd.CommandText = "replace into userdata (key, userId, data) values (@1, @2, @3)";
  157. cmd.AddParam("@1", key);
  158. cmd.AddParam("@2", userId);
  159. cmd.AddParam("@3", serialized);
  160. cmd.Transaction = transaction;
  161. await cmd.ExecuteNonQueryAsync(cancellationToken);
  162. }
  163. transaction.Commit();
  164. }
  165. catch (OperationCanceledException)
  166. {
  167. if (transaction != null)
  168. {
  169. transaction.Rollback();
  170. }
  171. throw;
  172. }
  173. catch (Exception e)
  174. {
  175. _logger.ErrorException("Failed to save user data:", e);
  176. if (transaction != null)
  177. {
  178. transaction.Rollback();
  179. }
  180. throw;
  181. }
  182. finally
  183. {
  184. if (transaction != null)
  185. {
  186. transaction.Dispose();
  187. }
  188. _writeLock.Release();
  189. }
  190. }
  191. /// <summary>
  192. /// Gets the user data.
  193. /// </summary>
  194. /// <param name="userId">The user id.</param>
  195. /// <param name="key">The key.</param>
  196. /// <returns>Task{UserItemData}.</returns>
  197. /// <exception cref="System.ArgumentNullException">
  198. /// userId
  199. /// or
  200. /// key
  201. /// </exception>
  202. public UserItemData GetUserData(Guid userId, string key)
  203. {
  204. if (userId == Guid.Empty)
  205. {
  206. throw new ArgumentNullException("userId");
  207. }
  208. if (string.IsNullOrEmpty(key))
  209. {
  210. throw new ArgumentNullException("key");
  211. }
  212. return _userData.GetOrAdd(GetInternalKey(userId, key), keyName => RetrieveUserData(userId, key));
  213. }
  214. /// <summary>
  215. /// Retrieves the user data.
  216. /// </summary>
  217. /// <param name="userId">The user id.</param>
  218. /// <param name="key">The key.</param>
  219. /// <returns>Task{UserItemData}.</returns>
  220. private UserItemData RetrieveUserData(Guid userId, string key)
  221. {
  222. using (var cmd = _connection.CreateCommand())
  223. {
  224. cmd.CommandText = "select data from userdata where key = @key and userId=@userId";
  225. var idParam = cmd.Parameters.Add("@key", DbType.String);
  226. idParam.Value = key;
  227. var userIdParam = cmd.Parameters.Add("@userId", DbType.Guid);
  228. userIdParam.Value = userId;
  229. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  230. {
  231. if (reader.Read())
  232. {
  233. using (var stream = reader.GetMemoryStream(0))
  234. {
  235. return _jsonSerializer.DeserializeFromStream<UserItemData>(stream);
  236. }
  237. }
  238. }
  239. return new UserItemData();
  240. }
  241. }
  242. /// <summary>
  243. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  244. /// </summary>
  245. public void Dispose()
  246. {
  247. Dispose(true);
  248. GC.SuppressFinalize(this);
  249. }
  250. private readonly object _disposeLock = new object();
  251. /// <summary>
  252. /// Releases unmanaged and - optionally - managed resources.
  253. /// </summary>
  254. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  255. protected virtual void Dispose(bool dispose)
  256. {
  257. if (dispose)
  258. {
  259. try
  260. {
  261. lock (_disposeLock)
  262. {
  263. if (_connection != null)
  264. {
  265. if (_connection.IsOpen())
  266. {
  267. _connection.Close();
  268. }
  269. _connection.Dispose();
  270. _connection = null;
  271. }
  272. }
  273. }
  274. catch (Exception ex)
  275. {
  276. _logger.ErrorException("Error disposing database", ex);
  277. }
  278. }
  279. }
  280. }
  281. }