Example #1
0
 public TwitchChatBot(IBotAuthenticated authenticated, TwitchAPIClient twitchAPIClient, IServiceProvider serviceProvider, ILogger <TwitchChatBot> logger)
 {
     _authenticated   = authenticated;
     _twitchAPIClient = twitchAPIClient;
     _serviceProvider = serviceProvider;
     _logger          = logger;
 }
Example #2
0
 public GameSynopsisCommand(
     ITwitchCategoryProvider twitchProvider,
     TwitchAPIClient twitchAPIClient,
     ILogger <GameSynopsisCommand> logger)
 {
     _twitchCategoryProvider = twitchProvider;
     _twitchAPIClient        = twitchAPIClient;
     _logger = logger;
 }
Example #3
0
        async Task IChannelGrain.Activate(string userToken)
        {
            var userAuthenticated = Twitch.Authenticate()
                                    .FromOAuthToken(userToken)
                                    .Build();
            var userClient = TwitchAPIClient.CreateFromBase(_appClient, userAuthenticated);
            var validated  = await userClient.ValidateToken();

            if (validated == null || validated.UserId != _channelId || validated.ExpiresIn == 0)
            {
                throw new ArgumentException("Could not validate token");
            }
            _userClient = userClient;

            var channelInfoTask = _userClient.GetChannelInfoAsync(_channelId);
            List <HelixChannelModerator> moderators = new List <HelixChannelModerator>();
            var editorsTask = _userClient.GetHelixChannelEditorsAsync(_channelId);

            await foreach (var moderator in _userClient.EnumerateChannelModeratorsAsync(_channelId))
            {
                moderators.Add(moderator);
            }
            _channelState.State.BroadcasterToken = userToken;
            _channelState.State.Editors          = (await editorsTask).ToList();
            _channelState.State.Moderators       = moderators.ToList();
            await _channelState.WriteStateAsync();

            var editorsTasks = _channelState.State.Editors.Select(editor =>
                                                                  GrainFactory.GetGrain <IUserGrain>(editor.UserId).SetRole(new UserRole
            {
                Role        = ChannelRole.Editor,
                ChannelId   = _channelId,
                ChannelName = _channelInfo.BroadcasterName,
            })
                                                                  );

            var modsTasks = _channelState.State.Moderators.Select(moderator =>
                                                                  GrainFactory.GetGrain <IUserGrain>(moderator.UserId).SetRole(new UserRole
            {
                Role        = ChannelRole.Moderator,
                ChannelId   = _channelId,
                ChannelName = _channelInfo.BroadcasterName,
            })
                                                                  );

            await Task.WhenAll(editorsTasks);

            await Task.WhenAll(modsTasks);

            _channelInfo = await channelInfoTask;
            await RegisterEventSubSubscriptions(CancellationToken.None);
        }
Example #4
0
 public LoadConfigurationStartupTask(
     IGrainFactory grainFactory,
     TwitchAPIClient twitchClient,
     IEnumerable <ChannelOptions> options,
     IEnumerable <CommandRegistration> commands,
     ILogger <LoadConfigurationStartupTask> logger)
 {
     _grainFactory = grainFactory;
     _twitchClient = twitchClient;
     _channels     = options.ToList();
     _commands     = commands.ToList();
     _logger       = logger;
 }
Example #5
0
 public PollingTwitchCategoryProvider(
     TwitchAPIClient twitchAPIClient,
     IGDBClient IGDBClient,
     SteamStoreClient steamStoreClient,
     IGameLocalizationStore gameLocalizationStore,
     IOptions <TwitchApplicationOptions> twitchOptions,
     ILogger <PollingTwitchCategoryProvider> logger)
 {
     _twitchAPIClient  = twitchAPIClient;
     _igdbClient       = IGDBClient;
     _gameLocalization = gameLocalizationStore;
     _twitchOptions    = twitchOptions.Value;
     _logger           = logger;
 }
Example #6
0
 public GrainTwitchCategoryProvider(
     IGrainFactory grainFactory,
     TwitchAPIClient twitchClient,
     IGDBClient igdbClient,
     SteamStoreClient steamStoreClient,
     IGameLocalizationStore localizationStore,
     ILogger <GrainTwitchCategoryProvider> logger)
 {
     _grainFactory          = grainFactory;
     _twitchAPIClient       = twitchClient;
     _igdbClient            = igdbClient;
     _steamStoreClient      = steamStoreClient;
     _gameLocalizationStore = localizationStore;
     _logger = logger;
 }
Example #7
0
 public TwitchCategoriesSynchronizationService(
     TwitchAPIClient twitchApiClient,
     IGDBClient igdbClient,
     SteamStoreClient steamStoreClient,
     IOptions <TwitchApplicationOptions> options,
     IGameLocalizationStore gameLocalizationStore,
     ILogger <TwitchCategoriesSynchronizationService> logger)
 {
     _twitchAPIClient            = twitchApiClient;
     _igdbClient                 = igdbClient;
     _steamStoreClient           = steamStoreClient;
     _steamStoreClient.WebAPIKey = options.Value.SteamApiKey;
     _gameLocalization           = gameLocalizationStore;
     _options = options.Value;
     _logger  = logger;
 }
Example #8
0
 public ChannelGrain(
     [PersistentState("channel", "channelStore")] IPersistentState <ChannelState> channelState,
     [PersistentState("botsettings", "botSettingsStore")] IPersistentState <ChannelBotSettingsState> botSettingsState,
     [PersistentState("customcategories", "customCategoriesStore")] IPersistentState <CategoryDescriptionState> customCategoriesState,
     TwitchAPIClient appClient,
     IOptions <TwitchChatClientOptions> botOptions,
     IOptions <TwitchApplicationOptions> appOptions,
     IEnumerable <CommandRegistration> commands,
     ILogger <ChannelGrain> logger)
 {
     _channelState       = channelState;
     _channelBotState    = botSettingsState;
     _categoriesState    = customCategoriesState;
     _appClient          = appClient;
     _options            = botOptions.Value;
     _twitchOptions      = appOptions.Value;
     _registeredCommands = commands.ToDictionary(c => c.Name, c => c);
     _logger             = logger;
 }
Example #9
0
        public async Task <bool> SetOAuthToken(string oauthToken)
        {
            _profile.State.OAuthToken = oauthToken;

            var authenticated = new AuthenticationBuilder()
                                .FromOAuthToken(oauthToken)
                                .Build();

            _twitchAPIClient = new TwitchAPIClient(authenticated, _httpClientFactory, ServiceProvider.GetRequiredService <ILogger <TwitchAPIClient> >());
            var validated = await _twitchAPIClient.ValidateToken();

            if (validated != null)
            {
                _tokenInfo = validated;

                if (_profile.State.HasActiveChannel)
                {
                    await SetRole(new UserRole
                    {
                        Role        = ChannelRole.Broadcaster,
                        ChannelId   = _tokenInfo.UserId,
                        ChannelName = _tokenInfo.Login,
                    });

                    var channelGrain = GrainFactory.GetGrain <IChannelGrain>(UserId);
                    await channelGrain.Activate(_profile.State.OAuthToken);
                }

                _profile.State.CurrentScopes = validated.Scopes.Where(s => TwitchConstants.ScopesValues.ContainsValue(s)).Select(s => TwitchConstants.ScopesValues.FirstOrDefault(kvp => kvp.Value == s).Key).ToArray();

                await _profile.WriteStateAsync();
            }
            else
            {
                _profile.State.CurrentScopes = new TwitchConstants.TwitchOAuthScopes[0];
            }

            return(validated != null);
        }
Example #10
0
        void BuildSiloHost()
        {
            var instrumentationKey           = _configuration.GetValue <string>("ApplicationInsights:InstrumentationKey");
            var hostname                     = _configuration.GetValue <string>("HOSTNAME");
            var azureStorageConnectionString = _configuration.GetValue <string>("Storage:AzureStorageConnectionString");
            var redisClusteringUrl           = _configuration.GetValue <string>("REDIS_URL");

            var builder = new SiloHostBuilder()
                          .ConfigureLogging(loggingBuilder =>
            {
                if (!string.IsNullOrEmpty(instrumentationKey))
                {
                    loggingBuilder.AddApplicationInsights(instrumentationKey);
                }
                loggingBuilder.AddConsole();
            })
                          // Configure ClusterId and ServiceId
                          .Configure <ClusterOptions>(options =>
            {
                options.ClusterId = "dev";
                options.ServiceId = "TwitchServices";
            })
                          .AddStartupTask <LoadConfigurationStartupTask>()
                          .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(ChannelGrain).Assembly).WithReferences())
                          // Configure connectivity
                          .ConfigureEndpoints(hostname: hostname, siloPort: 11111, gatewayPort: 30000);

            if (!string.IsNullOrEmpty(azureStorageConnectionString))
            {
                builder.AddAzureTableGrainStorage("profileStore", (AzureTableStorageOptions options) =>
                {
                    options.ConnectionString = azureStorageConnectionString;
                    options.TableName        = "profiles";
                    options.UseJson          = true;
                    options.IndentJson       = false;
                });
                builder.AddAzureTableGrainStorage("channelStore", (AzureTableStorageOptions options) =>
                {
                    options.ConnectionString = azureStorageConnectionString;
                    options.TableName        = "channels";
                    options.UseJson          = true;
                    options.IndentJson       = false;
                });
                builder.AddAzureTableGrainStorage("botSettingsStore", (AzureTableStorageOptions options) =>
                {
                    options.ConnectionString = azureStorageConnectionString;
                    options.TableName        = "botsettings";
                    options.UseJson          = true;
                    options.IndentJson       = false;
                });
                builder.AddCustomCategoriesStorage("customCategoriesStore", (CustomCategoriesStorageOptions options) =>
                {
                    options.ConnectionString = azureStorageConnectionString;
                    options.TableName        = "customcategories";
                });
            }
            else
            {
                builder.AddMemoryGrainStorage("profileStore");
                builder.AddMemoryGrainStorage("channelStore");
                builder.AddMemoryGrainStorage("botSettingsStore");
                builder.AddMemoryGrainStorage("customCategoriesStore");
            }

            if (!string.IsNullOrEmpty(redisClusteringUrl))
            {
                // Use redis clustering when available
                builder.UseRedisClustering(redisClusteringUrl);
            }
            else
            {
                // Use localhost clustering for a single local silo
                builder.UseLocalhostClustering(11111, 30000, null, "TwitchServices", "dev");
            }

            // Temp

            builder.ConfigureServices((context, services) =>
            {
                // Load channels and command configuration from static json file, and inject
                var channelsConfig = new ConfigurationBuilder().AddJsonFile("channels.json").Build();
                IEnumerable <ChannelOptions> channelOptions = new List <ChannelOptions>();
                channelsConfig.GetSection("channels").Bind(channelOptions);
                services.AddTransient <IEnumerable <ChannelOptions> >((_) => channelOptions);

                // Configure services
                services.AddHttpClient();
                services.Configure <TwitchApplicationOptions>(_configuration.GetSection("twitch"));
                services.Configure <TwitchChatClientOptions>(_configuration.GetSection("twitch").GetSection("IrcOptions"));
                services.Configure <AzureGameLocalizationStoreOptions>(_configuration.GetSection("loc:azure"));
                services.AddSingleton <IMessageProcessor, TracingMessageProcessor>();
                services.AddTransient <TwitchChatClient>();
                services.AddTransient <TwitchAPIClient>();
                services.AddTransient <IGDBClient>();
                services.AddSingleton <IMemoryCache, MemoryCache>();
                services.AddSingleton <SteamStoreClient>();
                services.AddSingleton <IAuthenticated>(s =>
                                                       Twitch.Authenticate()
                                                       .FromAppCredentials(
                                                           s.GetService <IOptions <TwitchApplicationOptions> >().Value.ClientId,
                                                           s.GetService <IOptions <TwitchApplicationOptions> >().Value.ClientSecret)
                                                       .Build()
                                                       );
                services.AddTransient <ITwitchCategoryProvider, GrainTwitchCategoryProvider>();
                services.AddSingleton <IGameLocalizationStore, AzureStorageGameLocalizationStore>();
                services.PostConfigure <TwitchChatClientOptions>(options =>
                {
                    var oauth = Twitch.Authenticate()
                                .FromOAuthToken(options.OAuthToken)
                                .Build();
                    var loggerFactory = new LoggerFactory();
                    using (var httpClient = new HttpClient())
                        using (var apiClient = TwitchAPIClient.Create(oauth))
                        {
                            options.TokenInfo = apiClient.ValidateToken().Result;
                        }
                });

                // Configure commands
                services.AddCommand <GameSynopsisCommand>("GameSynopsis");
                services.AddCommand <TracingMessageProcessor>("Logger");
                services.AddCommand <ResponseCommandProcessor>("Response");
            });
            _siloHost = builder.Build();
        }