Skip to content

Commit 609a069

Browse files
csharpfritzmozts2005
authored andcommitted
Fixed hosted services so they run in the background, added PubSubAuthToken configuration option
1 parent 3f0b44a commit 609a069

File tree

7 files changed

+60
-14
lines changed

7 files changed

+60
-14
lines changed

Fritz.StreamTools/Services/GitHubService.cs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ public class GitHubService : IHostedService
1515
{
1616

1717
public static DateTime LastUpdate = DateTime.MinValue;
18+
private CancellationToken _Token;
19+
private Task _RunningTask;
1820

1921
public GitHubService(IServiceProvider services, ILogger<GitHubService> logger)
2022
{
@@ -27,22 +29,24 @@ public GitHubService(IServiceProvider services, ILogger<GitHubService> logger)
2729

2830
public Task StartAsync(CancellationToken cancellationToken)
2931
{
30-
return MonitorUpdates(cancellationToken);
32+
_Token = cancellationToken;
33+
_RunningTask = MonitorUpdates();
34+
return Task.CompletedTask;
3135
}
3236

3337
public Task StopAsync(CancellationToken cancellationToken)
3438
{
3539
return Task.CompletedTask;
3640
}
3741

38-
private async Task MonitorUpdates(CancellationToken cancellationToken)
42+
private async Task MonitorUpdates()
3943
{
4044
var lastRequest = DateTime.Now;
4145
using (var scope = Services.CreateScope())
4246
{
4347
var repo = scope.ServiceProvider.GetService(typeof(GitHubRepository)) as GitHubRepository;
4448
var mcGithubFaceClient = scope.ServiceProvider.GetService(typeof(GithubyMcGithubFaceClient)) as GithubyMcGithubFaceClient;
45-
while (!cancellationToken.IsCancellationRequested)
49+
while (!_Token.IsCancellationRequested)
4650
{
4751
if (repo != null)
4852
{
@@ -56,7 +60,7 @@ private async Task MonitorUpdates(CancellationToken cancellationToken)
5660
mcGithubFaceClient?.UpdateGitHub("", "", 0);
5761
}
5862
}
59-
await Task.Delay(500, cancellationToken);
63+
await Task.Delay(500, _Token);
6064
}
6165
}
6266
}

Fritz.StreamTools/Services/TwitchPubSubService.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ public class TwitchPubSubService : IHostedService
1919
{
2020

2121
private IServiceProvider _ServiceProvider;
22+
private CancellationToken _Token;
23+
private Task _BackgroundTask;
2224
private readonly Twitch.PubSub.Proxy _Proxy;
2325
private readonly ConfigurationSettings _Configuration;
2426

@@ -32,7 +34,9 @@ public TwitchPubSubService(IServiceProvider serviceProvider, Twitch.PubSub.Proxy
3234
public Task StartAsync(CancellationToken cancellationToken)
3335
{
3436
_Proxy.OnChannelPointsRedeemed += _Proxy_OnChannelPointsRedeemed;
35-
return _Proxy.StartAsync(new TwitchTopic[] { TwitchTopic.ChannelPoints(_Configuration.UserId) }, cancellationToken);
37+
_Token = cancellationToken;
38+
_BackgroundTask = _Proxy.StartAsync(new TwitchTopic[] { TwitchTopic.ChannelPoints(_Configuration.UserId) }, _Token);
39+
return Task.CompletedTask;
3640
}
3741

3842
private void _Proxy_OnChannelPointsRedeemed(object sender, ChannelRedemption e)

Fritz.StreamTools/Startup.cs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public void Configure(IApplicationBuilder app, IHostEnvironment env, IConfigurat
4949
}
5050

5151
app.UseHsts();
52-
app.UseHttpsRedirection();
52+
//app.UseHttpsRedirection();
5353

5454
app.UseStaticFiles();
5555

@@ -62,6 +62,8 @@ public void Configure(IApplicationBuilder app, IHostEnvironment env, IConfigurat
6262
endpoints.MapHub<GithubyMcGithubFace>("/github");
6363
endpoints.MapHub<AttentionHub>("/attentionhub");
6464

65+
endpoints.MapRazorPages();
66+
6567
endpoints.MapDefaultControllerRoute();
6668

6769
});

Fritz.StreamTools/StartupServices/ConfigureServices.cs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public static void Execute(IServiceCollection services, IConfiguration configura
4949
// Add the SentimentSink
5050
//services.AddSingleton<Fritz.Chatbot.Commands.SentimentSink>();
5151

52-
services.AddSingleton<IHostedService, FritzBot>();
52+
services.AddHostedService<FritzBot>();
5353

5454
services.AddSingleton(new GitHubClient(new ProductHeaderValue("Fritz.StreamTools")));
5555
FritzBot.RegisterCommands(services);
@@ -119,6 +119,7 @@ private static void AddStreamingServices(this IServiceCollection services, IConf
119119
c => !bool.TryParse(c["StreamServices:Fake:Enabled"], out var enabled) || !enabled); // Test to disable
120120

121121
services.AddSingleton<StreamService>();
122+
122123
}
123124

124125
/// <summary>
@@ -133,7 +134,7 @@ private static void AddStreamService<TStreamService>(this IServiceCollection ser
133134
IConfiguration configuration,
134135
Func<IConfiguration, ILoggerFactory, TStreamService> factory,
135136
Func<IConfiguration, bool> isDisabled)
136-
where TStreamService : class, IStreamService
137+
where TStreamService : class, IStreamService, IHostedService
137138
{
138139

139140
// Don't configure this service if it is disabled
@@ -174,6 +175,8 @@ private static void AddAspNetFeatures(this IServiceCollection services)
174175

175176
}).AddMessagePackProtocol();
176177

178+
services.AddRazorPages();
179+
177180
services.AddMvc()
178181
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
179182

@@ -182,7 +185,9 @@ private static void AddAspNetFeatures(this IServiceCollection services)
182185
private static void RegisterTwitchPubSub(this IServiceCollection services) {
183186

184187
services.AddSingleton<Twitch.PubSub.Proxy>();
188+
185189
services.AddHostedService<TwitchPubSubService>();
190+
186191
//var provider = services.BuildServiceProvider();
187192

188193
//var pubSub = new TwitchPubSubService(

Fritz.StreamTools/appsettings.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"ClientId": "",
1818
"UserId": "",
1919
"ChatToken": "",
20+
"PubSubAuthToken": "",
2021
"ChatBotName": "FritzBot_"
2122
},
2223
"Mixer": {

Fritz.Twitch/ConfigurationSettings.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,8 @@ public class ConfigurationSettings
1717

1818
public virtual string OAuthToken { get; set; }
1919

20+
public virtual string PubSubAuthToken { get; set; }
21+
2022
[Obsolete]
2123
public string Channel { get => ChannelName; set => ChannelName = value; }
2224

Fritz.Twitch/PubSub/Proxy.cs

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,17 @@ public class Proxy : IDisposable {
2020
private ClientWebSocket _Socket;
2121
private System.Timers.Timer _PingTimer;
2222
private System.Timers.Timer _PongTimer;
23-
private readonly ConfigurationSettings _Configuration;
24-
private readonly ILogger _Logger;
23+
private System.Timers.Timer _ReconnectTimer = new System.Timers.Timer();
24+
private ConfigurationSettings _Configuration;
25+
private ILogger _Logger;
2526
private static bool _Reconnect;
2627

27-
public Proxy(IOptions<ConfigurationSettings> settings, ILoggerFactory loggerFactory) {
28+
private static readonly TimeSpan[] _ReconnectTimeouts = new TimeSpan[] {
29+
TimeSpan.FromSeconds(10), TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(1), TimeSpan.FromMinutes(5)
30+
};
31+
32+
public Proxy(IOptions<ConfigurationSettings> settings, ILoggerFactory loggerFactory)
33+
{
2834

2935
InitializeMethodStrategies();
3036

@@ -36,6 +42,7 @@ public Proxy(IOptions<ConfigurationSettings> settings, ILoggerFactory loggerFact
3642
public async Task StartAsync(IEnumerable<TwitchTopic> topics, CancellationToken token) {
3743

3844
_Topics = topics;
45+
_Reconnect = false;
3946

4047
// Start a timer to manage the connection over the websocket
4148
_PingTimer = new System.Timers.Timer(TimeSpan.FromSeconds(30).TotalMilliseconds);
@@ -77,14 +84,35 @@ public async Task StartAsync(IEnumerable<TwitchTopic> topics, CancellationToken
7784
}
7885

7986
if (_Reconnect) {
87+
if (!_ReconnectTimeouts.Any(t => t.TotalMilliseconds == _ReconnectTimer.Interval)) {
88+
_ReconnectTimer.Interval = _ReconnectTimeouts[0].TotalMilliseconds;
89+
_Logger.LogError($"Unable to connect to Twitch PubSub. Reconnecting in {_ReconnectTimeouts[0].TotalSeconds} seconds");
90+
}
91+
else if (_ReconnectTimeouts.Last().TotalMilliseconds == _ReconnectTimer.Interval) {
92+
_Reconnect = false;
93+
_Logger.LogError("Unable to connect to Twitch PubSub. Ceasing attempting to connect");
94+
} else {
95+
96+
for (var i=0; i<_ReconnectTimeouts.Length; i++) {
97+
if (_ReconnectTimeouts[i].TotalMilliseconds == _ReconnectTimer.Interval) {
98+
_Logger.LogError($"Unable to connect to Twitch PubSub. Reconnecting in {_ReconnectTimeouts[i + 1].TotalSeconds} seconds");
99+
_ReconnectTimer.Interval = _ReconnectTimeouts[i + 1].TotalMilliseconds;
100+
break;
101+
}
102+
}
103+
104+
105+
}
106+
107+
await Task.Delay((int)_ReconnectTimer.Interval);
80108
break;
109+
81110
}
82111

83112
}
84113

85-
if (_Reconnect) {
86-
_ = Task.Run(() => StartAsync(topics, token));
87-
}
114+
// if (_Reconnect) _ = Task.Run(() => StartAsync(topics, token));
115+
88116
}
89117

90118

0 commit comments

Comments
 (0)