public async System.Threading.Tasks.Task <bool> UploadVideo(IInstaApi instaApi, string filePath, string thumbnailPath, string caption) { try { var mediaVideo = new InstaVideoUpload { Video = new InstaVideo(filePath, 0, 0), VideoThumbnail = new InstaImage(thumbnailPath, 0, 0) }; var result = await instaApi.MediaProcessor.UploadVideoAsync(mediaVideo, caption); if (!result.Succeeded) { InfoFormat("Unable to upload video: {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 video: {0}", e, filePath); return(false); } }
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}"); }
public async void UploadVideo() { var video = new InstaVideoUpload { Video = new InstaVideo(@"c:\video1.mp4", 0, 0), VideoThumbnail = new InstaImage(@"c:\video thumbnail 1.jpg", 0, 0) }; var result = await InstaApi.StoryProcessor.UploadStoryVideoAsync(video, "ramtinak"); Console.WriteLine(result.Succeeded ? $"Story created: {result.Value.Media.Pk}" : $"Unable to upload video story: {result.Info.Message}"); }
public async Task DoShow() { var video = 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) }; var result = await InstaApi.MediaProcessor.UploadVideoAsync(video, "ramtinak"); Console.WriteLine(result.Succeeded ? $"Media created: {result.Value.Pk}, {result.Value.Caption}" : $"Unable to upload video: {result.Info.Message}"); }
public async Task DoShow() { var images = new InstaImage[] { new InstaImage { // leave zero, if you don't know how height and width is it. Height = 0, Width = 0, Uri = @"c:\image1.jpg" }, new InstaImage { // 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."); Console.WriteLine(result.Succeeded ? $"Media created: {result.Value.Pk}, {result.Value.Caption}" : $"Unable to upload photo: {result.Info.Message}"); }
/// <summary> /// Upload video /// </summary> /// <param name="video">Video and thumbnail to upload</param> /// <param name="caption">Caption</param> public async Task <IResult <InstaMedia> > UploadVideoAsync(InstaVideoUpload video, string caption) { UserAuthValidator.Validate(_userAuthValidate); try { var instaUri = UriCreator.GetUploadVideoUri(); var uploadId = ApiRequestMessage.GenerateUploadId(); var requestContent = new MultipartFormDataContent(uploadId) { { new StringContent("2"), "\"media_type\"" }, { new StringContent(uploadId), "\"upload_id\"" }, { new StringContent(_deviceInfo.DeviceGuid.ToString()), "\"_uuid\"" }, { new StringContent(_user.CsrfToken), "\"_csrftoken\"" }, { new StringContent("{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}"), "\"image_compression\"" } }; var request = HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo); request.Content = requestContent; var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); var videoResponse = JsonConvert.DeserializeObject <VideoUploadJobResponse>(json); if (videoResponse == null) { return(Result.Fail <InstaMedia>("Failed to get response from instagram video upload endpoint")); } var fileBytes = File.ReadAllBytes(video.Video.Url); var first = videoResponse.VideoUploadUrls[0]; instaUri = new Uri(Uri.EscapeUriString(first.Url)); requestContent = new MultipartFormDataContent(uploadId) { { new StringContent(_user.CsrfToken), "\"_csrftoken\"" }, { new StringContent("{\"lib_name\":\"jt\",\"lib_version\":\"1.3.0\",\"quality\":\"87\"}"), "\"image_compression\"" } }; var videoContent = new ByteArrayContent(fileBytes); videoContent.Headers.Add("Content-Transfer-Encoding", "binary"); videoContent.Headers.Add("Content-Type", "application/octet-stream"); videoContent.Headers.Add("Content-Disposition", $"attachment; filename=\"{Path.GetFileName(video.Video.Url)}\""); requestContent.Add(videoContent); request = HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo); request.Content = requestContent; request.Headers.Host = "upload.instagram.com"; request.Headers.Add("Cookie2", "$Version=1"); request.Headers.Add("Session-ID", uploadId); request.Headers.Add("job", first.Job); response = await _httpRequestProcessor.SendAsync(request); json = await response.Content.ReadAsStringAsync(); await UploadVideoThumbnailAsync(video.VideoThumbnail, uploadId); return(await ConfigureVideoAsync(video.Video, uploadId, caption)); } catch (Exception exception) { _logger?.LogException(exception); return(Result.Fail <InstaMedia>(exception)); } }
/// <summary> /// Upload video /// </summary> /// <param name="video">Video and thumbnail to upload</param> /// <param name="caption">Caption</param> /// <param name="location">Location => Optional (get it from <seealso cref="LocationProcessor.SearchLocationAsync"/></param> public async Task <IResult <InstaMedia> > UploadVideoAsync(InstaVideoUpload video, string caption, InstaLocationShort location = null) { return(await UploadVideoAsync(null, video, caption, location)); }
private async void btnVideo_Click(object sender, EventArgs e) { OpenFileDialog op = new OpenFileDialog() { Title = "فالی فیلم را انتخاب کنید ", Filter = "All Videos Files |*.dat; *.wmv; *.3g2; *.3gp; *.3gp2; *.3gpp; *.amv; *.asf; *.avi; *.bin; *.cue; *.divx; *.dv; *.flv; *.gxf; *.iso; *.m1v; *.m2v; *.m2t; *.m2ts; *.m4v; " + " *.mkv; *.mov; *.mp2; *.mp2v; *.mp4; *.mp4v; *.mpa; *.mpe; *.mpeg; *.mpeg1; *.mpeg2; *.mpeg4; *.mpg; *.mpv2; *.mts; *.nsv; *.nuv; *.ogg; *.ogm; *.ogv; *.ogx; *.ps; *.rec; *.rm; *.rmvb; *.tod; *.ts; *.tts; *.vob; *.vro; *.webm", }; grpStory.Visible = false; lblStory.Visible = true; progressBar1.Visible = true; for (int i = 0; i < 100; i++) { progressBar1.percentage = i; } timeLoad.Enabled = true; if (op.ShowDialog() == DialogResult.OK) { OpenFileDialog imageDialog = new OpenFileDialog() { Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png", Title = "ارسال تصویر شاخص" }; if (imageDialog.ShowDialog() == DialogResult.OK) { string imageUri = imageDialog.FileName; string videoUri = op.FileName; var video = new InstaVideoUpload() { Video = new InstaVideo(videoUri, 0, 0), VideoThumbnail = new InstaImage(imageUri, 0, 0) }; var res = await ApiManage.instaApi.StoryProcessor.UploadStoryVideoAsync(video, txtCaption.Text); if (res.Succeeded) { MessageBox.Show("فیلم با موفقیت آپلود شد "); grpStory.Visible = true; lblStory.Visible = false; progressBar1.Percentage = 100; progressBar1.Visible = false; } else { MessageBox.Show($"آپلود انجام نشد به دلیل \n {res.Info.Message}"); grpStory.Visible = true; lblStory.Visible = false; progressBar1.Percentage = 100; progressBar1.Visible = false; } } } }
/// <summary> /// Send disappearing video to direct thread (video will remove after user saw it) /// </summary> /// <param name="video">Video to upload</param> /// <param name="viewMode">View mode</param> /// <param name="threadIds">Thread ids</param> public async Task <IResult <bool> > SendDirectDisappearingVideoAsync(InstaVideoUpload video, InstaViewMode viewMode = InstaViewMode.Replayable, params string[] threadIds) { return(await SendDirectDisappearingVideoAsync(null, video, viewMode, threadIds)); }
/// <summary> /// Send video to direct thread (single) with progress /// </summary> /// <param name="progress">Progress action</param> /// <param name="video">Video to upload (no need to set thumbnail)</param> /// <param name="threadId">Thread id</param> public async Task <Result <bool> > SendDirectVideoAsync(Action <UploaderProgress> progress, InstaVideoUpload video, string threadId) { ValidateLoggedIn(); return(await SendVideoAsync(progress, true, false, null, VisualMediaViewMode.Replayable, InstaStoryType.Both, null, threadId, video)); }
/// <summary> /// Upload video to Instagram TV /// </summary> /// <param name="video">Video to upload (aspect ratio is very important for thumbnail and video | range 0.5 - 1.0 | Width = 480, Height = 852)</param> /// <param name="title">Title</param> /// <param name="caption">Caption</param> public async Task <IResult <InstaMedia> > UploadVideoAsync(InstaVideoUpload video, string title, string caption) { return(await UploadVideoAsync(null, video, title, caption)); }
/// <summary> /// Send video to direct thread (single) /// </summary> /// <param name="video">Video to upload (no need to set thumbnail)</param> /// <param name="threadId">Thread id</param> public async Task <IResult <bool> > SendDirectVideoAsync(InstaVideoUpload video, string threadId) { return(await SendDirectVideoAsync(null, video, threadId)); }
/// <summary> /// Upload story video (to self story) /// </summary> /// <param name="video">Video to upload</param> /// <param name="caption">Caption</param> public async Task <IResult <InstaStoryMedia> > UploadStoryVideoAsync(InstaVideoUpload video, string caption) { return(await UploadStoryVideoAsync(null, video, caption)); }
private async void UploadButtonClick(object sender, RoutedEventArgs e) { if (FileSelectorHelper.LatestSelected == null) { "Please select at least one file.".ShowMsg("ERR", MessageBoxImage.Error); } if (UploadButton.Content.ToString().StartsWith("Uploading") || UploadButton.Content.ToString().StartsWith("Preparing")) { "Uploading....".ShowMsg("ERR", MessageBoxImage.Error); return; } var caption = CaptionText.Text; if (FileSelectorHelper.LatestSelected.Length == 1) { // single photo or video var firstPath = FileSelectorHelper.LatestSelected.FirstOrDefault(); FileType type = FileSelectorHelper.GetFileType(firstPath); if (type == FileType.Video) { UploadButton.Content = "Preparing video..."; var screenshot = Path.Combine(Helper.CacheTempPath, Helper.RandomString()) + ".jpg"; Helper.FFmpeg.ExtractImageFromVideo(firstPath, screenshot); await Task.Delay(500); var vid = new InstaVideoUpload { Video = new InstaVideo(firstPath, 0, 0), VideoThumbnail = new InstaImage(screenshot, 0, 0) }; UploadButton.Content = "Preparing video..."; var up = await Helper.InstaApi.MediaProcessor.UploadVideoAsync(vid, caption); if (up.Succeeded) { "Your video uploaded successfully.".ShowMsg("Succeeded", MessageBoxImage.Information); } else { up.Info.Message.ShowMsg("ERR", MessageBoxImage.Error); } UploadButton.Content = "Upload"; } else { UploadButton.Content = "Uploading photo..."; var imgPath = ImageHelper.ConvertToJPEG(firstPath); var img = new InstaImage(imgPath, 0, 0); var up = await Helper.InstaApi.MediaProcessor.UploadPhotoAsync(img, caption); if (up.Succeeded) { "Your photo uploaded successfully.".ShowMsg("Succeeded", MessageBoxImage.Information); } else { up.Info.Message.ShowMsg("ERR", MessageBoxImage.Error); } UploadButton.Content = "Upload"; } } else { // album var videos = new List <InstaVideoUpload>(); var images = new List <InstaImage>(); UploadButton.Content = "Preparing album..."; Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(async() => { foreach (var item in FileSelectorHelper.LatestSelected) { var type = FileSelectorHelper.GetFileType(item); if (type == FileType.Image) { var imgPath = ImageHelper.ConvertToJPEG(item); images.Add(new InstaImage(imgPath, 0, 0)); } else { var screenshot = Path.Combine(Helper.CacheTempPath, Helper.RandomString()) + ".jpg"; Helper.FFmpeg.ExtractImageFromVideo(item, screenshot); var vid = new InstaVideoUpload { Video = new InstaVideo(item, 0, 0), VideoThumbnail = new InstaImage(screenshot, 0, 0) }; videos.Add(vid); await Task.Delay(2000); } } await Task.Delay(6000); UploadButton.Content = "Uploading album..."; var up = await Helper.InstaApi.MediaProcessor.UploadAlbumAsync(images.ToArray(), videos.ToArray(), caption); if (up.Succeeded) { "Your album uploaded successfully.".ShowMsg("Succeeded", MessageBoxImage.Information); } else { up.Info.Message.ShowMsg("ERR", MessageBoxImage.Error); } UploadButton.Content = "Upload"; })); } }
/// <summary> /// Send video to multiple recipients (multiple user) with progress /// </summary> /// <param name="progress">Progress action</param> /// <param name="video">Video to upload (no need to set thumbnail)</param> /// <param name="recipients">Recipients (user ids/pk)</param> public async Task <IResult <bool> > SendDirectVideoToRecipientsAsync(Action <InstaUploaderProgress> progress, InstaVideoUpload video, params string[] recipients) { UserAuthValidator.Validate(_userAuthValidate); return(await _instaApi.HelperProcessor.SendVideoAsync(progress, true, false, "", InstaViewMode.Replayable, InstaStoryType.Both, recipients.EncodeList(false), null, video)); }
/// <summary> /// Send video to multiple recipients (multiple user) /// </summary> /// <param name="video">Video to upload (no need to set thumbnail)</param> /// <param name="recipients">Recipients (user ids/pk)</param> public async Task <IResult <bool> > SendDirectVideoToRecipientsAsync(InstaVideoUpload video, params string[] recipients) { UserAuthValidator.Validate(_userAuthValidate); return(await SendDirectVideoToRecipientsAsync(null, video, recipients)); }
/// <summary> /// Send video to direct thread (single) with progress /// </summary> /// <param name="progress">Progress action</param> /// <param name="video">Video to upload (no need to set thumbnail)</param> /// <param name="threadId">Thread id</param> public async Task <IResult <bool> > SendDirectVideoAsync(Action <InstaUploaderProgress> progress, InstaVideoUpload video, string threadId) { UserAuthValidator.Validate(_userAuthValidate); return(await _instaApi.HelperProcessor.SendVideoAsync(progress, true, false, "", InstaViewMode.Replayable, InstaStoryType.Both, null, threadId, video)); }
/// <summary> /// Upload story video (to self story) with progress /// </summary> /// <param name="progress">Progress action</param> /// <param name="video">Video to upload</param> /// <param name="caption">Caption</param> public async Task <IResult <bool> > UploadStoryVideoAsync(Action <InstaUploaderProgress> progress, InstaVideoUpload video, InstaStoryType storyType = InstaStoryType.SelfStory, params string[] threadIds) { UserAuthValidator.Validate(_userAuthValidate); return(await _instaApi.HelperProcessor.SendVideoAsync(progress, false, false, "", InstaViewMode.Replayable, storyType, null, threadIds.EncodeList(), video)); }
/// <summary> /// Send disappearing video to direct thread (video will remove after user saw it) with progress /// </summary> /// <param name="progress">Progress action</param> /// <param name="video">Video to upload</param> /// <param name="viewMode">View mode</param> /// <param name="threadIds">Thread ids</param> public async Task <IResult <bool> > SendDirectDisappearingVideoAsync(Action <InstaUploaderProgress> progress, InstaVideoUpload video, InstaViewMode viewMode = InstaViewMode.Replayable, params string[] threadIds) { UserAuthValidator.Validate(_userAuthValidate); return(await _instaApi.HelperProcessor.SendVideoAsync(progress, false, true, "", viewMode, InstaStoryType.Direct, null, threadIds.EncodeList(), video)); }
/// <summary> /// Upload story video (to self story) with progress /// </summary> /// <param name="progress">Progress action</param> /// <param name="video">Video to upload</param> /// <param name="caption">Caption</param> public async Task <IResult <InstaStoryMedia> > UploadStoryVideoAsync(Action <InstaUploaderProgress> progress, InstaVideoUpload video, string caption) { UserAuthValidator.Validate(_userAuthValidate); var upProgress = new InstaUploaderProgress { Caption = caption ?? string.Empty, UploadState = InstaUploadState.Preparing }; try { var uploadId = ApiRequestMessage.GenerateRandomUploadId(); var videoHashCode = Path.GetFileName(video.Video.Uri ?? $"C:\\{13.GenerateRandomString()}.mp4").GetHashCode(); var photoHashCode = Path.GetFileName(video.VideoThumbnail.Uri ?? $"C:\\{13.GenerateRandomString()}.jpg").GetHashCode(); var waterfallId = Guid.NewGuid().ToString(); var videoEntityName = string.Format("{0}_0_{1}", uploadId, videoHashCode); var videoUri = UriCreator.GetStoryUploadVideoUri(uploadId, videoHashCode); var photoEntityName = string.Format("{0}_0_{1}", uploadId, photoHashCode); var photoUri = UriCreator.GetStoryUploadPhotoUri(uploadId, photoHashCode); upProgress.UploadId = uploadId; progress?.Invoke(upProgress); var videoMediaInfoData = new JObject { { "_csrftoken", _user.CsrfToken }, { "_uid", _user.LoggedInUser.Pk }, { "_uuid", _deviceInfo.DeviceGuid.ToString() }, { "media_info", new JObject { { "capture_mode", "normal" }, { "media_type", 2 }, { "caption", caption }, { "mentions", new JArray() }, { "hashtags", new JArray() }, { "locations", new JArray() }, { "stickers", new JArray() }, } } }; var request = HttpHelper.GetSignedRequest(HttpMethod.Post, UriCreator.GetStoryMediaInfoUploadUri(), _deviceInfo, videoMediaInfoData); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); var videoUploadParamsObj = new JObject { { "upload_media_height", "0" }, { "upload_media_width", "0" }, { "upload_media_duration_ms", "46000" }, { "upload_id", uploadId }, { "for_album", "1" }, { "retry_context", "{\"num_step_auto_retry\":0,\"num_reupload\":0,\"num_step_manual_retry\":0}" }, { "media_type", "2" }, }; var videoUploadParams = JsonConvert.SerializeObject(videoUploadParamsObj); request = HttpHelper.GetDefaultRequest(HttpMethod.Get, videoUri, _deviceInfo); request.Headers.Add("X_FB_VIDEO_WATERFALL_ID", waterfallId); request.Headers.Add("X-Instagram-Rupload-Params", videoUploadParams); response = await _httpRequestProcessor.SendAsync(request); json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result.UnExpectedResponse <InstaStoryMedia>(response, json)); } byte[] videoBytes; if (video.Video.VideoBytes == null) { videoBytes = File.ReadAllBytes(video.Video.Uri); } else { videoBytes = video.Video.VideoBytes; } var videoContent = new ByteArrayContent(videoBytes); videoContent.Headers.Add("Content-Transfer-Encoding", "binary"); videoContent.Headers.Add("Content-Type", "application/octet-stream"); var progressContent = new ProgressableStreamContent(videoContent, 4096, progress) { UploaderProgress = upProgress }; request = HttpHelper.GetDefaultRequest(HttpMethod.Post, videoUri, _deviceInfo); request.Content = progressContent; var vidExt = Path.GetExtension(video.Video.Uri ?? $"C:\\{13.GenerateRandomString()}.mp4").Replace(".", "").ToLower(); if (vidExt == "mov") { request.Headers.Add("X-Entity-Type", "video/quicktime"); } else { request.Headers.Add("X-Entity-Type", "video/mp4"); } request.Headers.Add("Offset", "0"); request.Headers.Add("X-Instagram-Rupload-Params", videoUploadParams); request.Headers.Add("X-Entity-Name", videoEntityName); request.Headers.Add("X-Entity-Length", videoBytes.Length.ToString()); request.Headers.Add("X_FB_VIDEO_WATERFALL_ID", waterfallId); response = await _httpRequestProcessor.SendAsync(request); json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result.UnExpectedResponse <InstaStoryMedia>(response, json)); } var photoUploadParamsObj = new JObject { { "retry_context", "{\"num_step_auto_retry\":0,\"num_reupload\":0,\"num_step_manual_retry\":0}" }, { "media_type", "2" }, { "upload_id", uploadId }, { "image_compression", "{\"lib_name\":\"moz\",\"lib_version\":\"3.1.m\",\"quality\":\"95\"}" }, }; var photoUploadParams = JsonConvert.SerializeObject(photoUploadParamsObj); request = HttpHelper.GetDefaultRequest(HttpMethod.Get, photoUri, _deviceInfo); request.Headers.Add("X_FB_PHOTO_WATERFALL_ID", waterfallId); request.Headers.Add("X-Instagram-Rupload-Params", photoUploadParams); response = await _httpRequestProcessor.SendAsync(request); json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.OK) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result.UnExpectedResponse <InstaStoryMedia>(response, json)); } upProgress.UploadState = InstaUploadState.UploadingThumbnail; progress?.Invoke(upProgress); byte[] imageBytes; if (video.VideoThumbnail.ImageBytes == null) { imageBytes = File.ReadAllBytes(video.VideoThumbnail.Uri); } else { imageBytes = video.VideoThumbnail.ImageBytes; } var imageContent = new ByteArrayContent(imageBytes); imageContent.Headers.Add("Content-Transfer-Encoding", "binary"); imageContent.Headers.Add("Content-Type", "application/octet-stream"); request = HttpHelper.GetDefaultRequest(HttpMethod.Post, photoUri, _deviceInfo); 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", waterfallId); response = await _httpRequestProcessor.SendAsync(request); json = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { upProgress = progressContent?.UploaderProgress; upProgress.UploadState = InstaUploadState.ThumbnailUploaded; progress?.Invoke(upProgress); return(await ConfigureStoryVideoAsync(progress, upProgress, video, uploadId, caption)); } upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result.UnExpectedResponse <InstaStoryMedia>(response, json)); } catch (Exception exception) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); _logger?.LogException(exception); return(Result.Fail <InstaStoryMedia>(exception.Message)); } }
/// <summary> /// Upload story video (to self story) with progress /// </summary> /// <param name="progress">Progress action</param> /// <param name="video">Video to upload</param> /// <param name="caption">Caption</param> public async Task <IResult <InstaStoryMedia> > UploadStoryVideoAsync(Action <InstaUploaderProgress> progress, InstaVideoUpload video, string caption) { return(await UploadStoryVideoWithUrlAsync(progress, video, caption, null)); }
/// <summary> /// Configure story video /// </summary> /// <param name="video">Video to configure</param> /// <param name="uploadId">Upload id</param> /// <param name="caption">Caption</param> private async Task <IResult <InstaStoryMedia> > ConfigureStoryVideoAsync(Action <InstaUploaderProgress> progress, InstaUploaderProgress upProgress, InstaVideoUpload video, string uploadId, string caption) { try { upProgress.UploadState = InstaUploadState.Configuring; progress?.Invoke(upProgress); var instaUri = UriCreator.GetVideoStoryConfigureUri(false); Random rnd = new Random(); var data = new JObject { { "filter_type", "0" }, { "timezone_offset", "16200" }, { "_csrftoken", _user.CsrfToken }, { "client_shared_at", (long.Parse(ApiRequestMessage.GenerateUploadId()) - rnd.Next(25, 55)).ToString() }, { "story_media_creation_date", (long.Parse(ApiRequestMessage.GenerateUploadId()) - rnd.Next(50, 70)).ToString() }, { "media_folder", "Camera" }, { "configure_mode", "1" }, { "source_type", "4" }, { "video_result", "" }, { "_uid", _user.LoggedInUser.Pk.ToString() }, { "_uuid", _deviceInfo.DeviceGuid.ToString() }, { "caption", caption }, { "date_time_original", DateTime.Now.ToString("yyyy-dd-MMTh:mm:ss-0fffZ") }, { "capture_type", "normal" }, { "mas_opt_in", "NOT_PROMPTED" }, { "upload_id", uploadId }, { "client_timestamp", ApiRequestMessage.GenerateUploadId() }, { "device", new JObject { { "manufacturer", _deviceInfo.HardwareManufacturer }, { "model", _deviceInfo.DeviceModelIdentifier }, { "android_release", _deviceInfo.AndroidVer.VersionNumber }, { "android_version", _deviceInfo.AndroidVer.APILevel } } }, { "length", 0 }, { "extra", new JObject { { "source_width", 0 }, { "source_height", 0 } } }, { "audio_muted", false }, { "poster_frame_index", 0 }, }; var request = HttpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data); var uploadParamsObj = new JObject { { "num_step_auto_retry", 0 }, { "num_reupload", 0 }, { "num_step_manual_retry", 0 } }; var uploadParams = JsonConvert.SerializeObject(uploadParamsObj); request.Headers.Add("retry_context", uploadParams); var response = await _httpRequestProcessor.SendAsync(request); var json = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { var mediaResponse = JsonConvert.DeserializeObject <InstaStoryMediaResponse>(json); var converter = ConvertersFabric.Instance.GetStoryMediaConverter(mediaResponse); var obj = Result.Success(converter.Convert()); upProgress.UploadState = InstaUploadState.Configured; progress?.Invoke(upProgress); upProgress.UploadState = InstaUploadState.Completed; progress?.Invoke(upProgress); return(obj); } upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result.UnExpectedResponse <InstaStoryMedia>(response, json)); } catch (Exception exception) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); _logger?.LogException(exception); return(Result.Fail <InstaStoryMedia>(exception.Message)); } }
/// <summary> /// Upload story video (to self story) with adding link address /// <para>Note: this function only works with verified account or you have more than 10k followers.</para> /// </summary> /// <param name="progress">Progress action</param> /// <param name="video">Video to upload</param> /// <param name="caption">Caption</param> /// <param name="uri">Uri to add</param> public async Task <IResult <InstaStoryMedia> > UploadStoryVideoWithUrlAsync(InstaVideoUpload video, string caption, Uri uri) { return(await UploadStoryVideoWithUrlAsync(null, video, caption, uri)); }
/// <summary> /// Upload video to Instagram TV with progress /// </summary> /// <param name="progress">Progress action</param> /// <param name="video">Video to upload (aspect ratio is very important for thumbnail and video | range 0.5 - 1.0 | Width = 480, Height = 852)</param> /// <param name="title">Title</param> /// <param name="caption">Caption</param> public async Task <IResult <InstaMedia> > UploadVideoAsync(Action <InstaUploaderProgress> progress, InstaVideoUpload video, string title, string caption) { UserAuthValidator.Validate(_userAuthValidate); return(await _instaApi.HelperProcessor.SendIGTVVideoAsync(progress, video, title, caption)); }
private async void btnVideo_Click(object sender, EventArgs e) { OpenFileDialog op = new OpenFileDialog() { Filter = "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png", Title = "ارسال تصویر شاخص" }; if (op.ShowDialog() == DialogResult.OK) { OpenFileDialog videDialog = new OpenFileDialog() { Title = "ویدیو را انتخاب کنید دوست من ", Filter = "All Videos Files |*.dat; *.wmv; *.3g2; *.3gp; *.3gp2; *.3gpp; *.amv; *.asf; *.avi; *.bin; *.cue; *.divx; *.dv; *.flv; *.gxf; *.iso; *.m1v; *.m2v; *.m2t; *.m2ts; *.m4v; " + " *.mkv; *.mov; *.mp2; *.mp2v; *.mp4; *.mp4v; *.mpa; *.mpe; *.mpeg; *.mpeg1; *.mpeg2; *.mpeg4; *.mpg; *.mpv2; *.mts; *.nsv; *.nuv; *.ogg; *.ogm; *.ogv; *.ogx; *.ps; *.rec; *.rm; *.rmvb; *.tod; *.ts; *.tts; *.vob; *.vro; *.webm", }; if (videDialog.ShowDialog() == DialogResult.OK) { var video = new InstaVideoUpload() { Video = new InstaVideo(videDialog.FileName, 0, 0), VideoThumbnail = new InstaImage(op.FileName, 0, 0) }; video.UserTags.Add(new InstaUserTagUpload() { Username = txtTag.Text }); label1.Visible = false; label2.Visible = false; txtCapthion.Visible = false; txtTag.Visible = false; btnImage.Visible = false; btnVideo.Visible = false; lblLoad.Visible = true; var res = await ApiManage.instaApi.MediaProcessor.UploadVideoAsync(video, 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($"پست ارسال نشد \n {res.Info.Message}"); } } else { MessageBox.Show("فیلمت کو پس "); } } else { MessageBox.Show("تصویر میخوام کو پس "); } }
/// <summary> /// Send video story, direct video, disappearing video /// </summary> /// <param name="isDirectVideo">Direct video</param> /// <param name="isDisappearingVideo">Disappearing video</param> private async Task <Result <bool> > SendVideoAsync(Action <UploaderProgress> progress, bool isDirectVideo, bool isDisappearingVideo, string caption, VisualMediaViewMode viewMode, InstaStoryType storyType, string recipients, string threadId, InstaVideoUpload video, Uri uri = null, StoryUploadOptions uploadOptions = null) { var upProgress = new UploaderProgress { Caption = caption ?? string.Empty, UploadState = InstaUploadState.Preparing }; try { var uploadId = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(); var videoHashCode = video.Video.Url?.GetHashCode() ?? $"C:\\{GenerateRandomString(13)}.mp4".GetHashCode(); var waterfallId = Guid.NewGuid().ToString(); var videoEntityName = $"{uploadId}_0_{videoHashCode}"; var videoUri = UriCreator.GetStoryUploadVideoUri(uploadId, videoHashCode); var retryContext = GetRetryContext(); HttpRequestMessage request; HttpResponseMessage response; string videoUploadParams = null; string json = null; upProgress.UploadId = uploadId; progress?.Invoke(upProgress); var videoUploadParamsObj = new JObject(); if (isDirectVideo) { videoUploadParamsObj = new JObject { { "upload_media_height", "0" }, { "direct_v2", "1" }, { "upload_media_width", "0" }, { "upload_media_duration_ms", "0" }, { "upload_id", uploadId }, { "retry_context", retryContext }, { "media_type", "2" } }; videoUploadParams = JsonConvert.SerializeObject(videoUploadParamsObj); request = new HttpRequestMessage(HttpMethod.Get, videoUri); request.Headers.Add("X_FB_VIDEO_WATERFALL_ID", waterfallId); request.Headers.Add("X-Instagram-Rupload-Params", videoUploadParams); response = await _httpClient.SendRequestAsync(request); json = await response.Content.ReadAsStringAsync(); DebugLogger.LogResponse(response); if (response.StatusCode != HttpStatusCode.Ok) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result <bool> .Fail(json, response.ReasonPhrase)); } } else { videoUploadParamsObj = new JObject { { "_csrftoken", Session.CsrfToken }, { "_uid", Session.LoggedInUser.Pk }, { "_uuid", Device.Uuid.ToString() }, { "media_info", new JObject { { "capture_mode", "normal" }, { "media_type", 2 }, { "caption", caption ?? string.Empty }, { "mentions", new JArray() }, { "hashtags", new JArray() }, { "locations", new JArray() }, { "stickers", new JArray() }, } } }; request = GetSignedRequest(UriCreator.GetStoryMediaInfoUploadUri(), videoUploadParamsObj); response = await _httpClient.SendRequestAsync(request); json = await response.Content.ReadAsStringAsync(); DebugLogger.LogResponse(response); videoUploadParamsObj = new JObject { { "upload_media_height", "0" }, { "upload_media_width", "0" }, { "upload_media_duration_ms", "0" }, { "upload_id", uploadId }, { "retry_context", "{\"num_step_auto_retry\":0,\"num_reupload\":0,\"num_step_manual_retry\":0}" }, { "media_type", "2" } }; if (isDisappearingVideo) { videoUploadParamsObj.Add("for_direct_story", "1"); } else { switch (storyType) { case InstaStoryType.SelfStory: default: videoUploadParamsObj.Add("for_album", "1"); break; case InstaStoryType.Direct: videoUploadParamsObj.Add("for_direct_story", "1"); break; case InstaStoryType.Both: videoUploadParamsObj.Add("for_album", "1"); videoUploadParamsObj.Add("for_direct_story", "1"); break; } } videoUploadParams = JsonConvert.SerializeObject(videoUploadParamsObj); request = new HttpRequestMessage(Windows.Web.Http.HttpMethod.Get, videoUri); request.Headers.Add("X_FB_VIDEO_WATERFALL_ID", waterfallId); request.Headers.Add("X-Instagram-Rupload-Params", videoUploadParams); response = await _httpClient.SendRequestAsync(request); json = await response.Content.ReadAsStringAsync(); DebugLogger.LogResponse(response); if (response.StatusCode != HttpStatusCode.Ok) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result <bool> .Fail(json, response.ReasonPhrase)); } } // video part IBuffer videoUploadBuffer; if (video.Video.UploadBuffer == null) { if (video.Video.Url == null) { throw new NullReferenceException("No upload buffer or file path are provided for video upload."); } var videoFile = await StorageFile.GetFileFromPathAsync(video.Video.Url.AbsolutePath); videoUploadBuffer = await FileIO.ReadBufferAsync(videoFile); } else { videoUploadBuffer = video.Video.UploadBuffer; } var videoContent = new HttpBufferContent(videoUploadBuffer); request = new HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, videoUri) { Content = videoContent }; upProgress.UploadState = InstaUploadState.Uploading; progress?.Invoke(upProgress); var vidExt = Path.GetExtension(video.Video.Url?.AbsolutePath ?? $"C:\\{GenerateRandomString(13)}.mp4") .Replace(".", "").ToLower(); if (vidExt == "mov") { request.Headers.Add("X-Entity-Type", "video/quicktime"); } else { request.Headers.Add("X-Entity-Type", "video/mp4"); } request.Headers.Add("Offset", "0"); request.Headers.Add("X-Instagram-Rupload-Params", videoUploadParams); request.Headers.Add("X-Entity-Name", videoEntityName); request.Headers.Add("X-Entity-Length", videoUploadBuffer.Length.ToString()); request.Headers.Add("X_FB_VIDEO_WATERFALL_ID", waterfallId); response = await _httpClient.SendRequestAsync(request); json = await response.Content.ReadAsStringAsync(); if (response.StatusCode != HttpStatusCode.Ok) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); return(Result <bool> .Fail(json, response.ReasonPhrase)); } upProgress.UploadState = InstaUploadState.Uploaded; progress?.Invoke(upProgress); //upProgress = progressContent?.UploaderProgress; if (!isDirectVideo) { upProgress.UploadState = InstaUploadState.UploadingThumbnail; progress?.Invoke(upProgress); var photoHashCode = video.VideoThumbnail.Url?.GetHashCode() ?? $"C:\\{GenerateRandomString(13)}.jpg".GetHashCode(); var photoEntityName = $"{uploadId}_0_{photoHashCode}"; var photoUri = UriCreator.GetStoryUploadPhotoUri(uploadId, photoHashCode); var photoUploadParamsObj = new JObject { { "retry_context", retryContext }, { "media_type", "2" }, { "upload_id", uploadId }, { "image_compression", "{\"lib_name\":\"moz\",\"lib_version\":\"3.1.m\",\"quality\":\"95\"}" }, }; var photoUploadParams = JsonConvert.SerializeObject(photoUploadParamsObj); IBuffer thumbnailUploadBuffer; if (video.VideoThumbnail.UploadBuffer == null) { if (video.VideoThumbnail.Url == null) { throw new NullReferenceException("No upload buffer or file path are provided for video thumbnail upload."); } var videoFile = await StorageFile.GetFileFromPathAsync(video.VideoThumbnail.Url.AbsolutePath); thumbnailUploadBuffer = await FileIO.ReadBufferAsync(videoFile); } else { thumbnailUploadBuffer = video.VideoThumbnail.UploadBuffer; } var imageContent = new HttpBufferContent(thumbnailUploadBuffer); imageContent.Headers.Add("Content-Transfer-Encoding", "binary"); imageContent.Headers.Add("Content-Type", "application/octet-stream"); request = new HttpRequestMessage(HttpMethod.Post, photoUri); 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", thumbnailUploadBuffer.Length.ToString()); request.Headers.Add("X_FB_PHOTO_WATERFALL_ID", waterfallId); response = await _httpClient.SendRequestAsync(request); json = await response.Content.ReadAsStringAsync(); DebugLogger.LogResponse(response); upProgress.UploadState = InstaUploadState.ThumbnailUploaded; progress?.Invoke(upProgress); } return(await ConfigureVideo(progress, upProgress, uploadId, isDirectVideo, isDisappearingVideo, caption, viewMode, storyType, recipients, threadId, uri, uploadOptions)); } catch (Exception exception) { upProgress.UploadState = InstaUploadState.Error; progress?.Invoke(upProgress); DebugLogger.LogException(exception); return(Result <bool> .Except(exception)); } }
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(); } } } }