123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403 |
- #if !BESTHTTP_DISABLE_CACHING && (!UNITY_WEBGL || UNITY_EDITOR)
- using System;
- using System.Collections.Generic;
- #if NETFX_CORE
- using FileStream = BestHTTP.PlatformSupport.IO.FileStream;
- using Directory = BestHTTP.PlatformSupport.IO.Directory;
- using File = BestHTTP.PlatformSupport.IO.File;
- using BestHTTP.PlatformSupport.IO;
- #else
- using FileStream = System.IO.FileStream;
- using System.IO;
- #endif
- namespace BestHTTP.Caching
- {
- using BestHTTP.Extensions;
-
-
-
- public class HTTPCacheFileInfo : IComparable<HTTPCacheFileInfo>
- {
- #region Properties
-
-
-
- internal Uri Uri { get; set; }
-
-
-
- internal DateTime LastAccess { get; set; }
-
-
-
- public int BodyLength { get; set; }
-
-
-
- private string ETag { get; set; }
-
-
-
- private string LastModified { get; set; }
-
-
-
- private DateTime Expires { get; set; }
-
-
-
- private long Age { get; set; }
-
-
-
- private long MaxAge { get; set; }
-
-
-
- private DateTime Date { get; set; }
-
-
-
- private bool MustRevalidate { get; set; }
-
-
-
- private DateTime Received { get; set; }
-
-
-
- private string ConstructedPath { get; set; }
-
-
-
- internal UInt64 MappedNameIDX { get; set; }
- #endregion
- #region Constructors
- internal HTTPCacheFileInfo(Uri uri)
- :this(uri, DateTime.UtcNow, -1)
- {
- }
- internal HTTPCacheFileInfo(Uri uri, DateTime lastAcces, int bodyLength)
- {
- this.Uri = uri;
- this.LastAccess = lastAcces;
- this.BodyLength = bodyLength;
- this.MaxAge = -1;
- this.MappedNameIDX = HTTPCacheService.GetNameIdx();
- }
- internal HTTPCacheFileInfo(Uri uri, System.IO.BinaryReader reader, int version)
- {
- this.Uri = uri;
- this.LastAccess = DateTime.FromBinary(reader.ReadInt64());
- this.BodyLength = reader.ReadInt32();
- switch(version)
- {
- case 2:
- this.MappedNameIDX = reader.ReadUInt64();
- goto case 1;
- case 1:
- {
- this.ETag = reader.ReadString();
- this.LastModified = reader.ReadString();
- this.Expires = DateTime.FromBinary(reader.ReadInt64());
- this.Age = reader.ReadInt64();
- this.MaxAge = reader.ReadInt64();
- this.Date = DateTime.FromBinary(reader.ReadInt64());
- this.MustRevalidate = reader.ReadBoolean();
- this.Received = DateTime.FromBinary(reader.ReadInt64());
- break;
- }
- }
- }
- #endregion
- #region Helper Functions
- internal void SaveTo(System.IO.BinaryWriter writer)
- {
- writer.Write(LastAccess.ToBinary());
- writer.Write(BodyLength);
- writer.Write(MappedNameIDX);
- writer.Write(ETag);
- writer.Write(LastModified);
- writer.Write(Expires.ToBinary());
- writer.Write(Age);
- writer.Write(MaxAge);
- writer.Write(Date.ToBinary());
- writer.Write(MustRevalidate);
- writer.Write(Received.ToBinary());
- }
- public string GetPath()
- {
- if (ConstructedPath != null)
- return ConstructedPath;
- return ConstructedPath = System.IO.Path.Combine(HTTPCacheService.CacheFolder, MappedNameIDX.ToString("X"));
- }
- public bool IsExists()
- {
- if (!HTTPCacheService.IsSupported)
- return false;
- return File.Exists(GetPath());
- }
- internal void Delete()
- {
- if (!HTTPCacheService.IsSupported)
- return;
- string path = GetPath();
- try
- {
- File.Delete(path);
- }
- catch
- { }
- finally
- {
- Reset();
- }
- }
- private void Reset()
- {
-
- this.BodyLength = -1;
- this.ETag = string.Empty;
- this.Expires = DateTime.FromBinary(0);
- this.LastModified = string.Empty;
- this.Age = 0;
- this.MaxAge = -1;
- this.Date = DateTime.FromBinary(0);
- this.MustRevalidate = false;
- this.Received = DateTime.FromBinary(0);
- }
- #endregion
- #region Caching
- private void SetUpCachingValues(HTTPResponse response)
- {
- response.CacheFileInfo = this;
- this.ETag = response.GetFirstHeaderValue("ETag").ToStrOrEmpty();
- this.Expires = response.GetFirstHeaderValue("Expires").ToDateTime(DateTime.FromBinary(0));
- this.LastModified = response.GetFirstHeaderValue("Last-Modified").ToStrOrEmpty();
- this.Age = response.GetFirstHeaderValue("Age").ToInt64(0);
- this.Date = response.GetFirstHeaderValue("Date").ToDateTime(DateTime.FromBinary(0));
- string cacheControl = response.GetFirstHeaderValue("cache-control");
- if (!string.IsNullOrEmpty(cacheControl))
- {
- string[] kvp = cacheControl.FindOption("max-age");
- if (kvp != null)
- {
-
- double maxAge;
- if (double.TryParse(kvp[1], out maxAge))
- this.MaxAge = (int)maxAge;
- }
- this.MustRevalidate = cacheControl.ToLower().Contains("must-revalidate");
- }
- this.Received = DateTime.UtcNow;
- }
- internal bool WillExpireInTheFuture()
- {
- if (!IsExists())
- return false;
- if (MustRevalidate)
- return false;
-
-
- if (MaxAge != -1)
- {
-
-
- long apparent_age = Math.Max(0, (long)(Received - Date).TotalSeconds);
- long corrected_received_age = Math.Max(apparent_age, Age);
- long resident_time = (long)(DateTime.UtcNow - Date).TotalSeconds;
- long current_age = corrected_received_age + resident_time;
- return current_age < MaxAge;
- }
- return Expires > DateTime.UtcNow;
- }
- internal void SetUpRevalidationHeaders(HTTPRequest request)
- {
- if (!IsExists())
- return;
-
-
-
- if (!string.IsNullOrEmpty(ETag))
- request.AddHeader("If-None-Match", ETag);
- if (!string.IsNullOrEmpty(LastModified))
- request.AddHeader("If-Modified-Since", LastModified);
- }
- public System.IO.Stream GetBodyStream(out int length)
- {
- if (!IsExists())
- {
- length = 0;
- return null;
- }
- length = BodyLength;
- LastAccess = DateTime.UtcNow;
- FileStream stream = new FileStream(GetPath(), FileMode.Open, FileAccess.Read, FileShare.Read);
- stream.Seek(-length, System.IO.SeekOrigin.End);
- return stream;
- }
- internal HTTPResponse ReadResponseTo(HTTPRequest request)
- {
- if (!IsExists())
- return null;
- LastAccess = DateTime.UtcNow;
- using (FileStream stream = new FileStream(GetPath(), FileMode.Open, FileAccess.Read, FileShare.Read))
- {
- var response = new HTTPResponse(request, stream, request.UseStreaming, true);
- response.CacheFileInfo = this;
- response.Receive(BodyLength);
- return response;
- }
- }
- internal void Store(HTTPResponse response)
- {
- if (!HTTPCacheService.IsSupported)
- return;
- string path = GetPath();
-
- if (path.Length > HTTPManager.MaxPathLength)
- return;
- if (File.Exists(path))
- Delete();
- using (FileStream writer = new FileStream(path, FileMode.Create))
- {
- writer.WriteLine("HTTP/1.1 {0} {1}", response.StatusCode, response.Message);
- foreach (var kvp in response.Headers)
- {
- for (int i = 0; i < kvp.Value.Count; ++i)
- writer.WriteLine("{0}: {1}", kvp.Key, kvp.Value[i]);
- }
- writer.WriteLine();
- writer.Write(response.Data, 0, response.Data.Length);
- }
- BodyLength = response.Data.Length;
- LastAccess = DateTime.UtcNow;
- SetUpCachingValues(response);
- }
- internal System.IO.Stream GetSaveStream(HTTPResponse response)
- {
- if (!HTTPCacheService.IsSupported)
- return null;
- LastAccess = DateTime.UtcNow;
- string path = GetPath();
- if (File.Exists(path))
- Delete();
-
- if (path.Length > HTTPManager.MaxPathLength)
- return null;
-
- using (FileStream writer = new FileStream(path, FileMode.Create))
- {
- writer.WriteLine("HTTP/1.1 {0} {1}", response.StatusCode, response.Message);
- foreach (var kvp in response.Headers)
- {
- for (int i = 0; i < kvp.Value.Count; ++i)
- writer.WriteLine("{0}: {1}", kvp.Key, kvp.Value[i]);
- }
- writer.WriteLine();
- }
-
- if (response.IsFromCache && !response.Headers.ContainsKey("content-length"))
- response.Headers.Add("content-length", new List<string> { BodyLength.ToString() });
- SetUpCachingValues(response);
-
- return new FileStream(GetPath(), FileMode.Append);
- }
- #endregion
- #region IComparable<HTTPCacheFileInfo>
- public int CompareTo(HTTPCacheFileInfo other)
- {
- return this.LastAccess.CompareTo(other.LastAccess);
- }
- #endregion
- }
- }
- #endif
|