コード例 #1
0
        // ***********************************************************************************************
        // Internal
        //------------------------------------------------------------------------------------------------
        private long getFileOffset(string URL)
        {
            var client  = new TusHTTPClient();
            var request = new TusHTTPRequest(URL);

            request.Method = "HEAD";
            request.AddHeader("Tus-Resumable", "1.0.0");
            if (autorization != null)
            {
                request.AddHeader("Authorization", autorization);
            }

            var response = client.PerformRequest(request);

            if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.OK)
            {
                if (response.Headers.ContainsKey("Upload-Offset"))
                {
                    return(long.Parse(response.Headers["Upload-Offset"]));
                }
                else
                {
                    throw new Exception("Offset Header Missing");
                }
            }
            else
            {
                throw new Exception("getFileOffset failed. " + response.ResponseString);
            }
        }
コード例 #2
0
        // ***********************************************************************************************
        // Internal
        //------------------------------------------------------------------------------------------------
        private long getFileOffset(string URL, Dictionary <string, string> headers = null)
        {
            var client  = new TusHTTPClient();
            var request = new TusHTTPRequest(URL);

            request.Method = "HEAD";
            request.AddHeader("Tus-Resumable", "1.0.0");
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }
            var response = client.PerformRequest(request);

            if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.OK)
            {
                if (response.Headers.ContainsKey("Upload-Offset"))
                {
                    return(long.Parse(response.Headers["Upload-Offset"]));
                }
                else
                {
                    throw new Exception("Offset Header Missing");
                }
            }
            else
            {
                throw new Exception("getFileOffset failed. " + response.ResponseString);
            }
        }
コード例 #3
0
        public TusServerInfo getServerInfo(string URL)
        {
            var client  = new TusHTTPClient();
            var request = new TusHTTPRequest(URL);

            request.Method = "OPTIONS";

            var response = client.PerformRequest(request);

            if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.OK)
            {
                // Spec says NoContent but tusd gives OK because of browser bugs
                var info = new TusServerInfo();
                response.Headers.TryGetValue("Tus-Resumable", out info.Version);
                response.Headers.TryGetValue("Tus-Version", out info.SupportedVersions);
                response.Headers.TryGetValue("Tus-Extension", out info.Extensions);

                string MaxSize;
                if (response.Headers.TryGetValue("Tus-Max-Size", out MaxSize))
                {
                    info.MaxSize = long.Parse(MaxSize);
                }
                else
                {
                    info.MaxSize = 0;
                }

                return(info);
            }
            else
            {
                throw new Exception("getServerInfo failed. " + response.ResponseString);
            }
        }
コード例 #4
0
        //------------------------------------------------------------------------------------------------
        public bool Delete(string URL, Dictionary <string, string> headers = null)
        {
            var client  = new TusHTTPClient();
            var request = new TusHTTPRequest(URL);

            request.Method = "DELETE";
            request.AddHeader("Tus-Resumable", "1.0.0");
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }
            var response = client.PerformRequest(request);

            if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Gone)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #5
0
        //------------------------------------------------------------------------------------------------
        public TusHTTPResponse Head(string URL, Dictionary <string, string> headers = null)
        {
            var client  = new TusHTTPClient();
            var request = new TusHTTPRequest(URL);

            request.Method = "HEAD";
            request.AddHeader("Tus-Resumable", "1.0.0");
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }
            try
            {
                var response = client.PerformRequest(request);
                return(response);
            }
            catch (TusException ex)
            {
                var response = new TusHTTPResponse();
                response.StatusCode = ex.statuscode;
                return(response);
            }
        }
コード例 #6
0
        //------------------------------------------------------------------------------------------------
        public TusHTTPResponse Download(string URL, Dictionary <string, string> headers = null)
        {
            var client = new TusHTTPClient();

            var request = new TusHTTPRequest(URL);

            request.cancelToken = this.cancelSource.Token;
            request.Method      = "GET";
            if (headers != null)
            {
                foreach (var header in headers)
                {
                    request.AddHeader(header.Key, header.Value);
                }
            }
            request.Downloading += delegate(long bytesTransferred, long bytesTotal)
            {
                if (Downloading != null)
                {
                    Downloading((long)bytesTransferred, (long)bytesTotal);
                }
            };

            var response = client.PerformRequest(request);

            return(response);
        }
コード例 #7
0
        public string Create(string URL, long UploadLength, Dictionary <string, string> metadata = null)
        {
            var requestUri = new Uri(URL);
            var client     = new TusHTTPClient();

            client.Proxy = this.Proxy;

            var request = new TusHTTPRequest(URL);

            request.Method = "POST";
            request.AddHeader("Tus-Resumable", "1.0.0");
            request.AddHeader("Upload-Length", UploadLength.ToString());
            request.AddHeader("Content-Length", "0");

            if (metadata == null)
            {
                metadata = new Dictionary <string, string>();
            }

            var metadatastrings = new List <string>();

            foreach (var meta in metadata)
            {
                string k = meta.Key.Replace(" ", "").Replace(",", "");
                string v = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(meta.Value));
                metadatastrings.Add(string.Format("{0} {1}", k, v));
            }
            request.AddHeader("Upload-Metadata", string.Join(",", metadatastrings.ToArray()));

            var response = client.PerformRequest(request);

            if (response.StatusCode == HttpStatusCode.Created)
            {
                if (response.Headers.ContainsKey("Location"))
                {
                    Uri locationUri;
                    if (Uri.TryCreate(response.Headers["Location"], UriKind.RelativeOrAbsolute, out locationUri))
                    {
                        if (!locationUri.IsAbsoluteUri)
                        {
                            locationUri = new Uri(requestUri, locationUri);
                        }
                        return(locationUri.ToString());
                    }
                    else
                    {
                        throw new Exception("Invalid Location Header");
                    }
                }
                else
                {
                    throw new Exception("Location Header Missing");
                }
            }
            else
            {
                throw new Exception("CreateFileInServer failed. " + response.ResponseString);
            }
        }
コード例 #8
0
        //------------------------------------------------------------------------------------------------
        public bool Delete(string URL)
        {
            var client  = new TusHTTPClient();
            var request = new TusHTTPRequest(URL);

            request.Method = "DELETE";
            request.AddHeader("Tus-Resumable", "1.0.0");

            var response = client.PerformRequest(request);

            if (response.StatusCode == HttpStatusCode.NoContent || response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.Gone)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
コード例 #9
0
        //------------------------------------------------------------------------------------------------
        public TusHTTPResponse Head(string URL)
        {
            var client  = new TusHTTPClient();
            var request = new TusHTTPRequest(URL);

            request.Method = "HEAD";
            request.AddHeader("Tus-Resumable", "1.0.0");

            try
            {
                var response = client.PerformRequest(request);
                return(response);
            }
            catch (TusException ex)
            {
                var response = new TusHTTPResponse();
                response.StatusCode = ex.statuscode;
                return(response);
            }
        }
コード例 #10
0
        //------------------------------------------------------------------------------------------------
        public TusHTTPResponse Download(string URL)
        {
            var client = new TusHTTPClient();

            var request = new TusHTTPRequest(URL);

            request.cancelToken = this.cancelSource.Token;
            request.Method      = "GET";

            request.Downloading += delegate(long bytesTransferred, long bytesTotal)
            {
                if (Downloading != null)
                {
                    Downloading((long)bytesTransferred, (long)bytesTotal);
                }
            };

            var response = client.PerformRequest(request);

            return(response);
        }
コード例 #11
0
        public void Upload(string URL, System.IO.Stream fs)
        {
            var Offset = this.getFileOffset(URL);
            var client = new TusHTTPClient();

            System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1Managed();
            int ChunkSize = (int)Math.Ceiling(5 * 1024.0 * 1024.0);  //3 mb

            if (Offset == fs.Length)
            {
                if (Uploading != null)
                {
                    Uploading((long)fs.Length, (long)fs.Length);
                }
            }


            while (Offset < fs.Length)
            {
                fs.Seek(Offset, SeekOrigin.Begin);
                byte[] buffer    = new byte[ChunkSize];
                var    BytesRead = fs.Read(buffer, 0, ChunkSize);

                Array.Resize(ref buffer, BytesRead);
                var sha1hash = sha.ComputeHash(buffer);

                var request = new TusHTTPRequest(URL);
                request.cancelToken = this.cancelSource.Token;
                request.Method      = "PATCH";
                if (autorization != null)
                {
                    request.AddHeader("Authorization", autorization);
                }
                request.AddHeader("Tus-Resumable", "1.0.0");
                request.AddHeader("Upload-Offset", string.Format("{0}", Offset));
                request.AddHeader("Upload-Checksum", "sha1 " + Convert.ToBase64String(sha1hash));
                request.AddHeader("Content-Type", "application/offset+octet-stream");

                request.BodyBytes = buffer;

                request.Uploading += delegate(long bytesTransferred, long bytesTotal)
                {
                    if (Uploading != null)
                    {
                        Uploading((long)Offset + bytesTransferred, (long)fs.Length);
                    }
                };

                try
                {
                    var response = client.PerformRequest(request);

                    if (response.StatusCode == HttpStatusCode.NoContent)
                    {
                        Offset += BytesRead;
                    }
                    else
                    {
                        throw new Exception("WriteFileInServer failed. " + response.ResponseString);
                    }
                }
                catch (IOException ex)
                {
                    if (ex.InnerException.GetType() == typeof(System.Net.Sockets.SocketException))
                    {
                        var socketex = (System.Net.Sockets.SocketException)ex.InnerException;
                        if (socketex.SocketErrorCode == System.Net.Sockets.SocketError.ConnectionReset)
                        {
                            // retry by continuing the while loop but get new offset from server to prevent Conflict error
                            Offset = this.getFileOffset(URL);
                        }
                        else
                        {
                            throw socketex;
                        }
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
コード例 #12
0
        public TusHTTPResponse PerformRequest(TusHTTPRequest req)
        {
            try
            {
                var instream = new MemoryStream(req.BodyBytes);

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(req.URL);
                request.AutomaticDecompression = DecompressionMethods.GZip;

                request.Timeout          = System.Threading.Timeout.Infinite;
                request.ReadWriteTimeout = System.Threading.Timeout.Infinite;
                request.Method           = req.Method;
                request.KeepAlive        = false;

                request.Proxy = this.Proxy;

                try
                {
                    ServicePoint currentServicePoint = request.ServicePoint;
                    currentServicePoint.Expect100Continue = false;
                }
                catch (PlatformNotSupportedException)
                {
                    //expected on .net core 2.0 with systemproxy
                    //fixed by https://github.com/dotnet/corefx/commit/a9e01da6f1b3a0dfbc36d17823a2264e2ec47050
                    //should work in .net core 2.2
                }


                //SEND
                req.FireUploading(0, 0);
                byte[] buffer = new byte[4096];

                long contentlength = 0;

                int  byteswritten      = 0;
                long totalbyteswritten = 0;

                contentlength = (long)instream.Length;
                request.AllowWriteStreamBuffering = false;
                request.ContentLength             = instream.Length;

                foreach (var header in req.Headers)
                {
                    switch (header.Key)
                    {
                    case "Content-Length":
                        request.ContentLength = long.Parse(header.Value);
                        break;

                    case "Content-Type":
                        request.ContentType = header.Value;
                        break;

                    default:
                        request.Headers.Add(header.Key, header.Value);
                        break;
                    }
                }

                if (req.BodyBytes.Length > 0)
                {
                    using (System.IO.Stream requestStream = request.GetRequestStream())
                    {
                        instream.Seek(0, SeekOrigin.Begin);
                        byteswritten = instream.Read(buffer, 0, buffer.Length);

                        while (byteswritten > 0)
                        {
                            totalbyteswritten += byteswritten;

                            req.FireUploading(totalbyteswritten, contentlength);

                            requestStream.Write(buffer, 0, byteswritten);

                            byteswritten = instream.Read(buffer, 0, buffer.Length);

                            req.cancelToken.ThrowIfCancellationRequested();
                        }
                    }
                }

                req.FireDownloading(0, 0);

                HttpWebResponse response = (HttpWebResponse)request.GetResponse();


                contentlength = 0;
                contentlength = (long)response.ContentLength;
                //contentlength=0 for gzipped responses due to .net bug

                buffer = new byte[16 * 1024];
                var outstream = new MemoryStream();

                using (Stream responseStream = response.GetResponseStream())
                {
                    int  bytesread      = 0;
                    long totalbytesread = 0;

                    bytesread = responseStream.Read(buffer, 0, buffer.Length);

                    while (bytesread > 0)
                    {
                        totalbytesread += bytesread;

                        req.FireDownloading(totalbytesread, contentlength);

                        outstream.Write(buffer, 0, bytesread);

                        bytesread = responseStream.Read(buffer, 0, buffer.Length);

                        req.cancelToken.ThrowIfCancellationRequested();
                    }
                }

                TusHTTPResponse resp = new TusHTTPResponse();
                resp.ResponseBytes = outstream.ToArray();
                resp.StatusCode    = response.StatusCode;
                foreach (string headerName in response.Headers.Keys)
                {
                    resp.Headers[headerName] = response.Headers[headerName];
                }

                return(resp);
            }
            catch (OperationCanceledException cancelEx)
            {
                TusException rex = new TusException(cancelEx);
                throw rex;
            }
            catch (WebException ex)
            {
                TusException rex = new TusException(ex);
                throw rex;
            }
        }