Exemplo n.º 1
0
 public MessageRepository(
     ApplicationDbContext dbContext,
     UserContext userContext,
     AccountRepository accountRepository,
     BoardRepository boardRepository,
     SmileyRepository smileyRepository,
     IImageStore imageStore,
     BBCodeParser bbcParser,
     GzipWebClient webClient,
     ImgurClient imgurClient,
     YouTubeClient youTubeClient,
     ILogger <MessageRepository> log
     )
 {
     DbContext         = dbContext;
     CurrentUser       = userContext;
     AccountRepository = accountRepository;
     BoardRepository   = boardRepository;
     SmileyRepository  = smileyRepository;
     ImageStore        = imageStore;
     BBCParser         = bbcParser;
     WebClient         = webClient;
     ImgurClient       = imgurClient;
     YouTubeClient     = youTubeClient;
     Log = log;
 }
Exemplo n.º 2
0
		public MessageRepository(
			ApplicationDbContext dbContext,
			UserContext userContext,
			AccountRepository accountRepository,
			BoardRepository boardRepository,
			RoleRepository roleRepository,
			SmileyRepository smileyRepository,
			IHubContext<ForumHub> forumHub,
			IActionContextAccessor actionContextAccessor,
			IUrlHelperFactory urlHelperFactory,
			IImageStore imageStore,
			BBCodeParser bbcParser,
			GzipWebClient webClient,
			ImgurClient imgurClient,
			YouTubeClient youTubeClient,
			ILogger<MessageRepository> log
		) {
			DbContext = dbContext;
			UserContext = userContext;
			AccountRepository = accountRepository;
			BoardRepository = boardRepository;
			RoleRepository = roleRepository;
			SmileyRepository = smileyRepository;
			ForumHub = forumHub;
			UrlHelper = urlHelperFactory.GetUrlHelper(actionContextAccessor.ActionContext);
			ImageStore = imageStore;
			BBCParser = bbcParser;
			WebClient = webClient;
			ImgurClient = imgurClient;
			YouTubeClient = youTubeClient;
			Log = log;
		}
Exemplo n.º 3
0
        /// <summary>
        /// Attempt to replace the ugly URL with a human readable title.
        /// </summary>
        public async Task <UrlReplacement> GetRemoteUrlReplacement(string remoteUrl)
        {
            var remotePageDetails = await GetRemotePageDetails(remoteUrl);

            remotePageDetails.Title = remotePageDetails.Title.Replace("$", "&#36;");

            var favicon = string.Empty;

            if (!string.IsNullOrEmpty(remotePageDetails.Favicon))
            {
                favicon = $"<img class='link-favicon' src='{remotePageDetails.Favicon}' /> ";
            }


            if (YouTubeClient.TryGetReplacement(remoteUrl, remotePageDetails.Title, favicon, out var replacement))
            {
                return(replacement);
            }

            if (ImgurClient.TryGetReplacement(remoteUrl, remotePageDetails.Title, favicon, out replacement))
            {
                return(replacement);
            }

            // replace the URL with the HTML
            return(new UrlReplacement {
                ReplacementText = $"<a target='_blank' href='{remoteUrl}'>{favicon}{remotePageDetails.Title}</a>",
                Card = remotePageDetails.Card ?? string.Empty
            });
        }
Exemplo n.º 4
0
        public async Task Search(CommandContext ctx, [Description("Search query")] params string[] query)
        {
            try
            {
                await ctx.TriggerTypingAsync();

                var interactivity = ctx.Client.GetInteractivityModule();

                var searchResult = await YouTubeClient.GetInstance().Search(string.Join(" ", query), 10);

                var resultPages = new List <Page>();
                foreach (var searchChunk in searchResult.FastSplit(1))
                {
                    var linkAndThumbnails = searchChunk[0].Split(";");
                    var page = new Page
                    {
                        Embed = new DiscordEmbedBuilder
                        {
                            Title = string.Format(
                                Resource.ResourceManager.GetString("page-text", ctx.Channel.GetCultureInfo()),
                                resultPages.Count + 1),
                            Description = linkAndThumbnails[0],
                            ImageUrl    = linkAndThumbnails.Last()
                        }
                    };
                    resultPages.Add(page);
                }

                await interactivity.SendPaginatedMessage(ctx.Channel, ctx.User, resultPages, TimeSpan.FromMinutes(5), TimeoutBehaviour.Delete);
            }
            catch (Exception ex)
            {
                Program.Log("Error during yotube video search", ex, DSharpPlus.LogLevel.Warning);
            }
        }
Exemplo n.º 5
0
        public void Setup()
        {
            // NOTE: Go configure the settings before running this...

            var appSettings = ConfigurationManager.AppSettings;

            _client = new YouTubeClient(appSettings["AppName"],
                                        appSettings["ApiKey"],
                                        appSettings["Username"]);
        }
        public void Initialize(string mountPointId, string configurationXmlElement, IHostServices hostServices)
        {
            MountPointId = mountPointId;
            HostServices = hostServices;
            var config = XElement.Parse(configurationXmlElement);

            var usersList = config.Element(Namespace + "Users");

            var youtubeUsers = usersList.Elements(Namespace + "User").Select(xUsers => xUsers.Value).ToList();

            var proxyURI      = String.Empty;
            var proxyUser     = String.Empty;
            var proxyPassword = String.Empty;

            WebProxy proxy = new WebProxy();

            if (config.Element(Namespace + "ProxyURI") != null)
            {
                proxyURI = config.Element(Namespace + "ProxyURI").Value;
                proxy    = new WebProxy(proxyURI, true);
            }
            if (config.Element(Namespace + "ProxyUser") != null)
            {
                proxyUser = config.Element(Namespace + "ProxyUser").Value;
            }
            if (config.Element(Namespace + "ProxyPassword") != null)
            {
                proxyPassword = config.Element(Namespace + "ProxyPassword").Value;
            }

            if (!String.IsNullOrEmpty(proxyUser) && !String.IsNullOrEmpty(proxyPassword))
            {
                proxy.Credentials = new NetworkCredential(proxyUser, proxyPassword);
            }


            Client = new YouTubeClient(config.Element(Namespace + "AppName").Value,
                                       config.Element(Namespace + "ApiKey").Value,
                                       config.Element(Namespace + "Username").Value,
                                       proxy)
            {
                Users = youtubeUsers
            };
        }
Exemplo n.º 7
0
        public async Task AddChannel(CommandContext ctx, [Description("Channel name")] params string[] channelName)
        {
            await ctx.TriggerTypingAsync();

            var    nameFull = string.Join(" ", channelName);
            string youTubeChannelId;
            string youTubeChannelName;

            try
            {
                var channelsList = await YouTubeClient.GetInstance().SearchChannel(nameFull);

                youTubeChannelId   = channelsList.Count > 0 ? channelsList.First().Value : "";
                youTubeChannelName = channelsList.Count > 0 ? channelsList.First().Key : "";
            }
            catch (Exception ex)
            {
                await ctx.RespondAsync(Resources.Resource.ResourceManager.GetString("add-channel-exception-text", ctx.Channel.GetCultureInfo()));

                Program.Log(ex.Source, ex.Message, DSharpPlus.LogLevel.Error);
                return;
            }

            if (youTubeChannelId == string.Empty)
            {
                await ctx.RespondAsync(Resource.ResourceManager.GetString("add-channel-not-found-text", ctx.Channel.GetCultureInfo()));

                return;
            }

            if (SettingsManager.Config.ChannelList.ContainsChannel(ctx.Channel.Id, youTubeChannelId) != null)
            {
                await ctx.RespondAsync(Resource.ResourceManager.GetString("add-channel-already-exist-text", ctx.Channel.GetCultureInfo()));

                return;
            }

            SettingsManager.Config.ChannelList.Add(new ChatChannel(ctx.Channel.Id, youTubeChannelId, typeof(YouTubeClient), youTubeChannelName));

            await ctx.RespondAsync(Resource.ResourceManager.GetString("add-channel-success-text", ctx.Channel.GetCultureInfo()));
        }
Exemplo n.º 8
0
        public void SearchButton_Clicked(object sender, RoutedEventArgs e)
        {
            var button = sender as Button;

            if (button == null)
            {
                throw new System.Exception("Expected a button!");
            }

            //
            // Don't bother to conduct a search if the query is empty.
            //
            var queryText = QueryText.Text;

            if (queryText != string.Empty)
            {
                var client  = new YouTubeClient();
                var results = client.SearchForVideos(queryText);

                SearchResults.ItemsSource = results;
            }
        }
Exemplo n.º 9
0
 public SlackRequestProcessor()
 {
     _triggerWordMap = new Dictionary <CommandType, Func <SlackResponse> >
     {
         { CommandType.Help, Help },
         { CommandType.Info, Info },
         { CommandType.SetProjectId, SetProjectId },
         { CommandType.AddTasks, AddTasks },
         { CommandType.AddStory, AddStory },
         { CommandType.AddDefaultTask, AddDefaultTask },
         { CommandType.ClearDefaultTasks, ClearDefaultTasks },
         { CommandType.SetDefaultTasksFromJson, SetDefaultTasksFromJson },
         { CommandType.RandomFractal, RandomFractal },
         { CommandType.AddCats, AddCats },
         { CommandType.YouTube, YouTube },
         { CommandType.Imgur, Imgur },
         { CommandType.GoogleBooks, GoogleBooks },
         { CommandType.GoogleVision, GoogleVision },
         { CommandType.SendText, SendText },
         { CommandType.SearchRepos, SearchRepos }
     };
     _databaseClient = !string.IsNullOrEmpty(ConfigurationManager.AppSettings["SqlConnectionString"])
         ? (IDatabaseClient) new SqlDatabaseClient()
         : new RavenDatabaseClient();
     _pivotalClient      = new PivotalClient();
     _fractalClient      = new FractalClient();
     _bitlyClient        = new BitlyClient();
     _catApiClient       = new CatApiClient();
     _imgurClient        = new ImgurClient();
     _youTubeClient      = new YouTubeClient();
     _googleVisionClient = new GoogleVisionClient();
     _googleBooksClient  = new GoogleBooksClient();
     _textBeltClient     = new TextBeltClient();
     _gitHubClient       = new GitHubClient();
     _validator          = new RequestValidator();
 }
Exemplo n.º 10
0
        public static ValidationResponse<PlaceSummary> PrepareSummary(string placeIDToSummarize, string mainPlaceNearByName, string lang = "en")
        {
            ValidationResponse<PlaceSummary> response = new ValidationResponse<PlaceSummary>();

            if (string.IsNullOrEmpty(placeIDToSummarize))
            {
                throw new ArgumentException("placeIDToSummarize");
            }
            PlaceSummary summary;
            string cacheKey = "Summary-" + placeIDToSummarize + "-" + lang;
            if (HttpContext.Current.Cache[cacheKey] != null)
            {
                summary = HttpContext.Current.Cache[cacheKey] as PlaceSummary;
                if (summary != null)
                {
                    response.Obj = summary;
                    return response;
                }
            }
            summary = new PlaceSummary(placeIDToSummarize);

            // step 0 - gt place details from places api.
            using (GooglePlacesClient placesClient = new GooglePlacesClient())
            {
                var placeRes = placesClient.GetPlacesDetails(new ReqPlaceDetails()
                {
                    placeid = summary.PlaceIDToSummarize,
                    language = lang
                });
                if (placeRes.Obj != null)
                {
                    summary.Place = placeRes.Obj;
                }
                else
                {
                    foreach (var error in placeRes.Errors)
                    {
                        response.Errors.Add(error.Key, error.Value);
                    }
                }
            }
            if (summary.Place != null)
            {
                // step 2 - Create summary
                summary.MainSummaryText = summary.Place.name;
                summary.MainSummarySources = new List<string>();

                using (AylienClient summClient = new AylienClient())
                {
                    ReqSummarise summReq = new ReqSummarise();
                    summReq.sentences_number = 6;
                    summReq.language = "auto";
                    List<string> summarizedArticles = new List<string>();

                    string SourcesToSummarizeNumberStr = System.Configuration.ConfigurationManager.AppSettings["SourcesToSummarizeNumber"];
                    short SourcesToSummarizeNumber;
                    Int16.TryParse(SourcesToSummarizeNumberStr, out SourcesToSummarizeNumber);
                    if (SourcesToSummarizeNumber == 0)
                    {
                        SourcesToSummarizeNumber = 3;
                    }

                    // Try to retrieve summary from place website
                    if (!string.IsNullOrEmpty(summary.Place.website))
                    {
                        summReq.url = summary.Place.website;
                        var summResp = summClient.Summarise(summReq);
                        if (summResp.Obj != null && summResp.Obj.sentences != null && summResp.Obj.sentences.Count > 0)
                        {
                            summarizedArticles.Add(string.Join(" ", summResp.Obj.sentences));
                            summary.MainSummarySources.Add(summary.Place.website);
                        }
                    }

                    // Try to retrieve summary from google search results

                    // Google search
                    List<Result> googleSearchResults = null;
                    using (GoogleSearchClient clWebPages = new GoogleSearchClient())
                    {
                        ReqGoogleSearch req = new ReqGoogleSearch();
                        req.q = summary.Place.name + ", " + mainPlaceNearByName;
                        req.hl = lang;
                        req.lr = "lang_" + lang;
                        var googleSearchResultsResp = clWebPages.GetSearchResults(req);
                        if (googleSearchResultsResp.Obj != null && googleSearchResultsResp.Obj.Items != null && googleSearchResultsResp.Obj.Items.Count > 0)
                        {
                            googleSearchResults = googleSearchResultsResp.Obj.Items.ToList();
                        }
                    }

                    // Summaries from search results
                    if (googleSearchResults != null && googleSearchResults.Count > 0)
                    {
                        int maxResultsToSearchIn = 4;
                        for (int i = 0; i < googleSearchResults.Count
                            && i < maxResultsToSearchIn
                            && summarizedArticles.Count < SourcesToSummarizeNumber
                            && !summary.MainSummarySources.Contains(googleSearchResults[i].Link)
                            ; i++)
                        {
                            summReq.url = googleSearchResults[i].Link;
                            var summResp = summClient.Summarise(summReq);
                            if (summResp.Obj != null && summResp.Obj.sentences != null && summResp.Obj.sentences.Count > 0)
                            {
                                summarizedArticles.Add(string.Join(" ", summResp.Obj.sentences));
                                summary.MainSummarySources.Add(googleSearchResults[i].Link);
                            }
                        }
                    }

                    // Summarise all summaries to one big summary.
                    if (summarizedArticles.Count > 0)
                    {
                        ReqSummarise summFuncReq = new ReqSummarise();
                        summFuncReq.title = summary.Place.name;
                        summFuncReq.text = string.Join("\n\r\\s", summarizedArticles.OrderByDescending(s => s.Length)); // Combine all summarized articles.
                        summFuncReq.sentences_number = 5;
                        var summFuncResp = summClient.Summarise(summFuncReq);
                        if (summFuncResp.Obj != null && summFuncResp.Obj.sentences != null && summFuncResp.Obj.sentences.Count > 0)
                        {
                            summary.MainSummaryText = string.Join(" ", summFuncResp.Obj.sentences);
                        }
                        else
                        {
                            // fallback just print combined text.
                            summary.MainSummaryText = summFuncReq.text;
                        }
                    }

                }

                // step 3 - Retrieve images
                using (GoogleSearchClient clImages = new GoogleSearchClient())
                {
                    ReqGoogleSearch req = new ReqGoogleSearch();
                    req.q = summary.Place.name + ", " + mainPlaceNearByName;
                    req.searchType = PlacesIR.GoogleSearch.ReqGoogleSearch.SearchTypeEnum.image;
                    req.hl = lang;
                    var imgResp = clImages.GetSearchResults(req);
                    if (imgResp.Obj != null && imgResp.Obj.Items != null)
                    {
                        foreach (var item in imgResp.Obj.Items)
                        {
                            Image img = new Image();
                            img.title = item.Title;
                            img.url = item.Link;
                            img.thumb_url = item.Image.ThumbnailLink;
                            summary.Images.Add(img);
                        }
                    }
                }

                // step 4 - Retrieve videos
                using (YouTubeClient YouTubeClient = new YouTubeClient())
                {
                    ReqSearch req = new ReqSearch();
                    req.q = summary.Place.name + ", " + mainPlaceNearByName;
                    req.relevanceLanguage = lang;
                    var youResp = YouTubeClient.GetSearchResults(req);
                    if (youResp.Obj != null && youResp.Obj.items != null)
                    {
                        summary.Videos = youResp.Obj.items;
                    }
                }

                // step 5 - get prices if available.
                // TODO Retrieve prices if available

                HttpRuntime.Cache.Insert(cacheKey, summary, null, DateTime.Now.AddHours(4), TimeSpan.Zero);
            }

            response.Obj = summary;
            return response;
        }
Exemplo n.º 11
0
 public void Teardown()
 {
     _client = null;
 }