NewsEntryPoint.cs 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. using MediaBrowser.Common.Configuration;
  2. using MediaBrowser.Common.Extensions;
  3. using MediaBrowser.Common.Net;
  4. using MediaBrowser.Controller.Library;
  5. using MediaBrowser.Controller.Notifications;
  6. using MediaBrowser.Controller.Plugins;
  7. using MediaBrowser.Model.Logging;
  8. using MediaBrowser.Model.News;
  9. using MediaBrowser.Model.Notifications;
  10. using MediaBrowser.Model.Serialization;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Threading;
  16. using System.Threading.Tasks;
  17. using System.Xml;
  18. using MediaBrowser.Common.IO;
  19. using MediaBrowser.Controller.IO;
  20. using MediaBrowser.Model.IO;
  21. using MediaBrowser.Server.Implementations.Threading;
  22. namespace MediaBrowser.Server.Implementations.News
  23. {
  24. public class NewsEntryPoint : IServerEntryPoint
  25. {
  26. private PeriodicTimer _timer;
  27. private readonly IHttpClient _httpClient;
  28. private readonly IApplicationPaths _appPaths;
  29. private readonly IFileSystem _fileSystem;
  30. private readonly ILogger _logger;
  31. private readonly IJsonSerializer _json;
  32. private readonly INotificationManager _notifications;
  33. private readonly IUserManager _userManager;
  34. private readonly TimeSpan _frequency = TimeSpan.FromHours(24);
  35. public NewsEntryPoint(IHttpClient httpClient, IApplicationPaths appPaths, IFileSystem fileSystem, ILogger logger, IJsonSerializer json, INotificationManager notifications, IUserManager userManager)
  36. {
  37. _httpClient = httpClient;
  38. _appPaths = appPaths;
  39. _fileSystem = fileSystem;
  40. _logger = logger;
  41. _json = json;
  42. _notifications = notifications;
  43. _userManager = userManager;
  44. }
  45. public void Run()
  46. {
  47. _timer = new PeriodicTimer(OnTimerFired, null, TimeSpan.FromMilliseconds(500), _frequency);
  48. }
  49. /// <summary>
  50. /// Called when [timer fired].
  51. /// </summary>
  52. /// <param name="state">The state.</param>
  53. private async void OnTimerFired(object state)
  54. {
  55. var path = Path.Combine(_appPaths.CachePath, "news.json");
  56. try
  57. {
  58. await DownloadNews(path).ConfigureAwait(false);
  59. }
  60. catch (Exception ex)
  61. {
  62. _logger.ErrorException("Error downloading news", ex);
  63. }
  64. }
  65. private async Task DownloadNews(string path)
  66. {
  67. DateTime? lastUpdate = null;
  68. if (_fileSystem.FileExists(path))
  69. {
  70. lastUpdate = _fileSystem.GetLastWriteTimeUtc(path);
  71. }
  72. var requestOptions = new HttpRequestOptions
  73. {
  74. Url = "http://emby.media/community/index.php?/blog/rss/1-media-browser-developers-blog",
  75. Progress = new Progress<double>(),
  76. UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.42 Safari/537.36",
  77. BufferContent = false
  78. };
  79. using (var stream = await _httpClient.Get(requestOptions).ConfigureAwait(false))
  80. {
  81. var doc = new XmlDocument();
  82. doc.Load(stream);
  83. var news = ParseRssItems(doc).ToList();
  84. _json.SerializeToFile(news, path);
  85. await CreateNotifications(news, lastUpdate, CancellationToken.None).ConfigureAwait(false);
  86. }
  87. }
  88. private Task CreateNotifications(List<NewsItem> items, DateTime? lastUpdate, CancellationToken cancellationToken)
  89. {
  90. if (lastUpdate.HasValue)
  91. {
  92. items = items.Where(i => i.Date.ToUniversalTime() >= lastUpdate.Value)
  93. .ToList();
  94. }
  95. var tasks = items.Select(i => _notifications.SendNotification(new NotificationRequest
  96. {
  97. Date = i.Date,
  98. Name = i.Title,
  99. Description = i.Description,
  100. Url = i.Link,
  101. UserIds = _userManager.Users.Select(u => u.Id.ToString("N")).ToList()
  102. }, cancellationToken));
  103. return Task.WhenAll(tasks);
  104. }
  105. private IEnumerable<NewsItem> ParseRssItems(XmlDocument xmlDoc)
  106. {
  107. var nodes = xmlDoc.SelectNodes("rss/channel/item");
  108. if (nodes != null)
  109. {
  110. foreach (XmlNode node in nodes)
  111. {
  112. var newsItem = new NewsItem();
  113. newsItem.Title = ParseDocElements(node, "title");
  114. newsItem.DescriptionHtml = ParseDocElements(node, "description");
  115. newsItem.Description = newsItem.DescriptionHtml.StripHtml();
  116. newsItem.Link = ParseDocElements(node, "link");
  117. var date = ParseDocElements(node, "pubDate");
  118. DateTime parsedDate;
  119. if (DateTime.TryParse(date, out parsedDate))
  120. {
  121. newsItem.Date = parsedDate;
  122. }
  123. yield return newsItem;
  124. }
  125. }
  126. }
  127. private string ParseDocElements(XmlNode parent, string xPath)
  128. {
  129. var node = parent.SelectSingleNode(xPath);
  130. return node != null ? node.InnerText : string.Empty;
  131. }
  132. public void Dispose()
  133. {
  134. if (_timer != null)
  135. {
  136. _timer.Dispose();
  137. _timer = null;
  138. }
  139. }
  140. }
  141. }