/// <summary>
        ///     Send profile to direct thrad
        /// </summary>
        /// <param name="userIdToSend">User id to send</param>
        /// <param name="threadIds">Thread ids</param>
        public async Task <IResult <bool> > SendDirectProfileAsync(long userIdToSend, params string[] threadIds)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri      = UriCreator.GetSendDirectProfileUri();
                var clientContext = Guid.NewGuid().ToString();
                var data          = new Dictionary <string, string>
                {
                    { "profile_user_id", userIdToSend.ToString() },
                    { "action", "send_item" },
                    { "thread_ids", $"[{threadIds.EncodeList(false)}]" },
                    { "client_context", clientContext },
                    { "_csrftoken", _user.CsrfToken },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() }
                };
                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 <InstaDefault>(json);
                return(obj.Status.ToLower() == "ok" ? Result.Success(true) : Result.UnExpectedResponse <bool>(response, json));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <bool>(exception));
            }
        }
Beispiel #2
0
        /// <summary>
        ///     Get stories of an hashtag
        /// </summary>
        /// <param name="tagname">Tag name</param>
        public async Task <IResult <InstaHashtagStory> > GetHashtagStoriesAsync(string tagname)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetHashtagStoryUri(tagname);

                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 <InstaHashtagStory>(response, json));
                }

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

                return(Result.Success(ConvertersFabric.Instance.GetHashtagStoryConverter(obj.Story).Convert()));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaHashtagStory), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaHashtagStory>(exception));
            }
        }
Beispiel #3
0
        /// <summary>
        ///     Get media inline comments
        /// </summary>
        /// <param name="mediaId">Media id</param>
        /// <param name="targetCommentId">Target comment id</param>
        /// <param name="paginationParameters">Maximum amount of pages to load and start id</param>
        /// <returns></returns>
        public async Task <IResult <InstaInlineCommentList> > GetMediaRepliesCommentsAsync(string mediaId, string targetCommentId,
                                                                                           PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var commentsUri = UriCreator.GetMediaInlineCommentsUri(mediaId, targetCommentId, 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 <InstaInlineCommentList>(response, json));
                }
                var commentListResponse = JsonConvert.DeserializeObject <InstaInlineCommentListResponse>(json);

                var pagesLoaded = 1;

                InstaInlineCommentList Convert(InstaInlineCommentListResponse commentsResponse)
                {
                    return(ConvertersFabric.Instance.GetInlineCommentsConverter(commentsResponse).Convert());
                }
                while (commentListResponse.HasMoreTailChildComments &&
                       !string.IsNullOrEmpty(commentListResponse.NextMaxId) &&
                       pagesLoaded < paginationParameters.MaximumPagesToLoad ||
                       commentListResponse.HasMoreHeadChildComments &&
                       !string.IsNullOrEmpty(commentListResponse.NextMinId) &&
                       pagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    IResult <InstaInlineCommentListResponse> nextComments;
                    if (!string.IsNullOrEmpty(commentListResponse.NextMaxId))
                    {
                        nextComments = await GetInlineCommentListWithMaxIdAsync(mediaId, targetCommentId, commentListResponse.NextMaxId, null);
                    }
                    else
                    {
                        nextComments = await GetInlineCommentListWithMaxIdAsync(mediaId, targetCommentId, null, commentListResponse.NextMinId);
                    }
                    if (!nextComments.Succeeded)
                    {
                        return(Result.Fail(nextComments.Info, Convert(commentListResponse)));
                    }
                    commentListResponse.NextMaxId = nextComments.Value.NextMaxId;
                    commentListResponse.NextMinId = nextComments.Value.NextMinId;
                    commentListResponse.HasMoreHeadChildComments = nextComments.Value.HasMoreHeadChildComments;
                    commentListResponse.HasMoreTailChildComments = nextComments.Value.HasMoreTailChildComments;
                    commentListResponse.ChildComments.AddRange(nextComments.Value.ChildComments);
                    pagesLoaded++;
                }
                var comments = ConvertersFabric.Instance.GetInlineCommentsConverter(commentListResponse).Convert();
                return(Result.Success(comments));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaInlineCommentList>(exception));
            }
        }
        /// <summary>
        ///     Ignore user friendship requst.
        /// </summary>
        /// <param name="userId">User id (pk)</param>
        public async Task <IResult <InstaFriendshipStatus> > IgnoreFriendshipRequestAsync(long userId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetDenyFriendshipUri(userId);
                //var instaUri = new Uri($"https://i.instagram.com/api/v1/friendships/ignore/{UserID}/", UriKind.RelativeOrAbsolute);
                var fields = new Dictionary <string, string>
                {
                    { "user_id", userId.ToString() },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_csrftoken", _user.CsrfToken },
                };
                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 <InstaFriendshipStatus>(response, json));
                }
                var JRes = JsonConvert.DeserializeObject <InstaFriendshipStatus>(json);
                return(Result.Success(JRes));
            }
            catch (Exception ex)
            {
                return(Result.Fail <InstaFriendshipStatus>(ex.Message));
            }
        }
        /// <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));
            }
        }
        /// <summary>
        ///     Get users (short) who liked certain media. Normaly it return around 1000 last users.
        /// </summary>
        /// <param name="mediaId">Media id</param>
        public async Task <IResult <InstaLikersList> > GetMediaLikersAsync(string mediaId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var likers    = new InstaLikersList();
                var likersUri = UriCreator.GetMediaLikersUri(mediaId);
                var request   = HttpHelper.GetDefaultRequest(HttpMethod.Get, likersUri, _deviceInfo);
                var response  = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaLikersList>(response, json));
                }
                var mediaLikersResponse = JsonConvert.DeserializeObject <InstaMediaLikersResponse>(json);
                likers.UsersCount = mediaLikersResponse.UsersCount;
                if (mediaLikersResponse.UsersCount < 1)
                {
                    return(Result.Success(likers));
                }
                likers.AddRange(
                    mediaLikersResponse.Users.Select(ConvertersFabric.Instance.GetUserShortConverter)
                    .Select(converter => converter.Convert()));
                return(Result.Success(likers));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaLikersList>(exception));
            }
        }
        /// <summary>
        ///     Get share link from media Id
        /// </summary>
        /// <param name="mediaId">media ID</param>
        /// <returns>Share link as Uri</returns>
        public async Task <IResult <Uri> > GetShareLinkFromMediaIdAsync(string mediaId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var collectionUri = UriCreator.GetShareLinkFromMediaId(mediaId);
                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 <Uri>(response, json));
                }

                var data = JsonConvert.DeserializeObject <InstaPermalinkResponse>(json);
                return(Result.Success(new Uri(data.Permalink)));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <Uri>(exception.Message));
            }
        }
Beispiel #8
0
        /// <summary>
        ///     Gets the hashtag information by user tagname.
        /// </summary>
        /// <param name="tagname">Tagname</param>
        /// <returns>Hashtag information</returns>
        public async Task <IResult <InstaHashtag> > GetHashtagInfoAsync(string tagname)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var userUri  = UriCreator.GetTagInfoUri(tagname);
                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 <InstaHashtag>(response, json));
                }

                var tagInfoResponse = JsonConvert.DeserializeObject <InstaHashtagResponse>(json);
                var tagInfo         = ConvertersFabric.Instance.GetHashTagConverter(tagInfoResponse).Convert();

                return(Result.Success(tagInfo));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaHashtag>(exception.Message));
            }
        }
Beispiel #9
0
        /// <summary>
        ///     Create a new collection
        /// </summary>
        /// <param name="collectionName">The name of the new collection</param>
        /// <returns>
        ///     <see cref="T:InstagramApiSharp.Classes.Models.InstaCollectionItem" />
        /// </returns>
        public async Task <IResult <InstaCollectionItem> > CreateCollectionAsync(string collectionName)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var createCollectionUri = UriCreator.GetCreateCollectionUri();

                var data = new JObject
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk },
                    { "_csrftoken", _user.CsrfToken },
                    { "name", collectionName },
                    { "module_name", InstaApiConstants.COLLECTION_CREATE_MODULE }
                };

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

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

                var newCollectionResponse = JsonConvert.DeserializeObject <InstaCollectionItemResponse>(json);
                var converter             = ConvertersFabric.Instance.GetCollectionConverter(newCollectionResponse);

                return(response.StatusCode != HttpStatusCode.OK
                    ? Result.UnExpectedResponse <InstaCollectionItem>(response, json)
                    : Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaCollectionItem>(exception.Message));
            }
        }
Beispiel #10
0
        private async Task <IResult <InstaCollectionItemResponse> > GetSingleCollection(long collectionId,
                                                                                        PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var collectionUri = UriCreator.GetCollectionUri(collectionId, paginationParameters?.NextMaxId);
                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 <InstaCollectionItemResponse>(response, json));
                }

                var collectionsListResponse =
                    JsonConvert.DeserializeObject <InstaCollectionItemResponse>(json,
                                                                                new InstaCollectionDataConverter());
                return(Result.Success(collectionsListResponse));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaCollectionItemResponse), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaCollectionItemResponse>(exception));
            }
        }
Beispiel #11
0
        /// <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 (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <bool>(exception));
            }
        }
Beispiel #12
0
        /// <summary>
        ///     Get your collections
        /// </summary>
        /// <param name="paginationParameters">Pagination parameters: next max id and max amount of pages to load</param>
        /// <returns>
        ///     <see cref="T:InstagramApiSharp.Classes.Models.InstaCollections" />
        /// </returns>
        public async Task <IResult <InstaCollections> > GetCollectionsAsync(PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                if (paginationParameters == null)
                {
                    paginationParameters = PaginationParameters.MaxPagesToLoad(1);
                }

                InstaCollections Convert(InstaCollectionsResponse instaCollectionsResponse)
                {
                    return(ConvertersFabric.Instance.GetCollectionsConverter(instaCollectionsResponse).Convert());
                }

                var collections = await GetCollections(paginationParameters);

                if (!collections.Succeeded)
                {
                    return(Result.Fail(collections.Info, default(InstaCollections)));
                }

                var collectionsResponse = collections.Value;
                paginationParameters.NextMaxId = collectionsResponse.NextMaxId;
                var pagesLoaded = 1;

                while (collectionsResponse.MoreAvailable &&
                       !string.IsNullOrEmpty(collectionsResponse.NextMaxId) &&
                       pagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    var nextCollection = await GetCollections(paginationParameters);

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

                    collectionsResponse.NextMaxId           = paginationParameters.NextMaxId = nextCollection.Value.NextMaxId;
                    collectionsResponse.MoreAvailable       = nextCollection.Value.MoreAvailable;
                    collectionsResponse.AutoLoadMoreEnabled = nextCollection.Value.AutoLoadMoreEnabled;
                    collectionsResponse.Status = nextCollection.Value.Status;
                    collectionsResponse.Items.AddRange(nextCollection.Value.Items);
                    pagesLoaded++;
                }

                var converter = ConvertersFabric.Instance.GetCollectionsConverter(collectionsResponse);

                return(Result.Success(converter.Convert()));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaCollections), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaCollections>(exception));
            }
        }
        /// <summary>
        ///     Get direct inbox thread by its id asynchronously
        /// </summary>
        /// <param name="threadId">Thread id</param>
        /// <returns>
        ///     <see cref="InstaDirectInboxThread" />
        /// </returns>
        public async Task <IResult <InstaDirectInboxThread> > GetDirectInboxThreadAsync(string threadId, string nextOrCursorId = "")
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var directInboxUri = UriCreator.GetDirectInboxThreadUri(threadId, 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 <InstaDirectInboxThread>(response, json));
                }
                var threadResponse = JsonConvert.DeserializeObject <InstaDirectInboxThreadResponse>(json,
                                                                                                    new InstaThreadDataConverter());

                //Reverse for Chat Order
                threadResponse.Items.Reverse();
                //
                var converter = ConvertersFabric.Instance.GetDirectThreadConverter(threadResponse);


                return(Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaDirectInboxThread>(exception.Message));
            }
        }
        /// <summary>
        ///     Leave from group thread
        /// </summary>
        /// <param name="threadId">Thread id</param>
        public async Task <IResult <bool> > LeaveGroupThreadAsync(string threadId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri      = UriCreator.GetLeaveThreadUri(threadId);
                var clientContext = Guid.NewGuid().ToString();
                var data          = new Dictionary <string, string>
                {
                    { "_csrftoken", _user.CsrfToken },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                };
                var request =
                    _httpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, _deviceInfo, data);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                //Debug.WriteLine(json);
                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 (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <bool>(exception));
            }
        }
Beispiel #15
0
        /// <summary>
        ///     Edit the caption of the media (photo/video)
        /// </summary>
        /// <param name="mediaId">The media ID</param>
        /// <param name="caption">The new caption</param>
        /// <returns>Return true if everything is ok</returns>
        public async Task <IResult <bool> > EditMediaAsync(string mediaId, string caption)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var editMediaUri = UriCreator.GetEditMediaUri(mediaId);

                var data = new JObject
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk },
                    { "_csrftoken", _user.CsrfToken },
                    { "caption_text", caption }
                };

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

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

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(Result.Success(true));
                }
                var error = JsonConvert.DeserializeObject <BadStatusResponse>(json);
                return(Result.Fail(error.Message, false));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <bool>(exception));
            }
        }
Beispiel #16
0
        /// <summary>
        ///     Delete your collection for given collection id
        /// </summary>
        /// <param name="collectionId">Collection ID to delete</param>
        /// <returns>true if succeed</returns>
        public async Task <IResult <bool> > DeleteCollectionAsync(long collectionId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var createCollectionUri = UriCreator.GetDeleteCollectionUri(collectionId);

                var data = new JObject
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk },
                    { "_csrftoken", _user.CsrfToken },
                    { "module_name", "collection_editor" }
                };

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

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

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(Result.Success(true));
                }

                var error = JsonConvert.DeserializeObject <BadStatusResponse>(json);
                return(Result.Fail(error.Message, false));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception.Message, false));
            }
        }
Beispiel #17
0
        /// <summary>
        ///     Delete a media (photo, video or album)
        /// </summary>
        /// <param name="mediaId">The media ID</param>
        /// <param name="mediaType">The type of the media</param>
        /// <returns>Return true if the media is deleted</returns>
        public async Task <IResult <bool> > DeleteMediaAsync(string mediaId, InstaMediaType mediaType)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var deleteMediaUri = UriCreator.GetDeleteMediaUri(mediaId, mediaType);

                var data = new JObject
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk },
                    { "_csrftoken", _user.CsrfToken },
                    { "media_id", mediaId }
                };

                var request =
                    HttpHelper.GetSignedRequest(HttpMethod.Get, deleteMediaUri, _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 deletedResponse = JsonConvert.DeserializeObject <DeleteResponse>(json);
                return(Result.Success(deletedResponse.IsDeleted));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <bool>(exception));
            }
        }
Beispiel #18
0
        /// <summary>
        ///     Get your collection for given collection id
        /// </summary>
        /// <param name="collectionId">Collection ID</param>
        /// <returns>
        ///     <see cref="T:InstagramApiSharp.Classes.Models.InstaCollectionItem" />
        /// </returns>
        public async Task <IResult <InstaCollectionItem> > GetCollectionAsync(long collectionId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var collectionUri = UriCreator.GetCollectionUri(collectionId);
                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 <InstaCollectionItem>(response, json));
                }

                var collectionsListResponse =
                    JsonConvert.DeserializeObject <InstaCollectionItemResponse>(json,
                                                                                new InstaCollectionDataConverter());
                var converter = ConvertersFabric.Instance.GetCollectionConverter(collectionsListResponse);
                return(Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaCollectionItem>(exception.Message));
            }
        }
Beispiel #19
0
        /// <summary>
        ///     Get media by its id asynchronously
        /// </summary>
        /// <param name="mediaId">Maximum count of pages to retrieve</param>
        /// <returns>
        ///     <see cref="InstaMedia" />
        /// </returns>
        public async Task <IResult <InstaMedia> > GetMediaByIdAsync(string mediaId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var mediaUri = UriCreator.GetMediaUri(mediaId);
                var request  = HttpHelper.GetDefaultRequest(HttpMethod.Get, mediaUri, _deviceInfo);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.UnExpectedResponse <InstaMedia>(response, json));
                }
                var mediaResponse = JsonConvert.DeserializeObject <InstaMediaListResponse>(json,
                                                                                           new InstaMediaListDataConverter());
                if (mediaResponse.Medias?.Count > 1)
                {
                    var errorMessage = $"Got wrong media count for request with media id={mediaId}";
                    _logger?.LogInfo(errorMessage);
                    return(Result.Fail <InstaMedia>(errorMessage));
                }

                var converter =
                    ConvertersFabric.Instance.GetSingleMediaConverter(mediaResponse.Medias.FirstOrDefault());
                return(Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaMedia>(exception));
            }
        }
        /// <summary>
        ///     Get top (ranked) hashtag media list
        /// </summary>
        /// <param name="tagname">Tag name</param>
        /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param>
        public async Task <IResult <InstaHashtagMedia> > GetTopHashtagMediaListAsync(string tagname,
                                                                                     PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                InstaHashtagMedia Convert(InstaHashtagMediaListResponse hashtagMediaListResponse)
                {
                    return(ConvertersFabric.Instance.GetHashtagMediaListConverter(hashtagMediaListResponse).Convert());
                }
                var mediaResponse = await GetHashtagTopMedia(tagname,
                                                             _user.RankToken ?? Guid.NewGuid().ToString(),
                                                             paginationParameters.NextMaxId);

                if (!mediaResponse.Succeeded)
                {
                    if (mediaResponse.Value != null)
                    {
                        Result.Fail(mediaResponse.Info, Convert(mediaResponse.Value));
                    }
                    else
                    {
                        Result.Fail(mediaResponse.Info, default(InstaHashtagMedia));
                    }
                }

                paginationParameters.NextMaxId = mediaResponse.Value.NextMaxId;
                paginationParameters.PagesLoaded++;
                while (mediaResponse.Value.MoreAvailable &&
                       !string.IsNullOrEmpty(paginationParameters.NextMaxId) &&
                       paginationParameters.PagesLoaded < paginationParameters.MaximumPagesToLoad)
                {
                    var moreMedias = await GetHashtagTopMedia(tagname, _user.RankToken ?? Guid.NewGuid().ToString(),
                                                              paginationParameters.NextMaxId, mediaResponse.Value.NextPage);

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

                    mediaResponse.Value.MoreAvailable       = moreMedias.Value.MoreAvailable;
                    mediaResponse.Value.NextMaxId           = paginationParameters.NextMaxId = moreMedias.Value.NextMaxId;
                    mediaResponse.Value.AutoLoadMoreEnabled = moreMedias.Value.AutoLoadMoreEnabled;
                    mediaResponse.Value.NextMediaIds        = moreMedias.Value.NextMediaIds;
                    mediaResponse.Value.NextPage            = moreMedias.Value.NextPage;
                }

                return(Result.Success(ConvertersFabric.Instance.GetHashtagMediaListConverter(mediaResponse.Value).Convert()));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaHashtagMedia), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaHashtagMedia>(exception));
            }
        }
        /// <summary>
        ///     Get pending friendship requests.
        /// </summary>
        public async Task <IResult <InstaPendingRequest> > GetPendingFriendRequestsAsync()
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var cookies =
                    _httpRequestProcessor.HttpHandler.CookieContainer.GetCookies(_httpRequestProcessor.Client
                                                                                 .BaseAddress);
                var csrftoken = cookies[InstaApiConstants.CSRFTOKEN]?.Value ?? String.Empty;
                _user.CsrfToken = csrftoken;
                //var instaUri = new Uri($"https://i.instagram.com/api/v1/friendships/pending/?rank_mutual=0&rank_token={_user.RankToken}", UriKind.RelativeOrAbsolute);
                var instaUri = UriCreator.GetFriendshipPendingRequestsUri(_user.RankToken);
                var request  = HttpHelper.GetDefaultRequest(HttpMethod.Get, instaUri, _deviceInfo);
                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)
                {
                    var JRes = JsonConvert.DeserializeObject <InstaPendingRequest>(json);
                    return(Result.Success(JRes));
                }
                else
                {
                    return(Result.Fail <InstaPendingRequest>(response.StatusCode.ToString()));
                }
            }
            catch (Exception ex)
            {
                return(Result.Fail <InstaPendingRequest>(ex.Message));
            }
        }
Beispiel #22
0
        /// <summary>
        ///     Unlike media comment
        /// </summary>
        /// <param name="commentId">Comment id</param>
        public async Task <IResult <bool> > UnlikeCommentAsync(string commentId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetUnLikeCommentUri(commentId);
                var fields   = new Dictionary <string, string>
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_csrftoken", _user.CsrfToken }
                };
                var request =
                    _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, fields);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                return(response.StatusCode == HttpStatusCode.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(exception, false));
            }
        }
        /// <summary>
        ///     Get story media viewers
        /// </summary>
        /// <param name="StoryMediaId">Story media id</param>
        /// <param name="paginationParameters">Pagination parameters</param>
        public async Task <IResult <InstaReelStoryMediaViewers> > GetStoryMediaViewers(string StoryMediaId, PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                if (paginationParameters.MaximumPagesToLoad > 1)
                {
                    throw new Exception("Not supported");
                }
                var directInboxUri = new Uri(InstaApiConstants.BASE_INSTAGRAM_API_URL + $"media/{StoryMediaId}/list_reel_media_viewer/?max_id={paginationParameters.NextId}", UriKind.RelativeOrAbsolute);
                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 <InstaReelStoryMediaViewers>(response, json));
                }
                var threadResponse = JsonConvert.DeserializeObject <InstaReelStoryMediaViewers>(json);

                return(Result.Success(threadResponse));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaReelStoryMediaViewers>(exception.Message));
            }
        }
Beispiel #24
0
        /// <summary>
        ///     Get ranked recipients (threads and users) asynchronously
        /// </summary>
        /// <returns>
        ///     <see cref="InstaRecipients" />
        /// </returns>
        public async Task <IResult <InstaRecipients> > GetRankedRecipientsAsync()
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var userUri  = UriCreator.GetRankedRecipientsUri();
                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 <InstaRecipients>(response, json));
                }
                var responseRecipients = JsonConvert.DeserializeObject <InstaRankedRecipientsResponse>(json);
                var converter          = ConvertersFabric.Instance.GetRecipientsConverter(responseRecipients);
                return(Result.Success(converter.Convert()));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaRecipients>(exception.Message));
            }
        }
        /// <summary>
        ///     Get the story by userId
        /// </summary>
        /// <param name="userId">User Id</param>
        public async Task <IResult <InstaStory> > GetUserStoryAsync(long userId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var userStoryUri = UriCreator.GetUserStoryUri(userId);
                var request      = HttpHelper.GetDefaultRequest(HttpMethod.Get, userStoryUri, _deviceInfo);
                var response     = await _httpRequestProcessor.SendAsync(request);

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

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    Result.UnExpectedResponse <InstaStory>(response, json);
                }
                var userStoryResponse = JsonConvert.DeserializeObject <InstaStoryResponse>(json);
                var userStory         = ConvertersFabric.Instance.GetStoryConverter(userStoryResponse).Convert();
                return(Result.Success(userStory));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail <InstaStory>(exception.Message));
            }
        }
Beispiel #26
0
        /// <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(PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                if (paginationParameters.MaximumPagesToLoad > 1)
                {
                    throw new Exception("Not supported");
                }
                var directInboxUri = UriCreator.GetDirectInboxUri(paginationParameters.NextId);
                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));
            }
        }
Beispiel #27
0
        /// <summary>
        ///     Get following hashtags information
        /// </summary>
        /// <param name="userId">User identifier (pk)</param>
        /// <returns>
        ///     List of hashtags
        /// </returns>
        public async Task <IResult <InstaHashtagSearch> > GetFollowingHashtagsInfoAsync(long userId)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            var tags = new InstaHashtagSearch();

            try
            {
                var userUri  = UriCreator.GetFollowingTagsInfoUri(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 <InstaHashtagSearch>(response, json));
                }

                var tagsResponse = JsonConvert.DeserializeObject <InstaHashtagSearchResponse>(json,
                                                                                              new InstaHashtagSuggestedDataConverter());

                tags = ConvertersFabric.Instance.GetHashTagsSearchConverter(tagsResponse).Convert();
                return(Result.Success(tags));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaHashtagSearch), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, tags));
            }
        }
        /// <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));
            }
        }
Beispiel #29
0
        /// <summary>
        ///     Delete media comments(multiple)
        /// </summary>
        /// <param name="mediaId">Media id</param>
        /// <param name="commentIds">Comment id</param>
        public async Task <IResult <bool> > DeleteMultipleCommentsAsync(string mediaId, params string[] commentIds)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            try
            {
                var instaUri = UriCreator.GetDeleteMultipleCommentsUri(mediaId);
                var fields   = new Dictionary <string, string>
                {
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "_uid", _user.LoggedInUser.Pk.ToString() },
                    { "_csrftoken", _user.CsrfToken },
                    { "comment_ids_to_delete", commentIds.EncodeList(false) }
                };
                var request =
                    _httpHelper.GetSignedRequest(HttpMethod.Post, instaUri, _deviceInfo, fields);
                var response = await _httpRequestProcessor.SendAsync(request);

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

                return(response.StatusCode == HttpStatusCode.OK
                    ? Result.Success(true)
                    : Result.UnExpectedResponse <bool>(response, json));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception.Message, false));
            }
        }
        /// <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();

                //Debug.WriteLine(json);
                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));
            }
        }