public async Task <ActionResult <ReturnJson> > GetSearchComments(string video_id, string search, string lang = "en", int count = 25)
        {
            //var uid = User.Claims.FirstOrDefault(c => c.Type == "uid")?.Value;
            //var role = await OktaClientHelper.GetProfileDetails(uid: uid).Result;
            //Console.WriteLine(userClaims.ToList());
            //var data = _db.SavedObjects.OrderBy(o => o.VideoId).First();

            try {
                var results = await YoutubeAPI.SearchComments(video_id : video_id, search : search, lang : lang, count : count, youtube_key : _configuration["youtube_key"]);

                var srm = await _db.SearchResultsMetadata.FirstAsync();

                srm.totalSearches         = srm.totalSearches + 1;
                srm.totalCommentsSearched = srm.totalCommentsSearched + results.count;
                await _db.SaveChangesAsync();

                return(Ok(new { documents = results.comments, metadata = new { count = results.count, search = results.search, video_id = results.video_id } }));
            } catch {
                return(BadRequest("Please enter a video id"));
            }
        }
Beispiel #2
0
        public static void Initialize()
        {
            log.Info("Start Initializing");

            if (Running)
            {
                throw new InvalidOperationException("already initialized");
            }

            // init CEF
            log.Info("Initializing CEF");
            var settings = new CefSettings();

            settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required";
            Cef.Initialize(settings);

            // init Setting file
            log.Info("Load Settings");
            Setting = Setting.LoadSetting(YMPInfo.SettingPath);

            // init Youtube Data v3 API
            log.Info("Initializing YoutubeAPI");
            Youtube = new YoutubeAPI();

            // load PlayLists
            log.Info("Initializing PlayListManager");
            PlayList = new PlayListManager();
            PlayList.LoadAllPlayLists();

            // load CEF Browser
            log.Info("Initializing YoutubeBrowser");
            Browser = new YoutubeBrowser();

            // Show MainWindow
            log.Info("Start MainWindow");
            Running = true;
            Main    = new MainWindow();
            Main.Show();
        }
Beispiel #3
0
        public async Task Update()
        {
            // Load streamers
            List <ContentCreator> streamers = await ContentCreatorDatabase.LoadAll();

            foreach (SocketGuild guild in Program.DiscordClient.Guilds)
            {
                // Load guild settings and check if content creator channel specified
                GuildSettings settings = await SettingsService.GetSettings <GuildSettings>(guild.Id);

                if (settings.ContentCreatorChannel == null)
                {
                    continue;
                }

                // Do not process if invalid
                if (!ulong.TryParse(settings.ContentCreatorChannel, out ulong channelId))
                {
                    continue;
                }

                // Do not process if couldn't find channel
                SocketTextChannel contentCreatorChannel = (SocketTextChannel)Program.DiscordClient.GetChannel(channelId);
                if (contentCreatorChannel == null)
                {
                    continue;
                }

                // Channel found - load streamers
                foreach (ContentCreator streamer in streamers.Where(x => x.DiscordGuildId == guild.Id))
                {
                    try
                    {
                        bool streamerUpdated = false;

                        // Check if display name should be updated
                        SocketGuildUser user = guild.Users.FirstOrDefault(x => x.Id == streamer.DiscordGuildId);
                        if (user != null)
                        {
                            string displayName = string.IsNullOrWhiteSpace(user.Nickname) ? user.Username : user.Nickname;
                            if (streamer.GuildNickName != displayName)
                            {
                                streamer.GuildNickName = displayName;
                                streamerUpdated        = true;
                            }
                        }

                        // Twitch streamer
                        if (streamer.Twitch != null && !string.IsNullOrWhiteSpace(streamer.Twitch.UserName))
                        {
                            StreamerAPI.Stream stream = await StreamerAPI.GetStreams(streamer.Twitch.UserName);

                            // Streamer is live
                            if (stream.IsLive)
                            {
                                // First stream or Current stream hasn't been posted and last stream longer than 30 minutes ago
                                if (streamer.Twitch.LastStream == null ||
                                    (stream.Id != streamer.Twitch.LastStream?.Id &&
                                     (stream.ParsedStartedAt - (streamer.Twitch.LastStream?.Created ?? DateTime.MinValue)).TotalMinutes > 30))
                                {
                                    RestUserMessage message = await contentCreatorChannel.SendMessageAsync(embed : stream.ToEmbed());

                                    // Save streamer id
                                    streamer.Twitch.LastStream = new ContentCreator.ContentInfo.Content(stream.Id, message.Id.ToString());
                                    streamerUpdated            = true;
                                }
                                ////else
                                ////{
                                ////	if (!string.IsNullOrWhiteSpace(streamer.Twitch.LastStreamEmbedMessageId)
                                ////		&& ulong.TryParse(streamer.Twitch.LastStreamEmbedMessageId, out ulong messageId))
                                ////	{
                                ////		if (await contentCreatorChannel.GetMessageAsync(messageId) is RestUserMessage message)
                                ////			await message.UpdateAsync(); // .ModifyAsync(x => x.); // x => x.Embed = stream.ToEmbed());
                                ////	}
                                ////}
                            }
                        }

                        // Youtube
                        if (streamer.Youtube != null && !string.IsNullOrWhiteSpace(streamer.Youtube.LinkId))
                        {
                            // Check video upload
                            ExploderAPI.Video latestVideo = await ExploderAPI.GetLatestVideo(streamer.Youtube.LinkId);

                            // Latest Video hasn't been posted
                            if (latestVideo != null && latestVideo.Id != streamer.Youtube.LastVideo?.Id)
                            {
                                YoutubeAPI.YoutubeVideo youtubeVideo = await YoutubeAPI.GetVideoInformation(latestVideo.Id);

                                latestVideo.UploadDate = youtubeVideo.Items.FirstOrDefault()?.Snippet.PublishedAt ?? latestVideo.UploadDate;

                                await contentCreatorChannel.SendMessageAsync(embed : latestVideo.ToEmbed());

                                // Save last video id
                                streamer.Youtube.LastVideo = new ContentCreator.ContentInfo.Content(latestVideo.Id);
                                streamerUpdated            = true;
                            }

                            // Check live stream
                            ExploderAPI.Video liveStream = await ExploderAPI.GetLiveVideo(streamer.Youtube.LinkId);

                            // Live stream occurring
                            if (liveStream != null && liveStream.Id != streamer.Youtube.LastStream?.Id)
                            {
                                await contentCreatorChannel.SendMessageAsync(embed : liveStream.ToLiveEmbed());

                                // Save last video id
                                streamer.Youtube.LastStream = new ContentCreator.ContentInfo.Content(liveStream.Id);
                                streamerUpdated             = true;
                            }
                        }

                        if (streamerUpdated)
                        {
                            await ContentCreatorDatabase.Save(streamer);
                        }
                    }
                    catch (Exception ex)
                    {
                        await Utils.Logger.LogExceptionToDiscordChannel(ex, "Content Creator Update", streamer.DiscordGuildId.ToString(), streamer.GuildNickName?.ToString());
                    }
                }
            }
        }
        //TODO: Add to the database, the maximum call amount, such as 10 pages. I think 5,000 commnets is a good start.
        public async Task <ActionResult <ReturnJson> > GetAsync(string video_id, string search, string nextPageToken)
        {
            if (!string.IsNullOrWhiteSpace(video_id))
            {
                var     cacheKey = string.Join(",", search, video_id);
                dynamic cached_object;

                if (_cache.TryGetValue(cacheKey, out cached_object))
                {
                    return(Ok(cached_object));
                }

                // get all the comments while they are less than the comment restriction i imposed. Use SQL lite for the restriction eventually. Certainly could be done per user.
                List <ReturnJson> obj      = new List <ReturnJson> {
                };
                var    maxComments         = _configuration["maxComments"];
                string nextPageIdFromQuery = null;
                int    allCommentCount     = 0;
                int    index = 0;

                do
                {
                    var result = await YoutubeAPI.GetCommentsNextPageAsync(
                        video_id : video_id, search : search,
                        NextPageToken : nextPageIdFromQuery, lastNumOfComments : allCommentCount,
                        youtube_key : _configuration["youtube_key"]);

                    var results = result.Cast <ReturnJson>();

                    nextPageIdFromQuery = results.Select(p => p.nextPage).First();

                    obj.Add(new ReturnJson {
                        search = results.Select(x => x.search).First(),
                        count  = results.Select(x => x.count).First(),
                        //url = results.Select(x => x.url).First(),
                        video_id = results.Select(x => x.video_id).First(),
                        comments = results.Select(x => x.comments).First(),
                        nextPage = results.Select(x => x.nextPage).First(),
                    });
                    allCommentCount += results.Select(c => c.count).Last();
                    index++;
                } while (!string.IsNullOrEmpty(nextPageIdFromQuery) && index < 10);

                // Return the comments neatly.
                var allcomments = obj.SelectMany(o => o.comments.Select(c => new {
                    id          = c.id,
                    text        = c.text,
                    language    = c.language,
                    publishedAt = c.publishedAt,
                    likeCount   = c.likeCount,
                    commentId   = c.commentId
                }).ToList());

                int sum         = obj.Sum(s => s.count);
                var meta        = obj.Select(s => new { count = sum, search = s.search, video_id = s.video_id }).FirstOrDefault();
                var finalObject = new { documents = allcomments, metadata = meta };

                cached_object = finalObject;


                var srm = await _db.SearchResultsMetadata.FirstAsync();

                srm.totalSearches         = srm.totalSearches + 1;
                srm.totalCommentsSearched = srm.totalCommentsSearched + sum;
                await _db.SaveChangesAsync();

                var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(500));
                _cache.Set(cacheKey, finalObject, cacheEntryOptions);

                return(Ok(finalObject));
            }
            return(BadRequest("Please enter a video id"));
        }