예제 #1
0
        public async Task <IUploadRequest> StartUploadFileAsync(IBinaryContent fileContent,
                                                                int chunkSize = DEFAULT_UPLOAD_CHUNK_SIZE)
        {
            if (!fileContent.Data.CanRead)
            {
                throw new ArgumentException("fileContent should be readable");
            }
            if (fileContent.Data.CanSeek && fileContent.Data.Position > 0)
            {
                fileContent.Data.Position = 0;
            }

            UploadTicket ticket = await GetUploadTicketAsync();

            var uploadRequest = new UploadRequest
            {
                Ticket    = ticket,
                File      = fileContent,
                ChunkSize = chunkSize
            };

            VerifyUploadResponse uploadStatus = await ContinueUploadFileAsync(uploadRequest);

            uploadRequest.BytesWritten = uploadStatus.BytesWritten;

            return(uploadRequest);
        }
예제 #2
0
        public async Task <IUploadRequest> StartUploadFileAsync(IBinaryContent fileContent,
                                                                int chunkSize       = DEFAULT_UPLOAD_CHUNK_SIZE,
                                                                long?replaceVideoId = null)
        {
            if (!fileContent.Data.CanRead)
            {
                throw new ArgumentException("fileContent should be readable");
            }
            if (fileContent.Data.CanSeek && fileContent.Data.Position > 0)
            {
                fileContent.Data.Position = 0;
            }

            UploadTicket ticket = replaceVideoId.HasValue
                ? await GetReplaceVideoUploadTicketAsync(replaceVideoId.Value)
                : await GetUploadTicketAsync();

            var uploadRequest = new UploadRequest
            {
                Ticket    = ticket,
                File      = fileContent,
                ChunkSize = chunkSize
            };

            VerifyUploadResponse uploadStatus = await ContinueUploadFileAsync(uploadRequest);

            return(uploadRequest);
        }
예제 #3
0
        /// <summary>
        /// Complete upload file form
        /// </summary>
        /// <param name="ticket">Ticket</param>
        /// <returns></returns>
        public async Task <int> CompleteFileTicketAsync(UploadTicket ticket)
        {
            ThrowIfUnauthorized();

            try
            {
                var request  = GenerateCompleteUploadRequest(ticket);
                var response = await request.ExecuteRequestAsync();

                //CheckStatusCodeError(uploadRequest, response, "Error marking file upload as complete.");

                /*
                 * if (response.Headers.Location != null)
                 * {
                 *  uploadRequest.ClipUri = response.Headers.Location.ToString();
                 * }
                 */
                System.Collections.Generic.IEnumerable <string> i;

                string l    = response.Headers.TryGetValues("Location", out i)? i.First(): "";
                Regex  word = new Regex(@"([0-9]*)$");
                Match  m    = word.Match(l);
                return(int.Parse(m.Value));
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                return(-1);
                //throw new VimeoUploadException("Error marking file upload as complete.", uploadRequest, ex);
            }
        }
예제 #4
0
        private IApiRequest GenerateCompleteUploadRequest(UploadTicket ticket)
        {
            IApiRequest request = _apiRequestFactory.GetApiRequest(AccessToken);

            request.Method = Method.DELETE;
            request.Path   = ticket.complete_uri;
            return(request);
        }
예제 #5
0
        private IApiRequest GenerateCompleteUploadRequest(UploadTicket ticket)
        {
            var request = _apiRequestFactory.GetApiRequest(AccessToken);

            request.Method = HttpMethod.Delete;
            request.Path   = ticket.CompleteUri;
            return(request);
        }
예제 #6
0
파일: Methods.cs 프로젝트: llenroc/InfoHub
        public string UploadSingleFile(string filePath)
        {
            UploadTicket ticket   = GetUploadTicket();
            string       fileHash = FileUpload(filePath, ticket);
            XmlDocument  xmlDoc   = _utils.GenerateUploadManifest(fileHash, null);

            return(ConfirmUpload(ticket.Ticket, xmlDoc));
        }
예제 #7
0
        public void Integration_VimeoClient_GetUploadTicket_CanGenerateStreamingTicket()
        {
            // arrange
            VimeoClient client = CreateAuthenticatedClient();

            // act
            UploadTicket ticket = client.GetUploadTicket();

            // assert
            Assert.IsNotNull(ticket);
        }
        public void Integration_VimeoClient_GetReplaceVideoUploadTicket_CanGenerateStreamingTicket()
        {
            // arrange
            VimeoClient client = CreateAuthenticatedClient();

            // act
            UploadTicket ticket = client.GetReplaceVideoUploadTicket(vimeoSettings.VideoId);

            // assert
            ticket.ShouldNotBeNull();
        }
예제 #9
0
        private void uploadFiles_do(object sender, DoWorkEventArgs e)
        {
            uploadError = false;
            updateStatus("Ready to upload " + osuUploadTickets.Count + " files.");
            for (int i = 0; i < osuUploadTickets.Count; i++)
            {
                UploadTicket sp = osuUploadTickets[i];
                updateStatus(String.Format("Uploading {0}...", Path.GetFileName(sp.Filename)));

                string url =
                    string.Format("http://peppy.chigau.com/upload.php?u={0}&p={1}&c={2}&of={3}&oc={4}&r={5}",
                                  ConfigManager.sUsername, ConfigManager.sPassword, sp.Ticket,
                                  GeneralHelper.UrlEncode(oszFilename), oszTicket, (i == 0 ? 1 : 0));
                FileStream f    = File.OpenRead(sp.Filename);
                byte[]     file = new byte[f.Length];
                f.Read(file, 0, (int)f.Length);
                f.Close();
                try
                {
                    fileUpload           = new FileUploadNetRequest(url, file, Path.GetFileName(sp.Filename), "osu");
                    fileUpload.onUpdate += up_onUpdate;
                    string error = fileUpload.BlockingPerform();
                    Console.WriteLine(error);
                    fileUpload.onUpdate -= up_onUpdate;
                }
                catch (Exception)
                {
                    uploadError = true;
                }
                progress = (int)((float)(i + 1) / osuUploadTickets.Count * 100);
            }

            if (oszFilename != null)
            {
                File.Delete(oszFilename);
            }

            if (hasVideo)
            {
                updateStatus("Creating no-video file...");
                string url = string.Format("http://peppy.chigau.com/novideo.php?file={0}",
                                           GeneralHelper.UrlEncode(oszFilename));
                DataNetRequest r = new DataNetRequest(url);
                r.onFinish += r_onFinish;
                NetManager.AddRequest(r);
                while (!noVideoFinished)
                {
                    Thread.Sleep(100);
                }
            }
        }
예제 #10
0
파일: Methods.cs 프로젝트: llenroc/InfoHub
        public UploadTicket GetUploadTicket()
        {
            Validate();

            UploadTicket UT = new UploadTicket();
            XmlDocument  xd = new XmlDocument();

            if (!CallMethod(videos_getUploadTicket, xd))
            {
                return(null);
            }

            UT.Ticket = xd.DocumentElement.SelectSingleNode("ticket").Attributes["id"].Value;
            UT.URI    = xd.DocumentElement.SelectSingleNode("ticket").Attributes["endpoint"].Value;

            SortedList parms = new SortedList();

            parms[Parameters.AUTHTOKEN] = _auth.Token;

            UT.URI = _utils.GetMethodURI(UT.URI, parms, _auth);

            return(UT);
        }
예제 #11
0
        private async Task <IApiRequest> GenerateFileStreamRequest(IBinaryContent fileContent, UploadTicket ticket,
                                                                   long written = 0, int?chunkSize = null, bool verifyOnly = false)
        {
            if (ticket == null || string.IsNullOrWhiteSpace(ticket.ticket_id))
            {
                throw new ArgumentException("Invalid upload ticket.");
            }
            if (fileContent.Data.Length > ticket.user.upload_quota.space.free)
            {
                throw new InvalidOperationException(
                          "User does not have enough free space to upload this video. Remaining space: " +
                          ticket.quota.free_space + ".");
            }

            IApiRequest request = _apiRequestFactory.GetApiRequest();

            request.Method = Method.PUT;
            request.ExcludeAuthorizationHeader = true;
            request.Path = ticket.upload_link_secure;
            request.Headers.Add(Request.HeaderContentType, fileContent.ContentType);
            if (verifyOnly)
            {
                request.Headers.Add(Request.HeaderContentLength, "0");
                request.Headers.Add(Request.HeaderContentRange, "bytes */*");
            }
            else
            {
                if (chunkSize.HasValue)
                {
                    long startIndex = fileContent.Data.CanSeek ? fileContent.Data.Position : written;
                    long endIndex   = Math.Min(startIndex + chunkSize.Value, fileContent.Data.Length);
                    request.Headers.Add(Request.HeaderContentLength, (endIndex - startIndex).ToString());
                    request.Headers.Add(Request.HeaderContentRange,
                                        string.Format("bytes {0}-{1}/{2}", startIndex, endIndex, fileContent.Data.Length));
                    request.BinaryContent = await fileContent.ReadAsync(startIndex, endIndex);
                }
                else
                {
                    request.Headers.Add(Request.HeaderContentLength, fileContent.Data.Length.ToString());
                    request.BinaryContent = await fileContent.ReadAllAsync();
                }
            }

            return(request);
        }
예제 #12
0
        private async Task <IApiRequest> GenerateFileStreamRequest(IBinaryContent fileContent, UploadTicket ticket,
                                                                   long written = 0, int?chunkSize = null, bool verifyOnly = false)
        {
            if (string.IsNullOrWhiteSpace(ticket?.TicketId))
            {
                throw new ArgumentException("Invalid upload ticket.");
            }

            if (fileContent.Data.Length > ticket.User.UploadQuota.Space.Free)
            {
                throw new InvalidOperationException(
                          "User does not have enough free space to upload this video. Remaining space: " +
                          ticket.Quota.FreeSpace + ".");
            }

            var request = _apiRequestFactory.GetApiRequest();

            request.Method = HttpMethod.Put;
            request.ExcludeAuthorizationHeader = true;
            request.Path = ticket.UploadLinkSecure;

            if (verifyOnly)
            {
                var body = new ByteArrayContent(new byte[0]);
                body.Headers.Add("Content-Range", "bytes */*");
                body.Headers.ContentLength = 0;
                request.Body = body;
            }
            else
            {
                if (chunkSize.HasValue)
                {
                    var startIndex = fileContent.Data.CanSeek ? fileContent.Data.Position : written;
                    var endIndex   = Math.Min(startIndex + chunkSize.Value, fileContent.Data.Length);
                    var byteArray  = await fileContent.ReadAsync(startIndex, endIndex).ConfigureAwait(false);

                    var body = new ByteArrayContent(byteArray, 0, byteArray.Length);
                    body.Headers.Add("Content-Range", $"bytes {startIndex}-{endIndex}/*");
                    body.Headers.ContentLength = endIndex - startIndex;
                    request.Body = body;
                }
                else
                {
                    request.Body = new ByteArrayContent(await fileContent.ReadAllAsync().ConfigureAwait(false));
                }
            }

            return(request);
        }
예제 #13
0
        private async Task <IApiRequest> GenerateFileStreamRequest(IBinaryContent fileContent, UploadTicket ticket,
                                                                   long written = 0, int?chunkSize = null, bool verifyOnly = false)
        {
            if (ticket == null || string.IsNullOrWhiteSpace(ticket.ticket_id))
            {
                throw new ArgumentException("Invalid upload ticket.");
            }
            if (fileContent.Data.Length > ticket.user.upload_quota.space.free)
            {
                throw new InvalidOperationException(
                          "User does not have enough free space to upload this video. Remaining space: " +
                          ticket.quota.free_space + ".");
            }

            var request = ApiRequestFactory.GetApiRequest();

            request.Method = HttpMethod.Put;
            request.ExcludeAuthorizationHeader = true;
            request.Path = ticket.upload_link_secure;

            if (verifyOnly)
            {
                request.Body = new ByteArrayContent(new byte [0]);
            }
            else
            {
                if (chunkSize.HasValue)
                {
                    var startIndex = fileContent.Data.CanSeek ? fileContent.Data.Position : written;
                    var endIndex   = Math.Min(startIndex + chunkSize.Value, fileContent.Data.Length);
                    request.Body = new ByteArrayContent(await fileContent.ReadAsync(startIndex, endIndex), (int)startIndex, (int)endIndex);
                }
                else
                {
                    request.Body = new ByteArrayContent(await fileContent.ReadAllAsync());
                }
            }

            return(request);
        }
예제 #14
0
파일: Methods.cs 프로젝트: llenroc/InfoHub
        public string FileUpload(string filePath, UploadTicket UT)
        {
            Validate();

            var sl = new SortedList {
                { Parameters.TICKETID, UT.Ticket }, { Parameters.AUTHTOKEN, _auth.Token }
            };

            UT.URI = UT.URI.Remove(UT.URI.IndexOf('?'));
            var url = _utils.GetMethodURI(UT.URI, sl, _auth);

            // create the request
            var request = WebRequest.Create(url) as HttpWebRequest;

            // get a boundary string - used to separate parts of the form data
            var boundary = String.Format("----------{0:B}", Guid.NewGuid());

            // set the content type and method
            request.ContentType = String.Format("multipart/form-data; boundary={0}", boundary);
            request.Method      = "POST";
            request.KeepAlive   = true;
            request.Credentials = System.Net.CredentialCache.DefaultCredentials;

            // build the form part header
            var header = new StringBuilder();

            header.AppendFormat("--{0}\r\n", boundary);
            header.AppendFormat("Content-Disposition: form-data; name=\"file_data\"; filename=\"{0}\"\r\n", Path.GetFileName(filePath), filePath);
            header.Append("Content-Type: application/octet-stream\r\n\r\n");

            // get the header as bytes
            var headerBytes = Encoding.ASCII.GetBytes(header.ToString());

            // read the file
            var fileBytes = File.ReadAllBytes(filePath);

            // get the footer bytes
            byte[] footerBytes = Encoding.ASCII.GetBytes(String.Format("\r\n--{0}--", boundary));

            // get the complete set of bytes
            byte[] data = headerBytes
                          .Concat(fileBytes)
                          .Concat(footerBytes).ToArray();

            // set the content length
            request.ContentLength = data.Length;

            // write the bytes to the request stream
            using (Stream s = request.GetRequestStream())
            {
                s.Write(data, 0, data.Length);
            }

            // get the response
            var response = request.GetResponse() as HttpWebResponse;

            Stream responseStream = response.GetResponseStream();
            var    responseReader = new StreamReader(responseStream);

            return(responseReader.ReadToEnd());
        }