using NReadability;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using PocketSharp.Models;
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");
}
///
/// Reads content from the given URI.
///
/// The pocket item.
///
public async Task Read(PocketItem item)
{
return await Read(item.Uri);
}
///
/// Reads content from the given URI.
///
/// The URI.
///
public async Task Read(Uri uri)
{
NReadabilityTranscoder transcoder = new NReadabilityTranscoder();
string htmlResponse = await Request(uri);
TranscodingInput input = new TranscodingInput(htmlResponse);
TranscodingResult result = transcoder.Transcode(input);
// //new TranscodingInput(
// //transcoder.Transcode(
// //string transcodedContent =
// // transcoder.Transcode("https://github.com/marek-stoj/NReadability", out success);
return result.ExtractedContent;
}
///
/// Fetches a 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);
}
}
}