Compare commits

..
6 Commits
13 changed files with 780 additions and 40 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;
}
} }
} }
@@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.IO;
namespace MusicDownloader.Class.Downloader
{
/// <summary>
/// YouTubeの認証・年齢制限解除用Cookie(cookies.txt)やブラウザCookieの検出・引数付与を行うヘルパークラス
/// </summary>
public static class CookieHelper
{
/// <summary>
/// 利用可能な cookies.txt ファイルの絶対パスを探索して取得する
/// </summary>
/// <param name="outputBaseDir">音楽出力ベースディレクトリ(例: C:\MyMusic や /music)</param>
/// <param name="youtubeFolder">楽曲集約ディレクトリ(例: C:\MyMusic\Youtube や /music/Youtube)</param>
/// <returns>見つかったCookieファイルの絶対パス、存在しない場合は null</returns>
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. ユーザーマウントの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))
{
var p = Path.Combine(outputBaseDir, "cookies.txt");
if (File.Exists(p)) return Path.GetFullPath(p);
}
// 5. 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);
}
// 6. アプリケーション実行フォルダ直下(ローカル bin 配下またはコンテナ /app/cookies.txt)
var appDir = AppDomain.CurrentDomain.BaseDirectory;
var appCookie = Path.Combine(appDir, "cookies.txt");
if (File.Exists(appCookie)) return Path.GetFullPath(appCookie);
// 7. ログ出力先ボリューム(ホスト 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;
}
/// <summary>
/// ローカル実行時にブラウザから直接Cookieを取得するための指定名(chrome, firefox, edge等)を取得する
/// </summary>
public static string? GetCookiesBrowser()
{
var envBrowser = Environment.GetEnvironmentVariable("YOUTUBE_COOKIES_BROWSER")
?? Environment.GetEnvironmentVariable("COOKIES_BROWSER");
return string.IsNullOrWhiteSpace(envBrowser) ? null : envBrowser.Trim();
}
/// <summary>
/// yt-dlp のコマンド引数リストに Cookie オプション(--cookies または --cookies-from-browser)を付与する
/// ※ yt-dlp は実行終了時に渡された Cookie ファイルに書き戻す仕様があるため、
/// 元のファイルの上書き破壊や Read-Only マウントでの例外 (OSError Errno 30) を防ぐため、
/// 一時ファイルにコピーしてからそのパスを渡します。
/// </summary>
/// <param name="args">付与対象の引数リスト</param>
/// <param name="outputBaseDir">音楽出力ベースディレクトリ</param>
/// <param name="youtubeFolder">楽曲集約ディレクトリ</param>
/// <param name="tempWorkDir">一時作業ディレクトリ</param>
/// <returns>Cookieオプションが付与されたかどうか</returns>
public static bool ApplyCookieArgs(List<string> args, string? outputBaseDir = null, string? youtubeFolder = null, string? tempWorkDir = null)
{
var cookieFile = FindCookiesFile(outputBaseDir, youtubeFolder);
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(cookieToPass);
return true;
}
var browser = GetCookiesBrowser();
if (!string.IsNullOrEmpty(browser))
{
args.Add("--cookies-from-browser");
args.Add(browser);
return true;
}
return false;
}
/// <summary>
/// 現在のCookie検出状況を説明する文字列を取得する(ログ出力・案内用)
/// </summary>
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 = "C:\\Users\\<ユーザー名>\\Music\\cookies.txt または C:\\MyMusic\\cookies.txt";
return (false, $"未配置 (年齢制限動画を取得する場合は {suggestedPath} に cookies.txt を配置してください)");
}
}
}
@@ -0,0 +1,110 @@
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace MusicDownloader.Class.Downloader
{
/// <summary>
/// Docker公開時・起動時の処理モード(最初から / 続きから)を制御する設定クラス
/// </summary>
public class RunConfig
{
/// <summary>
/// 初回起動時の動作モード: "resume" (続きから / 差分) または "from_scratch" (最初から / 全曲)
/// </summary>
[JsonPropertyName("initial_mode")]
public string InitialMode { get; set; } = "resume";
/// <summary>
/// 読み込み元の設定ファイルパス
/// </summary>
[JsonIgnore]
public string? LoadedPath { get; set; }
/// <summary>
/// 初回処理を続きから行う(差分ダウンロード)かどうかを判定する
/// </summary>
/// <returns>true: 続きから(差分), false: 最初から(全曲再取得)</returns>
public bool IsResumeMode()
{
// 環境変数 INITIAL_DOWNLOAD_MODE による上書きチェック
var envMode = Environment.GetEnvironmentVariable("INITIAL_DOWNLOAD_MODE");
var modeToCheck = !string.IsNullOrWhiteSpace(envMode) ? envMode : InitialMode;
if (string.IsNullOrWhiteSpace(modeToCheck))
{
return true; // デフォルトは続きから
}
var val = modeToCheck.Trim().ToLowerInvariant();
if (val is "from_scratch" or "scratch" or "reset" or "full" or "最初から" or "全曲" or "false")
{
return false;
}
return true;
}
/// <summary>
/// 設定ファイル(run_config.json)を探索して読み込む
/// </summary>
/// <param name="outputDir">ベース出力先ディレクトリ</param>
/// <returns>読み込まれた設定オブジェクト</returns>
public static RunConfig Load(string? outputDir = null)
{
// 探索対象のパス候補
var candidates = new List<string>();
// 1. 環境変数による指定パス
var envPath = Environment.GetEnvironmentVariable("RUN_CONFIG_PATH");
if (!string.IsNullOrWhiteSpace(envPath)) candidates.Add(envPath);
// 2. コンテナ内の /app/run_config.json または実行フォルダ直下
var appDir = AppDomain.CurrentDomain.BaseDirectory;
candidates.Add(Path.Combine(appDir, "run_config.json"));
// 3. /config/run_config.json
candidates.Add("/config/run_config.json");
// 4. 出力フォルダ配下(/music/run_config.json 等)
if (!string.IsNullOrWhiteSpace(outputDir))
{
candidates.Add(Path.Combine(outputDir, "run_config.json"));
}
// 5. ホスト開発環境の既定パス(C:\VS2026\MusicDownloader\run_config.json)
candidates.Add(@"C:\VS2026\MusicDownloader\run_config.json");
foreach (var candidate in candidates)
{
try
{
if (File.Exists(candidate))
{
var json = File.ReadAllText(candidate);
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
ReadCommentHandling = JsonCommentHandling.Skip,
AllowTrailingCommas = true
};
var config = JsonSerializer.Deserialize<RunConfig>(json, options);
if (config != null)
{
config.LoadedPath = candidate;
return config;
}
}
}
catch (Exception ex)
{
LogManager.AddWarning($"設定ファイル '{candidate}' の読み込み中に例外: {ex.Message}");
}
}
// 見つからなかった場合はデフォルト(続きから)
return new RunConfig { InitialMode = "resume", LoadedPath = null };
}
}
}
@@ -145,14 +145,19 @@ namespace MusicDownloader.Class.Downloader
/// <summary> /// <summary>
/// プレイリストURLからプレイリスト名および動画リストを取得する /// プレイリストURLからプレイリスト名および動画リストを取得する
/// </summary> /// </summary>
public async Task<YtPlaylistInfo?> GetPlaylistInfoAsync(string playlistUrl) public async Task<YtPlaylistInfo?> GetPlaylistInfoAsync(string playlistUrl, string? outputBaseDir = null)
{ {
LogManager.AddLog($"プレイリスト情報を取得中: {playlistUrl}"); LogManager.AddLog($"プレイリスト情報を取得中: {playlistUrl}");
try try
{ {
var args = new List<string> { "--dump-single-json", "--flat-playlist", "--no-warnings" };
// Cookieファイルが存在する場合は付与(年齢制限や限定公開動画のメタデータ取得用)
CookieHelper.ApplyCookieArgs(args, outputBaseDir);
args.Add(playlistUrl);
var result = await Cli.Wrap(_ytDlpPath) var result = await Cli.Wrap(_ytDlpPath)
.WithArguments(new[] { "--dump-single-json", "--flat-playlist", "--no-warnings", playlistUrl }) .WithArguments(args)
.WithValidation(CommandResultValidation.None) .WithValidation(CommandResultValidation.None)
.ExecuteBufferedAsync(); .ExecuteBufferedAsync();
@@ -209,16 +214,19 @@ namespace MusicDownloader.Class.Downloader
/// <param name="isIncremental">差分ダウンロードを行うかどうか (falseの場合は起動直後として全曲をダウンロード・最新化)</param> /// <param name="isIncremental">差分ダウンロードを行うかどうか (falseの場合は起動直後として全曲をダウンロード・最新化)</param>
public async Task ProcessPlaylistAsync(string playlistUrl, string outputBaseDir, bool isIncremental = true) 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 rawTitle = playlistInfo?.Title ?? "YouTube_Playlist";
var sanitizedPlaylistName = CmnUtil.SanitizeFileName(rawTitle); var sanitizedPlaylistName = CmnUtil.SanitizeFileName(rawTitle);
// 【要件⑥】プレイリストごとのログファイル(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();
@@ -268,7 +276,7 @@ namespace MusicDownloader.Class.Downloader
// 単一動画URLまたはエントリがフラット取得できなかった場合、直接ダウンロード // 単一動画URLまたはエントリがフラット取得できなかった場合、直接ダウンロード
LogManager.AddLog($"プレイリストのエントリが見つからないか単一動画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) if (singleTrack != null)
{ {
currentPlaylistTracks.Add(singleTrack); currentPlaylistTracks.Add(singleTrack);
@@ -310,7 +318,7 @@ namespace MusicDownloader.Class.Downloader
// 1曲の処理(ローカル作業フォルダでダウンロード・タグ付け・検証を完結させ、完成後にYoutubeフォルダへ転送) // 1曲の処理(ローカル作業フォルダでダウンロード・タグ付け・検証を完結させ、完成後にYoutubeフォルダへ転送)
var trackInfo = await DownloadAndProcessSingleAsync( var trackInfo = await DownloadAndProcessSingleAsync(
videoUrl, videoIndex, totalCount, stagingDir, youtubeFolder, sanitizedPlaylistName, entry, downloadedTracks); videoUrl, videoIndex, totalCount, stagingDir, youtubeFolder, sanitizedPlaylistName, entry, downloadedTracks, outputBaseDir);
if (trackInfo != null) if (trackInfo != null)
{ {
@@ -356,13 +364,14 @@ namespace MusicDownloader.Class.Downloader
string youtubeFolder, string youtubeFolder,
string playlistName, string playlistName,
YtPlaylistEntry? entryInfo, YtPlaylistEntry? entryInfo,
Dictionary<string, DownloadedTrackInfo> downloadedTracks) Dictionary<string, DownloadedTrackInfo> downloadedTracks,
string? outputBaseDir = null)
{ {
var videoId = entryInfo?.Id ?? ""; var videoId = entryInfo?.Id ?? "";
var archiveFile = Path.Combine(youtubeFolder, "archive.txt"); var archiveFile = Path.Combine(youtubeFolder, "archive.txt");
// ② 多段階フォールバックによるダウンロード実行(429字幕エラーや403Forbiddenエラーを自動回避) // ② 多段階フォールバックによるダウンロード実行(429字幕エラー、403Forbiddenエラー、年齢制限エラーを自動回避)
var isDownloadSuccess = await DownloadWithFallbackAsync(videoUrl, videoId, stagingDir, archiveFile); var isDownloadSuccess = await DownloadWithFallbackAsync(videoUrl, videoId, stagingDir, archiveFile, outputBaseDir, youtubeFolder, entryInfo?.Title);
if (!isDownloadSuccess) if (!isDownloadSuccess)
{ {
LogManager.AddWarning($"[{index}/{totalCount}] すべてのフォールバックを試みましたがダウンロードできませんでした。"); LogManager.AddWarning($"[{index}/{totalCount}] すべてのフォールバックを試みましたがダウンロードできませんでした。");
@@ -532,12 +541,20 @@ namespace MusicDownloader.Class.Downloader
var sanitizedBaseName = CmnUtil.SanitizeFileName(rawBaseName); var sanitizedBaseName = CmnUtil.SanitizeFileName(rawBaseName);
var cleanFileName = $"{sanitizedBaseName}{ext}"; var cleanFileName = $"{sanitizedBaseName}{ext}";
// 保存先へのファイル転送を安全に試行(Google Drive切断・マウント一時切れ時の自動待機&リトライ付き)
bool transferSuccess = false;
string targetFinalFileName = cleanFileName;
const int maxTransferRetries = 6; // 15秒 x 6回 = 最大90秒間待機
const int transferRetryDelayMs = 15000;
for (int attempt = 1; attempt <= maxTransferRetries; attempt++)
{
try
{
// ① 同名別動画(another vocal等)の衝突を検知し、ユニークな保存名(曲名 (2).opus等)を決定 // ① 同名別動画(another vocal等)の衝突を検知し、ユニークな保存名(曲名 (2).opus等)を決定
var finalFileName = GetUniqueTargetFileName(youtubeFolder, cleanFileName, videoId, downloadedTracks); var finalFileName = GetUniqueTargetFileName(youtubeFolder, cleanFileName, videoId, downloadedTracks);
var destOpusPath = Path.Combine(youtubeFolder, finalFileName); var destOpusPath = Path.Combine(youtubeFolder, finalFileName);
try
{
File.Copy(targetOpus, destOpusPath, overwrite: true); File.Copy(targetOpus, destOpusPath, overwrite: true);
LogManager.AddLog($"ファイルを保存先に配置しました: {finalFileName}"); LogManager.AddLog($"ファイルを保存先に配置しました: {finalFileName}");
@@ -549,23 +566,57 @@ namespace MusicDownloader.Class.Downloader
var destLrcPath = Path.Combine(youtubeFolder, targetLrcName); var destLrcPath = Path.Combine(youtubeFolder, targetLrcName);
File.Copy(lrcPath, destLrcPath, overwrite: true); File.Copy(lrcPath, destLrcPath, overwrite: true);
} }
// ダウンロード完了履歴 (archive.txt) に動画IDを記録
AddToArchiveFile(archiveFile, videoId);
transferSuccess = true;
targetFinalFileName = finalFileName;
break;
} }
catch (Exception ex) catch (Exception ex)
{ {
LogManager.AddError($"保存先へのファイル転送に失敗しました: {ex.Message}", ex); bool isStorageFail = CmnUtil.IsStorageFailureException(ex);
} if (isStorageFail)
finally
{ {
// 作業フォルダ内の完成ファイルを掃除 LogManager.AddWarning($"[保存先転送待機] Google Drive/ストレージ切断を検知しました (試行 {attempt}/{maxTransferRetries}): {ex.Message}。{transferRetryDelayMs / 1000}秒後に再試行します...");
CleanupDirectory(stagingDir); 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;
}
}
} }
LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {finalFileName}"); // 転送が失敗した場合は、絶対に成功扱いせず作業フォルダを掃除して処理を中断
if (!transferSuccess)
{
RemoveFromArchiveFile(archiveFile, videoId);
CleanupDirectory(stagingDir);
return null;
}
// 転送成功時のみ作業フォルダを掃除し、完了ログを出力
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,
@@ -623,19 +674,25 @@ namespace MusicDownloader.Class.Downloader
/// <summary> /// <summary>
/// ② 多段階フォールバックにより動画の音声を確実にダウンロードする /// ② 多段階フォールバックにより動画の音声を確実にダウンロードする
/// - Cookie自動適用: cookies.txt による年齢制限解除・高画質取得
/// - 429 Too Many Requests: 字幕ダウンロードを無効化して音声のみ取得 /// - 429 Too Many Requests: 字幕ダウンロードを無効化して音声のみ取得
/// - 403 Forbidden: YouTube AndroidクライアントAPIやiOSクライアントAPIへの切り替え /// - 403 Forbidden / 年齢制限: YouTube Android / Creator / TV / iOS クライアントAPIへの自動切り替え
/// </summary> /// </summary>
private async Task<bool> DownloadWithFallbackAsync( private async Task<bool> DownloadWithFallbackAsync(
string videoUrl, string videoUrl,
string videoId, string videoId,
string stagingDir, string stagingDir,
string archiveFile) string archiveFile,
string? outputBaseDir = null,
string? youtubeFolder = null,
string? videoTitle = null)
{ {
var outputTemplate = Path.Combine(stagingDir, "%(title)s.%(ext)s"); var outputTemplate = Path.Combine(stagingDir, "%(title)s.%(ext)s");
// 基本引数の生成 // 基本引数の生成
List<string> GetBaseArgs() => new List<string> List<string> GetBaseArgs()
{
var baseArgs = new List<string>
{ {
"-f", "bestaudio/best", "-f", "bestaudio/best",
"--extract-audio", "--extract-audio",
@@ -650,11 +707,16 @@ 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の自動適用(年齢確認・制限解除用、一時コピーで安全に適用)
CookieHelper.ApplyCookieArgs(baseArgs, outputBaseDir, youtubeFolder, stagingDir);
return baseArgs;
}
// 試行1: 標準(429を避けるため英語en字幕は除外してja字幕のみ) // 試行1: 標準(429を避けるため英語en字幕は除外してja字幕のみ)
var plan1 = GetBaseArgs(); var plan1 = GetBaseArgs();
plan1.AddRange(new[] { "--write-subs", "--write-auto-subs", "--sub-lang", "ja", "--sub-format", "vtt", videoUrl }); plan1.AddRange(new[] { "--write-subs", "--write-auto-subs", "--sub-lang", "ja", "--sub-format", "vtt", videoUrl });
@@ -663,22 +725,34 @@ 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: iOSクライアントAPI & キャッシュ無効化(最終フォールバック) // 試行4: TVクライアントAPI(年齢確認バイパス試行)
var plan4 = GetBaseArgs(); 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=tv_embedded,tv", videoUrl });
// 試行5: AndroidクライアントAPI(403 Forbidden ストリーム拒否対策)
var plan5 = GetBaseArgs();
plan5.AddRange(new[] { "--extractor-args", "youtube:player_client=android,web", 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<string> Args)[] var plans = new (string Name, List<string> Args)[]
{ {
("通常ダウンロード (日本語字幕あり)", plan1), ("通常ダウンロード (日本語字幕あり)", plan1),
("フォールバック1 (字幕取得オフ / 429対策)", plan2), ("フォールバック1 (字幕取得オフ / 429対策)", plan2),
("フォールバック2 (YouTube Androidクライアント / 403対策)", plan3), ("フォールバック2 (YouTube Mobile Webクライアント / 403・年齢確認対策)", plan3),
("フォールバック3 (YouTube iOSクライアント & キャッシュ無効化)", plan4) ("フォールバック3 (YouTube TVクライアント / 年齢確認対策)", plan4),
("フォールバック4 (YouTube Androidクライアント / 403対策)", plan5),
("フォールバック5 (YouTube iOSクライアント & キャッシュ無効化)", plan6)
}; };
bool detectedAgeRestriction = false;
for (int i = 0; i < plans.Length; i++) for (int i = 0; i < plans.Length; i++)
{ {
var (name, args) = plans[i]; var (name, args) = plans[i];
@@ -707,11 +781,22 @@ 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))
{ {
if (stdErr.Contains("confirm your age", StringComparison.OrdinalIgnoreCase) ||
stdErr.Contains("Sign in to confirm", StringComparison.OrdinalIgnoreCase))
{
detectedAgeRestriction = true;
}
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)
@@ -726,6 +811,13 @@ namespace MusicDownloader.Class.Downloader
} }
} }
if (detectedAgeRestriction)
{
var (_, cookieDesc) = CookieHelper.GetCookieStatus(outputBaseDir, youtubeFolder);
LogManager.AddWarning($"[年齢制限エラー] 動画「{videoTitle ?? videoId}」はYouTubeの年齢確認が必要です。");
LogManager.AddWarning($"[Cookie設定状況] {cookieDesc}");
}
return false; return false;
} }
@@ -755,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)直下のみに配置します。
@@ -990,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);
}
} }
} }
@@ -1049,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 { }
} }
+5 -4
View File
@@ -27,14 +27,15 @@
<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共通対応) -->
<Exec Command="robocopy &quot;$(PublishDir).&quot; &quot;C:\docker\MusicDownloader\app&quot; /MIR /NP /NFL /NDL" IgnoreExitCode="true" /> <Exec Command="robocopy &quot;$(PublishDir).&quot; &quot;C:\docker\MusicDownloader\app&quot; /MIR /NP /NFL /NDL" IgnoreExitCode="true" />
<!-- Dockerfile と compose.yaml を最新同期 --> <!-- Dockerfile と compose.yaml と run_config.json を最新同期 -->
<Exec Command="powershell -Command &quot;Copy-Item -Path '$(SolutionDir)Dockerfile', '$(SolutionDir)compose.yaml' -Destination 'C:\docker\MusicDownloader\' -Force&quot;" /> <Exec Command="powershell -Command &quot;Copy-Item -Path '$(SolutionDir)Dockerfile', '$(SolutionDir)compose.yaml', '$(SolutionDir)run_config.json' -Destination 'C:\docker\MusicDownloader\' -Force&quot;" />
<!-- ローカルDocker Desktopでコンテナをビルド・起動(常駐) --> <!-- ローカルDocker Desktopでコンテナをビルド・起動(常駐) -->
<Exec Command="docker compose -f C:\docker\MusicDownloader\compose.yaml up -d --build" /> <Exec Command="docker compose -f C:\docker\MusicDownloader\compose.yaml up -d --build" />
<Message Text="=== [Local Docker Deploy] All processes completed successfully! ===" Importance="high" /> <Message Text="=== [Local Docker Deploy] All processes completed successfully! ===" Importance="high" />
+79 -5
View File
@@ -100,10 +100,22 @@ LogManager.AddLog($"==================================================");
// 出力先およびログ保存先ディレクトリの決定 // 出力先およびログ保存先ディレクトリの決定
var outputDir = CmnDefine.GetOutputDir(); var outputDir = CmnDefine.GetOutputDir();
var logDir = CmnDefine.GetLogDir(); var logDir = CmnDefine.GetLogDir();
var youtubeDir = Path.Combine(outputDir, CmnDefine.YoutubeFolderName);
LogManager.AddLog($"ベース出力先: {outputDir}"); LogManager.AddLog($"ベース出力先: {outputDir}");
LogManager.AddLog($"楽曲集約フォルダ: {Path.Combine(outputDir, CmnDefine.YoutubeFolderName)}"); LogManager.AddLog($"楽曲集約フォルダ: {youtubeDir}");
LogManager.AddLog($"ログ保存先: {logDir}"); 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)の準備確認 // 依存ツール(yt-dlp)の準備確認
using var initClient = httpClientFactory.CreateClient("webClient"); using var initClient = httpClientFactory.CreateClient("webClient");
var ytDlpPath = await DependencyManager.EnsureYtDlpAsync(initClient); var ytDlpPath = await DependencyManager.EnsureYtDlpAsync(initClient);
@@ -159,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}");
} }
@@ -182,10 +194,57 @@ int loopCount = 0;
bool isFirstRun = true; bool isFirstRun = true;
var playlistsFile = Path.Combine(outputDir, "playlists.txt"); var playlistsFile = Path.Combine(outputDir, "playlists.txt");
// 【設定読み込み】起動時・Docker公開時の初回処理モード(最初から / 続きから)
var runConfig = RunConfig.Load(outputDir);
bool isResumeOnStartup = runConfig.IsResumeMode();
if (!string.IsNullOrEmpty(runConfig.LoadedPath))
{
LogManager.AddLog($"[起動設定検出] 設定ファイル: {runConfig.LoadedPath}");
}
LogManager.AddLog($"[起動時モード判定] 初回処理: {(isResumeOnStartup ? "「続きから行う (差分ダウンロード)」" : "「最初から行う (全曲再ダウンロード)」")}");
while (true) while (true)
{ {
loopCount++; loopCount++;
bool isIncremental = !isFirstRun;
// 各サイクルの開始前に出力先ストレージの接続健全性を確認(書き込み疎通テスト)
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)
// 2回目以降 (loopCount > 1): 常に差分ダウンロード (true)
bool isIncremental = isFirstRun ? isResumeOnStartup : true;
var targetPlaylists = ResolveTargetPlaylists(outputDir); var targetPlaylists = ResolveTargetPlaylists(outputDir);
var processedInCycle = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var processedInCycle = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
@@ -193,13 +252,20 @@ while (true)
LogManager.AddLog($"[第 {loopCount} 回実行] 対象プレイリスト総数: {targetPlaylists.Count} 件のチェックを開始します (モード: {(isIncremental ? "差分ダウンロード" : "全曲ダウンロード")})"); LogManager.AddLog($"[第 {loopCount} 回実行] 対象プレイリスト総数: {targetPlaylists.Count} 件のチェックを開始します (モード: {(isIncremental ? "差分ダウンロード" : "全曲ダウンロード")})");
LogManager.AddLog($"================================================================================"); LogManager.AddLog($"================================================================================");
// 初回起動時(コンテナ再起動含む)はダウンロード完了状態(archive.txt)をリセットして全曲ダウンロード // 初回起動時の初期化処理
if (isFirstRun) if (isFirstRun)
{ {
LogManager.AddLog($"[起動時初期化] 起動・再起動時のため、ダウンロード完了履歴 (archive.txt) をリセットして全曲ダウンロードを行います。"); if (isResumeOnStartup)
{
LogManager.AddSuccess($"[起動時モード: 続きから行う] 設定に基づき、既存のダウンロード履歴 (archive.txt) を保持して続きから差分取得します。");
}
else
{
LogManager.AddLog($"[起動時モード: 最初から行う] 設定に基づき、ダウンロード完了履歴 (archive.txt) をリセットして全曲ダウンロードを行います。");
var youtubeFolder = Path.Combine(outputDir, CmnDefine.YoutubeFolderName); var youtubeFolder = Path.Combine(outputDir, CmnDefine.YoutubeFolderName);
downloader.ResetDownloadArchive(youtubeFolder); downloader.ResetDownloadArchive(youtubeFolder);
} }
}
for (int p = 0; p < targetPlaylists.Count; p++) for (int p = 0; p < targetPlaylists.Count; p++)
{ {
@@ -217,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 "[エラー] コンテナ確認中に例外が発生しました: $_"
}
+7
View File
@@ -20,11 +20,18 @@ services:
- CHECK_INTERVAL_HOURS=2 - CHECK_INTERVAL_HOURS=2
# プレイリストURLをコンテナ側から上書きしたい場合に指定 # プレイリストURLをコンテナ側から上書きしたい場合に指定
# - PLAYLIST_URL=https://www.youtube.com/playlist?list=... # - PLAYLIST_URL=https://www.youtube.com/playlist?list=...
# 年齢制限動画取得用のCookieファイルパスを明示指定する場合(未指定でも /music/cookies.txt 等から自動検出)
# - YOUTUBE_COOKIES_PATH=/music/cookies.txt
volumes: volumes:
# YouTubeからダウンロードした音楽ファイルをホストの G:\マイドライブ\MyMusic に出力(ジャンクション C:\MyMusic 経由) # YouTubeからダウンロードした音楽ファイルをホストの G:\マイドライブ\MyMusic に出力(ジャンクション C:\MyMusic 経由)
# ※ 年齢制限動画を取得する場合、ホスト側の C:\MyMusic\cookies.txt に配置すればコンテナ内 (/music/cookies.txt) で自動検知されます
- C:\MyMusic:/music - C:\MyMusic:/music
# ホストのログディレクトリ C:\feeds\Log へ出力するためのマウント # ホストのログディレクトリ C:\feeds\Log へ出力するためのマウント
- C:\feeds:/feeds - C:\feeds:/feeds
# 初回起動時の動作設定(最初から行う: from_scratch / 続きから行う: resume)
- 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
+5
View File
@@ -0,0 +1,5 @@
{
"// 説明": "Docker公開時・起動時の初回処理モード設定(最初から行う: 'from_scratch' / 続きから行う: 'resume')",
"// 選択肢": "'resume' (続きから / 差分ダウンロード - 既存のarchive.txtを保持) または 'from_scratch' (最初から / 全曲再ダウンロード - 起動時にarchive.txtをリセット)",
"initial_mode": "resume"
}
+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."