Skip to content

Commit

Permalink
Lots of changes.. this one targets v 6.x and above -- works with the …
Browse files Browse the repository at this point in the history
…changed merge endpoint
  • Loading branch information
Chris Mohan committed Nov 6, 2019
1 parent 5c7582b commit 0f2808a
Show file tree
Hide file tree
Showing 8 changed files with 100 additions and 74 deletions.
1 change: 1 addition & 0 deletions GotenbergSharp.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=Aire/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Gotenberg/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Pdfs/@EntryIndexedValue">True</s:Boolean>

<s:Boolean x:Key="/Default/UserDictionary/Words/=suppressions/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
14 changes: 7 additions & 7 deletions src/CaptiveAire.Gotenberg.App.API.Client/DocumentDimensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public class DocumentDimensions
/// <value>
/// The width of the paper.
/// </value>
[MultiFormHeader(name: "paperWidth")]
[MultiFormHeader("paperWidth")]
public double PaperWidth { get; set; }

/// <summary>
Expand All @@ -27,7 +27,7 @@ public class DocumentDimensions
/// <value>
/// The height of the paper.
/// </value>
[MultiFormHeader(name:"paperHeight")]
[MultiFormHeader("paperHeight")]
public double PaperHeight { get; set; }

/// <summary>
Expand All @@ -36,7 +36,7 @@ public class DocumentDimensions
/// <value>
/// The margin top.
/// </value>
[MultiFormHeader(name:"marginTop")]
[MultiFormHeader("marginTop")]
public double MarginTop { get; set; }

/// <summary>
Expand All @@ -45,7 +45,7 @@ public class DocumentDimensions
/// <value>
/// The margin bottom.
/// </value>
[MultiFormHeader(name:"marginBottom")]
[MultiFormHeader("marginBottom")]
public double MarginBottom { get; set; }

/// <summary>
Expand All @@ -54,7 +54,7 @@ public class DocumentDimensions
/// <value>
/// The margin left.
/// </value>
[MultiFormHeader(name:"marginLeft")]
[MultiFormHeader("marginLeft")]
public double MarginLeft { get; set; }

/// <summary>
Expand All @@ -63,7 +63,7 @@ public class DocumentDimensions
/// <value>
/// The margin right.
/// </value>
[MultiFormHeader(name:"marginRight")]
[MultiFormHeader("marginRight")]
public double MarginRight { get; set; }

/// <summary>
Expand All @@ -72,7 +72,7 @@ public class DocumentDimensions
/// <value>
/// <c>true</c> if landscape; otherwise, <c>false</c>.
/// </value>
[MultiFormHeader(name:"landscape")]
[MultiFormHeader("landscape")]
public bool Landscape { get;set; }


Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Gotenberg.App.API.Sharp.Client - Copyright (c) 2019 CaptiveAire

using System;
using System.Linq;

namespace CaptiveAire.Gotenberg.App.API.Sharp.Client.Extensions
{
/// <summary>
///
/// </summary>
public static class IntExtensions
{
const int alphabetLength = 26;
static readonly char[] _alphabet = Enumerable.Range('A', 'Z' - 'A' + 1).Select(c => (char) c).ToArray();

/// <summary>
/// Returns a-z for the first 26 (0-25); then za - zz for the next; zza - zzz, etc.
/// </summary>
/// <remarks>
/// Useful pdf merges. Gotenberg merges them alphabetically by file name
/// https://thecodingmachine.github.io/gotenberg/#merge
/// </remarks>
/// <param name="sortNumber"></param>
/// <returns></returns>
public static string ToAlphabeticallySortableName(this int sortNumber)
{
if(sortNumber < 0) throw new ArgumentOutOfRangeException(nameof(sortNumber));

return $"{new string('Z', sortNumber / alphabetLength)}{_alphabet[sortNumber % alphabetLength]}";
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,22 @@ public static IReadOnlyList<HttpContent> ToHttpContentCollection(this PdfRequest
/// <returns></returns>
public static IReadOnlyList<ByteArrayContent> AddAssetsToHttpContentCollection(this PdfRequest request)
{
return request.Assets?.Select((item) =>
{
string contentType;
new FileExtensionContentTypeProvider().TryGetContentType(item.Key, out contentType);
return request.Assets?
.Select(item =>
{
new FileExtensionContentTypeProvider().TryGetContentType(item.Key, out var contentType);
return new { Asset = item, ContentType = contentType };
return new { Asset = item, ContentType = contentType };
}).Where(_=> _.ContentType.IsSet())
.Select((item) =>
})
.Where(_ => _.ContentType.IsSet())
.Select(item =>
{
var assetItem = new ByteArrayContent(item.Asset.Value);
assetItem.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") {Name = "files", FileName = item.Asset.Key};
assetItem.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "files", FileName = item .Asset.Key };
assetItem.Headers.ContentType = new MediaTypeHeaderValue(item.ContentType);
return assetItem;
}).ToList();
})
.ToList();
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>latest</LangVersion>
<LangVersion>8</LangVersion>
<AssemblyName>CaptiveAire.Gotenberg.App.API.Sharp.Client</AssemblyName>
<RootNamespace>CaptiveAire.Gotenberg.App.API.Sharp.Client</RootNamespace>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Version>1.0.5</Version>
<Version>6.0.4</Version>
<VersionSuffix></VersionSuffix>
<TargetFrameworks>netstandard2.0;netstandard2.1</TargetFrameworks>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
Expand All @@ -16,7 +17,7 @@
<ItemGroup>
<PackageReference Include="ConcurrentSet" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="3.0.0" />
</ItemGroup>

</Project>
78 changes: 35 additions & 43 deletions src/CaptiveAire.Gotenberg.App.API.Client/GotenbergApiSharpClient.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
using CaptiveAire.Gotenberg.App.API.Sharp.Client.Extensions;
using CaptiveAire.Gotenberg.App.API.Sharp.Client.Helpers;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.StaticFiles;

namespace CaptiveAire.Gotenberg.App.API.Sharp.Client
{
Expand All @@ -20,17 +16,18 @@ namespace CaptiveAire.Gotenberg.App.API.Sharp.Client
/// https://github.com/thecodingmachine/gotenberg-go-client
/// https://github.com/thecodingmachine/gotenberg-php-client
/// https://github.com/thecodingmachine/gotenberg
/// https://github.com/thecodingmachine/gotenberg/releases
/// https://twitter.com/gulnap
/// </remarks>
// ReSharper disable once UnusedMember.Global
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public class GotenbergApiSharpClient
{
#region fields

readonly Uri _baseUri;
readonly HttpClient _client;
const string _convertHtmlPath = "convert/html";
const string _mergePdfPath = "convert/merge";
const string _mergePdfPath = "merge";

#endregion

Expand All @@ -39,16 +36,11 @@ public class GotenbergApiSharpClient
/// <summary>
/// Initializes a new instance of the <see cref="GotenbergApiSharpClient"/> class.
/// </summary>
/// <param name="baseUri">The base URI.</param>
/// <param name="clientFactory">The client factory.</param>
public GotenbergApiSharpClient(Uri baseUri, IHttpClientFactory clientFactory = null)
/// <param name="client"></param>
public GotenbergApiSharpClient(HttpClient client)
{
_baseUri = baseUri;
this._client = clientFactory != null
? clientFactory.CreateClient(nameof(GotenbergApiSharpClient))
: new HttpClient(new TimeoutHandler()) { Timeout = Timeout.InfiniteTimeSpan };

this._client.DefaultRequestHeaders.Add("Client", nameof(GotenbergApiSharpClient));
this._client = client ?? throw new ArgumentNullException(nameof(client));
this._client.DefaultRequestHeaders.Add("User-Agent", nameof(GotenbergApiSharpClient));
}

#endregion
Expand All @@ -69,26 +61,26 @@ public async Task<Stream> HtmlToPdfAsync(PdfRequest request, CancellationToken c
if(request == null) throw new ArgumentNullException(nameof(request));

var boundary = $"--------------------------{DateTime.Now.Ticks}";
using (var multiForm = new MultipartFormDataContent(boundary))

using var multiForm = new MultipartFormDataContent(boundary);

foreach (var item in request.ToHttpContentCollection())
{
foreach (var item in request.ToHttpContentCollection())
{
multiForm.Add(item);
}

foreach (var item in request.AddAssetsToHttpContentCollection())
{
multiForm.Add(item);
}

var response = await this._client
.PostAsync(new Uri($"{_baseUri}{_convertHtmlPath}"), multiForm, cancelToken)
.ConfigureAwait(false);
multiForm.Add(item);
}

cancelToken.ThrowIfCancellationRequested();
return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
foreach (var item in request.AddAssetsToHttpContentCollection())
{
multiForm.Add(item);
}

var response = await this._client
.PostAsync(new Uri($"{this._client.BaseAddress}{_convertHtmlPath}"), multiForm, cancelToken)
.ConfigureAwait(false);

cancelToken.ThrowIfCancellationRequested();

return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
}

/// <summary>
Expand All @@ -103,21 +95,21 @@ public async Task<Stream> MergePdfsAsync(MergeRequest request, CancellationToken
if (request.Items.Count == 0) throw new ArgumentOutOfRangeException(nameof(request.Items));

var boundary = $"--------------------------{DateTime.Now.Ticks}";
using (var multiForm = new MultipartFormDataContent(boundary))

using var multiForm = new MultipartFormDataContent(boundary);

foreach (var item in request.ToHttpContentCollection())
{
foreach (var item in request.ToHttpContentCollection())
{
multiForm.Add(item);
}
multiForm.Add(item);
}

var response = await this._client
.PostAsync(new Uri($"{_baseUri}{_mergePdfPath}"), multiForm, cancelToken)
.ConfigureAwait(false);
var response = await this._client
.PostAsync(new Uri($"{this._client.BaseAddress}{_mergePdfPath}"), multiForm, cancelToken)
.ConfigureAwait(false);

cancelToken.ThrowIfCancellationRequested();
cancelToken.ThrowIfCancellationRequested();

return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
}
return await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
}

#endregion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,15 @@ public TimeoutHandler(HttpMessageHandler innerHandler = null)
/// <exception cref="TimeoutException">Request Timeout</exception>
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancelToken)
{
using (var cts = GetCancelTokenSource(request, cancelToken))
using var cts = GetCancelTokenSource(request, cancelToken);

try
{
return await base.SendAsync(request, cts?.Token ?? cancelToken);
}
catch (OperationCanceledException ex) when (!cancelToken.IsCancellationRequested)
{
try
{
return await base.SendAsync(request, cts?.Token ?? cancelToken);
}
catch (OperationCanceledException ex) when (!cancelToken.IsCancellationRequested)
{
throw new TimeoutException("Request Timeout", ex.InnerException);
}
throw new TimeoutException("Request Timeout", ex.InnerException);
}
}

Expand Down
1 change: 0 additions & 1 deletion src/CaptiveAire.Gotenberg.App.API.Client/PdfRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
using CaptiveAire.Gotenberg.App.API.Sharp.Client.Extensions;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CaptiveAire.Gotenberg.App.API.Sharp.Client
{
Expand Down

0 comments on commit 0f2808a

Please sign in to comment.