Exemplo n.º 1
0
        /// <summary>
        /// This method tries to retrieve world top headlines
        /// </summary>
        /// <returns>List of Articles</returns>
        public static async Task <List <Article> > GetWorldTopHeadlines(int page = 1)
        {
            List <Article> articles = null;

            try
            {
                var articlesResponse = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
                {
                    Page     = page,
                    PageSize = 50,
                    Language = Languages.EN // Switch language to your preference
                });

                if (articlesResponse.Status == Statuses.Ok)
                {
                    return(articlesResponse.Articles);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return(articles);
        }
Exemplo n.º 2
0
        public async Task <ArticlesResult> GetHeadlinesByCountryOrCategoryAsync(Countries?country, Categories?category, string topic, Languages?language)
        {
            var request = new TopHeadlinesRequest();

            request.Country  = country;
            request.Category = category;
            request.Language = language;
            if (!string.IsNullOrEmpty(topic) && !string.IsNullOrWhiteSpace(topic))
            {
                request.Q = topic;
            }
            var response = await newsApiClient.GetTopHeadlinesAsync(request);

            return(response);
        }
        public async Task <List <Article> > GetHeadlines(NewsAPI.Constants.Countries country, int size = 25)
        {
            var output = new List <Article>();

            var tmp = new NewsAPI.Models.TopHeadlinesRequest {
                Country = country, Language = NewsAPI.Constants.Languages.EN, PageSize = size
            };

            var response = await webAPI.GetTopHeadlinesAsync(tmp);

            foreach (var article in response.Articles)
            {
                output.Add(new Article(article.Title, article.Description, article.Url));
            }

            return(output);
        }
Exemplo n.º 4
0
        /// <summary>
        /// This method tries to retrieve world top headlines
        /// </summary>
        /// <returns>List of Articles</returns>
        public static async Task <List <Models.Article> > GetWorldTopHeadlines(int page = 1)
        {
            articles = new List <Models.Article>();

            try
            {
                var articlesResponse = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
                {
                    Sources  = HeadlinesNewsSources,
                    Page     = page,
                    PageSize = 50,
                    Language = Languages.EN // Switch language to your preference
                });

                if (articlesResponse.Status == Statuses.Ok)
                {
                    articlesResponse.Articles.Reverse();

                    foreach (var article in articlesResponse.Articles)
                    {
                        var postition = articlesResponse.Articles.IndexOf(article);

                        articles.Add(new Models.Article
                        {
                            Author      = article.Author,
                            Description = article.Description,
                            PublishedAt = article.PublishedAt,
                            Source      = $"Source: {article.Source.Name} ",
                            Title       = article.Title,
                            Url         = article.Url,
                            UrlToImage  = article.UrlToImage,
                            IsWideView  = IsWideView(postition)
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }

            return(articles);
        }
        /// <summary>
        /// Get the current top headlines.
        /// </summary>
        /// <param name="maxResults">Limit results to this number (Max 100).</param>
        /// <param name="query">Specify a specific search query. Use null to get all.</param>
        /// <returns>A list of articles</returns>
        public async Task <List <Article> > GetTopHeadlines(int maxResults = 100, string query = null)
        {
            if (maxResults > 100)
            {
                return(new List <Article>());
            }
            ArticlesResult response = await Client.GetTopHeadlinesAsync(new TopHeadlinesRequest()
            {
                Country  = Countries.GB,
                PageSize = maxResults,
                Language = Languages.EN,
                Q        = query
            });

            if (response.Status == Statuses.Ok)
            {
                return(response.Articles);
            }
            return(new List <Article>());
        }
        private static async Task <ArticlesResult> getNewsBySource(Module module)
        {
            NewsApiClient newsApiClient = new NewsApiClient(Api.ApiKeys[ApiEnum.NEWSAPI]);

            ArticlesResult topheadlines = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
            {
                Language = module.NewsLanguage,
                Sources  = module.NewsSources
            });

            return(topheadlines);
        }
Exemplo n.º 7
0
        public override async Task Poll()
        {
            var news = await _newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest()
            {
                PageSize = Config.PageSize,
                Sources  = Config.Sources.Count > 0 ? Config.Sources : null,
                Language = _newsLanguage
            });

            if (news.Status == Statuses.Ok)
            {
            }
        }
        private static async Task <ArticlesResult> getNewsByCategory(Module module)
        {
            NewsApiClient newsApiClient = new NewsApiClient(Api.ApiKeys[ApiEnum.NEWSAPI]);

            ArticlesResult topheadlines = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
            {
                Category = module.NewsCategory,
                Country  = module.NewsCountry,
                Language = module.NewsLanguage
            });

            return(topheadlines);
        }
Exemplo n.º 9
0
        private void Service()
        {
            Receive <T>((msg =>
            {
                _everythingRequest = msg.TopHeadlinesRequest;
            }));

            Receive <FetchNews>(fetch =>
            {
                _client.GetTopHeadlinesAsync(_everythingRequest).ContinueWith((res) => new NewsResult(_everythingRequest.Q, res.Result)).PipeTo(_responseProcessActor);
                Self.Tell(PoisonPill.Instance);
            });
        }
Exemplo n.º 10
0
        private async void button1_Click(object sender, EventArgs e)
        {
            label1.Text = label1.Text + "\nButton Clicked";

            TopHeadlinesRequest request = GenerateHeadlinesRequest();
            var response = await APIn.GetTopHeadlinesAsync(request);

            label1.Text += label1.Text + "\nResponse recieved";

            if (response.Status == Statuses.Ok)
            {
                Console.WriteLine("Responses: " + response.TotalResults);
                label1.Text += ("Responses: " + response.TotalResults);

                foreach (var article in response.Articles)
                {
                    /*
                     * Console.WriteLine("Title: {0} - ({1})", article.Title, article.PublishedAt);
                     * Console.WriteLine("Author: {0}", article.Author);
                     * Console.WriteLine("Description: {0}", article.Description);
                     */

                    string txt = "";
                    txt += "Title: " + article.Title;
                    txt += "\nPublished: " + article.PublishedAt;
                    txt += "\nAuthor: " + article.Author;
                    txt += "\nDescription: " + article.Description;
                    txt += "\nSource: " + article.Source.Name + "\n\n";

                    TextBox.Text += txt;


                    if (article.Title.Length > 5)
                    {
                        Headlines.Add(article.Title);
                    }
                }
            }
            else
            {
                label1.Text = label1.Text + "\nError fetching data" + response.Error.Code;
                label1.Text = label1.Text + "\n\t" + response.Error.Message;

                TextBox.Text = label1.Text + "\nError fetching data" + response.Error.Code;
                TextBox.Text = label1.Text + "\n\t" + response.Error.Message;
            }


            label1.Text = label1.Text + "\nButton push end";
        }
Exemplo n.º 11
0
        private async Task <ArticlesResult> GetLatestNewsFromApi(Categories category, int page = 1)
        {
            var       newsApiClient = new NewsApiClient("8a4d40be944c4dbeb2d365c05cfe3eab");
            const int pageSize      = 10;

            ArticlesResult newsResponse = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
            {
                Category = category,
                Page     = page,
                PageSize = pageSize,
                Country  = Countries.US
            });

            return(newsResponse);
        }
Exemplo n.º 12
0
        public async Task <ArticlesResult> GetTopHeadlines(int countryId)
        {
            var            newsApiClient    = new NewsApiClient(ApiKey);
            ArticlesResult articlesResponse = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
            {
                Country = (Countries)countryId
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                return(articlesResponse);
            }

            return(null);
        }
Exemplo n.º 13
0
        private async Task <IList <Article> > GetTopNewsAsync()
        {
            // init with your API key
            var newsApiClient    = new NewsApiClient(_iConfig.GetValue <string>("ExternalApiURLs:NewsAPIKey"));
            var articlesResponse = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
            {
                Country  = Countries.US,
                PageSize = 10,
                Page     = 1
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                return(articlesResponse.Articles);
            }
            return(null);
        }
Exemplo n.º 14
0
        public async Task <IActionResult> GetNewsTopheadlines([FromQuery] TopHeadlinesRequest topHeadlinesRequest)
        {
            var invokingUser = int.Parse(User.FindFirst(claim => claim.Type == ClaimTypes.NameIdentifier).Value);

            var newsApiClient    = new NewsApiClient(_configuration.GetSection("ApiKey").Value);
            var articlesResponse = await newsApiClient.GetTopHeadlinesAsync(topHeadlinesRequest);

            if (articlesResponse.Status == Statuses.Ok)
            {
                var queryObject = _mapper.Map <TopHeadlinesRequest, QueryObjectTopHeadLinesRequest>(topHeadlinesRequest);
                await _repository.PostQueryObjectTopHeadLinesRequestAsync(invokingUser, queryObject);

                var articlesResponseDto = _mapper.Map <ArticlesResult, ArticlesResultViewModel>(articlesResponse);
                return(Ok(articlesResponseDto));
            }

            return(BadRequest(articlesResponse.Error.Message));
        }
Exemplo n.º 15
0
        public static async Task <ArticlesResult> RetrieveNewsAsync(String api_key)
        {
            var newsApiClient = new NewsApiClient(api_key);

            var articlesResponse = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest()
            {
                Language = Languages.EN,
                PageSize = 20
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                return(articlesResponse);
            }
            else
            {
                throw new Exception(articlesResponse.Error.Message);
            }
        }
Exemplo n.º 16
0
        private async Task LoadNewsAsync()
        {
            var newsApiClient    = new NewsApiClient(NewsApiKey);
            var articlesResponse = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
            {
                Q        = "covid",
                Page     = 1,
                PageSize = 40,
                Country  = Countries.IN,
                Language = Languages.EN,
            });

            if (articlesResponse.Status == Statuses.Ok)
            {
                News = new CovidNews()
                {
                    Articles     = articlesResponse.Articles,
                    TotalResults = articlesResponse.TotalResults
                };
            }
        }
Exemplo n.º 17
0
        public static async Task <List <Article> > GetArticlesAsync(string country)
        {
            // Initialise with the provided API KEY
            var newsApiClient = new NewsApiClient("4c4048f805584bf5996487f8c7a24e3c");
            var countryAPI    = Countries.GB; // Great Britain by default

            // Check if passed country matches any of the countries listed
            // And convert it to enum
            if (!string.IsNullOrEmpty(country))
            {
                var arr = Enum.GetNames(typeof(Countries));

                foreach (var c in arr)
                {
                    if (c.Equals(country))
                    {
                        Enum.TryParse(country, out Countries match);
                        countryAPI = match;
                    }
                }
            }

            // Make the request for top headlines
            var articlesResponse = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
            {
                Country  = countryAPI,
                Language = Languages.EN,
            });


            // If OK return articles
            if (articlesResponse.Status.Equals(Statuses.Ok))
            {
                return(articlesResponse.Articles);
            }

            return(null);
        }
Exemplo n.º 18
0
        public async Task <ArticlesResult> GetAll(string query)
        {
            // get user settings, this should be using the current user Id in the future
            UserSettings settings = await userSettingsService.Get();

            ArticlesResult articlesResponse;

            if (query == null)
            {
                // We get the top headlines according to the user settings
                articlesResponse = await newsApi.GetTopHeadlinesAsync(new TopHeadlinesRequest {
                    Sources  = settings.SourcesIds.Split(',').ToList(),
                    Language = (Languages)Enum.Parse(typeof(Languages), settings.LanguageCd.ToUpper()),
                    Page     = settings.Page,
                    PageSize = settings.PageSize
                });
            }
            else
            {
                articlesResponse = await newsApi.GetEverythingAsync(new EverythingRequest {
                    Q        = query,
                    Sources  = settings.SourcesIds.Split(',').ToList(),
                    SortBy   = settings.SortBy,
                    Language = (Languages)Enum.Parse(typeof(Languages), settings.LanguageCd.ToUpper()),
                    From     = new DateTime(2018, 1, 25)
                });
            }



            if (articlesResponse.Status == Statuses.Error)
            {
                // handle error
                return(null);
            }

            return(articlesResponse);
        }
Exemplo n.º 19
0
        public static async Task <IEnumerable <ArticleViewModel> > TopNews(string country)
        {
            try
            {
                var cont    = Enum.Parse <Countries>(country.ToUpper());
                var topNews = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest()
                {
                    Country  = cont,
                    PageSize = 100
                });

                var list = topNews.Articles.MapToListArticleViewModel();
                return(list);
            }
            catch (ArgumentNullException)
            {
                throw new ArgumentNullException();
            }
            catch (Exception)
            {
                throw new InvalidOperationException();
            }
        }
Exemplo n.º 20
0
        public static async Task <IEnumerable <Article> > GetArticlesAsync(TopHeadlinesRequest request)
        {
            var articles = await client.GetTopHeadlinesAsync(request);

            return(articles.Articles.AsEnumerable());
        }
Exemplo n.º 21
0
    // Use this for initialization
    async void Start()
    {
        TailoredRepository = GetComponentInChildren <TailoredRepository>();

        dF = new Dictionary <string, int>();

        _conceptNet = new ConceptNetWrapper("http://api.conceptnet.io/");

        //TODO: should have a variety of catgs:  business entertainment general health science sports technology

        // init with your API key (get this from newsapi.org)
        newsApiClient = new NewsApiClient("4235111de41841c2a22049677d24ccb7");

        using (var reader = new StreamReader(WORD_FREQUENCY_CSV_PATH))
            using (var csvReader = new CsvReader(reader))
            {
                csvReader.Read();
                csvReader.ReadHeader();

                while (csvReader.Read())
                {
                    string word  = csvReader.GetField("word");
                    int    count = int.Parse(csvReader.GetField("count"));

                    dF[word] = count;
                }
            }

        Debug.Log(String.Format("Words loaded: {0}", dF.Count()));
        Debug.Log(String.Format("Trump mentioned {0} times.", dF["trump"]));

        // var client = LanguageServiceClient.Create();

        // var response = client.AnalyzeSentiment(new Document()
        // {
        //  Content = text,
        //  Type = Document.Types.Type.PlainText
        // });

        // var sentiment = response.DocumentSentiment;

        var articlesResult = await newsApiClient.GetTopHeadlinesAsync(new TopHeadlinesRequest
        {
            Language = Languages.EN,
            Country  = Countries.US,            //TODO: blend countries, but weight current country
            PageSize = 50
        });

        if (articlesResult.Status == Statuses.Ok)
        {
            // total results found
            Debug.Log(articlesResult.TotalResults);

            foreach (var article in articlesResult.Articles)
            {
                // title
                Debug.Log(article.Title);

                // description
                Debug.Log(article.Description + "\n " + article.Source.Id);
                // // url
                // Debug.Log(article.Url);
                // // image
                // Debug.Log(article.UrlToImage);
                // // published at
                Debug.Log(article.PublishedAt);
            }
        }
        else
        {
            Debug.Log(articlesResult.Error.Message);
        }

        _gcNaturalLanguage = GCNaturalLanguage.Instance;

        _gcNaturalLanguage.AnnotateTextSuccessEvent += _gcNaturalLanguage_AnnotateTextSuccessEvent;
        _gcNaturalLanguage.AnnotateTextFailedEvent  += _gcNaturalLanguage_Failure;
    }