SqliteNotificationsRepository.cs 18 KB

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