/** * play fix html * sesuain sendiri loh yaa * Base script :https://github.com/Nakano-pdf/itsuki-base * Perintah: * .play2 -> cari lagu (10 hasil) * .play2 -> pilih hasil terakhir: thumbnail, audio penuh, dan kartu lirik * * API (sesuai contoh curl vamxapi): * GET {BASE}/search/spotify?q=&limit=10 header: x-api-key * respons: result.tracks[] { id, title, artist, album, duration, duration_ms, thumbnail, * preview_url, spotify_url, download_api_url } * GET {ORIGIN}{download_api_url} header: x-api-key -> audio penuh * * Key API: `.addapi vamx | https://vamxapi.my.id/api/v1 | | header | x-api-key` * atau config.APIkey.vamx. Key tidak ditulis di dalam plugin. * preview_url hanya cuplikan 30 detik, jadi TIDAK dikirim sebagai lagu penuh. */ /** * Play2 v5 — Final YouTube (Vamx API) + Web Audio Player * Struktur 100% mirip spotify3 (Anti Error 400 & Anti Blank) */ const axios = require('axios') const config = require('../../config') const { getApi } = require('../../src/lib/fixkit/store') const { sendRichCard, esc } = require('../../src/lib/richCard') const assetManager = require('../../src/lib/assetManager') const { spawn } = require('child_process') const fs = require('fs/promises') const os = require('os') const path = require('path') const FOOT = '\n\n> ~ *いつき〜なかの✨* 🌸' const SESSION_MS = 5 * 60 * 1000 const CHUNK = 3000 const LYRIC_MAX_LINES = 150 const API_NAME = 'vamx' const LRCLIB = 'https://lrclib.net/api' const OPUS_MIME = 'audio/webm;codecs=opus' const OPUS_CHAIN = ['24k', '16k', '12k'] const MAX_B64_BYTES = 800_000 const pluginConfig = { name: "play2", alias: ["playaudio2"], category: "search", description: "Putar musik dari YouTube (Vamx API + Web Audio)", usage: ".play2 | .putar-play2 ", example: ".play2 komang", cooldown: 15, energi: 1, isEnabled: true } const sessions = new Map() // ── Util ─────────────────────────────────────────────────────────────────── const fmtTime = (sec) => { const s = Math.max(0, Math.floor(sec)) return `${String(Math.floor(s / 60)).padStart(2, '0')}:${String(s % 60).padStart(2, '0')}` } function fmtNumber(v) { if (v === null || v === undefined || v === '') return '' const n = Number(String(v).replace(/[^\d.-]/g, '')) return isNaN(n) ? '' : n.toLocaleString('id-ID') } function toDataUri(buf) { if (!buf || buf.length < 4) return '' if (buf[0] === 0x89 && buf[1] === 0x50) return `data:image/png;base64,${buf.toString('base64')}` if (buf.slice(0, 4).toString('ascii') === 'RIFF' && buf.slice(8, 12).toString('ascii') === 'WEBP') { return `data:image/webp;base64,${buf.toString('base64')}` } return `data:image/jpeg;base64,${buf.toString('base64')}` } // ── API Vamx (Persis seperti spotify3) ────────────────────────────────────── function buildAuth(api) { const headers = {}, params = {} if (api.authType === 'query') params[api.authName || 'apikey'] = api.apiKey else if (api.authType === 'header') headers[api.authName || 'x-api-key'] = api.apiKey else headers['x-api-key'] = api.apiKey return { headers, params } } async function searchYouTube(q) { const api = getApi(API_NAME) if (!api?.baseURL || !api?.apiKey) throw new Error('API vamx belum terdaftar.') const auth = buildAuth(api) try { const { data } = await axios.get(`${api.baseURL.replace(/\/$/, '')}/search/youtube`, { params: { q, limit: 10, type: 'video', order: 'relevance', ...auth.params }, headers: auth.headers, timeout: 25000, }) return data?.result?.items || [] } catch (e) { throw new Error(`Pencarian gagal: ${e.message}`) } } async function downloadYouTubeAudio(track) { const api = getApi(API_NAME) if (!api?.baseURL || !api?.apiKey) throw new Error('API vamx belum terdaftar') const auth = buildAuth(api) try { // Paksa tembak ke endpoint /download/youtube pakai parameter url const { data } = await axios.get(`${api.baseURL.replace(/\/$/, '')}/download/youtube`, { params: { url: track.url, ...auth.params }, headers: auth.headers, responseType: 'arraybuffer', timeout: 60000, maxContentLength: 50 * 1024 * 1024, }) const checkText = Buffer.from(data.slice(0, 500)).toString('utf-8') if (checkText.trim().startsWith('{')) { const json = JSON.parse(Buffer.from(data).toString('utf-8')) const directUrl = json?.result?.url || json?.data?.url || json?.url if (directUrl && directUrl.startsWith('http')) { const audioRes = await axios.get(directUrl, { responseType: 'arraybuffer', timeout: 60000 }) return Buffer.from(audioRes.data) } throw new Error(json.message || 'Format respon API tidak valid') } return Buffer.from(data) } catch (e) { throw new Error(`Gagal unduh audio: ${e.message}`) } } async function fetchThumb(url) { if (!url) return null try { const { data } = await axios.get(url, { responseType: 'arraybuffer', timeout: 8000, maxContentLength: 5 * 1024 * 1024 }) return Buffer.from(data) } catch { return null } } // ── Kompres Opus + Cek Limit ───────────────────────── function compressOpus(inputBuffer, { bitrate, trimSec = 0, label = 'audio' }) { return new Promise(async (resolve, reject) => { const tmpDir = os.tmpdir() const safe = String(label).replace(/[^a-zA-Z0-9]/g, '') || 'audio' const stamp = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}` const inPath = path.join(tmpDir, `op_in_${safe}_${stamp}.tmp`) const outPath = path.join(tmpDir, `op_out_${safe}_${stamp}.webm`) const cleanup = async () => { try { await fs.unlink(inPath) } catch {} try { await fs.unlink(outPath) } catch {} } try { await fs.writeFile(inPath, inputBuffer) } catch (e) { await cleanup(); return reject(new Error(`tulis input: ${e.message}`)) } const args = [ '-y', '-i', inPath, ...(trimSec > 0 ? ['-t', String(trimSec)] : []), '-vn', '-ac', '1', '-ar', '48000', '-c:a', 'libopus', '-b:a', bitrate, '-vbr', 'on', '-application', 'audio', '-frame_duration', '40', '-compression_level', '10', outPath, ] const ff = spawn('ffmpeg', args) let stderr = '' ff.stderr.on('data', (d) => { stderr += d.toString() }) ff.on('error', async (e) => { await cleanup(); reject(new Error(`ffmpeg error: ${e.message}`)) }) ff.on('close', async (code) => { if (code !== 0) { await cleanup(); return reject(new Error(`ffmpeg exit ${code}: ${stderr.slice(-300)}`)) } try { const out = await fs.readFile(outPath) await cleanup() if (!out?.byteLength) throw new Error('output kosong') resolve(out) } catch (e) { await cleanup(); reject(e) } }) }) } async function compressWithFallback(inputBuffer, durationSec, label) { let best = null for (const bitrate of OPUS_CHAIN) { const buf = await compressOpus(inputBuffer, { bitrate, label }) const b64 = Math.ceil(buf.length * 4 / 3) best = { buf, bitrate, b64len: b64, trimSec: 0 } if (b64 <= MAX_B64_BYTES) return best } const targetRaw = Math.floor(MAX_B64_BYTES * 3 / 4) const ratio = Math.min(1, targetRaw / best.buf.length) * 0.9 const trimSec = Math.max(90, Math.floor(durationSec * ratio)) const buf = await compressOpus(inputBuffer, { bitrate: OPUS_CHAIN[0], trimSec, label }) const b64 = Math.ceil(buf.length * 4 / 3) if (b64 <= MAX_B64_BYTES) return { buf, bitrate: OPUS_CHAIN[0], b64len: b64, trimSec } return best } // ── Lirik (LRCLIB) ───────────────────────────────────────────────────────── async function getLyrics(title, artist, durationSec) { try { const { data } = await axios.get(`${LRCLIB}/get`, { params: { artist_name: artist, track_name: title, duration: durationSec || undefined }, timeout: 20000, }) if (data?.syncedLyrics) return { synced: data.syncedLyrics, plain: data.plainLyrics } if (data?.plainLyrics) return { plain: data.plainLyrics } } catch {} try { const { data } = await axios.get(`${LRCLIB}/search`, { params: { q: `${title} ${artist}` }, timeout: 20000 }) const arr = Array.isArray(data) ? data : [] const hit = arr.find((x) => x.syncedLyrics) || arr[0] if (hit?.syncedLyrics) return { synced: hit.syncedLyrics, plain: hit.plainLyrics } if (hit?.plainLyrics) return { plain: hit.plainLyrics } } catch {} return null } function parseLrc(lrc) { const lines = [] const re = /\[(\d{1,3}):(\d{2})(?:[.:](\d{1,3}))?\]\s*(.*)/g let m while ((m = re.exec(lrc))) { const text = (m[4] || '').trim() if (!text) continue const frac = m[3] ? Number(m[3].padEnd(3, '0')) / 1000 : 0 lines.push({ time: Number(m[1]) * 60 + Number(m[2]) + frac, text }) } return lines.sort((a, b) => a.time - b.time) } // ── Kartu Pemutar (Web Audio API) ────────────────────────────────────────── function buildPlayerHtml(track, lyr, { thumb = '', audioDataUri = '', totalSec = 0, bitrate = '', isTrimmed = false } = {}) { let lines = [] let mode = 'none' if (lyr?.synced) { lines = parseLrc(lyr.synced) if (lines.length) mode = 'synced' } if (!lines.length && lyr?.plain) { lines = String(lyr.plain).split('\n').map((x) => x.trim()).filter(Boolean).map((text) => ({ time: null, text })) mode = 'plain' } const total = totalSec || Math.floor((track.durationMs || 0) / 1000) || 180 if (isTrimmed) lines = lines.filter((l) => l.time === null || l.time <= total) if (mode === 'plain' && total > 0 && lines.length) { lines = lines.map((l, i) => ({ time: Math.round((i * total / lines.length) * 10) / 10, text: l.text })) mode = 'estimated' } lines = lines.slice(0, LYRIC_MAX_LINES) const body = lines.length ? lines.map((l, i) => `${esc(l.text)}`).join('') : 'Lirik tidak ditemukan untuk lagu ini 😢' const label = isTrimmed ? `🎬 Trim ${fmtTime(total)}` : (bitrate ? `🎧 Opus ${bitrate}` : '') const hint = audioDataUri ? `Tekan ▶ untuk memutar audio. Lirik mengikuti posisi lagu.` : 'Audio tidak tersedia. Pemutar hanya sebagai penanda waktu lirik.' const data = JSON.stringify(lines.map((l) => ({ t: l.time, x: l.text }))) .replace(/` : '' const audioHtml = audioDataUri ? `` : '' const detailParts = [track.album || 'YouTube'] if (track.views) detailParts.push(`👁️ ${fmtNumber(track.views)}`) if (track.published) detailParts.push(`📅 ${track.published}`) return ` ${audioHtml} ${thumbHtml} ${esc(track.title)} ${esc(track.artist)} ${detailParts.join(' · ')} ${label ? `${esc(label)}` : ''} Tekan ▶ untuk mulai 00:00${fmtTime(total)} −5 dtk ▶ Play +5 dtk ${body} ${hint} ` } async function sendPlayerCard(m, sock, track, lyr, opts) { const html = buildPlayerHtml(track, lyr, opts) try { return await sendRichCard(sock, m, { title: '🎶 Pemutar Lirik', footer: `${track.artist} · ${track.title}`, html, }) } catch (e) { console.log('[PLAY2] kartu gagal, fallback teks:', e?.message || e) } if (!lyr) return m.reply(`📜 *ʟɪʀɪᴋ*\n\n_Lirik tidak ditemukan..._ 😢${FOOT}`) const plain = lyr.synced ? parseLrc(lyr.synced).map(l => `[${fmtTime(l.time)}] ${l.text}`).join('\n') : lyr.plain const chunks = plain.match(/[\s\S]{1,3000}/g) || [] for (const c of chunks) await m.reply(c + FOOT) } // ── Proses Putar (Persis spotify3) ───────────────────────────────────────── async function processPlay(m, sock, url) { try { // Cari sesi const sess = sessions.get(m.chat) if (!sess || Date.now() - sess.createdAt > SESSION_MS) { sessions.delete(m.chat) m.react?.('❌') return m.reply(`⌛ *ꜱᴇꜱɪ ʙᴇʀᴀᴋʜɪʀ* 🌸\n\nSesi pencarian sudah kedaluwarsa atau hilang. Cari ulang ya~${FOOT}`) } // Cari video dari data yang disimpen const videoData = sess.results.find(v => v.url === url) if (!videoData) { m.react?.('❌') return m.reply(`⚠️ Video tidak ditemukan di sesi. Cari ulang ya~${FOOT}`) } sess.createdAt = Date.now() m.react?.('🎧') await m.reply(`🎧 *ᴍᴇɴʏɪᴀᴘᴋᴀɴ ᴘᴇᴍᴜᴛᴀʀ...* 🪸\n\n_${videoData.title}_\n_⏳ Unduh & kompres audio, tunggu 15–40 detik..._${FOOT}`) const durationSec = videoData.duration_seconds || 0 // Bersihin judul dari embel-embel (Official Video) let artist = videoData.author.name || 'YouTube' let title = videoData.title if (title.includes(' - ')) { const parts = title.split(' - ') artist = parts[0].trim() title = parts.slice(1).join(' - ').trim() } title = title.replace(/\(Official.*?\)|\[Official.*?\]|\(Lyric.*?\)/gi, '').trim() // Paralel process const [lyrR, thumbR, audioR] = await Promise.allSettled([ getLyrics(title, artist, durationSec), fetchThumb(videoData.thumbnail), downloadYouTubeAudio(videoData), ]) const lyrics = lyrR.status === 'fulfilled' ? lyrR.value : null const thumb = thumbR.status === 'fulfilled' ? thumbR.value : null const rawAudio = audioR.status === 'fulfilled' ? audioR.value : null let audioDataUri = '' let audioMeta = null let audioErr = null if (rawAudio && rawAudio.length > 0) { try { const c = await compressWithFallback(rawAudio, durationSec || 0, videoData.title) audioDataUri = `data:${OPUS_MIME};base64,${c.buf.toString('base64')}` audioMeta = c console.log(`[PLAY2] kompres ok: ${c.bitrate} → ${Math.round(c.b64len / 1024)} KB`) } catch (e) { audioErr = e.message console.error('[PLAY2] kompres gagal:', e) } } else if (audioR.status === 'rejected') { audioErr = audioR.reason?.message || 'unduh gagal' console.log('[PLAY2] Download API Error:', audioErr) } // KIRIM KARTU (Apapun yang terjadi, kartu tetap dikirim) await sendPlayerCard(m, sock, { title, artist, album: 'YouTube', views: videoData.views, published: videoData.published, durationMs: durationSec * 1000 }, lyrics, { thumb: toDataUri(thumb), audioDataUri, totalSec: audioMeta?.trimSec || durationSec, isTrimmed: !!(audioMeta?.trimSec), bitrate: audioMeta?.bitrate || '', }) m.react?.('✅') } catch (err) { console.error('[PLAY2] Error fatal di processPlay:', err) m.react?.('❌') m.reply(`❌ Gagal memproses lagu: ${err.message}`) } } // ── Main Handler ─────────────────────────────────────────────────────────── async function handler(m, { sock, text }) { const query = m.text?.trim() // Deteksi klik tombol PUTAR if (query && query.startsWith('putar-play2 ')) { const url = query.replace(/^putar-play2\s+/, '').trim() return processPlay(m, sock, url) } if (!query) return m.reply(`🎵 *ᴘʟᴀʏ 2*\n\n> Contoh:\n\`${m.prefix}play2 komang\``) m.react("🔍") try { const videos = await searchYouTube(query) if (!videos.length) throw new Error("Video tidak ditemukan") const video = videos[0] // Simpan sesi pencarian sessions.set(m.chat, { results: videos, createdAt: Date.now() }) const rows = videos.map((v, i) => { return { header: v.title.slice(0, 50), title: v.author.name.slice(0, 24), description: `⏱️ ${v.duration} · 👁️ ${fmtNumber(v.views)}`, id: `${m.prefix}putar-play2 ${v.url}` } }) const botName = config.bot.name || 'Itsuki' const caption = `🍀 *PLAY MUSIK* Hai *${m.pushName}* 👋 ╭┈┈⬡「 🎵 *ᴅᴇᴛᴀɪʟ ᴠɪᴅᴇᴏ* 」 ┃ 🎤 *Channel:* ${video.author.name} ┃ ⏱️ *Durasi:* ${video.duration} ┃ 👁️ *Views:* ${fmtNumber(video.views)} ┃ 📅 *Rilis:* ${video.published} ┃ 🔗 *Link:* ${video.url} ╰┈┈┈┈┈┈┈┈⬡ Mau putar lagu ini? Tekan tombol "🍕 PUTAR" di bawah ya! > ~ *${botName}* 🌸` await sock.sendMessage(m.chat, { image: { url: video.thumbnail }, caption: caption, footer: botName, interactiveButtons: [ { name: 'quick_reply', buttonParamsJson: JSON.stringify({ display_text: '🍕 PUTAR', id: `${m.prefix}putar-play2 ${video.url}` }) }, { name: 'single_select', buttonParamsJson: JSON.stringify({ title: 'Musik semacamnya', sections: [{ title: 'List Musik yang hampir sama', rows }] }) } ] }, { quoted: m }) m.react("✅") } catch (err) { console.error('[Play2]', err) m.react("❌") m.reply(`❌ *Error*: ${err.message || err}`) } } module.exports = { config: pluginConfig, handler }