Esempio n. 1
0
        public static CacheMetaData AddToCache(HttpWebResponse resp, string file)
        {
            string        md5  = resp.Headers[HttpResponseHeader.ETag].Split(':')[0].Substring(1);
            CacheMetaData meta = new CacheMetaData(resp.ContentLength, md5.ToByteArray());

            meta.Save(file);
            return(meta);
        }
Esempio n. 2
0
        public void DownloadFile(string url, string path)
        {
            Directory.CreateDirectory(Path.GetDirectoryName(path));

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
                using (Stream stream = resp.GetResponseStream())
                    using (Stream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                    {
                        CacheMetaData.AddToCache(resp, path);
                        CopyToStream(stream, fs, resp.ContentLength);
                    }
        }
Esempio n. 3
0
        public Stream OpenFile(string name, string url, bool isData)
        {
            if (!Enabled)
            {
                return(null);
            }

            if (isData && !CacheData)
            {
                return(null);
            }

            string file = cachePath + "/" + name;

            Log.Write("CDNCache: Opening file {0}", file);

            FileInfo fi = new FileInfo(file);

            if (!fi.Exists)
            {
                downloader.DownloadFile(url, file);
            }

            if (Validate)
            {
                CacheMetaData meta = CacheMetaData.Load(file) ?? downloader.GetMetaData(url, file);

                if (meta == null)
                {
                    throw new Exception(string.Format("unable to validate file {0}", file));
                }

                bool sizeOk, md5Ok;

                using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    sizeOk = fs.Length == meta.Size;
                    md5Ok  = md5.ComputeHash(fs).EqualsTo(meta.MD5);
                }

                if (!sizeOk || !md5Ok)
                {
                    downloader.DownloadFile(url, file);
                }
            }

            return(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite));
        }
Esempio n. 4
0
        public CacheMetaData GetMetaData(string url, string file)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "HEAD";

                using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
                {
                    return(CacheMetaData.AddToCache(resp, file));
                }
            }
            catch
            {
                return(null);
            }
        }