-
Notifications
You must be signed in to change notification settings - Fork 14
/
BinaryFactory.cs
541 lines (482 loc) · 19.5 KB
/
BinaryFactory.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
using System;
using System.Collections.Generic;
using System.IO;
using DD4T.ContentModel;
using DD4T.ContentModel.Contracts.Providers;
using DD4T.ContentModel.Exceptions;
using DD4T.Utils.Caching;
using DD4T.ContentModel.Factories;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Text.RegularExpressions;
using System.Linq;
using System.Web;
namespace DD4T.Factories
{
public class BinaryFactory : FactoryBase, IBinaryFactory
{
public const string CacheRegion = "Binary";
private const string CacheValueNullTitle = "DD4T-Special-Value-BinaryNotFound";
private IBinary CacheValueNull;
private static IDictionary<string, DateTime> lastPublishedDates = new Dictionary<string, DateTime>();
public IBinaryProvider BinaryProvider { get; set; }
public BinaryFactory(IBinaryProvider binaryProvider, IFactoryCommonServices factoryCommonServices)
: base(factoryCommonServices)
{
if (binaryProvider == null)
throw new ArgumentNullException("binaryProvider");
BinaryProvider = binaryProvider;
CacheValueNull = new Binary() { Title = CacheValueNullTitle };
}
#region IBinaryFactory members
public bool FindAndStoreBinary(string url, string physicalPath)
{
IBinary binary = new Binary();
return TryFindBinary(url, physicalPath, false, out binary);
}
public bool TryFindBinary(string url, out IBinary binary)
{
return TryFindBinary(url, null, true, out binary);
}
public IBinary FindBinary(string url)
{
IBinary binary;
if (!TryFindBinary(url, out binary))
{
throw new BinaryNotFoundException();
}
return binary;
}
public DateTime FindLastPublishedDate(string url)
{
return BinaryProvider.GetBinaryMetaByUrl(url).LastPublishedDate;
}
public bool TryGetBinary(string tcmUri, out IBinary binary)
{
binary = new Binary();
if (LoadBinariesAsStream)
{
LoggerService.Information("retrieving binaries as a stream is obsolete; support will be dropped in future versions of DD4T");
binary.BinaryStream = BinaryProvider.GetBinaryStreamByUri(tcmUri);
if (binary.BinaryStream == null)
return false;
}
else
{
binary.BinaryData = BinaryProvider.GetBinaryByUri(tcmUri);
if (binary.BinaryData == null || binary.BinaryData.Length == 0)
return false;
}
((Binary)binary).Id = tcmUri;
return true;
}
public IBinary GetBinary(string tcmUri)
{
IBinary binary;
if (!TryGetBinary(tcmUri, out binary))
{
throw new BinaryNotFoundException();
}
return binary;
}
public bool TryFindBinaryContent(string url, out byte[] bytes)
{
bytes = null;
try
{
bytes = BinaryProvider.GetBinaryByUrl(url);
return true;
}
catch
{
return false;
}
}
public byte[] FindBinaryContent(string url)
{
byte[] bytes;
if (!TryFindBinaryContent(url, out bytes))
{
throw new BinaryNotFoundException();
}
return bytes;
}
public bool TryGetBinaryContent(string uri, out byte[] bytes)
{
bytes = null;
try
{
bytes = BinaryProvider.GetBinaryByUri(uri);
return true;
}
catch
{
return false;
}
}
public byte[] GetBinaryContent(string uri)
{
byte[] bytes;
if (!TryFindBinaryContent(uri, out bytes))
{
throw new BinaryNotFoundException();
}
return bytes;
}
public bool HasBinaryChanged(string url)
{
return true; // TODO: implement
}
public IBinaryMeta FindBinaryMeta(string url)
{
string cacheKey = CacheKeyFactory.GenerateKey(url);
IBinaryMeta binaryMeta = CacheAgent.Load(cacheKey) as IBinaryMeta;
if (binaryMeta != null)
{
return binaryMeta;
}
binaryMeta = BinaryProvider.GetBinaryMetaByUrl(url);
if (binaryMeta == null) // TODO: cache null result
{
return null;
}
CacheAgent.Store(cacheKey, "Binary", binaryMeta, new List<string> { binaryMeta.Id });
return binaryMeta;
}
public IBinaryMeta GetBinaryMeta(string uri)
{
return BinaryProvider.GetBinaryMetaByUri(uri);
}
#endregion IBinaryFactory members
#region private
private bool TryFindBinary(string url, string localPath, bool retrieveData, out IBinary binary)
{
string physicalPath = localPath ?? Path.Combine(Configuration.BinaryFileSystemCachePath, Path.GetFileName(url));
LoggerService.Debug($"Using physical path {physicalPath}");
binary = new Binary();
Dimensions dimensions = null;
string urlWithoutDimensions = StripDimensions(url, out dimensions);
if (LoadBinariesAsStream)
{
LoggerService.Information("retrieving binaries as a stream is obsolete; support will be dropped in future versions of DD4T");
binary.BinaryStream = BinaryProvider.GetBinaryStreamByUrl(urlWithoutDimensions);
if (binary.BinaryStream == null)
return false;
}
string cacheKey = CacheKeyFactory.GenerateKey(urlWithoutDimensions);
try
{
IBinaryMeta binaryMeta = CacheAgent.Load(cacheKey) as IBinaryMeta;
bool metaWasInCache = true;
if (binaryMeta == null)
{
metaWasInCache = false;
binaryMeta = BinaryProvider.GetBinaryMetaByUrl(urlWithoutDimensions);
if (binaryMeta == null)
{
throw new BinaryNotFoundException();
}
CacheAgent.Store(cacheKey, "Binary", binaryMeta, new List<string> { binaryMeta.Id });
}
if (FileExistsAndIsNotEmpty(physicalPath))
{
if (binaryMeta.HasLastPublishedDate || metaWasInCache)
{
DateTime fileModifiedDate = File.GetLastWriteTime(physicalPath);
if (fileModifiedDate.CompareTo(binaryMeta.LastPublishedDate) >= 0)
{
LoggerService.Debug("binary {0} is still up to date, no action required", urlWithoutDimensions);
// TODO: load bytes from file system into binary
if (retrieveData)
{
FillBinaryFromLocalFS(binary, physicalPath);
}
CopyBinaryMetaToBinary(binaryMeta, binary);
return true;
}
}
}
// the normal situation (where a binary is still in Tridion and it is present on the file system already and it is up to date) is now covered
// Let's handle the exception situations.
byte[] bytes = BinaryProvider.GetBinaryByUrl(urlWithoutDimensions);
if (bytes == null || bytes.Length == 0)
{
throw new BinaryNotFoundException();
}
bool fileIsCreated = WriteBinaryToFile(bytes, physicalPath, dimensions);
if (!fileIsCreated)
{
LoggerService.Warning($"file '{physicalPath}' could not be created, binary {binary.Id} cannot be returned");
return false;
}
if (retrieveData)
{
if (dimensions == null)
{
binary.BinaryData = bytes;
}
else
{
FillBinaryFromLocalFS(binary, physicalPath);
}
}
CopyBinaryMetaToBinary(binaryMeta, binary);
return true;
}
catch (BinaryNotFoundException)
{
LoggerService.Debug("Binary with url {0} not found", urlWithoutDimensions);
// binary does not exist in Tridion, it should be removed from the local file system too
DeleteFile(physicalPath);
return false;
}
catch (Exception e)
{
LoggerService.Warning($"Caught unexpected exception while retrieving binary with url {urlWithoutDimensions} (requested url: {url}. Error message: {e.Message}\r\n{e.StackTrace}");
// in case of error, the binary should be removed from the local file system too
DeleteFile(physicalPath);
throw e;
}
}
private void CopyBinaryMetaToBinary(IBinaryMeta binaryMeta, IBinary binary)
{
((Binary)binary).Id = binaryMeta.Id;
((Binary)binary).VariantId = binaryMeta.VariantId;
((Binary)binary).LastPublishedDate = binaryMeta.LastPublishedDate;
}
private void FillBinaryFromLocalFS(IBinary binary, string physicalPath)
{
binary.BinaryData = File.ReadAllBytes(physicalPath);
}
private void DeleteFile(string physicalPath)
{
if (File.Exists(physicalPath))
{
LoggerService.Debug("requested binary {0} no longer exists in broker. Removing...", physicalPath);
var tempLocationToDeleteFile = $"{HttpContext.Current.Server.MapPath("/")}App_Data\\Temp\\"; //storing the file inside appdata as cannot be requested
if (!Directory.Exists(tempLocationToDeleteFile))
{
Directory.CreateDirectory(tempLocationToDeleteFile);
}
string uniqueName = Guid.NewGuid().ToString();
var movedPhysicalPath = $"{tempLocationToDeleteFile}{uniqueName}";
try
{
File.Move(physicalPath, movedPhysicalPath); //moving file as it happens during request
File.Delete(movedPhysicalPath); //File got unpublished / File does not exists
}
catch (Exception e)
{
LoggerService.Error("Exception occurred {0}\r\n{1}", e.Message, e.StackTrace);
}
RemoveEmptyDirectories(Path.GetDirectoryName(physicalPath));
LoggerService.Debug("done ({0})", physicalPath);
}
}
private void RemoveEmptyDirectories(string path)
{
try
{
if (Path.GetPathRoot(path).Equals(path)) // if we are at the root then let's end the recursive call
{
return;
}
if (IsDirectoryEmpty(path))
{
Directory.Delete(path);
RemoveEmptyDirectories(Path.GetDirectoryName(path)); // recursive call with parent folder as argument
}
}
catch (Exception e)
{
LoggerService.Error("Exception occurred {0}\r\n{1}", e.Message, e.StackTrace);
}
}
private bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}
private bool FileExistsAndIsNotEmpty(string physicalPath)
{
if (File.Exists(physicalPath))
{
FileInfo fi = new FileInfo(physicalPath);
if (fi.Length > 0)
{
return true;
}
}
return false;
}
/// <summary>
/// Perform actual write of binary content to file
/// </summary>
/// <param name="binaryMeta">BinaryMeta the binary meta to store</param>
/// <param name="physicalPath">String the file path to write to</param>
/// <returns></returns>
private bool WriteBinaryToFile(byte[] bytes, String physicalPath, Dimensions dimensions)
{
bool result = true;
FileStream fileStream = null;
try
{
lock (physicalPath)
{
if (File.Exists(physicalPath))
{
fileStream = new FileStream(physicalPath, FileMode.Create);
}
else
{
FileInfo fileInfo = new FileInfo(physicalPath);
if (!fileInfo.Directory.Exists)
{
fileInfo.Directory.Create();
}
fileStream = File.Create(physicalPath);
}
byte[] buffer = bytes;
if (dimensions != null)
buffer = ResizeImageFile(buffer, dimensions, GetImageFormat(physicalPath));
fileStream.Write(buffer, 0, buffer.Length);
}
}
catch (Exception e)
{
LoggerService.Error("Exception occurred {0}\r\n{1}", e.Message, e.StackTrace);
result = false;
}
finally
{
if (fileStream != null)
{
fileStream.Close();
}
}
return result;
}
internal static byte[] ResizeImageFile(byte[] imageFile, Dimensions dimensions, ImageFormat imageFormat)
{
int targetHeight, targetWidth;
using (Image originalImage = Image.FromStream(new MemoryStream(imageFile)))
{
if (dimensions.Width > 0 && dimensions.Height > 0 && !(dimensions.Width == originalImage.Width && dimensions.Height == originalImage.Height))
{
targetWidth = dimensions.Width;
targetHeight = dimensions.Height;
}
else if (dimensions.Width > 0 && dimensions.Width != originalImage.Width)
{
targetWidth = dimensions.Width;
targetHeight = (int)(originalImage.Height * ((float)targetWidth / (float)originalImage.Width));
}
else if (dimensions.Height > 0 && dimensions.Height != originalImage.Height)
{
targetHeight = dimensions.Height;
targetWidth = (int)(originalImage.Width * ((float)targetHeight / (float)originalImage.Height));
}
else
{
//No need to resize the image, return the original bytes.
return imageFile;
}
using (ImageAttributes imageAttributes = new ImageAttributes())
{
Bitmap bitmapResized = new Bitmap(targetWidth, targetHeight, PixelFormat.Format24bppRgb);
Bitmap bitmapOriginal = new Bitmap(originalImage);
imageAttributes.SetWrapMode(WrapMode.TileFlipXY);
bitmapResized.SetResolution(72, 72);
bitmapResized.MakeTransparent(bitmapOriginal.GetPixel(0, 0));
using (Graphics graphics = Graphics.FromImage(bitmapResized))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.SmoothingMode = SmoothingMode.AntiAlias;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(bitmapOriginal, new Rectangle(0, 0, targetWidth, targetHeight), 0, 0, originalImage.Width, originalImage.Height, GraphicsUnit.Pixel, imageAttributes);
// Save out to memory and then to a file. We dispose of all objects to make sure the files don't stay locked.
using (MemoryStream memoryStream = new MemoryStream())
{
bitmapResized.Save(memoryStream, imageFormat);
return memoryStream.GetBuffer();
}
}
}
}
}
private ImageFormat GetImageFormat(string path)
{
switch (Path.GetExtension(path).ToLower())
{
case ".jpg":
case ".jpeg":
return ImageFormat.Jpeg;
case ".png":
return ImageFormat.Png;
case ".gif":
return ImageFormat.Gif;
}
return ImageFormat.Png; // use png as default
}
private IBinary GetIBinaryObject(byte[] binaryContent, string url)
{
IBinary binary = new Binary();
binary.BinaryData = binaryContent;
binary.Url = url;
return binary;
}
private IBinary GetIBinaryObject(Stream binaryStream, string url)
{
IBinary binary = new Binary();
binary.BinaryStream = binaryStream;
binary.Url = url;
return binary;
}
#endregion private
public static bool DefaultLoadBinariesAsStream = false;
private bool _loadBinariesAsStream = DefaultLoadBinariesAsStream;
public bool LoadBinariesAsStream
{
get
{
return _loadBinariesAsStream;
}
set
{
_loadBinariesAsStream = value;
}
}
[Obsolete]
public override DateTime GetLastPublishedDateCallBack(string key, object cachedItem)
{
throw new NotImplementedException();
}
public string GetUrlForUri(string uri)
{
return BinaryProvider.GetUrlForUri(uri);
}
private string StripDimensions(string path, out Dimensions dimensions)
{
Regex re = new Regex(@"_([hw])(\d+)\.");
if (re.IsMatch(path))
{
string d = re.Match(path).Groups[1].ToString();
string v = re.Match(path).Groups[2].ToString();
if (d == "h")
dimensions = new Dimensions() { Height = Convert.ToInt32(v) };
else
dimensions = new Dimensions() { Width = Convert.ToInt32(v) };
return re.Replace(path, ".");
}
dimensions = null;
return path;
}
#region inner class Dimensions
internal class Dimensions
{
internal int Width; internal int Height;
}
#endregion inner class Dimensions
}
}