2
0

NewsEntryPoint.cs 5.4 KB

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