This repository has been archived by the owner on May 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Music.cs
279 lines (244 loc) · 10.4 KB
/
Music.cs
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
268
269
270
271
272
273
274
275
276
277
278
279
using System;
using System.Data;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent;
using Discord.Audio;
using Discord.WebSocket;
using System.IO;
using System.Linq;
using System.Diagnostics;
using System.Threading;
namespace csharp
{
class BotMusic : IDisposable
{
private static readonly Lazy<BotMusic> lazy = new Lazy<BotMusic>(() => new BotMusic());
private readonly ConcurrentDictionary<ulong, IAudioClient> voiceConnections;
private readonly ConcurrentDictionary<ulong, ConcurrentQueue<string>> playQueuePerserver;
private readonly ConcurrentDictionary<ulong, SocketVoiceChannel> voiceChannels;
private readonly ConcurrentDictionary<ulong, Task> serverDispatchers;
private readonly ConcurrentDictionary<ulong, CancellationTokenSource> dispatcherCancelTokens;
public static BotMusic Instance
{
get
{
return lazy.Value;
}
}
private BotMusic()
{
voiceConnections = new ConcurrentDictionary<ulong, IAudioClient>();
voiceChannels = new ConcurrentDictionary<ulong, SocketVoiceChannel>();
playQueuePerserver = new ConcurrentDictionary<ulong, ConcurrentQueue<string>>();
serverDispatchers = new ConcurrentDictionary<ulong, Task>();
dispatcherCancelTokens = new ConcurrentDictionary<ulong, CancellationTokenSource>();
if (!Directory.Exists(Directory.GetCurrentDirectory() + "/" + "Music"))
{
Directory.CreateDirectory(Directory.GetCurrentDirectory() + "/" + "Music");
}
}
public async Task LeaveAll()
{
foreach (var conn in voiceConnections)
{
await conn.Value.StopAsync();
conn.Value.Dispose();
voiceConnections.Remove(conn.Key, out _);
}
foreach (var channel in voiceChannels)
{
await channel.Value.DisconnectAsync();
voiceChannels.Remove(channel.Key, out _);
}
}
public async Task JoinVoiceChannel(SocketMessage message, string[] args)
{
if (!(message.Author is SocketGuildUser messageAuthor))
{
await message.Channel.SendMessageAsync("This command only works in a server");
return;
}
if (messageAuthor.VoiceChannel == null)
{
await message.Channel.SendMessageAsync("You must be in a voice channel first");
return;
}
try
{
var conn = await messageAuthor.VoiceChannel.ConnectAsync();
if (voiceConnections.ContainsKey(messageAuthor.Guild.Id))
{
voiceConnections.Remove(messageAuthor.Guild.Id, out _);
voiceChannels.Remove(messageAuthor.Guild.Id, out _);
}
voiceConnections.TryAdd(messageAuthor.Guild.Id, conn);
voiceChannels.TryAdd(messageAuthor.Guild.Id, messageAuthor.VoiceChannel);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public async Task LeaveVoiceChannel(SocketMessage message, string[] args)
{
if (!(message.Author is SocketGuildUser messageAuthor))
{
await message.Channel.SendMessageAsync("This command only works in a server");
return;
}
if (!voiceConnections.TryGetValue(messageAuthor.Guild.Id, out var conn))
{
await message.Channel.SendMessageAsync("I'm already not in a voice channel");
return;
}
voiceChannels.Remove(messageAuthor.Guild.Id, out var channel);
await channel.DisconnectAsync();
voiceConnections.Remove(messageAuthor.Guild.Id, out _);
conn.Dispose();
}
public async Task PlayMusic(SocketMessage message, string[] args)
{
if (!(message.Author is SocketGuildUser messageAuthor))
{
await message.Channel.SendMessageAsync("This command only works in a server");
return;
}
if (!voiceConnections.TryGetValue(messageAuthor.Guild.Id, out var conn))
{
//await message.Channel.SendMessageAsync("I'm not in a voice channel, joining...");
await this.JoinVoiceChannel(message, args);
if (!voiceConnections.ContainsKey(messageAuthor.Guild.Id))
{
return;
}
}
if (!Uri.TryCreate(args[1], UriKind.Absolute, out _))
{
await message.Channel.SendMessageAsync("That is not a valid youtube URL");
return;
}
playQueuePerserver.ContainsKey(messageAuthor.Guild.Id);
await message.Channel.SendMessageAsync("adding to queue...");
var playQueue = playQueuePerserver.GetOrAdd(messageAuthor.Guild.Id, new ConcurrentQueue<string>());
playQueue.Enqueue(args[1]);
if (serverDispatchers.TryGetValue(messageAuthor.Guild.Id, out var dispatcher))
{
if (dispatcher.IsCompleted) serverDispatchers.Remove(messageAuthor.Guild.Id, out _);
else return;
}
var toAddDispatcher = BeginDispatcher(messageAuthor.Guild.Id);
serverDispatchers.TryAdd(messageAuthor.Guild.Id, toAddDispatcher);
}
private Task BeginDispatcher(ulong guildID)
{
return Task.Run(async () =>
{
var token = new CancellationTokenSource();
dispatcherCancelTokens.TryAdd(guildID, token);
if (!voiceConnections.TryGetValue(guildID, out var conn))
{
await Program.Log(new Discord.LogMessage(Discord.LogSeverity.Error, "music", "no voice connection"));
return;
}
playQueuePerserver.TryGetValue(guildID, out var queue);
Process ffmpeg;
Stream output;
AudioOutStream discord;
Console.WriteLine(queue.Count);
while (!queue.IsEmpty)
{
if (token.IsCancellationRequested)
{
dispatcherCancelTokens.Remove(guildID, out _);
token.Dispose();
token = new CancellationTokenSource();
dispatcherCancelTokens.TryAdd(guildID, token);
}
queue.TryDequeue(out var toDownload);
Console.WriteLine("Downloading " + toDownload);
DownloadVideo(toDownload, guildID.ToString()).WaitForExit();
using (ffmpeg = CreateStream(Directory.GetCurrentDirectory() + "/" + "Music/" + guildID.ToString() + ".m4a"))
using (output = ffmpeg.StandardOutput.BaseStream)
using (discord = conn.CreatePCMStream(AudioApplication.Mixed))
{
int blockSize = 3480;
byte[] buffer = new byte[blockSize]; //block size of 3480
try
{
while(true)
{
int byteCount = await output.ReadAsync(buffer, 0, blockSize);
if(byteCount == 0 || token.IsCancellationRequested) break;
await discord.WriteAsync(buffer, 0, byteCount);
}
//await output.CopyToAsync(discord, 81920, token.Token);
discord.Clear();
}
catch (Exception e)
{
await Program.Log(new Discord.LogMessage(Discord.LogSeverity.Info, "music", e.Message, e));
}
finally { await discord.FlushAsync(); }
}
}
});
}
private Process DownloadVideo(string url, string fname)
{
fname = Directory.GetCurrentDirectory() + "/" + "Music/" + fname;
if (File.Exists(fname))
{
File.Delete(fname);
}
return Process.Start(new ProcessStartInfo
{
FileName = "youtube-dl",
Arguments = $"{url} -x -o {fname}.m4a",
UseShellExecute = true,
RedirectStandardOutput = false,
});
}
private Process CreateStream(string path)
{
return Process.Start(new ProcessStartInfo
{
FileName = "ffmpeg",
Arguments = $"-hide_banner -loglevel panic -i \"{path}\" -ac 2 -f s16le -ar 48000 pipe:1",
UseShellExecute = false,
RedirectStandardOutput = true,
});
}
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
LeaveAll().Wait();
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
// TODO: set large fields to null.
disposedValue = true;
}
}
// TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
~BotMusic()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(false);
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// TODO: uncomment the following line if the finalizer is overridden above.
GC.SuppressFinalize(this);
}
#endregion
}
}