using NReadability;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace PocketSharp
{
///
/// PocketReader
///
public partial class PocketReader
{
///
/// REST client used for HTML retrieval
///
protected readonly HttpClient _restClient;
///
/// Initializes a new instance of the class.
///
public PocketReader()
{
// initialize REST client
_restClient = new HttpClient(new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip
});
_restClient.DefaultRequestHeaders.Add("Accept", "text/html");
}
public async Task Read(Uri uri)
{
NReadabilityTranscoder transcoder = new NReadabilityTranscoder();
bool success;
string htmlResponse = await Request(uri);
string transcodedContent = transcoder.Transcode(htmlResponse, out success);
// //new TranscodingInput(
// //transcoder.Transcode(
// //string transcodedContent =
// // transcoder.Transcode("https://github.com/marek-stoj/NReadability", out success);
return transcodedContent;
}
///
/// Fetches a typed resource
///
protected async Task Request(Uri uri)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, uri);
// make async request
HttpResponseMessage response = await _restClient.SendAsync(request);
// validate HTTP response
ValidateResponse(response);
// read response
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
///
/// Validates the response.
///
/// The response.
///
///
/// Error retrieving response
///
protected void ValidateResponse(HttpResponseMessage response)
{
// no error found
if (response.StatusCode == HttpStatusCode.OK)
{
return;
}
string exceptionString = String.Format("Request error: {0} ({1})", response.ReasonPhrase, (int)response.StatusCode);
throw new PocketException(exceptionString);
}
}
}