Esempio n. 1
0
        public async Task <IResult <InstaMediaList> > GetUserTagsAsync(string username, int maxPages = 0)
        {
            ValidateUser();
            ValidateLoggedIn();
            try
            {
                if (maxPages == 0)
                {
                    maxPages = int.MaxValue;
                }
                var user = await GetUserAsync(username);

                if (!user.Succeeded || string.IsNullOrEmpty(user.Value.Pk))
                {
                    return(Result.Fail($"Unable to get user {username}", (InstaMediaList)null));
                }
                var uri      = UriCreator.GetUserTagsUri(user.Value?.Pk, _user.RankToken);
                var request  = HttpHelper.GetDefaultRequest(HttpMethod.Get, uri, _deviceInfo);
                var response = await _httpClient.SendAsync(request);

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

                var userTags = new InstaMediaList();
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    return(Result.Fail("", (InstaMediaList)null));
                }
                var mediaResponse = JsonConvert.DeserializeObject <InstaMediaListResponse>(json,
                                                                                           new InstaMediaListDataConverter());
                var nextId = mediaResponse.NextMaxId;
                userTags.AddRange(
                    mediaResponse.Medias.Select(ConvertersFabric.GetSingleMediaConverter)
                    .Select(converter => converter.Convert()));
                var pages = 1;
                while (!string.IsNullOrEmpty(nextId) && pages < maxPages)
                {
                    uri = UriCreator.GetUserTagsUri(user.Value?.Pk, _user.RankToken, nextId);
                    var nextMedia = await GetUserMediaListWithMaxIdAsync(uri);

                    if (!nextMedia.Succeeded)
                    {
                        Result.Success($"Not all pages was downloaded: {nextMedia.Info.Message}", userTags);
                    }
                    nextId = nextMedia.Value.NextMaxId;
                    userTags.AddRange(
                        mediaResponse.Medias.Select(ConvertersFabric.GetSingleMediaConverter)
                        .Select(converter => converter.Convert()));
                    pages++;
                }
                return(Result.Success(userTags));
            }
            catch (Exception exception)
            {
                return(Result.Fail(exception.Message, (InstaMediaList)null));
            }
        }
        /// <summary>
        ///     Get user tags by username asynchronously
        ///     <remarks>Returns media list containing tags</remarks>
        /// </summary>
        /// <param name="userId">User id (pk)</param>
        /// <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> > GetUserTagsAsync(long userId,
                                                                       PaginationParameters paginationParameters)
        {
            UserAuthValidator.Validate(_userAuthValidate);
            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));
            }
        }
        private async Task <IResult <InstaMediaList> > GetUserShoppableMedia(long userId,
                                                                             PaginationParameters paginationParameters)
        {
            var mediaList = new InstaMediaList();

            try
            {
                var instaUri = UriCreator.GetUserShoppableMediaListUri(userId, 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());

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

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

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

                mediaList.Pages    = paginationParameters.PagesLoaded;
                mediaList.PageSize = mediaResponse.ResultsCount;
                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(exception, mediaList));
            }
        }
Esempio n. 4
0
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     if (e.NavigationMode == NavigationMode.New)
     {
         GetType().RemovePageFromBackStack();
     }
     NavigationMode = e.NavigationMode;
     //if (e.Parameter is InstaMedia media)
     //{
     //    Media = media;
     //}
     //else
     if (e.Parameter is object[] obj)
     {
         if (obj.Length == 2)
         {
             var mediaList = obj[0] as List <InstaMedia>;
             SelectedIndex = (int)obj[1];
             MediaList.Clear();
             if (mediaList?.Count > 0)
             {
                 MediaList.AddRange(mediaList);
                 Media = MediaList[SelectedIndex];
             }
         }
         else if (obj.Length == 3)
         {
             var mediaList = obj[0] as List <InstaMedia>;
             SelectedIndex = (int)obj[1];
             MediaList.Clear();
             User = obj[2] as InstaUserShort;
             if (mediaList?.Count > 0)
             {
                 MediaList.AddRange(mediaList);
                 Media = MediaList[SelectedIndex];
             }
         }
     }
 }
Esempio n. 5
0
        public InstaCollectionItem Convert()
        {
            var instaMediaList = new InstaMediaList();

            if (SourceObject.Media != null)
            {
                instaMediaList.AddRange(SourceObject.Media.Medias
                                        .Select(ConvertersFabric.Instance.GetSingleMediaConverter)
                                        .Select(converter => converter.Convert()));
            }

            return(new InstaCollectionItem
            {
                CollectionId = SourceObject.CollectionId,
                CollectionName = SourceObject.CollectionName,
                HasRelatedMedia = SourceObject.HasRelatedMedia,
                Media = instaMediaList,
                CoverMedia = SourceObject.CoverMedia != null
                    ? ConvertersFabric.Instance.GetCoverMediaConverter(SourceObject.CoverMedia).Convert()
                    : null
            });
        }
Esempio n. 6
0
        public void Collect_By_Profile(string ProfilesList_Path, int count = 100, string Save_Path = "./Data/ByProfile/")
        {
            #region Read Profile File
            int index = 0;
            List <List <string> > Profiles = new StreamReader(ProfilesList_Path).ReadToEnd().Split("\r\n").ToList().Split <string>(Bots.Count);
            #endregion

            var spw = Stopwatch.StartNew();

            List <Task <Task> > TasksList = new List <Task <Task> >();

            for (; index < Bots.Count; index++)
            {
                TasksList.Add(new Task <Task>(new Func <object, Task>(async BotIndexOBJ =>
                {
                    int BotIndex = int.Parse(BotIndexOBJ.ToString());

                    #region Collect Profiles Medias
                    foreach (var profile in Profiles[BotIndex])
                    {
                        //Directory for instaMedias
                        string path = Save_Path + profile + "_" + DateTime.Now.ToFileTimeUtc();
                        Directory.CreateDirectory(path);

                        //Get instaMedias
                        InstaMediaList instaMedias = new InstaMediaList();
                        var FirstRequestResult     = await Bots[BotIndex].GetUserMediaAsync(profile, PaginationParameters.MaxPagesToLoad(1));
                        instaMedias.AddRange(FirstRequestResult.Value);
                        string nextid = FirstRequestResult.Value.NextId;
                        while (instaMedias.Count <= count)
                        {
                            if (nextid != "")
                            {
                                var RequestResult = await Bots[BotIndex].GetUserMediaAsync(profile, PaginationParameters.MaxPagesToLoad(1).StartFromId(nextid));
                                if (RequestResult.Succeeded)
                                {
                                    instaMedias.AddRange(RequestResult.Value);
                                }
                                nextid = RequestResult.Value.NextId;
                            }
                            else
                            {
                                break;
                            }
                        }

                        //Save instaMedias
                        using (StreamWriter sw = new StreamWriter(path + "/" + profile + "_instaMedias.json"))
                        {
                            string jsonstring = JsonConvert.SerializeObject(instaMedias, Formatting.Indented);
                            await sw.WriteAsync(jsonstring);
                        }

                        //Download Images
                        Directory.CreateDirectory(path + "/Image");
                        Directory.CreateDirectory(path + "/Video");
                        Directory.CreateDirectory(path + "/Carousel");

                        using (WebClient client = new WebClient())
                        {
                            foreach (var media in instaMedias)
                            {
                                switch (media.MediaType)
                                {
                                case InstaMediaType.Image:
                                    client.DownloadFile(new Uri(media.Images[0].URI), path + "/Image/" + media.InstaIdentifier + ".jpg");
                                    break;

                                case InstaMediaType.Video:
                                    client.DownloadFile(new Uri(media.Videos[0].Url), path + "/Video/" + media.InstaIdentifier + ".mp4");
                                    break;

                                case InstaMediaType.Carousel:
                                    for (int k = 0; k < media.Carousel.Count; k++)
                                    {
                                        if (media.Carousel[k].Images.Count > 0)
                                        {
                                            client.DownloadFile(new Uri(media.Carousel[k].Images[0].URI), path + "/Carousel/" + media.InstaIdentifier + "_" + k + "_" + ".jpg");
                                        }
                                        if (media.Carousel[k].Videos.Count > 0)
                                        {
                                            client.DownloadFile(new Uri(media.Carousel[k].Videos[0].Url), path + "/Carousel/" + media.InstaIdentifier + "_" + k + "_" + ".mp4");
                                        }
                                    }
                                    break;
                                }
                            }
                        }

                        Console.WriteLine($" Bot {BotIndex.ToString()} completed Profile {profile} with index {Profiles[BotIndex].IndexOf(profile)} from {Profiles[BotIndex].Count}");
                    }
                    #endregion

                    Console.WriteLine($" Tasks for Bot {BotIndex.ToString()} completed after {spw.Elapsed}");
                }), index));
            }

            TasksList.ForEach(t => t.Start());        //Step A Start
            TasksList.ForEach(t => t.Wait());         //Step B Wait
            TasksList.ForEach(t => t.Result.Wait());  //Step C Result

            Console.WriteLine(" Done !");

            spw.Stop();
        }
        private async Task <IResult <InstaMediaList> > GetUserShoppableMedia(long userId,
                                                                             PaginationParameters paginationParameters)
        {
            var mediaList = new InstaMediaList();

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

                InstaMediaList Convert(InstaMediaListResponse mediaListResponse)
                {
                    return(ConvertersFabric.Instance.GetMediaListConverter(mediaListResponse).Convert());
                }

                var mediaResult = await GetShoppableMedia(userId, paginationParameters);

                if (!mediaResult.Succeeded)
                {
                    if (mediaResult.Value != null)
                    {
                        return(Result.Fail(mediaResult.Info, Convert(mediaResult.Value)));
                    }
                    else
                    {
                        return(Result.Fail(mediaResult.Info, mediaList));
                    }
                }
                var mediaResponse = mediaResult.Value;
                mediaList           = ConvertersFabric.Instance.GetMediaListConverter(mediaResponse).Convert();
                mediaList.NextMaxId = paginationParameters.NextMaxId = mediaResponse.NextMaxId;
                paginationParameters.PagesLoaded++;

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

                    if (!nextMedia.Succeeded)
                    {
                        return(Result.Fail(nextMedia.Info, mediaList));
                    }
                    mediaList.NextMaxId = paginationParameters.NextMaxId = nextMedia.Value.NextMaxId;
                    mediaList.AddRange(Convert(nextMedia.Value));
                    mediaResponse.MoreAvailable = nextMedia.Value.MoreAvailable;
                    mediaResponse.ResultsCount += nextMedia.Value.ResultsCount;
                    paginationParameters.PagesLoaded++;
                }

                mediaList.Pages    = paginationParameters.PagesLoaded;
                mediaList.PageSize = mediaResponse.ResultsCount;
                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(exception, mediaList));
            }
        }