public async Task <IResult <InstaStoryFeed> > GetStoryFeedAsync()
        {
            try
            {
                var storyFeedUri = UriCreator.GetStoryFeedUri();
                var request      = HttpHelper.GetDefaultRequest(HttpMethod.Get, storyFeedUri, _deviceInfo);
                var response     = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.Fail("", (InstaStoryFeed)null));
                }
                var storyFeedResponse = JsonConvert.DeserializeObject <InstaStoryFeedResponse>(json);
                var instaStoryFeed    = ConvertersFabric.Instance.GetStoryFeedConverter(storyFeedResponse).Convert();
                return(Result.Success(instaStoryFeed));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaStoryFeed>(exception.Message));
            }
        }
        /// <summary>
        ///     Get direct inbox threads for current user asynchronously
        /// </summary>
        /// <returns>
        ///     <see cref="T:InstagramApiSharp.Classes.Models.InstaDirectInboxContainer" />
        /// </returns>
        public async Task <IResult <InstaDirectInboxContainer> > GetDirectInboxAsync(string nextOrCursorId = "")
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var directInboxUri = UriCreator.GetDirectInboxUri(nextOrCursorId);
                var request        = HttpHelper.GetDefaultRequest(HttpMethod.Get, directInboxUri, _deviceInfo);
                var response       = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaDirectInboxContainer>(response, json));
                }
                var inboxResponse = JsonConvert.DeserializeObject <InstaDirectInboxContainerResponse>(json);
                return(Result.Success(ConvertersFabric.Instance.GetDirectInboxConverter(inboxResponse).Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaDirectInboxContainer>(exception.Message));
            }
        }
Exemple #3
0
        /// <summary>
        ///     Get suggested searches
        /// </summary>
        public async Task <IResult <InstaTVSearch> > GetSuggestedSearchesAsync()
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetIGTVSuggestedSearchesUri();
                var request  = _httpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, _deviceInfo);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaTVSearch>(response, json));
                }
                var obj = JsonConvert.DeserializeObject <InstaTVSearch>(json);
                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaTVSearch>(exception.Message));
            }
        }
        /// <summary>
        ///     Get self account information like joined date or switched to business account date
        /// </summary>
        public async Task <IResult <InstaWebAccountInfo> > GetAccountInfoAsync()
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = WebUriCreator.GetAccountsDataUri();
                var request  = _httpHelper.GetWebRequest(HttpMethod.Get, instaUri, _deviceInfo);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.Fail($"Error! Status code: {response.StatusCode}", default(InstaWebAccountInfo)));
                }

                var json = html.GetJson();
                if (json.IsEmpty())
                {
                    return(Result.Fail($"Json response isn't available.", default(InstaWebAccountInfo)));
                }

                var obj = JsonConvert.DeserializeObject <InstaWebContainerResponse>(json);

                if (obj.Entry?.SettingsPages != null)
                {
                    var first = obj.Entry.SettingsPages.FirstOrDefault();
                    if (first != null)
                    {
                        return(Result.Success(ConvertersFabric.Instance.GetWebAccountInfoConverter(first).Convert()));
                    }
                }
                return(Result.Fail($"Date joined isn't available.", default(InstaWebAccountInfo)));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaWebAccountInfo), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, default(InstaWebAccountInfo)));
            }
        }
        public async Task <IResult <DiscoverRecentSearchsResponse> > GetRecentSearchsAsync()
        {
            try
            {
                var instaUri = new Uri(InstaApiConstants.BASE_INSTAGRAM_API_URL + "fbsearch/recent_searches/");
                Debug.WriteLine(instaUri.ToString());

                var request  = HttpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, _deviceInfo);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                Debug.WriteLine(json);
                var obj = JsonConvert.DeserializeObject <DiscoverRecentSearchsResponse>(json);
                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <DiscoverRecentSearchsResponse>(exception));
            }
        }
        /// <summary>
        /// Get recent searches
        /// </summary>
        /// <returns></returns>
        public async Task <IResult <DiscoverRecentSearchsResponse> > GetRecentSearchsAsync()
        {
            try
            {
                var instaUri = UriCreator.GetRecentSearchUri();
                var request  = HttpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, _deviceInfo);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.Fail("Status code: " + response.StatusCode, (DiscoverRecentSearchsResponse)null));
                }
                var obj = JsonConvert.DeserializeObject <DiscoverRecentSearchsResponse>(json);
                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <DiscoverRecentSearchsResponse>(exception));
            }
        }
Exemple #7
0
        /// <summary>
        ///     Get media comments
        /// </summary>
        /// <param name="mediaId">Media id</param>
        /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param>
        public async Task <IResult <InstaCommentList> > GetMediaCommentsAsync(string mediaId,
                                                                              PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var commentsUri = UriCreator.GetMediaCommentsUri(mediaId, paginationParameters.NextId);
                var request     = _httpHelper.GetDefaultRequest(HttpMethod.Get, commentsUri, _deviceInfo);
                var response    = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaCommentList>(response, json));
                }
                var commentListResponse = JsonConvert.DeserializeObject <InstaCommentListResponse>(json);
                var pagesLoaded         = 1;
                InstaCommentList Convert(InstaCommentListResponse commentsResponse)
                {
                    return(ConvertersFabric.Instance.GetCommentListConverter(commentsResponse).Convert());
                }

                while (commentListResponse.MoreCommentsAvailable &&
                       !string.IsNullOrEmpty(commentListResponse.NextMaxId) &&
                       pagesLoaded < paginationParameters.MaximumPagesToLoad ||

                       commentListResponse.MoreHeadLoadAvailable &&
                       !string.IsNullOrEmpty(commentListResponse.NextMinId) &&
                       pagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    IResult <InstaCommentListResponse> nextComments;
                    if (!string.IsNullOrEmpty(commentListResponse.NextMaxId))
                    {
                        nextComments = await GetCommentListWithMaxIdAsync(mediaId, commentListResponse.NextMaxId, null);
                    }
                    else
                    {
                        nextComments = await GetCommentListWithMaxIdAsync(mediaId, null, commentListResponse.NextMinId);
                    }

                    if (!nextComments.Succeeded)
                    {
                        return(Result.Fail(nextComments.Info, Convert(commentListResponse)));
                    }
                    commentListResponse.NextMaxId             = nextComments.Value.NextMaxId;
                    commentListResponse.NextMinId             = nextComments.Value.NextMinId;
                    commentListResponse.MoreCommentsAvailable = nextComments.Value.MoreCommentsAvailable;
                    commentListResponse.MoreHeadLoadAvailable = nextComments.Value.MoreHeadLoadAvailable;
                    commentListResponse.Comments.AddRange(nextComments.Value.Comments);
                    pagesLoaded++;
                }

                var converter = ConvertersFabric.Instance.GetCommentListConverter(commentListResponse);
                return(Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaCommentList>(exception));
            }
        }
Exemple #8
0
        /// <summary>
        /// NOT COMPLETE
        /// </summary>
        /// <param name="bio"></param>
        /// <returns></returns>
        public async Task <IResult <object> > SetBiographyAsync(string bio)
        {
            try
            {
                //POST /api/v1/accounts/set_biography/ HTTP/1.1

                var instaUri = new Uri(InstaApiConstants.BASE_INSTAGRAM_API_URL + $"accounts/set_biography/");
                Debug.WriteLine(instaUri.ToString());

                var data = new JObject
                {
                    { "_csrftoken", _user.CsrfToken },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "raw_text", bio }
                };
                Debug.WriteLine("-----------------------");
                Debug.WriteLine(JsonConvert.SerializeObject(data));
                Debug.WriteLine("--");

                Debug.WriteLine(JsonConvert.SerializeObject(data, Formatting.Indented));

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

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

                Debug.WriteLine(response.StatusCode);
                // hamash NotFound return mikone:|
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.Fail("Status code: " + response.StatusCode, (BroadcastCommentResponse)null));
                }
                Debug.WriteLine(json);
                var obj = JsonConvert.DeserializeObject <BroadcastCommentResponse>(json);

                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception.Message);
                _logger?.LogException(exception);
                return(Result.Fail <BroadcastCommentResponse>(exception));
            }
        }
Exemple #9
0
        public async Task <IResult <BroadcastLiveHeartBeatViewerCountResponse> > GetHeartBeatAndViewerCountAsync(string broadcastId)
        {
            try
            {
                var instaUri = new Uri(InstaApiConstants.BASE_INSTAGRAM_API_URL + $"live/{broadcastId}/heartbeat_and_get_viewer_count/");
                Debug.WriteLine(instaUri.ToString());

                var uploadId       = ApiRequestMessage.GenerateUploadId();
                var requestContent = new MultipartFormDataContent(uploadId)
                {
                    { new StringContent(_user.CsrfToken), "\"_csrftoken\"" },
                    { new StringContent(_deviceInfo.DeviceGuid.ToString()), "\"_uuid\"" },
                    { new StringContent("offset_to_video_start"), "30" }
                };
                var request = HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo);
                request.Content = requestContent;
                var response = await _httpRequestProcessor.SendAsync(request);

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

                Debug.WriteLine(json);
                var obj = JsonConvert.DeserializeObject <BroadcastLiveHeartBeatViewerCountResponse>(json);
                //{"viewer_count": 0.0, "broadcast_status": "interrupted", "cobroadcaster_ids": [], "offset_to_video_start": 0, "total_unique_viewer_count": 0, "is_top_live_eligible": 0, "status": "ok"}
                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <BroadcastLiveHeartBeatViewerCountResponse>(exception));
            }
        }
        /// <summary>
        ///     Approve direct pending request
        /// </summary>
        /// <param name="threadIds">Thread id</param>
        public async Task <IResult <bool> > ApproveDirectPendingRequestAsync(params string[] threadIds)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var data = new Dictionary <string, string>
                {
                    { "_csrftoken", _user.CsrfToken },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() }
                };
                Uri instaUri;
                if (threadIds.Length == 1)
                {
                    instaUri = UriCreator.GetApprovePendingDirectRequestUri(threadIds.FirstOrDefault());
                }
                else
                {
                    instaUri = UriCreator.GetApprovePendingMultipleDirectRequestUri();
                    data.Add("thread_ids", threadIds.EncodeList(false));
                }
                var request  = _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <bool>(response, json));
                }
                var obj = JsonConvert.DeserializeObject <InstaDefaultResponse>(json);
                if (obj.IsSucceed)
                {
                    return(Result.Success(true));
                }
                return(Result.Fail("Error: " + obj.Message, false));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <bool>(exception.Message));
            }
        }
Exemple #11
0
        /// <summary>
        ///     Get user explore feed (Explore tab info) asynchronously
        /// </summary>
        /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param>
        /// <returns><see cref="InstaExploreFeed" /></returns>
        public async Task <IResult <InstaExploreFeed> > GetExploreFeedAsync(PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            var exploreFeed = new InstaExploreFeed();

            try
            {
                InstaExploreFeed Convert(InstaExploreFeedResponse exploreFeedResponse)
                {
                    return(ConvertersFabric.Instance.GetExploreFeedConverter(exploreFeedResponse).Convert());
                }
                var feeds = await GetExploreFeed(paginationParameters);

                if (!feeds.Succeeded)
                {
                    if (feeds.Value != null)
                    {
                        return(Result.Fail(feeds.Info, Convert(feeds.Value)));
                    }
                    else
                    {
                        return(Result.Fail(feeds.Info, (InstaExploreFeed)null));
                    }
                }
                var feedResponse = feeds.Value;
                paginationParameters.NextMaxId = feedResponse.MaxId;
                paginationParameters.RankToken = feedResponse.RankToken;

                while (feedResponse.MoreAvailable &&
                       !string.IsNullOrEmpty(paginationParameters.NextMaxId) &&
                       paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    var nextFeed = await GetExploreFeed(paginationParameters);

                    if (!nextFeed.Succeeded)
                    {
                        return(Result.Fail(nextFeed.Info, Convert(feeds.Value)));
                    }

                    feedResponse.NextMaxId           = paginationParameters.NextMaxId = nextFeed.Value.MaxId;
                    feedResponse.RankToken           = paginationParameters.RankToken = nextFeed.Value.RankToken;
                    feedResponse.MoreAvailable       = nextFeed.Value.MoreAvailable;
                    feedResponse.AutoLoadMoreEnabled = nextFeed.Value.AutoLoadMoreEnabled;
                    feedResponse.NextMaxId           = nextFeed.Value.NextMaxId;
                    feedResponse.ResultsCount        = nextFeed.Value.ResultsCount;
                    feedResponse.Items.Channel       = nextFeed.Value.Items.Channel;
                    feedResponse.Items.Medias.AddRange(nextFeed.Value.Items.Medias);
                    if (nextFeed.Value.Items.StoryTray == null)
                    {
                        feedResponse.Items.StoryTray = nextFeed.Value.Items.StoryTray;
                    }
                    else
                    {
                        feedResponse.Items.StoryTray.Id         = nextFeed.Value.Items.StoryTray.Id;
                        feedResponse.Items.StoryTray.IsPortrait = nextFeed.Value.Items.StoryTray.IsPortrait;

                        feedResponse.Items.StoryTray.Tray.AddRange(nextFeed.Value.Items.StoryTray.Tray);
                        if (nextFeed.Value.Items.StoryTray.TopLive == null)
                        {
                            feedResponse.Items.StoryTray.TopLive = nextFeed.Value.Items.StoryTray.TopLive;
                        }
                        else
                        {
                            feedResponse.Items.StoryTray.TopLive.RankedPosition = nextFeed.Value.Items.StoryTray.TopLive.RankedPosition;
                            feedResponse.Items.StoryTray.TopLive.BroadcastOwners.AddRange(nextFeed.Value.Items.StoryTray.TopLive.BroadcastOwners);
                        }
                    }

                    paginationParameters.PagesLoaded++;
                }
                exploreFeed = Convert(feedResponse);
                exploreFeed.Medias.Pages    = paginationParameters.PagesLoaded;
                exploreFeed.Medias.PageSize = feedResponse.ResultsCount;
                return(Result.Success(exploreFeed));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaExploreFeed), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, exploreFeed));
            }
        }
        public async Task <IResult <InstaMediaList> > GetUserMediaAsync(long userId,
                                                                        PaginationParameters paginationParameters)
        {
            var mediaList = new InstaMediaList();

            try
            {
                var instaUri = UriCreator.GetUserMediaListUri(userId, paginationParameters.NextId);
                var request  = HttpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, _deviceInfo);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaMediaList>(response, json));
                }
                var mediaResponse = JsonConvert.DeserializeObject <InstaMediaListResponse>(json,
                                                                                           new InstaMediaListDataConverter());

                mediaList        = ConvertersFabric.Instance.GetMediaListConverter(mediaResponse).Convert();
                mediaList.NextId = paginationParameters.NextId = mediaResponse.NextMaxId;
                paginationParameters.PagesLoaded++;

                while (mediaResponse.MoreAvailable &&
                       !string.IsNullOrEmpty(paginationParameters.NextId) &&
                       paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    var nextMedia = await GetUserMediaAsync(userId, paginationParameters);

                    if (!nextMedia.Succeeded)
                    {
                        return(Result.Fail(nextMedia.Info, mediaList));
                    }
                    mediaList.NextId = paginationParameters.NextId = nextMedia.Value.NextId;
                    mediaList.AddRange(nextMedia.Value);
                }

                mediaList.Pages    = paginationParameters.PagesLoaded;
                mediaList.PageSize = mediaResponse.ResultsCount;
                return(Result.Success(mediaList));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, mediaList));
            }
        }
Exemple #13
0
        /// <summary>
        ///     Get statistics of current account
        /// </summary>
        public async Task <IResult <InstaStatistics> > GetStatisticsAsync()
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri        = UriCreator.GetGraphStatisticsUri(InstaApiConstants.ACCEPT_LANGUAGE);
                var queryParamsData = new JObject
                {
                    { "access_token", "" },
                    { "id", _user.LoggedInUser.Pk.ToString() }
                };
                var variables = new JObject
                {
                    { "query_params", queryParamsData },
                    { "timezone", InstaApiConstants.TIMEZONE }
                };
                var data = new Dictionary <string, string>
                {
                    { "access_token", "undefined" },
                    { "fb_api_caller_class", "RelayModern" },
                    { "variables", variables.ToString(Formatting.None) },
                    { "doc_id", "1618080801573402" }
                };
                var request =
                    _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaStatistics>(response, json));
                }
                var obj = JsonConvert.DeserializeObject <InstaStatisticsRootResponse>(json);
                return(Result.Success(ConvertersFabric.Instance.GetStatisticsConverter(obj).Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaStatistics>(exception));
            }
        }
        /// <summary>
        ///     Follow a hashtag
        /// </summary>
        /// <param name="tagname">Tag name</param>
        public async Task <IResult <bool> > FollowHashtagAsync(string tagname)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetFollowHashtagUri(tagname);

                var data = new JObject
                {
                    { "_csrftoken", _user.CsrfToken },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                };
                var request =
                    _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <bool>(response, json));
                }
                var obj = JsonConvert.DeserializeObject <InstaDefault>(json);
                return(obj.Status.ToLower() == "ok" ? Result.Success(true) : Result.UnExpectedResponse <bool>(response, json));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(bool), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <bool>(exception));
            }
        }
        /// <summary>
        ///     Set current account private
        /// </summary>
        public async Task <IResult <InstaUserShort> > SetAccountPrivateAsync()
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetUriSetAccountPrivate();
                var fields   = new Dictionary <string, string>
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_csrftoken", _user.CsrfToken }
                };
                var hash = CryptoHelper.CalculateHash(InstaApiConstants.IG_SIGNATURE_KEY,
                                                      JsonConvert.SerializeObject(fields));
                var payload   = JsonConvert.SerializeObject(fields);
                var signature = $"{hash}.{Uri.EscapeDataString(payload)}";
                var request   = HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo);
                request.Content = new FormUrlEncodedContent(fields);
                request.Properties.Add(InstaApiConstants.HEADER_IG_SIGNATURE, signature);
                request.Properties.Add(InstaApiConstants.HEADER_IG_SIGNATURE_KEY_VERSION,
                                       InstaApiConstants.IG_SIGNATURE_KEY_VERSION);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaUserShort>(response, json));
                }
                var userInfoUpdated =
                    JsonConvert.DeserializeObject <InstaUserShortResponse>(json, new InstaUserShortDataConverter());
                if (userInfoUpdated.Pk < 1)
                {
                    return(Result.Fail <InstaUserShort>("Pk is null or empty"));
                }
                var converter = ConvertersFabric.Instance.GetUserShortConverter(userInfoUpdated);
                return(Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception.Message, (InstaUserShort)null));
            }
        }
        /// <summary>
        /// Edit profile.
        /// </summary>
        /// <param name="url">Url</param>
        /// <param name="phone">Phone number</param>
        /// <param name="name">Name</param>
        /// <param name="biography">Biography</param>
        /// <param name="email">Email</param>
        /// <param name="gender">Gender type</param>
        /// <param name="newUsername">New username (optional)</param>
        /// <returns></returns>
        public async Task <IResult <AccountUserResponse> > EditProfileAsync(string url, string phone, string name, string biography, string email, GenderType gender, string newUsername = null)
        {
            try
            {
                var editRequest = await GetRequestForEditProfileAsync();

                if (!editRequest.Succeeded)
                {
                    return(Result.Fail("Edit request returns badrequest", (AccountUserResponse)null));
                }
                var user = editRequest.Value.User.Username;

                if (string.IsNullOrEmpty(newUsername))
                {
                    newUsername = user;
                }
                var instaUri = UriCreator.GetEditProfileUri();

                var data = new JObject
                {
                    { "external_url", url },
                    { "gender", ((int)gender).ToString() },
                    { "phone_number", phone },
                    { "_csrftoken", _user.CsrfToken },
                    { "username", newUsername },
                    { "first_name", name },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "biography", biography },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "email", email },
                };
                var request = HttpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                request.Headers.Add("Host", "i.instagram.com");
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.Fail("Status code: " + response.StatusCode, (AccountUserResponse)null));
                }
                var obj = JsonConvert.DeserializeObject <AccountUserResponse>(json);

                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <AccountUserResponse>(exception));
            }
        }
Exemple #17
0
        /// <summary>
        ///     Adds items to collection asynchronous.
        /// </summary>
        /// <param name="collectionId">Collection identifier.</param>
        /// <param name="mediaIds">Media id list.</param>
        public async Task <IResult <InstaCollectionItem> > AddItemsToCollectionAsync(long collectionId,
                                                                                     params string[] mediaIds)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                if (mediaIds?.Length < 1)
                {
                    return(Result.Fail <InstaCollectionItem>("Provide at least one media id to add to collection"));
                }
                var editCollectionUri = UriCreator.GetEditCollectionUri(collectionId);

                var data = new JObject
                {
                    { "module_name", InstaApiConstants.FEED_SAVED_ADD_TO_COLLECTION_MODULE },
                    { "added_media_ids", JsonConvert.SerializeObject(mediaIds) },
                    { "radio_type", "wifi-none" },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk },
                    { "_csrftoken", _user.CsrfToken }
                };

                var request =
                    _httpHelper.GetSignedRequest(HttpMethod.Get, editCollectionUri, _deviceInfo, data);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaCollectionItem>(response, json));
                }
                var newCollectionResponse = JsonConvert.DeserializeObject <InstaCollectionItemResponse>(json);
                var converter             = ConvertersFabric.Instance.GetCollectionConverter(newCollectionResponse);
                return(Result.Success(converter.Convert()));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaCollectionItem), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaCollectionItem>(exception));
            }
        }
        /// <summary>
        /// Get heart beat and viewer count.
        /// </summary>
        /// <param name="broadcastId">Broadcast id</param>
        /// <returns></returns>
        public async Task <IResult <BroadcastLiveHeartBeatViewerCountResponse> > GetHeartBeatAndViewerCountAsync(string broadcastId)
        {
            try
            {
                var instaUri       = UriCreator.GetLiveHeartbeatAndViewerCountUri(broadcastId);
                var uploadId       = ApiRequestMessage.GenerateUploadId();
                var requestContent = new MultipartFormDataContent(uploadId)
                {
                    { new StringContent(_user.CsrfToken), "\"_csrftoken\"" },
                    { new StringContent(_deviceInfo.DeviceGuid.ToString()), "\"_uuid\"" },
                    { new StringContent("offset_to_video_start"), "30" }
                };
                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.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.Fail("Status code: " + response.StatusCode, (BroadcastLiveHeartBeatViewerCountResponse)null));
                }
                var obj = JsonConvert.DeserializeObject <BroadcastLiveHeartBeatViewerCountResponse>(json);
                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <BroadcastLiveHeartBeatViewerCountResponse>(exception));
            }
        }
Exemple #19
0
        /// <summary>
        ///     Comment media
        /// </summary>
        /// <param name="mediaId">Media id</param>
        /// <param name="text">Comment text</param>
        public async Task <IResult <InstaComment> > CommentMediaAsync(string mediaId, string text)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri   = UriCreator.GetPostCommetUri(mediaId);
                var breadcrumb = CryptoHelper.GetCommentBreadCrumbEncoded(text);
                var fields     = new Dictionary <string, string>
                {
                    { "user_breadcrumb", breadcrumb },
                    { "idempotence_token", Guid.NewGuid().ToString() },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_csrftoken", _user.CsrfToken },
                    { "comment_text", text },
                    { "containermodule", "comments_feed_timeline" },
                    { "radio_type", "wifi-none" }
                };
                var request =
                    _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, fields);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaComment>(response, json));
                }
                var commentResponse = JsonConvert.DeserializeObject <InstaCommentResponse>(json,
                                                                                           new InstaCommentDataConverter());
                var converter = ConvertersFabric.Instance.GetCommentConverter(commentResponse);
                return(Result.Success(converter.Convert()));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaComment), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaComment>(exception));
            }
        }
Exemple #20
0
        /// <summary>
        ///     Add button to your business account
        /// </summary>
        /// <param name="businessPartner">Desire partner button (Use <see cref="IBusinessProcessor.GetBusinessPartnersButtonsAsync"/> to get business buttons(instagram partner) list!)</param>
        /// <param name="uri">Uri (related to Business partner button)</param>
        public async Task <IResult <InstaBusinessUser> > AddOrChangeBusinessButtonAsync(InstaBusinessPartner businessPartner, Uri uri)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                if (businessPartner == null)
                {
                    return(Result.Fail <InstaBusinessUser>("Business partner cannot be null"));
                }
                if (uri == null)
                {
                    return(Result.Fail <InstaBusinessUser>("Uri related to business partner cannot be null"));
                }

                var validateUri = await ValidateUrlAsync(businessPartner, uri);

                if (!validateUri.Succeeded)
                {
                    return(Result.Fail <InstaBusinessUser>(validateUri.Info.Message));
                }

                var instaUri = UriCreator.GetUpdateBusinessInfoUri();

                var data = new JObject
                {
                    { "ix_url", uri.ToString() },
                    { "ix_app_id", businessPartner.AppId },
                    { "is_call_to_action_enabled", "1" },
                    { "_csrftoken", _user.CsrfToken },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() }
                };

                var request =
                    _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaBusinessUser>(response, json));
                }

                var obj = JsonConvert.DeserializeObject <InstaBusinessUserContainerResponse>(json);

                return(Result.Success(ConvertersFabric.Instance.GetBusinessUserConverter(obj).Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaBusinessUser>(exception));
            }
        }
Exemple #21
0
 private void LogException(Exception exception)
 {
     _logger?.LogException(exception);
 }
Exemple #22
0
        /// <summary>
        ///     Get media ID from an url (got from "share link")
        /// </summary>
        /// <param name="uri">Uri to get media ID</param>
        /// <returns>Media ID</returns>
        public async Task <IResult <string> > GetMediaIdFromUrlAsync(Uri uri)
        {
            try
            {
                var collectionUri = UriCreator.GetMediaIdFromUrlUri(uri);
                var request       = HttpHelper.GetDefaultRequest(HttpMethod.Get, collectionUri, _deviceInfo);
                var response      = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <string>(response, json));
                }

                var data = JsonConvert.DeserializeObject <InstaOembedUrlResponse>(json);
                return(Result.Success(data.MediaId));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <string>(exception));
            }
        }
Exemple #23
0
        private async Task <IResult <bool> > GetResultAsync(Uri instaUri, Dictionary <string, string> data = null, bool signedRequest = false, bool setCsrfToken = false)
        {
            try
            {
                HttpRequestMessage request = null;
                if (data?.Count > 0)
                {
                    request = signedRequest ? _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, data) :
                              _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                }
                else
                {
                    request = _httpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, _deviceInfo);
                }
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (setCsrfToken)
                {
                    _user.SetCsrfTokenIfAvailable(response, _httpRequestProcessor);
                }
                var obj = JsonConvert.DeserializeObject <InstaDefaultResponse>(json);

                return(obj.IsSucceed ? Result.Success(true) : Result.UnExpectedResponse <bool>(response, json));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(bool), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <bool>(exception));
            }
        }
        /// <summary>
        ///     Gets the stories of particular location.
        /// </summary>
        /// <param name="locationId">Location identifier (location pk, external id, facebook id)</param>
        /// <returns>
        ///     Location stories
        /// </returns>
        public async Task <IResult <InstaStory> > GetLocationStoriesAsync(long locationId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var uri      = UriCreator.GetLocationFeedUri(locationId.ToString());
                var request  = _httpHelper.GetDefaultRequest(HttpMethod.Get, uri, _deviceInfo);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaStory>(response, json));
                }

                var feedResponse = JsonConvert.DeserializeObject <InstaLocationFeedResponse>(json);
                var feed         = ConvertersFabric.Instance.GetLocationFeedConverter(feedResponse).Convert();

                return(Result.Success(feed.Story));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaStory), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaStory>(exception));
            }
        }
        /// <summary>
        ///     Get currently logged in user info asynchronously
        /// </summary>
        /// <returns>
        ///     <see cref="InstaCurrentUser" />
        /// </returns>
        public async Task <IResult <InstaCurrentUser> > GetCurrentUserAsync()
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetCurrentUserUri();
                var fields   = new Dictionary <string, string>
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_csrftoken", _user.CsrfToken }
                };
                var request = HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo);
                request.Content = new FormUrlEncodedContent(fields);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaCurrentUser>(response, json));
                }
                var user = JsonConvert.DeserializeObject <InstaCurrentUserResponse>(json,
                                                                                    new InstaCurrentUserDataConverter());
                if (user.Pk < 1)
                {
                    Result.Fail <InstaCurrentUser>("Pk is incorrect");
                }
                var converter     = ConvertersFabric.Instance.GetCurrentUserConverter(user);
                var userConverted = converter.Convert();
                return(Result.Success(userConverted));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaCurrentUser>(exception.Message));
            }
        }
Exemple #26
0
        /// <summary>
        ///     Gets the feed of particular location.
        /// </summary>
        /// <param name="locationId">Location identifier</param>
        /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param>
        /// <returns>
        ///     Location feed
        /// </returns>
        public async Task <IResult <InstaLocationFeed> > GetLocationFeedAsync(long locationId,
                                                                              PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var uri      = _getFeedUriCreator.GetUri(locationId, paginationParameters.NextMaxId);
                var request  = _httpHelper.GetDefaultRequest(HttpMethod.Get, uri, _deviceInfo);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaLocationFeed>(response, json));
                }

                var feedResponse = JsonConvert.DeserializeObject <InstaLocationFeedResponse>(json);
                var feed         = ConvertersFabric.Instance.GetLocationFeedConverter(feedResponse).Convert();
                paginationParameters.PagesLoaded++;
                paginationParameters.NextMaxId = feed.NextMaxId;

                while (feedResponse.MoreAvailable &&
                       !string.IsNullOrEmpty(paginationParameters.NextMaxId) &&
                       paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    var nextFeed = await GetLocationFeedAsync(locationId, paginationParameters);

                    if (!nextFeed.Succeeded)
                    {
                        return(nextFeed);
                    }
                    paginationParameters.StartFromMaxId(nextFeed.Value.NextMaxId);
                    paginationParameters.PagesLoaded++;
                    feed.NextMaxId = nextFeed.Value.NextMaxId;
                    feed.Medias.AddRange(nextFeed.Value.Medias);
                    feed.RankedMedias.AddRange(nextFeed.Value.RankedMedias);
                }

                return(Result.Success(feed));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaLocationFeed), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaLocationFeed>(exception));
            }
        }
Exemple #27
0
        /// <summary>
        /// Add an broadcast to post live.
        /// </summary>
        /// <param name="broadcastId">Broadcast id</param>
        /// <returns></returns>
        public async Task <IResult <InstaBroadcastAddToPostLiveResponse> > AddToPostLiveAsync(string broadcastId)
        {
            try
            {
                var instaUri = UriCreator.GetBroadcastAddToPostLiveUri(broadcastId);
                var data     = new JObject
                {
                    { "_csrftoken", _user.CsrfToken },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk.ToString() }
                };
                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.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaBroadcastAddToPostLiveResponse>(response, json));
                }
                var obj = JsonConvert.DeserializeObject <InstaBroadcastAddToPostLiveResponse>(json);
                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaBroadcastAddToPostLiveResponse>(exception));
            }
        }