| import json |
| import os |
| import subprocess |
| import uuid |
| from config import TEMP_DIR |
|
|
| def extract_media_info(url, platform="tiktok"): |
| """ |
| Menggunakan yt-dlp --dump-json untuk mengekstrak metadata video. |
| """ |
| try: |
| cmd = [ |
| "yt-dlp", |
| "--dump-json", |
| "--no-warnings", |
| "--no-playlist", |
| "--skip-download", |
| url |
| ] |
|
|
| result = subprocess.run(cmd, capture_output=True, text=True, timeout=60) |
|
|
| if result.returncode != 0: |
| error_msg = result.stderr.strip() if result.stderr else "Unknown error" |
| return {"error": True, "message": f"yt-dlp error: {error_msg}"} |
|
|
| data = json.loads(result.stdout) |
|
|
| return { |
| "status": "success", |
| "platform": platform, |
| "raw_data": data |
| } |
|
|
| except subprocess.TimeoutExpired: |
| return {"error": True, "message": "Request timeout: yt-dlp membutuhkan waktu terlalu lama."} |
| except json.JSONDecodeError: |
| return {"error": True, "message": "Gagal memparse response dari yt-dlp."} |
| except Exception as e: |
| return {"error": True, "message": f"Internal error: {str(e)}"} |
|
|
| def download_video(url): |
| """ |
| Download video TikTok ke temp file. |
| Return: (file_id, output_path) atau raise Exception. |
| """ |
| file_id = str(uuid.uuid4()) |
| output_path = os.path.join(TEMP_DIR, f"{file_id}.mp4") |
|
|
| cmd = [ |
| "yt-dlp", |
| "--no-warnings", |
| "--no-playlist", |
| "-f", "bestvideo+bestaudio/best", |
| "--merge-output-format", "mp4", |
| "-o", output_path, |
| url |
| ] |
|
|
| result = subprocess.run(cmd, capture_output=True, timeout=180) |
|
|
| if result.returncode != 0: |
| error_msg = result.stderr.decode(errors="ignore").strip() |
| raise Exception(f"yt-dlp error: {error_msg}") |
|
|
| if not os.path.exists(output_path): |
| raise Exception("File tidak berhasil dibuat oleh yt-dlp.") |
|
|
| return file_id, output_path |
|
|