public MainWindow()
    {
        InitializeComponent();

        tweets = new Tweets();

        tweets.Add(new Tweet("user1", "name1", "url1"));
        tweets.Add(new Tweet("user2", "name2", "url2"));
        tweets.Add(new Tweet("user3", "name3", "url3"));

        this.DataContext = this;
    }
Exemplo n.º 2
0
        private async void FetchTweets(string fetchText)
        {
            IEnumerable <Tweet> timeLine = null;

            try
            {
                IsBusy = true;

                var filter = GetAccount(fetchText);

                if (filter != null)
                {
                    timeLine = await TwitterService.Instance.GetUserTimeLineAsync(filter, 10);
                }
                else
                {
                    timeLine = await TwitterService.Instance.SearchAsync(fetchText, 10);
                }

                Tweets.Clear();

                foreach (var tweet in timeLine)
                {
                    Tweets.Add(tweet);
                }
            }
            finally
            {
                IsBusy = false;
            }
        }
Exemplo n.º 3
0
 public MainViewModel()
 {
     if (IsInDesignMode)
     {
         Tweets.Add(new Tweet()
         {
             Avatar = "/Images/avatar.jpg", Handle = "Handle1", Location = "Frisco, TX", TweetText = "This is my latest tweet. There are many like them but this one is mine."
         });
         Tweets.Add(new Tweet()
         {
             Avatar = "/Images/avatar.jpg", Handle = "Handle2", Location = "Frisco, TX", TweetText = "This is my latest tweet. There are many like them but this one is mine."
         });
         Tweets.Add(new Tweet()
         {
             Avatar = "/Images/avatar.jpg", Handle = "Handle3", Location = "Frisco, TX", TweetText = "This is my latest tweet. There are many like them but this one is mine."
         });
         Tweets.Add(new Tweet()
         {
             Avatar = "/Images/avatar.jpg", Handle = "Handle4", Location = "Frisco, TX", TweetText = "This is my latest tweet. There are many like them but this one is mine."
         });
         Tweets.Add(new Tweet()
         {
             Avatar = "/Images/avatar.jpg", Handle = "Handle5", Location = "Frisco, TX", TweetText = "This is my latest tweet. There are many like them but this one is mine."
         });
         Tweets.Add(new Tweet()
         {
             Avatar = "/Images/avatar.jpg", Handle = "Handle6", Location = "Frisco, TX", TweetText = "This is my latest tweet. There are many like them but this one is mine."
         });
     }
     else
     {
         // Code runs "for real"
     }
 }
Exemplo n.º 4
0
        async Task ExecuteLoadTweetsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            try
            {
                Tweets.Clear();
                await TwitterController.GetTweets("熱中症");

                var tweets = TwitterController.GetTweetStatuses();
                foreach (var t in tweets)
                {
                    Tweet tweet = new Tweet();
                    tweet.Id                = t["id"];
                    tweet.Name              = t["user"]["name"];
                    tweet.Created           = t["created_at"];
                    tweet.Text              = t["text"];
                    tweet.Profile_image_url = t["user"]["profile_image_url"];
                    Tweets.Add(tweet);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
        public override async void Navigated(string navigationParameter)
        {
            try
            {
                IsSearching = true;
                Tweets.Clear();

                var clientResponse = await _twitterAuthenticator.AuthenticateAsync(_authInformation.AccessToken, _authInformation.AccessTokenSecret);

                if (clientResponse.StatusCode != HttpStatusCode.OK)
                {
                    Debug.WriteLine("Error authenticating: " + clientResponse.StatusCode + ": " + clientResponse.ErrorMessage);
                    return;
                }
                TwitterClient client = clientResponse.Content;

                var searchResponse = await client.SearchAsync(navigationParameter, RESULTS_TO_SHOW);

                if (searchResponse.StatusCode != HttpStatusCode.OK)
                {
                    Debug.WriteLine("Error searching: " + clientResponse.StatusCode + ": " + clientResponse.ErrorMessage);
                    return;
                }

                Tweets.Clear();

                //Tweets.Add(new Tweet()
                //{
                //    Author = "dsplaisted",
                //    ProfileImageUrl = new Uri("https://pbs.twimg.com/profile_images/51934680/iguana_bigger.jpg"),
                //    Text = "Short tweet",
                //    Timestamp = DateTime.Now
                //});

                //Tweets.Add(new Tweet()
                //{
                //    Author = "dsplaisted",
                //    ProfileImageUrl = new Uri("https://pbs.twimg.com/profile_images/51934680/iguana_bigger.jpg"),
                //    Text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
                //    Timestamp = DateTime.Now
                //});

                foreach (var tweet in searchResponse.Content)
                {
                    Tweets.Add(new Tweet()
                    {
                        Author          = tweet.User.ScreenName,
                        ProfileImageUrl = tweet.User.ProfileImageUri,
                        Text            = tweet.Text,
                        Timestamp       = tweet.CreatedAt
                    });
                }

                IsSearching = false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error searching Twitter: " + ex.ToString());
            }
        }
Exemplo n.º 6
0
        private async void ExecuteLoadTweetsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;
            try
            {
                Tweets.Clear();
                var auth = new ApplicationOnlyAuthorizer()
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey    = "ZTmEODUCChOhLXO4lnUCEbH2I",
                        ConsumerSecret = "Y8z2Wouc5ckFb1a0wjUDT9KAI6DUat5tFNdmIkPLl8T4Nyaa2J",
                    },
                };
                await auth.AuthorizeAsync();

                var twitterContext = new TwitterContext(auth);

                var searchResponse =
                    await(from search in twitterContext.Search
                          where search.Type == SearchType.Search &&
                          search.Count == 100 &&
                          search.Query == "\"#dcc14\""
                          select search)
                    .SingleOrDefaultAsync();

                if (searchResponse != null && searchResponse.Statuses != null)
                {
                    var tweets =
                        (from tweet in searchResponse.Statuses
                         select new Tweet
                    {
                        StatusID = tweet.StatusID,
                        ScreenName = tweet.User.ScreenNameResponse,
                        Text = tweet.Text,
                        CurrentUserRetweet = tweet.CurrentUserRetweet,
                        CreatedAt = tweet.CreatedAt
                    }).ToList();


                    foreach (var tweet in tweets)
                    {
                        Tweets.Add(tweet);
                    }
                }
            }
            catch (Exception ex)
            {
                var page = new ContentPage();
                page.DisplayAlert("Error", "Unable to load twitter.", "OK");
            }

            IsBusy = false;
        }
Exemplo n.º 7
0
        private static void AddUserAndTweet(string line, string[] usersAndTweet)
        {
            if (usersAndTweet.Length == 2)
            {
                User tweetingUser = Users[Users.IndexOf(new User(usersAndTweet[0]))];

                Tweet newTweet = new Tweet(usersAndTweet[1].Trim(), tweetingUser);
                Tweets.Add(newTweet);
            }
        }
Exemplo n.º 8
0
        void BuildTweetsFromAllUsers()
        {
            Tweets.Clear();
            var tweets = _repository.GetAll();

            foreach (var tweetFromUser in tweets)
            {
                Tweets.Add(tweetFromUser);
            }
        }
Exemplo n.º 9
0
 public void FollowUser(object sender, Tweet tweet)
 {
     try
     {
         Tweets.Add(tweet);
     }
     catch (System.Exception)
     {
         throw;
     }
 }
Exemplo n.º 10
0
 private Task AsyncAddList2()
 {
     return(Task.Run(() =>
     {
         for (int i = 0; i < 1000; i++)
         {
             Tweets /*[Account]*/.Add(new Tweet($"naruko + {i}", "hello waorla"));
             Thread.Sleep(5000);
         }
     }
                     ));
 }
Exemplo n.º 11
0
        protected void AddStatus(Status status)
        {
            TweetContext tweet = new TweetContext()
            {
                User    = status.User,
                Tweet   = status.Text,
                Time    = status.CreatedAt,
                Country = status.Place.Country ?? "Unknown"
            };

            Tweets.Add(tweet);
        }
        private async void SearchTweetsAsync()
        {
            var tweetsFound = Tweetinvi.Search.SearchTweets(SearchText);

            foreach (var tweet in tweetsFound)
            {
                var curTweet = tweet as Tweet;
                Tweets.Add(curTweet);
            }

            await Task.CompletedTask;
        }
        void MapTweets(Task <string> x)
        {
            Thread.Sleep(2000);
            var json = new JavaScriptSerializer().Deserialize <dynamic>(x.Result);

            Tweets.Clear();
            foreach (var result in json["results"])
            {
                Tweets.Add(new TweetViewModel(result["text"]));
            }
            IsBusy = false;
        }
Exemplo n.º 14
0
        public ITweet AddTweet(string text)
        {
            if (Tweets == null)
            {
                Tweets = new List <ITweet>();
            }

            Tweet newTweet = new Tweet(this, text);

            Tweets.Add(newTweet);

            return(newTweet);
        }
        async Task ExecuteLoadTweetsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;

            Tweets.Clear();

            var auth = new ApplicationOnlyAuthorizer
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey    = "4a8c7X6NqcBT5GY6nWOX9b32P",
                    ConsumerSecret = "QOIvLNS05WfORaQTwvkaxnfH7Rejwi7NgBVUBudtJ0yhiFpCjL",
                },
            };

            await auth.AuthorizeAsync();

            var twitterContext = new TwitterContext(auth);

            var queryResponse = await
                                    (from tweet in twitterContext.Status
                                    where tweet.Type == StatusType.User &&
                                    tweet.ScreenName == "xamarinhq" &&
                                    tweet.Count == 20 &&
                                    tweet.IncludeRetweets == true &&
                                    tweet.ExcludeReplies == true
                                    select tweet).ToListAsync();

            var tweets =
                (from tweet in queryResponse
                 select new Tweet
            {
                Name = tweet.User.Name,
                Time = tweet.CreatedAt,
                Text = tweet.Text,
                AvatarUrl = (tweet.RetweetedStatus != null && tweet.RetweetedStatus.User != null ?
                             tweet.RetweetedStatus.User.ProfileImageUrl.Replace("http://", "https://") : tweet.User.ProfileImageUrl.Replace("http://", "https://"))
            }).ToList();

            foreach (var tweet in tweets)
            {
                Tweets.Add(tweet);
            }

            IsBusy = false;
        }
Exemplo n.º 16
0
        //
        // BindingOperations.EnableCollectionSynchronization(this.Tweets, new object());
        // でObservableCollectionにプロパティを指定しない場合は、下記のようにBeginInvokeを呼ぶ
        //
        private Task AsyncAddList()
        {
            var act = new Action <int>((i) => { Tweets /*[Account]*/.Add(new Tweet($"naruko + {i}", "hello waorla", "")); });

            return(Task.Run(() =>
            {
                for (int i = 0; i < 1000; i++)
                {
                    App.Current.Dispatcher.BeginInvoke(act, new object[] { i });
                    Thread.Sleep(5000);
                }
            }
                            ));
        }
Exemplo n.º 17
0
 private void Tweets_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
     if (e.Action == NotifyCollectionChangedAction.Add)
     {
         foreach (var tweet in e.NewItems.Cast <Tweet>())
         {
             Tweets.Add(tweet);
         }
     }
     else if (e.Action == NotifyCollectionChangedAction.Reset)
     {
         Tweets.Clear();
     }
 }
Exemplo n.º 18
0
        private async void LoadTweetsAsync()
        {
            List <Tweet> tweets = await Service.SearchAsync(Hashtag);

            foreach (Tweet t in tweets)
            {
                Tweets.Add(t);
            }

            // stream tweets
            Service.StreamAsync(Hashtag, (t) =>
            {
                Tweets.Insert(0, t);
            });
        }
        public AppDbContext()
        {
            //check si la BDD est créée
            if (this.Database.EnsureCreated())
            {
                //injection des données
                //users
                User user1 = new User()
                {
                    UserPseudo = "Lyse", UserName = "******", Login = "******", Password = "******"
                };
                User user2 = new User()
                {
                    UserPseudo = "Matis", UserName = "******", Login = "******", Password = "******"
                };
                User user3 = new User()
                {
                    UserPseudo = "Flo", UserName = "******", Login = "******", Password = "******"
                };
                Users.Add(user1);
                Users.Add(user2);
                Users.Add(user3);
                this.SaveChanges();

                ////tweets
                var listTweetToPersist = new List <Tweet> {
                    new Tweet()
                    {
                        CreationDate = "50s", Text = "Nullam id accumsan ipsum. Nunc ullamcorper at velit ac semper. Integer vestibulum, lectus vitae pretium interdum, dui nibh auctor lectus.", User = user1
                    },
                    new Tweet()
                    {
                        CreationDate = "20s", Text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi tincidunt erat eu sapien congue, a scelerisque magnaum lacus, vitae dignissim erat", User = user2
                    },
                    new Tweet()
                    {
                        CreationDate = "10s", Text = "Ut vel lobortis enim. Pellentesque nisi lorem, mollis quis tellus eget, tincidunt maximus ante.", User = user3
                    }
                };
                foreach (var tweet in listTweetToPersist)
                {
                    Tweets.Add(tweet);
                }
                this.SaveChanges();
            }
        }
Exemplo n.º 20
0
 public void AddTweet(Tweet tweet)
 {
     Parallel.Invoke(
         () => {
         Tweets.Add(tweet);
     },
         () => {
         UpdateEmojiLists(tweet);
     },
         () => {
         UpdateHashtags(tweet);
     },
         () => {
         UpdateUrlLists(tweet);
     }
         );
 }
Exemplo n.º 21
0
        private async void FirstTimelineLoading()
        {
            var newTweets = Tweetinvi.Timeline.GetUserTimeline(UserToLoad.Id);

            if (newTweets != null)
            {
                foreach (var tweet in newTweets)
                {
                    var curTweet = tweet as Tweet;
                    Tweets.Add(curTweet);
                }

                await Task.CompletedTask;
            }
            else
            {
                FirstTimelineLoading();
            }
        }
Exemplo n.º 22
0
        public override async void Navigated(string navigationParameter)
        {
            try
            {
                IsSearching = true;
                Tweets.Clear();

                var clientResponse = await _twitterAuthenticator.AuthenticateAsync(_authInformation.AccessToken, _authInformation.AccessTokenSecret);

                if (clientResponse.StatusCode != HttpStatusCode.OK)
                {
                    Debug.WriteLine("Error authenticating: " + clientResponse.StatusCode + ": " + clientResponse.ErrorMessage);
                    return;
                }
                TwitterClient client = clientResponse.Content;

                var searchResponse = await client.SearchAsync(navigationParameter, RESULTS_TO_SHOW);

                if (searchResponse.StatusCode != HttpStatusCode.OK)
                {
                    Debug.WriteLine("Error searching: " + clientResponse.StatusCode + ": " + clientResponse.ErrorMessage);
                    return;
                }

                Tweets.Clear();
                foreach (var tweet in searchResponse.Content)
                {
                    Tweets.Add(new Tweet()
                    {
                        Author          = tweet.User.ScreenName,
                        ProfileImageUrl = tweet.User.ProfileImageUri,
                        Text            = tweet.Text,
                        Timestamp       = tweet.CreatedAt
                    });
                }

                IsSearching = false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Error searching Twitter: " + ex.ToString());
            }
        }
Exemplo n.º 23
0
        private async void GetTweetsAsync(int cnt, String str)
        {
            var API_Key             = "**********************";
            var API_Secret          = "**********************";
            var Access_token        = "**********************";
            var Access_token_secret = "**********************";

            var tokens = CoreTweet.Tokens.Create(API_Key,
                                                 API_Secret,
                                                 Access_token,
                                                 Access_token_secret);

            // 取得用パラメータ準備
            var parm = new Dictionary <string, object>();

            parm["count"]       = cnt;
            parm["screen_name"] = str;

            try
            {
                // Tweet 取得(非同期版)
                var tweets = await tokens.Statuses.UserTimelineAsync(parm);

                var mediaTweets = tweets.Where(tw => tw.Entities?.Media != null);

                // ここも非同期処理
                await Task.Run(
                    () =>
                {
                    foreach (var tweet in tweets)
                    {
                        Tweets.Add(new Tweet(tweet.User.ScreenName, tweet.Text, tweet.Entities?.Media?[0].MediaUrl));
                        Thread.Sleep(100);
                    }
                }
                    );
            }
            catch (Exception e)
            {
                Console.WriteLine("{0}", e.ToString());
                throw;
            }
        }
Exemplo n.º 24
0
        private async Task ShowHomeTimeline()
        {
            try
            {
                var timeline = await _applicationClient.Timelines.GetHomeTimelineAsync();

                if (timeline != null)
                {
                    var dispatcher = Application.Current?.Dispatcher;
                    if (dispatcher != null)
                    {
                        dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
                        {
                            Tweets.Clear();
                            foreach (var tweet in timeline)
                            {
                                if (Filter(tweet))
                                {
                                    Tweets.Add(tweet);
                                }
                            }
                            TweetsHTML = BuildHTML();
                        }));
                    }
                }
                _currentStream = await SubscribeToFilterStream();

                _refreshTimer = new System.Timers.Timer(Settings.RefreshInterval)
                {
                    AutoReset = false
                };
                _refreshTimer.Elapsed += OnRefreshTimerElapsed;
                _refreshTimer.Start();
            }
            finally
            {
                IsAppKeyScreen   = false;
                IsLoginScreen    = false;
                IsTweetScreen    = true;
                IsNotAuthorizing = true;
            }
        }
        private async void FirstTimelineLoading()
        {
            HomeTlParameters.MaximumNumberOfTweetsToRetrieve = 50;
            var newTweets = Tweetinvi.Timeline.GetHomeTimeline(HomeTlParameters);

            if (newTweets != null)
            {
                foreach (var tweet in newTweets)
                {
                    var curTweet = tweet as Tweet;
                    Tweets.Add(curTweet);
                }

                await Task.CompletedTask;
            }
            else
            {
                FirstTimelineLoading();
            }
        }
Exemplo n.º 26
0
        async Task ExecuteLoadItemsCommand()
        {
            IsBusy = true;

            try
            {
                Tweets.Clear();
                var tweets = await DataStore.GetItemsAsync(true);

                foreach (var tweet in tweets)
                {
                    Tweets.Add(tweet);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Exemplo n.º 27
0
        private async Task GetTweets()
        {
            string maxId = "";

            if (!_maxId.Equals(""))
            {
                maxId = "?max_id=" + _maxId;
            }

            try
            {
                Response response = await _azureService.Client.InvokeApiAsync <Response>("timeline" + maxId, HttpMethod.Get, null);

                IsNoMoreTweets = !response.More_tweets;

                List <Tweet> tweets = response.Tweets;

                _maxId = tweets.Last().Id_str;

                tweets = tweets.Take(10).ToList();

                foreach (Tweet tweet in tweets)
                {
                    Tweets.Add(tweet);
                }
            }
            catch
            {
                bool retry = await _pageDialogService.DisplayAlertAsync("Ops", "Houve um erro, deseja tentar novamente?", "Sim", "Não");

                if (retry)
                {
                    await GetTweets();
                }
            }
        }
Exemplo n.º 28
0
        public async Task LoadTweetsCommand(string search)
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;
            try
            {
                Tweets.Clear();
                var auth = new ApplicationOnlyAuthorizer()
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey    = "ZTmEODUCChOhLXO4lnUCEbH2I",
                        ConsumerSecret = "Y8z2Wouc5ckFb1a0wjUDT9KAI6DUat5tFNdmIkPLl8T4Nyaa2J",
                    },
                };
                await auth.AuthorizeAsync();

                var twitterContext = new TwitterContext(auth);

                var queryResponse = await
                                        (from tweet in twitterContext.Search
                                        where tweet.Type == SearchType.Search &&
                                        tweet.Query == search &&
                                        tweet.Count == 100
                                        select tweet).SingleOrDefaultAsync();

                if (queryResponse == null || queryResponse.Statuses == null)
                {
                    return;
                }


                var tweets =
                    (from tweet in queryResponse.Statuses
                     select new Tweet
                {
                    StatusID = tweet.StatusID,
                    ScreenName = tweet.User.ScreenNameResponse,
                    Text = tweet.Text,
                    CurrentUserRetweet = tweet.CurrentUserRetweet,
                    CreatedAt = tweet.CreatedAt,
                    Url = string.Format("https://m.twitter.com/{0}/status/{1}", tweet.User.ScreenNameResponse, tweet.StatusID),
                    Image = (tweet.RetweetedStatus != null && tweet.RetweetedStatus.User != null ?
                             tweet.RetweetedStatus.User.ProfileImageUrl : tweet.User.ProfileImageUrl)
                }).ToList();

                foreach (var tweet in tweets)
                {
                    Tweets.Add(tweet);
                }
            }
            catch (Exception ex)
            {
            }

            IsBusy = false;
        }
Exemplo n.º 29
0
        public async Task ExecuteLoadTweetsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;
            LoadTweetsCommand.ChangeCanExecute();
            var error = false;

            try
            {
                Tweets.Clear();
                var auth = new ApplicationOnlyAuthorizer()
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey    = "ZTmEODUCChOhLXO4lnUCEbH2I",
                        ConsumerSecret = "Y8z2Wouc5ckFb1a0wjUDT9KAI6DUat5tFNdmIkPLl8T4Nyaa2J",
                    },
                };
                await auth.AuthorizeAsync();

                var twitterContext = new TwitterContext(auth);

                var queryResponse = await
                                        (from tweet in twitterContext.Status
                                        where tweet.Type == StatusType.User &&
                                        tweet.ScreenName == "shanselman" &&
                                        tweet.Count == 100 &&
                                        tweet.IncludeRetweets == true &&
                                        tweet.ExcludeReplies == true
                                        select tweet).ToListAsync();

                var tweets =
                    (from tweet in queryResponse
                     select new Tweet
                {
                    StatusID = tweet.StatusID,
                    ScreenName = tweet.User.ScreenNameResponse,
                    Text = tweet.Text,
                    CurrentUserRetweet = tweet.CurrentUserRetweet,
                    CreatedAt = tweet.CreatedAt,
                    Image = tweet.RetweetedStatus != null && tweet.RetweetedStatus.User != null ?
                            tweet.RetweetedStatus.User.ProfileImageUrl.Replace("http://", "https://") : (tweet.User.ScreenNameResponse == "shanselman" ? "scott159.png" : tweet.User.ProfileImageUrl.Replace("http://", "https://"))
                }).ToList();
                foreach (var tweet in tweets)
                {
                    Tweets.Add(tweet);
                }

                if (Device.OS == TargetPlatform.iOS)
                {
                    // only does anything on iOS, for the Watch
                    DependencyService.Get <ITweetStore>().Save(tweets);
                }
            }
            catch
            {
                error = true;
            }

            if (error)
            {
                var page = new ContentPage();
                await page.DisplayAlert("Error", "Unable to load tweets.", "OK");
            }

            IsBusy = false;
            LoadTweetsCommand.ChangeCanExecute();
        }
Exemplo n.º 30
0
        public async Task ExecuteLoadTweetsCommand()
        {
            if (IsBusy)
            {
                return;
            }

            IsBusy = true;
            LoadTweetsCommand.ChangeCanExecute();
            var error = false;

            try
            {
                Tweets.Clear();
                var auth = new ApplicationOnlyAuthorizer()
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey    = "nJY9F8wmTlHRgk4ADC0daADEo",
                        ConsumerSecret = "svZXhBwQrStrtYKcQfXBL4txSo5d34qteRwoODia24S7Pqgdpa",
                    },
                };
                await auth.AuthorizeAsync();

                var twitterContext = new TwitterContext(auth);

                var queryResponse = await
                                        (from tweet in twitterContext.Status
                                        where tweet.Type == StatusType.User &&
                                        tweet.ScreenName == "bwiredstudios" &&
                                        tweet.Count == 100 &&
                                        tweet.IncludeRetweets == true &&
                                        tweet.ExcludeReplies == true
                                        select tweet).ToListAsync();

                var tweets =
                    (from tweet in queryResponse
                     select new Tweet
                {
                    StatusID = tweet.StatusID,
                    ScreenName = tweet.User.ScreenNameResponse,
                    Text = tweet.Text,
                    CurrentUserRetweet = tweet.CurrentUserRetweet,
                    CreatedAt = tweet.CreatedAt,
                    Image = tweet.RetweetedStatus != null && tweet.RetweetedStatus.User != null ?
                            tweet.RetweetedStatus.User.ProfileImageUrl.Replace("http://", "https://") : (tweet.User.ScreenNameResponse == "bwiredstudios" ? "bwired_twitter.jpg" : tweet.User.ProfileImageUrl.Replace("http://", "https://"))
                }).ToList();
                foreach (var tweet in tweets)
                {
                    Tweets.Add(tweet);
                }

                if (Device.OS == TargetPlatform.iOS)
                {
                    // only does anything on iOS, for the Watch
                    DependencyService.Get <ITweetStore>().Save(tweets);
                }
            }
            catch
            {
                error = true;
            }

            if (error)
            {
                var page = new ContentPage();
                await page.DisplayAlert("Error", "Unable to load tweets.", "OK");
            }

            IsBusy = false;
            LoadTweetsCommand.ChangeCanExecute();
        }
Exemplo n.º 31
0
        /// <summary>
        /// ロードしたツイートを追加する
        /// </summary>
        /// <param name="newTweets"></param>
        public void AddTweets(Tweets newTweets)
        {
            Debug.WriteLine("AddTweets");
            bool ageChanged = false;

            foreach (var tweet in this.tweets.Where(x => x.Age < 4))
            {
                tweet.Age++;
                ageChanged = true;
            }

            // 重複チェックして、新着だけ取り出す
            Tweets uniqueTweets = new Tweets();

            foreach (var tweet in newTweets.Where(x => tweets.FindId(x.Id) == null))
            {
                tweet.Age = 0;
                uniqueTweets.Add(tweet);
            }

            // 追加するツイートがある?
            if (uniqueTweets.Count > 0)
            {
                if (tweetsPanel.TopItemIndex > 0)
                {
                    AddNewTweets(uniqueTweets);
                }
                else
                {
                    if (uniqueTweets.Count < tweetsPanel.VisibleTweetCount)
                    {
                        AddNewTweets(uniqueTweets);
                    }
                    else
                    {
                        double stopSec = 1;
                        double divAdd = ((App.Settings.AutoReload - 2) / stopSec);
                        DispatcherTimer dt = new DispatcherTimer();
                        int addCountPerOne = (int)Math.Ceiling(uniqueTweets.Count / Math.Max(1, divAdd));
                        if (addCountPerOne < 1) addCountPerOne = 1;

                        dt.Interval = TimeSpan.FromSeconds(0);
                        dt.Tick += (s, e) =>
                        {
                            dt.Interval = TimeSpan.FromSeconds(stopSec);
                            int oneIdx = Math.Max(0, uniqueTweets.Count - addCountPerOne);
                            int oneCount = Math.Min(addCountPerOne, uniqueTweets.Count);
                            AddNewTweets(uniqueTweets.GetRange(oneIdx, oneCount));
                            uniqueTweets.RemoveRange(oneIdx, oneCount);
                            if (uniqueTweets.Count == 0)
                            {
                                dt.Stop();
                            }
                        };
                        dt.Start();
                    }
                }
            }
            else if (ageChanged)
            {
                // 追加はないけど、Ageが変更された
                tweetsPanel.LayoutTweets(TweetsPanelLayoutMode.Relayout);
            }
            Debug.WriteLine("/AddTweets");
        }