Example #1
0
        public async Task ProcessMessage(string message)
        {
            if (string.IsNullOrEmpty(message))
            {
                return;
            }

            var prefix     = string.Empty;
            var command    = string.Empty;
            var parameters = string.Empty;
            var author     = string.Empty;

            if (message.Contains(":") && !message.StartsWith(":"))
            {
                message = message.Substring(message.IndexOf(':'));
            }

            if (message.StartsWith(":"))
            {
                var index = prefix.IndexOf(' ');
                if (index < 0)
                {
                    index = message.Length;
                }

                prefix = message.Substring(0, index);
                var parts = message.Split(" ");
                command = parts[1];
                if (parts.Length > 2)
                {
                    parameters = string.Join(' ', parts.Skip(2));
                }
            }
            else
            {
                var parts = message.Split(" ");
                command = parts[0];
                if (parts.Length > 1)
                {
                    parameters = string.Join(' ', parts.Skip(1));
                }
            }

            if (prefix.Contains("!"))
            {
                var index = prefix.IndexOf('!') - 1;
                if (index < 1)
                {
                    index = 1;
                }

                author = prefix.Substring(1, index);
            }

            if (command != "PRIVMSG")
            {
                return;
            }

            var displayMessage = parameters.Substring(parameters.IndexOf(':') + 1);

            await chatService.CreateMessage(new ChatMessage
            {
                Author  = author,
                Message = displayMessage,
                Date    = DateTime.UtcNow,
                Source  = ApiSource.Twitch
            });
        }
        protected override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            pollingInterval = minimumPollingInterval;
            delay           = defaultDelay;

            cancellationToken.Register(() =>
            {
                logger.LogDebug($"YoutubeBackgroundService background task is stopping.");
            });

            using (var scope = serviceScopeFactory.CreateScope())
            {
                youtubeService   = scope.ServiceProvider.GetRequiredService <YoutubeService>();
                chatService      = scope.ServiceProvider.GetRequiredService <ChatService>();
                dashboardService = scope.ServiceProvider.GetRequiredService <DashboardService>();

                while (!cancellationToken.IsCancellationRequested)
                {
                    try
                    {
                        if (!youtubeService.IsEnabled().Result)
                        {
                            await dashboardService.UpdateStatus(ApiSource.Youtube, BackgroundServiceStatus.Disabled, cancellationToken);

                            await Task.Delay(delay, cancellationToken);

                            continue;
                        }

                        if (!youtubeService.IsConfigured())
                        {
                            await dashboardService.UpdateStatus(ApiSource.Youtube, BackgroundServiceStatus.NotConfigured, cancellationToken);

                            await Task.Delay(delay, cancellationToken);

                            continue;
                        }

                        var token = await youtubeService.GetToken();

                        if (token == null)
                        {
                            await dashboardService.UpdateStatus(ApiSource.Youtube, BackgroundServiceStatus.Forbidden, cancellationToken);

                            await Task.Delay(delay, cancellationToken);

                            continue;
                        }

                        if (token.Status == AccessTokenStatus.Expired && token.HasRefreshToken)
                        {
                            await youtubeService.RefreshToken(token);
                        }

                        if (!youtubeService.IsValidToken(token))
                        {
                            await dashboardService.UpdateStatus(ApiSource.Youtube, BackgroundServiceStatus.Forbidden, cancellationToken);

                            await Task.Delay(delay, cancellationToken);

                            continue;
                        }

                        while (!cancellationToken.IsCancellationRequested && youtubeService.IsEnabled().Result)
                        {
                            if (string.IsNullOrEmpty(liveChatId))
                            {
                                var liveBroadcast = await youtubeService.GetLiveBroadcast();

                                if (liveBroadcast == null)
                                {
                                    await dashboardService.UpdateStatus(ApiSource.Youtube, BackgroundServiceStatus.Offline, cancellationToken);

                                    await Task.Delay(delay, cancellationToken);

                                    continue;
                                }

                                liveChatId = liveBroadcast.snippet.liveChatId;
                            }

                            var liveChatMessages = await youtubeService.GetLiveChatMessages(liveChatId);

                            await dashboardService.UpdateStatus(ApiSource.Youtube, BackgroundServiceStatus.Connected, cancellationToken);

                            if (liveChatMessages == null || !liveChatMessages.items.Any())
                            {
                                await Task.Delay(TimeSpan.FromMilliseconds(pollingInterval), cancellationToken);

                                continue;
                            }

                            foreach (var item in liveChatMessages.items)
                            {
                                await chatService.CreateMessage(youtubeService.MapToChatMessage(item));
                            }

                            pollingInterval = Math.Max(liveChatMessages.pollingIntervalMillis, minimumPollingInterval);
                            await Task.Delay(pollingInterval, cancellationToken);
                        }

                        await dashboardService.UpdateStatus(ApiSource.Youtube, BackgroundServiceStatus.Stopped, cancellationToken);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex.GetBaseException(), ex.GetBaseException().Message);
                        await dashboardService.UpdateStatus(ApiSource.Youtube, BackgroundServiceStatus.Error, cancellationToken);
                    }
                    await Task.Delay(delay, cancellationToken);
                }
            }
        }