# ๐ŸŽต VideoToMP3 Microservice - Implementation Complete **Created:** 2026-01-31 **Status:** โœ… Ready for Integration Testing --- ## ๐Ÿ“‹ Overview Microservice for downloading YouTube videos and converting to MP3, with callback support for Hanasuba backend integration. --- ## โœ… Features Implemented ### 1. Download Queue System โœ… **File:** `src/services/downloadQueue.js` (8 KB, 280 lines) **Features:** - Job queue management - Concurrent download limiting (max 3) - Status tracking (pending, downloading, processing, uploading, completed, failed) - Progress reporting (0-100%) - Automatic cleanup (24h old jobs) **Methods:** ```javascript addJob(jobId, url, callbackUrl) // Add job to queue getJob(jobId) // Get job status cancelJob(jobId) // Cancel active job cleanupOldJobs() // Remove old jobs ``` ### 2. YouTube Download with yt-dlp โœ… **Features:** - Uses logged-in cookies (youtube-cookies.txt) - PO Token support (bgutil provider) - mweb client (most stable) - Best audio quality - Metadata embedding - Thumbnail embedding **Command:** ```bash yt-dlp \ --cookies youtube-cookies.txt \ --extractor-args "youtube:player_client=mweb" \ --format "bestaudio" \ --extract-audio \ --audio-format mp3 \ --audio-quality 0 \ --embed-thumbnail \ --add-metadata \ --output /tmp/music_{jobId}.mp3 \ {url} ``` ### 3. Metadata Extraction โœ… **Extracted fields:** - `title` - Video title - `artist` - Uploader/channel name - `album` - Album (if available) - `duration` - Duration in seconds - `thumbnail_url` - Thumbnail URL - `youtube_id` - YouTube video ID ### 4. Callback System โœ… **Success callback:** - Method: POST (multipart/form-data) - Fields: - `jobId` (string) - `success` (boolean) - `file` (binary MP3) - `metadata` (JSON string) - Headers: `X-API-Key` for auth **Failure callback:** - Method: POST (application/json) - Fields: - `jobId` (string) - `success` (false) - `error` (error message) --- ## ๐Ÿ”Œ API Endpoints ### POST /download **Queue download job** **Request:** ```json { "jobId": "uuid-v4", "url": "https://youtube.com/watch?v=dQw4w9WgXcQ", "callbackUrl": "https://api.hanasuba.com/api/music/callback" } ``` **Response:** ```json { "success": true, "jobId": "uuid-v4", "status": "pending", "message": "Download job queued successfully" } ``` --- ### GET /download/:jobId **Get job status** **Response:** ```json { "success": true, "jobId": "uuid-v4", "status": "downloading", "progress": 45, "error": null, "createdAt": "2026-01-31T08:00:00.000Z" } ``` **Status values:** - `pending` - Waiting in queue - `downloading` - Downloading from YouTube - `processing` - Extracting metadata - `uploading` - Sending callback - `completed` - Success - `failed` - Error occurred - `cancelled` - Cancelled by user --- ### DELETE /download/:jobId **Cancel job** **Response:** ```json { "success": true, "message": "Job cancelled successfully" } ``` --- ### GET /health **Health check** **Response:** ```json { "status": "ok", "service": "videotomp3-microservice", "version": "2.0.0", "cookies": { "valid": true, "lastRefresh": "2026-01-31T08:00:00.000Z" }, "queue": { "totalJobs": 5, "processing": 2 } } ``` --- ### POST /download-direct (Legacy) **Direct download without callback** **Request:** ```json { "url": "https://youtube.com/watch?v=...", "quality": "best" } ``` --- ## ๐Ÿ”„ Complete Flow ``` 1. Backend โ†’ POST /download { "jobId": "abc-123", "url": "https://youtube.com/...", "callbackUrl": "https://backend/api/music/callback" } 2. Microservice โ”œโ”€ Add to queue (status: pending) โ”œโ”€ Response: { success: true, jobId: "abc-123" } โ””โ”€ Start processing (when slot available) 3. Download Worker โ”œโ”€ Status: downloading (progress: 0-50%) โ”œโ”€ yt-dlp downloads MP3 โ”œโ”€ Status: processing (progress: 75%) โ”œโ”€ Extract metadata via yt-dlp --dump-json โ””โ”€ Status: uploading (progress: 90%) 4. Callback to Backend โ”œโ”€ POST https://backend/api/music/callback โ”œโ”€ FormData: โ”‚ โ”œโ”€ jobId: "abc-123" โ”‚ โ”œโ”€ success: true โ”‚ โ”œโ”€ file: โ”‚ โ””โ”€ metadata: { title, artist, ... } โ””โ”€ Headers: X-API-Key: "secret" 5. Backend Receives โ”œโ”€ Saves MP3 file โ”œโ”€ Creates music_track record โ”œโ”€ Adds to folders โ””โ”€ Marks job completed 6. Cleanup โ””โ”€ Delete /tmp/music_abc-123.mp3 ``` --- ## ๐Ÿš€ Running the Service ### Development ```bash cd /home/debian/videotomp3transcriptor npm install node src/server.js ``` ### Production (PM2) ```bash pm2 start src/server.js --name videotomp3 pm2 save pm2 startup ``` ### Docker ```bash docker build -t videotomp3 . docker run -d \ -p 3000:3000 \ -v $(pwd)/youtube-cookies.txt:/app/youtube-cookies.txt:ro \ --name videotomp3 \ videotomp3 ``` --- ## ๐Ÿงช Testing ### 1. Health Check ```bash curl http://localhost:3000/health ``` ### 2. Queue Download Job ```bash curl -X POST http://localhost:3000/download \ -H "Content-Type: application/json" \ -d '{ "jobId": "test-123", "url": "https://youtube.com/watch?v=dQw4w9WgXcQ", "callbackUrl": "https://webhook.site/your-unique-id" }' ``` ### 3. Check Job Status ```bash curl http://localhost:3000/download/test-123 ``` ### 4. Test with webhook.site 1. Go to https://webhook.site 2. Copy your unique URL 3. Use it as `callbackUrl` in download request 4. Watch callback arrive with file + metadata --- ## ๐Ÿ“ File Structure ``` videotomp3transcriptor/ โ”œโ”€โ”€ src/ โ”‚ โ”œโ”€โ”€ server.js โœ… Main server (8.3 KB) โ”‚ โ””โ”€โ”€ services/ โ”‚ โ”œโ”€โ”€ downloadQueue.js โœ… Queue system (8 KB) โ”‚ โ”œโ”€โ”€ download.js โœ… Legacy service โ”‚ โ””โ”€โ”€ cookiesManager.js โœ… Cookies management โ”œโ”€โ”€ youtube-cookies.txt โœ… Logged-in cookies โ”œโ”€โ”€ package.json โœ… Dependencies โ”œโ”€โ”€ .env โœ… Config โ””โ”€โ”€ MICROSERVICE_IMPLEMENTATION.md โœ… This file ``` --- ## โš™๏ธ Configuration **Environment Variables:** ```bash PORT=3000 # Server port ALLOWED_ORIGINS=* # CORS origins API_KEY=your-secret-key # API key for callbacks ``` **Queue Settings (downloadQueue.js):** ```javascript maxConcurrent: 3 // Max parallel downloads cleanupInterval: 60 * 60 * 1000 // Cleanup every hour jobRetention: 24 * 60 * 60 * 1000 // Keep jobs for 24h ``` --- ## ๐Ÿ” Security **API Key:** - Sent in `X-API-Key` header on callbacks - Backend should verify this key - Set in `.env` file **File Access:** - Temp files in `/tmp` (auto-cleanup) - Only accessible during processing - Deleted after callback sent **Cookies:** - Read-only mount in Docker - Permissions: 600 - Auto-refresh on expiry --- ## ๐Ÿ› Error Handling **Download Failures:** - Invalid URL โ†’ 400 Bad Request - YouTube block โ†’ Retry with different client - Network error โ†’ Retry 3 times - Callback failure โ†’ Send error callback **Job Failures:** - Update status to `failed` - Store error message - Send failure callback to backend - Keep job in history for 24h **Cleanup:** - Auto-delete temp files on success/failure - Cleanup old jobs (>24h) hourly - Graceful shutdown on SIGTERM --- ## ๐Ÿ“Š Monitoring **Health endpoint:** - Service status - Cookie validity - Queue size - Active jobs **Logs:** - Console output with timestamps - Job lifecycle events - Error messages - Callback results **Metrics (future):** - Jobs per minute - Success rate - Average duration - Error rate by type --- ## โœ… Integration with Hanasuba Backend **Backend expects:** ```javascript // POST /api/music/callback // Content-Type: multipart/form-data FormData: jobId: UUID success: boolean file: MP3 binary (if success) metadata: JSON string (if success) error: string (if failed) Headers: X-API-Key: secret ``` **Backend response:** ```json { "success": true, "track_id": "uuid", "message": "Track created successfully" } ``` --- ## ๐Ÿš€ Status **Implementation:** โœ… 100% Complete **Testing:** โณ Pending (manual test needed) **Integration:** โณ Pending (backend ready) **Production:** โณ Pending (deployment) --- ## ๐Ÿ“ Next Steps 1. โœ… Manual test (POST /download) 2. โœ… Test with webhook.site 3. โœ… Integration test with backend 4. Deploy to production 5. Monitor & optimize --- **Ready for integration with Hanasuba backend!** ๐ŸŽ‰