Exemplo n.º 1
0
        public ResumableUploadSession CreateResumableSession(File driveFile, long contentLength)
        {
            if (driveFile == null)
            {
                throw new ArgumentNullException("driveFile");
            }

            var fileId = string.Empty;
            var method = "POST";
            var body   = string.Empty;

            if (driveFile.Id != null)
            {
                fileId = "/" + driveFile.Id;
                method = "PUT";
            }
            else
            {
                var parents  = driveFile.Parents.FirstOrDefault();
                var folderId = parents != null ? parents.Id : null;

                var titleData  = !string.IsNullOrEmpty(driveFile.Title) ? string.Format("\"title\":\"{0}\"", driveFile.Title) : "";
                var parentData = !string.IsNullOrEmpty(folderId) ? string.Format(",\"parents\":[{{\"id\":\"{0}\"}}]", folderId) : "";

                body = !string.IsNullOrEmpty(titleData + parentData) ? string.Format("{{{0}{1}}}", titleData, parentData) : "";
            }

            var request = WebRequest.Create(GoogleUrlUpload + fileId + "?uploadType=resumable&conver=false");

            request.Method = method;

            var bytes = Encoding.UTF8.GetBytes(body);

            request.ContentLength = bytes.Length;
            request.ContentType   = "application/json; charset=UTF-8";
            request.Headers.Add("X-Upload-Content-Type", MimeMapping.GetMimeMapping(driveFile.Title));
            request.Headers.Add("X-Upload-Content-Length", contentLength.ToString(CultureInfo.InvariantCulture));
            request.Headers.Add("Authorization", "Bearer " + AccessToken);

            request.GetRequestStream().Write(bytes, 0, bytes.Length);

            var uploadSession = new ResumableUploadSession(driveFile, contentLength);

            using (var response = request.GetResponse())
            {
                uploadSession.Location = response.Headers["Location"];
            }
            uploadSession.Status = ResumableUploadSessionStatus.Started;

            return(uploadSession);
        }
Exemplo n.º 2
0
        public void Transfer(ResumableUploadSession googleDriveSession, Stream stream, long chunkLength)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (googleDriveSession.Status != ResumableUploadSessionStatus.Started)
            {
                throw new InvalidOperationException("Can't upload chunk for given upload session.");
            }

            var request = WebRequest.Create(googleDriveSession.Location);

            request.Method        = "PUT";
            request.ContentLength = chunkLength;
            request.Headers.Add("Authorization", "Bearer " + AccessToken);
            request.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}",
                                                               googleDriveSession.BytesTransfered,
                                                               googleDriveSession.BytesTransfered + chunkLength - 1,
                                                               googleDriveSession.BytesToTransfer));

            using (var requestStream = request.GetRequestStream())
            {
                stream.CopyTo(requestStream);
            }

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException exception)
            {
                if (exception.Status == WebExceptionStatus.ProtocolError)
                {
                    if (exception.Response != null && exception.Response.Headers.AllKeys.Contains("Range"))
                    {
                        response = (HttpWebResponse)exception.Response;
                    }
                    else if (exception.Message.Equals("Invalid status code: 308", StringComparison.InvariantCulture)) //response is null (unix)
                    {
                        response = null;
                    }
                    else
                    {
                        throw;
                    }
                }
                else
                {
                    throw;
                }
            }

            if (response == null || response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)
            {
                var uplSession = googleDriveSession;
                uplSession.BytesTransfered += chunkLength;

                if (response != null)
                {
                    var locationHeader = response.Headers["Location"];
                    if (!string.IsNullOrEmpty(locationHeader))
                    {
                        uplSession.Location = locationHeader;
                    }
                }
            }
            else
            {
                googleDriveSession.Status = ResumableUploadSessionStatus.Completed;

                using var responseStream = response.GetResponseStream();
                if (responseStream == null)
                {
                    return;
                }
                string responseString;
                using (var readStream = new StreamReader(responseStream))
                {
                    responseString = readStream.ReadToEnd();
                }
                var responseJson = JObject.Parse(responseString);

                googleDriveSession.FileId = responseJson.Value <string>("id");
            }

            if (response != null)
            {
                response.Close();
            }
        }
Exemplo n.º 3
0
        public void Transfer(ResumableUploadSession googleDriveSession, Stream stream, long chunkLength)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            if (googleDriveSession.Status != ResumableUploadSessionStatus.Started)
                throw new InvalidOperationException("Can't upload chunk for given upload session.");

            var request = WebRequest.Create(googleDriveSession.Location);
            request.Method = "PUT";
            request.ContentLength = chunkLength;
            request.Headers.Add("Authorization", "Bearer " + AccessToken);
            request.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}",
                                                               googleDriveSession.BytesTransfered,
                                                               googleDriveSession.BytesTransfered + chunkLength - 1,
                                                               googleDriveSession.BytesToTransfer));

            using (var requestStream = request.GetRequestStream())
            {
                stream.CopyTo(requestStream);
            }

            HttpWebResponse response;
            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException exception)
            {
                if (exception.Status == WebExceptionStatus.ProtocolError && exception.Response != null && exception.Response.Headers.AllKeys.Contains("Range"))
                {
                    response = (HttpWebResponse)exception.Response;
                }
                else
                {
                    throw;
                }
            }

            if (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)
            {
                var uplSession = googleDriveSession;
                uplSession.BytesTransfered += chunkLength;

                var locationHeader = response.Headers["Location"];
                if (!string.IsNullOrEmpty(locationHeader))
                {
                    uplSession.Location = locationHeader;
                }
            }
            else
            {
                googleDriveSession.Status = ResumableUploadSessionStatus.Completed;

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream == null) return;

                    var respFile = FileFromString(new StreamReader(responseStream).ReadToEnd());
                    var initFile = googleDriveSession.File;

                    initFile.Id = respFile.Id;
                    initFile.Title = respFile.Title;
                    initFile.MimeType = respFile.MimeType;
                    initFile.FileSize = respFile.FileSize;
                    initFile.CreatedDate = respFile.CreatedDate;
                    initFile.ModifiedDate = respFile.ModifiedDate;
                    initFile.Parents = respFile.Parents;
                }
            }

            response.Close();
        }
Exemplo n.º 4
0
        public ResumableUploadSession CreateResumableSession(File driveFile, long contentLength)
        {
            if (driveFile == null) throw new ArgumentNullException("driveFile");

            var fileId = string.Empty;
            var method = "POST";
            var body = string.Empty;
            if (driveFile.Id != null)
            {
                fileId = "/" + driveFile.Id;
                method = "PUT";
            }
            else
            {
                var parents = driveFile.Parents.FirstOrDefault();
                var folderId = parents != null ? parents.Id : null;

                var titleData = !string.IsNullOrEmpty(driveFile.Title) ? string.Format("\"title\":\"{0}\"", driveFile.Title) : "";
                var parentData = !string.IsNullOrEmpty(folderId) ? string.Format(",\"parents\":[{{\"id\":\"{0}\"}}]", folderId) : "";

                body = !string.IsNullOrEmpty(titleData + parentData) ? string.Format("{{{0}{1}}}", titleData, parentData) : "";
            }

            var request = WebRequest.Create(GoogleUrlUpload + fileId + "?uploadType=resumable&conver=false");
            request.Method = method;

            var bytes = Encoding.UTF8.GetBytes(body);
            request.ContentLength = bytes.Length;
            request.ContentType = "application/json; charset=UTF-8";
            request.Headers.Add("X-Upload-Content-Type", MimeMapping.GetMimeMapping(driveFile.Title));
            request.Headers.Add("X-Upload-Content-Length", contentLength.ToString(CultureInfo.InvariantCulture));
            request.Headers.Add("Authorization", "Bearer " + AccessToken);

            request.GetRequestStream().Write(bytes, 0, bytes.Length);

            var uploadSession = new ResumableUploadSession(driveFile, contentLength);
            using (var response = request.GetResponse())
            {
                uploadSession.Location = response.Headers["Location"];
            }
            uploadSession.Status = ResumableUploadSessionStatus.Started;

            return uploadSession;
        }
Exemplo n.º 5
0
        public void Transfer(ResumableUploadSession googleDriveSession, Stream stream, long chunkLength)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (googleDriveSession.Status != ResumableUploadSessionStatus.Started)
            {
                throw new InvalidOperationException("Can't upload chunk for given upload session.");
            }

            var request = WebRequest.Create(googleDriveSession.Location);

            request.Method        = "PUT";
            request.ContentLength = chunkLength;
            request.Headers.Add("Authorization", "Bearer " + AccessToken);
            request.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}",
                                                               googleDriveSession.BytesTransfered,
                                                               googleDriveSession.BytesTransfered + chunkLength - 1,
                                                               googleDriveSession.BytesToTransfer));

            using (var requestStream = request.GetRequestStream())
            {
                stream.CopyTo(requestStream);
            }

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException exception)
            {
                if (exception.Status == WebExceptionStatus.ProtocolError && exception.Response != null && exception.Response.Headers.AllKeys.Contains("Range"))
                {
                    response = (HttpWebResponse)exception.Response;
                }
                else
                {
                    throw;
                }
            }

            if (response.StatusCode != HttpStatusCode.Created && response.StatusCode != HttpStatusCode.OK)
            {
                var uplSession = googleDriveSession;
                uplSession.BytesTransfered += chunkLength;

                var locationHeader = response.Headers["Location"];
                if (!string.IsNullOrEmpty(locationHeader))
                {
                    uplSession.Location = locationHeader;
                }
            }
            else
            {
                googleDriveSession.Status = ResumableUploadSessionStatus.Completed;

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream == null)
                    {
                        return;
                    }

                    var respFile = FileFromString(new StreamReader(responseStream).ReadToEnd());
                    var initFile = googleDriveSession.File;

                    initFile.Id           = respFile.Id;
                    initFile.Title        = respFile.Title;
                    initFile.MimeType     = respFile.MimeType;
                    initFile.FileSize     = respFile.FileSize;
                    initFile.CreatedDate  = respFile.CreatedDate;
                    initFile.ModifiedDate = respFile.ModifiedDate;
                    initFile.Parents      = respFile.Parents;
                }
            }

            response.Close();
        }