Skip to content

Commit

Permalink
Fix quality for imagetaghelper and add raw endpoint
Browse files Browse the repository at this point in the history
  • Loading branch information
Roblinde committed Sep 27, 2022
1 parent 8fcf94b commit e13149f
Show file tree
Hide file tree
Showing 9 changed files with 89 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ public async Task JpgSpecificValuesShouldNotBeSetForNonJpgAssetWithFormat()
}
};
tagHelper.Format = Core.Images.ImageFormat.Png;
tagHelper.JpgQuality = 45;
tagHelper.Quality = 34;
tagHelper.ProgressiveJpg = true;
tagHelper.Width = 50;

Expand All @@ -243,7 +243,7 @@ public async Task JpgSpecificValuesShouldNotBeSetForNonJpgAssetWithFormat()

//Assert
Assert.Equal("https://robertlinde.se", tagHelper.Url);
Assert.Equal("https://robertlinde.se?w=50&fm=png", output.Attributes["src"].Value);
Assert.Equal("https://robertlinde.se?w=50&q=34&fm=png", output.Attributes["src"].Value);
}

[Fact]
Expand Down
8 changes: 4 additions & 4 deletions Contentful.AspNetCore/Contentful.AspNetCore.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@
<PackageProjectUrl>https://github.com/contentful/contentful.net</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<RepositoryType>git</RepositoryType>
<Version>7.2.0</Version>
<AssemblyVersion>7.2.0.0</AssemblyVersion>
<Version>7.2.2</Version>
<AssemblyVersion>7.2.2.0</AssemblyVersion>
<RepositoryUrl>https://github.com/contentful/contentful.net</RepositoryUrl>
<FileVersion>7.2.0.0</FileVersion>
<FileVersion>7.2.2.0</FileVersion>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
<DocumentationFile>bin\Release\netstandard1.5\Contentful.AspNetCore.xml</DocumentationFile>
Expand All @@ -25,7 +25,7 @@
<AllowedOutputExtensionsInPackageBuildOutputFolder>$(AllowedOutputExtensionsInPackageBuildOutputFolder);.pdb</AllowedOutputExtensionsInPackageBuildOutputFolder>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="contentful.csharp" Version="7.2.0" />
<PackageReference Include="contentful.csharp" Version="7.2.2" />
<PackageReference Include="gitlink" Version="3.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
Expand Down
13 changes: 13 additions & 0 deletions Contentful.AspNetCore/TagHelpers/ContentfulImageTagHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,14 @@ public abstract class ImageTagHelperBase : TagHelper {
/// <summary>
/// The quality of the image as a value between 0 and 100.
/// </summary>
[Obsolete("Use the Quality property instead")]
public int? JpgQuality { get; set; }

/// <summary>
/// The quality of the image as a value between 0 and 100.
/// </summary>
public int? Quality { get; set; }

/// <summary>
/// Wether progressive JPGs should be used.
/// </summary>
Expand Down Expand Up @@ -127,6 +133,11 @@ public async Task<string> BuildUrl()
queryBuilder.SetJpgQuality(JpgQuality.Value);
}

if (Quality.HasValue)
{
queryBuilder.SetQuality(Quality.Value);
}

if (CornerRadius.HasValue)
{
queryBuilder.SetCornerRadius(CornerRadius.Value);
Expand Down Expand Up @@ -180,6 +191,7 @@ public override async Task ProcessAsync(TagHelperContext context, TagHelperOutpu
await output.GetChildContentAsync();

output.TagName = "img";
string url = await BuildUrl();
output.Attributes.Add("src", await BuildUrl());

if (!context.AllAttributes.ContainsName("alt"))
Expand Down Expand Up @@ -251,6 +263,7 @@ private void SetDefaults(ContentfulImageTagHelper defaults)
Width = Width > 0 ? Width : defaults.Width;
Height = Height > 0 ? Height : defaults.Height;
JpgQuality = JpgQuality.HasValue ? JpgQuality : defaults.JpgQuality;
Quality = Quality.HasValue ? Quality : defaults.Quality;
CornerRadius = CornerRadius.HasValue ? CornerRadius : defaults.CornerRadius;
BackgroundColor = string.IsNullOrEmpty(BackgroundColor) ? defaults.BackgroundColor : BackgroundColor;
Url = string.IsNullOrEmpty(Url) ? defaults.Url : Url;
Expand Down
13 changes: 13 additions & 0 deletions Contentful.Core.Tests/ContentfulClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -618,6 +618,19 @@ public async Task GetEntriesByTypeShouldAddCorrectFilter()
Assert.Equal("?content_type=666", builder.Build());
}

[Fact]
public async Task GetEntriesRawShouldReturnCorrectString()
{
//Arrange
_handler.Response = GetResponseFromFile(@"EntriesCollection.json");
//Act
var res = await _client.GetEntriesRaw();

//Assert
Assert.NotEmpty(res);
Assert.Matches("Kitchen", res);
}

[Fact]
public async Task GetEntriesCollectionShouldSerializeIntoCorrectCollection()
{
Expand Down
27 changes: 26 additions & 1 deletion Contentful.Core.Tests/Images/ImageUrlBuilderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,20 @@ public void SettingJpgQualityShouldSetCorrectQueryString(int quality)
Assert.Equal($"?q={quality}", result);
}

[Theory]
[InlineData(24)]
[InlineData(45)]
[InlineData(888)]
public void SettingQualityShouldSetCorrectQueryString(int quality)
{
//Arrange
var builder = new ImageUrlBuilder();
//Act
var result = builder.SetQuality(quality).Build();
//Assert
Assert.Equal($"?q={quality}", result);
}

[Fact]
public void Setting8BitPngShouldSetCorrectQueryString()
{
Expand Down Expand Up @@ -224,11 +238,22 @@ public void SettingFormatToPngShouldNotAllowForJpgSpecificValues()
//Arrange
var builder = new ImageUrlBuilder();
//Act
var result = builder.SetFormat(ImageFormat.Png).SetJpgQuality(34).UseProgressiveJpg().Build();
var result = builder.SetFormat(ImageFormat.Png).UseProgressiveJpg().Build();
//Assert
Assert.Equal("?fm=png", result);
}

[Fact]
public void SettingFormatToWebpShouldAllowForQualitySpecificValues()
{
//Arrange
var builder = new ImageUrlBuilder();
//Act
var result = builder.SetFormat(ImageFormat.Webp).SetQuality(34).Build();
//Assert
Assert.Equal("?fm=webp&q=34", result);
}

[Fact]
public void SettingFormatToJpgShouldAllowForJpgSpecificValues()
{
Expand Down
6 changes: 3 additions & 3 deletions Contentful.Core/Contentful.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
<GenerateAssemblyConfigurationAttribute>false</GenerateAssemblyConfigurationAttribute>
<GenerateAssemblyCompanyAttribute>false</GenerateAssemblyCompanyAttribute>
<GenerateAssemblyProductAttribute>false</GenerateAssemblyProductAttribute>
<AssemblyVersion>7.2.0.0</AssemblyVersion>
<FileVersion>7.2.0.0</FileVersion>
<Version>7.2.0</Version>
<AssemblyVersion>7.2.2.0</AssemblyVersion>
<FileVersion>7.2.2.0</FileVersion>
<Version>7.2.2</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="gitlink" Version="3.1.0">
Expand Down
7 changes: 7 additions & 0 deletions Contentful.Core/ContentfulClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,13 @@ public async Task<ContentfulCollection<T>> GetEntries<T>(QueryBuilder<T> queryBu
return await GetEntries<T>(queryBuilder?.Build(), cancellationToken).ConfigureAwait(false);
}

public async Task<string> GetEntriesRaw(string queryString = null, CancellationToken cancellationToken = default)
{
var res = await Get($"{_baseUrl}{_options.SpaceId}/{EnvironmentsBase}entries{queryString}", null, cancellationToken).ConfigureAwait(false);
var resultString = await res.Content.ReadAsStringAsync().ConfigureAwait(false);
return resultString;
}

public async Task<ContentfulResult<ContentfulCollection<T>>> GetEntries<T>(string etag, string queryString = null, CancellationToken cancellationToken = default)
{
var res = await Get($"{_baseUrl}{_options.SpaceId}/{EnvironmentsBase}entries{queryString}", etag, cancellationToken).ConfigureAwait(false);
Expand Down
9 changes: 9 additions & 0 deletions Contentful.Core/IContentfulClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ public interface IContentfulClient
/// <exception cref="ContentfulException">There was an error when communicating with the Contentful API.</exception>
Task<ContentfulCollection<T>> GetEntriesByType<T>(string contentTypeId, QueryBuilder<T> queryBuilder = null, CancellationToken cancellationToken = default);

/// <summary>
/// Gets all the entries of a space,filtered by an optional querystring.
/// </summary>
/// <param name="queryString">The optional querystring to add additional filtering to the query.</param>
/// <param name="cancellationToken">The optional cancellation token to cancel the operation.</param>
/// <returns>A <see cref="ContentfulCollection{T}"/> of items.</returns>
/// <exception cref="ContentfulException">There was an error when communicating with the Contentful API.</exception>
Task<string> GetEntriesRaw(string queryString = null, CancellationToken cancellationToken = default);

/// <summary>
/// Gets all the entries of a space, filtered by an optional <see cref="QueryBuilder{T}"/>.
/// </summary>
Expand Down
19 changes: 12 additions & 7 deletions Contentful.Core/Images/ImageUrlBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,24 @@ public ImageUrlBuilder SetFormat(ImageFormat format)
/// </summary>
/// <param name="quality">The quality as a percentage between 0 and 100.</param>
/// <returns>The <see cref="ImageUrlBuilder"/> instance.</returns>
[Obsolete("This method will be removed in an upcoming release, use the SetQuality method instead.")]
public ImageUrlBuilder SetJpgQuality(int quality)
{
_querystringValues.Add(new KeyValuePair<string, string>("q", quality.ToString()));
return this;
}

/// <summary>
/// Sets the quality of the image returned.
/// </summary>
/// <param name="quality">The quality as a percentage between 0 and 100.</param>
/// <returns>The <see cref="ImageUrlBuilder"/> instance.</returns>
public ImageUrlBuilder SetQuality(int quality)
{
_querystringValues.Add(new KeyValuePair<string, string>("q", quality.ToString()));
return this;
}

/// <summary>
/// Sets the color depth of the png image returned to 8 bit.
/// </summary>
Expand Down Expand Up @@ -202,13 +214,6 @@ private void ClearImproperValues()

_querystringValues.Remove(progressive);
}

if(format != "jpg" && format != "webp")
{
var quality = _querystringValues.FirstOrDefault(c => c.Key == "q");

_querystringValues.Remove(quality);
}
}
}
}
Expand Down

0 comments on commit e13149f

Please sign in to comment.