/// <summary> /// GetTweets /// </summary> /// <returns></returns> public TweetViewModel GetTweets() { TweetViewModel tweetView = new TweetViewModel(); bool IsResponseAvailable = true; //End date string endDate = "2017-12-31T23:59:59.999Z"; //Start date string startDate = "2016-01-01T00:00:00.001Z"; /* * Loop through and get the response of Restapi until we get less then 100 records, assuming there may be less record in the last page or empty * * Filter the response list based on year, as we need to get records of 2016 & 2017 years * * Remove duplicates based on tweet id, by grouping based on tweet id and selecting first. * */ while (IsResponseAvailable) { try { var client = new RestClient(_badRestBaseUrl); var request = new RestRequest("/api/v1/Tweets", Method.GET); request.AddQueryParameter("startDate", startDate); request.AddQueryParameter("endDate", endDate); var response = client.Execute(request); if (response == null || string.IsNullOrEmpty(response.Content)) { break; } var tweetList = JsonConvert.DeserializeObject <List <TweetModel> >(response.Content); if (tweetList.Count < 100) { IsResponseAvailable = false; } var filtered = tweetList.Where(a => a.stamp.Year >= 2016 && a.stamp.Year <= 2017); if (filtered.Count() > 0) { tweetView.TweetList.AddRange(filtered); //Taking max timestamp from api response startDate = filtered.Max(t => t.stamp).ToString("yyyy-MM-ddThh:mm:ss.fffZ"); } } catch (Exception ex) { Console.Write(ex.Message); } } //Removing Duplicates var tweetsWithoutDuplicate = tweetView.TweetList.GroupBy(i => i.id).Select(g => g.First()).ToList(); //Getting count of duplicate records tweetView.DuplicateCount = tweetView.TweetList.Count() - tweetsWithoutDuplicate.Count(); tweetView.TweetList = tweetsWithoutDuplicate; return(tweetView); }
public ActionResult UserDashBoard([Bind(Include = "objTweet,objTweetList,objFollow")] TweetViewModel objTwt) { AssessmentEntities db = new AssessmentEntities(); tweet objTweet = new tweet(); following objFollow = new following(); TweetViewModel oTwt = new TweetViewModel(); if (ModelState.IsValid) { objTweet.user_id = Session["UserID"].ToString(); objTweet.created = DateTime.Now; objTweet.message = objTwt.objTweet.message; db.tweets.Add(objTweet); db.SaveChanges(); objFollow.user_id = Session["UserID"].ToString(); objFollow.following_id = objTwt.objFollow.following_id; db.followings.Add(objFollow); db.SaveChanges(); oTwt.objTweetList = GetTweetList(); oTwt.objTweet = new tweet(); oTwt.objTweet.message = string.Empty; oTwt.tweetCount = oTwt.objTweetList.Count.ToString(); string result = GetFollowingList(); oTwt.followingCount = result.Split(';')[0]; oTwt.followersCount = result.Split(';')[1]; return(View(oTwt)); } return(View(oTwt)); }
public ActionResult Create(TweetViewModel tweet) { if (this.ModelState.IsValid) { tweet.AuthorId = this.User.Identity.GetUserId(); var newTweet = new Tweet { AuthorId = tweet.AuthorId, Text = tweet.Text }; this.db.Tweets.Add(newTweet); this.db.SaveChanges(); // Show Tweet to all followers var context = GlobalHost.ConnectionManager.GetHubContext <TweeterHub>(); var usernames = this.UserProfile.Followers.Select(f => f.UserName).ToList(); context.Clients.Users(usernames).showTweet(newTweet.Id); this.TempData["message"] = "Tweet added successfully."; this.TempData["isMessageSuccess"] = true; return(this.RedirectToAction("Index", "Home")); } this.TempData["message"] = "There are problem with tweet adding."; this.TempData["isMessageSuccess"] = false; this.ViewBag.AuthorId = new SelectList(this.db.Users, "Id", "FullName", tweet.AuthorId); return(this.View("Tweet/_CreateTweetPartial", tweet)); }
public IActionResult ShowAllTweets() { var tweets = this.tweetService.GetAllAndDeletedTweets(); var model = new ShowAllTweetsModel() { Tweets = new List <TweetViewModel>() }; foreach (var tweet in tweets) { var tweetToAdd = new TweetViewModel() { Id = tweet.Id, TwitterId = tweet.TwitterId, CreatedAt = tweet.CreatedAt, Text = tweet.Text, TwitterUserName = tweet.TwitterUser.ScreenName, TwitterUserProfileImageUrl = tweet.TwitterUser.ProfileImageUrl, }; model.Tweets.Add(tweetToAdd); } return(View(model)); }
// GET: Tweet public ActionResult Index() { TweetViewModel tvm = new TweetViewModel(); tvm.Tweets = new List <Tweet>(); return(View(tvm)); }
public void ScreenName_ShoulBeFormattedWithOriginalUserScreenName_WhenRetweetStatusIsNotNullTest() { NGTweeterStatus tweeterStatus = new NGTweeterStatus { CreatedDate = DateTime.Today, Id = 101, RetweetedStatus = new NGTweeterStatus { CreatedDate = DateTime.Today, Id = 102, Tweet = "Original Tweet", User = new NGTweeterUser { Id = 5, Name = "Nilesh", ProfileImageUrl = "Nilesh.jpg", ScreenName = "NileshGule" } }, User = new NGTweeterUser { Id = 6, Name = "TestName", ProfileImageUrl = "Test.jpg", ScreenName = "TestScreenName" } }; _viewModel = new TweetViewModel(tweeterStatus); Assert.AreEqual("NileshGule, (RT by TestScreenName)", _viewModel.ScreenName); }
public override IEnumerable <Inline> ToTarget(TweetViewModel input, object parameter) { if (!Application.Current.Dispatcher.CheckAccess()) { return(Application.Current.Dispatcher.Invoke(new Action(() => ToTarget(input, parameter)), null) as IEnumerable <Inline>); } bool referenceOriginal = parameter as string != null?bool.Parse(parameter as string) : false; var status = input.Status as TwitterStatus; if (referenceOriginal && status != null && status.RetweetedOriginal != null) { status = status.RetweetedOriginal; } if (status != null) { var src = status.Source; Match m = null; if (!String.IsNullOrEmpty(src) && (m = SourceRegex.Match(src.Replace("\\", ""))).Success) { return(new[] { TextElementGenerator.GenerateHyperlink( m.Groups[2].Value, () => Browser.Start(m.Groups[1].Value)) }); } else { return(new[] { TextElementGenerator.GenerateRun(status.Source) }); } } // ELSE return(new Run[0]); }
public async Task <IHttpActionResult> PutTweet(int id, [FromBody] TweetViewModel tweetViewModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != tweetViewModel.Id) { return(BadRequest()); } db.Entry(tweetViewModel.ToTweet()).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TweetExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public void IsRetweet_ShoulBeTrue_WhenRetweetStatusIsNotNullTest() { NGTweeterStatus tweeterStatus = new NGTweeterStatus { CreatedDate = DateTime.Today, Id = 101, RetweetedStatus = new NGTweeterStatus { CreatedDate = DateTime.Today, Id = 102, Tweet = "Original Tweet", User = new NGTweeterUser { Id = 5, Name = "Nilesh", ProfileImageUrl = "Nilesh.jpg", ScreenName = "NileshGule" } }, User = new NGTweeterUser { Id = 6, Name = "TestName", ProfileImageUrl = "Test.jpg", ScreenName = "TestScreenName" } }; _viewModel = new TweetViewModel(tweeterStatus); Assert.IsTrue(_viewModel.IsRetweet); }
public async Task <IActionResult> ModalEdit(int id) { if (id == 0) { return(NotFound()); } Tweet tweet = await _unitofWork.TweetRepository.GetByIdAsync(id); if (tweet == null) { return(NotFound()); } TweetViewModel tweetVM = new TweetViewModel { Content = tweet.Content, Id = tweet.Id, UserId = tweet.UserId, CreateDate = tweet.CreatedDate }; _logger.LogInfo($"Controller : UserTweet | Action : ModalEdit GET | User : {tweetVM.UserId}"); return(PartialView("_ModalEditTweet", tweetVM)); }
// POST api/<controller> public Dictionary <string, bool> Post([FromBody] TweetViewModel tweet) { Dictionary <string, bool> answer = new Dictionary <string, bool>(); if (ModelState.IsValid && User.Identity.IsAuthenticated) { string user_id = User.Identity.GetUserId(); Twit found_user = Repo.GetTwitUser(user_id); if (found_user != null) { Tweet new_tweet = new Tweet { Message = tweet.Message, ImageURL = tweet.ImageURL, Author = found_user, CreatedAt = DateTime.Now }; Repo.AddTweet(new_tweet); answer.Add("successful", true); } else { answer.Add("successful", false); } } else { answer.Add("successful", false); } return(answer); }
public async Task <JsonResult> CreateTweet([Bind("Content")] TweetViewModel tweetVM) { if (!ModelState.IsValid) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new { success = false })); // return PartialView("_CreateTweet", tweetVM); } User loggedUser = await GetLoggedInUserDetails(); _logger.LogInfo($"Controller : UserTweet | Action : CreateTweet | User : {loggedUser.Id}"); Tweet tweet = new Tweet { UserId = loggedUser.Id, Content = tweetVM.Content, CreatedDate = DateTime.Now }; _unitofWork.TweetRepository.Add(tweet); if (await _unitofWork.SaveAsync()) { _logger.LogInfo($"{tweet.UserId} added new tweet."); Response.StatusCode = (int)HttpStatusCode.OK; ModelState.Clear(); return(Json(new { success = true })); } Response.StatusCode = (int)HttpStatusCode.BadRequest; return(Json(new { success = false })); }
private List <TweetViewModel> MapTweetsToVM(List <Tweet> userTweets, User tweetuser, bool isOwner) { List <TweetViewModel> tweetList = new List <TweetViewModel>(); TweetViewModel TweetVM; foreach (var tweet in userTweets.OrderByDescending(p => p.ModifiedDate > p.CreatedDate ? p.ModifiedDate : p.CreatedDate)) { TweetVM = new TweetViewModel() { Content = tweet.Content, Id = tweet.Id, DisplayCreateDate = $"{tweet.CreatedDate.Date.ToString("MMMM")},{tweet.CreatedDate.Day} {tweet.CreatedDate.Year} at {tweet.CreatedDate.ToString("hh:mm tt")}", DisplayModifedDate = tweet.ModifiedDate == DateTime.MinValue ? null : $"{tweet.ModifiedDate.Date.ToString("MMMM")},{tweet.ModifiedDate.Day} {tweet.ModifiedDate.Year} at {tweet.ModifiedDate.ToString("hh:mm tt")}", UserId = tweet.UserId, UserName = $"{tweetuser.FirstName} {tweetuser.LastName}", CreateDate = tweet.CreatedDate, ModifyDate = tweet.ModifiedDate, OwnTweet = isOwner }; tweetList.Add(TweetVM); } return(tweetList); }
public ActionResult GetTweet(int id) { var tweet = this.Data.Tweets.Find(id); if (tweet == null) { return this.HttpNotFound("Tweet not found."); } var viewModel = new TweetViewModel() { Id = tweet.Id, Content = tweet.Content, Uri = tweet.PageUrl, TweetedOn = tweet.Date, Author = new UserViewModel { Username = tweet.Author.UserName, ProfileImage = tweet.Author.ProfileImage ?? DefaultValues.DefaultProfileImage } }; return this.PartialView("_TweetPartial", viewModel); }
public ActionResult Create(TweetViewModel model) { //return null; if (this.ModelState.IsValid) { model.AuthorId = this.User.Identity.GetUserId(); db.Tweets.Add(new Tweet() { //AuthorId = model.AuthorId, Title = model.Title, Description = model.Description, TakenDate = DateTime.Now }); db.SaveChanges(); this.TempData["message"] = "Tweet added successfylly."; this.TempData["isMessageSuccess"] = true; return(RedirectToAction("Index", "Home")); } this.TempData["message"] = "There is a problem with the creation of this tweet. Please try again later."; this.TempData["isMessageSuccess"] = false; this.ViewBag.AuthorId = new SelectList(db.Users, "Id", "FullName", model.AuthorId); return(View("Tweets/Create", model)); }
public ActionResult Create(TweetViewModel tweet) { var tagsMatches = Regex.Matches(tweet.Content, @"(#[a-zA-Z_\d-]+)"); var tags = new List<Tag>(); foreach (Match tag in tagsMatches) { tags.Add(new Tag() { Name = tag.Value }); } var userId = User.Identity.GetUserId(); var newTweet = new Tweet() { AuthorId = userId, Content = tweet.Content, Tags = tags }; this.tweets.Create(newTweet); return this.RedirectToAction("Index", "Home"); }
// GET: Twitter public ActionResult Tweet() { if (Session["UserName"] != null) { string userId = Session["UserName"].ToString(); TweetViewModel tweetViewModel = new TweetViewModel(); tweetViewModel.Tweets = new Collection <TweetModel>(); Collection <Tweet> tweets = personManager.GetFollowingTweets(userId); tweetViewModel.FollowersCount = personManager.GetFollowers(userId).Count; tweetViewModel.FollowingCount = personManager.GetFollowings(userId).Count; tweets.ToList().ForEach(x => tweetViewModel.Tweets.Add(new TweetModel() { TweetId = x.Tweet_Id, UserId = x.User_Id, Message = x.Message, CreatedDate = x.Created })); tweetViewModel.IsTweetPage = true; return(View(tweetViewModel)); } else { return(RedirectToAction("Login", "Account")); } }
private TweetViewModel BuildTweetViewModel(IList <TweetDto> tweetsResult, int pageSize, int pageIndex, string hashTag, string searchTerm, bool filtering) { IEnumerable <TweetModel> tweets = tweetsResult .Select(result => new TweetModel() { Id = result.Id, ScreenName = result.ScreenName, Text = result.Text, Selected = false, CreatedAt = result.CreatedAt }); TweetViewModel tweetsViewModel = new TweetViewModel() { Tweets = tweets, HasNextPage = (tweets.Count() >= 0 && tweets.Count() == pageSize), HasPrevPage = (pageIndex > 0), PageIndex = pageIndex, SearchModel = new SearchModel() { HashTag = hashTag, SearchTerm = searchTerm } }; if (filtering) { tweetsViewModel.HasNextPage = true; tweetsViewModel.HasPrevPage = false; } return(tweetsViewModel); }
public void Create(TweetViewModel view) { var entity = mapper.Map <TweetViewModel, TweetEntity>(view); entity.Author = userRepository.Read(view.AuthorId); repository.Create(entity); }
/// <summary> /// ツイートをツイートストレージから除去 /// </summary> /// <param name="id">ツイートID</param> public static void Trim(long id) { TweetViewModel remobj = null; using (elockWrap.GetWriterLock()) { empties.Remove(id); } using (lockWrap.GetWriterLock()) { if (dictionary.TryGetValue(id, out remobj)) { dictionary.Remove(id); _count--; } } if (remobj != null) { using (vmLockWrap.GetWriterLock()) { viewmodels.Remove(remobj); } Task.Factory.StartNew(() => RaiseStatusRemoved(remobj)); } }
public IHttpActionResult UpdateTweet(TweetViewModel model) { tweetService.UpdateTweet(model); return(Ok("Success!")); }
/// <summary> /// ツイートデータを取得します。 /// </summary> /// <param name="id">ツイートID</param> /// <param name="createEmpty">存在しないとき、空のViewModelを作って登録して返す</param> public static TweetViewModel Get(long id, bool createEmpty = false) { TweetViewModel ret; using (lockWrap.GetReaderLock()) { if (dictionary.TryGetValue(id, out ret)) { return(ret); } } using (createEmpty ? elockWrap.GetUpgradableReaderLock() : elockWrap.GetReaderLock()) { if (empties.TryGetValue(id, out ret)) { return(ret); } if (createEmpty) { using (elockWrap.GetWriterLock()) { var nvm = new TweetViewModel(id); empties.Add(id, nvm); return(nvm); } } else { return(null); } } }
private static void RetweetCore(AccountInfo d, TweetViewModel status) { if (ApiHelper.ExecApi(() => d.Retweet(status.Status.Id)) == null) { throw new ApplicationException(); } }
private static void UnfavTweetCore(AccountInfo d, TweetViewModel status) { if (ApiHelper.ExecApi(() => d.DestroyFavorites(status.Status.Id)) == null) { throw new ApplicationException(); } }
public ActionResult ValidateTwitterAuth() { var verifierCode = Request.Params.Get("oauth_verifier"); var authorizationId = Request.Params.Get("authorization_id"); var userCreds = CredentialsCreator.GetCredentialsFromVerifierCode(verifierCode, authorizationId); var user = Tweetinvi.User.GetLoggedUser(userCreds); ViewBag.User = user; var homeTimeline = user.GetHomeTimeline(); List <TweetViewModel> tweetList = new List <TweetViewModel>(); foreach (var tweet in homeTimeline) { TweetViewModel tweetView = new TweetViewModel(); tweetView.Id = tweet.Id.ToString(); tweetView.Author = tweet.CreatedBy.ToString(); tweetView.Text = tweet.Text.ToString(); tweetView.DatePosted = tweet.CreatedAt; tweetView.UsersFavouriteCount = tweet.FavouriteCount; tweetView.RetweetsCount = tweet.RetweetCount; //tweetView.RepliesCount = tweetList.Add(tweetView); } return(View(tweetList)); }
public async Task <ActionResult> Feed(string hashTag, string searchTerm, bool filtering = false, int pageIndex = 0) { bool isAuthorized = _authorizationManager.IsAuthorized(HttpContext.Session); if (!isAuthorized) { return(RedirectToAction("Index", "TwitterOAuth")); } // Server side validation, in case the client side is removed by hand. if (string.IsNullOrEmpty(searchTerm) && string.IsNullOrEmpty(hashTag)) { return(View("Views/TwitterFeed/Error.cshtml", "The Search term can not be empty!")); } PageTweetBorders pageTweetBorders = GetPageTweetBorders(pageIndex, filtering); int pageSize = _twitterConfig.PageSize; string query = $"{hashTag} {searchTerm}"; // Unfortunatelly, twitter does not provide standart page parameters to do paging. // Their idea is to provide since and max ids and leave it to the developer to implement their own paging. IList <TweetDto> tweetsResult = await _twitterService.Search(query, pageSize, pageTweetBorders.SinceId, pageTweetBorders.MaxId); if (tweetsResult.Count > 0) { SetPageTweetBorders(pageIndex, tweetsResult); } TweetViewModel tweetsViewModel = BuildTweetViewModel(tweetsResult, pageSize, pageIndex, hashTag, searchTerm, filtering); return(View(tweetsViewModel)); }
private void AddTweet(TweetViewModel tvm) { var atdtvm = new TabDependentTweetViewModel(tvm, this.Parent); if (this._tweetsSource.Contains(atdtvm)) { return; } if (Setting.Instance.TimelineExperienceProperty.UseIntelligentOrdering && DateTime.Now.Subtract(tvm.CreatedAt).TotalSeconds < Setting.Instance.TimelineExperienceProperty.IntelligentOrderingThresholdSec) { if (Setting.Instance.TimelineExperienceProperty.OrderByAscending) { this._tweetsSource.AddLastSingle(atdtvm); } else { this._tweetsSource.AddTopSingle(atdtvm); } } else { this._tweetsSource.AddOrderedSingle( atdtvm, Setting.Instance.TimelineExperienceProperty.OrderByAscending, t => t.Tweet.CreatedAt); } OnNewTweetReceived(); }
public static void ExecuteAction(TweetViewModel target, ReplyMouseActionCandidates actionKind, string argument) { switch (actionKind) { case ReplyMouseActionCandidates.Reply: case ReplyMouseActionCandidates.ReplyFromSpecificAccount: KernelService.MainWindowViewModel.InputBlockViewModel.SetOpenText(true, true); KernelService.MainWindowViewModel.InputBlockViewModel.SetInReplyTo(target); if (actionKind == ReplyMouseActionCandidates.ReplyFromSpecificAccount && !String.IsNullOrEmpty(argument)) { KernelService.MainWindowViewModel.InputBlockViewModel.OverrideTarget( GetAccountInfos(argument)); } break; case ReplyMouseActionCandidates.ReplyImmediately: if (String.IsNullOrEmpty(argument)) { return; } var status = target.Status; if (!Setting.Instance.InputExperienceProperty.OfficialRetweetInReplyToRetweeter && status is TwitterStatus && ((TwitterStatus)status).RetweetedOriginal != null) { status = ((TwitterStatus)status).RetweetedOriginal; } PostImmediate(GetAccountInfos(), String.Format(argument, "@" + status.User.ScreenName), status.Id); break; } }
public static bool IsInReplyToMeStrict(TweetViewModel status) { if (status == null || !status.IsStatusInfoContains) { return(false); } var s = status.Status as TwitterStatus; if (s != null) { return(AccountStorage.Accounts.Any(d => d.ScreenName == s.InReplyToUserScreenName)); } else { var dm = status.Status as TwitterDirectMessage; if (dm != null) { return(AccountStorage.Accounts.Any(d => d.ScreenName == dm.Recipient.ScreenName)); } else { return(false); } } }
public static bool IsInReplyToMeCurrentStrict(TweetViewModel status, TabProperty property) { if (status == null || !status.IsStatusInfoContains || property == null) { return(false); } var s = status.Status as TwitterStatus; if (s != null) { return(property.LinkAccountScreenNames.Any(a => a == s.InReplyToUserScreenName)); } else { var dm = status.Status as TwitterDirectMessage; if (dm != null) { return(property.LinkAccountScreenNames.Any(a => a == dm.Recipient.ScreenName)); } else { return(false); } } }
public ActionResult CreateTweet(CreateTweetBindingModel model) { if (ModelState.IsValid && model.TweetContent != null) { Tweet tweet = new Tweet(); tweet.OwnerId = this.User.Identity.GetUserId(); tweet.Content = model.TweetContent; this.Data.Tweets.Add(tweet); this.Data.Users.GetById(this.User.Identity.GetUserId()).OwnedTweets.Add(tweet); this.Data.SaveChanges(); TweetViewModel tweetModel = new TweetViewModel() { Id = tweet.Id, Content = model.TweetContent, TimeOfPublication = tweet.TimeOfPublicated, Username = this.User.Identity.GetUserName() }; var hubContext = GlobalHost.ConnectionManager.GetHubContext <TweetHub>(); hubContext.Clients.All.receiveMessage(tweetModel); return(RedirectToAction("Index", "User")); } else { throw new ArgumentOutOfRangeException("The content of tweet must be less than 300 symbols!"); } return(RedirectToAction("Index", "User")); }
/// <summary> /// アクションを実行します。 /// </summary> /// <param name="target">対象ターゲット</param> /// <param name="action">アクション。Nullの場合は何も実行されません。</param> public static void ExecuteAction <T>(TweetViewModel target, ActionDescription <T> action) { if (action == null) { return; } ExecuteAction(target, (dynamic)action.Action, action.ActionArgs); }
public ActionResult GetUserTimelinePartialView() { TweetInputModel tweetInputModel = new TweetInputModel(); TweetModel tweetModel = new TweetModel(); IEnumerable<TweetModel> foundTweets = tweetModel.GetUserTimeline(tweetInputModel); // Transfer data from TweetModel to TweetViewModel IList<TweetViewModel> groupOfTweets = new List<TweetViewModel>(); foreach (TweetModel tweet in foundTweets) { TweetViewModel tweetViewModel = new TweetViewModel(); tweetViewModel.Message = tweet.Message; groupOfTweets.Add(tweetViewModel); } return PartialView("UserTimelinePartialView", groupOfTweets); }
public ActionResult Create(TweetViewModel tweet) { if (ModelState.IsValid) { var newTweet = new Tweet() { Content = tweet.Content, CreatedDate = DateTime.UtcNow, Title = tweet.Title, UserId = this.UserProfile.Id }; tweets.Add(newTweet); tweets.SaveChanges(); var givenTags = tweet.Tags.Split(';'); foreach (var tag in givenTags) { var tagDb = this.tags.All().FirstOrDefault(t => t.Title == tag); if (tagDb != null) { tagDb.Tweets.Add(newTweet); this.tags.Update(tagDb); } else { var newTag = new Tag() {Title = tag}; newTag.Tweets.Add(newTweet); this.tags.Add(newTag); } } this.tags.SaveChanges(); return RedirectToAction("Mine"); } return View(tweet); }