SqliteNotificationsRepository.cs 17 KB

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