SqliteNotificationsRepository.cs 18 KB

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