123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Xml.Linq;
- using Luticate2.Utils.Dbo.Result;
- using VDS.RDF;
- using WebApiWebSem.Dbo.Feed;
-
- namespace WebApiWebSem.DataAccess
- {
- public class FeedDataAccess
- {
- public LuResult<IList<FeedDbo>> Parse(string url)
- {
- try
- {
- using (var client = new HttpClient())
- {
- var request = new HttpRequestMessage(HttpMethod.Get, url);
-
- var responseTask = client.SendAsync(request);
- responseTask.Wait();
- using (var response = responseTask.Result)
- {
- var streamTask = response.Content.ReadAsStreamAsync();
- streamTask.Wait();
- using (var stream = streamTask.Result)
- {
- var doc = XDocument.Load(stream);
- var entries = from item in doc.Root.Descendants()
- .First(i => i.Name.LocalName == "channel")
- .Elements()
- .Where(i => i.Name.LocalName == "item")
- select new FeedDbo
- {
- Content = item.Elements().First(i => i.Name.LocalName == "description").Value,
- Link = item.Elements().First(i => i.Name.LocalName == "link").Value,
- PublishDate = ParseDate(
- item.Elements().First(i => i.Name.LocalName == "pubDate").Value),
- Title = item.Elements().First(i => i.Name.LocalName == "title").Value
- };
- return LuResult<IList<FeedDbo>>.Ok(entries.ToList());
- }
- }
- }
- }
- catch (Exception e)
- {
- return LuResult<IList<FeedDbo>>.Error(LuStatus.BackendError, e, "Failed to read remote RSS feed");
- }
- }
-
- private DateTime ParseDate(string date)
- {
- DateTime result;
- if (DateTime.TryParse(date, out result))
- return result;
- return DateTime.MinValue;
- }
- }
- }
|