#!/usr/bin/env bash set -euo pipefail # POS: media yt-mp3 — Download audio as MP3 (yt-dlp) # POS_FLAGS: --output --no-playlist --cookies --by-artist --dry-run source "$(dirname "$0")/../lib/common.sh" 2>/dev/null || source "$(dirname "$0")/common.sh" source "$(dirname "$0")/../lib/yt-lib.sh" 2>/dev/null || source "$(dirname "$0")/yt-lib.sh" # --dry-run is parsed before the deps guards (below): it previews the yt-dlp # command without requiring yt-dlp/ffmpeg to be installed. DRY_RUN=0 for arg in "$@"; do [ "$arg" = "--dry-run" ] && DRY_RUN=1 done # Deps guards sit before -h|--help (help also errors on a box missing the deps). # yt_check_deps with dry-run=1 skips the dep checks (dry-run preview needs none). yt_check_deps "$DRY_RUN" "MP3 conversion" # Env seam: YT_OUT_DIR overrides the default (keeps HOME sandbox-compatible). OUT_DIR="${YT_OUT_DIR:-$HOME/Music}" BY_ARTIST=0 EXTRA_ARGS=() usage() { cat < Download audio from a URL and convert to MP3 via yt-dlp. Options: -o, --output Output directory (default: $OUT_DIR) --by-artist Organize as //.mp3 --no-playlist Download only the single video --cookies <file> Netscape cookies.txt for age-gated content --dry-run Print the yt-dlp command without running it -h, --help This help Examples: pos media yt mp3 https://youtube.com/watch?v=dQw4w9WgXcQ pos media yt mp3 --by-artist --no-playlist https://youtu.be/dQw4w9WgXcQ pos media yt mp3 --cookies ~/cookies.txt https://vimeo.com/123 EOF exit 0 } URL="" while [[ $# -gt 0 ]]; do case "$1" in -h|--help) usage ;; -o|--output) [ $# -ge 2 ] || err "--output needs a value" OUT_DIR="$2"; shift 2 ;; --by-artist) BY_ARTIST=1; shift ;; --no-playlist) EXTRA_ARGS+=(--no-playlist); shift ;; --cookies) [ $# -ge 2 ] || err "--cookies needs a value" [ -f "$2" ] || err "cookies file not found: $2" EXTRA_ARGS+=(--cookies "$2"); shift 2 ;; --dry-run) DRY_RUN=1; shift ;; -*) err "Unknown option: $1 (see --help)" ;; *) [ -z "$URL" ] && URL="$1" && shift || err "Unexpected argument: $1" ;; esac done [ -n "$URL" ] || usage if [ "$BY_ARTIST" -eq 1 ]; then OUT_TEMPLATE="$OUT_DIR/%(artist,uploader)s/%(title)s.%(ext)s" else OUT_TEMPLATE="$OUT_DIR/%(title)s.%(ext)s" fi args=(yt-dlp -x --audio-format mp3 --audio-quality 0 --embed-metadata --embed-chapters --embed-thumbnail --convert-thumbnails jpg --parse-metadata "%(artist,uploader)s:%(artist)s" --no-overwrites -o "$OUT_TEMPLATE" "${EXTRA_ARGS[@]}" "$URL") if [ "$DRY_RUN" -eq 1 ]; then echo "yt-dlp ${args[*]:1}" else spawn "downloading audio → $OUT_DIR" "${args[@]}" fi