SqliteNotificationsRepository.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. using MediaBrowser.Controller.Notifications;
  2. using MediaBrowser.Model.Logging;
  3. using MediaBrowser.Model.Notifications;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Linq;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10. namespace MediaBrowser.Server.Implementations.Persistence
  11. {
  12. public class SqliteNotificationsRepository : INotificationsRepository
  13. {
  14. private readonly IDbConnection _connection;
  15. private readonly ILogger _logger;
  16. private readonly SemaphoreSlim _writeLock = new SemaphoreSlim(1, 1);
  17. public SqliteNotificationsRepository(IDbConnection connection, ILogManager logManager)
  18. {
  19. _connection = connection;
  20. _logger = logManager.GetLogger(GetType().Name);
  21. }
  22. public event EventHandler<NotificationUpdateEventArgs> NotificationAdded;
  23. public event EventHandler<NotificationReadEventArgs> NotificationsMarkedRead;
  24. public event EventHandler<NotificationUpdateEventArgs> NotificationUpdated;
  25. private IDbCommand _replaceNotificationCommand;
  26. private IDbCommand _markReadCommand;
  27. public void Initialize()
  28. {
  29. string[] queries = {
  30. "create table if not exists Notifications (Id GUID NOT NULL, UserId GUID NOT NULL, Date DATETIME NOT NULL, Name TEXT NOT NULL, Description TEXT, Url TEXT, Level TEXT NOT NULL, IsRead BOOLEAN NOT NULL, Category TEXT NOT NULL, RelatedId TEXT, PRIMARY KEY (Id, UserId))",
  31. "create index if not exists idx_Notifications on Notifications(Id, UserId)",
  32. //pragmas
  33. "pragma temp_store = memory"
  34. };
  35. _connection.RunQueries(queries, _logger);
  36. PrepareStatements();
  37. }
  38. private void PrepareStatements()
  39. {
  40. _replaceNotificationCommand = _connection.CreateCommand();
  41. _replaceNotificationCommand.CommandText = "replace into Notifications (Id, UserId, Date, Name, Description, Url, Level, IsRead, Category, RelatedId) values (@Id, @UserId, @Date, @Name, @Description, @Url, @Level, @IsRead, @Category, @RelatedId)";
  42. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Id");
  43. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@UserId");
  44. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Date");
  45. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Name");
  46. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Description");
  47. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Url");
  48. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Level");
  49. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@IsRead");
  50. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@Category");
  51. _replaceNotificationCommand.Parameters.Add(_replaceNotificationCommand, "@RelatedId");
  52. _markReadCommand = _connection.CreateCommand();
  53. _markReadCommand.CommandText = "update Notifications set IsRead=@IsRead where Id=@Id and UserId=@UserId";
  54. _markReadCommand.Parameters.Add(_replaceNotificationCommand, "@UserId");
  55. _markReadCommand.Parameters.Add(_replaceNotificationCommand, "@IsRead");
  56. _markReadCommand.Parameters.Add(_replaceNotificationCommand, "@Id");
  57. }
  58. /// <summary>
  59. /// Gets the notifications.
  60. /// </summary>
  61. /// <param name="query">The query.</param>
  62. /// <returns>NotificationResult.</returns>
  63. public NotificationResult GetNotifications(NotificationQuery query)
  64. {
  65. var result = new NotificationResult();
  66. using (var cmd = _connection.CreateCommand())
  67. {
  68. var clauses = new List<string>();
  69. if (query.IsRead.HasValue)
  70. {
  71. clauses.Add("IsRead=@IsRead");
  72. cmd.Parameters.Add(cmd, "@IsRead", DbType.Boolean).Value = query.IsRead.Value;
  73. }
  74. clauses.Add("UserId=@UserId");
  75. cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = new Guid(query.UserId);
  76. var whereClause = " where " + string.Join(" And ", clauses.ToArray());
  77. cmd.CommandText = string.Format("select count(Id) from Notifications{0};select Id,UserId,Date,Name,Description,Url,Level,IsRead,Category,RelatedId from Notifications{0} order by IsRead asc, Date desc", whereClause);
  78. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
  79. {
  80. if (reader.Read())
  81. {
  82. result.TotalRecordCount = reader.GetInt32(0);
  83. }
  84. if (reader.NextResult())
  85. {
  86. var notifications = GetNotifications(reader);
  87. if (query.StartIndex.HasValue)
  88. {
  89. notifications = notifications.Skip(query.StartIndex.Value);
  90. }
  91. if (query.Limit.HasValue)
  92. {
  93. notifications = notifications.Take(query.Limit.Value);
  94. }
  95. result.Notifications = notifications.ToArray();
  96. }
  97. }
  98. return result;
  99. }
  100. }
  101. public NotificationsSummary GetNotificationsSummary(Guid userId)
  102. {
  103. var result = new NotificationsSummary();
  104. using (var cmd = _connection.CreateCommand())
  105. {
  106. cmd.CommandText = "select Level from Notifications where UserId=@UserId and IsRead=@IsRead";
  107. cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = userId;
  108. cmd.Parameters.Add(cmd, "@IsRead", DbType.Boolean).Value = false;
  109. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess))
  110. {
  111. var levels = new List<NotificationLevel>();
  112. while (reader.Read())
  113. {
  114. levels.Add(GetLevel(reader, 0));
  115. }
  116. result.UnreadCount = levels.Count;
  117. if (levels.Count > 0)
  118. {
  119. result.MaxUnreadNotificationLevel = levels.Max();
  120. }
  121. }
  122. return result;
  123. }
  124. }
  125. /// <summary>
  126. /// Gets the notifications.
  127. /// </summary>
  128. /// <param name="reader">The reader.</param>
  129. /// <returns>IEnumerable{Notification}.</returns>
  130. private IEnumerable<Notification> GetNotifications(IDataReader reader)
  131. {
  132. while (reader.Read())
  133. {
  134. yield return GetNotification(reader);
  135. }
  136. }
  137. private Notification GetNotification(IDataReader reader)
  138. {
  139. var notification = new Notification
  140. {
  141. Id = reader.GetGuid(0),
  142. UserId = reader.GetGuid(1),
  143. Date = reader.GetDateTime(2).ToUniversalTime(),
  144. Name = reader.GetString(3)
  145. };
  146. if (!reader.IsDBNull(4))
  147. {
  148. notification.Description = reader.GetString(4);
  149. }
  150. if (!reader.IsDBNull(5))
  151. {
  152. notification.Url = reader.GetString(5);
  153. }
  154. notification.Level = GetLevel(reader, 6);
  155. notification.IsRead = reader.GetBoolean(7);
  156. notification.Category = reader.GetString(8);
  157. if (!reader.IsDBNull(9))
  158. {
  159. notification.RelatedId = reader.GetString(9);
  160. }
  161. return notification;
  162. }
  163. /// <summary>
  164. /// Gets the notification.
  165. /// </summary>
  166. /// <param name="id">The id.</param>
  167. /// <param name="userId">The user id.</param>
  168. /// <returns>Notification.</returns>
  169. /// <exception cref="System.ArgumentNullException">
  170. /// id
  171. /// or
  172. /// userId
  173. /// </exception>
  174. public Notification GetNotification(Guid id, Guid userId)
  175. {
  176. if (id == Guid.Empty)
  177. {
  178. throw new ArgumentNullException("id");
  179. }
  180. if (userId == Guid.Empty)
  181. {
  182. throw new ArgumentNullException("userId");
  183. }
  184. using (var cmd = _connection.CreateCommand())
  185. {
  186. cmd.CommandText = "select Id,UserId,Date,Name,Description,Url,Level,IsRead,Category,RelatedId where Id=@Id And UserId = @UserId";
  187. cmd.Parameters.Add(cmd, "@Id", DbType.Guid).Value = id;
  188. cmd.Parameters.Add(cmd, "@UserId", DbType.Guid).Value = userId;
  189. using (var reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess | CommandBehavior.SingleResult | CommandBehavior.SingleRow))
  190. {
  191. if (reader.Read())
  192. {
  193. return GetNotification(reader);
  194. }
  195. }
  196. return null;
  197. }
  198. }
  199. /// <summary>
  200. /// Gets the level.
  201. /// </summary>
  202. /// <param name="reader">The reader.</param>
  203. /// <param name="index">The index.</param>
  204. /// <returns>NotificationLevel.</returns>
  205. private NotificationLevel GetLevel(IDataReader reader, int index)
  206. {
  207. NotificationLevel level;
  208. var val = reader.GetString(index);
  209. Enum.TryParse(val, true, out level);
  210. return level;
  211. }
  212. /// <summary>
  213. /// Adds the notification.
  214. /// </summary>
  215. /// <param name="notification">The notification.</param>
  216. /// <param name="cancellationToken">The cancellation token.</param>
  217. /// <returns>Task.</returns>
  218. public async Task AddNotification(Notification notification, CancellationToken cancellationToken)
  219. {
  220. await ReplaceNotification(notification, cancellationToken).ConfigureAwait(false);
  221. if (NotificationAdded != null)
  222. {
  223. try
  224. {
  225. NotificationAdded(this, new NotificationUpdateEventArgs
  226. {
  227. Notification = notification
  228. });
  229. }
  230. catch (Exception ex)
  231. {
  232. _logger.ErrorException("Error in NotificationAdded event handler", ex);
  233. }
  234. }
  235. }
  236. /// <summary>
  237. /// Updates the notification.
  238. /// </summary>
  239. /// <param name="notification">The notification.</param>
  240. /// <param name="cancellationToken">The cancellation token.</param>
  241. /// <returns>Task.</returns>
  242. public async Task UpdateNotification(Notification notification, CancellationToken cancellationToken)
  243. {
  244. await ReplaceNotification(notification, cancellationToken).ConfigureAwait(false);
  245. if (NotificationUpdated != null)
  246. {
  247. try
  248. {
  249. NotificationUpdated(this, new NotificationUpdateEventArgs
  250. {
  251. Notification = notification
  252. });
  253. }
  254. catch (Exception ex)
  255. {
  256. _logger.ErrorException("Error in NotificationUpdated event handler", ex);
  257. }
  258. }
  259. }
  260. /// <summary>
  261. /// Replaces the notification.
  262. /// </summary>
  263. /// <param name="notification">The notification.</param>
  264. /// <param name="cancellationToken">The cancellation token.</param>
  265. /// <returns>Task.</returns>
  266. private async Task ReplaceNotification(Notification notification, CancellationToken cancellationToken)
  267. {
  268. if (notification.Id == Guid.Empty)
  269. {
  270. throw new ArgumentException("The notification must have an id");
  271. }
  272. if (notification.UserId == Guid.Empty)
  273. {
  274. throw new ArgumentException("The notification must have a user id");
  275. }
  276. cancellationToken.ThrowIfCancellationRequested();
  277. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  278. IDbTransaction transaction = null;
  279. try
  280. {
  281. transaction = _connection.BeginTransaction();
  282. _replaceNotificationCommand.GetParameter(0).Value = notification.Id;
  283. _replaceNotificationCommand.GetParameter(1).Value = notification.UserId;
  284. _replaceNotificationCommand.GetParameter(2).Value = notification.Date.ToUniversalTime();
  285. _replaceNotificationCommand.GetParameter(3).Value = notification.Name;
  286. _replaceNotificationCommand.GetParameter(4).Value = notification.Description;
  287. _replaceNotificationCommand.GetParameter(5).Value = notification.Url;
  288. _replaceNotificationCommand.GetParameter(6).Value = notification.Level.ToString();
  289. _replaceNotificationCommand.GetParameter(7).Value = notification.IsRead;
  290. _replaceNotificationCommand.GetParameter(8).Value = notification.Category;
  291. _replaceNotificationCommand.GetParameter(9).Value = notification.RelatedId;
  292. _replaceNotificationCommand.Transaction = transaction;
  293. _replaceNotificationCommand.ExecuteNonQuery();
  294. transaction.Commit();
  295. }
  296. catch (OperationCanceledException)
  297. {
  298. if (transaction != null)
  299. {
  300. transaction.Rollback();
  301. }
  302. throw;
  303. }
  304. catch (Exception e)
  305. {
  306. _logger.ErrorException("Failed to save notification:", e);
  307. if (transaction != null)
  308. {
  309. transaction.Rollback();
  310. }
  311. throw;
  312. }
  313. finally
  314. {
  315. if (transaction != null)
  316. {
  317. transaction.Dispose();
  318. }
  319. _writeLock.Release();
  320. }
  321. }
  322. /// <summary>
  323. /// Marks the read.
  324. /// </summary>
  325. /// <param name="notificationIdList">The notification id list.</param>
  326. /// <param name="userId">The user id.</param>
  327. /// <param name="isRead">if set to <c>true</c> [is read].</param>
  328. /// <param name="cancellationToken">The cancellation token.</param>
  329. /// <returns>Task.</returns>
  330. public async Task MarkRead(IEnumerable<Guid> notificationIdList, Guid userId, bool isRead, CancellationToken cancellationToken)
  331. {
  332. var idArray = notificationIdList.ToArray();
  333. await MarkReadInternal(idArray, userId, isRead, cancellationToken).ConfigureAwait(false);
  334. if (NotificationsMarkedRead != null)
  335. {
  336. try
  337. {
  338. NotificationsMarkedRead(this, new NotificationReadEventArgs
  339. {
  340. IdList = idArray.ToArray(),
  341. IsRead = isRead,
  342. UserId = userId
  343. });
  344. }
  345. catch (Exception ex)
  346. {
  347. _logger.ErrorException("Error in NotificationsMarkedRead event handler", ex);
  348. }
  349. }
  350. }
  351. private async Task MarkReadInternal(IEnumerable<Guid> notificationIdList, Guid userId, bool isRead, CancellationToken cancellationToken)
  352. {
  353. cancellationToken.ThrowIfCancellationRequested();
  354. await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
  355. IDbTransaction transaction = null;
  356. try
  357. {
  358. cancellationToken.ThrowIfCancellationRequested();
  359. transaction = _connection.BeginTransaction();
  360. _markReadCommand.GetParameter(0).Value = userId;
  361. _markReadCommand.GetParameter(1).Value = isRead;
  362. foreach (var id in notificationIdList)
  363. {
  364. _markReadCommand.GetParameter(2).Value = id;
  365. _markReadCommand.Transaction = transaction;
  366. _markReadCommand.ExecuteNonQuery();
  367. }
  368. transaction.Commit();
  369. }
  370. catch (OperationCanceledException)
  371. {
  372. if (transaction != null)
  373. {
  374. transaction.Rollback();
  375. }
  376. throw;
  377. }
  378. catch (Exception e)
  379. {
  380. _logger.ErrorException("Failed to save notification:", e);
  381. if (transaction != null)
  382. {
  383. transaction.Rollback();
  384. }
  385. throw;
  386. }
  387. finally
  388. {
  389. if (transaction != null)
  390. {
  391. transaction.Dispose();
  392. }
  393. _writeLock.Release();
  394. }
  395. }
  396. }
  397. }