SQLiteUserDataRepository.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. using MediaBrowser.Common.Kernel;
  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.Generic;
  8. using System.Data;
  9. using System.IO;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Server.Implementations.Sqlite
  13. {
  14. /// <summary>
  15. /// Class SQLiteUserDataRepository
  16. /// </summary>
  17. public class SQLiteUserDataRepository : SqliteRepository, IUserDataRepository
  18. {
  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. /// <summary>
  35. /// The _protobuf serializer
  36. /// </summary>
  37. private readonly IProtobufSerializer _protobufSerializer;
  38. /// <summary>
  39. /// The _app paths
  40. /// </summary>
  41. private readonly IApplicationPaths _appPaths;
  42. /// <summary>
  43. /// Initializes a new instance of the <see cref="SQLiteUserDataRepository" /> class.
  44. /// </summary>
  45. /// <param name="appPaths">The app paths.</param>
  46. /// <param name="protobufSerializer">The protobuf serializer.</param>
  47. /// <param name="logger">The logger.</param>
  48. /// <exception cref="System.ArgumentNullException">protobufSerializer</exception>
  49. public SQLiteUserDataRepository(IApplicationPaths appPaths, IProtobufSerializer protobufSerializer, ILogger logger)
  50. : base(logger)
  51. {
  52. if (protobufSerializer == null)
  53. {
  54. throw new ArgumentNullException("protobufSerializer");
  55. }
  56. if (appPaths == null)
  57. {
  58. throw new ArgumentNullException("appPaths");
  59. }
  60. _protobufSerializer = protobufSerializer;
  61. _appPaths = appPaths;
  62. }
  63. /// <summary>
  64. /// Opens the connection to the database
  65. /// </summary>
  66. /// <returns>Task.</returns>
  67. public async Task Initialize()
  68. {
  69. var dbFile = Path.Combine(_appPaths.DataPath, "userdata.db");
  70. await ConnectToDB(dbFile).ConfigureAwait(false);
  71. string[] queries = {
  72. "create table if not exists user_data (item_id GUID, user_id GUID, data BLOB)",
  73. "create unique index if not exists idx_user_data on user_data (item_id, user_id)",
  74. "create table if not exists schema_version (table_name primary key, version)",
  75. //pragmas
  76. "pragma temp_store = memory"
  77. };
  78. RunQueries(queries);
  79. }
  80. /// <summary>
  81. /// Save the user specific data associated with an item in the repo
  82. /// </summary>
  83. /// <param name="item">The item.</param>
  84. /// <param name="cancellationToken">The cancellation token.</param>
  85. /// <returns>Task.</returns>
  86. /// <exception cref="System.ArgumentNullException">item</exception>
  87. public Task SaveUserData(BaseItem item, CancellationToken cancellationToken)
  88. {
  89. if (item == null)
  90. {
  91. throw new ArgumentNullException("item");
  92. }
  93. if (cancellationToken == null)
  94. {
  95. throw new ArgumentNullException("cancellationToken");
  96. }
  97. return Task.Run(() =>
  98. {
  99. cancellationToken.ThrowIfCancellationRequested();
  100. var cmd = connection.CreateCommand();
  101. cmd.CommandText = "delete from user_data where item_id = @guid";
  102. cmd.AddParam("@guid", item.UserDataId);
  103. QueueCommand(cmd);
  104. if (item.UserData != null)
  105. {
  106. foreach (var data in item.UserData)
  107. {
  108. cmd = connection.CreateCommand();
  109. cmd.CommandText = "insert into user_data (item_id, user_id, data) values (@1, @2, @3)";
  110. cmd.AddParam("@1", item.UserDataId);
  111. cmd.AddParam("@2", data.UserId);
  112. cmd.AddParam("@3", _protobufSerializer.SerializeToBytes(data));
  113. QueueCommand(cmd);
  114. }
  115. }
  116. });
  117. }
  118. /// <summary>
  119. /// Gets user data for an item
  120. /// </summary>
  121. /// <param name="item">The item.</param>
  122. /// <returns>IEnumerable{UserItemData}.</returns>
  123. /// <exception cref="System.ArgumentNullException">item</exception>
  124. public IEnumerable<UserItemData> RetrieveUserData(BaseItem item)
  125. {
  126. if (item == null)
  127. {
  128. throw new ArgumentNullException("item");
  129. }
  130. var cmd = connection.CreateCommand();
  131. cmd.CommandText = "select data from user_data where item_id = @guid";
  132. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  133. guidParam.Value = item.UserDataId;
  134. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  135. {
  136. while (reader.Read())
  137. {
  138. using (var stream = GetStream(reader, 0))
  139. {
  140. var data = _protobufSerializer.DeserializeFromStream<UserItemData>(stream);
  141. if (data != null)
  142. {
  143. yield return data;
  144. }
  145. }
  146. }
  147. }
  148. }
  149. }
  150. }