public async Task <IActionResult> TopNineResult(string username) { var userId = this.userManager.GetUserId(this.User); TopNineViewModel viewModel = await this.iGService.TopNine(userId, username); return(this.View(viewModel)); }
// TODO Refactor public async Task <TopNineViewModel> TopNine(string userId, string username) { this.instaApi = this.api.GetInstance(userId, username); var user = await this.instaApi.UserProcessor.GetUserInfoByUsernameAsync(username); var allMedia = await this.instaApi.UserProcessor.GetUserMediaAsync(username, PaginationParameters.Empty); var mediaFromThisYear = allMedia.Value .Where(m => m.TakenAt.Year == DateTime.Now.Year) .OrderByDescending(m => m.LikesCount) .ToList(); var likesTotal = mediaFromThisYear.Sum(l => l.LikesCount); var topNine = mediaFromThisYear.Take(9).ToList(); List <Post> posts = new List <Post>(); // InstaMedia Post to Model Post foreach (var post in topNine) { string photoUrl; if (post.Carousel != null) { photoUrl = post.Carousel[0].Images[1].Uri; } else if (post.Videos.Count != 0) { photoUrl = post.Videos[0].Uri; } else { photoUrl = post.Images[1].Uri; } var postModel = new Post { IGUserName = username, InstaMedia = post, PostPhoto = photoUrl, Likes = post.LikesCount, Comments = post.CommentsCount, HashtagSet = await this.FindHashtagSet(post), PostUrl = "https://www.instagram.com/p/" + post.Code, }; if (!this.postRepository.All().Any(p => p.PostUrl == postModel.PostUrl)) { await this.postRepository.AddAsync(postModel); await this.postRepository.SaveChangesAsync(); } posts.Add(postModel); } double likesAvrg; if (likesTotal != 0 && mediaFromThisYear.Count != 0) { likesAvrg = mediaFromThisYear.Average(x => x.LikesCount); } else { likesAvrg = 0; } var viewModel = new TopNineViewModel { IsPrivate = user.Value.IsPrivate, ProfilePicUrl = user.Value.ProfilePicUrl, IGFullName = user.Value.FullName, AllPosts = user.Value.MediaCount, Followers = user.Value.FollowerCount, Following = user.Value.FollowingCount, Caption = user.Value.Biography, IGUserName = user.Value.Username, LikesTotal = likesTotal, ThisYearsPostsCount = mediaFromThisYear.Count, LikesAvrg = likesAvrg, Posts = posts, }; return(viewModel); }