Skip to content

Commit

Permalink
Fixes : Bot Services (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
satpal123 authored Jan 11, 2024
1 parent 27941c9 commit 04e8c05
Show file tree
Hide file tree
Showing 34 changed files with 9,821 additions and 10,176 deletions.
13 changes: 8 additions & 5 deletions TrackMaster/Controllers/OverlayController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,16 @@ public IActionResult SaveSettings(OverlaySettingsModel overlaySettingsModel)
{
SettingsHelper settingsHelper = new(_dataFields);

MainSettingsModel = settingsHelper.GetSettings(_dataFields.Appfullpath);
settingsHelper.SetMainSettings(MainSettingsModel.TwitchCredentials, overlaySettingsModel, MainSettingsModel.DiscordCredentials);
_dataFields.ShowArtwork = overlaySettingsModel.DisplayAlbumArt;
if (_dataFields.Appfullpath != null)
{
MainSettingsModel = settingsHelper.GetSettings(_dataFields.Appfullpath);
settingsHelper.SetMainSettings(MainSettingsModel.TwitchCredentials, overlaySettingsModel, MainSettingsModel.DiscordCredentials);
_dataFields.ShowArtwork = overlaySettingsModel.DisplayAlbumArt;

_tracklisthubContext.Clients.All.SendAsync("Overlay", overlaySettingsModel.DisplayAlbumArt);
_tracklisthubContext.Clients.All.SendAsync("Overlay", overlaySettingsModel.DisplayAlbumArt);

_dataFields.IsConnectedTwitch = false;
_dataFields.IsConnectedTwitch = false;
}
}

return Json(new { title = "Notification", message = "Settings saved!", result = overlaySettingsModel });
Expand Down
29 changes: 18 additions & 11 deletions TrackMaster/Controllers/SettingsController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@
using TrackMaster.Helper;
using TrackMaster.Hubs;
using TrackMaster.Models;
using ITimerHostedServiceDiscord = TrackMaster.Services.DiscordServices.ITimerHostedService;
using ITimerHostedServiceTwitch = TrackMaster.Services.TwitchServices.ITimerHostedService;
using TrackMaster.Services.DiscordServices;
using TrackMaster.Services.TwitchServices;

namespace TrackMaster.Controllers
{
public class SettingsController : Controller
{
private MainSettingsModel MainSettingsModel;
private readonly DataFields _dataFields;
private readonly ITimerHostedServiceTwitch _hostedTwitchService;
private readonly ITimerHostedServiceDiscord _hostedDiscordService;
private readonly TwitchBot _hostedTwitchService;
private readonly DiscordBot _hostedDiscordService;
private readonly IHubContext<TrackistHub> _tracklisthubContext;

public SettingsController(ITimerHostedServiceTwitch hostedTwitchService, ITimerHostedServiceDiscord hostedDiscordService,
public SettingsController(TwitchBot hostedTwitchService, DiscordBot hostedDiscordService,
DataFields dataFields, IHubContext<TrackistHub> synchub)
{
_hostedTwitchService = hostedTwitchService;
Expand Down Expand Up @@ -68,10 +68,13 @@ public IActionResult SaveTwitchSettings(MainSettingsModel mainSettingsModel)
{
SettingsHelper settingsHelper = new(_dataFields);

MainSettingsModel = settingsHelper.GetSettings(_dataFields.Appfullpath);
settingsHelper.SetMainSettings(mainSettingsModel.TwitchCredentials, MainSettingsModel.OverlaySettings, MainSettingsModel.DiscordCredentials);
if(_dataFields.Appfullpath != null)
{
MainSettingsModel = settingsHelper.GetSettings(_dataFields.Appfullpath);
settingsHelper.SetMainSettings(mainSettingsModel.TwitchCredentials, MainSettingsModel.OverlaySettings, MainSettingsModel.DiscordCredentials);

_dataFields.IsConnectedTwitch = false;
_dataFields.IsConnectedTwitch = false;
}
}

return Json(new { title = "Notification", message = "Twitch Settings saved!", result = mainSettingsModel });
Expand All @@ -85,10 +88,14 @@ public IActionResult SaveDiscordSettings(MainSettingsModel mainSettingsModel)
{
SettingsHelper settingsHelper = new(_dataFields);

MainSettingsModel = settingsHelper.GetSettings(_dataFields.Appfullpath);
settingsHelper.SetMainSettings(MainSettingsModel.TwitchCredentials, MainSettingsModel.OverlaySettings, mainSettingsModel.DiscordCredentials);
if (_dataFields.Appfullpath != null)
{
MainSettingsModel = settingsHelper.GetSettings(_dataFields.Appfullpath);
settingsHelper.SetMainSettings(MainSettingsModel.TwitchCredentials, MainSettingsModel.OverlaySettings, mainSettingsModel.DiscordCredentials);

_dataFields.IsConnectedDiscord = false;
_dataFields.IsConnectedDiscord = false;
}

}

return Json(new { title = "Notification", message = "Discord Settings saved!", result = mainSettingsModel });
Expand Down
4 changes: 2 additions & 2 deletions TrackMaster/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
.UseSerilog()
.ConfigureServices(services =>
{
services.AddHostedService<TwitchBot>(); //Connect to Twitch
services.AddHostedService<DiscordBot>(); //Connect to Discord Channel
//services.AddHostedService<TwitchBot>(); //Connect to Twitch
//services.AddHostedService<DiscordBot>(); //Connect to Discord Channel
//Add more services to connect to here and create a service class under services.
services.AddHostedService<Sniffy>();
services.AddSingleton<DataFields>();
Expand Down
29 changes: 20 additions & 9 deletions TrackMaster/Services/DiscordServices/DiscordBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
using TrackMaster.Models;

namespace TrackMaster.Services.DiscordServices
{
public interface ITimerHostedService : IHostedService {}
public class DiscordBot : ITimerHostedService
{
public class DiscordBot : IHostedService
{
private DiscordSocketClient client;
private readonly IHubContext<TrackistHub> _tracklisthubContext;
Expand All @@ -26,7 +25,6 @@ public class DiscordBot : ITimerHostedService
private readonly DataFields _dataFields;

private static DiscordBot _instance;

public static DiscordBot Instance => _instance;

public DiscordBot(IHubContext<TrackistHub> synchub, ILogger<DiscordBot> logger, DataFields dataFields)
Expand All @@ -41,9 +39,13 @@ public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("DiscordBot Service is Starting");

DoWork();
Task.Run(async () =>
{
await DoWork(cancellationToken);
}, cancellationToken);

_timer = new Timer(CheckStatus, null, TimeSpan.Zero, TimeSpan.FromSeconds(20));
_timer = new Timer(CheckStatus, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

return Task.CompletedTask;
}
Expand All @@ -54,9 +56,17 @@ private void CheckStatus(object state)
{
_tracklisthubContext.Clients.All.SendAsync("DeviceAndTwitchStatus", 4, "Connected to Discord Bot!");
}
else
{
Task.Run(async () =>
{
await DoWork(state);
});
}
}

private async void DoWork()
private async Task DoWork(object state)
{
_logger.LogInformation("Timed Background Service is working.");

Expand Down Expand Up @@ -96,7 +106,7 @@ private async Task Bot()
return Task.CompletedTask;
};
await Task.Delay(-1);
//await Task.Delay(-1);
}
catch (Exception ex)
{
Expand Down Expand Up @@ -125,7 +135,7 @@ private Task ReadyAsync()
return Task.CompletedTask;
}

public async Task SendMessageToDiscord(string message)
public async void SendMessageToDiscord(string message)
{
var channel = client.GetChannel(_discordChannelId) as ITextChannel;
await channel.SendMessageAsync(message, false, flags: MessageFlags.SuppressNotification);
Expand All @@ -138,6 +148,7 @@ private async Task<MainSettingsModel> GetSetDiscordCredentials()
if (HybridSupport.IsElectronActive)
{
string path = await Electron.App.GetPathAsync(PathName.UserData);
Console.WriteLine("Discord: " + path);
_dataFields.Appfullpath = path + @"\Settings.json";
return settingsHelper.GetSettings(_dataFields.Appfullpath);
}
Expand Down
23 changes: 12 additions & 11 deletions TrackMaster/Services/Sniffy/Sniffy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ public class Sniffy : BackgroundService
{
#region Variable declarations
private readonly IHubContext<TrackistHub> _tracklisthubContext;
private readonly DiscordBot _discordBot;
private readonly TwitchBot _twitchBot;
readonly DiscordBot _discordBot;
TwitchBot _twitchBot;

private readonly string _ethernetdevice;
private readonly string _controllerIP;
Expand Down Expand Up @@ -60,16 +60,15 @@ public class Sniffy : BackgroundService
private RestoreTrackMetadataModel RestoreTrackMetadataModel;

#endregion
public Sniffy(IConfiguration configuration, IHubContext<TrackistHub> synchub, ILogger<Sniffy> logger, DataFields dataFields,
DiscordBot discordBot, TwitchBot twitchBot)
public Sniffy(IConfiguration configuration, IHubContext<TrackistHub> synchub, ILogger<Sniffy> logger, DataFields dataFields, TwitchBot twitchBot, DiscordBot discordBot)
{
_tracklisthubContext = synchub;
_ethernetdevice = configuration.GetSection("EthernetDevice").Value;
_controllerIP = configuration.GetSection("ControllerIP").Value;
_dataFields = dataFields;
_logger = logger;
_discordBot = discordBot;
_twitchBot = twitchBot;
_discordBot = discordBot;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
Expand Down Expand Up @@ -741,23 +740,25 @@ private static string HextoString(string InputText)

private void MixStatusChanged(object sender, OverlayChangeObserver.MixStatusChangedEventArgs e)
{


if (e.Player1)
{
_tracklisthubContext.Clients.All.SendAsync("NowPlaying", _dataFields.Trackartist1, _dataFields.Tracktitle1, _dataFields.Albumartid1, _dataFields.ShowArtwork);
TrackHistory(_dataFields.Trackpath);

_discordBot.SendMessageToDiscord(string.Join(@"{0} - {1}", _dataFields.Trackartist1, _dataFields.Tracktitle1)).Wait();
_twitchBot.CurrentTrackPlaying(string.Join(@"{0} - {1}", _dataFields.Trackartist1, _dataFields.Tracktitle1));
_discordBot.SendMessageToDiscord(string.Format(@"{0} - {1}", _dataFields.Trackartist1, _dataFields.Tracktitle1));
_twitchBot.CurrentTrackPlaying(string.Format(@"{0} - {1}", _dataFields.Trackartist1, _dataFields.Tracktitle1));

}
if (e.Player2)
{
_tracklisthubContext.Clients.All.SendAsync("NowPlaying", _dataFields.Trackartist2, _dataFields.Tracktitle2, _dataFields.Albumartid2, _dataFields.ShowArtwork);
TrackHistory(_dataFields.Trackpath2);

_discordBot.SendMessageToDiscord(string.Join(@"{0} - {1}", _dataFields.Trackartist2, _dataFields.Tracktitle2)).Wait();
_twitchBot.CurrentTrackPlaying(string.Join(@"{0} - {1}", _dataFields.Trackartist2, _dataFields.Tracktitle2));
}
_discordBot.SendMessageToDiscord(string.Format(@"{0} - {1}", _dataFields.Trackartist2, _dataFields.Tracktitle2));
_twitchBot.CurrentTrackPlaying(string.Format(@"{0} - {1}", _dataFields.Trackartist2, _dataFields.Tracktitle2));
}
}

private List<string> TrackHistory(string trackMetadata)
Expand Down
59 changes: 35 additions & 24 deletions TrackMaster/Services/TwitchServices/TwitchBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@

namespace TrackMaster.Services.TwitchServices
{
public interface ITimerHostedService : IHostedService {}
public class TwitchBot : ITimerHostedService
public class TwitchBot : IHostedService
{
private TwitchClient client;
private readonly IHubContext<TrackistHub> _tracklisthubContext;
Expand All @@ -29,7 +28,6 @@ public class TwitchBot : ITimerHostedService
private Timer _timer;
private readonly DataFields _dataFields;


private static TwitchBot _instance;

public static TwitchBot Instance => _instance;
Expand All @@ -46,10 +44,12 @@ public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("TwitchBot Service is Starting");

DoWork();

_timer = new Timer(CheckStatus, null, TimeSpan.Zero, TimeSpan.FromSeconds(20));

Task.Run(async () =>
{
await DoWork(cancellationToken);
}, cancellationToken);
_timer = new Timer(CheckStatus, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
return Task.CompletedTask;
}

Expand All @@ -59,9 +59,17 @@ private void CheckStatus(object state)
{
_tracklisthubContext.Clients.All.SendAsync("DeviceAndTwitchStatus", 2, "Connected to Twitch Bot!");
}
else
{
Task.Run(async () =>
{
await DoWork(state);
});
}
}

private async void DoWork()
private async Task DoWork(object state)
{
_logger.LogInformation("Timed Background Service is working.");

Expand Down Expand Up @@ -96,22 +104,23 @@ private async Task Bot()
if (string.IsNullOrEmpty(_twitchUsername) || string.IsNullOrEmpty(_twitchPassword))
throw new ArgumentException();

ConnectionCredentials credentials = new(_twitchUsername, _twitchPassword);
var clientOptions = new ClientOptions
{
MessagesAllowedInPeriod = 750,
ThrottlingPeriod = TimeSpan.FromSeconds(30)
};
WebSocketClient customClient = new(clientOptions);
client = new TwitchClient(customClient);
client.Initialize(credentials, _twitchChannel);
client.OnMessageReceived += Client_OnMessageReceived;
client.OnConnectionError += Client_OnConnectionError;
client.OnIncorrectLogin += Client_OnIncorrectLogin;
client.OnConnected += Client_OnConnected;
client.OnJoinedChannel += Client_OnJoinedChannel;
client.Connect();

await Task.Run(() => {
ConnectionCredentials credentials = new(_twitchUsername, _twitchPassword);
var clientOptions = new ClientOptions
{
MessagesAllowedInPeriod = 750,
ThrottlingPeriod = TimeSpan.FromSeconds(30)
};
WebSocketClient customClient = new(clientOptions);
client = new TwitchClient(customClient);
client.Initialize(credentials, _twitchChannel);
client.OnMessageReceived += Client_OnMessageReceived;
client.OnConnectionError += Client_OnConnectionError;
client.OnIncorrectLogin += Client_OnIncorrectLogin;
client.OnConnected += Client_OnConnected;
client.OnJoinedChannel += Client_OnJoinedChannel;
client.Connect();
});
}
catch (Exception ex)
{
Expand Down Expand Up @@ -174,6 +183,8 @@ private async Task<MainSettingsModel> GetSetTwitchCredentials()
if (HybridSupport.IsElectronActive)
{
string path = await Electron.App.GetPathAsync(PathName.UserData);

Console.WriteLine("Twitch: " + path);
_dataFields.Appfullpath = path + @"\Settings.json";
return settingsHelper.GetSettings(_dataFields.Appfullpath);
}
Expand Down
26 changes: 15 additions & 11 deletions TrackMaster/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,23 @@ public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSignalR();
services.AddElectron();
services.AddSingleton(Configuration);
services.AddSingleton<IHostedService, Sniffy>();
services.AddSingleton<DataFieldsInstance>();
services.AddSingleton<DiscordBot>();
services.AddSingleton<TwitchBot>();
services.AddSingleton<Services.TwitchServices.ITimerHostedService, TwitchBot>(serviceProvider =>
services.AddSingleton<DiscordBot>();
services.AddSingleton<IHostedService, TwitchBot>(serviceProvider =>
{
return TwitchBot.Instance;
});
services.AddSingleton<Services.DiscordServices.ITimerHostedService, DiscordBot>(serviceProvider =>
services.AddSingleton<IHostedService, DiscordBot>(serviceProvider =>
{
return DiscordBot.Instance;
});
services.AddHostedService<TwitchBot>();
services.AddHostedService<DiscordBot>();

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
Expand Down Expand Up @@ -73,20 +77,20 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
});

Task.Run(async () =>
{
{
var browserWindowOptions = new BrowserWindowOptions
{
WebPreferences = new WebPreferences
{
NodeIntegration = false
}
},
Center = true,
Height = 880,
Width = 1450,
AutoHideMenuBar = true,
Resizable = true,
HasShadow = true
};
browserWindowOptions.Center = true;
browserWindowOptions.Height = 880;
browserWindowOptions.Width = 1450;
browserWindowOptions.AutoHideMenuBar = true;
browserWindowOptions.Resizable = true;
browserWindowOptions.HasShadow = true;
var browserWindow = await Electron.WindowManager.CreateWindowAsync(browserWindowOptions);
browserWindow.Show();
Expand Down
Loading

0 comments on commit 04e8c05

Please sign in to comment.