public async System.Threading.Tasks.Task <bool> UploadImage(IInstaApi instaApi, string filePath, string caption) { try { var mediaImage = new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 0, Width = 0, Uri = filePath }; var result = await instaApi.MediaProcessor.UploadPhotoAsync(mediaImage, caption); if (!result.Succeeded) { InfoFormat("Unable to upload image: {0}", result.Info.Message); return(false); } InfoFormat("Media created: {0}, {1}", result.Value.Pk, result.Value.Caption.Text); return(true); } catch (Exception e) { ErrorFormat("An error occured while uploading the image: {0}", e, filePath); return(false); } }
private async Task SetPostAsync(string path, string message) { if (File.Exists(path)) { Console.WriteLine("Loading.."); var mediaImage = new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 0, Width = 0, Uri = path }; /* Add user tag (tag people) * mediaImage.UserTags.Add(new InstaUserTagUpload * { * Username = "******", * X = 0.5, * Y = 0.5 * }); */ var result = await InstaApi.MediaProcessor.UploadPhotoAsync(mediaImage, message); Console.WriteLine(result.Succeeded ? $"Media created: {result.Value.Pk}, {result.Value.Caption}" : $"Unable to upload photo: {result.Info.Message}"); } else { DirectoryInfo dirInfo = new DirectoryInfo(Environment.CurrentDirectory + PathContract.pathImg); dirInfo.Create(); Console.WriteLine("File not found : " + path); Console.WriteLine("Add image into next directory: " + Environment.CurrentDirectory + PathContract.pathImg); } }
public static InstaImageUpload AsUpload( this InstaImage image, InstaMedia media, string uri) { var imageUpload = new InstaImageUpload(uri, image.Width, image.Height); var tagsUpload = new List <InstaUserTagUpload>(); if (media.UserTags != null) { foreach (var tag in media.UserTags) { var tagUpload = new InstaUserTagUpload(); if (tag.User != null) { tagUpload.Username = tag.User.UserName; } if (tag.Position != null) { tagUpload.X = tag.Position.X; tagUpload.Y = tag.Position.Y; } tagsUpload.Add(tagUpload); } } imageUpload.UserTags.AddRange(tagsUpload); return(imageUpload); }
/// <summary> /// Attempts to upload an image to instagram /// </summary> /// <param name="filePath"></param> /// <returns></returns> public bool PostImage(string filePath) { var captionTags = instagramTags; var captionTitle = Path.GetFileNameWithoutExtension(filePath); var instagramCaption = captionTitle + Environment.NewLine + captionTags; var igImage = Image.FromFile(filePath); var mediaImage = new InstaImageUpload() { Height = igImage.Height, Width = igImage.Width, ImageBytes = File.ReadAllBytes(filePath), Uri = filePath }; if (InstaClient.IsUserAuthenticated) { var uploadResult = InstaClient.MediaProcessor.UploadPhotoAsync(mediaImage, instagramCaption).Result; igImage.Dispose(); if (uploadResult.Succeeded) { return(true); } } return(false); }
public async Task DoShowWithProgress() { var mediaImage = new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 0, Width = 0, Uri = "e/" + imagename1 }; // Add user tag (tag people) //mediaImage.UserTags.Add(new InstaUserTagUpload //{ // Username = "******", // X = 0.5, // Y = 0.5 //}); // Upload photo with progress //var result = await InstaApi.MediaProcessor.UploadPhotoAsync(UploadProgress, mediaImage, Content); //Console.WriteLine(result.Succeeded // ? $"Media created: {result.Value.Pk}, {result.Value.Caption}" // : $"Unable to upload photo: {result.Info.Message}"); await InstaApi.LogoutAsync(); }
private async void btnImage_Click(object sender, EventArgs e) { OpenFileDialog op = new OpenFileDialog() { Title = "تصویر را انتخاب کنید", Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png" }; if (op.ShowDialog() == DialogResult.OK) { label1.Visible = false; label2.Visible = false; txtCapthion.Visible = false; txtTag.Visible = false; btnImage.Visible = false; btnVideo.Visible = false; lblLoad.Visible = true; var media = new InstaImageUpload() { Uri = op.FileName, }; media.UserTags.Add(new InstaUserTagUpload() { Username = txtTag.Text, }); var res = await ApiManage.instaApi.MediaProcessor.UploadPhotoAsync(media, txtCapthion.Text); if (res.Succeeded) { lblLoad.Visible = false; label1.Visible = true; label2.Visible = true; txtCapthion.Visible = true; txtTag.Visible = true; btnImage.Visible = true; btnVideo.Visible = true; if (MessageBox.Show("پست شما ارسال شد کار دیگری در این صفحه دارید ", "سوال", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No) { this.Close(); } else { txtCapthion.Clear(); txtTag.Clear(); } } else { MessageBox.Show($"پست ارسال نشد {res.Info.Message}"); } } }
async Task <IResult <string> > UploadSinglePhoto(InstaImageUpload image, string uploadId = null, string recipient = null) { if (string.IsNullOrEmpty(uploadId)) { uploadId = GenerateUploadId(); } var photoHashCode = Path.GetFileName(image.Uri ?? $"C:\\{13.GenerateRandomStringStatic()}.jpg").GetHashCode(); var photoEntityName = $"{uploadId}_0_{photoHashCode}"; var photoUri = GetUploadPhotoUri(uploadId, photoHashCode); var photoUploadParamsObj = new JObject { { "upload_id", uploadId }, { "media_type", "1" }, { "retry_context", GetRetryContext() }, { "image_compression", "{\"lib_name\":\"moz\",\"lib_version\":\"3.1.m\",\"quality\":\"95\"}" }, { "xsharing_user_ids", $"[{recipient ?? string.Empty}]" }, }; if (UploadItem.IsAlbum) { photoUploadParamsObj.Add("is_sidecar", "1"); } var photoUploadParams = JsonConvert.SerializeObject(photoUploadParamsObj); var imageBytes = image.ImageBytes ?? File.ReadAllBytes(image.Uri); var imageContent = new ByteArrayContent(imageBytes); imageContent.Headers.Add("Content-Transfer-Encoding", "binary"); imageContent.Headers.Add("Content-Type", "application/octet-stream"); var device = InstaApi.GetCurrentDevice(); var httpRequestProcessor = InstaApi.HttpRequestProcessor; var request = InstaApi.HttpHelper.GetDefaultRequest(HttpMethod.Post, photoUri, device); request.Content = imageContent; request.Headers.Add("X-Entity-Type", "image/jpeg"); request.Headers.Add("Offset", "0"); request.Headers.Add("X-Instagram-Rupload-Params", photoUploadParams); request.Headers.Add("X-Entity-Name", photoEntityName); request.Headers.Add("X-Entity-Length", imageBytes.Length.ToString()); request.Headers.Add("X_FB_PHOTO_WATERFALL_ID", UploadItem.IsStory ? UploadId : Guid.NewGuid().ToString()); var response = await httpRequestProcessor.SendAsync(request); /* var json =*/ await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { return(Result.Success(uploadId)); } else { return(Result.Fail <string>("NO UPLOAD ID")); } }
public async Task DoShow() { var images = new InstaImageUpload[] { new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 0, Width = 0, Uri = @"c:\image1.jpg", // add user tags to your images UserTags = new List <InstaUserTagUpload> { new InstaUserTagUpload { Username = "******", X = 0.5, Y = 0.5 } } }, new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 0, Width = 0, Uri = @"c:\image2.jpg" } }; var videos = new InstaVideoUpload[] { new InstaVideoUpload { // leave zero, if you don't know how height and width is it. Video = new InstaVideo(@"c:\video1.mp4", 0, 0), VideoThumbnail = new InstaImage(@"c:\video thumbnail 1.jpg", 0, 0) }, new InstaVideoUpload { // leave zero, if you don't know how height and width is it. Video = new InstaVideo(@"c:\video2.mp4", 0, 0), VideoThumbnail = new InstaImage(@"c:\video thumbnail 2.jpg", 0, 0) } }; var result = await InstaApi.MediaProcessor.UploadAlbumAsync(images, videos, "Hey, this my first album upload via InstagramApiSharp library."); // Above result will be something like this: IMAGE1, IMAGE2, VIDEO1, VIDEO2 Console.WriteLine(result.Succeeded ? $"Media created: {result.Value.Pk}, {result.Value.Caption}" : $"Unable to upload album: {result.Info.Message}"); }
/// <summary> /// Post to instagram account /// </summary> /// <param name="ID"></param> public static void InstagramPost(string ID) { if (!InstagramLogin().Result) { return; } System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\Users\email\Desktop\Hardware Hub\images\" + ID + ".png"); var mediaImage = new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 0, Width = 0, ImageBytes = ImageToByteArray(img) }; api.MediaProcessor.UploadPhotoAsync(mediaImage, getInstaBody(ID)).Wait(); #region old Selenium Post approach //try //{ // wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath("//div [@class = 'q02Nz _0TPg']"))); //} //catch (WebDriverTimeoutException) //{ //} //driver.FindElement(By.XPath("//div [@class = 'q02Nz _0TPg']")).Click(); //Thread.Sleep(500); //System.Windows.Forms.SendKeys.SendWait(@"C:\Users\email\Desktop\Hardware Hub\images\" + ID + ".png"); //Thread.Sleep(500); //System.Windows.Forms.SendKeys.SendWait("{ENTER}"); //Thread.Sleep(500); //System.Windows.Forms.SendKeys.SendWait(@"C:\Users\email\Desktop\Hardware Hub\images\" + ID + ".png"); //Thread.Sleep(500); //System.Windows.Forms.SendKeys.SendWait("{ENTER}"); //try //{ // wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath("//div [@class = 'mt3GC']"))); //} //catch (WebDriverTimeoutException) //{ //} //driver.FindElement(By.XPath("//div [@class = 'mXkkY KDuQp']")).Click(); //wait.Until(ExpectedConditions.PresenceOfAllElementsLocatedBy(By.XPath("//div [@class = 'NfvXc']"))); //driver.FindElement(By.XPath("//div [@class = 'NfvXc']")).Click(); //driver.FindElement(By.XPath("//textarea")).SendKeys(getInstaBody(ID)); //driver.FindElement(By.XPath("//div [@class = 'mXkkY KDuQp']")).Click(); #endregion }
public async Task <HttpResponseMessage> Post() { var httpRequest = HttpContext.Current.Request; string content = httpRequest.Form["content"]; if (content == null) { content = ""; } if (httpRequest.Files.Count > 0) { var postedFile = httpRequest.Files[0]; string filePath = HttpContext.Current.Server.MapPath("~/InstagramPhotos/" + postedFile.FileName); postedFile.SaveAs(filePath); var mediaImage = new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 0, Width = 0, Uri = @"" + filePath }; IInstaApi api = (IInstaApi)HttpContext.Current.Session["api"]; if (api == null || api.IsUserAuthenticated == false) { return(Request.CreateResponse(HttpStatusCode.Unauthorized)); } var result = await api.MediaProcessor.UploadPhotoAsync(mediaImage, content); //var collections = await api.GetCurrentUserAsync(); //var mediacollections = await api.UserProcessor.GetUserMediaAsync(collections.Value.UserName, InstagramApiSharp.PaginationParameters.MaxPagesToLoad(1)); //mediacollections.Value[0].Like return(Request.CreateResponse(HttpStatusCode.Created)); } return(Request.CreateResponse(HttpStatusCode.BadRequest)); }
private async Task DoPictureUpload() { uploadBtn.Enabled = false; var picture = new InstaImageUpload { Height = 0, Width = 0, Uri = @filePath }; var caption = captionRichTxtBox.Text; var result = await instaApi.MediaProcessor.UploadPhotoAsync(UpdateUploadProgressToLabel, picture, caption); progressLbl.Text = (result.Succeeded ? $"Picture Uploaded: {result.Value.Pk}" : $"Unable to upload photo: {result.Info.Message}"); uploadBtn.Enabled = true; }
private async void button1_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; try { string startupPath = Directory.GetCurrentDirectory(); Bitmap imgBitmap = Utilidades.ConvertTo24bpp(ImagenAsubir.Image); string sRutaImagen = string.Format("{0}\\Uploads\\{1}.jpg", startupPath, Guid.NewGuid().ToString()); imgBitmap.Save(sRutaImagen, ImageFormat.Jpeg); var mediaImage = new InstaImageUpload { Height = 1080, Width = 1080, Uri = sRutaImagen }; var result = await _instaApi.MediaProcessor.UploadPhotoAsync(mediaImage, txtComentarios.Text); if (result.Succeeded) { this.Cursor = Cursors.Default; MessageBox.Show("Proceso completado satisfactoriamente", "Mensaje de Información", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { this.Cursor = Cursors.Default; MessageBox.Show(result.Info.Message, "Mensaje de Exception Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } imgBitmap.Dispose(); File.Delete(sRutaImagen); } catch (Exception ex) { this.Cursor = Cursors.Default; MessageBox.Show(ex.Message, "Mensaje de Exception Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Instagram Resim Upload /// </summary> /// <param name="yol"></param> /// <param name="mesaj"></param> /// <returns></returns> private string instaResimUploadFonk(string yol, string mesaj) { string cikti = null; var resimUpload = Task.Run(() => { try { var mediaImage = new InstaImageUpload { Height = 1080, Width = 1080, Uri = yol }; var result = InstaApi.MediaProcessor.UploadPhotoAsync(mediaImage, mesaj); if (result.Result.Succeeded) { cikti = "true"; } else { cikti = "false"; } } catch { cikti = "Exception"; } }); resimUpload.Wait(); if (resimUpload.IsCompleted) { return(cikti); } else { return(cikti); } }
public static bool UploadPicture(string path, string caption) { InstaImageUpload img = new InstaImageUpload() { Uri = path }; InstaImage img2 = new InstaImage() { Uri = path }; var iimg = _api.MediaProcessor.UploadPhotoAsync(img, caption).Result; var anotherResult = _api.StoryProcessor.UploadStoryPhotoAsync(img2, caption).Result; //System.Threading.Thread.Sleep(1000); InstaMedia im = iimg.Value; File.Delete(path); Console.WriteLine("New Image online"); return(true); }
public async Task DoShow() { var mediaImage = new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 1080, Width = 1080, Uri = "e/" + imagename1 }; // Add user tag (tag people) //mediaImage.UserTags.Add(new InstaUserTagUpload //{ // Username = "******", // X = 0.5, // Y = 0.5 //}); var result = await InstaApi.MediaProcessor.UploadPhotoAsync(mediaImage, Content); Console.WriteLine(result.Succeeded ? $"Media created: {result.Value.Pk}, {result.Value.Caption}" : $"Unable to upload photo: {result.Info.Message}"); }
public async Task DoShow() { var mediaImage = new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 1080, Width = 1080, Uri = @"C:\Users\idrees.FI\Desktop\yky\01.jpg" }; // Add user tag (tag people) mediaImage.UserTags.Add(new InstaUserTagUpload { Username = "******", X = 0.5, Y = 0.5 }); var result = await InstaApi.MediaProcessor.UploadPhotoAsync(mediaImage, "someawesomepicture"); Console.WriteLine(result.Succeeded ? $"Media created: {result.Value.Pk}, {result.Value.Caption}" : $"Unable to upload photo: {result.Info.Message}"); }
public async Task UploadAndComment() { string postAuthor = File.ReadAllText(@"C:\dev\me_irl_bot_two\credit\author.txt"); string postTitle = File.ReadAllText(@"C:\dev\me_irl_bot_two\credit\title.txt"); string postLink = File.ReadAllText(@"C:\dev\me_irl_bot_two\credit\link.txt"); string location = imageFolder + "bot_resized.jpg"; string caption = postTitle; if (caption.ToLower() == "me irl" || caption.ToLower() == "me_irl") { caption = "me_irl"; } string imageUser = "******" + postAuthor; string comment = "A mirrored post from /r/me_irl by " + imageUser + ": " + postLink; string url = "http://instagram.com/p/"; var mediaImage = new InstaImageUpload { Height = 0, Width = 0, Uri = @location }; Process("Uploading image to Instagram and adding caption and credit."); var result = await api.MediaProcessor.UploadPhotoAsync(mediaImage, "" + caption); var commentResult = await api.CommentProcessor.CommentMediaAsync(result.Value.Pk, comment); if (result.Succeeded && commentResult.Succeeded) { Success("Media was uploaded."); Result( $"\n\n\tTYPE: " + result.Value.MediaType + $"\n\tCAPTION: \"" + caption + "\"" + $"\n\tID: " + result.Value.Pk + $"\n\tLINK: " + url + result.Value.Code + $"\n\tSOURCE: " + location + $"\n\tCREDIT: \"" + comment + "\""); try { await DeleteImages(); } catch (Exception ex) { ErrorReason("Error detected. ", ex.Message); EndTime(); Wait(); } } else { if (!result.Succeeded) { Error("Media could not be uploaded."); Reason(result.Info.Message); var deleteMedia = await api.MediaProcessor.DeleteMediaAsync(result.Value.Pk, result.Value.MediaType); Logout(); Environment.Exit(0); } else if (!commentResult.Succeeded) { Error("Media could not be captioned."); Reason(commentResult.Info.Message); var deleteMedia = await api.MediaProcessor.DeleteMediaAsync(result.Value.Pk, result.Value.MediaType); Logout(); Environment.Exit(0); } else if (!commentResult.Succeeded && !result.Succeeded) { Error("Media could not be captioned or uploaded."); Reason(commentResult.Info.Message); Reason(result.Info.Message); var deleteMedia = await api.MediaProcessor.DeleteMediaAsync(result.Value.Pk, result.Value.MediaType); Logout(); Environment.Exit(0); } } }
protected void UploadButton_Click1(object sender, EventArgs e) { string content = ContentText.Text; string name = FileUploader.PostedFile.FileName; //string type = FileUploader.PostedFile.ContentType.ToString(); //UploadButton.Text = type; string extension = Path.GetExtension(FileUploader.PostedFile.FileName); if (extension.ToLower() == ".jpg") { var mediaImage = new InstaImageUpload { // leave zero, if you don't know how height and width is it. Height = 0, Width = 0, Uri = @"E:\" + name }; //UploadButton.Text = mediaImage.Uri; DataTable dtusers = Session["users"] as DataTable; //sepet DataTable'a dönüştürülüyor. DataTable dt; for (int i = 0; i < dtusers.Rows.Count; i++) { SqlParameter prm_Username = new SqlParameter("@username", dtusers.Rows[i]["Username"].ToString()); dt = db.Fill("select * from Userstbl where Username=@username", prm_Username); if (dt != null && dt.Rows.Count > 0) { var userSession = new UserSessionData { UserName = dt.Rows[0]["Username"].ToString(), Password = dt.Rows[0]["PassWord"].ToString() }; var delay = RequestDelay.FromSeconds(2, 2); ınstagramApi = InstaApiBuilder.CreateBuilder() .SetUser(userSession) .UseLogger(new DebugLogger(LogLevel.Exceptions)) // use logger for requests and debug messages .SetRequestDelay(delay) //.SetDevice(androidDevice); .SetSessionHandler(new FileSessionHandler() { FilePath = StateFile }) .Build(); var x = Task.Run(() => ınstagramApi.LoginAsync()); if (x.Result.Succeeded) { UploadButton.Text = "Login"; } var t = Task.Run(() => ınstagramApi.MediaProcessor.UploadPhotoAsync(mediaImage, content)); if (t.Result.Succeeded) { UploadButton.Text = "Uploaded succesfully"; } LoadSession(); } } } else { var video = new InstaVideoUpload { // leave zero, if you don't know how height and width is it. Video = new InstaVideo(@"E:\" + name, 0, 0), //VideoThumbnail = new InstaImage(@"E:\5b0cef13ae78490f20de575c.jpg" , 0, 0) }; DataTable dtusers = Session["users"] as DataTable; //sepet DataTable'a dönüştürülüyor. DataTable dt; for (int i = 0; i < dtusers.Rows.Count; i++) { SqlParameter prm_Username = new SqlParameter("@username", dtusers.Rows[i]["Username"].ToString()); dt = db.Fill("select * from Userstbl where Username=@username", prm_Username); if (dt != null && dt.Rows.Count > 0) { var userSession = new UserSessionData { UserName = dt.Rows[0]["Username"].ToString(), Password = dt.Rows[0]["PassWord"].ToString() }; var delay = RequestDelay.FromSeconds(2, 2); ınstagramApi = InstaApiBuilder.CreateBuilder() .SetUser(userSession) .UseLogger(new DebugLogger(LogLevel.Exceptions)) // use logger for requests and debug messages .SetRequestDelay(delay) //.SetDevice(androidDevice); .SetSessionHandler(new FileSessionHandler() { FilePath = StateFile }) .Build(); var x = Task.Run(() => ınstagramApi.LoginAsync()); var result = Task.Run(() => ınstagramApi.MediaProcessor.UploadVideoAsync(video, content)); if (result.Result.Succeeded) { UploadButton.Text = "Uploaded succesfully"; } LoadSession(); } } } }
private async void UploadButtonClick(object sender, RoutedEventArgs e) { if (SelectedFiles == null) { "Please select at least one file.".ShowERR(); return; } if (UploadButton.Content.ToString().StartsWith("Uploading") || UploadButton.Content.ToString().StartsWith("Preparing")) { "Uploading....".ShowERR(); return; } var caption = CaptionText.Text; if (SelectedFiles.Count == 1) { var file = SelectedFiles.FirstOrDefault(); var fileBytes = (await FileIO.ReadBufferAsync(file)).ToArray(); UploadButton.Content = "Uploading photo..."; var img = new InstaImageUpload { // Set image bytes ImageBytes = fileBytes, // Note: you should set Uri path ! Uri = file.Path }; // Add user tag (tag people) img.UserTags.Add(new InstaUserTagUpload { Username = "******", X = 0.5, Y = 0.5 }); var up = await InstaApi.MediaProcessor.UploadPhotoAsync(img, caption); if (up.Succeeded) { "Your photo uploaded successfully.".ShowMsg(); } else { up.Info.Message.ShowERR(); } UploadButton.Content = "Upload"; } else { // album var videos = new List <InstaVideoUpload>(); var images = new List <InstaImage>(); //// How set videos? //videos.Add(new InstaVideoUpload //{ // // video // Video = new InstaVideo // { // // set video bytes // VideoBytes = VIDEOBYTES // // Note: you should set Uri path ! you can set a random path // //Uri = VIDEO PATH // }, // // video thumbnail image // VideoThumbnail = new InstaImage // { // // set video thumbnail image bytes // ImageBytes = THUMBNAILIMAGEBYTES, // // Note: you should set Uri path ! you can set a random path // //Uri = THUMBNAIL PATH // } //}); foreach (var file in SelectedFiles) { var fileBytes = (await FileIO.ReadBufferAsync(file)).ToArray(); var img = new InstaImage { // Set image bytes ImageBytes = fileBytes, // Note: you should set Uri path ! you can set random path Uri = file.Path }; images.Add(img); } UploadButton.Content = "Uploading album..."; var up = await InstaApi.MediaProcessor.UploadAlbumAsync(images.ToArray(), videos.ToArray(), caption); if (up.Succeeded) { "Your album uploaded successfully.".ShowMsg(); } else { up.Info.Message.ShowERR(); } UploadButton.Content = "Upload"; } }
async void UploadProgress(UploadOperation upload) { LogStatus(string.Format("Progress: {0}, Status: {1}", upload.Guid, upload.Progress.Status)); BackgroundUploadProgress progress = upload.Progress; double percentSent = 100; if (progress.TotalBytesToSend > 0) { var bs = progress.BytesSent; percentSent = bs * 100 / progress.TotalBytesToSend; } SendNotify(percentSent); //MarshalLog(String.Format(" - Sent bytes: {0} of {1} ({2}%)", // progress.BytesSent, progress.TotalBytesToSend, percentSent)); LogStatus(string.Format(" - Sent bytes: {0} of {1} ({2}%), Received bytes: {3} of {4}", progress.BytesSent, progress.TotalBytesToSend, percentSent, progress.BytesReceived, progress.TotalBytesToReceive)); if (progress.HasRestarted) { LogStatus(" - Upload restarted"); } if (progress.HasResponseChanged) { var resp = upload.GetResponseInformation(); // We've received new response headers from the server. LogStatus(" - Response updated; Header count: " + resp.Headers.Count); var response = upload.GetResultStreamAt(0); StreamReader stream = new StreamReader(response.AsStreamForRead()); Debug.WriteLine("----------------------------------------Response from upload----------------------------------"); var st = stream.ReadToEnd(); Debug.WriteLine(st); //var res = JsonConvert.DeserializeObject<APIResponseOverride>(st); //await ConfigureMediaPhotoAsync(res.upload_id, Caption, null, null); var thumbStream = (await Thumbnail.OpenAsync(FileAccessMode.Read)).AsStream(); var bytes = await thumbStream.ToByteArray(); var img = new InstaImageUpload { ImageBytes = bytes, Uri = Thumbnail.Path }; await UploadSinglePhoto(img, UploadId, false); await Task.Delay(15000); await FinishVideoAsync(); await Task.Delay(1500); await ConfigureVideoAsync(); //UploadCompleted?.Invoke(null, Convert.ToInt64(res.upload_id)); // If you want to stream the response data this is a good time to start. // upload.GetResultStreamAt(0); } }
async void UploadProgress(UploadOperation upload) { LogStatus(string.Format("Progress: {0}, Status: {1}", upload.Guid, upload.Progress.Status)); MainPage.Current?.ShowMediaUploadingUc(); BackgroundUploadProgress progress = upload.Progress; double percentSent = 100; if (progress.TotalBytesToSend > 0) { percentSent = progress.BytesSent * 100 / progress.TotalBytesToSend; } SendNotify(percentSent); LogStatus(string.Format(" - Sent bytes: {0} of {1} ({2}%), Received bytes: {3} of {4}", progress.BytesSent, progress.TotalBytesToSend, percentSent, progress.BytesReceived, progress.TotalBytesToReceive)); if (progress.HasRestarted) { LogStatus(" - Upload restarted"); } if (progress.HasResponseChanged) { var resp = upload.GetResponseInformation(); LogStatus(" - Response updated; Header count: " + resp.Headers.Count); var response = upload.GetResultStreamAt(0); StreamReader stream = new StreamReader(response.AsStreamForRead()); Debug.WriteLine("----------------------------------------Response from upload----------------------------------"); var st = stream.ReadToEnd(); Debug.WriteLine(st); if (UploadItem.IsVideo) { if (!UploadItem.IsStory) { var thumbStream = (await UploadItem.ImageToUpload.OpenAsync(FileAccessMode.Read)).AsStream(); var bytes = await thumbStream.ToByteArray(); var img = new InstaImageUpload { ImageBytes = bytes, Uri = UploadItem.ImageToUpload.Path }; await UploadSinglePhoto(img, UploadId); } await Task.Delay(15000); if (!UploadItem.IsStory) { await FinishVideoAsync(); } await Task.Delay(1500); } if (!UploadItem.IsAlbum) { await ConfigurMediaAsync(); } else { OnUploadCompleted?.Invoke(this); } } }