You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FeedDataAccess.cs 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Xml.Linq;
  7. using Luticate2.Utils.Dbo.Result;
  8. using VDS.RDF;
  9. using WebApiWebSem.Dbo.Feed;
  10. namespace WebApiWebSem.DataAccess
  11. {
  12. public class FeedDataAccess
  13. {
  14. public LuResult<IList<FeedDbo>> Parse(string url)
  15. {
  16. try
  17. {
  18. using (var client = new HttpClient())
  19. {
  20. var request = new HttpRequestMessage(HttpMethod.Get, url);
  21. var responseTask = client.SendAsync(request);
  22. responseTask.Wait();
  23. using (var response = responseTask.Result)
  24. {
  25. var streamTask = response.Content.ReadAsStreamAsync();
  26. streamTask.Wait();
  27. using (var stream = streamTask.Result)
  28. {
  29. var doc = XDocument.Load(stream);
  30. var entries = from item in doc.Root.Descendants()
  31. .First(i => i.Name.LocalName == "channel")
  32. .Elements()
  33. .Where(i => i.Name.LocalName == "item")
  34. select new FeedDbo
  35. {
  36. Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
  37. Link = item.Elements().First(i => i.Name.LocalName == "link").Value,
  38. PublishDate = ParseDate(
  39. item.Elements().First(i => i.Name.LocalName == "pubDate").Value),
  40. Title = item.Elements().First(i => i.Name.LocalName == "title").Value
  41. };
  42. return LuResult<IList<FeedDbo>>.Ok(entries.ToList());
  43. }
  44. }
  45. }
  46. }
  47. catch (Exception e)
  48. {
  49. return LuResult<IList<FeedDbo>>.Error(LuStatus.BackendError, e, "Failed to read remote RSS feed");
  50. }
  51. }
  52. private DateTime ParseDate(string date)
  53. {
  54. DateTime result;
  55. if (DateTime.TryParse(date, out result))
  56. return result;
  57. return DateTime.MinValue;
  58. }
  59. }
  60. }