diff --git a/commands/seek.mjs b/commands/seek.mjs index 3aa91f7..0008f15 100644 --- a/commands/seek.mjs +++ b/commands/seek.mjs @@ -42,6 +42,12 @@ export async function run(msg, data) { return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.paused"))] }); } + const current = p.queue.getCurrent(); + + if (current?.type === "radio" || current?.isLive || p._getTrackDurationMs(current) === 0) { + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.live"))] }); + } + let seekMs = Utils.parseDuration(positionInput); if (!seekMs || seekMs < 0) { return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.invalidFormat"))] }); diff --git a/src/core/BotVoiceMixin.mjs b/src/core/BotVoiceMixin.mjs index e1c6fcc..9e06760 100644 --- a/src/core/BotVoiceMixin.mjs +++ b/src/core/BotVoiceMixin.mjs @@ -499,7 +499,7 @@ const BotVoiceMixin = { await player.playNext(); - if (current && pos > 0) { + if (current && pos > 0 && dur > 0) { await new Promise((r) => setTimeout(r, 800)); // let the bridge settle try { await player.seekToPosition(pos); } catch (_) {} } diff --git a/src/db/PlayerStateStore.mjs b/src/db/PlayerStateStore.mjs index 651cd11..b0a670b 100644 --- a/src/db/PlayerStateStore.mjs +++ b/src/db/PlayerStateStore.mjs @@ -4,24 +4,6 @@ * survive bot reboots/crashes. One row per (bot_id, guild_id) holding a JSON * snapshot of the player: voice channel, text channel, queue tracks, current * track, resume position, volume and loop modes. - * - * WHY MySQL AND NOT REDIS/FILES: - * - The bot already owns a MySQL pool (RemoteSettingsManager) that is flushed - * on graceful shutdown; snapshots ride the same healthy connection and are - * durable across restarts of ANY component. - * - The project's Redis handle (dashboard RedisHandler) is a pub/sub cache - * whose client is closed on shutdown — it is the wrong place for state - * that must outlive a reboot. - * - Local JSON files were audited and removed from the hot path years ago - * (storage/stats.json has no writer left); adding file writes would make - * the bot slower, not faster. - * - * Write pattern: - * - Full snapshot: debounced 3s per player, triggered by queue/playback - * events (see Player.mjs). - * - Position heartbeat: single cheap UPDATE of the position_ms column every - * 15s while a track is playing, so resume-after-crash lands within ~15s - * of where the song actually was. */ import { logger } from "../core/Logger.mjs"; diff --git a/src/music/player/DisplayMixin.mjs b/src/music/player/DisplayMixin.mjs index ad2b0c1..12a4082 100644 --- a/src/music/player/DisplayMixin.mjs +++ b/src/music/player/DisplayMixin.mjs @@ -79,6 +79,12 @@ const DisplayMixin = { ? `${vid.title} - ${vid.url}` : `[${vid.title}](${vid.url})`; } + if (vid.isLive || vid.type === "livestream") { + const link = vid.url || ""; + return code + ? `${vid.title} (LIVE) - ${link}` + : `🔴 [${vid.title}](${link}) — **LIVE**`; + } const elapsed = this.getCurrentElapsedDuration(); const total = this.getDuration(vid.duration); const link = vid.spotifyUrl || vid.url || ""; diff --git a/src/music/player/PlaybackMixin.mjs b/src/music/player/PlaybackMixin.mjs index d5897e1..1901f05 100644 --- a/src/music/player/PlaybackMixin.mjs +++ b/src/music/player/PlaybackMixin.mjs @@ -37,9 +37,7 @@ const PlaybackMixin = { this._lastPlayedTrack = this.queue.getCurrent() ?? songData; this.queue.current = null; this.emit("stopplay"); - if (!this._is247Enabled()) { - this._startInactivityTimer(); - } + this._scheduleRadioReconnect(songData); return; } @@ -173,6 +171,7 @@ const PlaybackMixin = { this._pausedAt = null; this._queueEndedSent = false; this._consecutiveErrors = 0; + this._radioReconnects = 0; if (songData.type !== "radio" || !this._radioAnnounced) { this.announceSong(songData); @@ -362,6 +361,31 @@ const PlaybackMixin = { this._skipping = false; }, + /** + * @private Re-arm the same radio station after its stream drops. Live + * streams end on network hiccups, not on purpose — retry twice (3s apart) + * before giving the channel back to the inactivity timer. A user-queued + * song or an intentional leave during the wait window cancels it. + * @this {import('./Player.mjs').Player} + * @param {object} track - The radio track object that ended. + */ + _scheduleRadioReconnect(track) { + const maxRetries = 2; + if ((this._radioReconnects ?? 0) >= maxRetries || !track?.url) { + this._radioReconnects = 0; + if (!this._is247Enabled()) this._startInactivityTimer(); + return; + } + this._radioReconnects = (this._radioReconnects ?? 0) + 1; + logger.player(`[Player] Radio stream ended — reconnecting (${this._radioReconnects}/${maxRetries}) in 3s: ${track.title}`); + setTimeout(() => { + if (this._destroyed || this.leaving || !this._voiceConn) return; + if (this.queue.getCurrent() || !this.queue.isEmpty()) return; + this.queue.add(track); + this.playNext().catch(e => logger.error("[Player] Radio reconnect playNext error:", e.message)); + }, 3_000).unref?.(); + }, + /** * @private Clear the track-end timer. * @this {import('./Player.mjs').Player} diff --git a/src/music/player/SearchMixin.mjs b/src/music/player/SearchMixin.mjs index 233a6e4..c31cc78 100644 --- a/src/music/player/SearchMixin.mjs +++ b/src/music/player/SearchMixin.mjs @@ -148,6 +148,7 @@ const SearchMixin = { videoId: info.identifier ?? "", encoded: track.encoded ?? info.encoded ?? "", sourceName: info.sourceName ?? "unknown", + isLive: info.isLive === true, title: Utils.cleanTitle(info.title ?? "Unknown"), url: trackUri, thumbnail: info.artworkUrl ?? null, @@ -292,20 +293,36 @@ const SearchMixin = { } if (lcTracks.length === 0) { - if (!isUrl && source !== "ytmsearch") { - events.emit("message", "No results from primary source, trying YouTube Music..."); - const fallback = await this._lavalink.search(searchQuery, { source: "ytmsearch" }); - if (fallback?.tracks?.length > 0) { - const video = this._lcTrackToVideo(fallback.tracks[0], trackMeta); - if (video) { - this.addToQueue(video, top); - events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue."); - if (!this.queue.getCurrent()) { - this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + if (!isUrl) { + const FALLBACKS = [ + { source: "ytmsearch", label: "YouTube Music" }, + { source: "ytsearch", label: "YouTube" }, + { source: "scsearch", label: "SoundCloud" }, + ].filter(f => f.source !== source); + + for (const fb of FALLBACKS) { + events.emit("message", "No results yet — trying **" + fb.label + "**..."); + let fbResult = null; + try { + fbResult = await this._lavalink.search(searchQuery, { source: fb.source }); + } catch (_) { fbResult = null; } + if (fbResult?.tracks?.length > 0) { + const video = this._lcTrackToVideo(fbResult.tracks[0], trackMeta); + if (video) { + this.addToQueue(video, top); + events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue. *(found on " + fb.label + ")*"); + if (!this.queue.getCurrent()) { + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + } + return; } - return; } } + } else { + const lavasrcHost = /(?:open\.spotify\.com|spotify\.link|music\.apple\.com|tidal\.com|deezer\.com|deezer\.page\.link|music\.youtube\.com\/playlist)/i; + try { if (lavasrcHost.test(new URL(query.trim()).hostname)) { + events.emit("message", "⚠️ This link needs the **LavaSrc plugin** on the audio node, which isn't available. Try the song/playlist **name** instead — e.g. `%play `."); + } } catch (_) {} } events.emit("message", "**No results found for '" + query + "'.**"); return; @@ -328,6 +345,9 @@ const SearchMixin = { if (video) { this.addToQueue(video, top); events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue."); + if (playlistQuery) { + events.emit("message", "⚠️ Couldn't load the full playlist — added just this video."); + } } else { events.emit("message", "**Failed to parse track data.**"); return; diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index 3e80573..52cbff9 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -775,6 +775,7 @@ "seek": { "nothingPlaying": "❌ لا يوجد شيء يعمل حالياً!", "paused": "❌ لا يمكن الانتقال أثناء الإيقاف المؤقت. استأنف أولاً.", + "live": "❌ هذا بث مباشر أو راديو — لا يمكن الانتقال إلى موضع محدد.", "invalidFormat": "❌ تنسيق موضع غير صالح. استخدم `mm:ss` أو `hh:mm:ss` أو ثوانٍ (مثلاً `1:30`، `90`).", "exceedsDuration": "❌ موضع الانتقال يتجاوز مدة المقطع (**{{duration}}**).", "seeked": "⏩ تم الانتقال إلى **{{position}}**", diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index 4b1ec2e..2c190cf 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -775,6 +775,7 @@ "seek": { "nothingPlaying": "❌ هیچ شتێک پەخش ناکرێت لە ئێستادا!", "paused": "❌ ناتوانرێت لە کاتی وەستاودا بگەڕێیتەوە. سەرەتا بەردەوامبکە.", + "live": "❌ ئەمە پەخشێکی ڕاستەوخۆ یان ڕادیۆیە — ناتوانرێت بگوازرێتەوە بۆ شوێنێکی دیاریکراو.", "invalidFormat": "❅ شێوازی شوێنی نادروست. `mm:ss`، `hh:mm:ss`، یان چرکە بەکاربهێنە (بۆ نموونە `1:30`، `90`).", "exceedsDuration": "❌ شوێنی گەڕانەوە لە ماوەی تراکەکە زیاترە (**{{duration}}**).", "seeked": "⏩ گەڕایەوە بۆ **{{position}}**", diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index f729d3d..9cc67dd 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -775,6 +775,7 @@ "seek": { "nothingPlaying": "❌ Es wird gerade nichts abgespielt!", "paused": "❌ Kann nicht springen während pausiert. Zuerst fortsetzen.", + "live": "❌ Das ist ein Livestream oder Radio — Spulen wird hier nicht unterstützt.", "invalidFormat": "❌ Ungültiges Positionsformat. Nutze `mm:ss`, `hh:mm:ss` oder Sekunden (z.B. `1:30`, `90`).", "exceedsDuration": "❌ Sprungposition überschreitet Track-Dauer (**{{duration}}**).", "seeked": "⏩ Gesprungen zu **{{position}}**", diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index a91f933..a7879b6 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -776,6 +776,7 @@ "seek": { "nothingPlaying": "❌ There's nothing playing at the moment!", "paused": "❌ Can't seek while paused. Resume first.", + "live": "❌ This is a live stream or radio — you can't seek in it.", "invalidFormat": "❌ Invalid position format. Use `mm:ss`, `hh:mm:ss`, or seconds (e.g. `1:30`, `90`).", "exceedsDuration": "❌ Seek position exceeds track duration (**{{duration}}**).", "seeked": "⏩ Seeked to **{{position}}**", diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index 76228df..d875d7b 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -775,6 +775,7 @@ "seek": { "nothingPlaying": "❌ Não está tocando nada no momento!", "paused": "❌ Não é possível buscar enquanto pausado. Retome primeiro.", + "live": "❌ Isto é uma transmissão ao vivo ou rádio — não é possível buscar uma posição.", "invalidFormat": "❌ Formato de posição inválido. Use `mm:ss`, `hh:mm:ss`, ou segundos (ex: `1:30`, `90`).", "exceedsDuration": "❌ Posição de busca excede a duração da faixa (**{{duration}}**).", "seeked": "⏩ Pulou para **{{position}}**", diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index 6b992f9..0ff36bd 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -738,6 +738,7 @@ "seek": { "nothingPlaying": "❌ Şu anda çalan bir şey yok!", "paused": "❌ Duraklatılmışken konuma gidilemez. Önce devam ettirin.", + "live": "❌ Bu canlı bir yayın veya radyo — belirli bir konuma geçilemez.", "invalidFormat": "❌ Geçersiz konum biçimi. `dd:ss`, `sa:dd:ss` veya saniye kullanın (örn. `1:30`, `90`).", "exceedsDuration": "❌ Konum parça süresini aşıyor (**{{duration}}**).", "seeked": "⏩ **{{position}}** konumuna gidildi",