-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathBotManager.cs
More file actions
267 lines (226 loc) · 9.97 KB
/
BotManager.cs
File metadata and controls
267 lines (226 loc) · 9.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
using System;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using KickFuckerApi.Data;
using KickFuckerApi.Models;
using Microsoft.EntityFrameworkCore;
namespace KickFuckerApi.Services
{
public class BotManager
{
private readonly ConcurrentDictionary<int, BotInstance> _botInstances = new();
private int _nextKey = 1;
private readonly IServiceScopeFactory _serviceScopeFactory;
private readonly CancellationTokenSource _cancellationTokenSource = new();
public BotManager(IServiceScopeFactory serviceScopeFactory)
{
_serviceScopeFactory = serviceScopeFactory;
_ = SyncKickViewTasks(_cancellationTokenSource.Token);
}
public async Task<KickViewTask> StartWatchingChannelAsync(string channel, int count, int delay)
{
var key = _nextKey++;
var botInstance = new BotInstance();
_botInstances.TryAdd(key, botInstance);
botInstance.BotStopped += BotInstanceOnBotStopped;
_ = Task.Run(() => botInstance.Start(channel, count, delay));
var kickViewTask = new KickViewTask
{
CreatedAt = DateTime.UtcNow,
TargetChannel = channel,
TargetViewCount = count,
CurrentStatus = KickViewTaskStatus.Initializing,
};
using var scope = _serviceScopeFactory.CreateScope();
var databaseContext = scope.ServiceProvider.GetRequiredService<KickFuckerDbContext>();
databaseContext.KickViewTasks.Add(kickViewTask);
await databaseContext.SaveChangesAsync();
botInstance.KickViewTaskId = kickViewTask.Id;
return kickViewTask;
}
private void BotInstanceOnBotStopped(object? sender, EventArgs e)
{
if (sender is BotInstance stoppedBot)
{
// Find the key associated with the stopped bot instance
int? keyToRemove = null;
foreach (var keyValuePair in _botInstances)
{
if (keyValuePair.Value == stoppedBot)
{
keyToRemove = keyValuePair.Key;
break;
}
}
if (keyToRemove != null)
{
// Remove the stopped bot instance from the dictionary
_botInstances.TryRemove(keyToRemove.Value, out _);
// Unsubscribe from the BotStopped event
stoppedBot.BotStopped -= BotInstanceOnBotStopped;
}
// Perform any additional cleanup or logging tasks here
Console.WriteLine($"Bot instance with key {keyToRemove} has stopped watching channel.");
}
}
public BotInstance GetBotInstance(int key)
{
_botInstances.TryGetValue(key, out var botInstance);
return botInstance;
}
public ConcurrentDictionary<int, BotInstance> GetAllBotInstances()
{
return _botInstances;
}
public void StopWatchingChannel(int key, int delay)
{
if (_botInstances.TryGetValue(key, out var botInstance))
{
_ = botInstance.StopAsync(delay);
_botInstances.TryRemove(key, out _);
}
}
public async Task<KickViewTask> GetKickViewTaskByIdAsync(int id)
{
using var scope = _serviceScopeFactory.CreateScope();
var databaseContext = scope.ServiceProvider.GetRequiredService<KickFuckerDbContext>();
return await databaseContext.KickViewTasks.FindAsync(id);
}
public async Task<List<KickViewTask>> GetAllKickViewTasksAsync()
{
using var scope = _serviceScopeFactory.CreateScope();
var databaseContext = scope.ServiceProvider.GetRequiredService<KickFuckerDbContext>();
// Retrieve and return the list of KickViewTasks
return await databaseContext.KickViewTasks.ToListAsync();
}
public async Task<bool> StopKickViewTaskAsync(int taskId, int delay)
{
using var scope = _serviceScopeFactory.CreateScope();
var databaseContext = scope.ServiceProvider.GetRequiredService<KickFuckerDbContext>();
var kickViewTask = await databaseContext.KickViewTasks.FindAsync(taskId);
if (kickViewTask != null)
{
kickViewTask.CurrentStatus = KickViewTaskStatus.Stopping;
await databaseContext.SaveChangesAsync();
// Find the associated BotInstance and stop it
foreach (var botInstance in _botInstances.Values)
{
if (botInstance.KickViewTaskId == taskId)
{
_ = botInstance.StopAsync(delay);
break;
}
}
kickViewTask.CurrentStatus = KickViewTaskStatus.Completed;
await databaseContext.SaveChangesAsync();
return true;
}
return false;
}
private KickViewTaskStatus MapBotStatusToKickViewTaskStatus(BotStatus botStatus)
{
return botStatus switch
{
BotStatus.Starting => KickViewTaskStatus.Initializing,
BotStatus.Started => KickViewTaskStatus.Running,
BotStatus.Stopping => KickViewTaskStatus.Stopping,
BotStatus.Stopped => KickViewTaskStatus.Completed,
_ => throw new ArgumentOutOfRangeException(nameof(botStatus), botStatus, "Invalid bot status value."),
};
}
private async Task SyncKickViewTasks(CancellationToken cancellationToken)
{
bool firstTime = true;
while (!cancellationToken.IsCancellationRequested)
{
using var scope = _serviceScopeFactory.CreateScope();
var databaseContext = scope.ServiceProvider.GetRequiredService<KickFuckerDbContext>();
if (firstTime)
{
foreach (var t in databaseContext.KickViewTasks)
{
t.CurrentStatus = KickViewTaskStatus.Completed;
}
firstTime = false;
}
foreach (var keyValuePair in _botInstances)
{
int key = keyValuePair.Key;
BotInstance botInstance = keyValuePair.Value;
// Find the KickViewTask using the BotInstance.KickViewTaskId property
var kickViewTask = await databaseContext.KickViewTasks.FindAsync(botInstance.KickViewTaskId);
if (kickViewTask != null)
{
// Update the KickViewTask with the current state of the BotInstance
kickViewTask.ActiveViewers = botInstance.WorkingClients;
kickViewTask.CurrentStatus = MapBotStatusToKickViewTaskStatus(botInstance.Status);
}
}
foreach (var task in databaseContext.KickViewTasks.Where(t => t.CurrentStatus == KickViewTaskStatus.Running))
{
bool botInstanceExists = false;
foreach (var keyValuePair in _botInstances)
{
int key = keyValuePair.Key;
BotInstance botInstance = keyValuePair.Value;
if (botInstance.KickViewTaskId == task.Id)
{
botInstanceExists = true;
break;
}
}
if (!botInstanceExists)
{
task.CurrentStatus = KickViewTaskStatus.Completed;
}
}
// Save changes to the database
await databaseContext.SaveChangesAsync();
// Wait for a given interval before syncing again
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
}
}
public async Task IncreaseViewersAsync(int taskId, int count, int delay)
{
using var scope = _serviceScopeFactory.CreateScope();
var databaseContext = scope.ServiceProvider.GetRequiredService<KickFuckerDbContext>();
var kickViewTask = await databaseContext.KickViewTasks.FindAsync(taskId);
if (kickViewTask != null)
{
foreach (var botInstance in _botInstances.Values)
{
if (botInstance.KickViewTaskId == taskId)
{
_ = Task.Run(() => botInstance.IncreaseViewersAsync(count, delay));
break;
}
}
}
else
{
throw new KeyNotFoundException("No KickViewTask found with the given ID");
}
}
public async Task DecreaseViewersAsync(int taskId, int count, int delay)
{
using var scope = _serviceScopeFactory.CreateScope();
var databaseContext = scope.ServiceProvider.GetRequiredService<KickFuckerDbContext>();
var kickViewTask = await databaseContext.KickViewTasks.FindAsync(taskId);
if (kickViewTask != null)
{
foreach (var botInstance in _botInstances.Values)
{
if (botInstance.KickViewTaskId == taskId)
{
_ = botInstance.DecreaseViewersAsync(count, delay);
break;
}
}
}
else
{
throw new KeyNotFoundException("No KickViewTask found with the given ID");
}
}
}
}