共通Youtubeフォルダ集約・重複防止・Powerampプレイリスト生成・安全ステージング・ログファイル出力対応
- 全曲を共通フォルダ「Youtube」へ集約し、downloaded_tracks.json による重複防止と再利用に対応 - 同名別動画(Another vocal等)の上書き衝突防止(連番付与) - Google Drive同期競合を避けるローカル作業フォルダでの完結・一括転送 - Android Poweramp対応プレイリスト(.m3u8)の自動生成 - 429/403エラーに対する多段階フォールバックと失敗時再試行 - Channelを用いた非同期ファイルログ出力(C:\feeds\Log\)の実装 - compose.yaml にログボリュームマウント追加 - .gitignore の整理
This commit is contained in:
1 parent
b57b812bbe
commit
93403e631b
8 files changed
+695
-132
No files matched your search
+4
-3
@@ -1,7 +1,8 @@
|
||||
################################################################################
|
||||
################################################################################
|
||||
# この .gitignore ファイルは Microsoft(R) Visual Studio によって自動的に作成されました。
|
||||
################################################################################
|
||||
|
||||
/.vs
|
||||
/rss-generator/bin
|
||||
/rss-generator/obj
|
||||
/app/
|
||||
[Bb]in/
|
||||
[Oo]bj/
|
||||
@@ -28,6 +28,11 @@ namespace MusicDownloader.Class
|
||||
/// </summary>
|
||||
public const string UserAgent = "MusicDownloader/1.0 (https://github.com/myuser/MusicDownloader)";
|
||||
|
||||
/// <summary>
|
||||
/// 全曲およびプレイリストを格納する共通フォルダ名
|
||||
/// </summary>
|
||||
public const string YoutubeFolderName = "Youtube";
|
||||
|
||||
/// <summary>
|
||||
/// 出力先ディレクトリパスの取得(環境変数 MUSIC_OUTPUT_DIR または実行環境に応じて自動切替)
|
||||
/// </summary>
|
||||
@@ -54,5 +59,77 @@ namespace MusicDownloader.Class
|
||||
// G:\マイドライブ\MyMusic が見つからない場合のフォールバック(MusicDownloader\output)
|
||||
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ログ出力先ディレクトリの取得(環境変数 LOG_DIR または C:\feeds\Log / コンテナ内 /feeds/Log)
|
||||
/// </summary>
|
||||
public static string GetLogDir()
|
||||
{
|
||||
var envPath = Environment.GetEnvironmentVariable("LOG_DIR");
|
||||
if (!string.IsNullOrWhiteSpace(envPath))
|
||||
{
|
||||
return envPath;
|
||||
}
|
||||
|
||||
// Windowsホスト環境の場合: C:\feeds\Log
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
const string winPath = @"C:\feeds\Log";
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(winPath))
|
||||
{
|
||||
Directory.CreateDirectory(winPath);
|
||||
}
|
||||
return winPath;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 万が一権限等で作成できない場合はローカルにフォールバック
|
||||
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");
|
||||
}
|
||||
}
|
||||
|
||||
// Linuxコンテナ環境の場合: /feeds/Log
|
||||
const string containerPath = "/feeds/Log";
|
||||
try
|
||||
{
|
||||
if (Directory.Exists("/feeds"))
|
||||
{
|
||||
if (!Directory.Exists(containerPath))
|
||||
{
|
||||
Directory.CreateDirectory(containerPath);
|
||||
}
|
||||
return containerPath;
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
// フォールバック
|
||||
return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Log");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ダウンロードおよびタグ付け処理を行うローカル作業ディレクトリの取得
|
||||
/// Google Drive等の同期先への書き込み競合を避けるため、ローカルで完結させてから転送する
|
||||
/// </summary>
|
||||
public static string GetStagingDir()
|
||||
{
|
||||
string stagingDir;
|
||||
if (OperatingSystem.IsWindows())
|
||||
{
|
||||
stagingDir = Path.Combine(Path.GetTempPath(), "MusicDownloader_Work");
|
||||
}
|
||||
else
|
||||
{
|
||||
stagingDir = "/tmp/musicdownloader_work";
|
||||
}
|
||||
|
||||
if (!Directory.Exists(stagingDir))
|
||||
{
|
||||
Directory.CreateDirectory(stagingDir);
|
||||
}
|
||||
return stagingDir;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using System.Threading.Tasks;
|
||||
@@ -90,7 +91,31 @@ namespace MusicDownloader.Class.Downloader
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 高音質変換・外部検索メタデータ付与・歌詞連携を行うダウンロード処理クラス
|
||||
/// ダウンロード済みトラック情報モデル(重複防止およびプレイリスト生成用)
|
||||
/// </summary>
|
||||
public class DownloadedTrackInfo
|
||||
{
|
||||
[JsonPropertyName("video_id")]
|
||||
public string VideoId { get; set; } = "";
|
||||
|
||||
[JsonPropertyName("file_name")]
|
||||
public string FileName { get; set; } = "";
|
||||
|
||||
[JsonPropertyName("title")]
|
||||
public string Title { get; set; } = "";
|
||||
|
||||
[JsonPropertyName("artist")]
|
||||
public string Artist { get; set; } = "";
|
||||
|
||||
[JsonPropertyName("duration")]
|
||||
public double? Duration { get; set; }
|
||||
|
||||
[JsonPropertyName("updated_at")]
|
||||
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 高音質変換・外部検索メタデータ付与・歌詞連携・重複排除を行うダウンロード処理クラス
|
||||
/// </summary>
|
||||
public class YoutubeDownloader
|
||||
{
|
||||
@@ -98,6 +123,12 @@ namespace MusicDownloader.Class.Downloader
|
||||
private readonly LyricsManager _lyricsManager;
|
||||
private readonly MusicMetadataClient _metadataClient;
|
||||
|
||||
private static readonly JsonSerializerOptions _jsonOptions = new()
|
||||
{
|
||||
WriteIndented = true,
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
public YoutubeDownloader(string ytDlpPath, LyricsManager lyricsManager, MusicMetadataClient metadataClient)
|
||||
{
|
||||
_ytDlpPath = ytDlpPath;
|
||||
@@ -137,7 +168,8 @@ namespace MusicDownloader.Class.Downloader
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// プレイリスト全体のダウンロードおよびメタデータ・歌詞付与を実行する
|
||||
/// プレイリスト全体のダウンロードおよびメタデータ・歌詞付与・プレイリスト生成を実行する
|
||||
/// 全ての曲は共通フォルダ「Youtube」に集約され、重複動画は再利用されます。
|
||||
/// </summary>
|
||||
public async Task ProcessPlaylistAsync(string playlistUrl, string outputBaseDir)
|
||||
{
|
||||
@@ -145,10 +177,18 @@ namespace MusicDownloader.Class.Downloader
|
||||
var rawTitle = playlistInfo?.Title ?? "YouTube_Playlist";
|
||||
var sanitizedPlaylistName = CmnUtil.SanitizeFileName(rawTitle);
|
||||
|
||||
var targetFolder = Path.Combine(outputBaseDir, sanitizedPlaylistName);
|
||||
Directory.CreateDirectory(targetFolder);
|
||||
// ① 全ての曲を格納する共通フォルダ「Youtube」の準備
|
||||
var youtubeFolder = Path.Combine(outputBaseDir, CmnDefine.YoutubeFolderName);
|
||||
Directory.CreateDirectory(youtubeFolder);
|
||||
|
||||
LogManager.AddLog($"保存先ディレクトリ: {targetFolder}");
|
||||
// ④ Google Drive同期前の安全なローカル作業領域
|
||||
var stagingDir = CmnDefine.GetStagingDir();
|
||||
|
||||
LogManager.AddLog($"保存先ディレクトリ: {youtubeFolder}");
|
||||
LogManager.AddLog($"ローカル作業ディレクトリ: {stagingDir}");
|
||||
|
||||
// ③ 重複排除用マップ(downloaded_tracks.json)の読み込み
|
||||
var downloadedTracks = await LoadDownloadedTracksAsync(youtubeFolder);
|
||||
|
||||
// 有効な動画エントリのみを抽出(削除済みや非公開動画は除外)
|
||||
var rawEntries = playlistInfo?.Entries ?? new List<YtPlaylistEntry>();
|
||||
@@ -159,6 +199,9 @@ namespace MusicDownloader.Class.Downloader
|
||||
e.Title != "[Deleted video]")
|
||||
.ToList();
|
||||
|
||||
// プレイリスト登録用の楽曲リスト
|
||||
var currentPlaylistTracks = new List<DownloadedTrackInfo>();
|
||||
|
||||
if (validEntries.Count == 0)
|
||||
{
|
||||
if (rawEntries.Count > 0)
|
||||
@@ -169,118 +212,119 @@ namespace MusicDownloader.Class.Downloader
|
||||
|
||||
// 単一動画URLまたはエントリがフラット取得できなかった場合、直接ダウンロード
|
||||
LogManager.AddLog($"プレイリストのエントリが見つからないか単一動画URLです。直接ダウンロードを試行します。");
|
||||
await DownloadAndProcessSingleAsync(playlistUrl, 1, 1, targetFolder, sanitizedPlaylistName, null);
|
||||
return;
|
||||
var singleTrack = await DownloadAndProcessSingleAsync(playlistUrl, 1, 1, stagingDir, youtubeFolder, sanitizedPlaylistName, null, downloadedTracks);
|
||||
if (singleTrack != null)
|
||||
{
|
||||
currentPlaylistTracks.Add(singleTrack);
|
||||
if (!string.IsNullOrEmpty(singleTrack.VideoId))
|
||||
{
|
||||
downloadedTracks[singleTrack.VideoId] = singleTrack;
|
||||
await SaveDownloadedTracksAsync(youtubeFolder, downloadedTracks);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var totalCount = (uint)validEntries.Count;
|
||||
LogManager.AddLog($"プレイリスト「{sanitizedPlaylistName}」: 有効な全 {totalCount} 曲の処理を開始します。");
|
||||
|
||||
for (int i = 0; i < validEntries.Count; i++)
|
||||
else
|
||||
{
|
||||
var entry = validEntries[i];
|
||||
var videoIndex = (uint)(i + 1);
|
||||
var videoUrl = !string.IsNullOrEmpty(entry.Url) && entry.Url.StartsWith("http")
|
||||
? entry.Url
|
||||
: $"https://www.youtube.com/watch?v={entry.Id}";
|
||||
var totalCount = (uint)validEntries.Count;
|
||||
LogManager.AddLog($"プレイリスト「{sanitizedPlaylistName}」: 有効な全 {totalCount} 曲の処理を開始します。");
|
||||
|
||||
LogManager.AddLog($"--------------------------------------------------------------------------------");
|
||||
LogManager.AddLog($"[{videoIndex}/{totalCount}] 処理開始: {entry.Title ?? entry.Id}");
|
||||
for (int i = 0; i < validEntries.Count; i++)
|
||||
{
|
||||
var entry = validEntries[i];
|
||||
var videoIndex = (uint)(i + 1);
|
||||
var videoId = entry.Id ?? "";
|
||||
var videoUrl = !string.IsNullOrEmpty(entry.Url) && entry.Url.StartsWith("http")
|
||||
? entry.Url
|
||||
: $"https://www.youtube.com/watch?v={videoId}";
|
||||
|
||||
await DownloadAndProcessSingleAsync(videoUrl, videoIndex, totalCount, targetFolder, sanitizedPlaylistName, entry);
|
||||
LogManager.AddLog($"--------------------------------------------------------------------------------");
|
||||
LogManager.AddLog($"[{videoIndex}/{totalCount}] 処理開始: {entry.Title ?? videoId}");
|
||||
|
||||
// サーバー負荷軽減および省メモリ・安定化のためのクールダウン待機(3秒)
|
||||
await Task.Delay(3000);
|
||||
// ③ 別々のプレイリストでも同じ動画が参照されている場合は重複を防止(既存ファイルの再利用)
|
||||
if (!string.IsNullOrEmpty(videoId) &&
|
||||
downloadedTracks.TryGetValue(videoId, out var existingTrack) &&
|
||||
File.Exists(Path.Combine(youtubeFolder, existingTrack.FileName)))
|
||||
{
|
||||
LogManager.AddSuccess($"[重複検出・スキップ] 既に保存済みの曲を再利用します: {existingTrack.FileName}");
|
||||
currentPlaylistTracks.Add(existingTrack);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 1曲ごとに不要メモリを速やかに解放(省メモリ化)
|
||||
GC.Collect(1, GCCollectionMode.Optimized, false);
|
||||
// 1曲の処理(ローカル作業フォルダでダウンロード・タグ付け・検証を完結させ、完成後にYoutubeフォルダへ転送)
|
||||
var trackInfo = await DownloadAndProcessSingleAsync(
|
||||
videoUrl, videoIndex, totalCount, stagingDir, youtubeFolder, sanitizedPlaylistName, entry, downloadedTracks);
|
||||
|
||||
if (trackInfo != null)
|
||||
{
|
||||
currentPlaylistTracks.Add(trackInfo);
|
||||
if (!string.IsNullOrEmpty(trackInfo.VideoId))
|
||||
{
|
||||
downloadedTracks[trackInfo.VideoId] = trackInfo;
|
||||
await SaveDownloadedTracksAsync(youtubeFolder, downloadedTracks);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
LogManager.AddWarning($"[次回リトライ予定] ダウンロードが完了しなかったため、次回の定期チェックループ時に再試行します: {entry.Title ?? videoId}");
|
||||
}
|
||||
|
||||
// サーバー負荷軽減および省メモリ・安定化のためのクールダウン待機(3秒)
|
||||
await Task.Delay(3000);
|
||||
|
||||
// 1曲ごとに不要メモリを速やかに解放(省メモリ化)
|
||||
GC.Collect(1, GCCollectionMode.Optimized, false);
|
||||
}
|
||||
}
|
||||
|
||||
// ② AndroidのPowerampで読み取れるプレイリストファイル(.m3u8)を保存
|
||||
await GenerateM3u8PlaylistAsync(sanitizedPlaylistName, currentPlaylistTracks, youtubeFolder, outputBaseDir);
|
||||
|
||||
LogManager.AddSuccess($"================================================================================");
|
||||
LogManager.AddSuccess($"プレイリスト「{sanitizedPlaylistName}」の全ダウンロードおよび処理が完了しました!");
|
||||
LogManager.AddSuccess($"保存先: {targetFolder}");
|
||||
LogManager.AddSuccess($"プレイリスト「{sanitizedPlaylistName}」の処理が完了しました! (登録曲数: {currentPlaylistTracks.Count})");
|
||||
LogManager.AddSuccess($"保存先: {youtubeFolder}");
|
||||
LogManager.AddSuccess($"================================================================================");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 1曲のダウンロード・高音質Opus変換・外部楽曲メタデータ解決・タグ付与を実行する
|
||||
/// ④ Google Driveへのアップロード競合を防ぐため、ローカル作業ディレクトリ(stagingDir)で
|
||||
/// すべての処理・ファイル生成を完了させてから、完成ファイルをYoutubeフォルダへコピーします。
|
||||
/// </summary>
|
||||
private async Task DownloadAndProcessSingleAsync(
|
||||
private async Task<DownloadedTrackInfo?> DownloadAndProcessSingleAsync(
|
||||
string videoUrl,
|
||||
uint index,
|
||||
uint totalCount,
|
||||
string targetFolder,
|
||||
string stagingDir,
|
||||
string youtubeFolder,
|
||||
string playlistName,
|
||||
YtPlaylistEntry? entryInfo)
|
||||
YtPlaylistEntry? entryInfo,
|
||||
Dictionary<string, DownloadedTrackInfo> downloadedTracks)
|
||||
{
|
||||
var archiveFile = Path.Combine(targetFolder, "archive.txt");
|
||||
var filePrefix = $"{index:D2} - ";
|
||||
var videoId = entryInfo?.Id ?? "";
|
||||
var archiveFile = Path.Combine(youtubeFolder, "archive.txt");
|
||||
|
||||
// 出力ファイル名テンプレート
|
||||
var outputTemplate = Path.Combine(targetFolder, $"{filePrefix}%(title)s.%(ext)s");
|
||||
|
||||
// 高音質変換およびブツブツ防止のためのyt-dlp・ffmpeg引数
|
||||
// - 最高音質音声ストリームの選択 (-f bestaudio/best)
|
||||
// - フラグメント並行数1でパケット抜け・順序乱れ・メモリ枯渇を防止
|
||||
// - ffmpeg aresample=async=1000 によりタイムスタンプのドリフト・不連続を補正しプチプチ音を根絶
|
||||
var arguments = new List<string>
|
||||
// ② 多段階フォールバックによるダウンロード実行(429字幕エラーや403Forbiddenエラーを自動回避)
|
||||
var isDownloadSuccess = await DownloadWithFallbackAsync(videoUrl, videoId, stagingDir, archiveFile);
|
||||
if (!isDownloadSuccess)
|
||||
{
|
||||
"-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",
|
||||
"--write-subs",
|
||||
"--write-auto-subs",
|
||||
"--sub-lang", "ja,en",
|
||||
"--sub-format", "vtt",
|
||||
"--no-abort-on-error",
|
||||
"--retries", "10",
|
||||
"--fragment-retries", "10",
|
||||
"--retry-sleep", "3",
|
||||
"--download-archive", archiveFile,
|
||||
"-o", outputTemplate,
|
||||
"--no-warnings",
|
||||
videoUrl
|
||||
};
|
||||
|
||||
LogManager.AddLog($"ダウンロード&高音質変換実行中 (yt-dlp)...");
|
||||
try
|
||||
{
|
||||
var cmdResult = await Cli.Wrap(_ytDlpPath)
|
||||
.WithArguments(arguments)
|
||||
.WithValidation(CommandResultValidation.None)
|
||||
.ExecuteBufferedAsync();
|
||||
|
||||
if (cmdResult.ExitCode != 0)
|
||||
{
|
||||
LogManager.AddWarning($"yt-dlp 終了コード: {cmdResult.ExitCode}");
|
||||
if (!string.IsNullOrWhiteSpace(cmdResult.StandardError))
|
||||
{
|
||||
LogManager.AddWarning($"詳細: {cmdResult.StandardError}");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddError($"ダウンロード処理中にエラーが発生しました: {ex.Message}", ex);
|
||||
return;
|
||||
LogManager.AddWarning($"[{index}/{totalCount}] すべてのフォールバックを試みましたがダウンロードできませんでした。");
|
||||
// 次回ループ時にyt-dlpがスキップしないよう、archive.txtから動画IDを除去
|
||||
RemoveFromArchiveFile(archiveFile, videoId);
|
||||
CleanupDirectory(stagingDir);
|
||||
return null;
|
||||
}
|
||||
|
||||
// ダウンロードされた .opus ファイルを特定(当インデックスのもののみ対象)
|
||||
var opusFiles = Directory.GetFiles(targetFolder, $"{filePrefix}*.opus");
|
||||
// ダウンロードされた .opus ファイルを作業フォルダから特定
|
||||
var opusFiles = Directory.GetFiles(stagingDir, "*.opus");
|
||||
if (opusFiles.Length == 0)
|
||||
{
|
||||
LogManager.AddWarning($"[{index}/{totalCount}] 該当インデックスのOpusファイルが見つかりませんでした (アーカイブによりスキップされたか、ダウンロードに失敗しました)。");
|
||||
CleanupTempFiles(targetFolder, filePrefix);
|
||||
return;
|
||||
LogManager.AddWarning($"[{index}/{totalCount}] 作業フォルダ内にOpusファイルが見つかりませんでした。");
|
||||
RemoveFromArchiveFile(archiveFile, videoId);
|
||||
CleanupDirectory(stagingDir);
|
||||
return null;
|
||||
}
|
||||
|
||||
// 該当ファイルを特定
|
||||
// 該当ファイルを特定(最新ファイル)
|
||||
var targetOpus = opusFiles.OrderByDescending(f => File.GetLastWriteTime(f)).First();
|
||||
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(targetOpus);
|
||||
|
||||
@@ -290,8 +334,7 @@ namespace MusicDownloader.Class.Downloader
|
||||
// -------------------------------------------------------------
|
||||
// メタデータ(曲名・アーティスト・アルバム・アルバムアーティスト)の決定
|
||||
// -------------------------------------------------------------
|
||||
var rawTitle = fileNameWithoutExt.StartsWith(filePrefix) ? fileNameWithoutExt.Substring(filePrefix.Length) : fileNameWithoutExt;
|
||||
var baseTitle = !string.IsNullOrWhiteSpace(entryInfo?.Title) ? entryInfo.Title : rawTitle;
|
||||
var baseTitle = !string.IsNullOrWhiteSpace(entryInfo?.Title) ? entryInfo.Title : fileNameWithoutExt;
|
||||
var uploader = !string.IsNullOrWhiteSpace(entryInfo?.Channel) ? entryInfo.Channel : (entryInfo?.Uploader ?? "");
|
||||
|
||||
// 1. タイトル文字列の初期パース
|
||||
@@ -344,7 +387,7 @@ namespace MusicDownloader.Class.Downloader
|
||||
// 高画質カバー画像が存在すればダウンロードして適用
|
||||
if (!string.IsNullOrWhiteSpace(resolvedMeta.ArtworkUrl))
|
||||
{
|
||||
var highResArtPath = Path.Combine(targetFolder, $"{filePrefix}itunes_cover.jpg");
|
||||
var highResArtPath = Path.Combine(stagingDir, "itunes_cover.jpg");
|
||||
var downloadedArt = await _metadataClient.DownloadArtworkAsync(resolvedMeta.ArtworkUrl, highResArtPath);
|
||||
if (downloadedArt != null)
|
||||
{
|
||||
@@ -364,16 +407,16 @@ namespace MusicDownloader.Class.Downloader
|
||||
}
|
||||
else
|
||||
{
|
||||
var prefixJpgs = Directory.GetFiles(targetFolder, $"{filePrefix}*.jpg");
|
||||
if (prefixJpgs.Length > 0)
|
||||
var jpgs = Directory.GetFiles(stagingDir, "*.jpg");
|
||||
if (jpgs.Length > 0)
|
||||
{
|
||||
thumbnailToUse = prefixJpgs[0];
|
||||
thumbnailToUse = jpgs[0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 歌詞処理 (.lrc作成および歌詞テキスト取得)
|
||||
var lyrics = await _lyricsManager.ProcessLyricsAsync(targetOpus, finalTitle, finalArtist, entryInfo?.Duration, targetFolder, filePrefix);
|
||||
// 歌詞処理 (.lrc作成および歌詞テキスト取得) - stagingDir 内に生成
|
||||
var lyrics = await _lyricsManager.ProcessLyricsAsync(targetOpus, finalTitle, finalArtist, entryInfo?.Duration, stagingDir, null);
|
||||
|
||||
// メタデータ (TagLibSharp) の書き込み(正確な曲名・アーティスト・アルバム・アルバムアーティスト)
|
||||
AudioTagManager.ApplyMetadata(
|
||||
@@ -389,21 +432,345 @@ namespace MusicDownloader.Class.Downloader
|
||||
comment: videoUrl,
|
||||
albumArtist: finalAlbumArtist);
|
||||
|
||||
// プレイリスト代表カバー画像として cover.jpg が存在しなければコピー
|
||||
var albumCoverPath = Path.Combine(targetFolder, "cover.jpg");
|
||||
if (!File.Exists(albumCoverPath) && thumbnailToUse != null)
|
||||
// 不要な中間ファイル(.vtt, 一時画像等)のクリーンアップ(.opus と .lrc は保持)
|
||||
CleanupStagingTempFiles(stagingDir);
|
||||
|
||||
// ④ ファイルがすべて用意されてから、Google Drive保存先(Youtubeフォルダ)へ転送
|
||||
var rawFileName = Path.GetFileName(targetOpus);
|
||||
|
||||
// ① 同名別動画(another vocal等)の衝突を検知し、ユニークな保存名(曲名 (2).opus等)を決定
|
||||
var finalFileName = GetUniqueTargetFileName(youtubeFolder, rawFileName, videoId, downloadedTracks);
|
||||
var destOpusPath = Path.Combine(youtubeFolder, finalFileName);
|
||||
|
||||
try
|
||||
{
|
||||
try
|
||||
File.Copy(targetOpus, destOpusPath, overwrite: true);
|
||||
LogManager.AddLog($"ファイルを保存先に配置しました: {finalFileName}");
|
||||
|
||||
// 歌詞ファイル (.lrc) も完成していれば転送(音声ファイル名に合わせた名前にする)
|
||||
var lrcPath = Path.ChangeExtension(targetOpus, ".lrc");
|
||||
if (File.Exists(lrcPath))
|
||||
{
|
||||
File.Copy(thumbnailToUse, albumCoverPath, true);
|
||||
var targetLrcName = Path.ChangeExtension(finalFileName, ".lrc");
|
||||
var destLrcPath = Path.Combine(youtubeFolder, targetLrcName);
|
||||
File.Copy(lrcPath, destLrcPath, overwrite: true);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddError($"保存先へのファイル転送に失敗しました: {ex.Message}", ex);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 作業フォルダ内の完成ファイルを掃除
|
||||
CleanupDirectory(stagingDir);
|
||||
}
|
||||
|
||||
// 一時ファイル(.vtt, 一時画像等)のクリーンアップ
|
||||
CleanupTempFiles(targetFolder, filePrefix);
|
||||
LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {finalFileName}");
|
||||
|
||||
LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {Path.GetFileName(targetOpus)}");
|
||||
return new DownloadedTrackInfo
|
||||
{
|
||||
VideoId = videoId,
|
||||
FileName = finalFileName,
|
||||
Title = finalTitle,
|
||||
Artist = finalArtist,
|
||||
Duration = entryInfo?.Duration,
|
||||
UpdatedAt = DateTime.Now
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ① 同じ動画名(another vocalなど)の別動画が既に存在する場合に上書きを防止し、
|
||||
/// 「曲名 (2).opus」等のユニークなファイル名を決定する
|
||||
/// </summary>
|
||||
private string GetUniqueTargetFileName(
|
||||
string youtubeFolder,
|
||||
string originalFileName,
|
||||
string videoId,
|
||||
Dictionary<string, DownloadedTrackInfo> downloadedTracks)
|
||||
{
|
||||
var baseName = Path.GetFileNameWithoutExtension(originalFileName);
|
||||
var ext = Path.GetExtension(originalFileName);
|
||||
var candidateFileName = originalFileName;
|
||||
|
||||
int counter = 1;
|
||||
while (true)
|
||||
{
|
||||
var checkPath = Path.Combine(youtubeFolder, candidateFileName);
|
||||
if (!File.Exists(checkPath))
|
||||
{
|
||||
// 空いているファイル名が見つかった
|
||||
break;
|
||||
}
|
||||
|
||||
// 既存ファイルが存在する場合: それが同一動画IDのものであれば上書き更新として許可
|
||||
if (!string.IsNullOrEmpty(videoId) &&
|
||||
downloadedTracks.TryGetValue(videoId, out var existing) &&
|
||||
string.Equals(existing.FileName, candidateFileName, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
// 別の動画IDがすでにこのファイル名を使っている、あるいはファイルが存在する場合
|
||||
// 衝突を回避するため連番サフィックスを付与: "曲名 (2).opus"
|
||||
counter++;
|
||||
candidateFileName = $"{baseName} ({counter}){ext}";
|
||||
}
|
||||
|
||||
if (candidateFileName != originalFileName)
|
||||
{
|
||||
LogManager.AddLog($"[同名別動画を検出] 重複回避のためファイル名を「{candidateFileName}」に変更して保存します");
|
||||
}
|
||||
|
||||
return candidateFileName;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ② 多段階フォールバックにより動画の音声を確実にダウンロードする
|
||||
/// - 429 Too Many Requests: 字幕ダウンロードを無効化して音声のみ取得
|
||||
/// - 403 Forbidden: YouTube AndroidクライアントAPIやiOSクライアントAPIへの切り替え
|
||||
/// </summary>
|
||||
private async Task<bool> DownloadWithFallbackAsync(
|
||||
string videoUrl,
|
||||
string videoId,
|
||||
string stagingDir,
|
||||
string archiveFile)
|
||||
{
|
||||
var outputTemplate = Path.Combine(stagingDir, "%(title)s.%(ext)s");
|
||||
|
||||
// 基本引数の生成
|
||||
List<string> GetBaseArgs() => new List<string>
|
||||
{
|
||||
"-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"
|
||||
};
|
||||
|
||||
// 試行1: 標準(429を避けるため英語en字幕は除外してja字幕のみ)
|
||||
var plan1 = GetBaseArgs();
|
||||
plan1.AddRange(new[] { "--write-subs", "--write-auto-subs", "--sub-lang", "ja", "--sub-format", "vtt", videoUrl });
|
||||
|
||||
// 試行2: 字幕ダウンロードオフ(429 Too Many Requests や字幕エラー対策)
|
||||
var plan2 = GetBaseArgs();
|
||||
plan2.Add(videoUrl);
|
||||
|
||||
// 試行3: AndroidクライアントAPI(403 Forbidden ストリーム拒否対策)
|
||||
var plan3 = GetBaseArgs();
|
||||
plan3.AddRange(new[] { "--extractor-args", "youtube:player_client=android,web", videoUrl });
|
||||
|
||||
// 試行4: iOSクライアントAPI & キャッシュ無効化(最終フォールバック)
|
||||
var plan4 = GetBaseArgs();
|
||||
plan4.AddRange(new[] { "--extractor-args", "youtube:player_client=ios,web", "--no-cache-dir", videoUrl });
|
||||
|
||||
var plans = new (string Name, List<string> Args)[]
|
||||
{
|
||||
("通常ダウンロード (日本語字幕あり)", plan1),
|
||||
("フォールバック1 (字幕取得オフ / 429対策)", plan2),
|
||||
("フォールバック2 (YouTube Androidクライアント / 403対策)", plan3),
|
||||
("フォールバック3 (YouTube iOSクライアント & キャッシュ無効化)", plan4)
|
||||
};
|
||||
|
||||
for (int i = 0; i < plans.Length; i++)
|
||||
{
|
||||
var (name, args) = plans[i];
|
||||
if (i > 0)
|
||||
{
|
||||
LogManager.AddWarning($"[{name}] を試行します...");
|
||||
CleanupDirectory(stagingDir);
|
||||
await Task.Delay(2000);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogManager.AddLog($"ダウンロード&高音質変換実行中 (yt-dlp)...");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var cmdResult = await Cli.Wrap(_ytDlpPath)
|
||||
.WithArguments(args)
|
||||
.WithValidation(CommandResultValidation.None)
|
||||
.ExecuteBufferedAsync();
|
||||
|
||||
var opusFiles = Directory.GetFiles(stagingDir, "*.opus");
|
||||
if (cmdResult.ExitCode == 0 && opusFiles.Length > 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var stdErr = cmdResult.StandardError ?? "";
|
||||
LogManager.AddWarning($"[{name}] 終了コード: {cmdResult.ExitCode}");
|
||||
if (!string.IsNullOrWhiteSpace(stdErr))
|
||||
{
|
||||
LogManager.AddWarning($"詳細: {stdErr.Trim()}");
|
||||
}
|
||||
|
||||
// エラー終了コードでもOpusファイル自体が生成完了していれば成功とみなす
|
||||
if (opusFiles.Length > 0)
|
||||
{
|
||||
LogManager.AddLog($"音声ファイル自体の生成を確認したため処理を継続します。");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddWarning($"[{name}] 例外発生: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ダウンロード失敗時に archive.txt から動画IDを除去し、次回の定期チェックループ時に確実に再試行できるようにする
|
||||
/// </summary>
|
||||
private void RemoveFromArchiveFile(string archiveFile, string videoId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(videoId) || !File.Exists(archiveFile))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var lines = File.ReadAllLines(archiveFile);
|
||||
var filtered = lines.Where(line => !line.Contains(videoId)).ToList();
|
||||
if (filtered.Count != lines.Length)
|
||||
{
|
||||
File.WriteAllLines(archiveFile, filtered, Encoding.UTF8);
|
||||
LogManager.AddLog($"archive.txt から動画ID「{videoId}」を除去しました (次回ループで再試行)");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddWarning($"archive.txt の更新中に例外: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ② AndroidのPowerampで読み取れるプレイリストファイル(.m3u8)を保存
|
||||
/// 「曲が保存されているフォルダと同じ階層(Youtube/)」および親フォルダ直下に保存します。
|
||||
/// </summary>
|
||||
private async Task GenerateM3u8PlaylistAsync(
|
||||
string playlistName,
|
||||
List<DownloadedTrackInfo> tracks,
|
||||
string youtubeFolder,
|
||||
string outputBaseDir)
|
||||
{
|
||||
if (tracks.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var sanitizedName = CmnUtil.SanitizeFileName(playlistName);
|
||||
var sbSameDir = new StringBuilder();
|
||||
var sbParentDir = new StringBuilder();
|
||||
|
||||
sbSameDir.AppendLine("#EXTM3U");
|
||||
sbParentDir.AppendLine("#EXTM3U");
|
||||
|
||||
foreach (var track in tracks)
|
||||
{
|
||||
var durationSec = track.Duration.HasValue && track.Duration.Value > 0
|
||||
? (long)Math.Round(track.Duration.Value)
|
||||
: -1;
|
||||
var displayTitle = !string.IsNullOrWhiteSpace(track.Artist) && !string.IsNullOrWhiteSpace(track.Title)
|
||||
? $"{track.Artist} - {track.Title}"
|
||||
: track.Title;
|
||||
|
||||
// 1. 曲ファイルと同じフォルダ(Youtube/)用:ファイル名単体(相対パス)
|
||||
sbSameDir.AppendLine($"#EXTINF:{durationSec},{displayTitle}");
|
||||
sbSameDir.AppendLine(track.FileName);
|
||||
|
||||
// 2. 親フォルダ(outputBaseDir)用:Youtube/ファイル名
|
||||
sbParentDir.AppendLine($"#EXTINF:{durationSec},{displayTitle}");
|
||||
sbParentDir.AppendLine($"{CmnDefine.YoutubeFolderName}/{track.FileName}");
|
||||
}
|
||||
|
||||
// Poweramp対応: UTF-8 (BOMなし)
|
||||
var utf8WithoutBom = new UTF8Encoding(false);
|
||||
|
||||
try
|
||||
{
|
||||
// 1. 曲が保存されているフォルダと同じ階層(Youtube/{プレイリスト名}.m3u8)
|
||||
var m3u8SameDir = Path.Combine(youtubeFolder, $"{sanitizedName}.m3u8");
|
||||
await File.WriteAllTextAsync(m3u8SameDir, sbSameDir.ToString(), utf8WithoutBom);
|
||||
LogManager.AddSuccess($"Poweramp用プレイリストファイルを保存しました: {m3u8SameDir}");
|
||||
|
||||
// 2. outputBaseDir 直下(親階層)にも配置してスキャン漏れを完全防止
|
||||
var m3u8ParentDir = Path.Combine(outputBaseDir, $"{sanitizedName}.m3u8");
|
||||
await File.WriteAllTextAsync(m3u8ParentDir, sbParentDir.ToString(), utf8WithoutBom);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddError($"プレイリストファイルの保存に失敗しました: {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ダウンロード済みトラック情報の読み込み
|
||||
/// </summary>
|
||||
private async Task<Dictionary<string, DownloadedTrackInfo>> LoadDownloadedTracksAsync(string youtubeFolder)
|
||||
{
|
||||
var dbPath = Path.Combine(youtubeFolder, "downloaded_tracks.json");
|
||||
var dict = new Dictionary<string, DownloadedTrackInfo>(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
if (!File.Exists(dbPath))
|
||||
{
|
||||
return dict;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = await File.ReadAllTextAsync(dbPath);
|
||||
var list = JsonSerializer.Deserialize<List<DownloadedTrackInfo>>(json, _jsonOptions);
|
||||
if (list != null)
|
||||
{
|
||||
foreach (var item in list)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(item.VideoId))
|
||||
{
|
||||
dict[item.VideoId] = item;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddWarning($"downloaded_tracks.json の読み込みに失敗しました: {ex.Message}");
|
||||
}
|
||||
|
||||
return dict;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ダウンロード済みトラック情報の保存
|
||||
/// </summary>
|
||||
private async Task SaveDownloadedTracksAsync(string youtubeFolder, Dictionary<string, DownloadedTrackInfo> dict)
|
||||
{
|
||||
try
|
||||
{
|
||||
var dbPath = Path.Combine(youtubeFolder, "downloaded_tracks.json");
|
||||
var list = dict.Values.ToList();
|
||||
var json = JsonSerializer.Serialize(list, _jsonOptions);
|
||||
await File.WriteAllTextAsync(dbPath, json, Encoding.UTF8);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
LogManager.AddWarning($"downloaded_tracks.json の保存に失敗しました: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -434,18 +801,35 @@ namespace MusicDownloader.Class.Downloader
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 中間一時ファイル(.vtt, .part, 一時画像)を削除
|
||||
/// 作業用ディレクトリ内のすべてのファイルをクリア
|
||||
/// </summary>
|
||||
private void CleanupTempFiles(string folder, string? prefix = null)
|
||||
private void CleanupDirectory(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
var searchPattern = !string.IsNullOrEmpty(prefix) ? $"{prefix}*" : "*";
|
||||
var files = Directory.GetFiles(folder, searchPattern);
|
||||
if (!Directory.Exists(folder)) return;
|
||||
var files = Directory.GetFiles(folder);
|
||||
foreach (var file in files)
|
||||
{
|
||||
try { File.Delete(file); } catch { }
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 作業ディレクトリから中間一時ファイル(.vtt, .part, 一時画像等)を削除(.opus と .lrc は保持)
|
||||
/// </summary>
|
||||
private void CleanupStagingTempFiles(string folder)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!Directory.Exists(folder)) return;
|
||||
var files = Directory.GetFiles(folder);
|
||||
foreach (var file in files)
|
||||
{
|
||||
var ext = Path.GetExtension(file).ToLowerInvariant();
|
||||
if (ext == ".vtt" || ext == ".part" || ext == ".ytdl" || file.EndsWith("itunes_cover.jpg"))
|
||||
if (ext == ".vtt" || ext == ".part" || ext == ".ytdl" || ext == ".jpg" || ext == ".webp" || ext == ".png")
|
||||
{
|
||||
try { File.Delete(file); } catch { }
|
||||
}
|
||||
@@ -455,3 +839,4 @@ namespace MusicDownloader.Class.Downloader
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,45 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading.Channels;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace MusicDownloader.Class
|
||||
{
|
||||
/// <summary>
|
||||
/// アプリケーション全体のコンソールログを管理するクラス
|
||||
/// アプリケーション全体のログ管理クラス
|
||||
/// コンソールへのカラー出力および C:\feeds\Log\ への非同期ファイル書き込み(MusicDownloader_日付.log)を行う
|
||||
/// </summary>
|
||||
public static class LogManager
|
||||
{
|
||||
private static readonly object _lock = new object();
|
||||
private class LogMessage
|
||||
{
|
||||
public string Message { get; set; } = "";
|
||||
public DateTime Timestamp { get; set; }
|
||||
}
|
||||
|
||||
private static readonly object _consoleLock = new object();
|
||||
private static readonly Channel<LogMessage> _channel;
|
||||
private static readonly Task _backgroundTask;
|
||||
|
||||
static LogManager()
|
||||
{
|
||||
_channel = Channel.CreateUnbounded<LogMessage>(new UnboundedChannelOptions
|
||||
{
|
||||
SingleReader = true
|
||||
});
|
||||
|
||||
_backgroundTask = Task.Run(WriteToFileBackgroundAsync);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通常の情報ログを出力
|
||||
/// </summary>
|
||||
public static void AddLog(string message)
|
||||
{
|
||||
WriteWithColor($"[情報] {message}", ConsoleColor.Cyan);
|
||||
var text = $"[情報] {message}";
|
||||
WriteToConsole(text, ConsoleColor.Cyan);
|
||||
EnqueueFileLog(text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -22,7 +47,9 @@ namespace MusicDownloader.Class
|
||||
/// </summary>
|
||||
public static void AddSuccess(string message)
|
||||
{
|
||||
WriteWithColor($"[成功] {message}", ConsoleColor.Green);
|
||||
var text = $"[成功] {message}";
|
||||
WriteToConsole(text, ConsoleColor.Green);
|
||||
EnqueueFileLog(text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -30,7 +57,9 @@ namespace MusicDownloader.Class
|
||||
/// </summary>
|
||||
public static void AddWarning(string message)
|
||||
{
|
||||
WriteWithColor($"[警告] {message}", ConsoleColor.Yellow);
|
||||
var text = $"[警告] {message}";
|
||||
WriteToConsole(text, ConsoleColor.Yellow);
|
||||
EnqueueFileLog(text);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -38,23 +67,35 @@ namespace MusicDownloader.Class
|
||||
/// </summary>
|
||||
public static void AddError(string message, Exception? ex = null)
|
||||
{
|
||||
lock (_lock)
|
||||
var sb = new StringBuilder();
|
||||
sb.AppendLine($"[エラー] {message}");
|
||||
if (ex != null)
|
||||
{
|
||||
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine($"[{timestamp}] [エラー] {message}");
|
||||
if (ex != null)
|
||||
sb.AppendLine($"例外詳細: {ex.Message}");
|
||||
if (!string.IsNullOrWhiteSpace(ex.StackTrace))
|
||||
{
|
||||
Console.WriteLine($"例外詳細: {ex.Message}");
|
||||
Console.WriteLine(ex.StackTrace);
|
||||
sb.AppendLine(ex.StackTrace);
|
||||
}
|
||||
Console.ResetColor();
|
||||
}
|
||||
|
||||
var fullText = sb.ToString().TrimEnd('\r', '\n');
|
||||
WriteToConsole(fullText, ConsoleColor.Red);
|
||||
EnqueueFileLog(fullText);
|
||||
}
|
||||
|
||||
private static void WriteWithColor(string message, ConsoleColor color)
|
||||
private static void EnqueueFileLog(string text)
|
||||
{
|
||||
lock (_lock)
|
||||
var log = new LogMessage
|
||||
{
|
||||
Message = text,
|
||||
Timestamp = DateTime.Now
|
||||
};
|
||||
_channel.Writer.TryWrite(log);
|
||||
}
|
||||
|
||||
private static void WriteToConsole(string message, ConsoleColor color)
|
||||
{
|
||||
lock (_consoleLock)
|
||||
{
|
||||
var timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
|
||||
Console.ForegroundColor = color;
|
||||
@@ -62,5 +103,51 @@ namespace MusicDownloader.Class
|
||||
Console.ResetColor();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バックグラウンドでログファイル(C:\feeds\Log\MusicDownloader_日付.log)に書き込むタスク
|
||||
/// </summary>
|
||||
private static async Task WriteToFileBackgroundAsync()
|
||||
{
|
||||
await foreach (var log in _channel.Reader.ReadAllAsync())
|
||||
{
|
||||
try
|
||||
{
|
||||
var logDir = CmnDefine.GetLogDir();
|
||||
if (!Directory.Exists(logDir))
|
||||
{
|
||||
Directory.CreateDirectory(logDir);
|
||||
}
|
||||
|
||||
// ファイル名: MusicDownloader_yyyy-MM-dd.log
|
||||
var fileName = $"MusicDownloader_{log.Timestamp:yyyy-MM-dd}.log";
|
||||
var filePath = Path.Combine(logDir, fileName);
|
||||
|
||||
// 複数行の場合は各行にタイムスタンプを付与
|
||||
var lines = log.Message.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
|
||||
using var sw = new StreamWriter(filePath, append: true, Encoding.UTF8);
|
||||
foreach (var line in lines)
|
||||
{
|
||||
await sw.WriteLineAsync($"[{log.Timestamp:yyyy-MM-dd HH:mm:ss.fff}] {line}");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($"ログファイル書き込みエラー: {ex.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// キューを完了し、溜まっているすべてのログがファイルに書き込まれるまで待機
|
||||
/// </summary>
|
||||
public static async Task FlushAndCloseAsync()
|
||||
{
|
||||
_channel.Writer.Complete();
|
||||
if (_backgroundTask != null)
|
||||
{
|
||||
await _backgroundTask;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -77,13 +77,22 @@ var httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>()
|
||||
var lyricsManager = serviceProvider.GetRequiredService<LyricsManager>();
|
||||
var metadataClient = serviceProvider.GetRequiredService<MusicMetadataClient>();
|
||||
|
||||
// プロセス終了時に未書き込みログを確実にファイルへ出力
|
||||
AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
|
||||
{
|
||||
LogManager.FlushAndCloseAsync().GetAwaiter().GetResult();
|
||||
};
|
||||
|
||||
LogManager.AddLog($"==================================================");
|
||||
LogManager.AddLog($" MusicDownloader (高音質・正確タグ・常駐版) 起動");
|
||||
LogManager.AddLog($"==================================================");
|
||||
|
||||
// 出力先ディレクトリの決定
|
||||
// 出力先およびログ保存先ディレクトリの決定
|
||||
var outputDir = CmnDefine.GetOutputDir();
|
||||
var logDir = CmnDefine.GetLogDir();
|
||||
LogManager.AddLog($"ベース出力先: {outputDir}");
|
||||
LogManager.AddLog($"楽曲集約フォルダ: {Path.Combine(outputDir, CmnDefine.YoutubeFolderName)}");
|
||||
LogManager.AddLog($"ログ保存先: {logDir}");
|
||||
|
||||
// 依存ツール(yt-dlp)の準備確認
|
||||
using var initClient = httpClientFactory.CreateClient("webClient");
|
||||
@@ -204,3 +213,5 @@ while (true)
|
||||
|
||||
await Task.Delay(checkInterval);
|
||||
}
|
||||
|
||||
await LogManager.FlushAndCloseAsync();
|
||||
@@ -13,7 +13,7 @@ using System.Reflection;
|
||||
[assembly: System.Reflection.AssemblyCompanyAttribute("MusicDownloader")]
|
||||
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
|
||||
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+c0fdf1708a8b2c265224253be801c8f0d7fc3b3e")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+b57b812bbed7e74d655c6002cf1d74a541911eba")]
|
||||
[assembly: System.Reflection.AssemblyProductAttribute("MusicDownloader")]
|
||||
[assembly: System.Reflection.AssemblyTitleAttribute("MusicDownloader")]
|
||||
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
|
||||
|
||||
@@ -13,7 +13,7 @@ using System.Reflection;
|
||||
[assembly: System.Reflection.AssemblyCompanyAttribute("MusicDownloader")]
|
||||
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
|
||||
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+c0fdf1708a8b2c265224253be801c8f0d7fc3b3e")]
|
||||
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+b57b812bbed7e74d655c6002cf1d74a541911eba")]
|
||||
[assembly: System.Reflection.AssemblyProductAttribute("MusicDownloader")]
|
||||
[assembly: System.Reflection.AssemblyTitleAttribute("MusicDownloader")]
|
||||
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
|
||||
|
||||
@@ -23,6 +23,8 @@ services:
|
||||
volumes:
|
||||
# YouTubeからダウンロードした音楽ファイルをホストの G:\マイドライブ\MyMusic に出力(ジャンクション C:\MyMusic 経由)
|
||||
- C:\MyMusic:/music
|
||||
# ホストのログディレクトリ C:\feeds\Log へ出力するためのマウント
|
||||
- C:\feeds:/feeds
|
||||
networks:
|
||||
- common-network
|
||||
|
||||
|
||||
Reference in new issue
Block a user