Skip to content

Commit

Permalink
Fix typo
Browse files Browse the repository at this point in the history
  • Loading branch information
Kees committed Oct 12, 2023
1 parent 7f5b494 commit 335a641
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 27 deletions.
2 changes: 1 addition & 1 deletion ChromiumHtmlToPdfConsole/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"profiles": {
"ChromeHtmlToPdf": {
"commandName": "Project",
"commandLineArgs": "--input \"https://www.google.nl\" --output d:\\test.pdf --log-network-traffic --media-load-timeout 5000 --image-resize true --image-load-timeout 5000 --paper-format A4 --sanitize-html"
"commandLineArgs": "--input \"d:\\test.html\" --output d:\\test.pdf --log-network-traffic --media-load-timeout 5000 --image-resize true --image-load-timeout 5000 --paper-format A4 --sanitize-html"
}
}
}
2 changes: 1 addition & 1 deletion ChromiumHtmlToPdfLib/Converter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ public bool DiskCacheDisabled
/// <remarks>
/// https://developer.chrome.com/articles/new-headless/
/// </remarks>
public bool UseOldHeaslessMode { get; set; }
public bool UseOldHeadlessMode { get; set; }
#endregion

#region Constructor & Destructor
Expand Down
49 changes: 24 additions & 25 deletions ChromiumHtmlToPdfLib/Helpers/DocumentHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Cache;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading;
Expand Down Expand Up @@ -152,12 +151,10 @@ public DocumentHelper(DirectoryInfo tempDirectory,
_useCache = useCache;
_logger = logger;

if (imageLoadTimeout.HasValue)
{
_imageLoadTimeout = imageLoadTimeout.Value;
WriteToLog($"Setting image load timeout to '{_imageLoadTimeout}' milliseconds");
_stopwatch = Stopwatch.StartNew();
}
if (!imageLoadTimeout.HasValue) return;
_imageLoadTimeout = imageLoadTimeout.Value;
WriteToLog($"Setting image load timeout to '{_imageLoadTimeout}' milliseconds");
_stopwatch = Stopwatch.StartNew();
}
#endregion

Expand Down Expand Up @@ -903,31 +900,33 @@ private async Task<Stream> OpenDownloadStream(Uri sourceUri, bool checkTimeout =
{
try
{
var request = WebRequest.Create(sourceUri);
var httpClientHandler = new HttpClientHandler();

if (_webProxy != null)
httpClientHandler.Proxy = _webProxy;

var handler = new FileCacheHandler(httpClientHandler);
using var client = new HttpClient(handler);
var timeLeft = TimeLeft;

if (_stopwatch != null && checkTimeout)
{
if (timeLeft == 0)
{
WriteToLog($"Image load has timed out, skipping opening stream to url '{sourceUri}'");
return null;
}
//if (_stopwatch != null && checkTimeout)
//{
// if (timeLeft == 0)
// {
// WriteToLog($"Image load has timed out, skipping opening stream to url '{sourceUri}'");
// return null;
// }

request.Timeout = TimeLeft;
}
// request.Timeout = TimeLeft;
//}

if (_webProxy != null)
request.Proxy = _webProxy;

if (_useCache)
request.CachePolicy = new HttpRequestCachePolicy(HttpCacheAgeControl.MaxAge, TimeSpan.FromDays(1));

WriteToLog($"Opening stream to url '{sourceUri}'{(_stopwatch != null ? $" with a timeout of {timeLeft} milliseconds" : string.Empty)}");
var response = (HttpWebResponse)await request.GetResponseAsync();

WriteToLog($"Opened {(response.IsFromCache ? "cached " : string.Empty)}stream to url '{sourceUri}'");
return response.GetResponseStream();
var response = await client.GetAsync(sourceUri);
//WriteToLog($"Opened {(response.IsFromCache ? "cached " : string.Empty)}stream to url '{sourceUri}'");
return await response.Content.ReadAsStreamAsync();
}
catch (Exception exception)
{
Expand Down
63 changes: 63 additions & 0 deletions ChromiumHtmlToPdfLib/Helpers/FileCacheHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ChromiumHtmlToPdfLib.Helpers;

internal class FileCacheHandler : HttpClientHandler
{
HttpClientHandler _httpClientHandler;

public FileCacheHandler(HttpClientHandler httpClientHandler, DirectoryInfo cacheFolder)
{
_httpClientHandler = httpClientHandler;
}

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var hash = GetMd5HashFromString(request.RequestUri.ToString());

if (File.Exists(hash))
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(new FileStream(hash, FileMode.OpenOrCreate)),
ReasonPhrase = "Loaded from cache"
};
return Task.FromResult(response);
}

var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(new FileStream(hash, FileMode.OpenOrCreate)),
ReasonPhrase = "Loaded from cache"
};

return Task.FromResult(response);

//throw new NotImplementedException();
return base.SendAsync(request, cancellationToken);
}

#region GetMd5HashFromString
/// <summary>
/// Retourneert een MD5 hash voor de opgegeven <paramref name="value" />
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public string GetMd5HashFromString(string value)
{
value ??= string.Empty;
using var md5 = MD5.Create();
var bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(value));
return bytes.Aggregate(string.Empty, (current, b) => current + b.ToString("X2"));
}
#endregion
}

0 comments on commit 335a641

Please sign in to comment.