Esempio n. 1
0
        public async Task SendTweetAsync(SendTweetMessage sendTweetMessage)
        {
            var auth = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey      = SettingsHelper.GetEnvironmentVariable("TwitterConsumerKey"),
                    ConsumerSecret   = SettingsHelper.GetEnvironmentVariable("TwitterConsumerSecret"),
                    OAuthToken       = SettingsHelper.GetEnvironmentVariable("TwitterOAuthToken"),
                    OAuthTokenSecret = SettingsHelper.GetEnvironmentVariable("TwitterOAuthTokenSecret")
                }
            };

            await auth.AuthorizeAsync();

            var ctx          = new TwitterContext(auth);
            var tweetMessage = BuildTweet(sendTweetMessage);

            if (sendTweetMessage.EventLocationLatitude > 0 && sendTweetMessage.EventLocationLongitude > 0)
            {
                await ctx.TweetAsync(tweetMessage, sendTweetMessage.EventLocationLatitude, sendTweetMessage.EventLocationLongitude, true);
            }
            else
            {
                await ctx.TweetAsync(tweetMessage);
            }
        }
        protected override Task ProcessRecordAsync()
        {
            if (OAuthToken == null)
            {
                throw new ArgumentNullException(nameof(OAuthToken));
            }
            if (OAuthTokenSecret == null)
            {
                throw new ArgumentNullException(nameof(OAuthTokenSecret));
            }
            if (ConsumerKey == null)
            {
                throw new ArgumentNullException(nameof(ConsumerKey));
            }
            if (ConsumerSecret == null)
            {
                throw new ArgumentNullException(nameof(ConsumerSecret));
            }
            var memoryCredentialStore = new InMemoryCredentialStore {
                ConsumerKey      = ConsumerKey,
                ConsumerSecret   = ConsumerSecret,
                OAuthToken       = OAuthToken,
                OAuthTokenSecret = OAuthTokenSecret
            };
            var authorizer = new SingleUserAuthorizer {
                CredentialStore = memoryCredentialStore
            };

            return(authorizer.AuthorizeAsync().ToObservable()
                   .HandleErrors(this).Select(_ => new TwitterContext(authorizer))
                   .WriteObject(this)
                   .ToTask());
        }
Esempio n. 3
0
        public async Task <Account> GetTwitterAccount(string userId, string screenName)
        {
            if (AnyTwitterAuthenticationSettingsAreNotSet())
            {
                return(null);
            }

            var authTwitter = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey      = twitterAuthenticationSettings.Value.ConsumerKey,
                    ConsumerSecret   = twitterAuthenticationSettings.Value.ConsumerSecret,
                    OAuthToken       = twitterAuthenticationSettings.Value.OAuthToken,
                    OAuthTokenSecret = twitterAuthenticationSettings.Value.OAuthSecret,
                    UserID           = ulong.Parse(userId),
                    ScreenName       = screenName
                }
            };

            await authTwitter.AuthorizeAsync();

            var twitterContext = new TwitterContext(authTwitter);

            //VERY important you explicitly keep the "== true" part of comparison. ReSharper will prompt you to remove this, and if it does, the query will not work
            var account = await(from acct in twitterContext.Account
                                where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true)
                                select acct).SingleOrDefaultAsync();

            return(account);
        }
Esempio n. 4
0
        private void Authorizing()
        {
            Receive <TwitterContext>(twitterContext =>
            {
                Become(() => Connected(twitterContext));
                Stash.UnstashAll();
            });

            ReceiveAny(_ => Stash.Stash());

            async Task <TwitterContext> GetTwitterContext()
            {
                var auth = new SingleUserAuthorizer
                {
                    CredentialStore = new SingleUserInMemoryCredentialStore
                    {
                        ConsumerKey       = _settings.Twitter.ConsumerKey,
                        ConsumerSecret    = _settings.Twitter.ConsumerSecret,
                        AccessToken       = _settings.Twitter.AccessTokenKey,
                        AccessTokenSecret = _settings.Twitter.AccessTokenSecret,
                    },
                };

                await auth.AuthorizeAsync();

                return(new TwitterContext(auth));
            }

            GetTwitterContext().PipeTo(Self);
        }
Esempio n. 5
0
        public async Task <bool> Connect()
        {
            if (this.token != null)
            {
                try
                {
                    SingleUserAuthorizer singleUserAuth = new SingleUserAuthorizer
                    {
                        CredentialStore = new SingleUserInMemoryCredentialStore
                        {
                            ConsumerKey    = TwitterService.ClientID,
                            ConsumerSecret = ChannelSession.SecretManager.GetSecret("TwitterSecret"),

                            AccessToken       = this.token.accessToken,
                            AccessTokenSecret = this.token.refreshToken,

                            UserID     = ulong.Parse(this.token.clientID),
                            ScreenName = this.token.authorizationCode,
                        }
                    };
                    await singleUserAuth.AuthorizeAsync();

                    if (await this.InitializeInternal(singleUserAuth))
                    {
                        return(true);
                    }
                }
                catch (Exception ex) { Logger.Log(ex); }
            }

            try
            {
                PinAuthorizer pinAuth = new PinAuthorizer()
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey    = TwitterService.ClientID,
                        ConsumerSecret = ChannelSession.SecretManager.GetSecret("TwitterSecret"),
                    },
                    GoToTwitterAuthorization = pageLink => Process.Start(pageLink),
                    GetPin = () =>
                    {
                        while (string.IsNullOrEmpty(this.authPin))
                        {
                            Task.Delay(1000).Wait();
                        }
                        return(this.authPin);
                    }
                };

                await pinAuth.AuthorizeAsync();

                this.authPin = null;

                return(await this.InitializeInternal(pinAuth));
            }
            catch (Exception ex) { Logger.Log(ex); }

            return(false);
        }
Esempio n. 6
0
        public override async Task <Result> Connect(OAuthTokenModel token)
        {
            try
            {
                SingleUserAuthorizer singleUserAuthorizer = new SingleUserAuthorizer
                {
                    CredentialStore = new SingleUserInMemoryCredentialStore
                    {
                        ConsumerKey    = TwitterService.ClientID,
                        ConsumerSecret = ChannelSession.Services.Secrets.GetSecret("TwitterSecret"),

                        AccessToken       = token.accessToken,
                        AccessTokenSecret = token.refreshToken,

                        UserID     = ulong.Parse(token.clientID),
                        ScreenName = token.authorizationCode,
                    }
                };

                await singleUserAuthorizer.AuthorizeAsync();

                this.authorizer = singleUserAuthorizer;

                return(await this.InitializeInternal());
            }
            catch (Exception ex)
            {
                Logger.Log(ex);
                return(new Result(ex));
            }
        }
Esempio n. 7
0
        //#########################################################################################################

        protected void AuthorizeContext()
        {
            var credential = new SingleUserInMemoryCredentialStore();

            try
            {
                using (StreamReader sr = new StreamReader(new FileStream("twitterKey.txt", FileMode.Open)))
                {
                    credential.ConsumerKey       = sr.ReadLine();
                    credential.ConsumerSecret    = sr.ReadLine();
                    credential.AccessToken       = sr.ReadLine();
                    credential.AccessTokenSecret = sr.ReadLine();


                    sr.Close();
                }
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("트위터 키 파일을 찾을 수 없습니다.");
            }
            catch (EndOfStreamException)
            {
                Console.WriteLine("트위터 키 파일을 읽을 수 없습니다.");
            }

            var auth = new SingleUserAuthorizer
            {
                CredentialStore = credential,
            };

            auth.AuthorizeAsync().Wait();

            m_twitterCtx = new TwitterContext(auth);
        }
        private async Task <IAuthorizer> AuthAsync()
        {
            if (_authorizer == null)
            {
                var auth = new SingleUserAuthorizer
                {
                    CredentialStore = new SingleUserInMemoryCredentialStore
                    {
                        ConsumerKey       = "i4CpLM6hX3TuR2EGNvAfVOYxT",
                        ConsumerSecret    = "HUm1Vfp4Y1HhKg1hKQrypOHQyOuHohNrYuT6qU2spKS9rJ1YpN",
                        OAuthToken        = "314742868-8K7Fcv7KgaY3WXzr60MLQN9776BLD7z62iuHWkf2",
                        OAuthTokenSecret  = "vmPbZGBQ3wphMHUBM4bXkAW09axy0M8vcGurK1LH4oYli",
                        AccessToken       = "314742868-8K7Fcv7KgaY3WXzr60MLQN9776BLD7z62iuHWkf2",
                        AccessTokenSecret = "vmPbZGBQ3wphMHUBM4bXkAW09axy0M8vcGurK1LH4oYli"
                    }

                    /*
                     * CredentialStore = new InMemoryCredentialStore
                     * {
                     *      ConsumerKey = "i4CpLM6hX3TuR2EGNvAfVOYxT",
                     *      ConsumerSecret = "HUm1Vfp4Y1HhKg1hKQrypOHQyOuHohNrYuT6qU2spKS9rJ1YpN",
                     *      OAuthToken = "314742868-8K7Fcv7KgaY3WXzr60MLQN9776BLD7z62iuHWkf2",
                     *      OAuthTokenSecret = "vmPbZGBQ3wphMHUBM4bXkAW09axy0M8vcGurK1LH4oYli"
                     * }
                     */
                };
                await auth.AuthorizeAsync();

                _authorizer = auth;
            }
            return(_authorizer);
        }
Esempio n. 9
0
        /// <summary>
        /// Authorizes against Twitter.
        /// </summary>
        /// <returns></returns>
        private async Task <IAuthorizer> AuthorizeAsync()
        {
            ServiceEventSource.Current.ServiceMessage(this, "Twitter: Authorizing");
            try
            {
                #region string consumerKey, consumerSecret, accessToken, accessTokenSecret = ...

                string consumerKey       = Environment.GetEnvironmentVariable("TweeterConsumerKey");
                string consumerSecret    = Environment.GetEnvironmentVariable("TweeterConsumerSecret");
                string accessToken       = Environment.GetEnvironmentVariable("TwitterAccessToken");
                string accessTokenSecret = Environment.GetEnvironmentVariable("TwitterAccessTokenSecret");

                if (string.IsNullOrEmpty(consumerKey))
                {
                    var config = this.ServiceInitializationParameters
                                 .CodePackageActivationContext
                                 .GetConfigurationPackageObject("Config")
                                 .Settings.Sections["TwitterCredentials"]
                                 .Parameters;

                    consumerKey       = config["TweeterConsumerKey"]?.Value;
                    consumerSecret    = config["TweeterConsumerSecret"]?.Value;
                    accessToken       = config["TwitterAccessToken"]?.Value;
                    accessTokenSecret = config["TwitterAccessTokenSecret"]?.Value;
                }

                #endregion // string consumerKey, consumerSecret, accessToken, accessTokenSecret = ...

                var auth = new SingleUserAuthorizer()
                {
                    CredentialStore = new SingleUserInMemoryCredentialStore
                    {
                        ConsumerKey       = consumerKey,
                        ConsumerSecret    = consumerSecret,
                        AccessToken       = accessToken,
                        AccessTokenSecret = accessTokenSecret
                    }
                };

                await auth.AuthorizeAsync();

                ServiceEventSource.Current.ServiceMessage(this, "Twitter: Authorized");

                return(auth);
            }
            #region Exception Handling

            catch (Exception ex)
            {
                var id    = Constants.Singleton;
                var proxy = ActorProxy.Create <IImdbFaults>(id);
                await proxy.ReportError($"Twitter Authorization failed: {ex}");

                ServiceEventSource.Current.ServiceHostInitializationFailed(ex);
                throw;
            }

            #endregion // Exception Handling
        }
        /// <summary>
        /// Get mentions in tweet
        /// </summary>
        /// <param name="input"></param>
        /// <param name="logger"></param>
        /// <returns></returns>
        public static GetTweetTaskOutput getMentions(GetTweetsTaskInput input, ILogger logger)
        {
            logger.LogInformation($"Getting mention. Method {nameof(getMentions)}, Time: {DateTime.Now}");

            GetTweetTaskOutput output = new GetTweetTaskOutput()
            {
                IsTweetAvailable = false
            };

            try
            {
                var auth = new SingleUserAuthorizer()
                {
                    CredentialStore = new SingleUserInMemoryCredentialStore()
                    {
                        ConsumerKey       = input.ConsumerKey,
                        ConsumerSecret    = input.ConsumerSecret,
                        AccessToken       = input.AccessToken,
                        AccessTokenSecret = input.AccessTokenSecret
                    },
                };

                auth.AuthorizeAsync().Wait();
                var twitterCtx = new TwitterContext(auth);

                //var tweets =
                //     await
                //     (from tweet in twitterCtx.Status
                //      where tweet.Type == StatusType.Mentions &&
                //      tweet.Count == input.Count
                //      select tweet)
                //     .ToListAsync();

                var tweets = (from t in twitterCtx.Status
                              where t.Type == StatusType.Mentions &&
                              t.Count == input.Count
                              select t).ToList();

                foreach (var tweet in tweets)
                {
                    output.LatestTweetId = tweet.StatusID.ToString();

                    logger.LogInformation($"Mention Id: {tweet.StatusID}");

                    output.IsTweetAvailable = true;
                }

                logger.LogInformation($"Exit method {nameof(getMentions)}");

                //Task.Delay(15000).Wait();
            }
            catch (Exception ex)
            {
                logger.LogWarning($"{ex.Message}");
            }

            return(output);
        }
Esempio n. 11
0
        public async Task Run(
            [ServiceBusTrigger(Constants.QUEUE_TWITTER, Connection = "ServicebusQueueConnectionString")]
            SendTweetMessage sendTweetMessage, ILogger log)
        {
            var auth = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey      = GetEnvironmentVariable("TwitterConsumerKey"),
                    ConsumerSecret   = GetEnvironmentVariable("TwitterConsumerSecret"),
                    OAuthToken       = GetEnvironmentVariable("TwitterOAuthToken"),
                    OAuthTokenSecret = GetEnvironmentVariable("TwitterOAuthTokenSecret")
                }
            };

            await auth.AuthorizeAsync();

            var ctx = new TwitterContext(auth);
            var tweetMessageBuilder = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(sendTweetMessage.TwitterHandle))
            {
                var twitterHandle = sendTweetMessage.TwitterHandle;
                if (!twitterHandle.StartsWith('@'))
                {
                    twitterHandle = "@" + twitterHandle;
                }
                tweetMessageBuilder.AppendLine($"\U0001F4E2 New CFP: {sendTweetMessage.EventName} ({twitterHandle}) ");
            }
            else
            {
                tweetMessageBuilder.AppendLine($"\U0001F4E2 New CFP: {sendTweetMessage.EventName}");
            }

            tweetMessageBuilder.AppendLine($"\U000023F3 Closes: {sendTweetMessage.CfpEndDate.ToLongDateString()}");
            if (sendTweetMessage.EventStartDate != default && sendTweetMessage.EventStartDate.Date == sendTweetMessage.EventEndDate.Date)
            {
                tweetMessageBuilder.AppendLine($"\U0001F5D3 Event: {sendTweetMessage.EventStartDate:MMM dd}");
            }
            else if (sendTweetMessage.EventStartDate != default)
            {
                tweetMessageBuilder.AppendLine($"\U0001F5D3 Event: {sendTweetMessage.EventStartDate:MMM dd} - {sendTweetMessage.EventEndDate:MMM dd}");
            }

            tweetMessageBuilder.AppendLine($"#cfp #cfpexchange {sendTweetMessage.UrlToCfp}");
            var tweetMessage = tweetMessageBuilder.ToString();

            log.LogInformation(tweetMessage);
            if (!GetEnvironmentVariable("AZURE_FUNCTIONS_ENVIRONMENT").Equals("Development"))
            {
                // TODO substringing is not the best thing, but does the trick for now
                await ctx.TweetAsync(tweetMessage.Length > 280?tweetMessage.Substring(0, 280) : tweetMessage,
                                     sendTweetMessage.EventLocationLatitude, sendTweetMessage.EventLocationLongitude, true);
            }
        }
Esempio n. 12
0
        public TwitterUserProvider()
        {
            _authorizer = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey       = "",
                    ConsumerSecret    = "",
                    AccessToken       = "",
                    AccessTokenSecret = ""
                }
            };

            _authorizer.AuthorizeAsync();
        }
Esempio n. 13
0
        public async Task authorize()
        {
            var auth = new SingleUserAuthorizer()
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey       = config.Value.consumerKey,
                    ConsumerSecret    = config.Value.consumerSecretKey,
                    AccessToken       = config.Value.accessToken,
                    AccessTokenSecret = config.Value.accessTokenSecret
                }
            };

            await auth.AuthorizeAsync();

            twitterContext = new TwitterContext(auth);
        }
Esempio n. 14
0
        private static async Task <IAuthorizer> AuthorizeAsync()
        {
            var         settings = Config.GetSection("Twitter");
            IAuthorizer oauth    = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey      = settings["ConsumerKey"],
                    ConsumerSecret   = settings["ConsumerSecret"],
                    OAuthToken       = settings["AccessToken"],
                    OAuthTokenSecret = settings["AccessTokenSecret"]
                }
            };

            await oauth.AuthorizeAsync();

            return(oauth);
        }
Esempio n. 15
0
        /// <summary>
        /// Logs into the Twitter service provider and authenticates bloon via the keys stored in the DB.
        /// </summary>
        public async void Authenticate()
        {
            // Keys and secrets could be moved to an external config file
            SingleUserAuthorizer auth = new SingleUserAuthorizer
            {
                CredentialStore = new InMemoryCredentialStore()
                {
                    ConsumerKey      = Environment.GetEnvironmentVariable("TWITTER_CONSUMER_KEY"),
                    ConsumerSecret   = Environment.GetEnvironmentVariable("TWITTER_CONSUMER_SECRET"),
                    OAuthToken       = Environment.GetEnvironmentVariable("TWITTER_OAUTH_TOKEN"),
                    OAuthTokenSecret = Environment.GetEnvironmentVariable("TWITTER_OAUTH_TOKEN_SECRET"),
                },
            };

            await auth.AuthorizeAsync();

            this.ctx = new TwitterContext(auth);
        }
Esempio n. 16
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Get tweets!");

            var auth = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore()
                {
                    ConsumerKey       = TwitterConsumerKey,
                    ConsumerSecret    = TwitterConsumerSecret,
                    AccessToken       = TwitterAccessToken,
                    AccessTokenSecret = TwitterAccessTokenSecret
                }
            };
            await auth.AuthorizeAsync();

            var twitterCtx = new TwitterContext(auth);
            var tweets     = await twitterCtx.GetTweets("cloudbrew");

            var credentials = new ApiKeyServiceClientCredentials(CognitiveServicesKey);
            var client      = new TextAnalyticsClient(credentials)
            {
                Endpoint = CognitiveServicesEndpoint
            };

            foreach (var t in tweets)
            {
                var sentiment = await client.SentimentAsync(t.FullText, t.Lang);

                Console.WriteLine($"ID   : {t.StatusID}");
                Console.WriteLine($"User : {t.User.Name}");
                Console.WriteLine($"Text : {t.FullText}");
                Console.WriteLine($"Score: {sentiment.Score:0.00}");

                if (sentiment.Score > 0.5)
                {
                    await twitterCtx.Retweet(t.StatusID);

                    Console.WriteLine("Retweeted!");
                }
            }
            Console.WriteLine("End");
            Console.ReadLine();
        }
Esempio n. 17
0
        public async Task InitTweetsByGeoLocation(double lat = 0, double lng = 0, int radious = 5, string searchTerm = "@")
        {
            var auth = new SingleUserAuthorizer()
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey      = "dkYmFF7c4dLXaUXpalKKzItcG",
                    ConsumerSecret   = "XPPPJpSNEIbUErbe6Aaw4VMENsrH2NtOLl2J9Wus0zXy3dklBI",
                    OAuthToken       = "192372509-7mYW4GXDwZaTyzc7LFGFw8NfKC1T9OrGDUyqhrka",
                    OAuthTokenSecret = "MK1Tj4xKcnvd86MdvBLqh53H5qQXlEfsPQeTJtQ2WE1gv",
                    UserID           = 192372509
                }
            };

            string geoCode = $"{lat},{lng},{radious}km";

            await auth.AuthorizeAsync();

            var ctx = new TwitterContext(auth);

            var searchResponse = await(from search in ctx.Search
                                       where search.Type == SearchType.Search &&
                                       search.Query == searchTerm &&
                                       search.GeoCode == geoCode &&
                                       //search.IncludeEntities == true &&
                                       search.Count == 200
                                       select search).SingleOrDefaultAsync();


            Tweets = (from tweet in searchResponse.Statuses
                      where tweet?.Entities?.MediaEntities?.FirstOrDefault()?.MediaUrl != null
                      select new Tweet
            {
                StatusId = tweet.StatusID,
                ScreenName = tweet.User.ScreenNameResponse,
                Text = tweet.Text,
                ImageUrl = tweet.User.ProfileImageUrl,
                MediaUrl = tweet.Entities.MediaEntities.FirstOrDefault().MediaUrl
            }).ToList();
        }
Esempio n. 18
0
        private static async Task SetupTwitterClient()
        {
            SingleUserAuthorizer authorizer = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey       = "",
                    ConsumerSecret    = "",
                    AccessToken       = "",
                    AccessTokenSecret = ""
                }
            };
            await authorizer.AuthorizeAsync();

            _twitterCtx = new TwitterContext(authorizer);

            //Get recipients who have already recieved auto DM
            var sentMessages = await(from dm in _twitterCtx.DirectMessage
                                     where dm.Type == DirectMessageType.SentBy &&
                                     dm.Text.Contains("Replying:")
                                     select dm.RecipientID).ToListAsync();
            //Get DMs recieved
            var recievedMessages = await(from dm in _twitterCtx.DirectMessage
                                         where dm.Type == DirectMessageType.SentTo
                                         select dm).ToListAsync();

            //Get DMs that have NOT recieved an auto DM
            var replyQueue = (from x in recievedMessages
                              where !sentMessages.Contains(x.SenderID)
                              select x);

            // Console.WriteLine("Auto messages sent: " + sentMessages.Count + " Messages Recieved: " + recievedMessages.Count + " Auto messages to queue: " + replyQueue.ToList().Count);

            foreach (var item in replyQueue)
            {
                var message = await _twitterCtx.NewDirectMessageAsync(item.SenderID, "Replying: " + DateTime.Now + "!'");
            }
        }
        private async void Btn_Twitter_Login_Click(object sender, RoutedEventArgs e)
        {
            if (SharedState.Authorizer == null)
            {
                var auth = new SingleUserAuthorizer
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey      = "MsLLdIN5d4tGig1mIOd544sre",
                        ConsumerSecret   = "ZPHLC05kp0wt2ZZMYPsCPMrLlhe7bXIPgHP2BaK2PHoMSl8OWR",
                        OAuthToken       = "730162950-GA2MJy8n6vqwstq2ZgCaU3fe5JzZjAi8bOKXN9sN",
                        OAuthTokenSecret = "ss5yUNU1RwXws2iuQMFZ77pC97r6smuoNO5e0pm8d6xux"
                    },
                };

                await auth.AuthorizeAsync();

                SharedState.Authorizer = auth;

                this.Btn_Twitter_Login.Content = "Logout";
                MessageDialogHelper.Show("Twitter Login successfully");
            }
        }
Esempio n. 20
0
        private async Task PostNewCfpTweet(Cfp cfpToAdd)
        {
            var auth = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey      = _configuration["TwitterConsumerKey"],
                    ConsumerSecret   = _configuration["TwitterConsumerSecret"],
                    OAuthToken       = _configuration["TwitterOAuthToken"],
                    OAuthTokenSecret = _configuration["TwitterOAuthTokenSecret"]
                }
            };

            await auth.AuthorizeAsync();

            var ctx = new TwitterContext(auth);

            var tweetMessageBuilder = new StringBuilder();

            if (!string.IsNullOrWhiteSpace(cfpToAdd.EventTwitterHandle))
            {
                var twitterHandle = cfpToAdd.EventTwitterHandle;

                if (!twitterHandle.StartsWith('@'))
                {
                    twitterHandle = "@" + twitterHandle;
                }

                tweetMessageBuilder.AppendLine($"\U0001F4E2 New CFP: {cfpToAdd.EventName} ({twitterHandle}) ");
            }
            else
            {
                tweetMessageBuilder.AppendLine($"\U0001F4E2 New CFP: {cfpToAdd.EventName}");
            }

            tweetMessageBuilder.AppendLine($"\U000023F3 Closes: {cfpToAdd.CfpEndDate.ToLongDateString()}");

            if (cfpToAdd.EventStartDate != default(DateTime) && cfpToAdd.EventStartDate.Date == cfpToAdd.EventEndDate.Date)
            {
                tweetMessageBuilder.AppendLine($"\U0001F5D3 Event: {cfpToAdd.EventStartDate.ToString("MMM dd")}");
            }
            else if (cfpToAdd.EventStartDate != default(DateTime))
            {
                tweetMessageBuilder.AppendLine($"\U0001F5D3 Event: {cfpToAdd.EventStartDate.ToString("MMM dd")} - {cfpToAdd.EventEndDate.ToString("MMM dd")}");
            }

            tweetMessageBuilder.AppendLine($"#cfp #cfpexchange {Url.Action("details", "cfp", new { id = cfpToAdd.Id }, " https ", " cfp.exchange ")}");

            var tweetMessage = tweetMessageBuilder.ToString();

            if (_hostingEnvironment.IsProduction())
            {
                // TODO substringing is not the best thing, but does the trick for now
                await ctx.TweetAsync(tweetMessage.Length > 280?tweetMessage.Substring(0, 280) : tweetMessage,
                                     (decimal)cfpToAdd.EventLocationLat, (decimal)cfpToAdd.EventLocationLng, true);
            }
            else
            {
                Debug.WriteLine(tweetMessage);
            }
        }
Esempio n. 21
0
        public static async Task Main(string[] args)
        {
            // Bootstrap the app
            var builder = new ConfigurationBuilder()
                          .AddJsonFile("appsettings.json")
                          .AddJsonFile("appsettings.Development.json", optional: true)
                          .AddEnvironmentVariables()
                          .AddConfigServer();

            Configuration = builder.Build();

            var factory = new LoggerFactory();

            factory.AddConsole(Configuration.GetSection("Logging"));

            var services = new ServiceCollection()
                           .AddDiscoveryClient(Configuration)
                           .AddOptions()
                           .BuildServiceProvider();

            TwitterCredentials twitterCreds = new TwitterCredentials();

            Configuration.GetSection("Twitter").Bind(twitterCreds);

            var auth = new SingleUserAuthorizer
            {
                CredentialStore = new InMemoryCredentialStore
                {
                    ConsumerKey      = twitterCreds.ConsumerKey,
                    ConsumerSecret   = twitterCreds.ConsumerSecret,
                    OAuthToken       = twitterCreds.AccessToken,
                    OAuthTokenSecret = twitterCreds.AccessTokenSecret
                }
            };
            await auth.AuthorizeAsync();

            var   ctx     = new TwitterContext(auth);
            ulong sinceId = 1;

            // next line Fails, not able to resolve IOptionsMonitor<EurekaClientOptions>
            var discoveryClient = services.GetRequiredService <IDiscoveryClient>();
            DiscoveryHttpClientHandler _handler = new DiscoveryHttpClientHandler(discoveryClient, factory.CreateLogger <DiscoveryHttpClientHandler>());
            var httpClient = new HttpClient(_handler, false);

            // begin monitoring
            Console.WriteLine("Entering the loop...");
            while (true)
            {
                string searchTerm = Configuration.GetValue <string>("twitterSearch");
                Console.WriteLine($"Checking for 10 tweets with query '{searchTerm}'");

                List <Status> searchResponse =
                    await(from s in ctx.Search where s.Query == searchTerm && s.Type == SearchType.Search && s.IncludeEntities == true && s.TweetMode == TweetMode.Extended && s.SinceID == sinceId && s.Count == 10 select s.Statuses).SingleOrDefaultAsync();

                if (searchResponse.Any())
                {
                    sinceId = searchResponse.Max(s => s.StatusID);
                    var texts = searchResponse.Select(t => t.FullText);
                    Console.WriteLine($"Found {texts.Count()} tweets");
                    foreach (var t in texts)
                    {
                        Console.WriteLine(t);
                    }

                    // post to web api
                    var apiResponse = await httpClient.PostAsync("http://SmartBulbs-Web/home/bulktext", new StringContent(JsonConvert.SerializeObject(texts), Encoding.UTF8, "application/json"));

                    if (apiResponse.IsSuccessStatusCode)
                    {
                        var responseBody = await apiResponse.Content.ReadAsJsonAsync <ColorChangeResponse>();

                        Console.WriteLine($"Aggregate sentiment value was {responseBody.Sentiment} which translates to #{responseBody.HexColor}");
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"Request failed, status code: {apiResponse.StatusCode}");
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                }
                else
                {
                    Console.WriteLine("No new tweets found");
                }
                Thread.Sleep(Configuration.GetValue <int>("sleepTime"));
            }
        }
Esempio n. 22
0
 public async Task Authorize()
 {
     await auth.AuthorizeAsync();
 }
Esempio n. 23
0
        public async Task <IActionResult> Get()
        {
            try
            {
                var auth = new SingleUserAuthorizer
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey      = _twitterCreds.ConsumerKey,
                        ConsumerSecret   = _twitterCreds.ConsumerSecret,
                        OAuthToken       = _twitterCreds.AccessToken,
                        OAuthTokenSecret = _twitterCreds.AccessTokenSecret
                    }
                };
                await auth.AuthorizeAsync();

                var ctx = new TwitterContext(auth);
                if (auth == null)
                {
                }
                string searchTerm = _twitterSearchTerm;

                Search searchResponse =
                    await
                        (from search in ctx.Search
                        where search.Type == SearchType.Search &&
                        search.ResultType == ResultType.Recent &&
                        search.Query == searchTerm &&
                        search.IncludeEntities == true &&
                        search.TweetMode == TweetMode.Extended &&
                        search.Count == 10 &&
                        search.SinceID == sinceId
                        select search)
                    .SingleOrDefaultAsync();

                if (!searchResponse.Statuses.Any())
                {
                    return(Json(new TweetListWithSentiment
                    {
                        Tweets = new List <EnhancedTwitterStatus>()
                    }));
                }
                var subset = searchResponse.Statuses.OrderBy(o => o.StatusID) /*.Take(2)*/;
                sinceId = subset.Max(i => i.StatusID);
                var texts    = subset.Select(t => t.FullText);
                var analyzed = await _utils.GetColorAndSentimentFromText(texts);

                var aggScore = analyzed.Average(r => r.Sentiment);

                var toReturn = new TweetListWithSentiment {
                    Tweets         = new List <EnhancedTwitterStatus>(),
                    AggregateScore = aggScore,
                    AggregateColor = _utils.HexColorFromDouble(aggScore)
                };
                var hystrixOptions = new HystrixCommandOptions(HystrixCommandKeyDefault.AsKey("SetColor"))
                {
                    GroupKey = HystrixCommandGroupKeyDefault.AsKey("SetColorGroup"),
                    ExecutionTimeoutEnabled = false
                };
                SetColorCommand command = new SetColorCommand(hystrixOptions, _lifxKey, toReturn.AggregateColor);
                await command.ExecuteAsync();

                foreach (var status in subset.Select((value, i) => new { i, value }))
                {
                    var s        = status.value;
                    var analysis = analyzed.Find(a => a.TextInput == s.FullText);
                    toReturn.Tweets.Add(new EnhancedTwitterStatus
                    {
                        FullText       = s.FullText,
                        CreatedAt      = s.CreatedAt,
                        User           = s.User,
                        SentimentValue = analysis.Sentiment,
                        HexColor       = analysis.HexColor
                    });
                }

                return(Json(toReturn));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 24
0
        private async void Login_Click(object sender, RoutedEventArgs e)
        {
            this.myProgressRing.Visibility = Visibility.Visible;


            if (SharedState.Authorizer == null)
            {
                var auth = new SingleUserAuthorizer
                {
                    CredentialStore = new InMemoryCredentialStore
                    {
                        ConsumerKey      = "MsLLdIN5d4tGig1mIOd544sre",
                        ConsumerSecret   = "ZPHLC05kp0wt2ZZMYPsCPMrLlhe7bXIPgHP2BaK2PHoMSl8OWR",
                        OAuthToken       = "730162950-GA2MJy8n6vqwstq2ZgCaU3fe5JzZjAi8bOKXN9sN",
                        OAuthTokenSecret = "ss5yUNU1RwXws2iuQMFZ77pC97r6smuoNO5e0pm8d6xux"
                    },
                };

                await auth.AuthorizeAsync();

                SharedState.Authorizer = auth;

//              var xauth = new XAuthAuthorizer
//              {
//                  CredentialStore = new XAuthCredentials
//                  {
//                      ConsumerKey = "MsLLdIN5d4tGig1mIOd544sre",
//                      ConsumerSecret = "ZPHLC05kp0wt2ZZMYPsCPMrLlhe7bXIPgHP2BaK2PHoMSl8OWR",
//                      UserName = "******",
//                      OAuthTokenSecret = "thanhdat1234"
//                  },
//              };
//              await xauth.AuthorizeAsync();
//              SharedState.Authorizer = xauth;
            }



            //////////
            var twitterCtx = new TwitterContext(SharedState.Authorizer);

            var timelineResponse =
                await
                    (from tweet in twitterCtx.Status
                    where tweet.Type == StatusType.Home
                    select tweet)
                .ToListAsync();


            Tweets =
                (from tweet in timelineResponse
                 select new Tweet
            {
                Name = tweet.User.ScreenNameResponse,
                Text = tweet.Text,
                ImageUrl = tweet.User.ProfileImageUrl
            })
                .ToList();

//          foreach (var tw in Tweets)
//              tessss.Text += tw.Text + "\r\n";

            newFeedList.ItemsSource = Tweets;

            this.myProgressRing.Visibility = Visibility.Collapsed;
        }
Esempio n. 25
0
        public async Task <ActionResult> ExternalTWLoginCallback(string returnUrl)
        {
            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }

            ClaimsIdentity ext = await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);

            var AccessToken = "";


            foreach (Claim clm in ext.Claims)
            {
                if (clm.Type == "urn:twitter:access_token")
                {
                    AccessToken = clm.Value;
                }
            }

            var authTwitter = new SingleUserAuthorizer
            {
                CredentialStore = new SingleUserInMemoryCredentialStore
                {
                    ConsumerKey      = "CluAp7CCaoCjUMPGqa0TVTUYP",
                    ConsumerSecret   = "ZhnOhatYS9Z0EyMbCARzWnzfAsghMJSBe47QORldg7ZRdGjS1Y",
                    OAuthToken       = "2685481184-pvADYhwEjtiHb4jBLuIW4V0N3XMs7k5mq6TEXX4",
                    OAuthTokenSecret = "lujvWMbFC2Nt9CGO4zvAg6U6IVPY1If0bGv60VcB4E9zA",
                    UserID           = ulong.Parse(loginInfo.Login.ProviderKey),
                    ScreenName       = loginInfo.DefaultUserName
                }
            };

            await authTwitter.AuthorizeAsync();

            var twitterCtx     = new TwitterContext(authTwitter);
            var verifyResponse =
                await
                    (from acct in twitterCtx.Account
                    where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true)
                    select acct).SingleOrDefaultAsync();
            dynamic me = verifyResponse.User;


            if (me.Email == null)
            {
                return(RedirectToAction("Login"));
            }

            var appUser = await userManager.FindByEmailAsync(me.Email);

            if (appUser == null)
            {
                AppUserModel appuser = new AppUserModel();
                appuser.emailAddress      = me.Email;
                appuser.firstName         = me.ScreenNameResponse;
                appuser.UserName          = me.Email;
                appuser.Email             = me.Email;
                appuser.EmailConfirmed    = true;
                appuser.accountExpireDate = DateTime.Now.AddMonths(3).ToShortDateString();
                appuser.companyName       = "Unknown";
                var result = await userManager.CreateAsync(appuser);

                appuser = await userManager.FindByEmailAsync(appuser.emailAddress);

                await userManager.AddToRolesAsync(appuser.Id, AppConsts.AppRoles.FREEMIUM.ToString());
                await SignIn(appuser, false);
            }
            else
            {
                await SignIn(appUser, false);
            }

            return(RedirectToAction("dashboard", "user"));
        }