SQLiteUserDataRepository.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Persistence;
  4. using MediaBrowser.Model.Logging;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel.Composition;
  8. using System.Data;
  9. using System.IO;
  10. using System.Threading;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Server.Sqlite
  13. {
  14. /// <summary>
  15. /// Class SQLiteUserDataRepository
  16. /// </summary>
  17. [Export(typeof(IUserDataRepository))]
  18. public class SQLiteUserDataRepository : SqliteRepository, IUserDataRepository
  19. {
  20. /// <summary>
  21. /// The repository name
  22. /// </summary>
  23. public const string RepositoryName = "SQLite";
  24. /// <summary>
  25. /// Gets the name of the repository
  26. /// </summary>
  27. /// <value>The name.</value>
  28. public string Name
  29. {
  30. get
  31. {
  32. return RepositoryName;
  33. }
  34. }
  35. /// <summary>
  36. /// Initializes a new instance of the <see cref="SQLiteUserDataRepository" /> class.
  37. /// </summary>
  38. /// <param name="logger">The logger.</param>
  39. [ImportingConstructor]
  40. protected SQLiteUserDataRepository([Import("logger")] ILogger logger)
  41. : base(logger)
  42. {
  43. }
  44. /// <summary>
  45. /// Opens the connection to the database
  46. /// </summary>
  47. /// <returns>Task.</returns>
  48. public async Task Initialize()
  49. {
  50. var dbFile = Path.Combine(Kernel.Instance.ApplicationPaths.DataPath, "userdata.db");
  51. await ConnectToDB(dbFile).ConfigureAwait(false);
  52. string[] queries = {
  53. "create table if not exists user_data (item_id GUID, user_id GUID, data BLOB)",
  54. "create unique index if not exists idx_user_data on user_data (item_id, user_id)",
  55. "create table if not exists schema_version (table_name primary key, version)",
  56. //pragmas
  57. "pragma temp_store = memory"
  58. };
  59. RunQueries(queries);
  60. }
  61. /// <summary>
  62. /// Save the user specific data associated with an item in the repo
  63. /// </summary>
  64. /// <param name="item">The item.</param>
  65. /// <param name="cancellationToken">The cancellation token.</param>
  66. /// <returns>Task.</returns>
  67. /// <exception cref="System.ArgumentNullException">item</exception>
  68. public Task SaveUserData(BaseItem item, CancellationToken cancellationToken)
  69. {
  70. if (item == null)
  71. {
  72. throw new ArgumentNullException("item");
  73. }
  74. if (cancellationToken == null)
  75. {
  76. throw new ArgumentNullException("cancellationToken");
  77. }
  78. return Task.Run(() =>
  79. {
  80. cancellationToken.ThrowIfCancellationRequested();
  81. var cmd = connection.CreateCommand();
  82. cmd.CommandText = "delete from user_data where item_id = @guid";
  83. cmd.AddParam("@guid", item.UserDataId);
  84. QueueCommand(cmd);
  85. if (item.UserData != null)
  86. {
  87. foreach (var data in item.UserData)
  88. {
  89. cmd = connection.CreateCommand();
  90. cmd.CommandText = "insert into user_data (item_id, user_id, data) values (@1, @2, @3)";
  91. cmd.AddParam("@1", item.UserDataId);
  92. cmd.AddParam("@2", data.UserId);
  93. cmd.AddParam("@3", Kernel.Instance.ProtobufSerializer.SerializeToBytes(data));
  94. QueueCommand(cmd);
  95. }
  96. }
  97. });
  98. }
  99. /// <summary>
  100. /// Gets user data for an item
  101. /// </summary>
  102. /// <param name="item">The item.</param>
  103. /// <returns>IEnumerable{UserItemData}.</returns>
  104. /// <exception cref="System.ArgumentNullException">item</exception>
  105. public IEnumerable<UserItemData> RetrieveUserData(BaseItem item)
  106. {
  107. if (item == null)
  108. {
  109. throw new ArgumentNullException("item");
  110. }
  111. var cmd = connection.CreateCommand();
  112. cmd.CommandText = "select data from user_data where item_id = @guid";
  113. var guidParam = cmd.Parameters.Add("@guid", DbType.Guid);
  114. guidParam.Value = item.UserDataId;
  115. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult))
  116. {
  117. while (reader.Read())
  118. {
  119. using (var stream = GetStream(reader, 0))
  120. {
  121. var data = Kernel.Instance.ProtobufSerializer.DeserializeFromStream<UserItemData>(stream);
  122. if (data != null)
  123. {
  124. yield return data;
  125. }
  126. }
  127. }
  128. }
  129. }
  130. }
  131. }