Example #1
0
        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));
            }
        }
Example #2
0
        public async Task <IResult <InstaLocationShortList> > Search(double latitude, double longitude, string query)
        {
            try
            {
                var uri = _searchLocationUriCreator.GetUri();

                var fields = new Dictionary <string, string>
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_csrftoken", _user.CsrfToken },
                    { "latitude", latitude.ToString(CultureInfo.InvariantCulture) },
                    { "longitude", longitude.ToString(CultureInfo.InvariantCulture) },
                    { "rank_token", _user.RankToken }
                };

                if (!string.IsNullOrEmpty(query))
                {
                    fields.Add("search_query", query);
                }
                else
                {
                    fields.Add("timestamp", DateTimeHelper.GetUnixTimestampSeconds().ToString());
                }
                if (!Uri.TryCreate(uri, fields.AsQueryString(), out var newuri))
                {
                    return(Result.Fail <InstaLocationShortList>("Unable to create uri for location search"));
                }

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

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaLocationShortList>(response, json));
                }
                var locations = JsonConvert.DeserializeObject <InstaLocationSearchResponse>(json);
                var converter = ConvertersFabric.Instance.GetLocationsSearchConverter(locations);
                return(Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaLocationShortList>(exception));
            }
        }
Example #3
0
        public async Task <IResult <InstaCommentList> > GetMediaCommentsAsync(string mediaId,
                                                                              PaginationParameters paginationParameters)
        {
            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.MoreComentsAvailable &&
                       !string.IsNullOrEmpty(commentListResponse.NextMaxId) &&
                       pagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    var nextComments = await GetCommentListWithMaxIdAsync(mediaId, commentListResponse.NextMaxId);

                    if (!nextComments.Succeeded)
                    {
                        return(Result.Fail(nextComments.Info, Convert(commentListResponse)));
                    }
                    commentListResponse.NextMaxId            = nextComments.Value.NextMaxId;
                    commentListResponse.MoreComentsAvailable = nextComments.Value.MoreComentsAvailable;
                    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));
            }
        }
        // public async Task<IResult<InstaCurrentUser>> GetCurrentUserAsync()
        // {
        //     try
        //     {
        //         var instaUri = UriCreator.GetCurrentUserUri();
        //         var fields = new Dictionary<string, string>
        //         {
        //             {"_uuid", _deviceInfo.DeviceGuid.ToString()},
        //             {"_uid", _user.LoggedInUder.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);
        //     }
        // }

        // public async Task<IResult<InstaUserShortList>> GetUserFollowersAsync(string username,
        //     PaginationParameters paginationParameters, string searchQuery)
        // {
        //     var followers = new InstaUserShortList();
        //     try
        //     {
        //         var user = await GetUserAsync(username);
        //         var userFollowersUri =
        //             UriCreator.GetUserFollowersUri(user.Value.Pk, _user.RankToken, searchQuery,
        //                 paginationParameters.NextId);
        //         var followersResponse = await GetUserListByUriAsync(userFollowersUri);
        //         if (!followersResponse.Succeeded)
        //             return Result.Fail(followersResponse.Info, (InstaUserShortList) null);
        //         followers.AddRange(
        //             followersResponse.Value.Items?.Select(ConvertersFabric.Instance.GetUserShortConverter)
        //                 .Select(converter => converter.Convert()));
        //         followers.NextId = followersResponse.Value.NextMaxId;

        //         var pagesLoaded = 1;
        //         while (!string.IsNullOrEmpty(followersResponse.Value.NextMaxId)
        //                && pagesLoaded < paginationParameters.MaximumPagesToLoad)
        //         {
        //             var nextFollowersUri =
        //                 UriCreator.GetUserFollowersUri(user.Value.Pk, _user.RankToken, searchQuery,
        //                     followersResponse.Value.NextMaxId);
        //             followersResponse = await GetUserListByUriAsync(nextFollowersUri);
        //             if (!followersResponse.Succeeded)
        //                 return Result.Fail(followersResponse.Info, followers);
        //             followers.AddRange(
        //                 followersResponse.Value.Items?.Select(ConvertersFabric.Instance.GetUserShortConverter)
        //                     .Select(converter => converter.Convert()));
        //             pagesLoaded++;
        //             followers.NextId = followersResponse.Value.NextMaxId;
        //         }

        //         return Result.Success(followers);
        //     }
        //     catch (Exception exception)
        //     {
        //         _logger?.LogException(exception);
        //         return Result.Fail(exception, followers);
        //     }
        // }

        // public async Task<IResult<InstaUserShortList>> GetUserFollowingAsync(string username,
        //     PaginationParameters paginationParameters, string searchQuery)
        // {
        //     var following = new InstaUserShortList();
        //     try
        //     {
        //         var user = await GetUserAsync(username);
        //         var uri = UriCreator.GetUserFollowingUri(user.Value.Pk, _user.RankToken, searchQuery,
        //             paginationParameters.NextId);
        //         var userListResponse = await GetUserListByUriAsync(uri);
        //         if (!userListResponse.Succeeded)
        //             return Result.Fail(userListResponse.Info, (InstaUserShortList) null);
        //         following.AddRange(
        //             userListResponse.Value.Items.Select(ConvertersFabric.Instance.GetUserShortConverter)
        //                 .Select(converter => converter.Convert()));
        //         following.NextId = userListResponse.Value.NextMaxId;
        //         var pages = 1;
        //         while (!string.IsNullOrEmpty(following.NextId)
        //                && pages < paginationParameters.MaximumPagesToLoad)
        //         {
        //             var nextUri =
        //                 UriCreator.GetUserFollowingUri(user.Value.Pk, _user.RankToken, searchQuery,
        //                     userListResponse.Value.NextMaxId);
        //             userListResponse = await GetUserListByUriAsync(nextUri);
        //             if (!userListResponse.Succeeded)
        //                 return Result.Fail(userListResponse.Info, following);
        //             following.AddRange(
        //                 userListResponse.Value.Items.Select(ConvertersFabric.Instance.GetUserShortConverter)
        //                     .Select(converter => converter.Convert()));
        //             pages++;
        //             following.NextId = userListResponse.Value.NextMaxId;
        //         }

        //         return Result.Success(following);
        //     }
        //     catch (Exception exception)
        //     {
        //         _logger?.LogException(exception);
        //         return Result.Fail(exception, following);
        //     }
        // }

        // public async Task<IResult<InstaUserShortList>> GetCurrentUserFollowersAsync(
        //     PaginationParameters paginationParameters)
        // {
        //     return await GetUserFollowersAsync(_user.UserName, paginationParameters, string.Empty);
        // }

        // public async Task<IResult<InstaMediaList>> GetUserTagsAsync(long userId,
        //     PaginationParameters paginationParameters)
        // {
        //     var userTags = new InstaMediaList();
        //     try
        //     {
        //         var uri = UriCreator.GetUserTagsUri(userId, _user.RankToken, paginationParameters.NextId);
        //         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.Fail("", (InstaMediaList) null);
        //         var mediaResponse = JsonConvert.DeserializeObject<InstaMediaListResponse>(json,
        //             new InstaMediaListDataConverter());
        //         userTags.AddRange(
        //             mediaResponse.Medias.Select(ConvertersFabric.Instance.GetSingleMediaConverter)
        //                 .Select(converter => converter.Convert()));
        //         userTags.NextId = paginationParameters.NextId = mediaResponse.NextMaxId;
        //         paginationParameters.PagesLoaded++;

        //         while (mediaResponse.MoreAvailable
        //                && !string.IsNullOrEmpty(paginationParameters.NextId)
        //                && paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad)
        //         {
        //             var nextMedia = await GetUserTagsAsync(userId, paginationParameters);
        //             if (!nextMedia.Succeeded)
        //                 return nextMedia;

        //             userTags.AddRange(nextMedia.Value);
        //             userTags.NextId = paginationParameters.NextId = nextMedia.Value.NextId;
        //         }

        //         return Result.Success(userTags);
        //     }
        //     catch (Exception exception)
        //     {
        //         _logger?.LogException(exception);
        //         return Result.Fail(exception, userTags);
        //     }
        // }

        // public async Task<IResult<InstaFriendshipStatus>> FollowUserAsync(long userId)
        // {
        //     return await FollowUnfollowUserInternal(userId, UriCreator.GetFollowUserUri(userId));
        // }

        // public async Task<IResult<InstaFriendshipStatus>> UnFollowUserAsync(long userId)
        // {
        //     return await FollowUnfollowUserInternal(userId, UriCreator.GetUnFollowUserUri(userId));
        // }

        // public async Task<IResult<InstaFriendshipStatus>> BlockUserAsync(long userId)
        // {
        //     return await BlockUnblockUserInternal(userId, UriCreator.GetBlockUserUri(userId));
        // }

        // public async Task<IResult<InstaFriendshipStatus>> UnBlockUserAsync(long userId)
        // {
        //     return await BlockUnblockUserInternal(userId, UriCreator.GetUnBlockUserUri(userId));
        // }

        // public async Task<IResult<InstaFriendshipStatus>> GetFriendshipStatusAsync(long userId)
        // {
        //     try
        //     {
        //         var userUri = UriCreator.GetUserFriendshipUri(userId);
        //         var request = HttpHelper.GetDefaultRequest(HttpMethod.Get, userUri, _deviceInfo);
        //         var response = await _httpRequestProcessor.SendAsync(request);
        //         var json = await response.Content.ReadAsStringAsync();
        //         if (response.StatusCode != HttpStatusCode.OK)
        //             return Result.UnExpectedResponse<InstaFriendshipStatus>(response, json);
        //         var friendshipStatusResponse = JsonConvert.DeserializeObject<InstaFriendshipStatusResponse>(json);
        //         var converter = ConvertersFabric.Instance.GetFriendShipStatusConverter(friendshipStatusResponse);
        //         return Result.Success(converter.Convert());
        //     }
        //     catch (Exception exception)
        //     {
        //         _logger?.LogException(exception);
        //         return Result.Fail<InstaFriendshipStatus>(exception.Message);
        //     }
        // }

        private async Task <IResult <InstaUserInfo> > GetUserInfoAsync(Uri userUri)
        {
            try
            {
                var request  = HttpHelper.GetDefaultRequest(HttpMethod.Get, userUri);
                var response = await _httpRequestProcessor.SendAsync(request);

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

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

                var json      = GetSharedDataJsonFromHtml(html);
                var userInfo  = json.SelectToken("entry_data.ProfilePage[0].graphql").ToObject <InstaUserInfoContainerResponse>();
                var converter = ConvertersFabric.Instance.GetUserInfoConverter(userInfo);
                return(Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaUserInfo>(exception.Message));
            }
        }
Example #5
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.NextId);
                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.NextId = feed.NextMaxId;

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

                    if (!nextFeed.Succeeded)
                    {
                        return(nextFeed);
                    }
                    paginationParameters.StartFromId(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 (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaLocationFeed>(exception));
            }
        }
Example #6
0
        /// <summary>
        ///     Get self account information like joined date or switched to business account date
        /// </summary>
        public async Task <IResult <InstaWebAccountInfo> > GetAccountInfoAsync()
        {
            InstaUserAuthValidator.Validate(userAuthValidate);
            try
            {
                var instaUri = InstaWebUriCreator.GetAccountsDataUri();
                var request  = httpHelper.GetWebRequest(HttpMethod.Get, instaUri, deviceInfo);
                var response = await httpRequestProcessor.SendAsync(request).ConfigureAwait(false);

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

                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(InstaConvertersFabric.Instance.GetWebAccountInfoConverter(first).Convert()));
                    }
                }

                return(Result.Fail("Date joined isn't available.", default(InstaWebAccountInfo)));
            }
            catch (HttpRequestException httpException)
            {
                logger?.LogError(httpException, "Error");
                return(Result.Fail(httpException, default(InstaWebAccountInfo), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                logger?.LogError(exception, "Error");
                return(Result.Fail(exception, default(InstaWebAccountInfo)));
            }
        }
        /// <summary>
        ///     Get user story feed (stories from users followed by current user).
        /// </summary>
        public async Task <IResult <InstaStoryFeed> > GetStoryFeedAsync()
        {
            UserAuthValidator.Validate(_userAuthValidate);
            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));
            }
        }
Example #8
0
        /// <summary>
        ///     Clear Recent searches
        /// </summary>
        public async Task <IResult <bool> > ClearRecentSearchsAsync()
        {
            try
            {
                var instaUri = UriCreator.GetClearSearchHistoryUri();
                var data     = new JObject
                {
                    { "_csrftoken", _user.CsrfToken },
                    { "_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 == "ok" ? Result.Success(true) : Result.UnExpectedResponse <bool>(response, json));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <bool>(exception));
            }
        }
Example #9
0
        private async Task <IResult <InstaRecentActivityResponse> > GetFollowingActivityWithMaxIdAsync(string maxId)
        {
            try
            {
                var uri      = UriCreator.GetFollowingRecentActivityUri(maxId);
                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 <InstaRecentActivityResponse>(response, json));
                }
                var followingActivity = JsonConvert.DeserializeObject <InstaRecentActivityResponse>(json,
                                                                                                    new InstaRecentActivityConverter());
                return(Result.Success(followingActivity));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaRecentActivityResponse), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaRecentActivityResponse>(exception));
            }
        }
Example #10
0
        private async Task <IResult <InstaMediaListResponse> > GetAnyFeeds(Uri instaUri)
        {
            try
            {
                var request  = httpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, deviceInfo);
                var response = await httpRequestProcessor.SendAsync(request).ConfigureAwait(false);

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

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

                var mediaResponse = JsonConvert.DeserializeObject <InstaMediaListResponse>(
                    json,
                    new InstaMediaListDataConverter());

                return(Result.Success(mediaResponse));
            }
            catch (HttpRequestException httpException)
            {
                logger?.LogError(httpException, "Error");
                return(Result.Fail(httpException, default(InstaMediaListResponse), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                logger?.LogError(exception, "Error");
                return(Result.Fail <InstaMediaListResponse>(exception));
            }
        }
Example #11
0
        /// <summary>
        ///     Searches for specific hashtag by search query.
        /// </summary>
        /// <param name="query">Search query</param>
        /// <param name="excludeList">Array of numerical hashtag IDs (ie "17841562498105353") to exclude from the response, allowing you to skip tags from a previous call to get more results</param>
        /// <param name="rankToken">The rank token from the previous page's response</param>
        /// <returns>
        ///     List of hashtags
        /// </returns>
        public async Task <IResult <InstaHashtagSearch> > SearchHashtagAsync(string query, IEnumerable <long> excludeList, string rankToken)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            var RequestHeaderFieldsTooLarge = (HttpStatusCode)431;
            var count = 50;
            var tags  = new InstaHashtagSearch();

            try
            {
                var userUri  = UriCreator.GetSearchTagUri(query, count, excludeList, rankToken);
                var request  = _httpHelper.GetDefaultRequest(HttpMethod.Get, userUri, _deviceInfo);
                var response = await _httpRequestProcessor.SendAsync(request);

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

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

                var tagsResponse = JsonConvert.DeserializeObject <InstaHashtagSearchResponse>(json);
                tags = ConvertersFabric.Instance.GetHashTagsSearchConverter(tagsResponse).Convert();

                if (tags.Any() && excludeList != null && excludeList.Contains(tags.First().Id))
                {
                    tags.RemoveAt(0);
                }

                if (!tags.Any())
                {
                    tags = new InstaHashtagSearch();
                }

                return(Result.Success(tags));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, tags));
            }
        }
Example #12
0
        public async Task <IResult <InstaUserShort> > SetAccountPrivateAsync()
        {
            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));
            }
        }
Example #13
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 (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaCollectionItem>(exception.Message));
            }
        }
Example #14
0
        public async Task <IResult <InstaDirectInboxThread> > GetDirectInboxThreadAsync(string threadId)
        {
            try
            {
                var directInboxUri = UriCreator.GetDirectInboxThreadUri(threadId);
                var request        = HttpHelper.GetDefaultRequest(HttpMethod.Get, directInboxUri, _deviceInfo);
                var response       = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaDirectInboxThread>(response, json));
                }
                var threadResponse = JsonConvert.DeserializeObject <InstaDirectInboxThreadResponse>(json,
                                                                                                    new InstaThreadDataConverter());
                var converter = ConvertersFabric.Instance.GetDirectThreadConverter(threadResponse);
                return(Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaDirectInboxThread>(exception.Message));
            }
        }
        /// <summary>
        ///     Get location(place) information by external id or facebook places id
        ///     <para>
        ///         Get external id from this function:
        ///         <see cref="ILocationProcessor.SearchLocationAsync(double, double, string)" />
        ///     </para>
        ///     <para>
        ///         Get facebook places id from this function:
        ///         <see cref="ILocationProcessor.SearchPlacesAsync(double, double, string)(double, double, string)" />
        ///     </para>
        /// </summary>
        /// <param name="externalIdOrFacebookPlacesId">
        ///     External id or facebook places id of an location/place
        ///     <para>
        ///         Get external id from this function:
        ///         <see cref="ILocationProcessor.SearchLocationAsync(double, double, string)" />
        ///     </para>
        ///     <para>
        ///         Get facebook places id from this function:
        ///         <see cref="ILocationProcessor.SearchPlacesAsync(double, double, string)(double, double, string)" />
        ///     </para>
        /// </param>
        public async Task <IResult <PlaceShort> > GetLocationInfoAsync(string externalIdOrFacebookPlacesId)
        {
            try
            {
                var instaUri = InstaUriCreator.GetLocationInfoUri(externalIdOrFacebookPlacesId);

                var request  = httpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, deviceInfo);
                var response = await httpRequestProcessor.SendAsync(request).ConfigureAwait(false);

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

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

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

                return(Result.Success(InstaConvertersFabric.Instance.GetPlaceShortConverter(obj.Location).Convert()));
            }
            catch (HttpRequestException httpException)
            {
                logger?.LogError(httpException, "Error");
                return(Result.Fail(httpException, default(PlaceShort), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                logger?.LogError(exception, "Error");
                return(Result.Fail <PlaceShort>(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));
            }
        }
Example #17
0
        /// <summary>
        /// Get recent searches
        /// </summary>
        /// <returns></returns>
        public async Task <IResult <InstaDiscoverRecentSearchesResponse> > 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.UnExpectedResponse <InstaDiscoverRecentSearchesResponse>(response, json));
                }
                var obj = JsonConvert.DeserializeObject <InstaDiscoverRecentSearchesResponse>(json);
                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaDiscoverRecentSearchesResponse>(exception));
            }
        }
Example #18
0
        /// <summary>
        ///     Get feed of media your liked.
        /// </summary>
        /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param>
        /// <returns>
        ///     <see cref="InstaMediaList" />
        /// </returns>
        public async Task <IResult <InstaMediaList> > GetLikedFeedAsync(PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetUserLikeFeedUri(paginationParameters.NextMaxId);
                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());

                var mediaList = ConvertersFabric.Instance.GetMediaListConverter(mediaResponse).Convert();
                mediaList.NextMaxId = paginationParameters.NextMaxId = mediaResponse.NextMaxId;
                while (mediaResponse.MoreAvailable &&
                       !string.IsNullOrEmpty(paginationParameters.NextMaxId) &&
                       paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    var result = await GetLikedFeedAsync(paginationParameters);

                    if (!result.Succeeded)
                    {
                        return(Result.Fail(result.Info, mediaList));
                    }

                    paginationParameters.PagesLoaded++;
                    mediaList.NextMaxId = paginationParameters.NextMaxId = result.Value.NextMaxId;
                    mediaList.AddRange(result.Value);
                }

                mediaList.PageSize = mediaResponse.ResultsCount;
                mediaList.Pages    = paginationParameters.PagesLoaded;
                return(Result.Success(mediaList));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaMediaList), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaMediaList>(exception));
            }
        }
Example #19
0
        /// <summary>
        ///     Get TV Guide (gets popular and suggested channels)
        /// </summary>
        public async Task <IResult <InstaTV> > GetTVGuideAsync()
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetIGTVGuideUri();
                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 <InstaTV>(response, json));
                }
                var obj = JsonConvert.DeserializeObject <InstaTV>(json);
                return(Result.Success(obj));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaTV>(exception.Message));
            }
        }
Example #20
0
        /// <summary>
        ///     Follow a hashtag
        /// </summary>
        /// <param name="tagName">Tag name</param>
        public async Task <IResult <bool> > FollowHashtagAsync(string tagName)
        {
            InstaUserAuthValidator.Validate(userAuthValidate);
            try
            {
                var instaUri = InstaUriCreator.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).ConfigureAwait(false);

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

                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?.LogError(httpException, "Error");
                return(Result.Fail(httpException, default(bool), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                logger?.LogError(exception, "Error");
                return(Result.Fail <bool>(exception));
            }
        }
Example #21
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)
        {
            InstaUserAuthValidator.Validate(userAuthValidate);
            try
            {
                if (mediaIds?.Length < 1)
                {
                    return(Result.Fail <InstaCollectionItem>("Provide at least one media id to add to collection"));
                }

                var editCollectionUri = InstaUriCreator.GetEditCollectionUri(collectionId);

                var data = new JObject
                {
                    { "module_name", InstaApiConstants.FeedSavedAddToCollectionModule },
                    { "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).ConfigureAwait(false);

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

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

                var newCollectionResponse = JsonConvert.DeserializeObject <InstaCollectionItemResponse>(json);
                var converter             = InstaConvertersFabric.Instance.GetCollectionConverter(newCollectionResponse);
                return(Result.Success(converter.Convert()));
            }
            catch (HttpRequestException httpException)
            {
                logger?.LogError(httpException, "Error");
                return(Result.Fail(httpException, default(InstaCollectionItem), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                logger?.LogError(exception, "Error");
                return(Result.Fail <InstaCollectionItem>(exception));
            }
        }
        public async Task <IResult <bool> > PostPinAsync(string ImageUrl, string BoardID, string Description, string Link, string Title, string SectionID = "")
        {
            var optionvalues = new Dictionary <string, string>
            {
                { "method", "scraped" },
                { "description", Description },
                { "link", Link },
                { "image_url", ImageUrl },
                { "board_id", BoardID },
                { "title", Title },
            };


            if (SectionID != "/pin-builder/")
            {
                optionvalues.Add("section", SectionID);
            }

            string jsonContet = JsonConvert.SerializeObject(optionvalues, Formatting.Indented);

            var fields = new Dictionary <string, string>
            {
                { "source_url", "" },
                { "data", "{\"options\":" + jsonContet + ",\"context\":{}}" }
            };



            var request = _httpHelper.GetDefaultRequest(HttpMethod.Post, UriCreator.GetPostPinUri(), fields);
            var cookies = _httpRequestProcessor.HttpHandler.CookieContainer.GetCookies(_httpRequestProcessor.Client.BaseAddress);

            _httpHelper.AssginDefaultHeaders(ref request, cookies[PinApiConstants.CSRFTOKEN]?.Value);


            var response = await _httpRequestProcessor.SendAsync(request);

            var json      = JObject.Parse(await response.Content.ReadAsStringAsync());
            var popupJson = json["resource_response"]["data"].ToString();

            return(Result.Success(true));
        }
Example #23
0
        public async Task <IResult <InstaTagFeed> > GetTagFeedAsync(string tag, PaginationParameters paginationParameters)
        {
            var tagFeed = new InstaTagFeed();

            try
            {
                var userFeedUri = UriCreator.GetTagFeedUri(tag, paginationParameters.NextId);
                var request     = HttpHelper.GetDefaultRequest(HttpMethod.Get, userFeedUri, _deviceInfo);
                var response    = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaTagFeed>(response, json));
                }
                var feedResponse = JsonConvert.DeserializeObject <InstaTagFeedResponse>(json,
                                                                                        new InstaTagFeedDataConverter());
                tagFeed = ConvertersFabric.Instance.GetTagFeedConverter(feedResponse).Convert();

                paginationParameters.NextId = feedResponse.NextMaxId;
                paginationParameters.PagesLoaded++;

                while (feedResponse.MoreAvailable &&
                       !string.IsNullOrEmpty(paginationParameters.NextId) &&
                       paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    var nextFeed = await GetTagFeedAsync(tag, paginationParameters);

                    if (!nextFeed.Succeeded)
                    {
                        return(Result.Fail(nextFeed.Info, tagFeed));
                    }
                    tagFeed.NextId = paginationParameters.NextId = nextFeed.Value.NextId;
                    tagFeed.Medias.AddRange(nextFeed.Value.Medias);
                    tagFeed.Stories.AddRange(nextFeed.Value.Stories);
                }

                return(Result.Success(tagFeed));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, tagFeed));
            }
        }
        public async Task <EstacionamientoCercaListResponse> GetTransitoEstacionamientosAsync(MiUbicacionParameters miUbicacion)
        {
            try
            {
                var transitoEstacionamientosUri = UriCreator.GetTransitoEstacionamientosUri(_user, miUbicacion);


                var request  = _httpHelper.GetDefaultRequest(HttpMethod.Get, transitoEstacionamientosUri);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                //if (response.StatusCode != HttpStatusCode.OK)
                //    return Result.UnExpectedResponse<GobiernoCommentList>(response, json);


                var EstacionamientosResponse = JsonConvert.DeserializeObject <EstacionamientoCercaListResponse>(json);

                Expression <Func <int, int, int> > asd = (a, b) => a * b;


                //var converter = ConvertersFabric.Gobiernonce.GetCommentListConverter(commentListResponse);
                //return Result.Success(converter.Convert());

                return(EstacionamientosResponse);
            }
            catch (HttpRequestException httpException)
            {
                throw httpException;
                //    _logger?.LogException(httpException);
                //    return Result.Fail(httpException, default(GobiernoCommentList), ResponseType.NetworkProblem);
                //}
                //catch (Exception exception)
                //{
                //    _logger?.LogException(exception);
                //    return Result.Fail<GobiernoCommentList>(exception);
            }
        }
Example #25
0
        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));
            }
        }
        public async Task <IResult <PinUser> > GetCurrentUserAsync()
        {
            var request = _httpHelper.GetDefaultRequest(HttpMethod.Get, UriCreator.GetUserSettingUri());
            var cookies = _httpRequestProcessor.HttpHandler.CookieContainer.GetCookies(_httpRequestProcessor.Client.BaseAddress);

            _httpHelper.AssginDefaultHeaders(ref request, cookies[PinApiConstants.CSRFTOKEN]?.Value);
            var response = await _httpRequestProcessor.SendAsync(request);

            var json      = JObject.Parse(await response.Content.ReadAsStringAsync());
            var popupJson = json["resource_response"]["data"].ToString();

            PinUser x = JsonConvert.DeserializeObject <PinUser>(popupJson);


            if (x.is_write_banned == true)
            {
                return(Result.Fail <PinUser>(new Exception("User Is Banned")));
            }
            return(Result.Success(JsonConvert.DeserializeObject <PinUser>(popupJson)));
        }
        /// <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));
            }
        }
Example #28
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));
            }
        }
Example #29
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));
            }
        }
Example #30
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));
            }
        }