Example #1
0
        public async Task <IResult <InstaFeed> > GetTagFeedAsync(string tag, int maxPages = 0)
        {
            ValidateUser();
            ValidateLoggedIn();
            var userFeedUri = UriCreator.GetTagFeedUri(tag);
            var request     = HttpHelper.GetDefaultRequest(HttpMethod.Get, userFeedUri, _deviceInfo);
            var response    = await _httpClient.SendAsync(request);

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

            if (response.StatusCode == HttpStatusCode.OK)
            {
                var feedResponse = JsonConvert.DeserializeObject <InstaMediaListResponse>(json,
                                                                                          new InstaMediaListDataConverter());
                var converter = ConvertersFabric.GetMediaListConverter(feedResponse);
                var tagFeed   = new InstaFeed();
                tagFeed.Medias.AddRange(converter.Convert());
                var nextId = feedResponse.NextMaxId;
                while (feedResponse.MoreAvailable && tagFeed.Pages < maxPages)
                {
                    var nextMedia = await GetTagFeedWithMaxIdAsync(tag, nextId);

                    if (!nextMedia.Succeeded)
                    {
                        Result.Success($"Not all pages was downloaded: {nextMedia.Info.Message}", tagFeed);
                    }
                    nextId    = nextMedia.Value.NextMaxId;
                    converter = ConvertersFabric.GetMediaListConverter(nextMedia.Value);
                    tagFeed.Medias.AddRange(converter.Convert());
                    tagFeed.Pages++;
                }
                return(Result.Success(tagFeed));
            }
            return(Result.Fail(GetBadStatusFromJsonString(json).Message, (InstaFeed)null));
        }
        public ActionResult Edit(InstaFeed insta)
        {
            if (ModelState.IsValid)
            {
                InstaFeed feed = context.InstaFeeds.Find(insta.Id);
                if (insta.ImageFile != null)
                {
                    string imgName = DateTime.Now.ToString("ddMMyyyyHHmmssfff") + insta.ImageFile.FileName;
                    string imgPath = Path.Combine(Server.MapPath("~/Uploads/"), imgName);

                    string oldPath = Path.Combine(Server.MapPath("~/Uploads"), feed.Image);
                    System.IO.File.Delete(oldPath);

                    insta.ImageFile.SaveAs(imgPath);
                    feed.Image = imgName;
                }

                feed.Link = insta.Link;

                context.Entry(feed).State = EntityState.Modified;
                context.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(insta));
        }
        public ActionResult Edit(int Id)
        {
            InstaFeed insta = context.InstaFeeds.Find(Id);

            if (insta == null)
            {
                return(HttpNotFound());
            }
            return(View(insta));
        }
        public ActionResult Delete(int Id)
        {
            InstaFeed insta = context.InstaFeeds.Find(Id);

            if (insta == null)
            {
                return(HttpNotFound());
            }

            context.InstaFeeds.Remove(insta);
            context.SaveChanges();
            return(RedirectToAction("Index"));
        }
        /// <summary>
        ///     Get user timeline feed (feed of recent posts from users you follow) asynchronously.
        /// </summary>
        /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param>
        /// <returns>
        ///     <see cref="InstaFeed" />
        /// </returns>
        public async Task <IResult <InstaFeed> > GetUserTimelineFeedAsync(PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            var feed = new InstaFeed();

            try
            {
                var userFeedUri = UriCreator.GetUserFeedUri(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 <InstaFeed>(response, json));
                }

                var feedResponse = JsonConvert.DeserializeObject <InstaFeedResponse>(json,
                                                                                     new InstaFeedResponseDataConverter());
                feed = ConvertersFabric.Instance.GetFeedConverter(feedResponse).Convert();
                paginationParameters.NextId = feed.NextId;
                paginationParameters.PagesLoaded++;

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

                    if (!nextFeed.Succeeded)
                    {
                        return(Result.Fail(nextFeed.Info, feed));
                    }

                    feed.Medias.AddRange(nextFeed.Value.Medias);
                    feed.Stories.AddRange(nextFeed.Value.Stories);

                    paginationParameters.NextId = nextFeed.Value.NextId;
                    paginationParameters.PagesLoaded++;
                }

                return(Result.Success(feed));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, feed));
            }
        }
Example #6
0
        public async Task <IResult <InstaFeed> > GetExploreFeedAsync(int maxPages = 0)
        {
            ValidateUser();
            ValidateLoggedIn();
            try
            {
                if (maxPages == 0)
                {
                    maxPages = int.MaxValue;
                }
                var exploreUri = UriCreator.GetExploreUri();
                var request    = HttpHelper.GetDefaultRequest(HttpMethod.Get, exploreUri, _deviceInfo);
                var response   = await _httpClient.SendAsync(request);

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

                var exploreFeed = new InstaFeed();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.Fail("", (InstaFeed)null));
                }
                var mediaResponse = JsonConvert.DeserializeObject <InstaMediaListResponse>(json,
                                                                                           new InstaMediaListDataConverter());
                exploreFeed.Medias.AddRange(
                    mediaResponse.Medias.Select(ConvertersFabric.GetSingleMediaConverter)
                    .Select(converter => converter.Convert()));
                exploreFeed.Stories.AddRange(
                    mediaResponse.Stories.Select(ConvertersFabric.GetSingleStoryConverter)
                    .Select(converter => converter.Convert()));
                var pages  = 1;
                var nextId = mediaResponse.NextMaxId;
                while (!string.IsNullOrEmpty(nextId) && pages < maxPages)
                {
                    if (string.IsNullOrEmpty(nextId) || nextId == "0")
                    {
                        break;
                    }
                }
                return(Result.Success(exploreFeed));
            }
            catch (Exception exception)
            {
                return(Result.Fail(exception.Message, (InstaFeed)null));
            }
        }
Example #7
0
        public async Task <IResult <InstaFeed> > GetUserTimelineFeedAsync(int maxPages = 0)
        {
            ValidateUser();
            ValidateLoggedIn();
            var userFeedUri = UriCreator.GetUserFeedUri();
            var request     = HttpHelper.GetDefaultRequest(HttpMethod.Get, userFeedUri, _deviceInfo);
            var response    = await _httpClient.SendAsync(request);

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

            var feed = new InstaFeed();

            if (response.StatusCode != HttpStatusCode.OK)
            {
                return(Result.Fail(GetBadStatusFromJsonString(json).Message, (InstaFeed)null));
            }
            var feedResponse = JsonConvert.DeserializeObject <InstaFeedResponse>(json,
                                                                                 new InstaFeedResponseDataConverter());
            var converter     = ConvertersFabric.GetFeedConverter(feedResponse);
            var feedConverted = converter.Convert();

            feed.Medias.AddRange(feedConverted.Medias);
            var nextId = feedResponse.NextMaxId;

            while (feedResponse.MoreAvailable && feed.Pages < maxPages)
            {
                if (string.IsNullOrEmpty(nextId))
                {
                    break;
                }
                var nextFeed = await GetUserFeedWithMaxIdAsync(nextId);

                if (!nextFeed.Succeeded)
                {
                    Result.Success($"Not all pages was downloaded: {nextFeed.Info.Message}", feed);
                }
                nextId = nextFeed.Value.NextMaxId;
                feed.Medias.AddRange(
                    nextFeed.Value.Items.Select(ConvertersFabric.GetSingleMediaConverter).Select(conv => conv.Convert()));
                feed.Pages++;
            }
            return(Result.Success(feed));
        }
        public ActionResult Create(InstaFeed insta)
        {
            if (ModelState.IsValid)
            {
                if (insta.ImageFile == null)
                {
                    ModelState.AddModelError("", "Image is required");
                    return(View(insta));
                }

                string imgName = DateTime.Now.ToString("ddMMyyyyHHmmssfff") + insta.ImageFile.FileName;
                string imgPath = Path.Combine(Server.MapPath("~/Uploads/"), imgName);

                insta.ImageFile.SaveAs(imgPath);
                insta.Image = imgName;

                context.InstaFeeds.Add(insta);
                context.SaveChanges();
                return(RedirectToAction("Index"));
            }
            return(View(insta));
        }
        /// <summary>
        /// Get the global story feed which contains everyone you follow.
        /// Note that users will eventually drop out of this list even though they
        /// still have stories.So it's always safer to call getUserStoryFeed() if
        /// a specific user's story feed matters to you.
        /// </summary>
        /// <returns></returns>
        public async Task <IResult <InstaFeed> > GetReelsTrayFeed()
        {
            var feed = new InstaFeed();

            try
            {
                var fields = new Dictionary <string, string>
                {
                    { "is_prefetch", "0" },
                    {
                        "supported_capabilities_new",
                        JsonConvert.SerializeObject(InstaApiConstants.SUPPORTED_CAPABILITIES)
                    },
                    { "_csrftoken", _user.CsrfToken },
                    { "_uuid", _httpRequestProcessor.RequestMessage.uuid },
                };

                var request = HttpHelper.GetDefaultRequest(HttpMethod.Post, new Uri("https://i.instagram.com/api/v1/feed/reels_tray/"), _deviceInfo, fields);

                var response = await _httpRequestProcessor.SendAsyncWithoutDelay(request);

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

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

                //var feedResponse = JsonConvert.DeserializeObject<InstaFeedResponse>(json, new InstaFeedResponseDataConverter());
                //feed = ConvertersFabric.Instance.GetFeedConverter(feedResponse).Convert();

                return(Result.Success(feed));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, feed));
            }
        }
Example #10
0
        /// <summary>
        ///     Get user timeline feed (feed of recent posts from users you follow) asynchronously.
        /// </summary>
        /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param>
        /// <param name="seenMediaIds">Id of the posts seen till now</param>
        /// <param name="refreshRequest">Request refresh feeds</param>
        /// <returns>
        ///     <see cref="InstaFeed" />
        /// </returns>
        public async Task <IResult <InstaFeed> > GetUserTimelineFeedAsync(PaginationParameters paginationParameters, string[] seenMediaIds = null, bool refreshRequest = false)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            var feed = new InstaFeed();

            try
            {
                if (paginationParameters == null)
                {
                    paginationParameters = PaginationParameters.MaxPagesToLoad(1);
                }

                InstaFeed Convert(InstaFeedResponse instaFeedResponse)
                {
                    return(ConvertersFabric.Instance.GetFeedConverter(instaFeedResponse).Convert());
                }
                var timelineFeeds = await GetUserTimelineFeed(paginationParameters, seenMediaIds, refreshRequest);

                if (!timelineFeeds.Succeeded)
                {
                    return(Result.Fail(timelineFeeds.Info, feed));
                }

                var feedResponse = timelineFeeds.Value;

                feed = Convert(feedResponse);
                paginationParameters.NextMaxId = feed.NextMaxId;
                paginationParameters.PagesLoaded++;

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

                    if (!nextFeed.Succeeded)
                    {
                        return(Result.Fail(nextFeed.Info, feed));
                    }

                    var convertedFeed = Convert(nextFeed.Value);
                    feed.Medias.AddRange(convertedFeed.Medias);
                    feed.Stories.AddRange(convertedFeed.Stories);
                    feedResponse.MoreAvailable     = nextFeed.Value.MoreAvailable;
                    paginationParameters.NextMaxId = nextFeed.Value.NextMaxId;
                    paginationParameters.PagesLoaded++;
                }

                return(Result.Success(feed));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaFeed), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, feed));
            }
        }
        /// <summary>
        /// Get your "home screen" timeline feed.
        ///
        /// An associative array with following keys (all of them are optional):
        /// "latest_story_pk" The media ID in Instagram's internal format (ie "3482384834_43294");
        ///
        /// "seen_posts" One or more seen media IDs;
        ///
        /// "unseen_posts" One or more unseen media IDs;
        ///
        /// "is_pull_to_refresh" Whether this call was triggered by a refresh;
        ///
        /// "push_disabled" Whether user has disabled PUSH;
        ///
        /// "recovered_from_crash" Whether the app has recovered from a crash/was killed by Android
        /// memory manager/force closed by user/just installed for the first time;
        ///
        /// "feed_view_info" DON'T USE IT YET.
        /// </summary>
        /// <returns></returns>
        public async Task <IResult <InstaFeed> > GetTimelineFeedAsync(Dictionary <string, string> options = null)
        {
            var feed = new InstaFeed();

            try
            {
                var request = HttpHelper.GetDefaultRequest(HttpMethod.Post, new Uri("https://i.instagram.com/api/v1/feed/timeline/"), _deviceInfo);

                request.Headers.Add("X-Ads-Opt-Out", "0");
                request.Headers.Add("X-Google-AD-ID", _httpRequestProcessor.RequestMessage.advertising_id);
                request.Headers.Add("X-DEVICE-ID", _httpRequestProcessor.RequestMessage.uuid);

                var fields = new Dictionary <string, string>
                {
                    { "_csrftoken", _user.CsrfToken },
                    { "_uuid", _httpRequestProcessor.RequestMessage.uuid },
                    { "is_prefetch", "0" },
                    { "phone_id", _httpRequestProcessor.RequestMessage.phone_id },
                    { "device_id", _httpRequestProcessor.RequestMessage.device_id },
                    { "client_session_id", _httpRequestProcessor.RequestMessage.session_id },
                    { "battery_level", "100" },
                    { "is_charging", "1" },
                    { "will_sound_on", "1" },
                    { "is_on_screen", "true" },
                    { "timezone_offset", InstaApiConstants.TIMEZONE_OFFSET.ToString() }, // date('Z')
                    { "is_async_ads", "0" },
                    { "is_async_ads_double_request", "0" },
                    { "is_async_ads_rti", "0" },
                    { "rti_delivery_backend", "" },
                };

                if (options != null && options.ContainsKey("latest_story_pk"))
                {
                    fields.Add("latest_story_pk", options["latest_story_pk"]);
                }

                /*
                 * if ($maxId !== null) {
                 *  $request->addPost('reason', 'pagination');
                 *  $request->addPost('max_id', $maxId);
                 *  $request->addPost('is_pull_to_refresh', '0');
                 *
                 * } elseif (!empty($options['is_pull_to_refresh'])) {
                 *  $request->addPost('reason', 'pull_to_refresh');
                 *  $request->addPost('is_pull_to_refresh', '1');
                 *
                 * } elseif (isset($options['is_pull_to_refresh'])) {
                 *  $request->addPost('reason', 'warm_start_fetch');
                 *  $request->addPost('is_pull_to_refresh', '0');
                 *
                 * } else {
                 *  $request->addPost('reason', 'cold_start_fetch');
                 *  $request->addPost('is_pull_to_refresh', '0');
                 * }
                 */

                //if (options != null && options.ContainsKey("is_pull_to_refresh"))
                //{
                //    if (options["is_pull_to_refresh"] != null)
                //    {
                //        fields.Add("reason", "pull_to_refresh");
                //        fields.Add("is_pull_to_refresh", "1");
                //    }
                //    else
                //    {
                //        fields.Add("reason", "warm_start_fetch");
                //        fields.Add("is_pull_to_refresh", "0");
                //    }
                //}
                //else
                //{
                //    fields.Add("reason", "cold_start_fetch");
                //    fields.Add("is_pull_to_refresh", "0");
                //}

                fields.Add("unseen_posts", "");
                fields.Add("feed_view_info", "");

                if (options != null && options.ContainsKey("recovered_from_crash"))
                {
                    fields.Add("recovered_from_crash", "1");
                }

                request.Content = new FormUrlEncodedContent(fields);

                var response = await _httpRequestProcessor.SendAsyncWithoutDelay(request);

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

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

                var feedResponse = JsonConvert.DeserializeObject <InstaFeedResponse>(json, new InstaFeedResponseDataConverter());
                feed = ConvertersFabric.Instance.GetFeedConverter(feedResponse).Convert();

                return(Result.Success(feed));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, feed));
            }
        }
Example #12
0
        /// <summary>
        ///     Get user timeline feed (feed of recent posts from users you follow) asynchronously.
        /// </summary>
        /// <param name="paginationParameters">Pagination parameters: next id and max amount of pages to load</param>
        /// <param name="seenMediaIds">Id of the posts seen till now</param>
        /// <param name="refreshRequest">Request refresh feeds</param>
        /// <returns>
        ///     <see cref="InstaFeed" />
        /// </returns>
        public async Task <IResult <InstaFeed> > GetUserTimelineFeedAsync(PaginationParameters paginationParameters, string[] seenMediaIds = null, bool refreshRequest = false)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            var feed = new InstaFeed();

            try
            {
                var userFeedUri = UriCreator.GetUserFeedUri(paginationParameters.NextMaxId);

                var data = new Dictionary <string, string>
                {
                    { "is_prefetch", "0" },
                    { "_csrftoken", _user.CsrfToken },
                    { "_uuid", _deviceInfo.DeviceGuid.ToString() },
                    { "device_id", _deviceInfo.PhoneGuid.ToString() },
                    { "phone_id", _deviceInfo.RankToken.ToString() },
                    { "client_session_id", _deviceInfo.AdId.ToString() }
                };

                if (seenMediaIds != null)
                {
                    data.Add("seen_posts", seenMediaIds.EncodeList(false));
                }

                if (refreshRequest)
                {
                    data.Add("reason", "pull_to_refresh");
                    data.Add("is_pull_to_refresh", "1");
                }

                var request = _httpHelper.GetDefaultRequest(HttpMethod.Post, userFeedUri, _deviceInfo, data);
                request.Headers.Add("X-Ads-Opt-Out", "0");
                request.Headers.Add("X-Google-AD-ID", _deviceInfo.GoogleAdId.ToString());
                request.Headers.Add("X-DEVICE-ID", _deviceInfo.DeviceGuid.ToString());

                var response = await _httpRequestProcessor.SendAsync(request);

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

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

                var feedResponse = JsonConvert.DeserializeObject <InstaFeedResponse>(json,
                                                                                     new InstaFeedResponseDataConverter());
                feed = ConvertersFabric.Instance.GetFeedConverter(feedResponse).Convert();
                paginationParameters.NextMaxId = feed.NextMaxId;
                paginationParameters.PagesLoaded++;

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

                    if (!nextFeed.Succeeded)
                    {
                        return(Result.Fail(nextFeed.Info, feed));
                    }

                    feed.Medias.AddRange(nextFeed.Value.Medias);
                    feed.Stories.AddRange(nextFeed.Value.Stories);

                    paginationParameters.NextMaxId = nextFeed.Value.NextMaxId;
                    paginationParameters.PagesLoaded++;
                }

                return(Result.Success(feed));
            }
            catch (HttpRequestException httpException)
            {
                _logger?.LogException(httpException);
                return(Result.Fail(httpException, default(InstaFeed), ResponseType.NetworkProblem));
            }
            catch (Exception exception)
            {
                _logger?.LogException(exception);
                return(Result.Fail(exception, feed));
            }
        }