Skip to content

Commit

Permalink
Add ImageflowMiddlewareOptions.AddCommandDefault(key,value)
Browse files Browse the repository at this point in the history
  • Loading branch information
lilith committed Jun 15, 2020
1 parent cff8acc commit 7efe919
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 16 deletions.
3 changes: 3 additions & 0 deletions examples/Imageflow.Server.Example/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
args.Query["watermark"] = "imazen";
})
.AddCommandDefault("down.filter", "mitchell")
.AddCommandDefault("f.sharpen", "15")
.AddCommandDefault("webp.quality", "90")
// Register a named watermark that floats 10% from the bottom-right corner of the image
// With 70% opacity and some sharpness applied.
.AddWatermark(
Expand Down
8 changes: 8 additions & 0 deletions src/Imageflow.Server/ImageJobInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,14 @@ private bool ProcessRewritesAndAuthorization(HttpContext context, ImageflowMiddl
path = args.VirtualPath;
}
}
// Set defaults if keys are missing
foreach (var pair in options.CommandDefaults)
{
if (!args.Query.ContainsKey(pair.Key))
{
args.Query[pair.Key] = pair.Value;
}
}
foreach (var handler in options.PreRewriteAuthorization)
{
var matches = string.IsNullOrEmpty(handler.PathPrefix) ||
Expand Down
10 changes: 5 additions & 5 deletions src/Imageflow.Server/ImageflowMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ await stream.WriteAsync(result.ResultBytes.Array, result.ResultBytes.Offset,

if (cacheResult.Data != null)
{
context.Response.ContentType = PathHelpers.ContentTypeFor(info.EstimatedFileExtension);
context.Response.ContentType = PathHelpers.ContentTypeForImageExtension(info.EstimatedFileExtension);
context.Response.ContentLength = cacheResult.Data.Length;
SetCachingHeaders(context, cacheKey);
await cacheResult.Data.CopyToAsync(context.Response.Body);
Expand All @@ -192,7 +192,7 @@ await stream.WriteAsync(result.ResultBytes.Array, result.ResultBytes.Offset,
{
logger?.LogInformation("Serving {0}?{1} from disk cache {2}", info.FinalVirtualPath, info.CommandString, cacheResult.RelativePath);
await ServeFileFromDisk(context, cacheResult.PhysicalPath, cacheKey,
PathHelpers.ContentTypeFor(info.EstimatedFileExtension));
PathHelpers.ContentTypeForImageExtension(info.EstimatedFileExtension));
}
}

Expand Down Expand Up @@ -228,7 +228,7 @@ private async Task ProcessWithMemoryCache(HttpContext context, string cacheKey,
{
logger?.LogInformation($"Memory Cache Miss: Proxying image {info.FinalVirtualPath}?{info.CommandString}");

contentType = PathHelpers.ContentTypeFor(info.EstimatedFileExtension);
contentType = PathHelpers.ContentTypeForImageExtension(info.EstimatedFileExtension);
await using var sourceStream = (await info.GetPrimaryBlob()).OpenRead();
var ms = new MemoryStream((int)sourceStream.Length);
await sourceStream.CopyToAsync(ms);
Expand Down Expand Up @@ -284,7 +284,7 @@ private async Task ProcessWithDistributedCache(HttpContext context, string cache
{
logger?.LogInformation($"Distributed Cache Miss: Proxying image {info.FinalVirtualPath}?{info.CommandString}");

contentType = PathHelpers.ContentTypeFor(info.EstimatedFileExtension);
contentType = PathHelpers.ContentTypeForImageExtension(info.EstimatedFileExtension);
await using var sourceStream = (await info.GetPrimaryBlob()).OpenRead();
var ms = new MemoryStream((int)sourceStream.Length);
await sourceStream.CopyToAsync(ms);
Expand Down Expand Up @@ -341,7 +341,7 @@ private async Task ProcessWithNoCache(HttpContext context, ImageJobInfo info)
{
logger?.LogInformation($"Proxying image {info.FinalVirtualPath} with params {info.CommandString}");

var contentType = PathHelpers.ContentTypeFor(info.EstimatedFileExtension);
var contentType = PathHelpers.ContentTypeForImageExtension(info.EstimatedFileExtension);
await using var sourceStream = (await info.GetPrimaryBlob()).OpenRead();
context.Response.ContentType = contentType;
context.Response.ContentLength = sourceStream.Length;
Expand Down
16 changes: 16 additions & 0 deletions src/Imageflow.Server/ImageflowMiddlewareOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ public ImageflowMiddlewareOptions()

internal readonly List<UrlHandler<Func<UrlEventArgs, bool>>> PostRewriteAuthorization = new List<UrlHandler<Func<UrlEventArgs, bool>>>();

internal readonly Dictionary<string, string> CommandDefaults = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

/// <summary>
/// Use this to add default command values if they are missing. Does not affect image requests with no querystring.
/// Example: AddCommandDefault("down.colorspace", "srgb") reverts to ImageResizer's legacy behavior in scaling shadows and highlights.
/// </summary>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public ImageflowMiddlewareOptions AddCommandDefault(string key, string value)
{
if (CommandDefaults.ContainsKey(key)) throw new ArgumentOutOfRangeException(nameof(key), "A default has already been added for this key");
CommandDefaults[key] = value;
return this;
}
public ImageflowMiddlewareOptions AddRewriteHandler(string pathPrefix, Action<UrlEventArgs> handler)
{
Rewrite.Add(new UrlHandler<Action<UrlEventArgs>>(pathPrefix, handler));
Expand Down
13 changes: 3 additions & 10 deletions src/Imageflow.Server/PathHelpers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ internal static string SanitizeImageExtension(string extension)
};
}

internal static string ContentTypeFor(string extension)
internal static string ContentTypeForImageExtension(string extension)
{
return extension switch
{
Expand All @@ -69,14 +69,7 @@ internal static string ContentTypeFor(string extension)
_ => "application/octet-stream"
};
}


internal static IEnumerable<string> MatchingResizeQueryStringParameters(IQueryCollection queryCollection)
{
return querystringKeys
.Where(queryCollection.ContainsKey)
.Select(qsKey => qsKey + "=" + queryCollection[qsKey]);
}


internal static string Base64Hash(string data)
{
Expand All @@ -94,7 +87,7 @@ internal static string Base64Hash(string data)

public static Dictionary<string, string> ToQueryDictionary(IQueryCollection requestQuery)
{
var dict = new Dictionary<string,string>(requestQuery.Count);
var dict = new Dictionary<string,string>(requestQuery.Count, StringComparer.OrdinalIgnoreCase);
foreach (var pair in requestQuery)
{
dict.Add(pair.Key, pair.Value.ToString());
Expand Down
2 changes: 1 addition & 1 deletion src/Imazen.Common/Imazen.Common.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="2.2.0" />
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All"/>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0" PrivateAssets="All" />
</ItemGroup>

</Project>

0 comments on commit 7efe919

Please sign in to comment.