Skip to content

Commit

Permalink
Update config elsewhere
Browse files Browse the repository at this point in the history
  • Loading branch information
viral32111 committed Aug 13, 2023
1 parent 0a263b3 commit 665a8a1
Show file tree
Hide file tree
Showing 11 changed files with 81 additions and 76 deletions.
4 changes: 2 additions & 2 deletions Source/Cloudflare.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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" );
}
}

Expand Down
30 changes: 15 additions & 15 deletions Source/Configuration.cs
Original file line number Diff line number Diff line change
Expand Up @@ -149,98 +149,98 @@ private set {
/// https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#authorization-code-grant-flow
/// </summary>
[ JsonPropertyName( "twitch-oauth-base-url" ) ]
public static readonly string TwitchOAuthBaseURL = "https://id.twitch.tv/oauth2";
public readonly string TwitchOAuthBaseURL = "https://id.twitch.tv/oauth2";

/// <summary>
/// The client identifier of the Twitch OAuth application.
/// https://dev.twitch.tv/docs/authentication/register-app/
/// </summary>
[ JsonPropertyName( "twitch-oauth-client-identifier" ) ]
public static readonly string TwitchOAuthClientIdentifier = "";
public readonly string TwitchOAuthClientIdentifier = "";

/// <summary>
/// The client secret of the Twitch OAuth application.
/// https://dev.twitch.tv/docs/authentication/register-app/
/// </summary>
[ JsonPropertyName( "twitch-oauth-client-secret" ) ]
public static readonly string TwitchOAuthClientSecret = "";
public readonly string TwitchOAuthClientSecret = "";

/// <summary>
/// The redirect URL of the Twitch OAuth application.
/// https://dev.twitch.tv/docs/authentication/register-app/
/// </summary>
[ 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";

/// <summary>
/// The scopes to request on behalf of the Twitch OAuth application.
/// https://dev.twitch.tv/docs/authentication/scopes/
/// </summary>
[ JsonPropertyName( "twitch-oauth-scopes" ) ]
public static readonly string[] TwitchOAuthScopes = new[] { "chat:read", "chat:edit" };
public readonly string[] TwitchOAuthScopes = new[] { "chat:read", "chat:edit" };

/// <summary>
/// The IP address of the Twitch chat IRC server.
/// https://dev.twitch.tv/docs/irc/#connecting-to-the-twitch-irc-server
/// </summary>
[ JsonPropertyName( "twitch-chat-address" ) ]
public static readonly string TwitchChatAddress = "irc.chat.twitch.tv";
public readonly string TwitchChatAddress = "irc.chat.twitch.tv";

/// <summary>
/// The port number of the Twitch chat IRC server.
/// https://dev.twitch.tv/docs/irc/#connecting-to-the-twitch-irc-server
/// </summary>
[ JsonPropertyName( "twitch-chat-port" ) ]
public static readonly int TwitchChatPort = 6697;
public readonly int TwitchChatPort = 6697;

/// <summary>
/// The identifier of the primary Twitch channel.
/// </summary>
[ JsonPropertyName( "twitch-primary-channel-identifier" ) ]
public static readonly int TwitchPrimaryChannelIdentifier = 127154290;
public readonly int TwitchPrimaryChannelIdentifier = 127154290;

/// <summary>
/// The base URL of the Twitch API.
/// https://dev.twitch.tv/docs/api/
/// </summary>
[ JsonPropertyName( "twitch-api-base-url" ) ]
public static readonly string TwitchAPIBaseURL = "https://api.twitch.tv/helix";
public readonly string TwitchAPIBaseURL = "https://api.twitch.tv/helix";

/// <summary>
/// The URL of the Twitch EventSub WebSocket.
/// https://dev.twitch.tv/docs/eventsub/handling-websocket-events/
/// </summary>
[ 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";

/// <summary>
/// The IP address of the MongoDB server.
/// </summary>
[ JsonPropertyName( "mongodb-server-address" ) ]
public static readonly string MongoDBServerAddress = "127.0.0.1";
public readonly string MongoDBServerAddress = "127.0.0.1";

/// <summary>
/// The port number of the MongoDB server.
/// </summary>
[ JsonPropertyName( "mongodb-server-port" ) ]
public static readonly int MongoDBServerPort = 27017;
public readonly int MongoDBServerPort = 27017;

/// <summary>
/// The username of the MongoDB user.
/// </summary>
[ JsonPropertyName( "mongodb-user-name" ) ]
public static readonly string MongoDBUserName = "";
public readonly string MongoDBUserName = "";

/// <summary>
/// The password of the MongoDB user.
/// </summary>
[ JsonPropertyName( "mongodb-user-password" ) ]
public static readonly string MongoDBUserPassword = "";
public readonly string MongoDBUserPassword = "";

/// <summary>
/// The name of the MongoDB database.
/// </summary>
[ JsonPropertyName( "mongodb-database-name" ) ]
public static readonly string MongoDBDatabaseName = "twitch-bot";
public readonly string MongoDBDatabaseName = "twitch-bot";

}
18 changes: 9 additions & 9 deletions Source/Database/Mongo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand All @@ -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();
Expand Down
31 changes: 17 additions & 14 deletions Source/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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 );
Expand All @@ -61,29 +58,33 @@ 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<string> databaseCollectionNames = await Mongo.Database.ListCollectionNames().ToListAsync();
Log.Info( "Found {0} collection(s) in the database: {1}.", databaseCollectionNames.Count, string.Join( ", ", databaseCollectionNames ) );

// 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 {
Expand All @@ -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 );
}

Expand Down Expand Up @@ -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();
Expand All @@ -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..." );
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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 );
Expand Down
18 changes: 10 additions & 8 deletions Source/Redis.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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." );
}
Expand All @@ -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() {
Expand All @@ -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<string?> 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 );
}
}
*/
14 changes: 7 additions & 7 deletions Source/Shared.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<SslProtocols, string> SslProtocolNames = new() {
{ SslProtocols.Tls, "TLSv1.0" },

Check warning on line 24 in Source/Shared.cs

View workflow job for this annotation

GitHub Actions / Build & Test

'SslProtocols.Tls' is obsolete: 'TLS versions 1.0 and 1.1 have known vulnerabilities and are not recommended. Use a newer TLS version instead, or use SslProtocols.None to defer to OS defaults.' (https://aka.ms/dotnet-warnings/SYSLIB0039)
Expand Down Expand Up @@ -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 );
}

}
Expand Down
4 changes: 2 additions & 2 deletions Source/Twitch/API.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public async static Task<JsonObject> 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() );
Expand All @@ -23,7 +23,7 @@ public async static Task<JsonObject> 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
Expand Down
4 changes: 2 additions & 2 deletions Source/Twitch/Channel.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Stream[]> FetchStreams( int limit = 100 ) {
Expand Down
Loading

0 comments on commit 665a8a1

Please sign in to comment.