コード例 #1
0
 public HtpClient(System.Net.Http.Handlers.ProgressMessageHandler progressHandler) : base(progressHandler)
 {
     base.DefaultRequestHeaders.UserAgent.ParseAdd("DepositfilesSDK");
     base.DefaultRequestHeaders.ConnectionClose = m_CloseConnection;
     base.Timeout = m_TimeOut;
     base.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
 }
コード例 #2
0
ファイル: Basic.cs プロジェクト: jackkoolage/pCloudSDK
 public HtpClient(System.Net.Http.Handlers.ProgressMessageHandler progressHandler) : base(progressHandler)
 {
     //base.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authToken);
     base.DefaultRequestHeaders.UserAgent.ParseAdd("pCloudSDK");
     base.DefaultRequestHeaders.ConnectionClose = m_CloseConnection;
     base.Timeout = m_TimeOut;
 }
コード例 #3
0
 public HtpClient(System.Net.Http.Handlers.ProgressMessageHandler progressHandler)
     : base(progressHandler)
 {
     base.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(APIkey + ":" + APISecret)));
     base.DefaultRequestHeaders.UserAgent.ParseAdd("Image4ioSDK");
     base.DefaultRequestHeaders.ConnectionClose = m_CloseConnection;
     Timeout = m_TimeOut;
 }
コード例 #4
0
 public HtpClient(System.Net.Http.Handlers.ProgressMessageHandler progressHandler) : base(progressHandler)
 {
     base.DefaultRequestHeaders.UserAgent.ParseAdd("SaruchSDK");
     base.DefaultRequestHeaders.ConnectionClose = m_CloseConnection;
     base.Timeout = m_TimeOut;
     base.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
     base.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AccessToken);
 }
コード例 #5
0
        public async Task DownloadLarge(string VideoUrl, string FileSaveDir, string FileName, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpReceiveProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Downloading..."
                    }); };
                using (HtpClient localHttpClient = new HtpClient(progressHandler))
                {
                    using (HttpResponseMessage ResPonse = await localHttpClient.GetAsync(new Uri(VideoUrl), HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false))
                    {
                        token.ThrowIfCancellationRequested();
                        if (ResPonse.IsSuccessStatusCode)
                        {
                            ResPonse.EnsureSuccessStatusCode();
                            // ''''''''''''''' write byte by byte to H.D '''''''''''''''''''''''''''''
                            string FPathname = System.IO.Path.Combine(FileSaveDir, FileName);
                            using (System.IO.Stream streamToReadFrom = await ResPonse.Content.ReadAsStreamAsync())
                            {
                                using (System.IO.Stream streamToWriteTo = System.IO.File.Open(FPathname, System.IO.FileMode.Create))
                                {
                                    await streamToReadFrom.CopyToAsync(streamToWriteTo, 1024, token);
                                }
                            }

                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = (string.Format("[{0}] Downloaded successfully.", FileName))
                            });
                        }
                        else
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = ((string.Format("Error code: {0}", ResPonse.ReasonPhrase)))
                            });
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new DailymotionException(ex.Message, 1001);
                }
            }
        }
コード例 #6
0
        public async Task Download(string VideoUrl, string FileSaveDir, string FileName, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpReceiveProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Downloading..."
                    }); };
                using (HtpClient localHttpClient = new HtpClient(progressHandler))
                {
                    HttpRequestMessage HtpReqMessage = new HttpRequestMessage(HttpMethod.Get, new Uri(VideoUrl));
                    // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                    using (HttpResponseMessage ResPonse = await localHttpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false))
                    {
                        token.ThrowIfCancellationRequested();
                        if (ResPonse.IsSuccessStatusCode)
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = (string.Format("[{0}] Downloaded successfully.", FileName))
                            });
                        }
                        else
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = ((string.Format("Error code: {0}", ResPonse.StatusCode)))
                            });
                        }

                        ResPonse.EnsureSuccessStatusCode();
                        var stream_ = await ResPonse.Content.ReadAsStreamAsync();

                        string FPathname = System.IO.Path.Combine(FileSaveDir, FileName);
                        using (var fileStream = new System.IO.FileStream(FPathname, System.IO.FileMode.Append, System.IO.FileAccess.Write))
                        {
                            stream_.CopyTo(fileStream);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new DailymotionException(ex.Message, 1001);
                }
            }
        }
コード例 #7
0
        public async Task <JSON_UploadLocalFile> UploadLocal(object FileToUpload, UploadTypes UploadType, string VideoTitle = null, List <string> VideoTags = null, ChannelsEnum?VideoChannel = null, PrivacyEnum?Privacy = null, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            var uploadUrl = await GetUploadUrl();

            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpSendProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Uploading..."
                    }); };
                using (HttpClient localHttpClient = new HtpClient(progressHandler))
                {
                    HttpRequestMessage HtpReqMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(uploadUrl.upload_url));
                    var         MultipartsformData   = new MultipartFormDataContent();
                    HttpContent streamContent        = null;
                    switch (UploadType)
                    {
                    case UploadTypes.FilePath:
                        streamContent = new StreamContent(new System.IO.FileStream(FileToUpload.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read));
                        break;

                    case UploadTypes.Stream:
                        streamContent = new StreamContent((System.IO.Stream)FileToUpload);
                        break;

                    case UploadTypes.BytesArry:
                        streamContent = new StreamContent(new System.IO.MemoryStream((byte[])FileToUpload));
                        break;
                    }
                    MultipartsformData.Add(streamContent, "file");

                    HtpReqMessage.Content = MultipartsformData;
                    // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                    using (HttpResponseMessage ResPonse = await localHttpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false))
                    {
                        string result = await ResPonse.Content.ReadAsStringAsync();

                        token.ThrowIfCancellationRequested();

                        var TheRsult = JsonConvert.DeserializeObject <JSON_UploadLocalFile>(result);
                        if (ResPonse.StatusCode == System.Net.HttpStatusCode.OK)
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = string.Format("[{0}] Uploaded successfully", VideoTitle)
                            });
                            // ''''''''Complete file upload''''''''''''
                            using (HtpClient localHttpClient2 = new HtpClient(new HCHandler()))
                            {
                                using (HttpRequestMessage HtpReqMessage2 = new HttpRequestMessage(HttpMethod.Post, new pUri("/me/videos")))
                                {
                                    var parameters = new Dictionary <string, string>();
                                    parameters.Add("url", TheRsult.url);
                                    parameters.Add("title", VideoTitle);
                                    parameters.Add("tags", VideoTags != null ? string.Join(",", VideoTags) : null);
                                    parameters.Add("channel", VideoChannel.HasValue ? VideoChannel.ToString() : null);
                                    if (Privacy.HasValue)
                                    {
                                        switch (Privacy)
                                        {
                                        case PrivacyEnum.Public:
                                            parameters.Add("published", "1");
                                            parameters.Add("private", "0");
                                            break;

                                        case PrivacyEnum.Private:
                                            parameters.Add("published", "0");
                                            parameters.Add("private", "1");
                                            break;
                                        }
                                    }

                                    HtpReqMessage2.Content = new FormUrlEncodedContent(parameters.RemoveEmptyValues());
                                    using (HttpResponseMessage ResPonse2 = await localHttpClient2.SendAsync(HtpReqMessage2, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false))
                                    {
                                        string resu = await ResPonse2.Content.ReadAsStringAsync();

                                        if (ResPonse2.StatusCode == System.Net.HttpStatusCode.OK)
                                        {
                                            var TheRlt = JsonConvert.DeserializeObject <JSON_CompleteUpload>(resu, JSONhandler);
                                            TheRsult.id = TheRlt.id;
                                            return(TheRsult);
                                        }
                                        else
                                        {
                                            throw new DailymotionException(JObject.Parse(resu).SelectToken("error.message").ToString(), (int)ResPonse2.StatusCode);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = string.Format("The request returned with HTTP status code {0}", ResPonse.StatusCode)
                            });
                            throw ShowError(result);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new DailymotionException(ex.Message, 1001);
                }
                return(null);
            }
        }
コード例 #8
0
 public HtpClient(System.Net.Http.Handlers.ProgressMessageHandler progressHandler) : base(progressHandler)
 {
     base.DefaultRequestHeaders.UserAgent.ParseAdd("BackBlazeSDK");
     base.DefaultRequestHeaders.ConnectionClose = m_CloseConnection;
     base.Timeout = m_TimeOut;
 }
コード例 #9
0
ファイル: BClient.cs プロジェクト: loudKode/BackBlazeSDK
        public async Task <System.IO.Stream> PrivateBucket_DownloadFileAsStream(string DestinationFileID, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpReceiveProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Downloading..."
                    }); };
                HtpClient localHttpClient = new HtpClient(progressHandler);
                var       HtpReqMessage   = new HttpRequestMessage(HttpMethod.Get, new Uri(APIbase + $"b2_download_file_by_id?fileId={DestinationFileID}"));
                // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                HttpResponseMessage ResPonse = await localHttpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false);

                token.ThrowIfCancellationRequested();
                if (ResPonse.StatusCode == HttpStatusCode.OK)
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        Finished = true, TextStatus = "File Downloaded successfully."
                    });
                }
                else
                {
                    string result = await ResPonse.Content.ReadAsStringAsync();

                    var errorInfo = JsonConvert.DeserializeObject <JSON_Error>(result);
                    ReportCls.Report(new ReportStatus()
                    {
                        Finished = true, TextStatus = ((string.Format("Error code: {0}", string.IsNullOrEmpty(errorInfo._ErrorMessage) ? errorInfo.code : errorInfo._ErrorMessage)))
                    });
                }

                ResPonse.EnsureSuccessStatusCode();
                System.IO.Stream stream_ = await ResPonse.Content.ReadAsStreamAsync();

                return(stream_);
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new BackBlazeException(ex.Message, 1001);
                }
                return(null);
            }
        }
コード例 #10
0
ファイル: BClient.cs プロジェクト: loudKode/BackBlazeSDK
        public async Task PrivateBucket_DownloadLargeFile(string DestinationFileID, string FileSaveDir, string FileName, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpReceiveProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Downloading..."
                    }); };
                HtpClient localHttpClient = new HtpClient(progressHandler);
                var       HtpReqMessage   = new HtpRequestMessage(HttpMethod.Get, new Uri(APIbase + $"b2_download_file_by_id?fileId={DestinationFileID}"));
                // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                using (HttpResponseMessage ResPonse = await localHttpClient.GetAsync(HtpReqMessage.RequestUri, HttpCompletionOption.ResponseHeadersRead, token).ConfigureAwait(false))
                {
                    token.ThrowIfCancellationRequested();
                    if (ResPonse.StatusCode == HttpStatusCode.OK)
                    {
                        ResPonse.EnsureSuccessStatusCode();
                        // ''''''''''''''' write byte by byte to H.D '''''''''''''''''''''''''''''
                        string FPathname = System.IO.Path.Combine(FileSaveDir, FileName);
                        using (System.IO.Stream streamToReadFrom = await ResPonse.Content.ReadAsStreamAsync())
                        {
                            using (System.IO.Stream streamToWriteTo = System.IO.File.Open(FPathname, System.IO.FileMode.Create))
                            {
                                await streamToReadFrom.CopyToAsync(streamToWriteTo, 1024, token);
                            }
                        }
                        ReportCls.Report(new ReportStatus()
                        {
                            Finished = true, TextStatus = (string.Format("[{0}] Downloaded successfully.", FileName))
                        });
                    }
                    else
                    {
                        string result = await ResPonse.Content.ReadAsStringAsync();

                        var errorInfo = JsonConvert.DeserializeObject <JSON_Error>(result);
                        ReportCls.Report(new ReportStatus()
                        {
                            Finished = true, TextStatus = ((string.Format("Error code: {0}", string.IsNullOrEmpty(errorInfo._ErrorMessage) ? errorInfo.code : errorInfo._ErrorMessage)))
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new BackBlazeException(ex.Message, 1001);
                }
            }
        }
コード例 #11
0
ファイル: BClient.cs プロジェクト: loudKode/BackBlazeSDK
        public async Task <JSON_FileMetadata> Upload(object FileToUpload, UploadTypes UploadType, string DestinationBucketID, string FileName, string SHA1, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            var uploadUrl = await GETUploadUrl(DestinationBucketID);

            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpSendProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Uploading..."
                    }); };
                using (HtpClient localHttpClient = new HtpClient(progressHandler))
                {
                    var         HtpReqMessage = new HtpRequestMessage(HttpMethod.Post, new Uri(uploadUrl.uploadUrl));
                    HttpContent streamContent = null;;
                    switch (UploadType)
                    {
                    case UploadTypes.FilePath:
                        streamContent = new StreamContent(new System.IO.FileStream(FileToUpload.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read));
                        break;

                    case UploadTypes.Stream:
                        streamContent = new StreamContent((System.IO.Stream)FileToUpload);
                        break;

                    case UploadTypes.BytesArry:
                        streamContent = new StreamContent(new System.IO.MemoryStream((byte[])FileToUpload));
                        break;
                    }
                    streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    // #If NET452 Then
                    // streamContent.Headers.ContentType = New Net.Http.Headers.MediaTypeHeaderValue(system.Web.MimeMapping.GetMimeMapping(FileName))
                    // #End If
                    HtpReqMessage.Content = streamContent;
                    HtpReqMessage.Headers.TryAddWithoutValidation("Authorization", uploadUrl.authorizationToken);
                    HtpReqMessage.Headers.TryAddWithoutValidation("X-Bz-File-Name", WebUtility.UrlEncode(FileName));
                    HtpReqMessage.Headers.TryAddWithoutValidation("Content-Length", "2000");
                    HtpReqMessage.Headers.TryAddWithoutValidation("X-Bz-Content-Sha1", SHA1);

                    // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                    using (HttpResponseMessage ResPonse = await localHttpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false))
                    {
                        string result = await ResPonse.Content.ReadAsStringAsync();

                        token.ThrowIfCancellationRequested();
                        if (ResPonse.StatusCode == HttpStatusCode.OK)
                        {
                            var userInfo = JsonConvert.DeserializeObject <JSON_FileMetadata>(result);
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = $"[{FileName}] Uploaded successfully"
                            });
                            return(userInfo);
                        }
                        else
                        {
                            var errorInfo = JsonConvert.DeserializeObject <JSON_Error>(result);
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = $"The request returned with HTTP status code {errorInfo._ErrorMessage ?? errorInfo.code}"
                            });
                            return(null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new BackBlazeException(ex.Message, 1001);
                }
                return(null);
            }
        }
コード例 #12
0
        public async Task DownloadAsZip(string FileSaveDir, string FileName, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            var parameters = new Dictionary <string, string>
            {
                { "username", Username },
                { "password", Password },
                { "fileids", string.Join(",", FileIDs) },
                { "forcedownload", "1" },
                { "filename", FileName }
            };

            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpReceiveProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Downloading..."
                    }); };
                // ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                HttpClient         localHttpClient = new HtpClient(progressHandler);
                HttpRequestMessage HtpReqMessage   = new HttpRequestMessage(HttpMethod.Get, new pUri("/getzip", parameters));
                // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                using (HttpResponseMessage ResPonse = await localHttpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false))
                {
                    token.ThrowIfCancellationRequested();
                    if (ResPonse.IsSuccessStatusCode)
                    {
                        ReportCls.Report(new ReportStatus()
                        {
                            Finished = true, TextStatus = $"[{FileName}] Downloaded successfully."
                        });
                    }
                    else
                    {
                        ReportCls.Report(new ReportStatus()
                        {
                            Finished = true, TextStatus = $"Error code: {ResPonse.ReasonPhrase}"
                        });
                    }

                    ResPonse.EnsureSuccessStatusCode();
                    var stream_ = await ResPonse.Content.ReadAsStreamAsync();

                    string FPathname = System.IO.Path.Combine(FileSaveDir, FileName);
                    using (var fileStream = new System.IO.FileStream(FPathname, System.IO.FileMode.Append, System.IO.FileAccess.Write))
                    {
                        stream_.CopyTo(fileStream);
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new pCloudException(ex.Message, 1001);
                }
            }
        }
コード例 #13
0
ファイル: PushClient.cs プロジェクト: loudKode/PushbulletSDK
        public async Task <string> Upload(object FileToUpload, Utilitiez.UploadTypes UploadType, string FileName, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            var uploadUrl = await GetUploaadUrl(FileName, UptoboxSDK.MimeMapping.GetMimeMapping(FileName));

            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                var progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpSendProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Uploading..."
                    }); };
                // '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
                using (HtpClient localHttpClient = new HtpClient(progressHandler))
                {
                    HttpRequestMessage HtpReqMessage = new HttpRequestMessage(HttpMethod.Post, new Uri(uploadUrl.upload_url));
                    var           MultipartsformData = new MultipartFormDataContent();
                    StreamContent streamContent      = null;
                    // streamContent.Headers.ContentType = New Net.Http.Headers.MediaTypeHeaderValue(Web.MimeMapping.GetMimeMapping(FileName))
                    switch (UploadType)
                    {
                    case Utilitiez.UploadTypes.FilePath:
                        streamContent = new StreamContent(new System.IO.FileStream(FileToUpload.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read));
                        break;

                    case Utilitiez.UploadTypes.Stream:
                        streamContent = new StreamContent((System.IO.Stream)FileToUpload);
                        break;

                    case Utilitiez.UploadTypes.BytesArry:
                        streamContent = new StreamContent(new System.IO.MemoryStream((byte[])FileToUpload));
                        break;
                    }

                    // streamContent.Headers.ContentDisposition = New System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") With {.Name = """files[]""", .FileName = """" + FileName + """"}
                    // streamContent.Headers.ContentType = New Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream")
                    MultipartsformData.Add(streamContent, "file", FileName);
                    HtpReqMessage.Content = MultipartsformData;
                    // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                    using (HttpResponseMessage ResPonse = await localHttpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false))
                    {
                        token.ThrowIfCancellationRequested();
                        if (ResPonse.StatusCode == HttpStatusCode.NoContent)
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = $"[{FileName}] Uploaded successfully"
                            });
                            return(uploadUrl.file_url);
                        }
                        else
                        {
                            string result = await ResPonse.Content.ReadAsStringAsync();

                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = $"The request returned with HTTP status code {ResPonse.ReasonPhrase}"
                            });
                            ShowError(result);
                            return(null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new PushbulletException(ex.Message, 1001);
                }
                return(null);
            }
        }
コード例 #14
0
ファイル: FolderClient.cs プロジェクト: jackkoolage/pCloudSDK
        public async Task <List <JSON_FileMetadata> > UploadLocal(object FileToUP, SentType TheUpType, string Filename, bool AutoRename = true, IProgress <ReportStatus> ReportCls = null, CancellationToken token = default)
        {
            var parameters = new AuthDictionary
            {
                { "folderid", FolderID.ToString() },
                { "filename", Filename },
                { "nopartial", "1" },
                { "renameifexists", AutoRename ? "1" : null }
            };

            ReportCls = ReportCls ?? new Progress <ReportStatus>();
            ReportCls.Report(new ReportStatus()
            {
                Finished = false, TextStatus = "Initializing..."
            });
            try
            {
                System.Net.Http.Handlers.ProgressMessageHandler progressHandler = new System.Net.Http.Handlers.ProgressMessageHandler(new HCHandler());
                progressHandler.HttpSendProgress += (sender, e) => { ReportCls.Report(new ReportStatus()
                    {
                        ProgressPercentage = e.ProgressPercentage, BytesTransferred = e.BytesTransferred, TotalBytes = e.TotalBytes ?? 0, TextStatus = "Uploading..."
                    }); };
                using (HttpClient localHttpClient = new HtpClient(progressHandler))
                {
                    HttpRequestMessage HtpReqMessage = new HttpRequestMessage(HttpMethod.Post, new pUri("/uploadfile", parameters.RemoveEmptyValues()));
                    // '''''''''''''''''''''''''''''''''
                    HttpContent streamContent = null;
                    switch (TheUpType)
                    {
                    case SentType.filepath:
                        streamContent = new StreamContent(new System.IO.FileStream(FileToUP.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read));
                        break;

                    case SentType.memorystream:
                        streamContent = new StreamContent((System.IO.Stream)FileToUP);
                        break;

                    case SentType.bytesArray:
                        streamContent = new StreamContent(new System.IO.MemoryStream((byte[])FileToUP));
                        break;
                    }
                    streamContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
                    HtpReqMessage.Content             = streamContent;
                    // ''''''''''''''''will write the whole content to H.D WHEN download completed'''''''''''''''''''''''''''''
                    using (HttpResponseMessage ResPonse = await localHttpClient.SendAsync(HtpReqMessage, HttpCompletionOption.ResponseContentRead, token).ConfigureAwait(false))
                    {
                        string result = await ResPonse.Content.ReadAsStringAsync();

                        token.ThrowIfCancellationRequested();
                        if (ResPonse.StatusCode == HttpStatusCode.OK && JObject.Parse(result).Value <int>("result").Equals(0))
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = "Upload completed successfully"
                            });
                            return(JsonConvert.DeserializeObject <List <JSON_FileMetadata> >(JObject.Parse(result).SelectToken("metadata").ToString(), JSONhandler));
                        }
                        else
                        {
                            ReportCls.Report(new ReportStatus()
                            {
                                Finished = true, TextStatus = $"The request returned with HTTP status code {ResPonse.ReasonPhrase}"
                            });
                            ShowError(result);
                            return(null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ReportCls.Report(new ReportStatus()
                {
                    Finished = true
                });
                if (ex.Message.ToString().ToLower().Contains("a task was canceled"))
                {
                    ReportCls.Report(new ReportStatus()
                    {
                        TextStatus = ex.Message
                    });
                }
                else
                {
                    throw new pCloudException(ex.Message, 1001);
                }
                return(null);
            }
        }