SqliteUserDataRepository.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  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_v2.db");
  69. _connection = await SqliteExtensions.ConnectToDb(dbFile).ConfigureAwait(false);
  70. string[] queries = {
  71. "create table if not exists userdata (key nvarchar, userId GUID, rating float null, played bit, playCount int, isFavorite bit, playbackPositionTicks bigint, lastPlayedDate datetime null)",
  72. "create unique index if not exists userdataindex on userdata (key, userId)",
  73. //pragmas
  74. "pragma temp_store = memory"
  75. };
  76. _connection.RunQueries(queries, _logger);
  77. var oldFile = Path.Combine(_appPaths.DataPath, "userdata.db");
  78. if (File.Exists(oldFile))
  79. {
  80. await UserDataMigration.Migrate(oldFile, _connection, _logger, _jsonSerializer).ConfigureAwait(false);
  81. }
  82. }
  83. /// <summary>
  84. /// Saves the user data.
  85. /// </summary>
  86. /// <param name="userId">The user id.</param>
  87. /// <param name="key">The key.</param>
  88. /// <param name="userData">The user data.</param>
  89. /// <param name="cancellationToken">The cancellation token.</param>
  90. /// <returns>Task.</returns>
  91. /// <exception cref="System.ArgumentNullException">userData
  92. /// or
  93. /// cancellationToken
  94. /// or
  95. /// userId
  96. /// or
  97. /// userDataId</exception>
  98. public async Task SaveUserData(Guid userId, string key, UserItemData userData, CancellationToken cancellationToken)
  99. {
  100. if (userData == null)
  101. {
  102. throw new ArgumentNullException("userData");
  103. }
  104. if (cancellationToken == null)
  105. {
  106. throw new ArgumentNullException("cancellationToken");
  107. }
  108. if (userId == Guid.Empty)
  109. {
  110. throw new ArgumentNullException("userId");
  111. }
  112. if (string.IsNullOrEmpty(key))
  113. {
  114. throw new ArgumentNullException("key");
  115. }
  116. cancellationToken.ThrowIfCancellationRequested();
  117. try
  118. {
  119. await PersistUserData(userId, key, userData, cancellationToken).ConfigureAwait(false);
  120. var newValue = userData;
  121. // Once it succeeds, put it into the dictionary to make it available to everyone else
  122. _userData.AddOrUpdate(GetInternalKey(userId, key), newValue, delegate { return newValue; });
  123. }
  124. catch (Exception ex)
  125. {
  126. _logger.ErrorException("Error saving user data", ex);
  127. throw;
  128. }
  129. }
  130. /// <summary>
  131. /// Gets the internal key.
  132. /// </summary>
  133. /// <param name="userId">The user id.</param>
  134. /// <param name="key">The key.</param>
  135. /// <returns>System.String.</returns>
  136. private string GetInternalKey(Guid userId, string key)
  137. {
  138. return userId + key;
  139. }
  140. /// <summary>
  141. /// Persists the user data.
  142. /// </summary>
  143. /// <param name="userId">The user id.</param>
  144. /// <param name="key">The key.</param>
  145. /// <param name="userData">The user data.</param>
  146. /// <param name="cancellationToken">The cancellation token.</param>
  147. /// <returns>Task.</returns>
  148. public async Task PersistUserData(Guid userId, string key, UserItemData userData, CancellationToken cancellationToken)
  149. {
  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, rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate) values (@key, @userId, @rating,@played,@playCount,@isFavorite,@playbackPositionTicks,@lastPlayedDate)";
  159. cmd.AddParam("@key", key);
  160. cmd.AddParam("@userId", userId);
  161. cmd.AddParam("@rating", userData.Rating);
  162. cmd.AddParam("@played", userData.Played);
  163. cmd.AddParam("@playCount", userData.PlayCount);
  164. cmd.AddParam("@isFavorite", userData.IsFavorite);
  165. cmd.AddParam("@playbackPositionTicks", userData.PlaybackPositionTicks);
  166. cmd.AddParam("@lastPlayedDate", userData.LastPlayedDate);
  167. cmd.Transaction = transaction;
  168. await cmd.ExecuteNonQueryAsync(cancellationToken);
  169. }
  170. transaction.Commit();
  171. }
  172. catch (OperationCanceledException)
  173. {
  174. if (transaction != null)
  175. {
  176. transaction.Rollback();
  177. }
  178. throw;
  179. }
  180. catch (Exception e)
  181. {
  182. _logger.ErrorException("Failed to save user data:", e);
  183. if (transaction != null)
  184. {
  185. transaction.Rollback();
  186. }
  187. throw;
  188. }
  189. finally
  190. {
  191. if (transaction != null)
  192. {
  193. transaction.Dispose();
  194. }
  195. _writeLock.Release();
  196. }
  197. }
  198. /// <summary>
  199. /// Gets the user data.
  200. /// </summary>
  201. /// <param name="userId">The user id.</param>
  202. /// <param name="key">The key.</param>
  203. /// <returns>Task{UserItemData}.</returns>
  204. /// <exception cref="System.ArgumentNullException">
  205. /// userId
  206. /// or
  207. /// key
  208. /// </exception>
  209. public UserItemData GetUserData(Guid userId, string key)
  210. {
  211. if (userId == Guid.Empty)
  212. {
  213. throw new ArgumentNullException("userId");
  214. }
  215. if (string.IsNullOrEmpty(key))
  216. {
  217. throw new ArgumentNullException("key");
  218. }
  219. return _userData.GetOrAdd(GetInternalKey(userId, key), keyName => RetrieveUserData(userId, key));
  220. }
  221. /// <summary>
  222. /// Retrieves the user data.
  223. /// </summary>
  224. /// <param name="userId">The user id.</param>
  225. /// <param name="key">The key.</param>
  226. /// <returns>Task{UserItemData}.</returns>
  227. private UserItemData RetrieveUserData(Guid userId, string key)
  228. {
  229. using (var cmd = _connection.CreateCommand())
  230. {
  231. cmd.CommandText = "select rating,played,playCount,isFavorite,playbackPositionTicks,lastPlayedDate from userdata where key = @key and userId=@userId";
  232. var idParam = cmd.Parameters.Add("@key", DbType.String);
  233. idParam.Value = key;
  234. var userIdParam = cmd.Parameters.Add("@userId", DbType.Guid);
  235. userIdParam.Value = userId;
  236. var userData = new UserItemData
  237. {
  238. UserId = userId,
  239. Key = key
  240. };
  241. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  242. {
  243. if (reader.Read())
  244. {
  245. if (!reader.IsDBNull(0))
  246. {
  247. userData.Rating = reader.GetDouble(0);
  248. }
  249. userData.Played = reader.GetBoolean(1);
  250. userData.PlayCount = reader.GetInt32(2);
  251. userData.IsFavorite = reader.GetBoolean(3);
  252. userData.PlaybackPositionTicks = reader.GetInt64(4);
  253. if (!reader.IsDBNull(5))
  254. {
  255. userData.LastPlayedDate = reader.GetDateTime(5);
  256. }
  257. }
  258. }
  259. return userData;
  260. }
  261. }
  262. /// <summary>
  263. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  264. /// </summary>
  265. public void Dispose()
  266. {
  267. Dispose(true);
  268. GC.SuppressFinalize(this);
  269. }
  270. private readonly object _disposeLock = new object();
  271. /// <summary>
  272. /// Releases unmanaged and - optionally - managed resources.
  273. /// </summary>
  274. /// <param name="dispose"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  275. protected virtual void Dispose(bool dispose)
  276. {
  277. if (dispose)
  278. {
  279. try
  280. {
  281. lock (_disposeLock)
  282. {
  283. if (_connection != null)
  284. {
  285. if (_connection.IsOpen())
  286. {
  287. _connection.Close();
  288. }
  289. _connection.Dispose();
  290. _connection = null;
  291. }
  292. }
  293. }
  294. catch (Exception ex)
  295. {
  296. _logger.ErrorException("Error disposing database", ex);
  297. }
  298. }
  299. }
  300. }
  301. }