From 665a8a13b415d665cf4513866be1124c30f7d4fa Mon Sep 17 00:00:00 2001 From: viral32111 <19510403+viral32111@users.noreply.github.com> Date: Sun, 13 Aug 2023 17:52:52 +0100 Subject: [PATCH] Update config elsewhere --- Source/Cloudflare.cs | 4 ++-- Source/Configuration.cs | 30 ++++++++++++------------- Source/Database/Mongo.cs | 18 +++++++-------- Source/Program.cs | 31 ++++++++++++++------------ Source/Redis.cs | 18 ++++++++------- Source/Shared.cs | 14 ++++++------ Source/Twitch/API.cs | 4 ++-- Source/Twitch/Channel.cs | 4 ++-- Source/Twitch/Client.cs | 8 +++---- Source/Twitch/OAuth/AppAccessToken.cs | 2 +- Source/Twitch/OAuth/UserAccessToken.cs | 24 ++++++++++---------- 11 files changed, 81 insertions(+), 76 deletions(-) diff --git a/Source/Cloudflare.cs b/Source/Cloudflare.cs index 6ceef95..3fe69fe 100644 --- a/Source/Cloudflare.cs +++ b/Source/Cloudflare.cs @@ -95,9 +95,9 @@ public static void StopTunnel() { // Gets the path to the executable file of the specific client version for Windows or Linux public static string GetClientPath( string clientVersion ) { if ( Shared.IsWindows() ) { - return Path.Combine( Config.CacheDirectory, $"cloudflared-{clientVersion}-windows-amd64.exe" ); + return Path.Combine( Program.Configuration.CacheDirectory, $"cloudflared-{clientVersion}-windows-amd64.exe" ); } else { - return Path.Combine( Config.CacheDirectory, $"cloudflared-{clientVersion}-linux-amd64" ); + return Path.Combine( Program.Configuration.CacheDirectory, $"cloudflared-{clientVersion}-linux-amd64" ); } } diff --git a/Source/Configuration.cs b/Source/Configuration.cs index 37515e3..122e925 100644 --- a/Source/Configuration.cs +++ b/Source/Configuration.cs @@ -149,98 +149,98 @@ private set { /// https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow /// [ JsonPropertyName( "twitch-oauth-base-url" ) ] - public static readonly string TwitchOAuthBaseURL = "https://id.twitch.tv/oauth2"; + public readonly string TwitchOAuthBaseURL = "https://id.twitch.tv/oauth2"; /// /// The client identifier of the Twitch OAuth application. /// https://dev.twitch.tv/docs/authentication/register-app/ /// [ JsonPropertyName( "twitch-oauth-client-identifier" ) ] - public static readonly string TwitchOAuthClientIdentifier = ""; + public readonly string TwitchOAuthClientIdentifier = ""; /// /// The client secret of the Twitch OAuth application. /// https://dev.twitch.tv/docs/authentication/register-app/ /// [ JsonPropertyName( "twitch-oauth-client-secret" ) ] - public static readonly string TwitchOAuthClientSecret = ""; + public readonly string TwitchOAuthClientSecret = ""; /// /// The redirect URL of the Twitch OAuth application. /// https://dev.twitch.tv/docs/authentication/register-app/ /// [ JsonPropertyName( "twitch-oauth-redirect-url" ) ] - public static readonly string TwitchOAuthRedirectURL = "https://example.com/my-redirect-handler"; + public readonly string TwitchOAuthRedirectURL = "https://example.com/my-redirect-handler"; /// /// The scopes to request on behalf of the Twitch OAuth application. /// https://dev.twitch.tv/docs/authentication/scopes/ /// [ JsonPropertyName( "twitch-oauth-scopes" ) ] - public static readonly string[] TwitchOAuthScopes = new[] { "chat:read", "chat:edit" }; + public readonly string[] TwitchOAuthScopes = new[] { "chat:read", "chat:edit" }; /// /// The IP address of the Twitch chat IRC server. /// https://dev.twitch.tv/docs/irc/#connecting-to-the-twitch-irc-server /// [ JsonPropertyName( "twitch-chat-address" ) ] - public static readonly string TwitchChatAddress = "irc.chat.twitch.tv"; + public readonly string TwitchChatAddress = "irc.chat.twitch.tv"; /// /// The port number of the Twitch chat IRC server. /// https://dev.twitch.tv/docs/irc/#connecting-to-the-twitch-irc-server /// [ JsonPropertyName( "twitch-chat-port" ) ] - public static readonly int TwitchChatPort = 6697; + public readonly int TwitchChatPort = 6697; /// /// The identifier of the primary Twitch channel. /// [ JsonPropertyName( "twitch-primary-channel-identifier" ) ] - public static readonly int TwitchPrimaryChannelIdentifier = 127154290; + public readonly int TwitchPrimaryChannelIdentifier = 127154290; /// /// The base URL of the Twitch API. /// https://dev.twitch.tv/docs/api/ /// [ JsonPropertyName( "twitch-api-base-url" ) ] - public static readonly string TwitchAPIBaseURL = "https://api.twitch.tv/helix"; + public readonly string TwitchAPIBaseURL = "https://api.twitch.tv/helix"; /// /// The URL of the Twitch EventSub WebSocket. /// https://dev.twitch.tv/docs/eventsub/handling-websocket-events/ /// [ JsonPropertyName( "twitch-events-websocket-url" ) ] - public static readonly string TwitchEventsWebSocketURL = "wss://eventsub.wss.twitch.tv/ws"; + public readonly string TwitchEventsWebSocketURL = "wss://eventsub.wss.twitch.tv/ws"; /// /// The IP address of the MongoDB server. /// [ JsonPropertyName( "mongodb-server-address" ) ] - public static readonly string MongoDBServerAddress = "127.0.0.1"; + public readonly string MongoDBServerAddress = "127.0.0.1"; /// /// The port number of the MongoDB server. /// [ JsonPropertyName( "mongodb-server-port" ) ] - public static readonly int MongoDBServerPort = 27017; + public readonly int MongoDBServerPort = 27017; /// /// The username of the MongoDB user. /// [ JsonPropertyName( "mongodb-user-name" ) ] - public static readonly string MongoDBUserName = ""; + public readonly string MongoDBUserName = ""; /// /// The password of the MongoDB user. /// [ JsonPropertyName( "mongodb-user-password" ) ] - public static readonly string MongoDBUserPassword = ""; + public readonly string MongoDBUserPassword = ""; /// /// The name of the MongoDB database. /// [ JsonPropertyName( "mongodb-database-name" ) ] - public static readonly string MongoDBDatabaseName = "twitch-bot"; + public readonly string MongoDBDatabaseName = "twitch-bot"; } diff --git a/Source/Database/Mongo.cs b/Source/Database/Mongo.cs index ae45b0c..db42407 100644 --- a/Source/Database/Mongo.cs +++ b/Source/Database/Mongo.cs @@ -13,11 +13,11 @@ public static class Mongo { static Mongo() { // Ensure the database configuration properties exist - if ( string.IsNullOrEmpty( Config.DatabaseName ) || - string.IsNullOrEmpty( Config.DatabaseServerAddress ) || - Config.DatabaseServerPort < 0 || Config.DatabaseServerPort > 65536 || - string.IsNullOrEmpty( Config.DatabaseUserName ) || - string.IsNullOrEmpty( Config.DatabaseUserPassword ) + if ( string.IsNullOrWhiteSpace( Program.Configuration.MongoDBDatabaseName ) || + string.IsNullOrWhiteSpace( Program.Configuration.MongoDBServerAddress ) || + Program.Configuration.MongoDBServerPort < 0 || Program.Configuration.MongoDBServerPort > 65536 || + string.IsNullOrWhiteSpace( Program.Configuration.MongoDBUserName ) || + string.IsNullOrWhiteSpace( Program.Configuration.MongoDBUserPassword ) ) { Log.Error( "One or more of the database configuration properties are not set!" ); Environment.Exit( 1 ); @@ -26,10 +26,10 @@ static Mongo() { // Construct the connection URL MongoUrl connectionUrl = new MongoUrlBuilder() { - Server = new MongoServerAddress( Config.DatabaseServerAddress, Config.DatabaseServerPort ), - Username = Config.DatabaseUserName, - Password = Config.DatabaseUserPassword, - DatabaseName = Config.DatabaseName, + Server = new MongoServerAddress( Program.Configuration.MongoDBServerAddress, Program.Configuration.MongoDBServerPort ), + Username = Program.Configuration.MongoDBUserName, + Password = Program.Configuration.MongoDBUserPassword, + DatabaseName = Program.Configuration.MongoDBDatabaseName, ApplicationName = Assembly.GetExecutingAssembly().GetName().Name, DirectConnection = true }.ToMongoUrl(); diff --git a/Source/Program.cs b/Source/Program.cs index 2cb410f..bc4a9bd 100644 --- a/Source/Program.cs +++ b/Source/Program.cs @@ -46,9 +46,6 @@ public static async Task Main( string[] arguments ) { // Create required directories Shared.CreateDirectories(); - Environment.Exit( 1 ); - return; - // Deprecation notice for the stream history file string streamHistoryFile = Path.Combine( Configuration.DataDirectory, "stream-history.json" ); if ( File.Exists( streamHistoryFile ) ) Log.Warn( "The stream history file ({0}) is deprecated, it can safely be deleted.", streamHistoryFile ); @@ -61,20 +58,22 @@ public static async Task Main( string[] arguments ) { } // Ensure the OAuth identifier & secret exists - if ( string.IsNullOrEmpty( Config.TwitchOAuthIdentifier ) || string.IsNullOrEmpty( Config.TwitchOAuthSecret ) ) { + if ( string.IsNullOrWhiteSpace( Configuration.TwitchOAuthClientIdentifier ) || string.IsNullOrWhiteSpace( Configuration.TwitchOAuthClientSecret ) ) { Console.WriteLine( "Could not load Twitch application Client ID and/or secret from the configuration file!" ); Environment.Exit( 1 ); return; } // Download the Cloudflare Tunnel client - if ( !Cloudflare.IsClientDownloaded( Config.CloudflareTunnelVersion, Config.CloudflareTunnelChecksum ) ) { - Log.Warn( "Cloudflare Tunnel client does not exist or is corrupt, downloading version {0}...", Config.CloudflareTunnelVersion ); - await Cloudflare.DownloadClient( Config.CloudflareTunnelVersion, Config.CloudflareTunnelChecksum ); - Log.Info( "Cloudflare Tunnel client downloaded to: '{0}'.", Cloudflare.GetClientPath( Config.CloudflareTunnelVersion ) ); + /* + if ( !Cloudflare.IsClientDownloaded( Configuration.CloudflareTunnelVersion, Configuration.CloudflareTunnelChecksum ) ) { + Log.Warn( "Cloudflare Tunnel client does not exist or is corrupt, downloading version {0}...", Configuration.CloudflareTunnelVersion ); + await Cloudflare.DownloadClient( Configuration.CloudflareTunnelVersion, Configuration.CloudflareTunnelChecksum ); + Log.Info( "Cloudflare Tunnel client downloaded to: '{0}'.", Cloudflare.GetClientPath( Configuration.CloudflareTunnelVersion ) ); } else { - Log.Info( "Using cached Cloudflare Tunnel client at: '{0}'.", Cloudflare.GetClientPath( Config.CloudflareTunnelVersion ) ); + Log.Info( "Using cached Cloudflare Tunnel client at: '{0}'.", Cloudflare.GetClientPath( Configuration.CloudflareTunnelVersion ) ); } + */ // List all collections in MongoDB List databaseCollectionNames = await Mongo.Database.ListCollectionNames().ToListAsync(); @@ -82,8 +81,10 @@ public static async Task Main( string[] arguments ) { // Open Redis connection // TODO: What are we even using Redis for?? + /* await Redis.Open(); Log.Info( "Connected to Redis." ); + */ // Attempt to load an existing user access token from disk try { @@ -105,7 +106,7 @@ public static async Task Main( string[] arguments ) { } catch ( FileNotFoundException ) { Log.Warn( "User access token file does not exist, requesting fresh token..." ); - Shared.UserAccessToken = await UserAccessToken.RequestAuthorization( Config.TwitchOAuthRedirectURL, Config.TwitchOAuthScopes ); + Shared.UserAccessToken = await UserAccessToken.RequestAuthorization( Configuration.TwitchOAuthRedirectURL, Configuration.TwitchOAuthScopes ); Shared.UserAccessToken.Save( Shared.UserAccessTokenFilePath ); } @@ -140,7 +141,7 @@ public static async Task Main( string[] arguments ) { // Connect to Twitch chat Log.Info( "Connecting to Twitch chat..." ); - await client.OpenAsync( Config.TwitchChatBaseURL ); + await client.OpenAsync( Configuration.TwitchChatAddress, Configuration.TwitchChatPort, true ); // Keep the program running until we disconnect from Twitch chat await client.WaitAsync(); @@ -157,8 +158,10 @@ private static bool OnApplicationExit( CtrlType signal ) { Log.Info( "Closed connection to the database." );*/ // Close Redis connection + /* Redis.Close().Wait(); Log.Info( "Disconnected from Redis." ); + */ // Close the EventSub websocket connection //Log.Info( "Closing EventSub websocket connection..." ); @@ -209,14 +212,14 @@ private static async Task OnReady( Twitch.Client client, GlobalUser user ) { Log.Info( "Ready as user {0}.", user.ToString() ); // Fetch the primary channel - Channel primaryChannel = await Channel.FetchFromAPI( Config.TwitchChatPrimaryChannelIdentifier, client ); + Channel primaryChannel = await Channel.FetchFromAPI( Configuration.TwitchPrimaryChannelIdentifier, client ); // Join the primary channel Log.Info( "Joining primary channel {0}...", primaryChannel.ToString() ); if ( await client.JoinChannel( primaryChannel ) ) { Log.Info( "Joined primary channel {0}.", primaryChannel.ToString() ); - //await eventSubClient.ConnectAsync( Config.TwitchEventSubWebSocketURL, new( 0, 0, 10 ), CancellationToken.None ); + //await eventSubClient.ConnectAsync( Configuration.TwitchEventSubWebSocketURL, new( 0, 0, 10 ), CancellationToken.None ); // TODO: Start time streamed goal thing @@ -262,7 +265,7 @@ private static async Task OnChannelUpdate( Twitch.Client client, Channel channel private static async Task OnEventSubClientReady( Twitch.EventSubscription.Client eventSubClient ) { Log.Info( "EventSub client is ready, our session identifier is '{0}'.", eventSubClient.SessionIdentifier ); - Channel? channel = State.GetChannel( 127154290 ); // Just for testing + Channel? channel = State.GetChannel( Configuration.TwitchPrimaryChannelIdentifier ); if ( channel == null ) throw new Exception( "Cannot find channel" ); await eventSubClient.SubscribeForChannel( Twitch.EventSubscription.SubscriptionType.ChannelUpdate, channel ); diff --git a/Source/Redis.cs b/Source/Redis.cs index 3da762a..ad9a3da 100644 --- a/Source/Redis.cs +++ b/Source/Redis.cs @@ -6,24 +6,25 @@ namespace TwitchBot; +/* public static class Redis { private static readonly ConfigurationOptions connectOptions; private static ConnectionMultiplexer? connection; private static IDatabase? database; - + static Redis() { - if ( string.IsNullOrEmpty( Config.RedisServerAddress ) || Config.RedisServerPort < 0 || Config.RedisServerPort > 65536 || string.IsNullOrEmpty( Config.RedisUserName ) || string.IsNullOrEmpty( Config.RedisUserPassword ) ) { + if ( string.IsNullOrEmpty( Program.Configuration.RedisServerAddress ) || Program.Configuration.RedisServerPort < 0 || Program.Configuration.RedisServerPort > 65536 || string.IsNullOrEmpty( Program.Configuration.RedisUserName ) || string.IsNullOrEmpty( Program.Configuration.RedisUserPassword ) ) { Log.Error( "One or more of the Redis connection details and/or Redis user credentials configuration properties are not set!" ); Environment.Exit( 1 ); return; } - connectOptions = ConfigurationOptions.Parse( $"{Config.RedisServerAddress}:{Config.RedisServerPort}" ); + connectOptions = ConfigurationOptions.Parse( $"{Program.Configuration.RedisServerAddress}:{Program.Configuration.RedisServerPort}" ); connectOptions.ClientName = Assembly.GetExecutingAssembly().GetName().Name; - connectOptions.User = Config.RedisUserName; - connectOptions.Password = Config.RedisUserPassword; + connectOptions.User = Program.Configuration.RedisUserName; + connectOptions.Password = Program.Configuration.RedisUserPassword; connectOptions.AbortOnConnectFail = false; Log.Info( "Initialized Redis connection options." ); } @@ -32,7 +33,7 @@ public static async Task Open() { if ( database != null && connection != null && connection.IsConnected ) throw new Exception( "Redis connection already opened" ); connection = await ConnectionMultiplexer.ConnectAsync( connectOptions ); - database = connection.GetDatabase( Config.RedisDatabase ); + database = connection.GetDatabase( Program.Configuration.RedisDatabase ); } public static async Task Close() { @@ -42,12 +43,13 @@ public static async Task Close() { public static async Task Set( string key, string value ) { if ( database == null || connection == null || !connection.IsConnected ) throw new Exception( "Redis connection not yet opened" ); - await database.StringSetAsync( Config.RedisKeyPrefix + key, value ); + await database.StringSetAsync( Program.Configuration.RedisKeyPrefix + key, value ); } public static async Task Get( string key ) { if ( database == null || connection == null || !connection.IsConnected ) throw new Exception( "Redis connection not yet opened" ); - return await database.StringGetAsync( Config.RedisKeyPrefix + key ); + return await database.StringGetAsync( Program.Configuration.RedisKeyPrefix + key ); } } +*/ diff --git a/Source/Shared.cs b/Source/Shared.cs index 5222a75..0c7ffee 100644 --- a/Source/Shared.cs +++ b/Source/Shared.cs @@ -18,7 +18,7 @@ public static class Shared { public static readonly HttpClient httpClient = new(); public static UserAccessToken? UserAccessToken; - public static readonly string UserAccessTokenFilePath = Path.Combine( Config.DataDirectory, "UserAccessToken.json" ); + public static readonly string UserAccessTokenFilePath = Path.Combine( Program.Configuration.DataDirectory, "UserAccessToken.json" ); public static readonly Dictionary SslProtocolNames = new() { { SslProtocols.Tls, "TLSv1.0" }, @@ -57,15 +57,15 @@ public static bool IsWindows() { public static void CreateDirectories() { // Create the persistent data directory - if ( !Directory.Exists( Config.DataDirectory ) ) { - Directory.CreateDirectory( Config.DataDirectory ); - Log.Info( "Created data directory: '{0}'.", Config.DataDirectory ); + if ( !Directory.Exists( Program.Configuration.DataDirectory ) ) { + Directory.CreateDirectory( Program.Configuration.DataDirectory ); + Log.Info( "Created data directory: '{0}'.", Program.Configuration.DataDirectory ); } // Create the cache directory - if ( !Directory.Exists( Config.CacheDirectory ) ) { - Directory.CreateDirectory( Config.CacheDirectory ); - Log.Info( "Created cache directory: '{0}'.", Config.CacheDirectory ); + if ( !Directory.Exists( Program.Configuration.CacheDirectory ) ) { + Directory.CreateDirectory( Program.Configuration.CacheDirectory ); + Log.Info( "Created cache directory: '{0}'.", Program.Configuration.CacheDirectory ); } } diff --git a/Source/Twitch/API.cs b/Source/Twitch/API.cs index 1293ef6..6f92870 100644 --- a/Source/Twitch/API.cs +++ b/Source/Twitch/API.cs @@ -14,7 +14,7 @@ public async static Task Request( string endpoint, HttpMethod? metho // Construct the URL string queryString = queryParameters != null ? $"?{queryParameters.ToQueryString()}" : ""; - Uri targetUrl = new( $"https://{Config.TwitchAPIBaseURL}/{endpoint}{queryString}" ); + Uri targetUrl = new( $"https://{Program.Configuration.TwitchAPIBaseURL}/{endpoint}{queryString}" ); // Create the request, defaulting to GET HttpRequestMessage httpRequest = new( method ?? HttpMethod.Get, targetUrl.ToString() ); @@ -23,7 +23,7 @@ public async static Task Request( string endpoint, HttpMethod? metho httpRequest.Headers.Accept.Add( MediaTypeWithQualityHeaderValue.Parse( "application/json" ) ); // Add the OAuth credentials as headers - httpRequest.Headers.Add( "Client-Id", Config.TwitchOAuthIdentifier ); + httpRequest.Headers.Add( "Client-Id", Program.Configuration.TwitchOAuthClientIdentifier ); httpRequest.Headers.Authorization = Shared.UserAccessToken!.GetAuthorizationHeader(); // Set the request body, if one is provided diff --git a/Source/Twitch/Channel.cs b/Source/Twitch/Channel.cs index 38d42f8..d6e73d3 100644 --- a/Source/Twitch/Channel.cs +++ b/Source/Twitch/Channel.cs @@ -131,13 +131,13 @@ public void UpdateProperties( viral32111.InternetRelayChat.Message ircMessage ) } // Sends a chat message, can be as a reply to another message - public async Task SendMessage( string message, Message? replyTo = null ) => await Client.SendAsync( viral32111.InternetRelayChat.Command.PrivateMessage, + public async Task SendMessage( string message, Message? replyTo = null ) => await Client.SendAsync( new( "PRIVMSG", middle: $"#{Name}", parameters: message, tags: replyTo != null ? new() { { "reply-parent-msg-id", replyTo.Identifier.ToString() } } : null - ); + ) ); // Fetches a list of streams for this channel public async Task FetchStreams( int limit = 100 ) { diff --git a/Source/Twitch/Client.cs b/Source/Twitch/Client.cs index 343e4be..b25eb8f 100644 --- a/Source/Twitch/Client.cs +++ b/Source/Twitch/Client.cs @@ -64,7 +64,7 @@ public Client() { public async Task RequestCapabilities( string[] desiredCapabilities ) { // Send the capabilities request, and wait for response message(s) - viral32111.InternetRelayChat.Message responseMessage = await SendWaitResponseAsync( viral32111.InternetRelayChat.Command.RequestCapabilities, string.Join( ' ', desiredCapabilities ) ); + viral32111.InternetRelayChat.Message responseMessage = ( await SendWaitResponseAsync( new( "CAP REQ", middle: string.Join( ' ', desiredCapabilities ) ) ) )[ 0 ]; // Get a list of the granted capabilities from the response message string[]? grantedCapabilities = responseMessage.Parameters?.Split( ' ' ); @@ -167,7 +167,7 @@ private async void ProcessMessage( object sender, MessagedEventArgs e ) { } // Did someone send a chat message in a channel? - } else if ( !e.Message.IsFromSystem() && e.Message.Command == viral32111.InternetRelayChat.Command.PrivateMessage && e.Message.Middle != null && e.Message.Parameters != null && e.Message.Tags.Count > 0 ) { + } else if ( !e.Message.IsFromSystem() && e.Message.Command == "PRIVMSG" && e.Message.Middle != null && e.Message.Parameters != null && e.Message.Tags.Count > 0 ) { // Update state for channel, channel user & message Channel channel = State.UpdateChannel( e.Message, this ); @@ -178,7 +178,7 @@ private async void ProcessMessage( object sender, MessagedEventArgs e ) { OnChannelChatMessage?.Invoke( this, message ); // Has a user (that isn't us) joined a channel's chat? - } else if ( !e.Message.IsFromSystem() && e.Message.User != null && e.Message.Command == viral32111.InternetRelayChat.Command.Join && e.Message.Middle != null ) { + } else if ( !e.Message.IsFromSystem() && e.Message.User != null && e.Message.Command == "JOIN" && e.Message.Middle != null ) { // Find the channel in state Channel? channel = State.FindChannelByName( e.Message.Middle[ 1.. ] ) ?? throw new Exception( "Received user join for an unknown channel" ); @@ -191,7 +191,7 @@ private async void ProcessMessage( object sender, MessagedEventArgs e ) { OnGlobalUserJoinChannel?.Invoke( this, globalUser, channel, false ); // Has a user left a channel's chat? - } else if ( !e.Message.IsFromSystem() && e.Message.User != null && e.Message.Command == viral32111.InternetRelayChat.Command.Leave && e.Message.Middle != null ) { + } else if ( !e.Message.IsFromSystem() && e.Message.User != null && e.Message.Command == "PART" && e.Message.Middle != null ) { // Find the channel in state Channel? channel = State.FindChannelByName( e.Message.Middle[ 1.. ] ) ?? throw new Exception( "Received user leave for an unknown channel" ); diff --git a/Source/Twitch/OAuth/AppAccessToken.cs b/Source/Twitch/OAuth/AppAccessToken.cs index 40dbfa5..2b77650 100644 --- a/Source/Twitch/OAuth/AppAccessToken.cs +++ b/Source/Twitch/OAuth/AppAccessToken.cs @@ -44,7 +44,7 @@ public AppAccessToken( TokenType type, string access, DateTimeOffset expiresAt ) public async Task Validate() { Shared.httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "OAuth", Access ); - HttpResponseMessage validateResponse = await Shared.httpClient.GetAsync( $"https://{Config.TwitchOAuthBaseURL}/validate" ); + HttpResponseMessage validateResponse = await Shared.httpClient.GetAsync( $"https://{Program.Configuration.TwitchOAuthBaseURL}/validate" ); //Stream responseStream = await validateResponse.Content.ReadAsStreamAsync(); //JsonDocument responseDocument = await JsonDocument.ParseAsync( responseStream ); diff --git a/Source/Twitch/OAuth/UserAccessToken.cs b/Source/Twitch/OAuth/UserAccessToken.cs index 8170f41..8436e2e 100644 --- a/Source/Twitch/OAuth/UserAccessToken.cs +++ b/Source/Twitch/OAuth/UserAccessToken.cs @@ -59,7 +59,7 @@ public static UserAccessToken Load( string filePath ) { try { scopes = storage.Get( "scopes" ); } catch { // Backwards compatibility as old file never contained scopes - scopes = Config.TwitchOAuthScopes; + scopes = Program.Configuration.TwitchOAuthScopes; isOldFile = true; } @@ -77,8 +77,8 @@ public static async Task RequestAuthorization( string redirectU string stateSecret = Shared.GenerateRandomString( 16 ); - string authorizationUrl = QueryHelpers.AddQueryString( $"https://{Config.TwitchOAuthBaseURL}/authorize", new Dictionary() { - { "client_id", Config.TwitchOAuthIdentifier }, + string authorizationUrl = QueryHelpers.AddQueryString( $"https://{Program.Configuration.TwitchOAuthBaseURL}/authorize", new Dictionary() { + { "client_id", Program.Configuration.TwitchOAuthClientIdentifier }, { "force_verify", "true" }, { "redirect_uri", redirectUri }, { "response_type", "code" }, @@ -89,7 +89,7 @@ public static async Task RequestAuthorization( string redirectU Log.Info( "Waiting for the authorization to complete..." ); string? authorizationCode = null; - await WebServer.ListenFor( Config.TwitchOAuthRedirectURL, async ( HttpListenerContext context ) => { + await WebServer.ListenFor( Program.Configuration.TwitchOAuthRedirectURL, async ( HttpListenerContext context ) => { NameValueCollection collection = HttpUtility.ParseQueryString( context.Request!.Url!.Query ); @@ -143,11 +143,11 @@ await WebServer.ListenFor( Config.TwitchOAuthRedirectURL, async ( HttpListenerCo private static async Task GrantAuthorization( string authorizationCode, string redirectUri ) { - if ( string.IsNullOrEmpty( Config.TwitchOAuthSecret ) ) throw new Exception( "Twitch OAuth Secret is missing" ); + if ( string.IsNullOrEmpty( Program.Configuration.TwitchOAuthClientSecret ) ) throw new Exception( "Twitch OAuth Secret is missing" ); - HttpResponseMessage grantResponse = await Shared.httpClient.PostAsync( $"https://{Config.TwitchOAuthBaseURL}/token", new FormUrlEncodedContent( new Dictionary() { - { "client_id", Config.TwitchOAuthIdentifier }, - { "client_secret", Config.TwitchOAuthSecret }, + HttpResponseMessage grantResponse = await Shared.httpClient.PostAsync( $"https://{Program.Configuration.TwitchOAuthBaseURL}/token", new FormUrlEncodedContent( new Dictionary() { + { "client_id", Program.Configuration.TwitchOAuthClientIdentifier }, + { "client_secret", Program.Configuration.TwitchOAuthClientSecret }, { "code", authorizationCode }, { "grant_type", "authorization_code" }, { "redirect_uri", redirectUri }, @@ -184,11 +184,11 @@ private static async Task GrantAuthorization( string authorizat public async Task DoRefresh() { - if ( string.IsNullOrEmpty( Config.TwitchOAuthSecret ) ) throw new Exception( "Twitch OAuth Secret is missing" ); + if ( string.IsNullOrEmpty( Program.Configuration.TwitchOAuthClientSecret ) ) throw new Exception( "Twitch OAuth Secret is missing" ); - HttpResponseMessage refreshResponse = await Shared.httpClient.PostAsync( $"https://{Config.TwitchOAuthBaseURL}/token", new FormUrlEncodedContent( new Dictionary() { - { "client_id", Config.TwitchOAuthIdentifier }, - { "client_secret", Config.TwitchOAuthSecret }, + HttpResponseMessage refreshResponse = await Shared.httpClient.PostAsync( $"https://{Program.Configuration.TwitchOAuthBaseURL}/token", new FormUrlEncodedContent( new Dictionary() { + { "client_id", Program.Configuration.TwitchOAuthClientIdentifier }, + { "client_secret", Program.Configuration.TwitchOAuthClientSecret }, { "grant_type", "refresh_token" }, { "refresh_token", Refresh }, } ) );