Merge pull request #403 from NextTurn/ims

Support 'If-Modified-Since' for downloads
pull/449/head^2
Oleg Nenashev 2020-03-25 11:05:52 +01:00 committed by GitHub
commit ecadc0ef8b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 48 additions and 20 deletions

View File

@ -6,9 +6,7 @@ using System.Text;
using System.Threading.Tasks; using System.Threading.Tasks;
#endif #endif
using System.Xml; using System.Xml;
#if !VNEXT
using log4net; using log4net;
#endif
using winsw.Util; using winsw.Util;
namespace winsw namespace winsw
@ -26,9 +24,7 @@ namespace winsw
basic basic
} }
#if !VNEXT
private static readonly ILog Logger = LogManager.GetLogger(typeof(Download)); private static readonly ILog Logger = LogManager.GetLogger(typeof(Download));
#endif
public readonly string From; public readonly string From;
public readonly string To; public readonly string To;
@ -163,7 +159,17 @@ namespace winsw
throw new WebException("Code defect. Unsupported authentication type: " + Auth); throw new WebException("Code defect. Unsupported authentication type: " + Auth);
} }
bool supportsIfModifiedSince = false;
if (request is HttpWebRequest httpRequest && File.Exists(To))
{
supportsIfModifiedSince = true;
httpRequest.IfModifiedSince = File.GetLastWriteTime(To);
}
DateTime lastModified = default;
string tmpFilePath = To + ".tmp"; string tmpFilePath = To + ".tmp";
try
{
#if VNEXT #if VNEXT
using (WebResponse response = await request.GetResponseAsync()) using (WebResponse response = await request.GetResponseAsync())
#else #else
@ -172,6 +178,11 @@ namespace winsw
using (Stream responseStream = response.GetResponseStream()) using (Stream responseStream = response.GetResponseStream())
using (FileStream tmpStream = new FileStream(tmpFilePath, FileMode.Create)) using (FileStream tmpStream = new FileStream(tmpFilePath, FileMode.Create))
{ {
if (supportsIfModifiedSince)
{
lastModified = ((HttpWebResponse)response).LastModified;
}
#if VNEXT #if VNEXT
await responseStream.CopyToAsync(tmpStream); await responseStream.CopyToAsync(tmpStream);
#elif NET20 #elif NET20
@ -182,6 +193,23 @@ namespace winsw
} }
FileHelper.MoveOrReplaceFile(To + ".tmp", To); FileHelper.MoveOrReplaceFile(To + ".tmp", To);
if (supportsIfModifiedSince)
{
File.SetLastWriteTime(To, lastModified);
}
}
catch (WebException e)
{
if (supportsIfModifiedSince && ((HttpWebResponse)e.Response).StatusCode == HttpStatusCode.NotModified)
{
Logger.Info($"Skipped downloading unmodified resource '{From}'");
}
else
{
throw;
}
}
} }
#if NET20 #if NET20