Compare commits

...
4 Commits
11 changed files with 476 additions and 52 deletions

No files matched your search

+5 -1
View File
@@ -2,13 +2,17 @@
FROM mcr.microsoft.com/dotnet/runtime:10.0 AS runtime FROM mcr.microsoft.com/dotnet/runtime:10.0 AS runtime
WORKDIR /app WORKDIR /app
# タイムゾーン設定 (JST) および必要なツール(ffmpeg, python3, curl等)のインストール # タイムゾーン設定 (JST) および必要なツール(ffmpeg, python3, curl, unzip, deno等)のインストール
# ※ YouTube最新仕様の署名解読 (n-challenge / EJS) には JavaScript ランタイム (deno) が必要
RUN apt-get update && apt-get install -y --no-install-recommends \ RUN apt-get update && apt-get install -y --no-install-recommends \
tzdata \ tzdata \
ca-certificates \ ca-certificates \
curl \ curl \
unzip \
python3 \ python3 \
ffmpeg \ ffmpeg \
&& curl -fsSL https://deno.land/install.sh | sh \
&& cp /root/.deno/bin/deno /usr/local/bin/ \
&& curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp \ && curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp \
&& chmod a+rx /usr/local/bin/yt-dlp \ && chmod a+rx /usr/local/bin/yt-dlp \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
+133
View File
@@ -444,5 +444,138 @@ namespace MusicDownloader.Class
if (ex == null) return; if (ex == null) return;
LogManager.AddError($"未処理の例外が発生しました: {ex.Message}", ex); LogManager.AddError($"未処理の例外が発生しました: {ex.Message}", ex);
} }
/// <summary>
/// 指定されたディレクトリが存在することを確認・作成する。
/// Google Drive や WSL2 DrvFs マウント等の一時的な切断(EINVAL / IOException等)に備え、自動リトライを行う。
/// </summary>
/// <param name="path">対象ディレクトリパス</param>
/// <param name="maxRetries">最大試行回数(既定5回)</param>
/// <param name="retryDelayMs">試行間隔ミリ秒(既定3000ms)</param>
public static void EnsureDirectoryExists(string path, int maxRetries = 5, int retryDelayMs = 3000)
{
if (string.IsNullOrWhiteSpace(path)) return;
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
if (Directory.Exists(path))
{
return;
}
Directory.CreateDirectory(path);
return;
}
catch (Exception ex) when (attempt < maxRetries)
{
LogManager.AddWarning($"ディレクトリへのアクセス/作成に失敗しました (試行 {attempt}/{maxRetries}): {path} - {ex.Message}。{retryDelayMs / 1000}秒後に再試行します...");
System.Threading.Thread.Sleep(retryDelayMs);
}
catch (Exception ex)
{
if (ex.Message.Contains("Read-only", StringComparison.OrdinalIgnoreCase))
{
LogManager.AddError($"ストレージが読み取り専用 (Read-only) になっています: {path} - Google Drive (G:) のマウントが切断されている可能性があります。remount-gdrive.bat を実行してください。", ex);
}
else
{
LogManager.AddError($"ディレクトリの作成に失敗しました(ストレージ切断等の可能性があります): {path} - {ex.Message}", ex);
}
throw;
}
}
}
/// <summary>
/// 例外がストレージ障害(Google Drive切断、WSL2マウント切れ、読み取り専用化、I/Oエラーなど)に起因するか判定する
/// </summary>
public static bool IsStorageFailureException(Exception? ex)
{
if (ex == null) return false;
var msg = ex.ToString();
// Linux/WSL2/DrvFs/Docker でマウント先が切断・無効になった際のエラーメッセージ・条件
if (msg.Contains("Invalid argument", StringComparison.OrdinalIgnoreCase) || // errno 22: EINVAL (マウント切断・ジャンクション破損時に発生)
msg.Contains("Read-only", StringComparison.OrdinalIgnoreCase) || // EROFS
msg.Contains("Input/output error", StringComparison.OrdinalIgnoreCase) || // errno 5: EIO
msg.Contains("Transport endpoint is not connected", StringComparison.OrdinalIgnoreCase) || // errno 107: ENOTCONN
msg.Contains("Stale file handle", StringComparison.OrdinalIgnoreCase) || // errno 116: ESTALE
msg.Contains("No such device", StringComparison.OrdinalIgnoreCase) || // ENODEV
msg.Contains("Host is down", StringComparison.OrdinalIgnoreCase) || // EHOSTDOWN
msg.Contains("Network is down", StringComparison.OrdinalIgnoreCase) || // ENETDOWN
msg.Contains("Connection reset", StringComparison.OrdinalIgnoreCase) ||
msg.Contains("Device not configured", StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (ex is DriveNotFoundException || ex is DirectoryNotFoundException)
{
return true;
}
// 内部例外も再帰的に確認
if (ex.InnerException != null && IsStorageFailureException(ex.InnerException))
{
return true;
}
return false;
}
/// <summary>
/// 指定されたストレージディレクトリへの書き込みが可能か(読み取り専用や切断になっていないか)を検証する。
/// Google Drive や WSL2 DrvFs マウント切断時に発生する Read-only / Invalid argument などの障害を早期検知する。
/// </summary>
/// <param name="dirPath">検証対象ディレクトリパス</param>
/// <param name="maxRetries">リトライ回数(既定3回)</param>
/// <param name="retryDelayMs">リトライ間隔ミリ秒(既定3000ms)</param>
/// <returns>正常に書き込み可能であれば true</returns>
public static bool EnsureStorageWritable(string dirPath, int maxRetries = 3, int retryDelayMs = 3000)
{
if (string.IsNullOrWhiteSpace(dirPath)) return false;
for (int attempt = 1; attempt <= maxRetries; attempt++)
{
try
{
EnsureDirectoryExists(dirPath, maxRetries: 2, retryDelayMs: 1000);
var testFile = Path.Combine(dirPath, $".storage_probe_{Guid.NewGuid():N}.tmp");
File.WriteAllText(testFile, "probe");
if (File.Exists(testFile))
{
File.Delete(testFile);
}
return true;
}
catch (Exception ex)
{
bool isStorageFail = IsStorageFailureException(ex);
if (attempt < maxRetries)
{
LogManager.AddWarning($"[ストレージ疎通確認] ディレクトリ書き込みテストに失敗しました (試行 {attempt}/{maxRetries}): {dirPath} - {ex.Message}。{retryDelayMs / 1000}秒後に再試行します...");
System.Threading.Thread.Sleep(retryDelayMs);
}
else
{
if (isStorageFail)
{
LogManager.AddError($"[ストレージ疎通異常] 出力先ストレージが切断・無効化または読み取り専用になっています: {dirPath} - Google Drive (G:) のマウント切断またはリンク切れの可能性があります ({ex.Message})。", ex);
}
else
{
LogManager.AddError($"[ストレージ疎通異常] 出力先ストレージへの書き込みに失敗しました: {dirPath} - {ex.Message}", ex);
}
return false;
}
}
}
return false;
}
} }
} }
@@ -25,29 +25,42 @@ namespace MusicDownloader.Class.Downloader
return Path.GetFullPath(envPath); return Path.GetFullPath(envPath);
} }
// 2. 出力ベースディレクトリ直下(ホスト C:\MyMusic\cookies.txt ➔ コンテナ /music/cookies.txt) // 2. ユーザーマウントのCookieパス (/user_music/cookies.txt または /cookies/cookies.txt) を最優先
if (File.Exists("/user_music/cookies.txt")) return "/user_music/cookies.txt";
if (File.Exists("/cookies/cookies.txt")) return "/cookies/cookies.txt";
// 3. ホストOSの標準ミュージックフォルダ (例: C:\Users\<ユーザー名>\Music\cookies.txt)
try
{
var myMusic = Environment.GetFolderPath(Environment.SpecialFolder.MyMusic);
if (!string.IsNullOrWhiteSpace(myMusic))
{
var userCookie = Path.Combine(myMusic, "cookies.txt");
if (File.Exists(userCookie)) return Path.GetFullPath(userCookie);
}
}
catch { }
// 4. 出力ベースディレクトリ直下(ホスト C:\MyMusic\cookies.txt ➔ コンテナ /music/cookies.txt)
if (!string.IsNullOrWhiteSpace(outputBaseDir)) if (!string.IsNullOrWhiteSpace(outputBaseDir))
{ {
var p = Path.Combine(outputBaseDir, "cookies.txt"); var p = Path.Combine(outputBaseDir, "cookies.txt");
if (File.Exists(p)) return Path.GetFullPath(p); if (File.Exists(p)) return Path.GetFullPath(p);
} }
// 3. YouTube集約フォルダ直下(C:\MyMusic\Youtube\cookies.txt ➔ コンテナ /music/Youtube/cookies.txt) // 5. YouTube集約フォルダ直下(C:\MyMusic\Youtube\cookies.txt ➔ コンテナ /music/Youtube/cookies.txt)
if (!string.IsNullOrWhiteSpace(youtubeFolder)) if (!string.IsNullOrWhiteSpace(youtubeFolder))
{ {
var p = Path.Combine(youtubeFolder, "cookies.txt"); var p = Path.Combine(youtubeFolder, "cookies.txt");
if (File.Exists(p)) return Path.GetFullPath(p); if (File.Exists(p)) return Path.GetFullPath(p);
} }
// 4. アプリケーション実行フォルダ直下(ローカル bin 配下またはコンテナ /app/cookies.txt) // 6. アプリケーション実行フォルダ直下(ローカル bin 配下またはコンテナ /app/cookies.txt)
var appDir = AppDomain.CurrentDomain.BaseDirectory; var appDir = AppDomain.CurrentDomain.BaseDirectory;
var appCookie = Path.Combine(appDir, "cookies.txt"); var appCookie = Path.Combine(appDir, "cookies.txt");
if (File.Exists(appCookie)) return Path.GetFullPath(appCookie); if (File.Exists(appCookie)) return Path.GetFullPath(appCookie);
// 5. Docker等で一般的にマウントされる /cookies/cookies.txt // 7. ログ出力先ボリューム(ホスト C:\feeds\cookies.txt ➔ コンテナ /feeds/cookies.txt)
if (File.Exists("/cookies/cookies.txt")) return "/cookies/cookies.txt";
// 6. ログ出力先ボリューム(ホスト C:\feeds\cookies.txt ➔ コンテナ /feeds/cookies.txt)
try try
{ {
var feedsCookie = Path.Combine(CmnDefine.GetLogDir(), "cookies.txt"); var feedsCookie = Path.Combine(CmnDefine.GetLogDir(), "cookies.txt");
@@ -70,18 +83,37 @@ namespace MusicDownloader.Class.Downloader
/// <summary> /// <summary>
/// yt-dlp のコマンド引数リストに Cookie オプション(--cookies または --cookies-from-browser)を付与する /// yt-dlp のコマンド引数リストに Cookie オプション(--cookies または --cookies-from-browser)を付与する
/// ※ yt-dlp は実行終了時に渡された Cookie ファイルに書き戻す仕様があるため、
/// 元のファイルの上書き破壊や Read-Only マウントでの例外 (OSError Errno 30) を防ぐため、
/// 一時ファイルにコピーしてからそのパスを渡します。
/// </summary> /// </summary>
/// <param name="args">付与対象の引数リスト</param> /// <param name="args">付与対象の引数リスト</param>
/// <param name="outputBaseDir">音楽出力ベースディレクトリ</param> /// <param name="outputBaseDir">音楽出力ベースディレクトリ</param>
/// <param name="youtubeFolder">楽曲集約ディレクトリ</param> /// <param name="youtubeFolder">楽曲集約ディレクトリ</param>
/// <param name="tempWorkDir">一時作業ディレクトリ</param>
/// <returns>Cookieオプションが付与されたかどうか</returns> /// <returns>Cookieオプションが付与されたかどうか</returns>
public static bool ApplyCookieArgs(List<string> args, string? outputBaseDir = null, string? youtubeFolder = null) public static bool ApplyCookieArgs(List<string> args, string? outputBaseDir = null, string? youtubeFolder = null, string? tempWorkDir = null)
{ {
var cookieFile = FindCookiesFile(outputBaseDir, youtubeFolder); var cookieFile = FindCookiesFile(outputBaseDir, youtubeFolder);
if (!string.IsNullOrEmpty(cookieFile)) if (!string.IsNullOrEmpty(cookieFile))
{ {
var cookieToPass = cookieFile;
try
{
var targetDir = !string.IsNullOrWhiteSpace(tempWorkDir) && Directory.Exists(tempWorkDir)
? tempWorkDir
: Path.GetTempPath();
var tempCookie = Path.Combine(targetDir, $"yt_cookies_{Guid.NewGuid():N}.txt");
File.Copy(cookieFile, tempCookie, overwrite: true);
cookieToPass = tempCookie;
}
catch
{
// コピーに失敗した場合は元のパスを使用
}
args.Add("--cookies"); args.Add("--cookies");
args.Add(cookieFile); args.Add(cookieToPass);
return true; return true;
} }
@@ -113,9 +145,7 @@ namespace MusicDownloader.Class.Downloader
return (true, $"ブラウザCookie指定検出: {browser}"); return (true, $"ブラウザCookie指定検出: {browser}");
} }
var suggestedPath = !string.IsNullOrWhiteSpace(outputBaseDir) var suggestedPath = "C:\\Users\\<ユーザー名>\\Music\\cookies.txt または C:\\MyMusic\\cookies.txt";
? Path.Combine(outputBaseDir, "cookies.txt")
: "C:\\MyMusic\\cookies.txt または /app/cookies.txt";
return (false, $"未配置 (年齢制限動画を取得する場合は {suggestedPath} に cookies.txt を配置してください)"); return (false, $"未配置 (年齢制限動画を取得する場合は {suggestedPath} に cookies.txt を配置してください)");
} }
@@ -221,9 +221,12 @@ namespace MusicDownloader.Class.Downloader
// 【要件⑥】プレイリストごとのログファイル(MusicDownloader_開始時間_プレイリスト名.log)を設定 // 【要件⑥】プレイリストごとのログファイル(MusicDownloader_開始時間_プレイリスト名.log)を設定
LogManager.SetPlaylistContext(DateTime.Now, sanitizedPlaylistName); LogManager.SetPlaylistContext(DateTime.Now, sanitizedPlaylistName);
// ① 全ての曲を格納する共通フォルダ「Youtube」の準備 // ① 全ての曲を格納する共通フォルダ「Youtube」の準備および書き込み疎通確認
var youtubeFolder = Path.Combine(outputBaseDir, CmnDefine.YoutubeFolderName); var youtubeFolder = Path.Combine(outputBaseDir, CmnDefine.YoutubeFolderName);
Directory.CreateDirectory(youtubeFolder); if (!CmnUtil.EnsureStorageWritable(youtubeFolder))
{
throw new IOException($"出力先ディレクトリへの書き込みができません (Read-only file system またはストレージ切断): {youtubeFolder}");
}
// ④ Google Drive同期前の安全なローカル作業領域 // ④ Google Drive同期前の安全なローカル作業領域
var stagingDir = CmnDefine.GetStagingDir(); var stagingDir = CmnDefine.GetStagingDir();
@@ -538,40 +541,82 @@ namespace MusicDownloader.Class.Downloader
var sanitizedBaseName = CmnUtil.SanitizeFileName(rawBaseName); var sanitizedBaseName = CmnUtil.SanitizeFileName(rawBaseName);
var cleanFileName = $"{sanitizedBaseName}{ext}"; var cleanFileName = $"{sanitizedBaseName}{ext}";
// ① 同名別動画(another vocal等)の衝突を検知し、ユニークな保存名(曲名 (2).opus等)を決定 // 保存先へのファイル転送を安全に試行(Google Drive切断・マウント一時切れ時の自動待機&リトライ付き)
var finalFileName = GetUniqueTargetFileName(youtubeFolder, cleanFileName, videoId, downloadedTracks); bool transferSuccess = false;
var destOpusPath = Path.Combine(youtubeFolder, finalFileName); string targetFinalFileName = cleanFileName;
const int maxTransferRetries = 6; // 15秒 x 6回 = 最大90秒間待機
const int transferRetryDelayMs = 15000;
try for (int attempt = 1; attempt <= maxTransferRetries; attempt++)
{ {
File.Copy(targetOpus, destOpusPath, overwrite: true); try
LogManager.AddLog($"ファイルを保存先に配置しました: {finalFileName}");
// 歌詞ファイル (.lrc) も完成していれば転送(音声ファイル名に合わせた名前にする)
var lrcPath = Path.ChangeExtension(targetOpus, ".lrc");
if (File.Exists(lrcPath))
{ {
var targetLrcName = Path.ChangeExtension(finalFileName, ".lrc"); // ① 同名別動画(another vocal等)の衝突を検知し、ユニークな保存名(曲名 (2).opus等)を決定
var destLrcPath = Path.Combine(youtubeFolder, targetLrcName); var finalFileName = GetUniqueTargetFileName(youtubeFolder, cleanFileName, videoId, downloadedTracks);
File.Copy(lrcPath, destLrcPath, overwrite: true); var destOpusPath = Path.Combine(youtubeFolder, finalFileName);
File.Copy(targetOpus, destOpusPath, overwrite: true);
LogManager.AddLog($"ファイルを保存先に配置しました: {finalFileName}");
// 歌詞ファイル (.lrc) も完成していれば転送(音声ファイル名に合わせた名前にする)
var lrcPath = Path.ChangeExtension(targetOpus, ".lrc");
if (File.Exists(lrcPath))
{
var targetLrcName = Path.ChangeExtension(finalFileName, ".lrc");
var destLrcPath = Path.Combine(youtubeFolder, targetLrcName);
File.Copy(lrcPath, destLrcPath, overwrite: true);
}
// ダウンロード完了履歴 (archive.txt) に動画IDを記録
AddToArchiveFile(archiveFile, videoId);
transferSuccess = true;
targetFinalFileName = finalFileName;
break;
}
catch (Exception ex)
{
bool isStorageFail = CmnUtil.IsStorageFailureException(ex);
if (isStorageFail)
{
LogManager.AddWarning($"[保存先転送待機] Google Drive/ストレージ切断を検知しました (試行 {attempt}/{maxTransferRetries}): {ex.Message}。{transferRetryDelayMs / 1000}秒後に再試行します...");
if (attempt < maxTransferRetries)
{
await Task.Delay(transferRetryDelayMs);
continue;
}
else
{
LogManager.AddError($"[ストレージ切断エラー] Google Driveへのファイル転送が復旧しませんでした ({attempt}回試行): {ex.Message}", ex);
// 致命的ストレージ切断例外を上位にスローして後続曲の誤完了・破棄ループを即座に停止
throw new IOException($"Google Driveストレージ切断のため処理を安全に中断します: {ex.Message}", ex);
}
}
else
{
// 通常のエラー(権限不足や特定ファイル名不整合等)
LogManager.AddError($"保存先へのファイル転送に失敗しました: {ex.Message}", ex);
break;
}
} }
} }
catch (Exception ex)
// 転送が失敗した場合は、絶対に成功扱いせず作業フォルダを掃除して処理を中断
if (!transferSuccess)
{ {
LogManager.AddError($"保存先へのファイル転送に失敗しました: {ex.Message}", ex); RemoveFromArchiveFile(archiveFile, videoId);
}
finally
{
// 作業フォルダ内の完成ファイルを掃除
CleanupDirectory(stagingDir); CleanupDirectory(stagingDir);
return null;
} }
LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {finalFileName}"); // 転送成功時のみ作業フォルダを掃除し、完了ログを出力
CleanupDirectory(stagingDir);
LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {targetFinalFileName}");
return new DownloadedTrackInfo return new DownloadedTrackInfo
{ {
VideoId = videoId, VideoId = videoId,
FileName = finalFileName, FileName = targetFinalFileName,
Title = finalTitle, Title = finalTitle,
Artist = finalArtist, Artist = finalArtist,
Duration = entryInfo?.Duration, Duration = entryInfo?.Duration,
@@ -662,13 +707,12 @@ namespace MusicDownloader.Class.Downloader
"--retries", "5", "--retries", "5",
"--fragment-retries", "5", "--fragment-retries", "5",
"--retry-sleep", "3", "--retry-sleep", "3",
"--download-archive", archiveFile,
"-o", outputTemplate, "-o", outputTemplate,
"--no-warnings" "--no-warnings"
}; };
// CookieファイルまたはブラウザCookieの自動適用(年齢確認・制限解除用) // CookieファイルまたはブラウザCookieの自動適用(年齢確認・制限解除用、一時コピーで安全に適用)
CookieHelper.ApplyCookieArgs(baseArgs, outputBaseDir, youtubeFolder); CookieHelper.ApplyCookieArgs(baseArgs, outputBaseDir, youtubeFolder, stagingDir);
return baseArgs; return baseArgs;
} }
@@ -681,17 +725,17 @@ namespace MusicDownloader.Class.Downloader
var plan2 = GetBaseArgs(); var plan2 = GetBaseArgs();
plan2.Add(videoUrl); plan2.Add(videoUrl);
// 試行3: AndroidクライアントAPI(403 Forbidden ストリーム拒否対策・一部年齢制限対策) // 試行3: Mobile Webクライアント(Cookie対応・403 Forbidden対策・年齢確認対策)
var plan3 = GetBaseArgs(); var plan3 = GetBaseArgs();
plan3.AddRange(new[] { "--extractor-args", "youtube:player_client=android,web", videoUrl }); plan3.AddRange(new[] { "--extractor-args", "youtube:player_client=mweb,web", videoUrl });
// 試行4: Android Creator & Mobile Webクライアント(年齢確認バイパス試行) // 試行4: TVクライアントAPI(年齢確認バイパス試行)
var plan4 = GetBaseArgs(); var plan4 = GetBaseArgs();
plan4.AddRange(new[] { "--extractor-args", "youtube:player_client=android_creator,mweb", videoUrl }); plan4.AddRange(new[] { "--extractor-args", "youtube:player_client=tv_embedded,tv", videoUrl });
// 試行5: TVクライアントAPI(年齢確認バイパス試行) // 試行5: AndroidクライアントAPI(403 Forbidden ストリーム拒否対策)
var plan5 = GetBaseArgs(); var plan5 = GetBaseArgs();
plan5.AddRange(new[] { "--extractor-args", "youtube:player_client=tv_embedded,tv", videoUrl }); plan5.AddRange(new[] { "--extractor-args", "youtube:player_client=android,web", videoUrl });
// 試行6: iOSクライアントAPI & キャッシュ無効化(最終フォールバック) // 試行6: iOSクライアントAPI & キャッシュ無効化(最終フォールバック)
var plan6 = GetBaseArgs(); var plan6 = GetBaseArgs();
@@ -701,9 +745,9 @@ namespace MusicDownloader.Class.Downloader
{ {
("通常ダウンロード (日本語字幕あり)", plan1), ("通常ダウンロード (日本語字幕あり)", plan1),
("フォールバック1 (字幕取得オフ / 429対策)", plan2), ("フォールバック1 (字幕取得オフ / 429対策)", plan2),
("フォールバック2 (YouTube Androidクライアント / 403・年齢確認対策)", plan3), ("フォールバック2 (YouTube Mobile Webクライアント / 403・年齢確認対策)", plan3),
("フォールバック3 (YouTube Creator・mwebクライアント / 年齢確認対策)", plan4), ("フォールバック3 (YouTube TVクライアント / 年齢確認対策)", plan4),
("フォールバック4 (YouTube TVクライアント / 年齢確認対策)", plan5), ("フォールバック4 (YouTube Androidクライアント / 403対策)", plan5),
("フォールバック5 (YouTube iOSクライアント & キャッシュ無効化)", plan6) ("フォールバック5 (YouTube iOSクライアント & キャッシュ無効化)", plan6)
}; };
@@ -737,6 +781,7 @@ namespace MusicDownloader.Class.Downloader
} }
var stdErr = cmdResult.StandardError ?? ""; var stdErr = cmdResult.StandardError ?? "";
var stdOut = cmdResult.StandardOutput ?? "";
LogManager.AddWarning($"[{name}] 終了コード: {cmdResult.ExitCode}"); LogManager.AddWarning($"[{name}] 終了コード: {cmdResult.ExitCode}");
if (!string.IsNullOrWhiteSpace(stdErr)) if (!string.IsNullOrWhiteSpace(stdErr))
{ {
@@ -747,6 +792,11 @@ namespace MusicDownloader.Class.Downloader
} }
LogManager.AddWarning($"詳細: {stdErr.Trim()}"); LogManager.AddWarning($"詳細: {stdErr.Trim()}");
} }
else if (cmdResult.ExitCode == 0 && opusFiles.Length == 0 && !string.IsNullOrWhiteSpace(stdOut))
{
var lastOut = stdOut.Trim().Split('\n').LastOrDefault()?.Trim() ?? "";
LogManager.AddWarning($"詳細(stdout): {lastOut}");
}
// エラー終了コードでもOpusファイル自体が生成完了していれば成功とみなす // エラー終了コードでもOpusファイル自体が生成完了していれば成功とみなす
if (opusFiles.Length > 0) if (opusFiles.Length > 0)
@@ -797,6 +847,35 @@ namespace MusicDownloader.Class.Downloader
} }
} }
/// <summary>
/// ダウンロード成功時に archive.txt に動画ID(youtube <videoId>)を追記する
/// </summary>
private void AddToArchiveFile(string archiveFile, string videoId)
{
if (string.IsNullOrWhiteSpace(videoId) || string.IsNullOrWhiteSpace(archiveFile))
{
return;
}
try
{
var entry = $"youtube {videoId}";
if (File.Exists(archiveFile))
{
var lines = File.ReadAllLines(archiveFile);
if (lines.Any(l => l.Trim().Equals(entry, StringComparison.OrdinalIgnoreCase)))
{
return; // 既に記録済み
}
}
File.AppendAllLines(archiveFile, new[] { entry }, Encoding.UTF8);
}
catch (Exception ex)
{
LogManager.AddWarning($"archive.txt への追記中に例外: {ex.Message}");
}
}
/// <summary> /// <summary>
/// 【要件①】AndroidのPowerampで読み取れるプレイリストファイル(.m3u8)を保存 /// 【要件①】AndroidのPowerampで読み取れるプレイリストファイル(.m3u8)を保存
/// m3u8ファイルはYoutubeフォルダ内には作成せず、親フォルダ(outputBaseDir)直下のみに配置します。 /// m3u8ファイルはYoutubeフォルダ内には作成せず、親フォルダ(outputBaseDir)直下のみに配置します。
@@ -1032,6 +1111,11 @@ namespace MusicDownloader.Class.Downloader
catch (Exception ex) catch (Exception ex)
{ {
LogManager.AddWarning($"downloaded_tracks.json の保存に失敗しました: {ex.Message}"); LogManager.AddWarning($"downloaded_tracks.json の保存に失敗しました: {ex.Message}");
if (CmnUtil.IsStorageFailureException(ex))
{
// ストレージ切断時は上位へスローしてプロセス終了・自己復旧へ促す
throw new IOException($"downloaded_tracks.json 保存中にストレージ切断を検知しました: {ex.Message}", ex);
}
} }
} }
@@ -1091,7 +1175,7 @@ namespace MusicDownloader.Class.Downloader
foreach (var file in files) foreach (var file in files)
{ {
var ext = Path.GetExtension(file).ToLowerInvariant(); var ext = Path.GetExtension(file).ToLowerInvariant();
if (ext == ".vtt" || ext == ".part" || ext == ".ytdl" || ext == ".jpg" || ext == ".webp" || ext == ".png") if (ext == ".vtt" || ext == ".part" || ext == ".ytdl" || ext == ".jpg" || ext == ".webp" || ext == ".png" || ext == ".txt")
{ {
try { File.Delete(file); } catch { } try { File.Delete(file); } catch { }
} }
+3 -2
View File
@@ -27,8 +27,9 @@
<Message Text="=== [Local Docker Deploy] Starting Deploy via MSBuild ===" Importance="high" /> <Message Text="=== [Local Docker Deploy] Starting Deploy via MSBuild ===" Importance="high" />
<!-- G:\マイドライブ\MyMusic へのジャンクション C:\MyMusic の作成(Docker共有用) --> <!-- G:\マイドライブ\MyMusic へのジャンクション C:\MyMusic の作成(Docker共有用) -->
<Exec Command="powershell -Command &quot;if (!(Test-Path 'C:\MyMusic') -and (Test-Path 'G:\マイドライブ\MyMusic')) { New-Item -ItemType Junction -Path 'C:\MyMusic' -Target 'G:\マイドライブ\MyMusic' }&quot;" /> <Exec Command="powershell -Command &quot;if (!(Test-Path 'C:\MyMusic') -and (Test-Path 'G:\マイドライブ\MyMusic')) { New-Item -ItemType Junction -Path 'C:\MyMusic' -Target 'G:\マイドライブ\MyMusic' }&quot;" />
<!-- WSL2 (docker-desktop) への G: ドライブのマウント保証 --> <!-- WSL2 (docker-desktop) への G: ドライブのマウント健全化(Docker Desktopの全マウントパスに反映) -->
<Exec Command="wsl -d docker-desktop sh -c &quot;mkdir -p /mnt/host/g &amp;&amp; mount -t drvfs G: /mnt/host/g || true&quot;" /> <Exec Command="wsl -d docker-desktop sh -c &quot;while umount -l /tmp/docker-desktop-root/run/desktop/mnt/host/g 2>/dev/null; do :; done; while umount -l /tmp/docker-desktop-root/mnt/host/g 2>/dev/null; do :; done; while umount -l /mnt/host/g 2>/dev/null; do :; done; mkdir -p /mnt/host/g &amp;&amp; mount -t drvfs G: /mnt/host/g &amp;&amp; mkdir -p /tmp/docker-desktop-root/run/desktop/mnt/host/g /tmp/docker-desktop-root/mnt/host/g &amp;&amp; mount --bind /mnt/host/g /tmp/docker-desktop-root/run/desktop/mnt/host/g &amp;&amp; mount --bind /mnt/host/g /tmp/docker-desktop-root/mnt/host/g || true&quot;" />
<Exec Command="wsl -d docker-desktop sh -c &quot;ls -d /mnt/host/c/MyMusic/Youtube >/dev/null 2>&amp;1 &amp;&amp; echo '[WSL Mount OK] /mnt/host/c/MyMusic/Youtube is verified.' || echo '[WSL Mount Warning] Could not access /mnt/host/c/MyMusic/Youtube.'&quot;" />
<!-- 配置先ディレクトリ C:\docker\MusicDownloader\app の存在確認と作成 --> <!-- 配置先ディレクトリ C:\docker\MusicDownloader\app の存在確認と作成 -->
<Exec Command="powershell -Command &quot;if (!(Test-Path 'C:\docker\MusicDownloader\app')) { New-Item -ItemType Directory -Force -Path 'C:\docker\MusicDownloader\app' }&quot;" /> <Exec Command="powershell -Command &quot;if (!(Test-Path 'C:\docker\MusicDownloader\app')) { New-Item -ItemType Directory -Force -Path 'C:\docker\MusicDownloader\app' }&quot;" />
<!-- 発行済みファイルを C:\docker\MusicDownloader\app に同期(Visual Studio発行プロファイル・CLI共通対応) --> <!-- 発行済みファイルを C:\docker\MusicDownloader\app に同期(Visual Studio発行プロファイル・CLI共通対応) -->
+44 -1
View File
@@ -171,7 +171,7 @@ List<string> ResolveTargetPlaylists(string baseDir)
// 存在しない場合は初期設定のURL一覧を playlists.txt として保存(今後の追加編集用) // 存在しない場合は初期設定のURL一覧を playlists.txt として保存(今後の追加編集用)
try try
{ {
Directory.CreateDirectory(baseDir); CmnUtil.EnsureDirectoryExists(baseDir);
File.WriteAllLines(playlistsFile, defaultPlaylistUrls); File.WriteAllLines(playlistsFile, defaultPlaylistUrls);
LogManager.AddLog($"playlists.txt を初期生成しました: {playlistsFile}"); LogManager.AddLog($"playlists.txt を初期生成しました: {playlistsFile}");
} }
@@ -207,6 +207,41 @@ LogManager.AddLog($"[起動時モード判定] 初回処理: {(isResumeOnStartup
while (true) while (true)
{ {
loopCount++; loopCount++;
// 各サイクルの開始前に出力先ストレージの接続健全性を確認(書き込み疎通テスト)
var commonYoutubeDir = Path.Combine(outputDir, CmnDefine.YoutubeFolderName);
bool isStorageReady = false;
int storageWaitCount = 0;
while (!isStorageReady)
{
if (CmnUtil.EnsureStorageWritable(outputDir, maxRetries: 1, retryDelayMs: 1000) &&
CmnUtil.EnsureStorageWritable(commonYoutubeDir, maxRetries: 1, retryDelayMs: 1000))
{
isStorageReady = true;
if (storageWaitCount > 0)
{
LogManager.AddSuccess($"[ストレージ復旧] 出力先ストレージへの書き込み権限を確認しました。処理を再開します。");
}
break;
}
storageWaitCount++;
if (storageWaitCount == 1)
{
LogManager.AddWarning($"[ストレージ待機] 出力先ストレージ ({outputDir}) が読み取り専用または未マウントです。");
LogManager.AddLog($"[ストレージ待機] Google Drive の起動およびマウント完了を待機しています (10秒間隔で自動確認中)...");
}
await Task.Delay(10000);
// 3分以上待機しても復旧しない場合は、ログを残して待機監視を継続
if (storageWaitCount % 18 == 0) // 18 * 10秒 = 180秒 (3分ごと)
{
LogManager.AddWarning($"[ストレージ待機継続中] Google Drive ({outputDir}) がまだ書き込み可能になっていません。ホスト側の起動を待機しています...");
}
}
// 初回実行時: 設定ファイルが resume なら差分ダウンロード (true)、from_scratch なら全曲ダウンロード (false) // 初回実行時: 設定ファイルが resume なら差分ダウンロード (true)、from_scratch なら全曲ダウンロード (false)
// 2回目以降 (loopCount > 1): 常に差分ダウンロード (true) // 2回目以降 (loopCount > 1): 常に差分ダウンロード (true)
bool isIncremental = isFirstRun ? isResumeOnStartup : true; bool isIncremental = isFirstRun ? isResumeOnStartup : true;
@@ -248,6 +283,14 @@ while (true)
catch (Exception ex) catch (Exception ex)
{ {
LogManager.AddError($"プレイリスト処理中にエラーが発生しました: {ex.Message}", ex); LogManager.AddError($"プレイリスト処理中にエラーが発生しました: {ex.Message}", ex);
// ストレージ切断(Invalid argument, Read-only, I/O error 等)が発生した場合はループを継続せずプロセスを終了し、コンテナの自動再起動に委ねる
if (CmnUtil.IsStorageFailureException(ex))
{
LogManager.AddError($"[ストレージ障害検知] 出力先ストレージ(Google Drive / WSL2マウント)の切断または障害を検知しました: {ex.Message}");
LogManager.AddError($"残りのプレイリスト処理を安全に中断し、コンテナ自動再起動による自己復旧のためプロセスを終了します。");
Environment.Exit(1);
}
} }
// プレイリスト間で不要メモリを完全に返却 // プレイリスト間で不要メモリを完全に返却
+59
View File
@@ -0,0 +1,59 @@
# ==============================================================================
# Google Drive (G:) WSL2 Auto-Mount & MusicDownloader Health Check Script
# Periodically monitors Google Drive mount status and automatically repairs
# broken mounts or stale containers.
# ==============================================================================
$logDir = "C:\feeds\Log"
if (!(Test-Path $logDir)) {
New-Item -ItemType Directory -Force -Path $logDir | Out-Null
}
$logFile = Join-Path $logDir "auto-mount-gdrive.log"
function Write-Log($msg) {
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$line = "[$timestamp] $msg"
Write-Output $line
Add-Content -Path $logFile -Value $line -Encoding UTF8
}
# 1. ホスト側 Google Drive (G:) のアクセス健全性確認
if (!(Test-Path "G:\マイドライブ\MyMusic") -or !(Test-Path "C:\MyMusic")) {
# ホスト側で Google Drive が起動していない場合は何もしない
exit 0
}
# 2. WSL2 (docker-desktop) 上の Google Drive マウント健全性確認
$wslCheckCmd = "ls -d /mnt/host/c/MyMusic/Youtube >/dev/null 2>&1"
$null = wsl -d docker-desktop sh -c $wslCheckCmd 2>&1
$isWslMountBroken = ($LASTEXITCODE -ne 0)
if ($isWslMountBroken) {
Write-Log "[異常検知] WSL2 の Google Drive マウント切断 (Invalid argument 等) を検知しました。マウントを修復します..."
$remountCmd = "while umount -l /tmp/docker-desktop-root/run/desktop/mnt/host/g 2>/dev/null; do :; done; while umount -l /tmp/docker-desktop-root/mnt/host/g 2>/dev/null; do :; done; while umount -l /mnt/host/g 2>/dev/null; do :; done; mkdir -p /mnt/host/g && mount -t drvfs G: /mnt/host/g && mkdir -p /tmp/docker-desktop-root/run/desktop/mnt/host/g /tmp/docker-desktop-root/mnt/host/g && mount --bind /mnt/host/g /tmp/docker-desktop-root/run/desktop/mnt/host/g && mount --bind /mnt/host/g /tmp/docker-desktop-root/mnt/host/g && (ls -d /mnt/host/c/MyMusic/Youtube >/dev/null 2>&1 && echo 'MOUNT_OK' || echo 'MOUNT_NG')"
$remountResult = wsl -d docker-desktop sh -c $remountCmd 2>&1
Write-Log "WSL2 再マウント結果: $remountResult"
}
# 3. MusicDownloader コンテナの健全性確認および復旧
try {
$containerStatus = docker inspect MusicDownloader --format "{{.State.Status}}" 2>&1
if ($containerStatus -eq "running") {
# コンテナ内部からのマウントアクセス確認
$null = docker exec MusicDownloader ls -d /music/Youtube 2>&1
$isContainerMountBroken = ($LASTEXITCODE -ne 0)
if ($isWslMountBroken -or $isContainerMountBroken) {
Write-Log "[コンテナ修復] コンテナ内のマウント無効化を検知しました。MusicDownloader を再起動します..."
docker restart MusicDownloader | Out-Null
Write-Log "[成功] MusicDownloader コンテナを再起動しました。"
}
} elseif ($containerStatus -eq "exited" -or $containerStatus -eq "created") {
Write-Log "コンテナが停止しています (Status: $containerStatus)。MusicDownloader を起動します..."
docker start MusicDownloader | Out-Null
Write-Log "[成功] MusicDownloader コンテナを起動しました。"
}
} catch {
Write-Log "[エラー] コンテナ確認中に例外が発生しました: $_"
}
+2
View File
@@ -30,6 +30,8 @@ services:
- C:\feeds:/feeds - C:\feeds:/feeds
# 初回起動時の動作設定(最初から行う: from_scratch / 続きから行う: resume) # 初回起動時の動作設定(最初から行う: from_scratch / 続きから行う: resume)
- C:\VS2026\MusicDownloader\run_config.json:/app/run_config.json:ro - C:\VS2026\MusicDownloader\run_config.json:/app/run_config.json:ro
# ユーザーの標準ミュージックフォルダに配置された cookies.txt をコンテナ内で自動認識するためのマウント
- C:\Users\uduki\Music:/user_music:ro
networks: networks:
- common-network - common-network
+34
View File
@@ -0,0 +1,34 @@
@echo off
chcp 65001 > nul
echo ========================================================
echo Google Drive (G:) WSL2 マウント再接続ツール
echo ========================================================
echo.
echo [1/3] ホスト側の Google Drive (G:) 接続確認中...
if not exist "G:\マイドライブ\MyMusic" (
echo [エラー] ホスト側で G:\マイドライブ\MyMusic が見つかりません。
echo Google Drive for Desktop が起動し、ログインしているか確認してください。
pause
exit /b 1
)
echo [成功] ホスト側 Google Drive (G:) を確認しました。
echo.
echo [2/3] WSL2 (docker-desktop) 上の古いマウントを解除して全マウントパスへ再接続中...
wsl -d docker-desktop sh -c "while umount -l /tmp/docker-desktop-root/run/desktop/mnt/host/g 2>/dev/null; do :; done; while umount -l /tmp/docker-desktop-root/mnt/host/g 2>/dev/null; do :; done; while umount -l /mnt/host/g 2>/dev/null; do :; done; mkdir -p /mnt/host/g && mount -t drvfs G: /mnt/host/g && mkdir -p /tmp/docker-desktop-root/run/desktop/mnt/host/g /tmp/docker-desktop-root/mnt/host/g && mount --bind /mnt/host/g /tmp/docker-desktop-root/run/desktop/mnt/host/g && mount --bind /mnt/host/g /tmp/docker-desktop-root/mnt/host/g"
echo.
echo [3/3] コンテナマウント元 (C:\MyMusic\Youtube) のアクセス疎通確認中...
wsl -d docker-desktop sh -c "ls -d /mnt/host/c/MyMusic/Youtube >/dev/null 2>&1"
if %ERRORLEVEL% equ 0 (
echo [成功] WSL2 から C:\MyMusic (G:\マイドライブ\MyMusic\Youtube) へのアクセスが正常に復旧しました!
) else (
echo [警告] WSL2 からのアクセスに失敗しました。Docker Desktop または WSL の再起動が必要な可能性があります。
)
echo.
echo ========================================================
echo 完了しました。
echo ========================================================
pause
+3
View File
@@ -0,0 +1,3 @@
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "powershell.exe -ExecutionPolicy Bypass -WindowStyle Hidden -File ""C:\VS2026\MusicDownloader\auto-mount-gdrive.ps1""", 0, False
Set WshShell = Nothing
+31
View File
@@ -0,0 +1,31 @@
# ==============================================================================
# Setup Startup Task and Shortcut for MusicDownloader Auto-Mount
# ==============================================================================
$scriptDir = "C:\VS2026\MusicDownloader"
$vbsPath = Join-Path $scriptDir "run-auto-mount-silent.vbs"
$ps1Path = Join-Path $scriptDir "auto-mount-gdrive.ps1"
# 1. Register to Startup Folder (PC起動時・ログオン時の即座実行用)
$startupFolder = [Environment]::GetFolderPath([Environment+SpecialFolder]::Startup)
$startupVbs = Join-Path $startupFolder "MusicDownloader-AutoMount.vbs"
Copy-Item -Path $vbsPath -Destination $startupVbs -Force
Write-Host "[OK] Startup folder configured: $startupVbs"
# 2. Register to Windows Task Scheduler (5分ごとの定期ヘルスチェック&自動復旧用)
$taskName = "MusicDownloader-AutoMount"
$taskCmd = "wscript.exe $vbsPath"
try {
# schtasks を用いて一般ユーザー権限でも登録可能な5分毎タスクを作成
& schtasks /create /tn $taskName /tr $taskCmd /sc minute /mo 5 /f | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Host "[OK] Task Scheduler configured (every 5 mins): $taskName"
} else {
Write-Warning "[Warning] schtasks failed with exit code: $LASTEXITCODE"
}
} catch {
Write-Warning "[Warning] Failed to register ScheduledTask: $_"
}
Write-Host "Setup completed successfully."