예제 #1
0
 public void SetLocation(InstaLocationShort locationShort)
 {
     CurrentLocation         = locationShort;
     txtLocationAddress.Text = locationShort.Address;
     txtLocationName.Text    = locationShort.Name;
     LocationGrid.Visibility = Visibility.Visible;
 }
예제 #2
0
        private void RemoveLocationButtonClick(object sender, RoutedEventArgs e)
        {
            CurrentLocation         = null;
            txtLocationAddress.Text = txtLocationName.Text = string.Empty;

            LocationGrid.Visibility = Visibility.Collapsed;
        }
예제 #3
0
 public async Task <IResult <InstaMedia> > EditMediaAsync(
     string mediaId,
     string caption,
     InstaLocationShort location   = null,
     InstaUserTagUpload[] userTags = null)
 {
     return(await this.Instagram.MediaProcessor.EditMediaAsync(
                mediaId,
                caption,
                location,
                userTags));
 }
예제 #4
0
        public static string GetJson(this InstaLocationShort location)
        {
            if (location == null)
            {
                return(null);
            }

            return(new JObject
            {
                { "name", location.Address ?? string.Empty },
                { "address", location.ExternalId ?? string.Empty },
                { "lat", location.Lat },
                { "lng", location.Lng },
                { "external_source", location.ExternalSource ?? "facebook_places" },
                { "facebook_places_id", location.ExternalId },
            }.ToString(Formatting.None));
        }
        private async Task <IResult <InstaMedia> > ConfigureAlbumAsync(Action <InstaUploaderProgress> progress, InstaUploaderProgress upProgress, string[] imagesUploadIds, Dictionary <string, InstaVideo> videos, string caption, InstaLocationShort location)
        {
            try
            {
                upProgress.Name        = "Album upload";
                upProgress.UploadState = InstaUploadState.Configuring;
                progress?.Invoke(upProgress);
                var instaUri        = UriCreator.GetMediaAlbumConfigureUri();
                var clientSidecarId = ApiRequestMessage.GenerateUploadId();
                var childrenArray   = new JArray();
                if (imagesUploadIds != null)
                {
                    foreach (var id in imagesUploadIds)
                    {
                        childrenArray.Add(new JObject
                        {
                            { "timezone_offset", "16200" },
                            { "source_type", 4 },
                            { "upload_id", id },
                            { "caption", "" },
                        });
                    }
                }
                if (videos != null)
                {
                    foreach (var id in videos)
                    {
                        childrenArray.Add(new JObject
                        {
                            { "timezone_offset", "16200" },
                            { "caption", "" },
                            { "upload_id", id.Key },
                            { "date_time_original", DateTime.Now.ToString("yyyy-dd-MMTh:mm:ss-0fffZ") },
                            { "source_type", "4" },
                            {
                                "extra", JsonConvert.SerializeObject(new JObject
                                {
                                    { "source_width", 0 },
                                    { "source_height", 0 }
                                })
                            },
                            {
                                "clips", JsonConvert.SerializeObject(new JArray {
                                    new JObject
                                    {
                                        { "length", id.Value.Length },
                                        { "source_type", "4" },
                                    }
                                })
                            },
                            {
                                "device", JsonConvert.SerializeObject(new JObject {
                                    { "manufacturer", _deviceInfo.HardwareManufacturer },
                                    { "model", _deviceInfo.DeviceModelIdentifier },
                                    { "android_release", _deviceInfo.AndroidVer.VersionNumber },
                                    { "android_version", _deviceInfo.AndroidVer.APILevel }
                                })
                            },
                            { "length", id.Value.Length },
                            { "poster_frame_index", 0 },
                            { "audio_muted", false },
                            { "filter_type", "0" },
                            { "video_result", "deprecated" },
                        });
                    }
                }
                var data = new JObject
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk },
                    { "_csrftoken", _user.CsrfToken },
                    { "caption", caption },
                    { "client_sidecar_id", clientSidecarId },
                    { "upload_id", clientSidecarId },
                    {
                        "device", new JObject
                        {
                            { "manufacturer", _deviceInfo.HardwareManufacturer },
                            { "model", _deviceInfo.DeviceModelIdentifier },
                            { "android_release", _deviceInfo.AndroidVer.VersionNumber },
                            { "android_version", _deviceInfo.AndroidVer.APILevel }
                        }
                    },
                    { "children_metadata", childrenArray },
                };
                if (location != null)
                {
                    data.Add("location", location.GetJson());
                    data.Add("date_time_digitalized", DateTime.Now.ToString("yyyy:dd:MM+h:mm:ss"));
                }
                var request  = _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                var response = await _httpRequestProcessor.SendAsync(request);

                var json = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    upProgress.UploadState = InstaUploadState.Error;
                    progress?.Invoke(upProgress);
                    return(Result.UnExpectedResponse <InstaMedia>(response, json));
                }
                var mediaResponse = JsonConvert.DeserializeObject <InstaMediaAlbumResponse>(json);
                var converter     = ConvertersFabric.Instance.GetSingleMediaFromAlbumConverter(mediaResponse);
                var obj           = converter.Convert();
                if (obj.Caption == null && !string.IsNullOrEmpty(caption))
                {
                    var editedMedia = await _instaApi.MediaProcessor.EditMediaAsync(obj.InstaIdentifier, caption, location);

                    if (editedMedia.Succeeded)
                    {
                        upProgress.UploadState = InstaUploadState.Configured;
                        progress?.Invoke(upProgress);
                        upProgress.UploadState = InstaUploadState.Completed;
                        progress?.Invoke(upProgress);
                        return(Result.Success(editedMedia.Value));
                    }
                }
                upProgress.UploadState = InstaUploadState.Configured;
                progress?.Invoke(upProgress);
                upProgress.UploadState = InstaUploadState.Completed;
                progress?.Invoke(upProgress);
                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                upProgress.UploadState = InstaUploadState.Error;
                progress?.Invoke(upProgress);
                _logger?.LogException(exception);
                return(Result.Fail <InstaMedia>(exception));
            }
        }
        /// <summary>
        ///     Upload album (videos and photos)
        /// </summary>
        /// <param name="progress">Progress action</param>
        /// <param name="images">Array of photos to upload</param>
        /// <param name="videos">Array of videos 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> > UploadAlbumAsync(Action <InstaUploaderProgress> progress, InstaImage[] images, InstaVideoUpload[] videos, string caption, InstaLocationShort location = null)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            var upProgress = new InstaUploaderProgress
            {
                Caption     = caption ?? string.Empty,
                UploadState = InstaUploadState.Preparing
            };

            try
            {
                upProgress.Name = "Album upload";
                progress?.Invoke(upProgress);
                string[] imagesUploadIds = null;
                var      index           = 1;
                if (images != null && images.Any())
                {
                    imagesUploadIds = new string[images.Length];
                    foreach (var image in images)
                    {
                        var instaUri = UriCreator.GetUploadPhotoUri();
                        var uploadId = ApiRequestMessage.GenerateUploadId();
                        upProgress.UploadId    = uploadId;
                        upProgress.Name        = $"[Album] Photo uploading {index}/{images.Length}";
                        upProgress.UploadState = InstaUploadState.Uploading;
                        progress?.Invoke(upProgress);
                        var requestContent = new MultipartFormDataContent(uploadId)
                        {
                            { 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\""
                            },
                            { new StringContent("1"), "\"is_sidecar\"" }
                        };
                        byte[] fileBytes;
                        if (image.ImageBytes == null)
                        {
                            fileBytes = File.ReadAllBytes(image.Uri);
                        }
                        else
                        {
                            fileBytes = image.ImageBytes;
                        }
                        var imageContent = new ByteArrayContent(fileBytes);
                        imageContent.Headers.Add("Content-Transfer-Encoding", "binary");
                        imageContent.Headers.Add("Content-Type", "application/octet-stream");
                        var progressContent = new ProgressableStreamContent(imageContent, 4096, progress)
                        {
                            UploaderProgress = upProgress
                        };
                        requestContent.Add(progressContent, "photo",
                                           $"pending_media_{ApiRequestMessage.GenerateUploadId()}.jpg");

                        var request = _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo);
                        request.Content = requestContent;
                        var response = await _httpRequestProcessor.SendAsync(request);

                        var json = await response.Content.ReadAsStringAsync();

                        if (response.IsSuccessStatusCode)
                        {
                            upProgress             = progressContent?.UploaderProgress;
                            upProgress.UploadState = InstaUploadState.Uploaded;
                            progress?.Invoke(upProgress);
                            imagesUploadIds[index++] = uploadId;
                        }
                        else
                        {
                            upProgress.UploadState = InstaUploadState.Error;
                            progress?.Invoke(upProgress);
                            return(Result.UnExpectedResponse <InstaMedia>(response, json));
                        }
                    }
                }

                var videosDic = new Dictionary <string, InstaVideo>();
                var vidIndex  = 1;
                if (videos != null && videos.Any())
                {
                    foreach (var video in videos)
                    {
                        var instaUri = UriCreator.GetUploadVideoUri();
                        var uploadId = ApiRequestMessage.GenerateUploadId();
                        upProgress.UploadId = uploadId;
                        upProgress.Name     = $"[Album] Video uploading {vidIndex}/{videos.Length}";

                        var requestContent = new MultipartFormDataContent(uploadId)
                        {
                            { new StringContent("0"), "\"upload_media_height\"" },
                            { new StringContent("1"), "\"is_sidecar\"" },
                            { new StringContent("0"), "\"upload_media_width\"" },
                            { new StringContent(_user.CsrfToken), "\"_csrftoken\"" },
                            { new StringContent(_deviceInfo.DeviceGuid.ToString()), "\"_uuid\"" },
                            { new StringContent("0"), "\"upload_media_duration_ms\"" },
                            { new StringContent(uploadId), "\"upload_id\"" },
                            { new StringContent("{\"num_step_auto_retry\":0,\"num_reupload\":0,\"num_step_manual_retry\":0}"), "\"retry_context\"" },
                            { new StringContent("2"), "\"media_type\"" },
                        };

                        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)
                        {
                            upProgress.UploadState = InstaUploadState.Error;
                            progress?.Invoke(upProgress);
                            return(Result.Fail <InstaMedia>("Failed to get response from instagram video upload endpoint"));
                        }

                        byte[] videoBytes;
                        if (video.Video.VideoBytes == null)
                        {
                            videoBytes = File.ReadAllBytes(video.Video.Uri);
                        }
                        else
                        {
                            videoBytes = video.Video.VideoBytes;
                        }
                        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(videoBytes);
                        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.Uri ?? $"C:\\{13.GenerateRandomString()}.mp4")}\"");
                        var progressContent = new ProgressableStreamContent(videoContent, 4096, progress)
                        {
                            UploaderProgress = upProgress
                        };
                        requestContent.Add(progressContent);
                        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();

                        upProgress             = progressContent?.UploaderProgress;
                        upProgress.UploadState = InstaUploadState.UploadingThumbnail;
                        progress?.Invoke(upProgress);
                        instaUri       = UriCreator.GetUploadPhotoUri();
                        requestContent = new MultipartFormDataContent(uploadId)
                        {
                            { new StringContent("1"), "\"is_sidecar\"" },
                            { 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\""
                            },
                            { new StringContent("{\"num_step_auto_retry\":0,\"num_reupload\":0,\"num_step_manual_retry\":0}"), "\"retry_context\"" },
                            { new StringContent("2"), "\"media_type\"" },
                        };
                        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");
                        requestContent.Add(imageContent, "photo", $"cover_photo_{uploadId}.jpg");
                        request         = _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo);
                        request.Content = requestContent;
                        response        = await _httpRequestProcessor.SendAsync(request);

                        json = await response.Content.ReadAsStringAsync();

                        var imgResp = JsonConvert.DeserializeObject <ImageThumbnailResponse>(json);
                        videosDic.Add(uploadId, video.Video);

                        upProgress.UploadState = InstaUploadState.Uploaded;
                        progress?.Invoke(upProgress);
                        vidIndex++;
                    }
                }
                var config = await ConfigureAlbumAsync(progress, upProgress, imagesUploadIds, videosDic, caption, location);

                return(config);
            }
            catch (Exception exception)
            {
                upProgress.UploadState = InstaUploadState.Error;
                progress?.Invoke(upProgress);
                _logger?.LogException(exception);
                return(Result.Fail <InstaMedia>(exception));
            }
        }
 /// <summary>
 ///     Upload album (videos and photos)
 /// </summary>
 /// <param name="images">Array of photos to upload</param>
 /// <param name="videos">Array of videos 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> > UploadAlbumAsync(InstaImage[] images, InstaVideoUpload[] videos, string caption, InstaLocationShort location = null)
 {
     return(await UploadAlbumAsync(null, images, videos, caption, location));
 }
 /// <summary>
 ///     Upload photo with progress
 /// </summary>
 /// <param name="progress">Progress action</param>
 /// <param name="image">Photo 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> > UploadPhotoAsync(Action <InstaUploaderProgress> progress, InstaImage image, string caption, InstaLocationShort location = null)
 {
     UserAuthValidator.Validate(_userAuthValidate);
     return(await _instaApi.HelperProcessor.SendMediaPhotoAsync(progress, image, caption, location));
 }
        private async Task <IResult <InstaMedia> > ExposeVideoAsync(string uploadId, string caption, InstaLocationShort location)
        {
            try
            {
                var instaUri = UriCreator.GetMediaConfigureUri();
                var data     = new JObject
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk },
                    { "_csrftoken", _user.CsrfToken },
                    { "experiment", "ig_android_profile_contextual_feed" },
                    { "id", _user.LoggedInUser.Pk },
                    { "upload_id", uploadId },
                };

                var request = _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                request.Headers.Host = "i.instagram.com";
                var response = await _httpRequestProcessor.SendAsync(request);

                var json = await response.Content.ReadAsStringAsync();

                var jObject = JsonConvert.DeserializeObject <ImageThumbnailResponse>(json);

                if (response.IsSuccessStatusCode)
                {
                    var mediaResponse = JsonConvert.DeserializeObject <InstaMediaItemResponse>(json,
                                                                                               new InstaMediaDataConverter());
                    var converter = ConvertersFabric.Instance.GetSingleMediaConverter(mediaResponse);
                    var obj       = converter.Convert();
                    if (obj.Caption == null && !string.IsNullOrEmpty(caption))
                    {
                        var editedMedia = await _instaApi.MediaProcessor.EditMediaAsync(obj.InstaIdentifier, caption, location);

                        if (editedMedia.Succeeded)
                        {
                            return(Result.Success(editedMedia.Value));
                        }
                    }
                    return(Result.Success(obj));
                }

                return(Result.Fail <InstaMedia>(jObject.Status));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaMedia>(exception));
            }
        }
        private async Task <IResult <InstaMedia> > ConfigureVideoAsync(Action <InstaUploaderProgress> progress, InstaUploaderProgress upProgress, InstaVideo video, string uploadId, string caption, InstaLocationShort location)
        {
            try
            {
                upProgress.UploadState = InstaUploadState.Configuring;
                progress?.Invoke(upProgress);
                var instaUri = UriCreator.GetMediaConfigureUri();
                var data     = new JObject
                {
                    { "caption", caption ?? string.Empty },
                    { "upload_id", uploadId },
                    { "source_type", "3" },
                    { "camera_position", "unknown" },
                    {
                        "extra", new JObject
                        {
                            { "source_width", 0 },
                            { "source_height", 0 }
                        }
                    },
                    {
                        "clips", new JArray {
                            new JObject
                            {
                                { "length", 0 },
                                { "creation_date", DateTime.Now.ToString("yyyy-dd-MMTh:mm:ss-0fff") },
                                { "source_type", "3" },
                                { "camera_position", "back" }
                            }
                        }
                    },
                    { "poster_frame_index", 0 },
                    { "audio_muted", false },
                    { "filter_type", "0" },
                    { "video_result", "" },
                    { "_csrftoken", _user.CsrfToken },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.UserName }
                };
                if (location != null)
                {
                    data.Add("location", location.GetJson());
                    data.Add("date_time_digitalized", DateTime.Now.ToString("yyyy:dd:MM+h:mm:ss"));
                }
                var request = _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                request.Headers.Host = "i.instagram.com";
                var response = await _httpRequestProcessor.SendAsync(request);

                var json = await response.Content.ReadAsStringAsync();

                if (!response.IsSuccessStatusCode)
                {
                    upProgress.UploadState = InstaUploadState.Error;
                    progress?.Invoke(upProgress);
                    return(Result.UnExpectedResponse <InstaMedia>(response, json));
                }
                upProgress.UploadState = InstaUploadState.Configured;
                progress?.Invoke(upProgress);
                var success = await ExposeVideoAsync(uploadId, caption, location);

                if (success.Succeeded)
                {
                    upProgress.UploadState = InstaUploadState.Completed;
                    progress?.Invoke(upProgress);
                    return(success);
                }

                upProgress.UploadState = InstaUploadState.Error;
                progress?.Invoke(upProgress);
                return(Result.Fail <InstaMedia>("Cannot expose media"));
            }
            catch (Exception exception)
            {
                upProgress.UploadState = InstaUploadState.Error;
                progress?.Invoke(upProgress);
                _logger?.LogException(exception);
                return(Result.Fail <InstaMedia>(exception));
            }
        }
        /// <summary>
        ///     Upload video with progress
        /// </summary>
        /// <param name="progress">Progress action</param>
        /// <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(Action <InstaUploaderProgress> progress, InstaVideoUpload video, string caption, InstaLocationShort location = null)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            var upProgress = new InstaUploaderProgress
            {
                Caption     = caption ?? string.Empty,
                UploadState = InstaUploadState.Preparing
            };

            try
            {
                var instaUri = UriCreator.GetUploadVideoUri();
                var uploadId = ApiRequestMessage.GenerateUploadId();
                upProgress.UploadId = uploadId;
                progress?.Invoke(upProgress);
                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)
                {
                    upProgress.UploadState = InstaUploadState.Error;
                    progress?.Invoke(upProgress);
                    return(Result.Fail <InstaMedia>("Failed to get response from instagram video upload endpoint"));
                }

                byte[] fileBytes;
                if (video.Video.VideoBytes == null)
                {
                    fileBytes = File.ReadAllBytes(video.Video.Uri);
                }
                else
                {
                    fileBytes = video.Video.VideoBytes;
                }
                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.Uri ?? $"C:\\{13.GenerateRandomString()}.mp4")}\"");
                var progressContent = new ProgressableStreamContent(videoContent, 4096, progress)
                {
                    UploaderProgress = upProgress
                };
                requestContent.Add(progressContent);
                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();

                upProgress = progressContent.UploaderProgress;
                await UploadVideoThumbnailAsync(progress, upProgress, video.VideoThumbnail, uploadId);

                return(await ConfigureVideoAsync(progress, upProgress, video.Video, uploadId, caption, location));
            }
            catch (Exception exception)
            {
                upProgress.UploadState = InstaUploadState.Error;
                progress?.Invoke(upProgress);
                _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));
 }
        /// <summary>
        ///     Edit the caption/location of the media (photo/video/album)
        /// </summary>
        /// <param name="mediaId">The media ID</param>
        /// <param name="caption">The new caption</param>
        /// <param name="location">Location => Optional (get it from <seealso cref="LocationProcessor.SearchLocationAsync"/></param>
        /// <returns>Return true if everything is ok</returns>
        public async Task <IResult <InstaMedia> > EditMediaAsync(string mediaId, string caption, InstaLocationShort location = null)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var editMediaUri = UriCreator.GetEditMediaUri(mediaId);

                var data = new JObject
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk },
                    { "_csrftoken", _user.CsrfToken },
                    { "caption_text", caption ?? string.Empty }
                };
                if (location != null)
                {
                    data.Add("location", location.GetJson());
                }
                var request  = _httpHelper.GetSignedRequest(HttpMethod.Post, editMediaUri, _deviceInfo, data);
                var response = await _httpRequestProcessor.SendAsync(request);

                var json = await response.Content.ReadAsStringAsync();

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var mediaResponse = JsonConvert.DeserializeObject <InstaMediaItemResponse>(json,
                                                                                               new InstaMediaDataConverter());
                    var converter = ConvertersFabric.Instance.GetSingleMediaConverter(mediaResponse);
                    return(Result.Success(converter.Convert()));
                }
                var error = JsonConvert.DeserializeObject <BadStatusResponse>(json);
                return(Result.Fail(error.Message, (InstaMedia)null));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaMedia>(exception));
            }
        }
예제 #14
0
        private async void ImportFiles(IReadOnlyList <StorageFile> files, bool appendFiles = false)
        {
            try
            {
                if (files == null)
                {
                    return;
                }
                if (files.Count > 0)
                {
                    if (!appendFiles)
                    {
                        //UploadUcList.Clear();
                        UploadUcListX.Clear();
                        CurrentLocation         = null;
                        NextButton.IsEnabled    = true;
                        NextButton.Visibility   = Visibility.Visible;
                        UploadButton.Visibility = Visibility.Collapsed;
                    }
                    else
                    {
                        var plusItem = UploadUcListX.FirstOrDefault(x => x.PlusVisibility == Visibility.Visible);
                        if (plusItem != null)
                        {
                            UploadUcListX.Remove(plusItem);
                        }
                    }
                    LoadingUc.Start();
                    foreach (var file in files)
                    {
                        var item = new UploadUcItem
                        {
                            CloseVisibility = Visibility.Visible
                        };
                        var uc = new UploadUc
                        {
                            HorizontalAlignment = HorizontalAlignment.Stretch,
                            VerticalAlignment   = VerticalAlignment.Stretch
                        };
                        uc.SetNewFile(file);
                        item.UploadUc = uc;
                        UploadUcListX.Add(item);
                        //item.SetThumbIfExists();
                        //UploadUcList.Add(uc);
                    }
                    await Task.Delay(500);

                    var tasks = new List <Task>();
                    foreach (var item in UploadUcListX)
                    {
                        try
                        {
                            if (item.Loadings != null && !item.Started)
                            {
                                item.Started = true;
                                item.Loadings.Start();
                                //tasks.Add(item.UploadUc.InitFileAsync());
                            }
                        }
                        catch { }
                    }
                    await Task.Delay(3000);

                    if (UploadUcListX.Count < 9)
                    {
                        var item = new UploadUcItem
                        {
                            VideoVisibility = Visibility.Collapsed,
                            PlusVisibility  = Visibility.Visible
                        };
                        UploadUcListX.Add(item);
                    }
                    if (!appendFiles && UploadUcListX.Count > 0)
                    {
                        CPresenter.Content = UploadUcListX[0].UploadUc;
                    }

                    //await Task.WhenAll(tasks);
                    int ix = 0;
                    foreach (var item in UploadUcListX)
                    {
                        CPresenter.Content = UploadUcListX[ix].UploadUc;

                        if (item.PlusVisibility == Visibility.Collapsed)
                        {
                            await item.UploadUc.InitFile();
                        }
                        item.SetThumbIfExists();
                        ix++;
                    }

                    LoadingUc.Stop();
                }
            }
            catch (Exception ex) { ex.PrintException("ImportFiles(IReadOnlyList<StorageFile>"); }
        }