Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Net;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Documents;
- using System.Windows.Ink;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Animation;
- using System.Windows.Shapes;
- using Tv.nu.Lib.Api.Configuration;
- using System.Collections.Generic;
- using System.IO;
- using System.Xml.Linq;
- using Tv.nu.Lib.Api.Helpers;
- using System.Linq;
- namespace Tv.nu.Lib.Api
- {
- public class ApiIntegrationHandler : IApiIntegrationHandler
- {
- #region Methods (Public)
- void IApiIntegrationHandler.GetChannels(Action<IEnumerable<Channel>> onSuccess, Action<string> onError)
- {
- string url = GetApiUrl("section/channels");
- Uri uri = new Uri(url, UriKind.Absolute);
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
- RequestState<IEnumerable<Channel>> requestState = new RequestState<IEnumerable<Channel>>(request, onError, onSuccess);
- request.BeginGetResponse(new AsyncCallback(result => {
- ParseResponseWith<IEnumerable<Channel>>(result, rootElement => {
- return ParseChannelList(rootElement);
- });
- }), requestState);
- }
- void IApiIntegrationHandler.GetChannelProgramListing(DateTime date, List<string> channels, Action<IEnumerable<ChannelProgramListing>> onSuccess, Action<string> onError)
- {
- string channelIdsString = String.Join("__", channels.ToArray());
- string url = string.Format("{0}/listing/channels/{1}/media/1/image_format/sq__50/date/{2}",
- ApiConfiguration.API_BASEURL,
- channelIdsString,
- //The date needs a special format in order
- //to be accepted by the API.
- GetFormattedDateString(date));
- Uri uri = new Uri(url, UriKind.Absolute);
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- RequestState<IEnumerable<ChannelProgramListing>> requestState = new RequestState<IEnumerable<ChannelProgramListing>>(request, onError, onSuccess);
- request.BeginGetResponse(new AsyncCallback(result => {
- ParseResponseWith<IEnumerable<ChannelProgramListing>>(result, rootElement => {
- return ParseChannelProgramListingList(rootElement);
- });
- }), requestState);
- }
- void IApiIntegrationHandler.GetProgramDetails(string programId, Action<ProgramDetails> onSuccess, Action<string> onError)
- {
- string url = string.Format("{0}section/program/id/{1}",
- ApiConfiguration.API_BASEURL,
- programId);
- Uri uri = new Uri(url, UriKind.Absolute);
- HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
- RequestState<ProgramDetails> requestState = new RequestState<ProgramDetails>(request, onError, onSuccess);
- request.BeginGetResponse(new AsyncCallback(result => {
- ParseResponseWith<ProgramDetails>(result, rootElement =>{
- return ParseProgramDetailsList(rootElement);
- });
- }), requestState);
- }
- #endregion
- #region Methods (Private)
- private void ParseResponseWith<T>(IAsyncResult result, Func<XElement, T> parseMethod)
- {
- RequestState<T> state = (RequestState<T>)result.AsyncState;
- string responseText;
- try
- {
- responseText = GetResponseText(result, state);
- }
- catch
- {
- state.OnError(ApiConfiguration.COMMUNICATION_ERROR_TEXT);
- return;
- }
- try
- {
- XElement root = XElement.Parse(responseText);
- T parsedData = parseMethod(root);
- state.OnSuccess(parsedData);
- }
- catch
- {
- state.OnError(ApiConfiguration.PARSE_ERROR_TEXT);
- }
- }
- private static string GetResponseText<T>(IAsyncResult result, RequestState<T> state)
- {
- using (HttpWebResponse response = (HttpWebResponse)state.Request.EndGetResponse(result))
- {
- using (Stream responseStream = response.GetResponseStream())
- {
- using (StreamReader reader = new StreamReader(responseStream))
- {
- return reader.ReadToEnd();
- }
- }
- }
- }
- private static string GetApiUrl(string section)
- {
- return String.Concat(ApiConfiguration.API_BASEURL, section);
- }
- /// <summary>
- /// Parses and combines the supplied elements to a ProgramInformation
- /// </summary>
- /// <param name="channel"></param>
- /// <param name="program"></param>
- /// <returns></returns>
- private static ProgramDetails ParseProgramDetails(XElement channel, XElement program)
- {
- ProgramDetails pi = new ProgramDetails
- {
- Channel = ParseChannel(channel)
- };
- if (program.Attribute("description") != null)
- pi.Description = program.Attribute("description").Value;
- if (program.Attribute("title") != null)
- pi.Title = program.Attribute("title").Value;
- if (program.Attribute("startTime") != null)
- pi.StartTime = program.Attribute("startTime").Value;
- if (program.Attribute("endTime") != null)
- pi.EndTime = program.Attribute("endTime").Value;
- if (program.Attribute("image") != null)
- pi.ImageUrl = program.Attribute("image").Value;
- if (program.Attribute("imdbRating") != null)
- pi.ImdbRating = program.Attribute("imdbRating").Value;
- if (program.Attribute("season") != null)
- pi.Season = program.Attribute("season").Value;
- if (program.Attribute("episode") != null)
- pi.Episode = program.Attribute("episode").Value;
- return pi;
- }
- /// <summary>
- /// Converts the supplied date to a string that is
- /// accepted by the API
- /// </summary>
- /// <param name="date"></param>
- /// <returns></returns>
- private object GetFormattedDateString(DateTime date)
- {
- return date.Year + "-" + date.Month.ToString("00") + "-" + date.Day.ToString("00");
- }
- /// <summary>
- /// Parses the supplied XElement to a Channel
- /// </summary>
- /// <param name="p"></param>
- /// <returns></returns>
- private static Channel ParseChannel(XElement p)
- {
- string logoImageUrl = string.Format(ApiConfiguration.CHANNEL_LOGO_URL_FORMAT, p.Attribute("logo").Value);
- return new Channel
- {
- Title = p.Attribute("title").Value,
- LogoImageUrl = logoImageUrl,
- SystemName = p.Attribute("systemname").Value
- };
- }
- /// <summary>
- /// Parses the supplied XElement to a Program
- /// </summary>
- /// <param name="q"></param>
- /// <returns></returns>
- private static Program ParseProgram(XElement q)
- {
- Program p = new Program
- {
- Title = q.Attribute("title").Value,
- StartTime = q.Attribute("startTime").Value,
- StartDate = DateTimeHelpers.UnixTimeToDateTime(q.Attribute("startTimestamp").Value),
- EndDate = DateTimeHelpers.UnixTimeToDateTime(q.Attribute("endTimestamp").Value),
- IsCurrent = q.Attribute("isCurrent").Value == "1",
- Id = q.Attribute("id").Value
- };
- if (q.Attribute("image") != null)
- p.ImageUrl = q.Attribute("image").Value;
- return p;
- }
- private static IEnumerable<ChannelProgramListing> ParseChannelProgramListingList(XElement rootElement)
- {
- return rootElement.Descendants("channel").Select(p =>
- {
- return new ChannelProgramListing
- {
- Channel = ParseChannel(p),
- Programs = p.Descendants("program").Select(q =>
- {
- return ParseProgram(q);
- })
- .ToList()
- };
- });
- }
- private static IEnumerable<Channel> ParseChannelList(XElement rootElement)
- {
- return rootElement.Descendants("channel").Select(p =>
- {
- return ParseChannel(p);
- });
- }
- private static ProgramDetails ParseProgramDetailsList(XElement rootElement)
- {
- return rootElement.Descendants("channel").Select(channel =>
- {
- return channel.Descendants("program").Select(program =>
- {
- return ParseProgramDetails(channel, program);
- }).SingleOrDefault();
- }).SingleOrDefault();
- }
- #endregion
- #region Private classes
- private class RequestState<T> {
- public readonly HttpWebRequest Request;
- public readonly Action<string> OnError;
- public readonly Action<T> OnSuccess;
- public RequestState(HttpWebRequest request, Action<string> onError, Action<T> onSuccess)
- {
- this.Request = request;
- this.OnError = onError;
- this.OnSuccess = onSuccess;
- }
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement