summaryrefslogtreecommitdiff
path: root/src/handlers/playCommand.js
blob: 5551d280cf443463e2affdd16a77273fc837d526 (plain)
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
const { EmbedBuilder } = require('discord.js');
const { 
  createAudioPlayer, 
  joinVoiceChannel,
  AudioPlayerStatus,
  VoiceConnectionStatus,
  entersState,
} = require('@discordjs/voice');
const { getVideoInfo, playSong, preloadSong, formatDuration, safeCleanup, clearSongBuffer } = require('../utils/player');
const { requireVoiceChannel } = require('../utils/helpers');

function createSongsFromVideos(videos, requestedBy) {
  return videos.map(v => ({
    title: v.title,
    url: v.url,
    duration: v.duration,
    thumbnail: v.thumbnail,
    requestedBy: requestedBy,
  }));
}

function onPlayerIdle(interaction, queue) {
  console.log(`[PLAYER IDLE] Guild: ${interaction.guild.id}, Loop mode: ${queue.loopMode}, Is seeking: ${queue.isSeeking || false}`);
  
  safeCleanup(queue, 'Player Idle');
  
  if (queue.isSeeking) {
    console.log(`[IDLE SKIP] Skipping queue shift because seek is in progress`);
    return;
  }
  
  if (queue.loopMode === 'song') {
    if (queue.songs[0]) {
      queue.songs[0].retryCount = 0;
    }
    playSong(interaction.guild.id, queue);
  } else if (queue.loopMode === 'queue') {
    const finishedSong = queue.songs.shift();
    queue.songs.push(finishedSong);
    if (queue.songs.length > 0) {
      playSong(interaction.guild.id, queue);
    }
  } else {
    const finishedSong = queue.songs.shift();
    clearSongBuffer(finishedSong, 'finished playing');
    if (queue.songs.length > 0) {
      playSong(interaction.guild.id, queue);
    } else {
      console.log(`[QUEUE EMPTY] Guild: ${interaction.guild.id}`);
    }
  }
}

function onPlayerError(error, interaction, queue) {
  console.error('Audio player error:', error);
  safeCleanup(queue, 'Player Error');
  
  if (queue.isSeeking) {
    console.log(`[ERROR DURING SEEK] Not shifting queue, seek in progress`);
    queue.isSeeking = false;
    return;
  }
  
  queue.songs.shift();
  if (queue.songs.length > 0) {
    playSong(interaction.guild.id, queue);
  }
}

function onPlayerAutoPaused(player) {
  console.warn('Player auto-paused, attempting to resume...');
  try {
    player.unpause();
  } catch (err) {
    console.error('Failed to unpause:', err);
  }
}

function onConnectionError(error, queue) {
  console.error('Voice connection error:', error);
  safeCleanup(queue, 'Connection Error');
}

async function onConnectionDisconnected(connection, queues, guildId) {
  try {
    await Promise.race([
      entersState(connection, VoiceConnectionStatus.Signalling, 5000),
      entersState(connection, VoiceConnectionStatus.Connecting, 5000),
    ]);
  } catch (error) {
    connection.destroy();
    queues.delete(guildId);
  }
}

function onConnectionDestroyed(queues, guildId) {
  queues.delete(guildId);
}

function setupPlayerEventListeners(player, interaction, queue) {
  player.on(AudioPlayerStatus.Idle, () => onPlayerIdle(interaction, queue));
  player.on('error', (error) => onPlayerError(error, interaction, queue));
  player.on(AudioPlayerStatus.AutoPaused, () => onPlayerAutoPaused(player));
}

function setupConnectionEventListeners(connection, queues, guildId, queue) {
  connection.on('error', (error) => onConnectionError(error, queue));
  connection.on(VoiceConnectionStatus.Disconnected, () => 
    onConnectionDisconnected(connection, queues, guildId)
  );
  connection.on(VoiceConnectionStatus.Destroyed, () => 
    onConnectionDestroyed(queues, guildId)
  );
}

async function createVoiceConnection(voiceChannel, interaction) {
  const connection = joinVoiceChannel({
    channelId: voiceChannel.id,
    guildId: interaction.guild.id,
    adapterCreator: voiceChannel.guild.voiceAdapterCreator,
  });

  try {
    await entersState(connection, VoiceConnectionStatus.Ready, 30000);
    return connection;
  } catch (error) {
    console.error('Failed to join voice channel:', error);
    connection.destroy();
    throw error;
  }
}

async function initializeQueue(voiceChannel, interaction, queues, songs) {
  const player = createAudioPlayer();
  let connection;
  
  try {
    connection = await createVoiceConnection(voiceChannel, interaction);
  } catch (error) {
    return null;
  }

  connection.subscribe(player);

  const queue = {
    voiceChannel,
    connection,
    player,
    songs: songs,
    volume: 50,
    isPlaying: false,
    loopMode: 'off',
  };

  queues.set(interaction.guild.id, queue);

  setupPlayerEventListeners(player, interaction, queue);
  setupConnectionEventListeners(connection, queues, interaction.guild.id, queue);

  return queue;
}

function addSongsToQueue(queue, songs, interaction) {
  const oldLength = queue.songs.length;
  const wasIdle = queue.player.state.status === AudioPlayerStatus.Idle;
  
  songs.forEach(song => queue.songs.push(song));
  const newLength = queue.songs.length;
  
  console.log(`[QUEUE ADD] Guild: ${interaction.guild.id}, Added ${songs.length} songs, Queue: ${oldLength} -> ${newLength}, Player state: ${queue.player.state.status}, Was idle: ${wasIdle}`);
  
  if (wasIdle && oldLength === 0 && queue.songs.length > 0) {
    if (queue.isSeeking) {
      console.log(`[AUTO-PLAY BLOCKED] Seek in progress, not starting playback`);
    } else {
      console.log(`[AUTO-PLAY] Starting playback, songs in queue: ${queue.songs.length}`);
      playSong(interaction.guild.id, queue);
    }
  }
  
  if (queue.songs.length >= 2) {
    const nextSong = queue.songs[1];
    if (!nextSong.audioBuffer && !nextSong.isPreloading) {
      console.log(`[PRELOAD TRIGGER] Preloading next song: ${nextSong.title}`);
      preloadSong(nextSong).catch(() => {});
    }
  }

  return wasIdle;
}

function createNewPlaybackEmbed(firstSong, isPlaylist, songs) {
  const embed = new EmbedBuilder()
    .setColor(0x00ff00)
    .setTitle(isPlaylist ? 'Playlist Added' : 'Now Playing')
    .setDescription(`**${firstSong.title}**`)
    .addFields(
      { name: 'Duration', value: formatDuration(firstSong.duration), inline: true },
      { name: 'Requested by', value: firstSong.requestedBy, inline: true }
    )
    .setThumbnail(firstSong.thumbnail);

  if (isPlaylist) {
    embed.addFields({ name: 'Playlist', value: `${songs.length} songs added to queue` });
  }

  return embed;
}

function createAddToQueueEmbed(firstSong, isPlaylist, songs, queuePosition) {
  const embed = new EmbedBuilder()
    .setColor(0x00ff00)
    .setTitle(isPlaylist ? 'Playlist Added to Queue' : 'Added to Queue')
    .setDescription(`**${firstSong.title}**`)
    .addFields(
      { name: 'Position', value: `${queuePosition}`, inline: true },
      { name: 'Requested by', value: firstSong.requestedBy, inline: true }
    )
    .setThumbnail(firstSong.thumbnail);

  if (isPlaylist) {
    embed.addFields({ name: 'Playlist', value: `${songs.length} songs added to queue` });
  }

  return embed;
}

async function handlePlay(interaction, queues) {
  await interaction.deferReply();
  
  const query = interaction.options.getString('query');
  const voiceChannel = requireVoiceChannel(interaction);
  if (!voiceChannel) return;
  
  const videoInfo = await getVideoInfo(query);
  if (!videoInfo) {
    return interaction.editReply('Could not find that video!');
  }

  const isPlaylist = videoInfo.isPlaylist;
  const videos = videoInfo.videos;

  if (!videos || videos.length === 0) {
    return interaction.editReply('Could not find any videos!');
  }

  const songs = createSongsFromVideos(videos, interaction.user.tag);
  const firstSong = songs[0];

  let queue = queues.get(interaction.guild.id);

  if (!queue) {
    queue = await initializeQueue(voiceChannel, interaction, queues, songs);
    
    if (!queue) {
      return interaction.editReply('Failed to join voice channel! Try again.');
    }

    const embed = createNewPlaybackEmbed(firstSong, isPlaylist, songs);
    interaction.editReply({ embeds: [embed] });
    playSong(interaction.guild.id, queue);
  } else {
    const queuePosition = queue.songs.length - songs.length + 1;
    addSongsToQueue(queue, songs, interaction);
    
    const embed = createAddToQueueEmbed(firstSong, isPlaylist, songs, queuePosition);
    interaction.editReply({ embeds: [embed] });
  }
}

module.exports = { handlePlay };