diff --git a/MusicDownloader/Class/Downloader/CookieHelper.cs b/MusicDownloader/Class/Downloader/CookieHelper.cs
new file mode 100644
index 0000000..1ea714e
--- /dev/null
+++ b/MusicDownloader/Class/Downloader/CookieHelper.cs
@@ -0,0 +1,123 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+namespace MusicDownloader.Class.Downloader
+{
+ ///
+ /// YouTubeの認証・年齢制限解除用Cookie(cookies.txt)やブラウザCookieの検出・引数付与を行うヘルパークラス
+ ///
+ public static class CookieHelper
+ {
+ ///
+ /// 利用可能な cookies.txt ファイルの絶対パスを探索して取得する
+ ///
+ /// 音楽出力ベースディレクトリ(例: C:\MyMusic や /music)
+ /// 楽曲集約ディレクトリ(例: C:\MyMusic\Youtube や /music/Youtube)
+ /// 見つかったCookieファイルの絶対パス、存在しない場合は null
+ public static string? FindCookiesFile(string? outputBaseDir = null, string? youtubeFolder = null)
+ {
+ // 1. 環境変数 YOUTUBE_COOKIES_PATH または COOKIES_PATH
+ var envPath = Environment.GetEnvironmentVariable("YOUTUBE_COOKIES_PATH")
+ ?? Environment.GetEnvironmentVariable("COOKIES_PATH");
+ if (!string.IsNullOrWhiteSpace(envPath) && File.Exists(envPath))
+ {
+ return Path.GetFullPath(envPath);
+ }
+
+ // 2. 出力ベースディレクトリ直下(ホスト C:\MyMusic\cookies.txt ➔ コンテナ /music/cookies.txt)
+ if (!string.IsNullOrWhiteSpace(outputBaseDir))
+ {
+ var p = Path.Combine(outputBaseDir, "cookies.txt");
+ if (File.Exists(p)) return Path.GetFullPath(p);
+ }
+
+ // 3. YouTube集約フォルダ直下(C:\MyMusic\Youtube\cookies.txt ➔ コンテナ /music/Youtube/cookies.txt)
+ if (!string.IsNullOrWhiteSpace(youtubeFolder))
+ {
+ var p = Path.Combine(youtubeFolder, "cookies.txt");
+ if (File.Exists(p)) return Path.GetFullPath(p);
+ }
+
+ // 4. アプリケーション実行フォルダ直下(ローカル bin 配下またはコンテナ /app/cookies.txt)
+ var appDir = AppDomain.CurrentDomain.BaseDirectory;
+ var appCookie = Path.Combine(appDir, "cookies.txt");
+ if (File.Exists(appCookie)) return Path.GetFullPath(appCookie);
+
+ // 5. Docker等で一般的にマウントされる /cookies/cookies.txt
+ if (File.Exists("/cookies/cookies.txt")) return "/cookies/cookies.txt";
+
+ // 6. ログ出力先ボリューム(ホスト C:\feeds\cookies.txt ➔ コンテナ /feeds/cookies.txt)
+ try
+ {
+ var feedsCookie = Path.Combine(CmnDefine.GetLogDir(), "cookies.txt");
+ if (File.Exists(feedsCookie)) return Path.GetFullPath(feedsCookie);
+ }
+ catch { }
+
+ return null;
+ }
+
+ ///
+ /// ローカル実行時にブラウザから直接Cookieを取得するための指定名(chrome, firefox, edge等)を取得する
+ ///
+ public static string? GetCookiesBrowser()
+ {
+ var envBrowser = Environment.GetEnvironmentVariable("YOUTUBE_COOKIES_BROWSER")
+ ?? Environment.GetEnvironmentVariable("COOKIES_BROWSER");
+ return string.IsNullOrWhiteSpace(envBrowser) ? null : envBrowser.Trim();
+ }
+
+ ///
+ /// yt-dlp のコマンド引数リストに Cookie オプション(--cookies または --cookies-from-browser)を付与する
+ ///
+ /// 付与対象の引数リスト
+ /// 音楽出力ベースディレクトリ
+ /// 楽曲集約ディレクトリ
+ /// Cookieオプションが付与されたかどうか
+ public static bool ApplyCookieArgs(List args, string? outputBaseDir = null, string? youtubeFolder = null)
+ {
+ var cookieFile = FindCookiesFile(outputBaseDir, youtubeFolder);
+ if (!string.IsNullOrEmpty(cookieFile))
+ {
+ args.Add("--cookies");
+ args.Add(cookieFile);
+ return true;
+ }
+
+ var browser = GetCookiesBrowser();
+ if (!string.IsNullOrEmpty(browser))
+ {
+ args.Add("--cookies-from-browser");
+ args.Add(browser);
+ return true;
+ }
+
+ return false;
+ }
+
+ ///
+ /// 現在のCookie検出状況を説明する文字列を取得する(ログ出力・案内用)
+ ///
+ public static (bool HasCookie, string Description) GetCookieStatus(string? outputBaseDir = null, string? youtubeFolder = null)
+ {
+ var cookieFile = FindCookiesFile(outputBaseDir, youtubeFolder);
+ if (!string.IsNullOrEmpty(cookieFile))
+ {
+ return (true, $"Cookieファイル検出: {cookieFile}");
+ }
+
+ var browser = GetCookiesBrowser();
+ if (!string.IsNullOrEmpty(browser))
+ {
+ return (true, $"ブラウザCookie指定検出: {browser}");
+ }
+
+ var suggestedPath = !string.IsNullOrWhiteSpace(outputBaseDir)
+ ? Path.Combine(outputBaseDir, "cookies.txt")
+ : "C:\\MyMusic\\cookies.txt または /app/cookies.txt";
+
+ return (false, $"未配置 (年齢制限動画を取得する場合は {suggestedPath} に cookies.txt を配置してください)");
+ }
+ }
+}
diff --git a/MusicDownloader/Class/Downloader/YoutubeDownloader.cs b/MusicDownloader/Class/Downloader/YoutubeDownloader.cs
index 8c6376f..8bb99f1 100644
--- a/MusicDownloader/Class/Downloader/YoutubeDownloader.cs
+++ b/MusicDownloader/Class/Downloader/YoutubeDownloader.cs
@@ -145,14 +145,19 @@ namespace MusicDownloader.Class.Downloader
///
/// プレイリストURLからプレイリスト名および動画リストを取得する
///
- public async Task GetPlaylistInfoAsync(string playlistUrl)
+ public async Task GetPlaylistInfoAsync(string playlistUrl, string? outputBaseDir = null)
{
LogManager.AddLog($"プレイリスト情報を取得中: {playlistUrl}");
try
{
+ var args = new List { "--dump-single-json", "--flat-playlist", "--no-warnings" };
+ // Cookieファイルが存在する場合は付与(年齢制限や限定公開動画のメタデータ取得用)
+ CookieHelper.ApplyCookieArgs(args, outputBaseDir);
+ args.Add(playlistUrl);
+
var result = await Cli.Wrap(_ytDlpPath)
- .WithArguments(new[] { "--dump-single-json", "--flat-playlist", "--no-warnings", playlistUrl })
+ .WithArguments(args)
.WithValidation(CommandResultValidation.None)
.ExecuteBufferedAsync();
@@ -209,7 +214,7 @@ namespace MusicDownloader.Class.Downloader
/// 差分ダウンロードを行うかどうか (falseの場合は起動直後として全曲をダウンロード・最新化)
public async Task ProcessPlaylistAsync(string playlistUrl, string outputBaseDir, bool isIncremental = true)
{
- var playlistInfo = await GetPlaylistInfoAsync(playlistUrl);
+ var playlistInfo = await GetPlaylistInfoAsync(playlistUrl, outputBaseDir);
var rawTitle = playlistInfo?.Title ?? "YouTube_Playlist";
var sanitizedPlaylistName = CmnUtil.SanitizeFileName(rawTitle);
@@ -268,7 +273,7 @@ namespace MusicDownloader.Class.Downloader
// 単一動画URLまたはエントリがフラット取得できなかった場合、直接ダウンロード
LogManager.AddLog($"プレイリストのエントリが見つからないか単一動画URLです。直接ダウンロードを試行します。");
- var singleTrack = await DownloadAndProcessSingleAsync(playlistUrl, 1, 1, stagingDir, youtubeFolder, sanitizedPlaylistName, null, downloadedTracks);
+ var singleTrack = await DownloadAndProcessSingleAsync(playlistUrl, 1, 1, stagingDir, youtubeFolder, sanitizedPlaylistName, null, downloadedTracks, outputBaseDir);
if (singleTrack != null)
{
currentPlaylistTracks.Add(singleTrack);
@@ -310,7 +315,7 @@ namespace MusicDownloader.Class.Downloader
// 1曲の処理(ローカル作業フォルダでダウンロード・タグ付け・検証を完結させ、完成後にYoutubeフォルダへ転送)
var trackInfo = await DownloadAndProcessSingleAsync(
- videoUrl, videoIndex, totalCount, stagingDir, youtubeFolder, sanitizedPlaylistName, entry, downloadedTracks);
+ videoUrl, videoIndex, totalCount, stagingDir, youtubeFolder, sanitizedPlaylistName, entry, downloadedTracks, outputBaseDir);
if (trackInfo != null)
{
@@ -356,13 +361,14 @@ namespace MusicDownloader.Class.Downloader
string youtubeFolder,
string playlistName,
YtPlaylistEntry? entryInfo,
- Dictionary downloadedTracks)
+ Dictionary downloadedTracks,
+ string? outputBaseDir = null)
{
var videoId = entryInfo?.Id ?? "";
var archiveFile = Path.Combine(youtubeFolder, "archive.txt");
- // ② 多段階フォールバックによるダウンロード実行(429字幕エラーや403Forbiddenエラーを自動回避)
- var isDownloadSuccess = await DownloadWithFallbackAsync(videoUrl, videoId, stagingDir, archiveFile);
+ // ② 多段階フォールバックによるダウンロード実行(429字幕エラー、403Forbiddenエラー、年齢制限エラーを自動回避)
+ var isDownloadSuccess = await DownloadWithFallbackAsync(videoUrl, videoId, stagingDir, archiveFile, outputBaseDir, youtubeFolder, entryInfo?.Title);
if (!isDownloadSuccess)
{
LogManager.AddWarning($"[{index}/{totalCount}] すべてのフォールバックを試みましたがダウンロードできませんでした。");
@@ -623,37 +629,49 @@ namespace MusicDownloader.Class.Downloader
///
/// ② 多段階フォールバックにより動画の音声を確実にダウンロードする
+ /// - Cookie自動適用: cookies.txt による年齢制限解除・高画質取得
/// - 429 Too Many Requests: 字幕ダウンロードを無効化して音声のみ取得
- /// - 403 Forbidden: YouTube AndroidクライアントAPIやiOSクライアントAPIへの切り替え
+ /// - 403 Forbidden / 年齢制限: YouTube Android / Creator / TV / iOS クライアントAPIへの自動切り替え
///
private async Task DownloadWithFallbackAsync(
string videoUrl,
string videoId,
string stagingDir,
- string archiveFile)
+ string archiveFile,
+ string? outputBaseDir = null,
+ string? youtubeFolder = null,
+ string? videoTitle = null)
{
var outputTemplate = Path.Combine(stagingDir, "%(title)s.%(ext)s");
// 基本引数の生成
- List GetBaseArgs() => new List
+ List GetBaseArgs()
{
- "-f", "bestaudio/best",
- "--extract-audio",
- "--audio-format", "opus",
- "--audio-quality", "0",
- "--postprocessor-args", "ExtractAudio:-af aresample=async=1000 -c:a libopus -b:a 160k -vbr on",
- "--concurrent-fragments", "1",
- "--buffer-size", "16K",
- "--write-thumbnail",
- "--convert-thumbnails", "jpg",
- "--no-abort-on-error",
- "--retries", "5",
- "--fragment-retries", "5",
- "--retry-sleep", "3",
- "--download-archive", archiveFile,
- "-o", outputTemplate,
- "--no-warnings"
- };
+ var baseArgs = new List
+ {
+ "-f", "bestaudio/best",
+ "--extract-audio",
+ "--audio-format", "opus",
+ "--audio-quality", "0",
+ "--postprocessor-args", "ExtractAudio:-af aresample=async=1000 -c:a libopus -b:a 160k -vbr on",
+ "--concurrent-fragments", "1",
+ "--buffer-size", "16K",
+ "--write-thumbnail",
+ "--convert-thumbnails", "jpg",
+ "--no-abort-on-error",
+ "--retries", "5",
+ "--fragment-retries", "5",
+ "--retry-sleep", "3",
+ "--download-archive", archiveFile,
+ "-o", outputTemplate,
+ "--no-warnings"
+ };
+
+ // CookieファイルまたはブラウザCookieの自動適用(年齢確認・制限解除用)
+ CookieHelper.ApplyCookieArgs(baseArgs, outputBaseDir, youtubeFolder);
+
+ return baseArgs;
+ }
// 試行1: 標準(429を避けるため英語en字幕は除外してja字幕のみ)
var plan1 = GetBaseArgs();
@@ -663,22 +681,34 @@ namespace MusicDownloader.Class.Downloader
var plan2 = GetBaseArgs();
plan2.Add(videoUrl);
- // 試行3: AndroidクライアントAPI(403 Forbidden ストリーム拒否対策)
+ // 試行3: AndroidクライアントAPI(403 Forbidden ストリーム拒否対策・一部年齢制限対策)
var plan3 = GetBaseArgs();
plan3.AddRange(new[] { "--extractor-args", "youtube:player_client=android,web", videoUrl });
- // 試行4: iOSクライアントAPI & キャッシュ無効化(最終フォールバック)
+ // 試行4: Android Creator & Mobile Webクライアント(年齢確認バイパス試行)
var plan4 = GetBaseArgs();
- plan4.AddRange(new[] { "--extractor-args", "youtube:player_client=ios,web", "--no-cache-dir", videoUrl });
+ plan4.AddRange(new[] { "--extractor-args", "youtube:player_client=android_creator,mweb", videoUrl });
+
+ // 試行5: TVクライアントAPI(年齢確認バイパス試行)
+ var plan5 = GetBaseArgs();
+ plan5.AddRange(new[] { "--extractor-args", "youtube:player_client=tv_embedded,tv", videoUrl });
+
+ // 試行6: iOSクライアントAPI & キャッシュ無効化(最終フォールバック)
+ var plan6 = GetBaseArgs();
+ plan6.AddRange(new[] { "--extractor-args", "youtube:player_client=ios,web", "--no-cache-dir", videoUrl });
var plans = new (string Name, List Args)[]
{
("通常ダウンロード (日本語字幕あり)", plan1),
("フォールバック1 (字幕取得オフ / 429対策)", plan2),
- ("フォールバック2 (YouTube Androidクライアント / 403対策)", plan3),
- ("フォールバック3 (YouTube iOSクライアント & キャッシュ無効化)", plan4)
+ ("フォールバック2 (YouTube Androidクライアント / 403・年齢確認対策)", plan3),
+ ("フォールバック3 (YouTube Creator・mwebクライアント / 年齢確認対策)", plan4),
+ ("フォールバック4 (YouTube TVクライアント / 年齢確認対策)", plan5),
+ ("フォールバック5 (YouTube iOSクライアント & キャッシュ無効化)", plan6)
};
+ bool detectedAgeRestriction = false;
+
for (int i = 0; i < plans.Length; i++)
{
var (name, args) = plans[i];
@@ -710,6 +740,11 @@ namespace MusicDownloader.Class.Downloader
LogManager.AddWarning($"[{name}] 終了コード: {cmdResult.ExitCode}");
if (!string.IsNullOrWhiteSpace(stdErr))
{
+ if (stdErr.Contains("confirm your age", StringComparison.OrdinalIgnoreCase) ||
+ stdErr.Contains("Sign in to confirm", StringComparison.OrdinalIgnoreCase))
+ {
+ detectedAgeRestriction = true;
+ }
LogManager.AddWarning($"詳細: {stdErr.Trim()}");
}
@@ -726,6 +761,13 @@ namespace MusicDownloader.Class.Downloader
}
}
+ if (detectedAgeRestriction)
+ {
+ var (_, cookieDesc) = CookieHelper.GetCookieStatus(outputBaseDir, youtubeFolder);
+ LogManager.AddWarning($"[年齢制限エラー] 動画「{videoTitle ?? videoId}」はYouTubeの年齢確認が必要です。");
+ LogManager.AddWarning($"[Cookie設定状況] {cookieDesc}");
+ }
+
return false;
}
diff --git a/MusicDownloader/Program.cs b/MusicDownloader/Program.cs
index f23787c..1767f4e 100644
--- a/MusicDownloader/Program.cs
+++ b/MusicDownloader/Program.cs
@@ -100,10 +100,22 @@ LogManager.AddLog($"==================================================");
// 出力先およびログ保存先ディレクトリの決定
var outputDir = CmnDefine.GetOutputDir();
var logDir = CmnDefine.GetLogDir();
+var youtubeDir = Path.Combine(outputDir, CmnDefine.YoutubeFolderName);
LogManager.AddLog($"ベース出力先: {outputDir}");
-LogManager.AddLog($"楽曲集約フォルダ: {Path.Combine(outputDir, CmnDefine.YoutubeFolderName)}");
+LogManager.AddLog($"楽曲集約フォルダ: {youtubeDir}");
LogManager.AddLog($"ログ保存先: {logDir}");
+// YouTube認証・年齢制限解除用Cookie(cookies.txt)の確認
+var (hasCookie, cookieStatusDesc) = CookieHelper.GetCookieStatus(outputDir, youtubeDir);
+if (hasCookie)
+{
+ LogManager.AddSuccess($"[Cookie設定] {cookieStatusDesc}");
+}
+else
+{
+ LogManager.AddLog($"[Cookie設定] {cookieStatusDesc}");
+}
+
// 依存ツール(yt-dlp)の準備確認
using var initClient = httpClientFactory.CreateClient("webClient");
var ytDlpPath = await DependencyManager.EnsureYtDlpAsync(initClient);
diff --git a/compose.yaml b/compose.yaml
index 1c0cc57..f450089 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -20,8 +20,11 @@ services:
- CHECK_INTERVAL_HOURS=2
# プレイリストURLをコンテナ側から上書きしたい場合に指定
# - PLAYLIST_URL=https://www.youtube.com/playlist?list=...
+ # 年齢制限動画取得用のCookieファイルパスを明示指定する場合(未指定でも /music/cookies.txt 等から自動検出)
+ # - YOUTUBE_COOKIES_PATH=/music/cookies.txt
volumes:
# YouTubeからダウンロードした音楽ファイルをホストの G:\マイドライブ\MyMusic に出力(ジャンクション C:\MyMusic 経由)
+ # ※ 年齢制限動画を取得する場合、ホスト側の C:\MyMusic\cookies.txt に配置すればコンテナ内 (/music/cookies.txt) で自動検知されます
- C:\MyMusic:/music
# ホストのログディレクトリ C:\feeds\Log へ出力するためのマウント
- C:\feeds:/feeds