This repository has been archived by the owner on Sep 6, 2023. It is now read-only.
/
ImageProcessingModule.cs
703 lines (616 loc) · 28.2 KB
/
ImageProcessingModule.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ImageProcessingModule.cs" company="James South">
// Copyright (c) James South.
// Licensed under the Apache License, Version 2.0.
// </copyright>
// <summary>
// Processes any image requests within the web application.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ImageProcessor.Web.HttpModules
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using System.Web.Hosting;
using ImageProcessor.Imaging.Formats;
using ImageProcessor.Web.Caching;
using ImageProcessor.Web.Configuration;
using ImageProcessor.Web.Extensions;
using ImageProcessor.Web.Helpers;
using ImageProcessor.Web.Services;
/// <summary>
/// Processes any image requests within the web application.
/// </summary>
public sealed class ImageProcessingModule : IHttpModule
{
#region Fields
/// <summary>
/// The key for storing the response type of the current image.
/// </summary>
private const string CachedResponseTypeKey = "CACHED_IMAGE_RESPONSE_TYPE_054F217C-11CF-49FF-8D2F-698E8E6EB58F";
/// <summary>
/// The key for storing the cached path of the current image.
/// </summary>
private const string CachedPathKey = "CACHED_IMAGE_PATH_TYPE_E0741478-C17B-433D-96A8-6CDA797644E9";
/// <summary>
/// The key for storing the file dependency of the current image.
/// </summary>
private const string CachedResponseFileDependency = "CACHED_IMAGE_DEPENDENCY_054F217C-11CF-49FF-8D2F-698E8E6EB58F";
/// <summary>
/// The regular expression to search strings for presets with.
/// </summary>
private static readonly Regex PresetRegex = new Regex(@"preset=[^&]+", RegexOptions.Compiled);
/// <summary>
/// The regular expression to search strings for protocols with.
/// </summary>
private static readonly Regex ProtocolRegex = new Regex("http(s)?://", RegexOptions.Compiled);
/// <summary>
/// The assembly version.
/// </summary>
private static readonly string AssemblyVersion = Assembly.GetExecutingAssembly().GetName().Version.ToString();
/// <summary>
/// Ensures duplicate requests are atomic.
/// </summary>
private static readonly AsyncDuplicateLock Locker = new AsyncDuplicateLock();
/// <summary>
/// Whether to preserve exif meta data.
/// </summary>
private static bool? preserveExifMetaData;
/// <summary>
/// A value indicating whether this instance of the given entity has been disposed.
/// </summary>
/// <value><see langword="true"/> if this instance has been disposed; otherwise, <see langword="false"/>.</value>
/// <remarks>
/// If the entity is disposed, it must not be disposed a second
/// time. The isDisposed field is set the first time the entity
/// is disposed. If the isDisposed field is true, then the Dispose()
/// method will not dispose again. This help not to prolong the entity's
/// life in the Garbage Collector.
/// </remarks>
private bool isDisposed;
/// <summary>
/// The image cache.
/// </summary>
private IImageCache imageCache;
#endregion
#region Destructors
/// <summary>
/// Finalizes an instance of the <see cref="T:ImageProcessor.Web.HttpModules.ImageProcessingModule"/> class.
/// </summary>
/// <remarks>
/// Use C# destructor syntax for finalization code.
/// This destructor will run only if the Dispose method
/// does not get called.
/// It gives your base class the opportunity to finalize.
/// Do not provide destructors in types derived from this class.
/// </remarks>
~ImageProcessingModule()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
this.Dispose(false);
}
#endregion
/// <summary>
/// The process querystring event handler.
/// </summary>
/// <param name="sender">
/// The sender.
/// </param>
/// <param name="e">
/// The <see cref="ProcessQueryStringEventArgs"/>.
/// </param>
/// <returns>Returns the processed querystring.</returns>
public delegate string ProcessQuerystringEventHandler(object sender, ProcessQueryStringEventArgs e);
/// <summary>
/// The event that is called when a new image is processed.
/// </summary>
public static event EventHandler<PostProcessingEventArgs> OnPostProcessing;
/// <summary>
/// The event that is called when a querystring is processed.
/// </summary>
public static event ProcessQuerystringEventHandler OnProcessQuerystring;
/// <summary>
/// This will make the browser and server keep the output
/// in its cache and thereby improve performance.
/// </summary>
/// <param name="context">
/// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
/// references to the intrinsic server objects
/// </param>
/// <param name="responseType">The HTTP MIME type to send.</param>
/// <param name="dependencyPaths">The dependency path for the cache dependency.</param>
/// <param name="maxDays">The maximum number of days to store the image in the browser cache.</param>
/// <param name="statusCode">An optional status code to send to the response.</param>
public static void SetHeaders(
HttpContext context,
string responseType,
IEnumerable<string> dependencyPaths,
int maxDays,
HttpStatusCode? statusCode = null)
{
HttpResponse response = context.Response;
if (response.Headers["ImageProcessedBy"] == null)
{
response.AddHeader("ImageProcessedBy", "ImageProcessor.Web/" + AssemblyVersion);
}
HttpCachePolicy cache = response.Cache;
cache.SetCacheability(HttpCacheability.Public);
cache.VaryByHeaders["Accept-Encoding"] = true;
if (!string.IsNullOrWhiteSpace(responseType))
{
response.ContentType = responseType;
}
if (dependencyPaths != null)
{
context.Response.AddFileDependencies(dependencyPaths.ToArray());
cache.SetLastModifiedFromFileDependencies();
}
if (statusCode != null)
{
response.StatusCode = (int)statusCode;
}
cache.SetExpires(DateTime.Now.ToUniversalTime().AddDays(maxDays));
cache.SetMaxAge(new TimeSpan(maxDays, 0, 0, 0));
cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
AddCorsRequestHeaders(context);
}
/// <summary>
/// Adds response headers allowing Cross Origin Requests if the current origin request
/// passes sanitizing rules.
/// </summary>
/// <param name="context">
/// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
/// references to the intrinsic server objects
/// </param>
public static void AddCorsRequestHeaders(HttpContext context)
{
if (!string.IsNullOrEmpty(context.Request.Headers["Origin"]))
{
string origin = context.Request.Headers["Origin"];
ImageSecuritySection.CORSOriginElement origins =
ImageProcessorConfiguration.Instance.GetImageSecuritySection().CORSOrigin;
if (origins == null || origins.WhiteList == null)
{
return;
}
// Check the url is from a whitelisted location.
Uri url = new Uri(origin);
string upper = url.Host.ToUpperInvariant();
// Check for root or sub domain.
bool validUrl = false;
foreach (Uri uri in origins.WhiteList)
{
if (uri.ToString() == "*")
{
validUrl = true;
break;
}
if (!uri.IsAbsoluteUri)
{
Uri rebaseUri = new Uri("http://" + uri.ToString().TrimStart('.', '/'));
validUrl = upper.StartsWith(rebaseUri.Host.ToUpperInvariant()) || upper.EndsWith(rebaseUri.Host.ToUpperInvariant());
}
else
{
validUrl = upper.StartsWith(uri.Host.ToUpperInvariant()) || upper.EndsWith(uri.Host.ToUpperInvariant());
}
if (validUrl)
{
break;
}
}
if (validUrl)
{
context.Response.AddHeader("Access-Control-Allow-Origin", origin);
}
}
}
#region IHttpModule Members
/// <summary>
/// Initializes a module and prepares it to handle requests.
/// </summary>
/// <param name="context">
/// An <see cref="T:System.Web.HttpApplication"/> that provides
/// access to the methods, properties, and events common to all
/// application objects within an ASP.NET application
/// </param>
public void Init(HttpApplication context)
{
if (preserveExifMetaData == null)
{
preserveExifMetaData = ImageProcessorConfiguration.Instance.PreserveExifMetaData;
}
EventHandlerTaskAsyncHelper postAuthorizeHelper = new EventHandlerTaskAsyncHelper(this.PostAuthorizeRequest);
context.AddOnPostAuthorizeRequestAsync(postAuthorizeHelper.BeginEventHandler, postAuthorizeHelper.EndEventHandler);
context.PostReleaseRequestState += this.PostReleaseRequestState;
EventHandlerTaskAsyncHelper postProcessHelper = new EventHandlerTaskAsyncHelper(this.PostProcessImage);
context.AddOnEndRequestAsync(postProcessHelper.BeginEventHandler, postProcessHelper.EndEventHandler);
}
/// <summary>
/// Disposes of the resources (other than memory) used by the module that implements <see cref="T:System.Web.IHttpModule"/>.
/// </summary>
public void Dispose()
{
this.Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SuppressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes the object and frees resources for the Garbage Collector.
/// </summary>
/// <param name="disposing">
/// If true, the object gets disposed.
/// </param>
private void Dispose(bool disposing)
{
if (this.isDisposed)
{
return;
}
if (disposing)
{
// Dispose of any managed resources here.
}
// Call the appropriate methods to clean up
// unmanaged resources here.
// Note disposing is done.
this.isDisposed = true;
}
#endregion
/// <summary>
/// Occurs when the user for the current request has been authorized.
/// </summary>
/// <param name="sender">
/// The source of the event.
/// </param>
/// <param name="e">
/// An <see cref="T:System.EventArgs">EventArgs</see> that contains the event data.
/// </param>
/// <returns>
/// The <see cref="T:System.Threading.Tasks.Task"/>.
/// </returns>
private Task PostAuthorizeRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
return this.ProcessImageAsync(context);
}
/// <summary>
/// Occurs when the ASP.NET event handler finishes execution.
/// </summary>
/// <param name="sender">
/// The source of the event.
/// </param>
/// <param name="e">
/// An <see cref="T:System.EventArgs">EventArgs</see> that contains the event data.
/// </param>
/// <returns>
/// The <see cref="T:System.Threading.Tasks.Task"/>.
/// </returns>
private async Task PostProcessImage(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
object cachedPathObject = context.Items[CachedPathKey];
if (cachedPathObject != null)
{
// Trim the cache.
await this.imageCache.TrimCacheAsync();
string cachedPath = cachedPathObject.ToString();
// Fire the post processing event.
EventHandler<PostProcessingEventArgs> handler = OnPostProcessing;
if (handler != null)
{
context.Items[CachedPathKey] = null;
await Task.Run(() => handler(this, new PostProcessingEventArgs { CachedImagePath = cachedPath }));
}
}
// Reset the cache.
this.imageCache = null;
}
/// <summary>
/// Occurs when ASP.NET has completed executing all request event handlers and the request
/// state data has been stored.
/// </summary>
/// <param name="sender">
/// The source of the event.
/// </param>
/// <param name="e">
/// An <see cref="T:System.EventArgs">EventArgs</see> that contains the event data.
/// </param>
private void PostReleaseRequestState(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
object responseTypeObject = context.Items[CachedResponseTypeKey];
object dependencyFileObject = context.Items[CachedResponseFileDependency];
string responseType = responseTypeObject as string;
List<string> dependencyFiles = dependencyFileObject as List<string>;
// Set the headers
if (this.imageCache != null)
{
SetHeaders(context, responseType, dependencyFiles, this.imageCache.MaxDays);
}
}
#region Private
/// <summary>
/// Processes the image.
/// </summary>
/// <param name="context">
/// the <see cref="T:System.Web.HttpContext">HttpContext</see> object that provides
/// references to the intrinsic server objects
/// </param>
/// <returns>
/// The <see cref="T:System.Threading.Tasks.Task"/>.
/// </returns>
private async Task ProcessImageAsync(HttpContext context)
{
HttpRequest request = context.Request;
// Should we ignore this request?
if (request.Unvalidated.RawUrl.ToUpperInvariant().Contains("IPIGNORE=TRUE"))
{
return;
}
IImageService currentService = this.GetImageServiceForRequest(request);
if (currentService != null)
{
bool isFileLocal = currentService.IsFileLocalService;
string url = request.Url.ToString();
bool isLegacy = ProtocolRegex.Matches(url).Count > 1;
bool hasMultiParams = url.Count(f => f == '?') > 1;
string requestPath;
string queryString = string.Empty;
string urlParameters = string.Empty;
// Legacy support. I'd like to remove this asap.
if (isLegacy && hasMultiParams)
{
// We need to split the querystring to get the actual values we want.
string[] paths = url.Split('?');
requestPath = paths[1];
// Handle extension-less urls.
if (paths.Length > 3)
{
queryString = paths[3];
urlParameters = paths[2];
}
else if (paths.Length > 1)
{
queryString = paths[2];
}
}
else
{
if (string.IsNullOrWhiteSpace(currentService.Prefix))
{
requestPath = currentService.IsFileLocalService
? HostingEnvironment.MapPath(request.Path)
: request.Path;
queryString = request.QueryString.ToString();
}
else
{
// Parse any protocol values from settings.
string protocol = currentService.Settings.ContainsKey("Protocol")
? currentService.Settings["Protocol"] + "://"
: currentService.GetType() == typeof(RemoteImageService) ? request.Url.Scheme + "://" : string.Empty;
// Handle requests that require parameters.
if (hasMultiParams)
{
string[] paths = url.Split('?');
requestPath = protocol
+ request.Path.TrimStart('/').Remove(0, currentService.Prefix.Length).TrimStart('/')
+ "?" + paths[1];
queryString = paths[2];
}
else
{
requestPath = protocol + request.Path.TrimStart('/').Remove(0, currentService.Prefix.Length).TrimStart('/');
queryString = request.QueryString.ToString();
}
}
}
// Replace any presets in the querystring with the actual value.
queryString = this.ReplacePresetsInQueryString(queryString);
// Execute the handler which can change the querystring
queryString = this.CheckQuerystringHandler(queryString, request.Unvalidated.RawUrl);
if (string.IsNullOrWhiteSpace(requestPath))
{
return;
}
string parts = !string.IsNullOrWhiteSpace(urlParameters) ? "?" + urlParameters : string.Empty;
string fullPath = string.Format("{0}{1}?{2}", requestPath, parts, queryString);
object resourcePath;
// More legacy support code.
if (hasMultiParams)
{
resourcePath = string.IsNullOrWhiteSpace(urlParameters)
? new Uri(requestPath, UriKind.RelativeOrAbsolute)
: new Uri(requestPath + "?" + urlParameters, UriKind.RelativeOrAbsolute);
}
else
{
resourcePath = requestPath;
}
// Check whether the path is valid for other requests.
if (!currentService.IsValidRequest(resourcePath.ToString()))
{
return;
}
string combined = requestPath + fullPath + queryString;
using (await Locker.LockAsync(combined))
{
// Create a new cache to help process and cache the request.
this.imageCache = (IImageCache)ImageProcessorConfiguration.Instance
.ImageCache.GetInstance(requestPath, fullPath, queryString);
// Is the file new or updated?
bool isNewOrUpdated = await this.imageCache.IsNewOrUpdatedAsync();
string cachedPath = this.imageCache.CachedPath;
// Only process if the file has been updated.
if (isNewOrUpdated)
{
// Process the image.
using (ImageFactory imageFactory = new ImageFactory(preserveExifMetaData != null && preserveExifMetaData.Value))
{
byte[] imageBuffer = await currentService.GetImage(resourcePath);
string mimeType;
using (MemoryStream inStream = new MemoryStream(imageBuffer))
{
// Process the Image
MemoryStream outStream = new MemoryStream();
if (!string.IsNullOrWhiteSpace(queryString))
{
imageFactory.Load(inStream).AutoProcess(queryString).Save(outStream);
mimeType = imageFactory.CurrentImageFormat.MimeType;
}
else
{
await inStream.CopyToAsync(outStream);
mimeType = FormatUtilities.GetFormat(outStream).MimeType;
}
// Post process the image.
if (ImageProcessorConfiguration.Instance.PostProcess)
{
string extension = Path.GetExtension(cachedPath);
outStream = await PostProcessor.PostProcessor.PostProcessImageAsync(outStream, extension);
}
// Add to the cache.
await this.imageCache.AddImageToCacheAsync(outStream, mimeType);
// Cleanup
outStream.Dispose();
}
// Store the cached path, response type, and cache dependency in the context for later retrieval.
context.Items[CachedPathKey] = cachedPath;
context.Items[CachedResponseTypeKey] = mimeType;
bool isFileCached = new Uri(cachedPath).IsFile;
if (isFileLocal)
{
if (isFileCached)
{
// Some services might only provide filename so we can't monitor for the browser.
context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
? new List<string> { cachedPath }
: new List<string> { requestPath, cachedPath };
}
else
{
context.Items[CachedResponseFileDependency] = Path.GetFileName(requestPath) == requestPath
? null
: new List<string> { requestPath };
}
}
else if (isFileCached)
{
context.Items[CachedResponseFileDependency] = new List<string> { cachedPath };
}
}
}
// The cached file is valid so just rewrite the path.
this.imageCache.RewritePath(context);
// Redirect if not a locally store file.
if (!new Uri(cachedPath).IsFile)
{
context.ApplicationInstance.CompleteRequest();
}
}
}
}
/// <summary>
/// Replaces preset values stored in the configuration in the querystring.
/// </summary>
/// <param name="queryString">
/// The query string.
/// </param>
/// <returns>
/// The <see cref="string"/> containing the updated querystring.
/// </returns>
private string ReplacePresetsInQueryString(string queryString)
{
if (!string.IsNullOrWhiteSpace(queryString))
{
foreach (Match match in PresetRegex.Matches(queryString))
{
if (match.Success)
{
string preset = match.Value.Split('=')[1];
// We use the processor config system to store the preset values.
string replacements = ImageProcessorConfiguration.Instance.GetPresetSettings(preset);
queryString = Regex.Replace(queryString, match.Value, replacements ?? string.Empty);
}
}
}
return queryString;
}
/// <summary>
/// Checks if there is a handler that changes the querystring and executes that handler.
/// </summary>
/// <param name="queryString">
/// The query string.
/// </param>
/// <param name="rawUrl">
/// The raw request url.
/// </param>
/// <returns>
/// The <see cref="string"/> containing the updated querystring.
/// </returns>
private string CheckQuerystringHandler(string queryString, string rawUrl)
{
// Fire the process querystring event.
ProcessQuerystringEventHandler handler = OnProcessQuerystring;
if (handler != null)
{
ProcessQueryStringEventArgs args = new ProcessQueryStringEventArgs { Querystring = queryString ?? string.Empty, RawUrl = rawUrl ?? string.Empty };
queryString = handler(this, args);
}
return queryString;
}
/// <summary>
/// Gets the correct <see cref="IImageService"/> for the given request.
/// </summary>
/// <param name="request">
/// The current image request.
/// </param>
/// <returns>
/// The <see cref="IImageService"/>.
/// </returns>
private IImageService GetImageServiceForRequest(HttpRequest request)
{
IImageService imageService = null;
IList<IImageService> services = ImageProcessorConfiguration.Instance.ImageServices;
string path = request.Path.TrimStart('/');
foreach (IImageService service in services)
{
string key = service.Prefix;
if (!string.IsNullOrWhiteSpace(key) && path.StartsWith(key, StringComparison.InvariantCultureIgnoreCase))
{
imageService = service;
}
}
if (imageService != null)
{
return imageService;
}
// Return the file based service.
if (services.Any(s => s.GetType() == typeof(LocalFileImageService)))
{
IImageService service = services.First(s => s.GetType() == typeof(LocalFileImageService));
if (service.IsValidRequest(path))
{
return service;
}
}
// Return the next unprefixed service.
return services.FirstOrDefault(s => string.IsNullOrWhiteSpace(s.Prefix) && s.IsValidRequest(path) && s.GetType() != typeof(LocalFileImageService));
}
#endregion
}
}