|
| 1 | +// Copyright (c) Six Labors. |
| 2 | +// Licensed under the Apache License, Version 2.0. |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Threading.Tasks; |
| 6 | +using Microsoft.AspNetCore.Http; |
| 7 | +using Microsoft.AspNetCore.Http.Extensions; |
| 8 | +using Microsoft.Extensions.FileProviders; |
| 9 | +using SixLabors.ImageSharp.Web.Resolvers; |
| 10 | + |
| 11 | +namespace SixLabors.ImageSharp.Web.Providers |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// Returns images from an <see cref="IFileProvider"/> abstraction. |
| 15 | + /// </summary> |
| 16 | + public class FileProviderImageProvider : IImageProvider |
| 17 | + { |
| 18 | + /// <summary> |
| 19 | + /// The file provider abstraction. |
| 20 | + /// </summary> |
| 21 | + private readonly IFileProvider fileProvider; |
| 22 | + |
| 23 | + /// <summary> |
| 24 | + /// Contains various format helper methods based on the current configuration. |
| 25 | + /// </summary> |
| 26 | + private readonly FormatUtilities formatUtilities; |
| 27 | + |
| 28 | + /// <summary> |
| 29 | + /// Initializes a new instance of the <see cref="FileProviderImageProvider"/> class. |
| 30 | + /// </summary> |
| 31 | + /// <param name="fileProvider">The file provider.</param> |
| 32 | + /// <param name="formatUtilities">Contains various format helper methods based on the current configuration.</param> |
| 33 | + public FileProviderImageProvider(IFileProvider fileProvider, FormatUtilities formatUtilities) |
| 34 | + { |
| 35 | + this.fileProvider = fileProvider ?? throw new ArgumentNullException(nameof(fileProvider)); |
| 36 | + this.formatUtilities = formatUtilities ?? throw new ArgumentNullException(nameof(formatUtilities)); |
| 37 | + } |
| 38 | + |
| 39 | + /// <inheritdoc/> |
| 40 | + public ProcessingBehavior ProcessingBehavior { get; protected set; } = ProcessingBehavior.CommandOnly; |
| 41 | + |
| 42 | + /// <inheritdoc/> |
| 43 | + public Func<HttpContext, bool> Match { get; set; } = _ => true; |
| 44 | + |
| 45 | + /// <inheritdoc/> |
| 46 | + public bool IsValidRequest(HttpContext context) |
| 47 | + => this.formatUtilities.TryGetExtensionFromUri(context.Request.GetDisplayUrl(), out _); |
| 48 | + |
| 49 | + /// <inheritdoc/> |
| 50 | + public Task<IImageResolver> GetAsync(HttpContext context) |
| 51 | + { |
| 52 | + IFileInfo fileInfo = this.fileProvider.GetFileInfo(context.Request.Path); |
| 53 | + if (!fileInfo.Exists) |
| 54 | + { |
| 55 | + return Task.FromResult<IImageResolver>(null); |
| 56 | + } |
| 57 | + |
| 58 | + return Task.FromResult<IImageResolver>(new FileProviderImageResolver(fileInfo)); |
| 59 | + } |
| 60 | + } |
| 61 | +} |
0 commit comments