1189 lines
55 KiB
C#
1189 lines
55 KiB
C#
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;
|
||
using CliWrap;
|
||
using CliWrap.Buffered;
|
||
using MusicDownloader.Class.Lyrics;
|
||
using MusicDownloader.Class.Metadata;
|
||
|
||
namespace MusicDownloader.Class.Downloader
|
||
{
|
||
/// <summary>
|
||
/// yt-dlpのプレイリストエントリモデル
|
||
/// </summary>
|
||
public class YtPlaylistEntry
|
||
{
|
||
[JsonPropertyName("id")]
|
||
public string? Id { get; set; }
|
||
|
||
[JsonPropertyName("title")]
|
||
public string? Title { get; set; }
|
||
|
||
[JsonPropertyName("uploader")]
|
||
public string? Uploader { get; set; }
|
||
|
||
[JsonPropertyName("channel")]
|
||
public string? Channel { get; set; }
|
||
|
||
[JsonPropertyName("track")]
|
||
public string? Track { get; set; }
|
||
|
||
[JsonPropertyName("artist")]
|
||
public string? Artist { get; set; }
|
||
|
||
[JsonPropertyName("album")]
|
||
public string? Album { get; set; }
|
||
|
||
[JsonPropertyName("duration")]
|
||
public double? Duration { get; set; }
|
||
|
||
[JsonPropertyName("url")]
|
||
public string? Url { get; set; }
|
||
|
||
[JsonPropertyName("upload_date")]
|
||
public string? UploadDate { get; set; }
|
||
|
||
[JsonPropertyName("release_year")]
|
||
public uint? ReleaseYear { get; set; }
|
||
|
||
/// <summary>
|
||
/// 公開年またはリリース年を取得
|
||
/// </summary>
|
||
public uint? GetYear()
|
||
{
|
||
if (ReleaseYear.HasValue && ReleaseYear.Value > 0)
|
||
{
|
||
return ReleaseYear.Value;
|
||
}
|
||
|
||
if (!string.IsNullOrWhiteSpace(UploadDate) && UploadDate.Length >= 4)
|
||
{
|
||
if (uint.TryParse(UploadDate.Substring(0, 4), out var y) && y > 1900 && y < 2100)
|
||
{
|
||
return y;
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// yt-dlpのプレイリスト情報モデル
|
||
/// </summary>
|
||
public class YtPlaylistInfo
|
||
{
|
||
[JsonPropertyName("id")]
|
||
public string? Id { get; set; }
|
||
|
||
[JsonPropertyName("title")]
|
||
public string? Title { get; set; }
|
||
|
||
[JsonPropertyName("uploader")]
|
||
public string? Uploader { get; set; }
|
||
|
||
[JsonPropertyName("entries")]
|
||
public List<YtPlaylistEntry>? Entries { get; set; }
|
||
}
|
||
|
||
/// <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; }
|
||
|
||
/// <summary>
|
||
/// 音声ファイルのバイナリSHA-256ハッシュ値(バイナリ重複判定用)
|
||
/// </summary>
|
||
[JsonPropertyName("file_hash")]
|
||
public string FileHash { get; set; } = "";
|
||
|
||
[JsonPropertyName("updated_at")]
|
||
public DateTime UpdatedAt { get; set; } = DateTime.Now;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 高音質変換・外部検索メタデータ付与・歌詞連携・重複排除を行うダウンロード処理クラス
|
||
/// </summary>
|
||
public class YoutubeDownloader
|
||
{
|
||
private readonly string _ytDlpPath;
|
||
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;
|
||
_lyricsManager = lyricsManager;
|
||
_metadataClient = metadataClient;
|
||
}
|
||
|
||
/// <summary>
|
||
/// プレイリストURLからプレイリスト名および動画リストを取得する
|
||
/// </summary>
|
||
public async Task<YtPlaylistInfo?> GetPlaylistInfoAsync(string playlistUrl, string? outputBaseDir = null)
|
||
{
|
||
LogManager.AddLog($"プレイリスト情報を取得中: {playlistUrl}");
|
||
|
||
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)
|
||
.WithArguments(args)
|
||
.WithValidation(CommandResultValidation.None)
|
||
.ExecuteBufferedAsync();
|
||
|
||
if (result.ExitCode != 0)
|
||
{
|
||
LogManager.AddError($"プレイリスト情報の取得に失敗しました (終了コード {result.ExitCode}): {result.StandardError}");
|
||
return null;
|
||
}
|
||
|
||
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
|
||
var info = JsonSerializer.Deserialize<YtPlaylistInfo>(result.StandardOutput, options);
|
||
return info;
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogManager.AddError($"プレイリスト情報の解析中に例外が発生しました: {ex.Message}", ex);
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 初回起動時や再起動時に、yt-dlp のダウンロード完了履歴 (archive.txt) をリセットし、
|
||
/// 全曲の再ダウンロード・最新タグ化を可能にする
|
||
/// </summary>
|
||
public void ResetDownloadArchive(string youtubeFolder)
|
||
{
|
||
try
|
||
{
|
||
if (string.IsNullOrWhiteSpace(youtubeFolder)) return;
|
||
var archivePath = Path.Combine(youtubeFolder, "archive.txt");
|
||
if (File.Exists(archivePath))
|
||
{
|
||
var backupPath = Path.Combine(youtubeFolder, $"archive_{DateTime.Now:yyyyMMddHHmmss}.bak");
|
||
File.Move(archivePath, backupPath, overwrite: true);
|
||
LogManager.AddLog($"[起動時初期化] 初回全曲ダウンロードのため、ダウンロード履歴 (archive.txt) を退避・リセットしました: {Path.GetFileName(backupPath)}");
|
||
}
|
||
else
|
||
{
|
||
LogManager.AddLog($"[起動時初期化] ダウンロード履歴 (archive.txt) は存在しません。新規に全曲取得を開始します。");
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogManager.AddWarning($"[起動時初期化] archive.txt のリセット中に例外: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// プレイリスト全体のダウンロードおよびメタデータ・歌詞付与・プレイリスト生成を実行する
|
||
/// 全ての曲は共通フォルダ「Youtube」に集約され、重複動画は再利用されます。
|
||
/// </summary>
|
||
/// <param name="playlistUrl">対象プレイリストURL</param>
|
||
/// <param name="outputBaseDir">出力ベースディレクトリ</param>
|
||
/// <param name="isIncremental">差分ダウンロードを行うかどうか (falseの場合は起動直後として全曲をダウンロード・最新化)</param>
|
||
public async Task ProcessPlaylistAsync(string playlistUrl, string outputBaseDir, bool isIncremental = true)
|
||
{
|
||
var playlistInfo = await GetPlaylistInfoAsync(playlistUrl, outputBaseDir);
|
||
var rawTitle = playlistInfo?.Title ?? "YouTube_Playlist";
|
||
var sanitizedPlaylistName = CmnUtil.SanitizeFileName(rawTitle);
|
||
|
||
// 【要件⑥】プレイリストごとのログファイル(MusicDownloader_開始時間_プレイリスト名.log)を設定
|
||
LogManager.SetPlaylistContext(DateTime.Now, sanitizedPlaylistName);
|
||
|
||
// ① 全ての曲を格納する共通フォルダ「Youtube」の準備および書き込み疎通確認
|
||
var youtubeFolder = Path.Combine(outputBaseDir, CmnDefine.YoutubeFolderName);
|
||
if (!CmnUtil.EnsureStorageWritable(youtubeFolder))
|
||
{
|
||
throw new IOException($"出力先ディレクトリへの書き込みができません (Read-only file system またはストレージ切断): {youtubeFolder}");
|
||
}
|
||
|
||
// ④ Google Drive同期前の安全なローカル作業領域
|
||
var stagingDir = CmnDefine.GetStagingDir();
|
||
|
||
LogManager.AddLog($"保存先ディレクトリ: {youtubeFolder}");
|
||
LogManager.AddLog($"ローカル作業ディレクトリ: {stagingDir}");
|
||
LogManager.AddLog($"実行モード: {(isIncremental ? "差分ダウンロード (既存曲スキップ)" : "全曲ダウンロード (最新化・タグ再適用)")}");
|
||
|
||
// ③ 重複排除用マップ(downloaded_tracks.json)の読み込み
|
||
var downloadedTracks = await LoadDownloadedTracksAsync(youtubeFolder);
|
||
|
||
// 有効な動画エントリのみを抽出(削除済みや非公開動画は除外)
|
||
var rawEntries = playlistInfo?.Entries ?? new List<YtPlaylistEntry>();
|
||
var validEntries = rawEntries
|
||
.Where(e => !string.IsNullOrWhiteSpace(e.Id) &&
|
||
!string.IsNullOrWhiteSpace(e.Title) &&
|
||
e.Title != "[Private video]" &&
|
||
e.Title != "[Deleted video]")
|
||
.ToList();
|
||
|
||
// 【要件③】プレイリスト内での同一動画IDの重複を事前に排除
|
||
var uniqueEntries = new List<YtPlaylistEntry>();
|
||
var seenIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||
foreach (var entry in validEntries)
|
||
{
|
||
if (seenIds.Add(entry.Id!))
|
||
{
|
||
uniqueEntries.Add(entry);
|
||
}
|
||
else
|
||
{
|
||
LogManager.AddLog($"[プレイリスト内重複除外] 同一プレイリスト内で重複している動画をスキップ対象としました: {entry.Title ?? entry.Id}");
|
||
}
|
||
}
|
||
validEntries = uniqueEntries;
|
||
|
||
// プレイリスト登録用の楽曲リスト
|
||
var currentPlaylistTracks = new List<DownloadedTrackInfo>();
|
||
|
||
if (validEntries.Count == 0)
|
||
{
|
||
if (rawEntries.Count > 0)
|
||
{
|
||
LogManager.AddWarning($"プレイリストに有効な公開動画が見つかりませんでした (全 {rawEntries.Count} 件が非公開または削除)");
|
||
return;
|
||
}
|
||
|
||
// 単一動画URLまたはエントリがフラット取得できなかった場合、直接ダウンロード
|
||
LogManager.AddLog($"プレイリストのエントリが見つからないか単一動画URLです。直接ダウンロードを試行します。");
|
||
var singleTrack = await DownloadAndProcessSingleAsync(playlistUrl, 1, 1, stagingDir, youtubeFolder, sanitizedPlaylistName, null, downloadedTracks, outputBaseDir);
|
||
if (singleTrack != null)
|
||
{
|
||
currentPlaylistTracks.Add(singleTrack);
|
||
if (!string.IsNullOrEmpty(singleTrack.VideoId))
|
||
{
|
||
downloadedTracks[singleTrack.VideoId] = singleTrack;
|
||
await SaveDownloadedTracksAsync(youtubeFolder, downloadedTracks);
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
var totalCount = (uint)validEntries.Count;
|
||
LogManager.AddLog($"プレイリスト「{sanitizedPlaylistName}」: 有効な全 {totalCount} 曲の処理を開始します。");
|
||
|
||
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}";
|
||
|
||
LogManager.AddLog($"--------------------------------------------------------------------------------");
|
||
LogManager.AddLog($"[{videoIndex}/{totalCount}] 処理開始: {entry.Title ?? videoId}");
|
||
|
||
// ③ 別々のプレイリストでも同じ動画が参照されている場合は重複を防止(既存ファイルの再利用)
|
||
// ※ 初回起動時 (isIncremental == false) はスキップせず、全曲をダウンロード・最新化する
|
||
if (isIncremental &&
|
||
!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曲の処理(ローカル作業フォルダでダウンロード・タグ付け・検証を完結させ、完成後にYoutubeフォルダへ転送)
|
||
var trackInfo = await DownloadAndProcessSingleAsync(
|
||
videoUrl, videoIndex, totalCount, stagingDir, youtubeFolder, sanitizedPlaylistName, entry, downloadedTracks, outputBaseDir);
|
||
|
||
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}」の処理が完了しました! (登録曲数: {currentPlaylistTracks.Count})");
|
||
LogManager.AddSuccess($"保存先: {youtubeFolder}");
|
||
LogManager.AddSuccess($"================================================================================");
|
||
}
|
||
|
||
/// <summary>
|
||
/// 1曲のダウンロード・高音質Opus変換・外部楽曲メタデータ解決・タグ付与を実行する
|
||
/// ④ Google Driveへのアップロード競合を防ぐため、ローカル作業ディレクトリ(stagingDir)で
|
||
/// すべての処理・ファイル生成を完了させてから、完成ファイルをYoutubeフォルダへコピーします。
|
||
/// </summary>
|
||
private async Task<DownloadedTrackInfo?> DownloadAndProcessSingleAsync(
|
||
string videoUrl,
|
||
uint index,
|
||
uint totalCount,
|
||
string stagingDir,
|
||
string youtubeFolder,
|
||
string playlistName,
|
||
YtPlaylistEntry? entryInfo,
|
||
Dictionary<string, DownloadedTrackInfo> downloadedTracks,
|
||
string? outputBaseDir = null)
|
||
{
|
||
var videoId = entryInfo?.Id ?? "";
|
||
var archiveFile = Path.Combine(youtubeFolder, "archive.txt");
|
||
|
||
// ② 多段階フォールバックによるダウンロード実行(429字幕エラー、403Forbiddenエラー、年齢制限エラーを自動回避)
|
||
var isDownloadSuccess = await DownloadWithFallbackAsync(videoUrl, videoId, stagingDir, archiveFile, outputBaseDir, youtubeFolder, entryInfo?.Title);
|
||
if (!isDownloadSuccess)
|
||
{
|
||
LogManager.AddWarning($"[{index}/{totalCount}] すべてのフォールバックを試みましたがダウンロードできませんでした。");
|
||
// 次回ループ時にyt-dlpがスキップしないよう、archive.txtから動画IDを除去
|
||
RemoveFromArchiveFile(archiveFile, videoId);
|
||
CleanupDirectory(stagingDir);
|
||
return null;
|
||
}
|
||
|
||
// ダウンロードされた .opus ファイルを作業フォルダから特定
|
||
var opusFiles = Directory.GetFiles(stagingDir, "*.opus");
|
||
if (opusFiles.Length == 0)
|
||
{
|
||
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);
|
||
|
||
// 音声ファイルの整合性検証(ブツブツ・破損チェック)
|
||
await VerifyAudioIntegrityAsync(targetOpus);
|
||
|
||
// 【要件④】ダウンロードした結果のバイナリ重複チェック(ファイルSHA-256および音声ストリームハッシュ)
|
||
var currentFileHash = await ComputeFileHashAsync(targetOpus);
|
||
var currentAudioHash = await ComputeAudioHashAsync(targetOpus);
|
||
var duplicateTrack = await FindDuplicateBinaryTrackAsync(currentFileHash, currentAudioHash, youtubeFolder, downloadedTracks, videoId);
|
||
if (duplicateTrack != null)
|
||
{
|
||
LogManager.AddSuccess($"[バイナリ重複検出] 既存ファイル「{duplicateTrack.FileName}」とバイナリレベルで完全に同一の動画です。新規保存をスキップし、既存ファイルを再利用します。");
|
||
CleanupDirectory(stagingDir);
|
||
return duplicateTrack;
|
||
}
|
||
|
||
// -------------------------------------------------------------
|
||
// メタデータ(曲名・アーティスト・アルバム・アルバムアーティスト)の決定
|
||
// 【要件】YouTubeからアーティスト・アルバムなどの情報が取得できる場合はそれを最優先
|
||
// -------------------------------------------------------------
|
||
var baseTitle = !string.IsNullOrWhiteSpace(entryInfo?.Title) ? entryInfo.Title : fileNameWithoutExt;
|
||
var uploader = !string.IsNullOrWhiteSpace(entryInfo?.Channel) ? entryInfo.Channel : (entryInfo?.Uploader ?? "");
|
||
|
||
// 1. タイトル文字列の初期パース
|
||
var (parsedArtist, parsedTitle) = CmnUtil.ParseArtistAndTitle(baseTitle, uploader);
|
||
|
||
// 2. YouTube公式メタデータの取得有無を確認
|
||
bool hasYoutubeTrack = !string.IsNullOrWhiteSpace(entryInfo?.Track);
|
||
bool hasYoutubeArtist = !string.IsNullOrWhiteSpace(entryInfo?.Artist);
|
||
bool hasYoutubeAlbum = !string.IsNullOrWhiteSpace(entryInfo?.Album);
|
||
uint? youtubeYear = entryInfo?.GetYear();
|
||
|
||
string finalTitle = hasYoutubeTrack ? entryInfo!.Track!.Trim() : parsedTitle;
|
||
string finalArtist = hasYoutubeArtist ? entryInfo!.Artist!.Trim() : parsedArtist;
|
||
string finalAlbum = hasYoutubeAlbum ? entryInfo!.Album!.Trim() : playlistName;
|
||
string finalAlbumArtist = finalArtist;
|
||
uint? finalYear = youtubeYear;
|
||
string? downloadArtworkPath = null;
|
||
|
||
if (hasYoutubeTrack || hasYoutubeArtist || hasYoutubeAlbum)
|
||
{
|
||
LogManager.AddLog($"[YouTube公式メタデータ優先] " +
|
||
$"[曲名: {(hasYoutubeTrack ? finalTitle : "(タイトルパース)")}] " +
|
||
$"[アーティスト: {(hasYoutubeArtist ? finalArtist : "(タイトルパース)")}] " +
|
||
$"[アルバム: {(hasYoutubeAlbum ? finalAlbum : "(プレイリスト名)")}]");
|
||
}
|
||
else
|
||
{
|
||
LogManager.AddLog($"解析候補: [アーティスト: {finalArtist}] [曲名: {finalTitle}]");
|
||
}
|
||
|
||
// 3. 外部楽曲検索API (iTunes / LRCLIB) を呼び出して未取得項目の補完や高画質カバーアートを取得
|
||
var resolvedMeta = await _metadataClient.ResolveMetadataAsync(
|
||
rawVideoTitle: baseTitle,
|
||
uploader: uploader,
|
||
parsedArtist: finalArtist,
|
||
parsedTitle: finalTitle,
|
||
durationSeconds: entryInfo?.Duration);
|
||
|
||
if (resolvedMeta != null)
|
||
{
|
||
// YouTube側で取得できなかった項目のみ、外部メタデータで補完
|
||
if (!hasYoutubeTrack && !string.IsNullOrWhiteSpace(resolvedMeta.Title))
|
||
{
|
||
finalTitle = resolvedMeta.Title;
|
||
}
|
||
if (!hasYoutubeArtist && !string.IsNullOrWhiteSpace(resolvedMeta.Artist))
|
||
{
|
||
finalArtist = resolvedMeta.Artist;
|
||
if (!hasYoutubeArtist)
|
||
{
|
||
finalAlbumArtist = resolvedMeta.Artist;
|
||
}
|
||
}
|
||
if (!hasYoutubeAlbum && !string.IsNullOrWhiteSpace(resolvedMeta.Album))
|
||
{
|
||
finalAlbum = resolvedMeta.Album;
|
||
}
|
||
if (!hasYoutubeArtist && !string.IsNullOrWhiteSpace(resolvedMeta.AlbumArtist))
|
||
{
|
||
finalAlbumArtist = resolvedMeta.AlbumArtist;
|
||
}
|
||
if (!finalYear.HasValue && resolvedMeta.Year.HasValue && resolvedMeta.Year.Value > 0)
|
||
{
|
||
finalYear = resolvedMeta.Year.Value;
|
||
}
|
||
|
||
// 高画質カバー画像が存在すればダウンロードして適用
|
||
if (!string.IsNullOrWhiteSpace(resolvedMeta.ArtworkUrl))
|
||
{
|
||
var highResArtPath = Path.Combine(stagingDir, "itunes_cover.jpg");
|
||
var downloadedArt = await _metadataClient.DownloadArtworkAsync(resolvedMeta.ArtworkUrl, highResArtPath);
|
||
if (downloadedArt != null)
|
||
{
|
||
downloadArtworkPath = downloadedArt;
|
||
}
|
||
}
|
||
}
|
||
|
||
// サムネイル画像の決定(高画質公式アートワーク > YouTubeサムネイル)
|
||
string? thumbnailToUse = downloadArtworkPath;
|
||
if (thumbnailToUse == null)
|
||
{
|
||
var thumbJpg = Path.ChangeExtension(targetOpus, ".jpg");
|
||
if (File.Exists(thumbJpg))
|
||
{
|
||
thumbnailToUse = thumbJpg;
|
||
}
|
||
else
|
||
{
|
||
var jpgs = Directory.GetFiles(stagingDir, "*.jpg");
|
||
if (jpgs.Length > 0)
|
||
{
|
||
thumbnailToUse = jpgs[0];
|
||
}
|
||
}
|
||
}
|
||
|
||
// 歌詞処理 (.lrc作成および歌詞テキスト取得) - stagingDir 内に生成
|
||
// 【要件】YouTube字幕の利用はYouTube Music公式曲(アーティスト・アルバム等の取得可能曲)に限定
|
||
bool isOfficialMusic = hasYoutubeTrack || hasYoutubeArtist || hasYoutubeAlbum;
|
||
var lyrics = await _lyricsManager.ProcessLyricsAsync(targetOpus, finalTitle, finalArtist, entryInfo?.Duration, stagingDir, isOfficialMusic: isOfficialMusic, filePrefix: null);
|
||
|
||
// メタデータ (TagLibSharp) の書き込み(正確な曲名・アーティスト・アルバム・アルバムアーティスト)
|
||
AudioTagManager.ApplyMetadata(
|
||
opusPath: targetOpus,
|
||
title: finalTitle,
|
||
artist: finalArtist,
|
||
album: finalAlbum,
|
||
trackNumber: index,
|
||
trackCount: totalCount,
|
||
year: finalYear,
|
||
lyrics: lyrics,
|
||
thumbnailPath: thumbnailToUse,
|
||
comment: videoUrl,
|
||
albumArtist: finalAlbumArtist);
|
||
|
||
// 不要な中間ファイル(.vtt, 一時画像等)のクリーンアップ(.opus と .lrc は保持)
|
||
CleanupStagingTempFiles(stagingDir);
|
||
|
||
// ④ ファイルがすべて用意されてから、Google Drive保存先(Youtubeフォルダ)へ転送
|
||
var rawBaseName = Path.GetFileNameWithoutExtension(targetOpus);
|
||
var ext = Path.GetExtension(targetOpus);
|
||
|
||
// 【要件②】ファイル名に使えない文字(\ / : * ? " < > |)を安全な全角文字等に変換
|
||
var sanitizedBaseName = CmnUtil.SanitizeFileName(rawBaseName);
|
||
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等)を決定
|
||
var finalFileName = GetUniqueTargetFileName(youtubeFolder, cleanFileName, videoId, downloadedTracks);
|
||
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;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 転送が失敗した場合は、絶対に成功扱いせず作業フォルダを掃除して処理を中断
|
||
if (!transferSuccess)
|
||
{
|
||
RemoveFromArchiveFile(archiveFile, videoId);
|
||
CleanupDirectory(stagingDir);
|
||
return null;
|
||
}
|
||
|
||
// 転送成功時のみ作業フォルダを掃除し、完了ログを出力
|
||
CleanupDirectory(stagingDir);
|
||
LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {targetFinalFileName}");
|
||
|
||
return new DownloadedTrackInfo
|
||
{
|
||
VideoId = videoId,
|
||
FileName = targetFinalFileName,
|
||
Title = finalTitle,
|
||
Artist = finalArtist,
|
||
Duration = entryInfo?.Duration,
|
||
FileHash = currentFileHash,
|
||
UpdatedAt = DateTime.Now
|
||
};
|
||
}
|
||
|
||
/// <summary>
|
||
/// ① 同じ動画名(another vocalなど)の別動画が既に存在する場合に上書きを防止し、
|
||
/// 「曲名 (2).opus」等のユニークなファイル名を決定する
|
||
/// </summary>
|
||
private string GetUniqueTargetFileName(
|
||
string youtubeFolder,
|
||
string originalFileName,
|
||
string videoId,
|
||
Dictionary<string, DownloadedTrackInfo> downloadedTracks)
|
||
{
|
||
var rawBase = Path.GetFileNameWithoutExtension(originalFileName);
|
||
var ext = Path.GetExtension(originalFileName);
|
||
var baseName = CmnUtil.SanitizeFileName(rawBase);
|
||
var candidateFileName = $"{baseName}{ext}";
|
||
|
||
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>
|
||
/// ② 多段階フォールバックにより動画の音声を確実にダウンロードする
|
||
/// - Cookie自動適用: cookies.txt による年齢制限解除・高画質取得
|
||
/// - 429 Too Many Requests: 字幕ダウンロードを無効化して音声のみ取得
|
||
/// - 403 Forbidden / 年齢制限: YouTube Android / Creator / TV / iOS クライアントAPIへの自動切り替え
|
||
/// </summary>
|
||
private async Task<bool> DownloadWithFallbackAsync(
|
||
string videoUrl,
|
||
string videoId,
|
||
string stagingDir,
|
||
string archiveFile,
|
||
string? outputBaseDir = null,
|
||
string? youtubeFolder = null,
|
||
string? videoTitle = null)
|
||
{
|
||
var outputTemplate = Path.Combine(stagingDir, "%(title)s.%(ext)s");
|
||
|
||
// 基本引数の生成
|
||
List<string> GetBaseArgs()
|
||
{
|
||
var baseArgs = 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",
|
||
"-o", outputTemplate,
|
||
"--no-warnings"
|
||
};
|
||
|
||
// CookieファイルまたはブラウザCookieの自動適用(年齢確認・制限解除用、一時コピーで安全に適用)
|
||
CookieHelper.ApplyCookieArgs(baseArgs, outputBaseDir, youtubeFolder, stagingDir);
|
||
|
||
return baseArgs;
|
||
}
|
||
|
||
// 試行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: Mobile Webクライアント(Cookie対応・403 Forbidden対策・年齢確認対策)
|
||
var plan3 = GetBaseArgs();
|
||
plan3.AddRange(new[] { "--extractor-args", "youtube:player_client=mweb,web", videoUrl });
|
||
|
||
// 試行4: TVクライアントAPI(年齢確認バイパス試行)
|
||
var plan4 = GetBaseArgs();
|
||
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)[]
|
||
{
|
||
("通常ダウンロード (日本語字幕あり)", plan1),
|
||
("フォールバック1 (字幕取得オフ / 429対策)", plan2),
|
||
("フォールバック2 (YouTube Mobile Webクライアント / 403・年齢確認対策)", plan3),
|
||
("フォールバック3 (YouTube TVクライアント / 年齢確認対策)", plan4),
|
||
("フォールバック4 (YouTube Androidクライアント / 403対策)", plan5),
|
||
("フォールバック5 (YouTube iOSクライアント & キャッシュ無効化)", plan6)
|
||
};
|
||
|
||
bool detectedAgeRestriction = false;
|
||
|
||
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 ?? "";
|
||
var stdOut = cmdResult.StandardOutput ?? "";
|
||
LogManager.AddWarning($"[{name}] 終了コード: {cmdResult.ExitCode}");
|
||
if (!string.IsNullOrWhiteSpace(stdErr))
|
||
{
|
||
if (stdErr.Contains("confirm your age", StringComparison.OrdinalIgnoreCase) ||
|
||
stdErr.Contains("Sign in to confirm", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
detectedAgeRestriction = true;
|
||
}
|
||
LogManager.AddWarning($"詳細: {stdErr.Trim()}");
|
||
}
|
||
else if (cmdResult.ExitCode == 0 && opusFiles.Length == 0 && !string.IsNullOrWhiteSpace(stdOut))
|
||
{
|
||
var lastOut = stdOut.Trim().Split('\n').LastOrDefault()?.Trim() ?? "";
|
||
LogManager.AddWarning($"詳細(stdout): {lastOut}");
|
||
}
|
||
|
||
// エラー終了コードでもOpusファイル自体が生成完了していれば成功とみなす
|
||
if (opusFiles.Length > 0)
|
||
{
|
||
LogManager.AddLog($"音声ファイル自体の生成を確認したため処理を継続します。");
|
||
return true;
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogManager.AddWarning($"[{name}] 例外発生: {ex.Message}");
|
||
}
|
||
}
|
||
|
||
if (detectedAgeRestriction)
|
||
{
|
||
var (_, cookieDesc) = CookieHelper.GetCookieStatus(outputBaseDir, youtubeFolder);
|
||
LogManager.AddWarning($"[年齢制限エラー] 動画「{videoTitle ?? videoId}」はYouTubeの年齢確認が必要です。");
|
||
LogManager.AddWarning($"[Cookie設定状況] {cookieDesc}");
|
||
}
|
||
|
||
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>
|
||
/// ダウンロード成功時に 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>
|
||
/// 【要件①】AndroidのPowerampで読み取れるプレイリストファイル(.m3u8)を保存
|
||
/// m3u8ファイルはYoutubeフォルダ内には作成せず、親フォルダ(outputBaseDir)直下のみに配置します。
|
||
/// 既存のYoutubeフォルダ内m3u8は削除してクリーンアップします。
|
||
/// </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 sbParentDir = new StringBuilder();
|
||
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;
|
||
|
||
// 親フォルダ(outputBaseDir)から見た相対パス:Youtube/ファイル名
|
||
sbParentDir.AppendLine($"#EXTINF:{durationSec},{displayTitle}");
|
||
sbParentDir.AppendLine($"{CmnDefine.YoutubeFolderName}/{track.FileName}");
|
||
}
|
||
|
||
// Poweramp対応: UTF-8 (BOMなし)
|
||
var utf8WithoutBom = new UTF8Encoding(false);
|
||
|
||
try
|
||
{
|
||
// 【要件①】Youtubeフォルダ内の既存m3u8があれば削除(Youtubeフォルダ内にm3u8を作らない)
|
||
var m3u8InsideYoutube = Path.Combine(youtubeFolder, $"{sanitizedName}.m3u8");
|
||
if (File.Exists(m3u8InsideYoutube))
|
||
{
|
||
try
|
||
{
|
||
File.Delete(m3u8InsideYoutube);
|
||
LogManager.AddLog($"Youtubeフォルダ内の既存m3u8ファイルをクリーンアップしました: {m3u8InsideYoutube}");
|
||
}
|
||
catch { }
|
||
}
|
||
|
||
// outputBaseDir 直下(親階層)にプレイリストファイルを保存
|
||
var m3u8ParentDir = Path.Combine(outputBaseDir, $"{sanitizedName}.m3u8");
|
||
await File.WriteAllTextAsync(m3u8ParentDir, sbParentDir.ToString(), utf8WithoutBom);
|
||
LogManager.AddSuccess($"Poweramp用プレイリストファイルを保存しました: {m3u8ParentDir}");
|
||
}
|
||
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)
|
||
{
|
||
bool needUpdateDb = false;
|
||
foreach (var item in list)
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(item.VideoId))
|
||
{
|
||
// 【要件④】既存ファイルでFileHashが未計算の場合、ロード時に補完
|
||
if (string.IsNullOrEmpty(item.FileHash))
|
||
{
|
||
var fullPath = Path.Combine(youtubeFolder, item.FileName);
|
||
if (File.Exists(fullPath))
|
||
{
|
||
item.FileHash = await ComputeFileHashAsync(fullPath);
|
||
needUpdateDb = true;
|
||
}
|
||
}
|
||
dict[item.VideoId] = item;
|
||
}
|
||
}
|
||
|
||
if (needUpdateDb)
|
||
{
|
||
await SaveDownloadedTracksAsync(youtubeFolder, dict);
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogManager.AddWarning($"downloaded_tracks.json の読み込みに失敗しました: {ex.Message}");
|
||
}
|
||
|
||
return dict;
|
||
}
|
||
|
||
/// <summary>
|
||
/// ファイル全体のバイナリSHA-256ハッシュ値を非同期に計算する
|
||
/// </summary>
|
||
private static async Task<string> ComputeFileHashAsync(string filePath)
|
||
{
|
||
if (!File.Exists(filePath)) return "";
|
||
try
|
||
{
|
||
using var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true);
|
||
using var sha256 = System.Security.Cryptography.SHA256.Create();
|
||
var hashBytes = await sha256.ComputeHashAsync(stream);
|
||
return Convert.ToHexString(hashBytes);
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
LogManager.AddWarning($"ファイルハッシュ計算例外 ({Path.GetFileName(filePath)}): {ex.Message}");
|
||
return "";
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// ffmpegを用いてタグメタデータを除いた純粋な音声ストリームのMD5ハッシュを計算する
|
||
/// (タグ付け前後の差異を吸収して同一音源バイナリを判定可能)
|
||
/// </summary>
|
||
private async Task<string> ComputeAudioHashAsync(string filePath)
|
||
{
|
||
if (!File.Exists(filePath)) return "";
|
||
try
|
||
{
|
||
var result = await Cli.Wrap("ffmpeg")
|
||
.WithArguments(new[] { "-v", "error", "-i", filePath, "-map", "0:a", "-c", "copy", "-f", "md5", "-" })
|
||
.WithValidation(CommandResultValidation.None)
|
||
.ExecuteBufferedAsync();
|
||
|
||
if (result.ExitCode == 0 && !string.IsNullOrWhiteSpace(result.StandardOutput))
|
||
{
|
||
var outStr = result.StandardOutput.Trim();
|
||
if (outStr.StartsWith("MD5=", StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
return outStr.Substring(4).Trim();
|
||
}
|
||
return outStr;
|
||
}
|
||
}
|
||
catch { }
|
||
|
||
return "";
|
||
}
|
||
|
||
/// <summary>
|
||
/// 【要件④】バイナリレベル(ファイルハッシュまたは音声ストリームハッシュ)で同一の既存ファイルを検索
|
||
/// ※ 同一動画IDの再ダウンロード・更新時は除外して別動画との重複のみを判定
|
||
/// </summary>
|
||
private async Task<DownloadedTrackInfo?> FindDuplicateBinaryTrackAsync(
|
||
string fileHash,
|
||
string audioHash,
|
||
string youtubeFolder,
|
||
Dictionary<string, DownloadedTrackInfo> downloadedTracks,
|
||
string currentVideoId)
|
||
{
|
||
// 1. downloadedTracks から FileHash の完全一致を検索
|
||
if (!string.IsNullOrEmpty(fileHash))
|
||
{
|
||
foreach (var track in downloadedTracks.Values)
|
||
{
|
||
// 同一動画IDの場合は自分自身の再ダウンロードのため重複扱いしない(最新のタグやファイル名で上書き更新を許可)
|
||
if (!string.IsNullOrEmpty(currentVideoId) && string.Equals(track.VideoId, currentVideoId, StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
if (string.Equals(track.FileHash, fileHash, StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
var fullPath = Path.Combine(youtubeFolder, track.FileName);
|
||
if (File.Exists(fullPath)) return track;
|
||
}
|
||
}
|
||
}
|
||
|
||
// 2. 音声ストリームハッシュによる一致検索(タグ付け済み既存ファイルとの比較)
|
||
if (!string.IsNullOrEmpty(audioHash))
|
||
{
|
||
foreach (var track in downloadedTracks.Values)
|
||
{
|
||
// 同一動画IDの場合は自分自身の再ダウンロードのため重複扱いしない
|
||
if (!string.IsNullOrEmpty(currentVideoId) && string.Equals(track.VideoId, currentVideoId, StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
continue;
|
||
}
|
||
|
||
var fullPath = Path.Combine(youtubeFolder, track.FileName);
|
||
if (File.Exists(fullPath))
|
||
{
|
||
var existingAudioHash = await ComputeAudioHashAsync(fullPath);
|
||
if (!string.IsNullOrEmpty(existingAudioHash) &&
|
||
string.Equals(existingAudioHash, audioHash, StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
return track;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
return null;
|
||
}
|
||
|
||
/// <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}");
|
||
if (CmnUtil.IsStorageFailureException(ex))
|
||
{
|
||
// ストレージ切断時は上位へスローしてプロセス終了・自己復旧へ促す
|
||
throw new IOException($"downloaded_tracks.json 保存中にストレージ切断を検知しました: {ex.Message}", ex);
|
||
}
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// ffmpegを用いて音声ファイルの整合性をチェック(破損やデコードエラーがないか検証)
|
||
/// </summary>
|
||
private async Task VerifyAudioIntegrityAsync(string opusPath)
|
||
{
|
||
try
|
||
{
|
||
var result = await Cli.Wrap("ffmpeg")
|
||
.WithArguments(new[] { "-v", "error", "-i", opusPath, "-f", "null", "-" })
|
||
.WithValidation(CommandResultValidation.None)
|
||
.ExecuteBufferedAsync();
|
||
|
||
if (result.ExitCode == 0 && string.IsNullOrWhiteSpace(result.StandardError))
|
||
{
|
||
LogManager.AddSuccess($"音声整合性チェック合格 (エラーなし): {Path.GetFileName(opusPath)}");
|
||
}
|
||
else if (!string.IsNullOrWhiteSpace(result.StandardError))
|
||
{
|
||
LogManager.AddWarning($"音声ファイル検証警告: {result.StandardError.Trim()}");
|
||
}
|
||
}
|
||
catch
|
||
{
|
||
// ffmpegがPATHに見当たらない等の場合はスキップ
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 作業用ディレクトリ内のすべてのファイルをクリア
|
||
/// </summary>
|
||
private void CleanupDirectory(string folder)
|
||
{
|
||
try
|
||
{
|
||
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" || ext == ".jpg" || ext == ".webp" || ext == ".png" || ext == ".txt")
|
||
{
|
||
try { File.Delete(file); } catch { }
|
||
}
|
||
}
|
||
}
|
||
catch { }
|
||
}
|
||
}
|
||
}
|
||
|