コード例 #1
0
        /// <summary>
        /// Complete upload file asynchronously
        /// </summary>
        /// <param name="uploadRequest">UploadRequest</param>
        /// <returns></returns>
        private async Task CompleteFileUploadAsync(IUploadRequest uploadRequest)
        {
            ThrowIfUnauthorized();

            try
            {
                var request  = GenerateCompleteUploadRequest(uploadRequest.Ticket);
                var response = await request.ExecuteRequestAsync().ConfigureAwait(false);

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

                if (response.Headers.Location != null)
                {
                    uploadRequest.ClipUri = response.Headers.Location.ToString();
                }
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }

                throw new VimeoUploadException("Error marking file upload as complete.", uploadRequest, ex);
            }
        }
コード例 #2
0
        public async Task CompleteFileUploadAsync(IUploadRequest uploadRequest)
        {
            ThrowIfUnauthorized();

            try
            {
                IApiRequest   request  = GenerateCompleteUploadRequest(uploadRequest.Ticket);
                IRestResponse response = await request.ExecuteRequestAsync();

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

                Parameter locationHeader =
                    response.Headers.FirstOrDefault(h => string.Compare(h.Name, "Location", true) == 0);
                if (locationHeader != null && locationHeader.Value != null)
                {
                    uploadRequest.ClipUri = locationHeader.Value as string;
                }
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoUploadException("Error marking file upload as complete.", uploadRequest, ex);
            }
        }
コード例 #3
0
        public T Execute <T>(IRequest <T> request, string session, string appAuthToken) where T : IResponse
        {
            // 构造请求参数
            ParamDictionary requestParams = buildRequestParams(request, session, appAuthToken);

            // 字典排序
            IDictionary <string, string> sortedParams = new SortedDictionary <string, string>(requestParams);
            ParamDictionary sortedDic = new ParamDictionary(sortedParams);

            // 参数签名
            string charset = string.IsNullOrEmpty(this.charset) ? "utf-8" : this.charset;
            //string signResult = Signature.RSASign(sortedDic, privateKeyPem, charset, this.keyFromFile, this.signType);
            //// 添加签名结果参数
            //sortedDic.Add(SIGN, signResult);

            // 参数拼接
            string signedResult = WebUtils.BuildQuery(sortedDic, charset);
            var    txtParams    = sortedDic;


            // 是否需要上传文件
            string body;
            string requestBody = null;
            string url         = "";                                // this.serverUrl + "?" + CHARSET + "=" + this.charset;

            url = GetFullUrl(this.serverUrl, request.GetApiName()); // + "?" + CHARSET + "=" + this.charset;
            if (request is IUploadRequest <T> )
            {
                IUploadRequest <T>             uRequest   = (IUploadRequest <T>)request;
                IDictionary <string, FileItem> fileParams = SdkUtils.CleanupDictionary(uRequest.GetFileParameters());
                body = webUtils.DoPost(url, txtParams, fileParams, this.charset, out requestBody);
            }
            else
            {
                body = webUtils.DoPost(url, txtParams, this.charset, out requestBody);
            }

            T           rsp    = null;
            IParser <T> parser = null;

            if ("xml".Equals(format))
            {
                parser = new XmlParser <T>();
                rsp    = parser.Parse(body, charset);
            }
            else
            {
                parser = new JsonParser <T>();
                rsp    = parser.Parse(body, charset);
            }

            ResponseParseItem item = parseRespItem(request, body, parser, this.encyptKey, this.encyptType, charset);

            rsp             = parser.Parse(item.realContent, charset);
            rsp.RequestBody = requestBody;

            CheckResponseSign(request, item.respContent, rsp.IsError, parser, this.publicKey, this.charset, signType, this.keyFromFile);

            return(rsp);
        }
コード例 #4
0
        public async Task CompleteFileUploadAsync(IUploadRequest uploadRequest)
        {
            ThrowIfUnauthorized();

            try
            {
                IApiRequest request = GenerateCompleteUploadRequest(uploadRequest.Ticket);
                IRestResponse response = await request.ExecuteRequestAsync();
                CheckStatusCodeError(uploadRequest, response, "Error marking file upload as complete.");

                Parameter locationHeader =
                    response.Headers.FirstOrDefault(h => string.Compare(h.Name, "Location", true) == 0);
                if (locationHeader != null && locationHeader.Value != null)
                {
                    uploadRequest.ClipUri = locationHeader.Value as string;
                }
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoUploadException("Error marking file upload as complete.", uploadRequest, ex);
            }
        }
コード例 #5
0
        /// <summary>
        /// Verify upload file part asynchronously
        /// </summary>
        /// <param name="uploadRequest">UploadRequest</param>
        /// <returns>Verification reponse</returns>
        private async Task <VerifyUploadResponse> VerifyUploadFileAsync(IUploadRequest uploadRequest)
        {
            try
            {
                var request =
                    await GenerateFileStreamRequest(uploadRequest.File, uploadRequest.Ticket, verifyOnly : true)
                    .ConfigureAwait(false);

                var response = await request.ExecuteRequestAsync().ConfigureAwait(false);

                var verify = new VerifyUploadResponse();
                CheckStatusCodeError(uploadRequest, response, "Error verifying file upload.", (HttpStatusCode)308);

                // ReSharper disable once ConvertIfStatementToSwitchStatement
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    verify.BytesWritten = uploadRequest.FileLength;
                    verify.Status       = UploadStatusEnum.Completed;
                }
                else if (response.StatusCode == (HttpStatusCode)308)
                {
                    verify.Status = UploadStatusEnum.InProgress;
                    if (!response.Headers.Contains("Range"))
                    {
                        return(verify);
                    }
                    var match = RangeRegex.Match(response.Headers.GetValues("Range").First());
                    // ReSharper disable once InvertIf
                    if (match.Success &&
                        long.TryParse(match.Groups["start"].Value, out var startIndex) &&
                        long.TryParse(match.Groups["end"].Value, out var endIndex))
                    {
                        verify.BytesWritten        = endIndex - startIndex;
                        uploadRequest.BytesWritten = verify.BytesWritten;
                        if (verify.BytesWritten == uploadRequest.FileLength)
                        {
                            verify.Status = UploadStatusEnum.Completed;
                        }
                    }
                }
                else
                {
                    verify.Status = UploadStatusEnum.NotFound;
                }

                return(verify);
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }

                throw new VimeoUploadException("Error verifying file upload.", uploadRequest, ex);
            }
        }
コード例 #6
0
        /// <summary>
        /// Makes an upload with image URL. Kraken will download the image from the provided URL.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="url">The URL.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task&lt;UploadCallbackUrlResponse&gt;.</returns>
        private Task <UploadCallbackUrlResponse> UploadCallbackUrl(IUploadRequest request, string url, CancellationToken cancellationToken)
        {
            Task <UploadCallbackUrlResponse> response = this.Execute <IUploadRequest, UploadCallbackUrlResponse>(
                request,
                url,
                HttpMethod.Post,
                default(CancellationToken));

            return(response);
        }
コード例 #7
0
        public async Task <VerifyUploadResponse> VerifyUploadFileAsync(IUploadRequest uploadRequest)
        {
            try
            {
                IApiRequest request =
                    await GenerateFileStreamRequest(uploadRequest.File, uploadRequest.Ticket, verifyOnly : true);

                IRestResponse response = await request.ExecuteRequestAsync();

                var verify = new VerifyUploadResponse();
                CheckStatusCodeError(uploadRequest, response, "Error verifying file upload.", (HttpStatusCode)308);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    verify.BytesWritten = uploadRequest.FileLength;
                    verify.Status       = UploadStatusEnum.Completed;
                }
                else if (response.StatusCode == (HttpStatusCode)308)
                {
                    verify.Status = UploadStatusEnum.InProgress;
                    int       startIndex  = 0;
                    int       endIndex    = 0;
                    Parameter rangeHeader =
                        response.Headers.FirstOrDefault(h => string.Compare(h.Name, "Range", true) == 0);
                    if (rangeHeader != null && rangeHeader.Value != null)
                    {
                        Match match = _rangeRegex.Match(rangeHeader.Value as string);
                        if (match.Success &&
                            int.TryParse(match.Groups["start"].Value, out startIndex) &&
                            int.TryParse(match.Groups["end"].Value, out endIndex))
                        {
                            verify.BytesWritten = endIndex - startIndex;
                            if (verify.BytesWritten == uploadRequest.FileLength)
                            {
                                verify.Status = UploadStatusEnum.Completed;
                            }
                        }
                    }
                }
                else
                {
                    verify.Status = UploadStatusEnum.NotFound;
                }

                return(verify);
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoUploadException("Error verifying file upload.", uploadRequest, ex);
            }
        }
コード例 #8
0
 public void CompleteFileUpload(IUploadRequest uploadRequest)
 {
     try
     {
         Task.Run(async () => await CompleteFileUploadAsync(uploadRequest)).Wait();
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
     }
 }
コード例 #9
0
 public void CompleteFileUpload(IUploadRequest uploadRequest)
 {
     try
     {
         CompleteFileUploadAsync(uploadRequest).RunSynchronouslyWithCurrentCulture();
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
     }
 }
コード例 #10
0
 private void CheckStatusCodeError(IUploadRequest request, IApiResponse response, string message,
                                   params HttpStatusCode[] validStatusCodes)
 {
     if (!IsSuccessStatusCode(response.StatusCode) && validStatusCodes != null &&
         !validStatusCodes.Contains(response.StatusCode))
     {
         throw new VimeoUploadException(string.Format("{1}{0}Code: {2}{0}Message: {3}",
                                                      Environment.NewLine, message, response.StatusCode, response.Text),
                                        request);
     }
 }
コード例 #11
0
 public void CompleteFileUpload(IUploadRequest uploadRequest)
 {
     try
     {
         Task.Run(async() => await CompleteFileUploadAsync(uploadRequest)).Wait();
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
     }
 }
コード例 #12
0
 public void CompleteFileUpload(IUploadRequest uploadRequest)
 {
     try
     {
         CompleteFileUploadAsync(uploadRequest).RunSynchronouslyWithCurrentCulture();
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
     }
 }
コード例 #13
0
 public VerifyUploadResponse ContinueUploadFile(IUploadRequest uploadRequest)
 {
     try
     {
         return(ContinueUploadFileAsync(uploadRequest).Result);
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
         return(null);
     }
 }
コード例 #14
0
 public VerifyUploadResponse ContinueUploadFile(IUploadRequest uploadRequest)
 {
     try
     {
         return Task.Run(async () => await ContinueUploadFileAsync(uploadRequest)).Result;
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
         return null;
     }
 }
コード例 #15
0
 public VerifyUploadResponse ContinueUploadFile(IUploadRequest uploadRequest)
 {
     try
     {
         return ContinueUploadFileAsync(uploadRequest).RunSynchronouslyWithCurrentCulture();
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
         return null;
     }
 }
コード例 #16
0
ファイル: Program.cs プロジェクト: manojjadoun/omnie
        static void Main(string[] args)
        {
            VimeoClient_IntegrationTests obj = new VimeoClient_IntegrationTests();

            string         filePath         = @"Resources\test.mp4";
            IUploadRequest completedRequest = obj.Integration_VimeoClient_UploadEntireFile_UploadsFile(filePath);

            Console.WriteLine("Video uploaded successfully.");
            Console.WriteLine("ID:" + completedRequest.ClipId);
            Console.WriteLine("URI:" + completedRequest.ClipUri);
            Console.ReadLine();
        }
コード例 #17
0
 public VerifyUploadResponse VerifyUploadFile(IUploadRequest uploadRequest)
 {
     try
     {
         return(Task.Run(async() => await VerifyUploadFileAsync(uploadRequest)).Result);
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
         return(null);
     }
 }
コード例 #18
0
 public VerifyUploadResponse VerifyUploadFile(IUploadRequest uploadRequest)
 {
     try
     {
         return(VerifyUploadFileAsync(uploadRequest).RunSynchronouslyWithCurrentCulture());
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
     }
     return(null);
 }
コード例 #19
0
ファイル: DopClient.cs プロジェクト: 314908953/Hello-Word
        /// <summary>
        /// 执行公开API请求。
        /// </summary>
        /// <typeparam name="T">领域对象</typeparam>
        /// <param name="request">具体的API请求</param>
        /// <returns>领域对象</returns>
        public T Execute <T>(IRequest <T> request) where T : IResponse
        {
            // 添加系统级请求参数
            SdkDictionary txtParams = new SdkDictionary(request.GetParameters());

            txtParams.Add("method", request.GetApiNameOrUrl());
            txtParams.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            txtParams.Add("format", "xml");
            txtParams.Add("app_key", this._apiKey);
            txtParams.Add("v", "1.0");
            txtParams.Add("sign_method", "md5");
            txtParams.Add("session", this._sessionKey);

            // 添加签名参数
            SdkDictionary signParams = new SdkDictionary();

            signParams.Add("app_key", _apiKey);
            signParams.Add("format", "xml");
            signParams.Add("method", request.GetApiNameOrUrl());
            signParams.Add("session", this._sessionKey);
            signParams.Add("sign_method", "md5");
            signParams.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            //signParams.Add("secret", _appSecret);
            signParams.Add("v", "1.0");

            txtParams.Add("sign", SignRequest(signParams, _appSecret));

            // 是否需要上传文件
            string   body;
            WebUtils webUtils = new WebUtils();

            webUtils.Charset = "GBK";

            if (request is IUploadRequest <T> )
            {
                IUploadRequest <T>             uRequest   = (IUploadRequest <T>)request;
                IDictionary <string, FileItem> fileParams = Utils.CleanupDictionary(uRequest.GetFileParameters());
                body = webUtils.DoPost(_appUrl, txtParams, fileParams);
            }
            else
            {
                body = webUtils.DoGet(_appUrl, txtParams);
            }

            T rsp;

            IParser <T> tp = new XmlParser <T>();

            rsp = tp.Parse(body, Encoding.GetEncoding("GBK"));

            return(rsp);
        }
コード例 #20
0
        /// <summary>
        /// Continue upload file asynchronously
        /// </summary>
        /// <param name="uploadRequest">UploadRequest</param>
        /// <returns>Verification upload response</returns>
        private async Task <VerifyUploadResponse> ContinueUploadFileAsync(IUploadRequest uploadRequest)
        {
            if (uploadRequest.FileLength == uploadRequest.BytesWritten)
            {
                // Already done, there's nothing to do.
                return(new VerifyUploadResponse
                {
                    Status = UploadStatusEnum.InProgress,
                    BytesWritten = uploadRequest.BytesWritten
                });
            }

            try
            {
                var request = await GenerateFileStreamRequest(uploadRequest.File, uploadRequest.Ticket,
                                                              chunkSize : uploadRequest.ChunkSize, written : uploadRequest.BytesWritten).ConfigureAwait(false);

                var response = await request.ExecuteRequestAsync().ConfigureAwait(false);

                CheckStatusCodeError(uploadRequest, response, "Error uploading file chunk.", HttpStatusCode.BadRequest);

                if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    // something went wrong, figure out where we need to start over
                    return(await VerifyUploadFileAsync(uploadRequest).ConfigureAwait(false));
                }

                // Success, update total written
                uploadRequest.BytesWritten += uploadRequest.ChunkSize;
                uploadRequest.BytesWritten  = Math.Min(uploadRequest.BytesWritten, uploadRequest.FileLength);

                return(new VerifyUploadResponse
                {
                    Status = uploadRequest.FileLength == uploadRequest.BytesWritten
                        ? UploadStatusEnum.Completed
                        : UploadStatusEnum.InProgress,
                    BytesWritten = uploadRequest.BytesWritten
                });
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }

                throw new VimeoUploadException("Error uploading file chunk", uploadRequest, ex);
            }
        }
コード例 #21
0
        public async Task<VerifyUploadResponse> ContinueUploadFileAsync(IUploadRequest uploadRequest)
        {
            if (uploadRequest.AllBytesWritten)
            {
                // Already done, there's nothing to do.
                return new VerifyUploadResponse
                {
                    Status = UploadStatusEnum.InProgress,
                    BytesWritten = uploadRequest.BytesWritten
                };
            }

            try
            {
                IApiRequest request = await GenerateFileStreamRequest(uploadRequest.File, uploadRequest.Ticket,
                    chunkSize: uploadRequest.ChunkSize, written: uploadRequest.BytesWritten);
                IRestResponse response = await request.ExecuteRequestAsync();
                CheckStatusCodeError(uploadRequest, response, "Error uploading file chunk.", HttpStatusCode.BadRequest);

                if (response.StatusCode == HttpStatusCode.BadRequest)
                {
                    // something went wrong, figure out where we need to start over
                    return await VerifyUploadFileAsync(uploadRequest);
                }

                // Success, update total written
                uploadRequest.BytesWritten += uploadRequest.ChunkSize;
                uploadRequest.BytesWritten = Math.Min(uploadRequest.BytesWritten, uploadRequest.FileLength);
                return new VerifyUploadResponse
                {
                    Status = UploadStatusEnum.InProgress,
                    BytesWritten = uploadRequest.BytesWritten
                };
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoUploadException("Error uploading file chunk", uploadRequest, ex);
            }
        }
コード例 #22
0
        public T Post <T>(IUploadRequest <T> request) where T : IWeiboResponse, new()
        {
            var url = new StringBuilder(request.Url);

            if (request.WeiboType == WeiboType.Sina)
            {
                url.Append(_format);
            }

            var form = new HttpMultipartMimeForm();

            if (request.WeiboType == WeiboType.QQ)
            {
                form.AppendValue("format", _format.ToString());
            }

            if (request.Parameters.Count > 0)
            {
                foreach (var parameter in request.Parameters)
                {
                    form.AppendValue(parameter.Key, parameter.Value);
                }
            }

            if (request.FileParameters.Count > 0)
            {
                foreach (var fileParameter in request.FileParameters)
                {
                    form.AppendFile(fileParameter.Key, fileParameter.Value);
                }
            }

            var oauthRequest = new OAuthHttpRequestMessage("POST", url.ToString(), form).Sign(_accessToken);
            var result       = _client.Send(oauthRequest).ReadContentAsString();

            var response = new T();

            response.ConvertFrom(result);

            return(response);
        }
コード例 #23
0
        public async Task <IUploadRequest> UploadEntireFileAsync(IBinaryContent fileContent,
                                                                 int chunkSize       = DEFAULT_UPLOAD_CHUNK_SIZE,
                                                                 long?replaceVideoId = null)
        {
            IUploadRequest uploadRequest = await StartUploadFileAsync(fileContent, chunkSize, replaceVideoId);

            VerifyUploadResponse uploadStatus = null;

            while (!uploadRequest.IsVerifiedComplete)
            {
                uploadStatus = await ContinueUploadFileAsync(uploadRequest);

                if (uploadRequest.AllBytesWritten)
                {
                    // We presumably wrote all the bytes in the file, so verify with Vimeo that it
                    // is completed
                    uploadStatus = await VerifyUploadFileAsync(uploadRequest);

                    if (uploadStatus.Status == UploadStatusEnum.Completed)
                    {
                        // If completed, mark file as complete
                        await CompleteFileUploadAsync(uploadRequest);

                        uploadRequest.IsVerifiedComplete = true;
                    }
                    else if (uploadStatus.BytesWritten == uploadRequest.FileLength)
                    {
                        // Supposedly all bytes are written, but Vimeo doesn't think so, so just
                        // bail out
                        throw new VimeoUploadException(
                                  string.Format(
                                      "Vimeo failed to mark file as completed, Bytes Written: {0:N0}, Expected: {1:N0}.",
                                      uploadStatus.BytesWritten),
                                  uploadRequest);
                    }
                }
            }

            return(uploadRequest);
        }
コード例 #24
0
 public VimeoUploadException(string message, IUploadRequest request, Exception innerException)
     : base(message, innerException)
 {
     Request = request;
 }
コード例 #25
0
 public VimeoUploadException(string message, IUploadRequest request)
     : base(message)
 {
     Request = request;
 }
コード例 #26
0
 public VimeoUploadException(IUploadRequest request)
 {
     Request = request;
 }
コード例 #27
0
ファイル: VimeoUploadException.cs プロジェクト: r15h1/heyteam
 public VimeoUploadException(string message, IUploadRequest request, Exception innerException)
     : base(message, innerException)
 {
     Request = request;
 }
コード例 #28
0
ファイル: VimeoUploadException.cs プロジェクト: r15h1/heyteam
 public VimeoUploadException(string message, IUploadRequest request)
     : base(message)
 {
     Request = request;
 }
コード例 #29
0
ファイル: VimeoUploadException.cs プロジェクト: r15h1/heyteam
 public VimeoUploadException(IUploadRequest request)
 {
     Request = request;
 }
コード例 #30
0
 private void CheckStatusCodeError(IUploadRequest request, IRestResponse response, string message,
     params HttpStatusCode[] validStatusCodes)
 {
     if (!IsSuccessStatusCode(response.StatusCode) && validStatusCodes != null &&
         !validStatusCodes.Contains(response.StatusCode))
     {
         throw new VimeoUploadException(string.Format("{1}{0}Code: {2}{0}Message: {3}",
             Environment.NewLine, message, response.StatusCode, response.Content),
             request);
     }
 }
コード例 #31
0
ファイル: DefaultClient.cs プロジェクト: cang2016/CCAPISDK
        private T DoExecute <T>(IRequest <T> request, string session, DateTime timestamp) where T : ResponseBase
        {
            long start = DateTime.Now.Ticks;

            // 提前检查业务参数
            try
            {
                request.Validate();
            }
            catch (CException e)
            {
                return(CreateErrorResponse <T>(e.ErrorCode, e.ErrorMsg));
            }

            CDictionary txtParams = new CDictionary(request.GetParameters());

            txtParams.Add(Constants.METHOD, request.GetApiName);
            InitParameters(txtParams);


            // 添加协议级请求参数
            //ACDictionary txtParams = new ACDictionary(request.GetParameters());
            //txtParams.Add(Constants.METHOD, request.GetApiName());
            //txtParams.Add(Constants.VERSION, "1.0");
            ////txtParams.Add(Constants.SIGN_METHOD, Constants.SIGN_METHOD_MD5);
            //txtParams.Add(Constants.APP_KEY, appKey);
            //txtParams.Add(Constants.FORMAT, format);
            //txtParams.Add(Constants.TIMESTAMP, timestamp);
            //txtParams.AddAll(this.systemParameters);


            //// 添加签名参数
            //txtParams.Add(Constants.SIGN, SignHelper.SignACRequest(txtParams, appSecret, Constants.SIGN_METHOD_MD5));

            // 添加头部参数
            if (this.useGzipEncoding)
            {
                request.GetHeaderParameters()[Constants.ACCEPT_ENCODING] = Constants.CONTENT_ENCODING_GZIP;
            }

            string realServerUrl = GetServerUrl(this.serverUrl, request.GetApiName, session);
            string reqUrl        = WebUtils.BuildRequestUrl(realServerUrl, txtParams);

            try
            {
                string body;
                if (request is IUploadRequest <T> ) // 是否需要上传文件
                {
                    IUploadRequest <T>             uRequest   = (IUploadRequest <T>)request;
                    IDictionary <string, FileItem> fileParams = SignHelper.CleanupDictionary(uRequest.GetFileParameters());
                    body = webUtils.DoPost(realServerUrl, txtParams, fileParams, request.GetHeaderParameters());
                }
                else
                {
                    body = webUtils.DoPost(realServerUrl, txtParams, request.GetHeaderParameters());
                }

                // 解释响应结果
                T rsp;
                if (disableParser)
                {
                    rsp = Activator.CreateInstance <T>();
                    rsp.ResponseBody = body;
                }
                else
                {
                    if (Constants.FORMAT_XML.Equals(format))
                    {
                        IParser <T> tp = new XmlParser <T>();
                        rsp = tp.Parse(body);
                    }
                    else
                    {
                        IParser <T> tp;
                        if (useSimplifyJson)
                        {
                            tp = new AcSimplifyJsonParser <T>();
                        }
                        else
                        {
                            tp = new JsonParser <T>();
                        }
                        rsp = tp.Parse(body);
                    }
                }

                // 追踪错误的请求
                if (!rsp.HaveError)
                {
                    TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                    TraceApiError(AppKey, request.GetApiName, serverUrl, txtParams, latency.TotalMilliseconds, rsp.ResponseBody);
                }
                return(rsp);
            }
            catch (Exception e)
            {
                TimeSpan latency = new TimeSpan(DateTime.Now.Ticks - start);
                TraceApiError(AppKey, request.GetApiName, serverUrl, txtParams, latency.TotalMilliseconds, e.GetType() + ": " + e.Message);
                throw e;
            }
        }
コード例 #32
0
 IUploadResponse IAlchemyStreamUpload.UploadBinaryContent(IUploadRequest request)
 {
     return(Channel.UploadBinaryContent((UploadRequest201501)request));
 }
コード例 #33
0
        public async Task<VerifyUploadResponse> VerifyUploadFileAsync(IUploadRequest uploadRequest)
        {
            try
            {
                IApiRequest request =
                    await GenerateFileStreamRequest(uploadRequest.File, uploadRequest.Ticket, verifyOnly: true);
                IRestResponse response = await request.ExecuteRequestAsync();
                var verify = new VerifyUploadResponse();
                CheckStatusCodeError(uploadRequest, response, "Error verifying file upload.", (HttpStatusCode)308);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    verify.BytesWritten = uploadRequest.FileLength;
                    verify.Status = UploadStatusEnum.Completed;
                }
                else if (response.StatusCode == (HttpStatusCode)308)
                {
                    verify.Status = UploadStatusEnum.InProgress;
                    int startIndex = 0;
                    int endIndex = 0;
                    Parameter rangeHeader =
                        response.Headers.FirstOrDefault(h => string.Compare(h.Name, "Range", true) == 0);
                    if (rangeHeader != null && rangeHeader.Value != null)
                    {
                        Match match = _rangeRegex.Match(rangeHeader.Value as string);
                        if (match.Success
                            && int.TryParse(match.Groups["start"].Value, out startIndex)
                            && int.TryParse(match.Groups["end"].Value, out endIndex))
                        {
                            verify.BytesWritten = endIndex - startIndex;
                            if (verify.BytesWritten == uploadRequest.FileLength)
                            {
                                verify.Status = UploadStatusEnum.Completed;
                            }
                        }
                    }
                }
                else
                {
                    verify.Status = UploadStatusEnum.NotFound;
                }

                return verify;
            }
            catch (Exception ex)
            {
                if (ex is VimeoApiException)
                {
                    throw;
                }
                throw new VimeoUploadException("Error verifying file upload.", uploadRequest, ex);
            }
        }
コード例 #34
0
ファイル: WebApiController.cs プロジェクト: hx215267863/src
        public ActionResult Index()
        {
            IResponse response;

            try
            {
                string                      appKey      = null;
                string                      key         = null;
                string                      str         = null;
                string                      strB        = null;
                string                      accessToken = null;
                DateTime                    dateTime    = DateTime.MinValue;
                NameValueCollection         form        = this.Request.Form;
                Dictionary <string, string> dictionary  = new Dictionary <string, string>();
                foreach (string allKey in form.AllKeys)
                {
                    string s = form[allKey];
                    switch (allKey)
                    {
                    case "app_key":
                        appKey = s;
                        break;

                    case "param_json":
                        str = s;
                        break;

                    case "method":
                        key = s;
                        break;

                    case "timestamp":
                        long result;
                        if (long.TryParse(s, out result))
                        {
                            dateTime = new DateTime(1970, 1, 1).ToLocalTime().AddMilliseconds((double)result);
                            break;
                        }
                        break;

                    case "sign":
                        strB = s;
                        break;

                    case "access_token":
                        accessToken = s;
                        break;
                    }
                    if (allKey != "sign")
                    {
                        dictionary.Add(allKey, s);
                    }
                }
                if (dateTime < DateTime.Now.AddMinutes(-15.0))
                {
                    response = new BaseResponse()
                    {
                        ErrCode = "005"
                    };
                }
                else
                {
                    AppInfo app = ServiceHelper.LoadService <IAppService>().GetApp(appKey);
                    if (app != null)
                    {
                        if (string.Compare(WebApiUtils.SignYrqRequest(dictionary, app.AppSecret), strB, true) == 0)
                        {
                            Dictionary <string, ApiMethodInfo> apiMethods = Util.Utils.GetApiMethods();
                            if (apiMethods.ContainsKey(key))
                            {
                                ApiMethodInfo        apiMethodInfo = apiMethods[key];
                                IRequest <IResponse> request       = (IRequest <IResponse>)JsonConvert.DeserializeObject(str ?? "{}", apiMethodInfo.RequestType, WebApiUtils.GetJsonConverters());
                                request.Validate();
                                this.Context.AppId = app.AppId;
                                if (request is ICraftsReqeust)
                                {
                                    ServiceHelper.LoadService <ICraftDbFactory>().CraftNO = ((ICraftsReqeust)request).CraftNO;
                                }
                                if (request is IUploadRequest)
                                {
                                    IUploadRequest uploadRequest = (IUploadRequest)request;
                                    IDictionary <string, FileItem> fileParameters = new Dictionary <string, FileItem>();
                                    foreach (string allKey in this.Request.Files.AllKeys)
                                    {
                                        HttpPostedFileBase httpPostedFileBase = this.Request.Files[allKey];
                                        byte[]             numArray           = new byte[httpPostedFileBase.InputStream.Length];
                                        httpPostedFileBase.InputStream.Read(numArray, 0, numArray.Length);
                                        fileParameters.Add(allKey, new FileItem(httpPostedFileBase.FileName, numArray));
                                        httpPostedFileBase.InputStream.Dispose();
                                    }
                                    uploadRequest.SetFileParamaters(fileParameters);
                                }
                                if (apiMethodInfo.IsCheckSession)
                                {
                                    AuthInfo auth = ServiceHelper.LoadService <IAuthService>().GetAuth(accessToken);
                                    if (auth != null && auth.AppId == this.Context.AppId)
                                    {
                                        this.Context.AuthId = auth.AppId;
                                        this.Context.UserId = auth.UserId;
                                        response            = (IResponse)apiMethodInfo.Method.Invoke(this, new object[1]
                                        {
                                            request
                                        });
                                    }
                                    else
                                    {
                                        response = new BaseResponse()
                                        {
                                            ErrCode = "004"
                                        }
                                    };
                                }
                                else
                                {
                                    response = (IResponse)apiMethodInfo.Method.Invoke(this, new object[1]
                                    {
                                        request
                                    });
                                }
                            }
                            else
                            {
                                response = new BaseResponse()
                                {
                                    ErrCode = "003"
                                }
                            };
                        }
                        else
                        {
                            response = new BaseResponse()
                            {
                                ErrCode = "002"
                            }
                        };
                    }
                    else
                    {
                        response = new BaseResponse()
                        {
                            ErrCode = "008"
                        }
                    };
                }
            }
            catch (TargetInvocationException ex)
            {
                LogUtil.LogError("处理请求异常", ex.GetBaseException());
                response = new BaseResponse()
                {
                    ErrCode = "001",
                    ErrMsg  = ex.GetBaseException().Message
                };
            }
            catch (Exception ex)
            {
                LogUtil.LogError("处理请求异常", ex);
                response = new BaseResponse()
                {
                    ErrCode = "001",
                    ErrMsg  = ex.Message
                };
            }
            return(Content(JsonConvert.SerializeObject(response, WebApiUtils.GetJsonConverters())));
        }
コード例 #35
0
 public VerifyUploadResponse VerifyUploadFile(IUploadRequest uploadRequest)
 {
     try
     {
         return VerifyUploadFileAsync(uploadRequest).Result;
     }
     catch (AggregateException ex)
     {
         ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
         return null;
     }
 }