Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.98 KB | None | 0 0
  1. using System;
  2. using System.Net;
  3. using System.Windows;
  4. using System.Windows.Controls;
  5. using System.Windows.Documents;
  6. using System.Windows.Ink;
  7. using System.Windows.Input;
  8. using System.Windows.Media;
  9. using System.Windows.Media.Animation;
  10. using System.Windows.Shapes;
  11. using Tv.nu.Lib.Api.Configuration;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Xml.Linq;
  15. using Tv.nu.Lib.Api.Helpers;
  16. using System.Linq;
  17.  
  18. namespace Tv.nu.Lib.Api
  19. {
  20.     public class ApiIntegrationHandler : IApiIntegrationHandler
  21.     {
  22.         #region Methods (Public)
  23.  
  24.         void IApiIntegrationHandler.GetChannels(Action<IEnumerable<Channel>> onSuccess, Action<string> onError)
  25.         {
  26.             string url = GetApiUrl("section/channels");
  27.             Uri uri = new Uri(url, UriKind.Absolute);
  28.             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
  29.             RequestState<IEnumerable<Channel>> requestState = new RequestState<IEnumerable<Channel>>(request, onError, onSuccess);
  30.  
  31.             request.BeginGetResponse(new AsyncCallback(result => {
  32.                 ParseResponseWith<IEnumerable<Channel>>(result, rootElement => {
  33.                     return ParseChannelList(rootElement);
  34.                 });
  35.             }), requestState);
  36.         }
  37.  
  38.         void IApiIntegrationHandler.GetChannelProgramListing(DateTime date, List<string> channels, Action<IEnumerable<ChannelProgramListing>> onSuccess, Action<string> onError)
  39.         {
  40.             string channelIdsString = String.Join("__", channels.ToArray());
  41.             string url = string.Format("{0}/listing/channels/{1}/media/1/image_format/sq__50/date/{2}",
  42.                 ApiConfiguration.API_BASEURL,
  43.                 channelIdsString,
  44.                 //The date needs a special format in order
  45.                 //to be accepted by the API.
  46.                 GetFormattedDateString(date));
  47.             Uri uri = new Uri(url, UriKind.Absolute);
  48.  
  49.             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  50.  
  51.             RequestState<IEnumerable<ChannelProgramListing>> requestState = new RequestState<IEnumerable<ChannelProgramListing>>(request, onError, onSuccess);
  52.  
  53.             request.BeginGetResponse(new AsyncCallback(result => {
  54.                 ParseResponseWith<IEnumerable<ChannelProgramListing>>(result, rootElement => {
  55.                     return ParseChannelProgramListingList(rootElement);
  56.                 });
  57.             }), requestState);
  58.  
  59.         }
  60.  
  61.         void IApiIntegrationHandler.GetProgramDetails(string programId, Action<ProgramDetails> onSuccess, Action<string> onError)
  62.         {
  63.             string url = string.Format("{0}section/program/id/{1}",
  64.                 ApiConfiguration.API_BASEURL,
  65.                 programId);
  66.  
  67.             Uri uri = new Uri(url, UriKind.Absolute);
  68.  
  69.             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
  70.  
  71.             RequestState<ProgramDetails> requestState = new RequestState<ProgramDetails>(request, onError, onSuccess);
  72.  
  73.             request.BeginGetResponse(new AsyncCallback(result => {
  74.                 ParseResponseWith<ProgramDetails>(result, rootElement =>{
  75.                     return ParseProgramDetailsList(rootElement);
  76.                 });
  77.             }), requestState);
  78.  
  79.         }
  80.  
  81.         #endregion
  82.  
  83.         #region Methods (Private)
  84.  
  85.         private void ParseResponseWith<T>(IAsyncResult result, Func<XElement, T> parseMethod)
  86.         {
  87.             RequestState<T> state = (RequestState<T>)result.AsyncState;
  88.             string responseText;
  89.  
  90.             try
  91.             {
  92.                 responseText = GetResponseText(result, state);
  93.             }
  94.             catch
  95.             {
  96.                 state.OnError(ApiConfiguration.COMMUNICATION_ERROR_TEXT);
  97.                 return;
  98.             }
  99.  
  100.             try
  101.             {
  102.                 XElement root = XElement.Parse(responseText);
  103.                 T parsedData = parseMethod(root);
  104.                 state.OnSuccess(parsedData);
  105.             }
  106.             catch
  107.             {
  108.                 state.OnError(ApiConfiguration.PARSE_ERROR_TEXT);
  109.             }
  110.         }
  111.  
  112.         private static string GetResponseText<T>(IAsyncResult result, RequestState<T> state)
  113.         {
  114.             using (HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(result))
  115.             {
  116.                 using (Stream responseStream = response.GetResponseStream())
  117.                 {
  118.                     using (StreamReader reader = new StreamReader(responseStream))
  119.                     {
  120.                         return reader.ReadToEnd();
  121.                     }
  122.                 }
  123.             }
  124.         }
  125.  
  126.         private static string GetApiUrl(string section)
  127.         {
  128.             return String.Concat(ApiConfiguration.API_BASEURL, section);
  129.         }
  130.        
  131.         /// <summary>
  132.         /// Parses and combines the supplied elements to a ProgramInformation
  133.         /// </summary>
  134.         /// <param name="channel"></param>
  135.         /// <param name="program"></param>
  136.         /// <returns></returns>
  137.         private static ProgramDetails ParseProgramDetails(XElement channel, XElement program)
  138.         {
  139.             ProgramDetails pi = new ProgramDetails
  140.             {
  141.                 Channel = ParseChannel(channel)
  142.             };
  143.             if (program.Attribute("description") != null)
  144.                 pi.Description = program.Attribute("description").Value;
  145.             if (program.Attribute("title") != null)
  146.                 pi.Title = program.Attribute("title").Value;
  147.             if (program.Attribute("startTime") != null)
  148.                 pi.StartTime = program.Attribute("startTime").Value;
  149.             if (program.Attribute("endTime") != null)
  150.                 pi.EndTime = program.Attribute("endTime").Value;
  151.             if (program.Attribute("image") != null)
  152.                 pi.ImageUrl = program.Attribute("image").Value;
  153.             if (program.Attribute("imdbRating") != null)
  154.                 pi.ImdbRating = program.Attribute("imdbRating").Value;
  155.             if (program.Attribute("season") != null)
  156.                 pi.Season = program.Attribute("season").Value;
  157.             if (program.Attribute("episode") != null)
  158.                 pi.Episode = program.Attribute("episode").Value;
  159.             return pi;
  160.         }
  161.  
  162.         /// <summary>
  163.         /// Converts the supplied date to a string that is
  164.         /// accepted by the API
  165.         /// </summary>
  166.         /// <param name="date"></param>
  167.         /// <returns></returns>
  168.         private object GetFormattedDateString(DateTime date)
  169.         {
  170.             return date.Year + "-" + date.Month.ToString("00") + "-" + date.Day.ToString("00");
  171.         }
  172.  
  173.         /// <summary>
  174.         /// Parses the supplied XElement to a Channel
  175.         /// </summary>
  176.         /// <param name="p"></param>
  177.         /// <returns></returns>
  178.         private static Channel ParseChannel(XElement p)
  179.         {
  180.             string logoImageUrl = string.Format(ApiConfiguration.CHANNEL_LOGO_URL_FORMAT, p.Attribute("logo").Value);
  181.  
  182.             return new Channel
  183.             {
  184.                 Title = p.Attribute("title").Value,
  185.                 LogoImageUrl = logoImageUrl,
  186.                 SystemName = p.Attribute("systemname").Value
  187.             };
  188.         }
  189.  
  190.         /// <summary>
  191.         /// Parses the supplied XElement to a Program
  192.         /// </summary>
  193.         /// <param name="q"></param>
  194.         /// <returns></returns>
  195.         private static Program ParseProgram(XElement q)
  196.         {
  197.             Program p = new Program
  198.             {
  199.                 Title = q.Attribute("title").Value,
  200.                 StartTime = q.Attribute("startTime").Value,
  201.                 StartDate = DateTimeHelpers.UnixTimeToDateTime(q.Attribute("startTimestamp").Value),
  202.                 EndDate = DateTimeHelpers.UnixTimeToDateTime(q.Attribute("endTimestamp").Value),
  203.                 IsCurrent = q.Attribute("isCurrent").Value == "1",
  204.                 Id = q.Attribute("id").Value
  205.             };
  206.             if (q.Attribute("image") != null)
  207.                 p.ImageUrl = q.Attribute("image").Value;
  208.             return p;
  209.  
  210.         }
  211.  
  212.         private static IEnumerable<ChannelProgramListing> ParseChannelProgramListingList(XElement rootElement)
  213.         {
  214.             return rootElement.Descendants("channel").Select(p =>
  215.             {
  216.                 return new ChannelProgramListing
  217.                 {
  218.                     Channel = ParseChannel(p),
  219.                     Programs = p.Descendants("program").Select(q =>
  220.                     {
  221.                         return ParseProgram(q);
  222.                     })
  223.                     .ToList()
  224.                 };
  225.             });
  226.         }
  227.  
  228.         private static IEnumerable<Channel> ParseChannelList(XElement rootElement)
  229.         {
  230.             return rootElement.Descendants("channel").Select(p =>
  231.             {
  232.                 return ParseChannel(p);
  233.             });
  234.         }
  235.  
  236.         private static ProgramDetails ParseProgramDetailsList(XElement rootElement)
  237.         {
  238.             return rootElement.Descendants("channel").Select(channel =>
  239.             {
  240.                 return channel.Descendants("program").Select(program =>
  241.                 {
  242.                     return ParseProgramDetails(channel, program);
  243.                 }).SingleOrDefault();
  244.             }).SingleOrDefault();
  245.         }
  246.  
  247.         #endregion
  248.  
  249.         #region Private classes
  250.  
  251.         private class RequestState<T> {
  252.             public readonly HttpWebRequest Request;
  253.             public readonly Action<string> OnError;
  254.             public readonly Action<T> OnSuccess;
  255.  
  256.             public RequestState(HttpWebRequest request, Action<string> onError, Action<T> onSuccess)
  257.             {
  258.                 this.Request = request;
  259.                 this.OnError = onError;
  260.                 this.OnSuccess = onSuccess;
  261.             }
  262.         }
  263.  
  264.         #endregion
  265.     }
  266. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement