確実にダウンロードできるように

This commit is contained in:
armonica committed 2026-09-11 10:22:25 +09:00
1 parent c0fdf1708a
commit b57b812bbe
14 files changed
+730 -76

No files matched your search

+92 -9
View File
@@ -33,34 +33,117 @@ namespace MusicDownloader.Class
} }
/// <summary> /// <summary>
/// YouTube動画のタイトルから不要な装飾記号を除去し、アーティスト名と曲名を推測・抽出する /// YouTubeチャンネル名(アップローダー名)から「 - Topic」などの自動付与サフィックスを除去・整形する
/// </summary>
public static string CleanChannelName(string? uploader)
{
if (string.IsNullOrWhiteSpace(uploader)) return "";
var clean = uploader.Trim();
// "xxx - Topic" や "xxx - トピック" の除去
clean = Regex.Replace(clean, @"\s*[-–—]\s*(?:Topic|トピック)$", "", RegexOptions.IgnoreCase).Trim();
// "xxx Official Channel" などの除去
clean = Regex.Replace(clean, @"\s*(?:Official\s*Channel|Official|公式)$", "", RegexOptions.IgnoreCase).Trim();
return clean;
}
/// <summary>
/// 動画タイトルから不要な装飾記号・タグ文字列を除去する
/// </summary>
public static string CleanVideoTitle(string rawTitle)
{
if (string.IsNullOrWhiteSpace(rawTitle)) return "";
var cleaned = rawTitle;
// 【MV】, [Official Video], (Audio), 【オリジナル曲】などの装飾カッコを除去
cleaned = Regex.Replace(cleaned, @"(?i)[\(\[\{【「『](?:MV|Music\s*Video|Official(?:\s*Music\s*Video|\s*Video|\s*Audio)?|Audio|Full|Cover|歌ってみた|オリジナル(?:曲)?|HQ|HD|4K|Lyric(?:\s*Video)?|Short\s*ver|Special\s*ver)[^\]\)\}】」』]*[\)\]\}】」』]", "", RegexOptions.Compiled).Trim();
// カッコ外に残った "Official Music Video" 等の単独テキストを除去
cleaned = Regex.Replace(cleaned, @"(?i)\b(?:Official\s*Music\s*Video|Official\s*Video|Official\s*Audio|Music\s*Video)\b", "", RegexOptions.Compiled).Trim();
// 末尾や先頭に残った不要なハイフンやスラッシュを除去
cleaned = Regex.Replace(cleaned, @"^[\s\-–—//||]+|[\s\-–—//||]+$", "", RegexOptions.Compiled).Trim();
return cleaned;
}
/// <summary>
/// YouTube動画のタイトルとアップローダー名から、アーティスト名と曲名を高度に推測・抽出する
/// </summary> /// </summary>
public static (string Artist, string Title) ParseArtistAndTitle(string rawTitle, string uploader) public static (string Artist, string Title) ParseArtistAndTitle(string rawTitle, string uploader)
{ {
var cleanUploader = CleanChannelName(uploader);
if (string.IsNullOrWhiteSpace(rawTitle)) if (string.IsNullOrWhiteSpace(rawTitle))
{ {
return (uploader, "Unknown"); return (!string.IsNullOrWhiteSpace(cleanUploader) ? cleanUploader : "Unknown", "Unknown");
} }
// 【MV】, [Official Video], (Audio), 【オリジナル曲】などの装飾文字を除去 // 1. カッコによる曲名囲みパターン: アーティスト「曲名」 または アーティスト『曲名』
var cleaned = Regex.Replace(rawTitle, @"(?i)[\(\[\{【「『](?:MV|Music Video|Official|Audio|Full|Cover|歌ってみた|オリジナル|HQ|HD|4K)[^\]\)\}】」』]*[\)\]\}】」』]", "", RegexOptions.Compiled).Trim(); var bracketMatch = Regex.Match(rawTitle, @"^(.*?)\s*[「『""]([^「『""」』]+)[」』""]\s*(.*)$", RegexOptions.Compiled);
cleaned = Regex.Replace(cleaned, @"(?i)(?:MV|Music Video|Official Video|Official Audio)", "", RegexOptions.Compiled).Trim(); if (bracketMatch.Success)
{
var candidateArtist = bracketMatch.Groups[1].Value.Trim();
var candidateTitle = bracketMatch.Groups[2].Value.Trim();
// "Artist - Title" または "Artist / Title" の形式を判定 candidateArtist = CleanVideoTitle(candidateArtist);
var match = Regex.Match(cleaned, @"^(.*?)\s*[-–—//]\s*(.*)$", RegexOptions.Compiled); candidateTitle = CleanVideoTitle(candidateTitle);
// アーティスト候補が空の場合、アップローダーを適用
if (string.IsNullOrWhiteSpace(candidateArtist) && !string.IsNullOrWhiteSpace(cleanUploader))
{
candidateArtist = cleanUploader;
}
if (!string.IsNullOrWhiteSpace(candidateArtist) && !string.IsNullOrWhiteSpace(candidateTitle))
{
return (candidateArtist, candidateTitle);
}
}
// 2. 装飾記号を除去したクリーンタイトルを生成
var cleaned = CleanVideoTitle(rawTitle);
// 3. 区切り記号(ハイフン、スラッシュ、パイプ等)で分割判定
var match = Regex.Match(cleaned, @"^(.*?)\s*[-–—//||]\s*(.*)$", RegexOptions.Compiled);
if (match.Success) if (match.Success)
{ {
var part1 = match.Groups[1].Value.Trim(); var part1 = match.Groups[1].Value.Trim();
var part2 = match.Groups[2].Value.Trim(); var part2 = match.Groups[2].Value.Trim();
if (!string.IsNullOrEmpty(part1) && !string.IsNullOrEmpty(part2)) if (!string.IsNullOrEmpty(part1) && !string.IsNullOrEmpty(part2))
{
// part1 と part2 のどちらがアーティストかを判定
// チャンネル名と照合
if (!string.IsNullOrWhiteSpace(cleanUploader))
{
// part2 がチャンネル名と一致する場合 -> 「曲名 - アーティスト」パターン
if (part2.Equals(cleanUploader, StringComparison.OrdinalIgnoreCase) ||
part2.Contains(cleanUploader, StringComparison.OrdinalIgnoreCase))
{
return (cleanUploader, part1);
}
// part1 がチャンネル名と一致する場合 -> 「アーティスト - 曲名」パターン
if (part1.Equals(cleanUploader, StringComparison.OrdinalIgnoreCase) ||
part1.Contains(cleanUploader, StringComparison.OrdinalIgnoreCase))
{ {
return (part1, part2); return (part1, part2);
} }
} }
// 区切りがない場合はアップローダーをアーティストとし、タイトルを曲名とする // 既定では「Artist - Title」と仮定
return (!string.IsNullOrWhiteSpace(uploader) ? uploader : "Unknown", string.IsNullOrWhiteSpace(cleaned) ? rawTitle : cleaned); return (part1, part2);
}
}
// 4. 区切りがない場合はアップローダーをアーティスト、タイトルを曲名とする
var finalArtist = !string.IsNullOrWhiteSpace(cleanUploader) ? cleanUploader : "Unknown";
var finalTitle = !string.IsNullOrWhiteSpace(cleaned) ? cleaned : rawTitle;
return (finalArtist, finalTitle);
} }
/// <summary> /// <summary>
@@ -26,6 +26,18 @@ namespace MusicDownloader.Class.Downloader
[JsonPropertyName("uploader")] [JsonPropertyName("uploader")]
public string? Uploader { get; set; } 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")] [JsonPropertyName("duration")]
public double? Duration { get; set; } public double? Duration { get; set; }
@@ -78,17 +90,19 @@ namespace MusicDownloader.Class.Downloader
} }
/// <summary> /// <summary>
/// yt-dlpを用いたYouTubeダウンロードおよびメタデータ/歌詞付与を行うクラス /// 高音質変換・外部検索メタデータ付与・歌詞連携を行うダウンロード処理クラス
/// </summary> /// </summary>
public class YoutubeDownloader public class YoutubeDownloader
{ {
private readonly string _ytDlpPath; private readonly string _ytDlpPath;
private readonly LyricsManager _lyricsManager; private readonly LyricsManager _lyricsManager;
private readonly MusicMetadataClient _metadataClient;
public YoutubeDownloader(string ytDlpPath, LyricsManager lyricsManager) public YoutubeDownloader(string ytDlpPath, LyricsManager lyricsManager, MusicMetadataClient metadataClient)
{ {
_ytDlpPath = ytDlpPath; _ytDlpPath = ytDlpPath;
_lyricsManager = lyricsManager; _lyricsManager = lyricsManager;
_metadataClient = metadataClient;
} }
/// <summary> /// <summary>
@@ -123,7 +137,7 @@ namespace MusicDownloader.Class.Downloader
} }
/// <summary> /// <summary>
/// プレイリスト全体のダウンロードおよび歌詞・メタデータ処理を実行する /// プレイリスト全体のダウンロードおよびメタデータ・歌詞付与を実行する
/// </summary> /// </summary>
public async Task ProcessPlaylistAsync(string playlistUrl, string outputBaseDir) public async Task ProcessPlaylistAsync(string playlistUrl, string outputBaseDir)
{ {
@@ -155,7 +169,7 @@ namespace MusicDownloader.Class.Downloader
// 単一動画URLまたはエントリがフラット取得できなかった場合、直接ダウンロード // 単一動画URLまたはエントリがフラット取得できなかった場合、直接ダウンロード
LogManager.AddLog($"プレイリストのエントリが見つからないか単一動画URLです。直接ダウンロードを試行します。"); LogManager.AddLog($"プレイリストのエントリが見つからないか単一動画URLです。直接ダウンロードを試行します。");
await DownloadAndProcessSingleAsync(playlistUrl, 1, 1, targetFolder, sanitizedPlaylistName, null, playlistInfo?.Uploader); await DownloadAndProcessSingleAsync(playlistUrl, 1, 1, targetFolder, sanitizedPlaylistName, null);
return; return;
} }
@@ -173,12 +187,12 @@ namespace MusicDownloader.Class.Downloader
LogManager.AddLog($"--------------------------------------------------------------------------------"); LogManager.AddLog($"--------------------------------------------------------------------------------");
LogManager.AddLog($"[{videoIndex}/{totalCount}] 処理開始: {entry.Title ?? entry.Id}"); LogManager.AddLog($"[{videoIndex}/{totalCount}] 処理開始: {entry.Title ?? entry.Id}");
await DownloadAndProcessSingleAsync(videoUrl, videoIndex, totalCount, targetFolder, sanitizedPlaylistName, entry, playlistInfo?.Uploader); await DownloadAndProcessSingleAsync(videoUrl, videoIndex, totalCount, targetFolder, sanitizedPlaylistName, entry);
// サーバー負荷軽減および確実性のための待機(1.5秒) // サーバー負荷軽減および省メモリ・安定化のためのクールダウン待機(3秒)
await Task.Delay(1500); await Task.Delay(3000);
// 1曲ごとにメモリを速やかに解放(省メモリ化) // 1曲ごとに不要メモリを速やかに解放(省メモリ化)
GC.Collect(1, GCCollectionMode.Optimized, false); GC.Collect(1, GCCollectionMode.Optimized, false);
} }
@@ -188,14 +202,16 @@ namespace MusicDownloader.Class.Downloader
LogManager.AddSuccess($"================================================================================"); LogManager.AddSuccess($"================================================================================");
} }
/// <summary>
/// 1曲のダウンロード・高音質Opus変換・外部楽曲メタデータ解決・タグ付与を実行する
/// </summary>
private async Task DownloadAndProcessSingleAsync( private async Task DownloadAndProcessSingleAsync(
string videoUrl, string videoUrl,
uint index, uint index,
uint totalCount, uint totalCount,
string targetFolder, string targetFolder,
string playlistName, string playlistName,
YtPlaylistEntry? entryInfo, YtPlaylistEntry? entryInfo)
string? playlistUploader)
{ {
var archiveFile = Path.Combine(targetFolder, "archive.txt"); var archiveFile = Path.Combine(targetFolder, "archive.txt");
var filePrefix = $"{index:D2} - "; var filePrefix = $"{index:D2} - ";
@@ -203,11 +219,19 @@ namespace MusicDownloader.Class.Downloader
// 出力ファイル名テンプレート // 出力ファイル名テンプレート
var outputTemplate = Path.Combine(targetFolder, $"{filePrefix}%(title)s.%(ext)s"); 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> var arguments = new List<string>
{ {
"-f", "bestaudio/best",
"--extract-audio", "--extract-audio",
"--audio-format", "opus", "--audio-format", "opus",
"--audio-quality", "0", "--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", "--write-thumbnail",
"--convert-thumbnails", "jpg", "--convert-thumbnails", "jpg",
"--write-subs", "--write-subs",
@@ -217,13 +241,14 @@ namespace MusicDownloader.Class.Downloader
"--no-abort-on-error", "--no-abort-on-error",
"--retries", "10", "--retries", "10",
"--fragment-retries", "10", "--fragment-retries", "10",
"--retry-sleep", "3",
"--download-archive", archiveFile, "--download-archive", archiveFile,
"-o", outputTemplate, "-o", outputTemplate,
"--no-warnings", "--no-warnings",
videoUrl videoUrl
}; };
LogManager.AddLog($"ダウンロード実行中 (yt-dlp)..."); LogManager.AddLog($"ダウンロード&高音質変換実行中 (yt-dlp)...");
try try
{ {
var cmdResult = await Cli.Wrap(_ytDlpPath) var cmdResult = await Cli.Wrap(_ytDlpPath)
@@ -259,16 +284,85 @@ namespace MusicDownloader.Class.Downloader
var targetOpus = opusFiles.OrderByDescending(f => File.GetLastWriteTime(f)).First(); var targetOpus = opusFiles.OrderByDescending(f => File.GetLastWriteTime(f)).First();
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(targetOpus); var fileNameWithoutExt = Path.GetFileNameWithoutExtension(targetOpus);
// 曲名とアーティスト名の正確な判定 // 音声ファイルの整合性検証(ブツブツ・破損チェック)
await VerifyAudioIntegrityAsync(targetOpus);
// -------------------------------------------------------------
// メタデータ(曲名・アーティスト・アルバム・アルバムアーティスト)の決定
// -------------------------------------------------------------
var rawTitle = fileNameWithoutExt.StartsWith(filePrefix) ? fileNameWithoutExt.Substring(filePrefix.Length) : fileNameWithoutExt; 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 : rawTitle;
var uploader = entryInfo?.Uploader ?? ""; var uploader = !string.IsNullOrWhiteSpace(entryInfo?.Channel) ? entryInfo.Channel : (entryInfo?.Uploader ?? "");
var (artist, title) = CmnUtil.ParseArtistAndTitle(baseTitle, uploader);
// サムネイル画像の検索 // 1. タイトル文字列の初期パース
var thumbJpg = Path.ChangeExtension(targetOpus, ".jpg"); var (initialArtist, initialTitle) = CmnUtil.ParseArtistAndTitle(baseTitle, uploader);
string? thumbnailToUse = File.Exists(thumbJpg) ? thumbJpg : null;
// 2. yt-dlp の公式トラック/アーティストメタデータが存在すれば優先
if (!string.IsNullOrWhiteSpace(entryInfo?.Track))
{
initialTitle = entryInfo.Track;
}
if (!string.IsNullOrWhiteSpace(entryInfo?.Artist))
{
initialArtist = entryInfo.Artist;
}
LogManager.AddLog($"解析候補: [アーティスト: {initialArtist}] [曲名: {initialTitle}]");
// 3. 外部楽曲検索API (iTunes / LRCLIB) を呼び出して正確な公式メタデータを解決
string finalTitle = initialTitle;
string finalArtist = initialArtist;
string finalAlbum = !string.IsNullOrWhiteSpace(entryInfo?.Album) ? entryInfo.Album : playlistName;
string finalAlbumArtist = initialArtist; // 既定は楽曲のアーティスト
uint? finalYear = entryInfo?.GetYear();
string? downloadArtworkPath = null;
var resolvedMeta = await _metadataClient.ResolveMetadataAsync(
rawVideoTitle: baseTitle,
uploader: uploader,
parsedArtist: initialArtist,
parsedTitle: initialTitle,
durationSeconds: entryInfo?.Duration);
if (resolvedMeta != null)
{
finalTitle = resolvedMeta.Title;
finalArtist = resolvedMeta.Artist;
if (!string.IsNullOrWhiteSpace(resolvedMeta.Album))
{
finalAlbum = resolvedMeta.Album;
}
if (!string.IsNullOrWhiteSpace(resolvedMeta.AlbumArtist))
{
finalAlbumArtist = resolvedMeta.AlbumArtist;
}
if (resolvedMeta.Year.HasValue && resolvedMeta.Year.Value > 0)
{
finalYear = resolvedMeta.Year.Value;
}
// 高画質カバー画像が存在すればダウンロードして適用
if (!string.IsNullOrWhiteSpace(resolvedMeta.ArtworkUrl))
{
var highResArtPath = Path.Combine(targetFolder, $"{filePrefix}itunes_cover.jpg");
var downloadedArt = await _metadataClient.DownloadArtworkAsync(resolvedMeta.ArtworkUrl, highResArtPath);
if (downloadedArt != null)
{
downloadArtworkPath = downloadedArt;
}
}
}
// サムネイル画像の決定(高画質公式アートワーク > YouTubeサムネイル)
string? thumbnailToUse = downloadArtworkPath;
if (thumbnailToUse == null) if (thumbnailToUse == null)
{
var thumbJpg = Path.ChangeExtension(targetOpus, ".jpg");
if (File.Exists(thumbJpg))
{
thumbnailToUse = thumbJpg;
}
else
{ {
var prefixJpgs = Directory.GetFiles(targetFolder, $"{filePrefix}*.jpg"); var prefixJpgs = Directory.GetFiles(targetFolder, $"{filePrefix}*.jpg");
if (prefixJpgs.Length > 0) if (prefixJpgs.Length > 0)
@@ -276,26 +370,24 @@ namespace MusicDownloader.Class.Downloader
thumbnailToUse = prefixJpgs[0]; thumbnailToUse = prefixJpgs[0];
} }
} }
}
// 歌詞処理 (.lrc作成および歌詞テキスト取得) // 歌詞処理 (.lrc作成および歌詞テキスト取得)
var lyrics = await _lyricsManager.ProcessLyricsAsync(targetOpus, title, artist, entryInfo?.Duration, targetFolder, filePrefix); var lyrics = await _lyricsManager.ProcessLyricsAsync(targetOpus, finalTitle, finalArtist, entryInfo?.Duration, targetFolder, filePrefix);
// 公開年(リリース年)の取得 // メタデータ (TagLibSharp) の書き込み(正確な曲名・アーティスト・アルバム・アルバムアーティスト)
var year = entryInfo?.GetYear();
// メタデータ (TagLibSharp) の書き込み(完全なメタデータ埋め込み)
AudioTagManager.ApplyMetadata( AudioTagManager.ApplyMetadata(
opusPath: targetOpus, opusPath: targetOpus,
title: title, title: finalTitle,
artist: artist, artist: finalArtist,
album: playlistName, album: finalAlbum,
trackNumber: index, trackNumber: index,
trackCount: totalCount, trackCount: totalCount,
year: year, year: finalYear,
lyrics: lyrics, lyrics: lyrics,
thumbnailPath: thumbnailToUse, thumbnailPath: thumbnailToUse,
comment: videoUrl, comment: videoUrl,
albumArtist: playlistUploader); albumArtist: finalAlbumArtist);
// プレイリスト代表カバー画像として cover.jpg が存在しなければコピー // プレイリスト代表カバー画像として cover.jpg が存在しなければコピー
var albumCoverPath = Path.Combine(targetFolder, "cover.jpg"); var albumCoverPath = Path.Combine(targetFolder, "cover.jpg");
@@ -308,21 +400,55 @@ namespace MusicDownloader.Class.Downloader
catch { } catch { }
} }
// 不要な中間ファイル(.vttファイル)のクリーンアップ // 一時ファイル(.vtt, 一時画像等)のクリーンアップ
CleanupTempFiles(targetFolder, filePrefix); CleanupTempFiles(targetFolder, filePrefix);
LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {Path.GetFileName(targetOpus)}"); LogManager.AddSuccess($"[{index}/{totalCount}] 完了: {Path.GetFileName(targetOpus)}");
} }
/// <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>
/// 中間一時ファイル(.vtt, .part, 一時画像)を削除
/// </summary>
private void CleanupTempFiles(string folder, string? prefix = null) private void CleanupTempFiles(string folder, string? prefix = null)
{ {
try try
{ {
var searchPattern = !string.IsNullOrEmpty(prefix) ? $"{prefix}*.vtt" : "*.vtt"; var searchPattern = !string.IsNullOrEmpty(prefix) ? $"{prefix}*" : "*";
var vttFiles = Directory.GetFiles(folder, searchPattern); var files = Directory.GetFiles(folder, searchPattern);
foreach (var vtt in vttFiles) foreach (var file in files)
{ {
try { File.Delete(vtt); } catch { } var ext = Path.GetExtension(file).ToLowerInvariant();
if (ext == ".vtt" || ext == ".part" || ext == ".ytdl" || file.EndsWith("itunes_cover.jpg"))
{
try { File.Delete(file); } catch { }
}
} }
} }
catch { } catch { }
@@ -4,7 +4,7 @@ using System.IO;
namespace MusicDownloader.Class.Metadata namespace MusicDownloader.Class.Metadata
{ {
/// <summary> /// <summary>
/// TagLibSharpを用いてOpusファイルにメタデータ・歌詞・カバーアートを埋め込むクラス /// TagLibSharpを用いてOpusファイルにメタデータ・歌詞・カバーアートを正確に埋め込むクラス
/// </summary> /// </summary>
public static class AudioTagManager public static class AudioTagManager
{ {
@@ -37,8 +37,16 @@ namespace MusicDownloader.Class.Metadata
// 基本タグの設定 // 基本タグの設定
file.Tag.Title = title; file.Tag.Title = title;
file.Tag.Performers = new[] { artist }; file.Tag.Performers = new[] { artist };
file.Tag.AlbumArtists = new[] { !string.IsNullOrWhiteSpace(albumArtist) ? albumArtist : artist };
file.Tag.Album = album; // アルバムアーティストの正確な決定(空や異常値の場合は楽曲のアーティストを適用)
var resolvedAlbumArtist = (!string.IsNullOrWhiteSpace(albumArtist) && albumArtist != "Unknown")
? albumArtist
: artist;
file.Tag.AlbumArtists = new[] { resolvedAlbumArtist };
// アルバム名の設定
file.Tag.Album = !string.IsNullOrWhiteSpace(album) ? album : title;
file.Tag.Track = trackNumber; file.Tag.Track = trackNumber;
file.Tag.TrackCount = trackCount; file.Tag.TrackCount = trackCount;
@@ -68,7 +76,8 @@ namespace MusicDownloader.Class.Metadata
var pic = new TagLib.Picture(thumbnailPath) var pic = new TagLib.Picture(thumbnailPath)
{ {
Type = TagLib.PictureType.FrontCover, Type = TagLib.PictureType.FrontCover,
Description = "Cover" Description = "Cover",
MimeType = "image/jpeg"
}; };
file.Tag.Pictures = new TagLib.IPicture[] { pic }; file.Tag.Pictures = new TagLib.IPicture[] { pic };
} }
@@ -80,7 +89,7 @@ namespace MusicDownloader.Class.Metadata
file.Save(); file.Save();
var yearStr = (year.HasValue && year.Value > 0) ? $" ({year.Value}年)" : ""; var yearStr = (year.HasValue && year.Value > 0) ? $" ({year.Value}年)" : "";
LogManager.AddSuccess($"メタデータを埋め込みました: 「{artist} - {title}」{yearStr} [Track {trackNumber}/{trackCount}]"); LogManager.AddSuccess($"メタデータを埋め込みました: 「{artist} - {title}」{yearStr} [アルバム: {file.Tag.Album} / アルバムアーティスト: {resolvedAlbumArtist}] (Track {trackNumber}/{trackCount})");
return true; return true;
} }
catch (Exception ex) catch (Exception ex)
@@ -0,0 +1,393 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace MusicDownloader.Class.Metadata
{
/// <summary>
/// 検索によって特定された確定楽曲メタデータ
/// </summary>
public class SongMetadataResult
{
/// <summary>曲名</summary>
public string Title { get; set; } = "";
/// <summary>アーティスト名</summary>
public string Artist { get; set; } = "";
/// <summary>アルバム名</summary>
public string Album { get; set; } = "";
/// <summary>アルバムアーティスト名</summary>
public string AlbumArtist { get; set; } = "";
/// <summary>リリース年</summary>
public uint? Year { get; set; }
/// <summary>高解像度カバー画像URL</summary>
public string? ArtworkUrl { get; set; }
/// <summary>再生時間(秒)</summary>
public double? DurationSeconds { get; set; }
}
/// <summary>
/// iTunes Search API レスポンスモデル
/// </summary>
public class ITunesSearchResponse
{
[JsonPropertyName("resultCount")]
public int ResultCount { get; set; }
[JsonPropertyName("results")]
public List<ITunesSongItem>? Results { get; set; }
}
/// <summary>
/// iTunes 楽曲アイテムモデル
/// </summary>
public class ITunesSongItem
{
[JsonPropertyName("trackName")]
public string? TrackName { get; set; }
[JsonPropertyName("artistName")]
public string? ArtistName { get; set; }
[JsonPropertyName("collectionName")]
public string? CollectionName { get; set; }
[JsonPropertyName("collectionArtistName")]
public string? CollectionArtistName { get; set; }
[JsonPropertyName("releaseDate")]
public string? ReleaseDate { get; set; }
[JsonPropertyName("artworkUrl100")]
public string? ArtworkUrl100 { get; set; }
[JsonPropertyName("trackTimeMillis")]
public long? TrackTimeMillis { get; set; }
}
/// <summary>
/// iTunes Search API および LRCLIB を用いた楽曲メタデータ検索クライアント
/// </summary>
public class MusicMetadataClient
{
private readonly HttpClient _httpClient;
public MusicMetadataClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
/// <summary>
/// 動画タイトル、アップローダー名、推測された曲名/アーティスト情報から公式楽曲メタデータを検索・補正する
/// </summary>
public async Task<SongMetadataResult?> ResolveMetadataAsync(
string rawVideoTitle,
string uploader,
string parsedArtist,
string parsedTitle,
double? durationSeconds)
{
// 1. 検索クエリのバリエーションを生成
var searchQueries = BuildSearchQueries(rawVideoTitle, uploader, parsedArtist, parsedTitle);
// 2. iTunes Search API で検索
foreach (var query in searchQueries)
{
var iTunesResult = await SearchITunesAsync(query, parsedArtist, parsedTitle, durationSeconds);
if (iTunesResult != null)
{
LogManager.AddSuccess($"iTunes楽曲データベースと一致しました: 「{iTunesResult.Artist} - {iTunesResult.Title}」 (アルバム: {iTunesResult.Album})");
return iTunesResult;
}
}
// 3. iTunesで見つからなかった場合、LRCLIBの検索APIでフォールバック検索
foreach (var query in searchQueries.Take(3))
{
var lrcResult = await SearchLrcLibAsync(query, durationSeconds);
if (lrcResult != null)
{
LogManager.AddSuccess($"LRCLIB楽曲データベースと一致しました: 「{lrcResult.Artist} - {lrcResult.Title}」 (アルバム: {lrcResult.Album})");
return lrcResult;
}
}
return null;
}
/// <summary>
/// 検索用のクエリリストを優先順位順に組み立てる
/// </summary>
private List<string> BuildSearchQueries(string rawVideoTitle, string uploader, string parsedArtist, string parsedTitle)
{
var list = new List<string>();
// クリーンアップされたアップローダー名(- Topic 等を除去)
var cleanUploader = CmnUtil.CleanChannelName(uploader);
// A. パースされた "Artist Title" または "Title Artist"
if (!string.IsNullOrWhiteSpace(parsedArtist) && !string.IsNullOrWhiteSpace(parsedTitle) &&
parsedArtist != "Unknown" && parsedTitle != "Unknown")
{
list.Add($"{parsedArtist} {parsedTitle}");
list.Add($"{parsedTitle} {parsedArtist}");
}
// B. チャンネル名 + パースされた曲名
if (!string.IsNullOrWhiteSpace(cleanUploader) && !string.IsNullOrWhiteSpace(parsedTitle) &&
cleanUploader != parsedArtist && parsedTitle != "Unknown")
{
list.Add($"{cleanUploader} {parsedTitle}");
}
// C. カッコ等で囲まれたタイトル部分の抽出(「...」や『...』)
var bracketMatch = Regex.Match(rawVideoTitle, @"[「『""]([^「『""」』]+)[」』""]");
if (bracketMatch.Success)
{
var insideTitle = bracketMatch.Groups[1].Value.Trim();
if (!string.IsNullOrWhiteSpace(cleanUploader))
{
list.Add($"{cleanUploader} {insideTitle}");
}
list.Add(insideTitle);
}
// D. 装飾記号を除去した動画タイトル全体
var cleanedTitle = CmnUtil.CleanVideoTitle(rawVideoTitle);
if (!string.IsNullOrWhiteSpace(cleanedTitle))
{
list.Add(cleanedTitle);
}
// 重複排除
return list.Where(q => !string.IsNullOrWhiteSpace(q))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
}
/// <summary>
/// iTunes Search API を呼び出して最適な曲を判定
/// </summary>
private async Task<SongMetadataResult?> SearchITunesAsync(
string query,
string expectedArtist,
string expectedTitle,
double? expectedDuration)
{
try
{
var url = $"https://itunes.apple.com/search?term={Uri.EscapeDataString(query)}&country=jp&entity=song&limit=8";
using var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.UserAgent.ParseAdd(CmnDefine.UserAgent);
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode) return null;
var json = await response.Content.ReadAsStringAsync();
var searchResponse = JsonSerializer.Deserialize<ITunesSearchResponse>(json);
if (searchResponse?.Results == null || searchResponse.Results.Count == 0) return null;
// 検索結果から最も一致度の高い曲をスコアリングして選出
ITunesSongItem? bestMatch = null;
int highestScore = -1;
foreach (var item in searchResponse.Results)
{
if (string.IsNullOrWhiteSpace(item.TrackName) || string.IsNullOrWhiteSpace(item.ArtistName))
continue;
var score = CalculateMatchScore(item, query, expectedArtist, expectedTitle, expectedDuration);
if (score > highestScore && score >= 30) // 最低限の適合閾値
{
highestScore = score;
bestMatch = item;
}
}
if (bestMatch != null)
{
uint? year = null;
if (!string.IsNullOrWhiteSpace(bestMatch.ReleaseDate) && bestMatch.ReleaseDate.Length >= 4)
{
if (uint.TryParse(bestMatch.ReleaseDate.Substring(0, 4), out var y)) year = y;
}
// 100x100 のサムネイルURLを高画質 (1000x1000) に置換
var artworkUrl = bestMatch.ArtworkUrl100;
if (!string.IsNullOrWhiteSpace(artworkUrl) && artworkUrl.Contains("100x100bb.jpg"))
{
artworkUrl = artworkUrl.Replace("100x100bb.jpg", "1000x1000bb.jpg");
}
var albumArtist = !string.IsNullOrWhiteSpace(bestMatch.CollectionArtistName)
? bestMatch.CollectionArtistName
: bestMatch.ArtistName;
return new SongMetadataResult
{
Title = bestMatch.TrackName ?? expectedTitle,
Artist = bestMatch.ArtistName ?? expectedArtist,
Album = bestMatch.CollectionName ?? (!string.IsNullOrWhiteSpace(bestMatch.TrackName) ? bestMatch.TrackName : "Single"),
AlbumArtist = albumArtist ?? bestMatch.ArtistName ?? expectedArtist,
Year = year,
ArtworkUrl = artworkUrl,
DurationSeconds = bestMatch.TrackTimeMillis.HasValue ? bestMatch.TrackTimeMillis.Value / 1000.0 : null
};
}
}
catch (Exception ex)
{
LogManager.AddWarning($"iTunes検索中にエラー (query: {query}): {ex.Message}");
}
return null;
}
/// <summary>
/// LRCLIB API を用いたフォールバック検索
/// </summary>
private async Task<SongMetadataResult?> SearchLrcLibAsync(string query, double? expectedDuration)
{
try
{
var url = $"{CmnDefine.LrcLibBaseUrl}/api/search?q={Uri.EscapeDataString(query)}";
using var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.UserAgent.ParseAdd(CmnDefine.UserAgent);
var response = await _httpClient.SendAsync(request);
if (!response.IsSuccessStatusCode) return null;
var json = await response.Content.ReadAsStringAsync();
var items = JsonSerializer.Deserialize<Class.Lyrics.LrcLibResponse[]>(json);
if (items == null || items.Length == 0) return null;
// 再生時間が近い、または完全一致度が高いものを選択
Class.Lyrics.LrcLibResponse? best = null;
double minDiff = double.MaxValue;
foreach (var item in items)
{
if (string.IsNullOrWhiteSpace(item.TrackName) || string.IsNullOrWhiteSpace(item.ArtistName))
continue;
if (expectedDuration.HasValue && item.Duration.HasValue && item.Duration.Value > 0)
{
var diff = Math.Abs(item.Duration.Value - expectedDuration.Value);
if (diff < minDiff)
{
minDiff = diff;
best = item;
}
}
else
{
best = item;
break;
}
}
if (best != null && (!expectedDuration.HasValue || minDiff <= 10.0))
{
return new SongMetadataResult
{
Title = best.TrackName!,
Artist = best.ArtistName!,
Album = !string.IsNullOrWhiteSpace(best.AlbumName) ? best.AlbumName : best.TrackName!,
AlbumArtist = best.ArtistName!,
Year = null,
DurationSeconds = best.Duration
};
}
}
catch { }
return null;
}
/// <summary>
/// 検索候補の一致度スコアリング
/// </summary>
private int CalculateMatchScore(
ITunesSongItem item,
string query,
string expectedArtist,
string expectedTitle,
double? expectedDuration)
{
int score = 0;
var tName = item.TrackName ?? "";
var aName = item.ArtistName ?? "";
// 曲名の一致判定
if (!string.IsNullOrWhiteSpace(expectedTitle))
{
if (string.Equals(tName, expectedTitle, StringComparison.OrdinalIgnoreCase)) score += 50;
else if (tName.Contains(expectedTitle, StringComparison.OrdinalIgnoreCase) ||
expectedTitle.Contains(tName, StringComparison.OrdinalIgnoreCase)) score += 30;
}
// アーティスト名の一致判定
if (!string.IsNullOrWhiteSpace(expectedArtist))
{
if (string.Equals(aName, expectedArtist, StringComparison.OrdinalIgnoreCase)) score += 50;
else if (aName.Contains(expectedArtist, StringComparison.OrdinalIgnoreCase) ||
expectedArtist.Contains(aName, StringComparison.OrdinalIgnoreCase)) score += 30;
}
// クエリ全体との含有判定
if (query.Contains(tName, StringComparison.OrdinalIgnoreCase)) score += 20;
if (query.Contains(aName, StringComparison.OrdinalIgnoreCase)) score += 20;
// 再生時間の近似判定(±6秒以内なら高スコア)
if (expectedDuration.HasValue && item.TrackTimeMillis.HasValue)
{
var itemDurSec = item.TrackTimeMillis.Value / 1000.0;
var diff = Math.Abs(itemDurSec - expectedDuration.Value);
if (diff <= 3.0) score += 30;
else if (diff <= 6.0) score += 15;
else if (diff > 30.0) score -= 20; // 30秒以上乖離している場合は減点
}
return score;
}
/// <summary>
/// カバー画像URLから画像をダウンロードして一時ファイルに保存する
/// </summary>
public async Task<string?> DownloadArtworkAsync(string artworkUrl, string destFilePath)
{
if (string.IsNullOrWhiteSpace(artworkUrl)) return null;
try
{
using var request = new HttpRequestMessage(HttpMethod.Get, artworkUrl);
request.Headers.UserAgent.ParseAdd(CmnDefine.UserAgent);
var response = await _httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var bytes = await response.Content.ReadAsByteArrayAsync();
await File.WriteAllBytesAsync(destFilePath, bytes);
return destFilePath;
}
}
catch (Exception ex)
{
LogManager.AddWarning($"カバー画像ダウンロードに失敗しました ({artworkUrl}): {ex.Message}");
}
return null;
}
}
}
+2
View File
@@ -27,6 +27,8 @@
<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: ドライブのマウント保証 -->
<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;" />
<!-- 配置先ディレクトリ 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共通対応) -->
+30 -11
View File
@@ -8,6 +8,7 @@ using Microsoft.Extensions.DependencyInjection;
using MusicDownloader.Class; using MusicDownloader.Class;
using MusicDownloader.Class.Downloader; using MusicDownloader.Class.Downloader;
using MusicDownloader.Class.Lyrics; using MusicDownloader.Class.Lyrics;
using MusicDownloader.Class.Metadata;
// ========================================================================= // =========================================================================
// 【設定】ダウンロード対象のYouTubeプレイリストURLリスト // 【設定】ダウンロード対象のYouTubeプレイリストURLリスト
@@ -22,12 +23,15 @@ List<string> defaultPlaylistUrls = new()
"https://www.youtube.com/playlist?list=PLcCVx7FV8UxriKA5suDcZeBoyuK7DFjck" "https://www.youtube.com/playlist?list=PLcCVx7FV8UxriKA5suDcZeBoyuK7DFjck"
}; };
// プレイリストの定期差分チェックを行うかどうか(true: 定期ポーリング、false: 1回完了後に待機/終了) // プレイリストの定期差分チェック常駐設定(デフォルトで常駐・2時間間隔)
bool isPeriodicCheck = false; bool isPeriodicCheck = true;
TimeSpan checkInterval = TimeSpan.FromMinutes(60); var intervalHoursStr = Environment.GetEnvironmentVariable("CHECK_INTERVAL_HOURS");
var checkInterval = (double.TryParse(intervalHoursStr, out var h) && h > 0)
? TimeSpan.FromHours(h)
: TimeSpan.FromHours(2);
// ========================================================================= // =========================================================================
// 未処理例外ハンドリング (rss-generator 同様) // 未処理例外ハンドリング
// ========================================================================= // =========================================================================
AppDomain.CurrentDomain.UnhandledException += (sender, e) => AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
{ {
@@ -61,14 +65,20 @@ services.AddSingleton<LrcLibClient>(sp =>
var factory = sp.GetRequiredService<IHttpClientFactory>(); var factory = sp.GetRequiredService<IHttpClientFactory>();
return new LrcLibClient(factory.CreateClient("webClient")); return new LrcLibClient(factory.CreateClient("webClient"));
}); });
services.AddSingleton<MusicMetadataClient>(sp =>
{
var factory = sp.GetRequiredService<IHttpClientFactory>();
return new MusicMetadataClient(factory.CreateClient("webClient"));
});
services.AddSingleton<LyricsManager>(); services.AddSingleton<LyricsManager>();
var serviceProvider = services.BuildServiceProvider(); var serviceProvider = services.BuildServiceProvider();
var httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>(); var httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>();
var lyricsManager = serviceProvider.GetRequiredService<LyricsManager>(); var lyricsManager = serviceProvider.GetRequiredService<LyricsManager>();
var metadataClient = serviceProvider.GetRequiredService<MusicMetadataClient>();
LogManager.AddLog($"=================================================="); LogManager.AddLog($"==================================================");
LogManager.AddLog($" MusicDownloader (Poweramp Optimized) 起動"); LogManager.AddLog($" MusicDownloader (高音質・正確タグ・常駐版) 起動");
LogManager.AddLog($"=================================================="); LogManager.AddLog($"==================================================");
// 出力先ディレクトリの決定 // 出力先ディレクトリの決定
@@ -80,7 +90,7 @@ using var initClient = httpClientFactory.CreateClient("webClient");
var ytDlpPath = await DependencyManager.EnsureYtDlpAsync(initClient); var ytDlpPath = await DependencyManager.EnsureYtDlpAsync(initClient);
LogManager.AddLog($"使用 yt-dlp パス: {ytDlpPath}"); LogManager.AddLog($"使用 yt-dlp パス: {ytDlpPath}");
var downloader = new YoutubeDownloader(ytDlpPath, lyricsManager); var downloader = new YoutubeDownloader(ytDlpPath, lyricsManager, metadataClient);
// ========================================================================= // =========================================================================
// ダウンロード対象プレイリストの解決 // ダウンロード対象プレイリストの解決
@@ -147,19 +157,24 @@ List<string> ResolveTargetPlaylists(string baseDir)
} }
// ========================================================================= // =========================================================================
// ダウンロード処理ループ // ダウンロード処理ループ(①曲の取得 ➔ ②2時間待機 ➔ ③①へ戻る)
// ========================================================================= // =========================================================================
int loopCount = 0;
while (true) while (true)
{ {
loopCount++;
var targetPlaylists = ResolveTargetPlaylists(outputDir); var targetPlaylists = ResolveTargetPlaylists(outputDir);
LogManager.AddLog($"対象プレイリスト総数: {targetPlaylists.Count} 件"); LogManager.AddLog($"================================================================================");
LogManager.AddLog($"[第 {loopCount} 回実行] 対象プレイリスト総数: {targetPlaylists.Count} 件のチェックを開始します");
LogManager.AddLog($"================================================================================");
for (int p = 0; p < targetPlaylists.Count; p++) for (int p = 0; p < targetPlaylists.Count; p++)
{ {
var playlistUrl = targetPlaylists[p]; var playlistUrl = targetPlaylists[p];
LogManager.AddLog($"================================================================================"); LogManager.AddLog($"--------------------------------------------------------------------------------");
LogManager.AddLog($"[プレイリスト {p + 1}/{targetPlaylists.Count}] 処理開始: {playlistUrl}"); LogManager.AddLog($"[プレイリスト {p + 1}/{targetPlaylists.Count}] 処理開始: {playlistUrl}");
LogManager.AddLog($"================================================================================"); LogManager.AddLog($"--------------------------------------------------------------------------------");
try try
{ {
@@ -182,6 +197,10 @@ while (true)
} }
var nextRunTime = DateTime.Now.Add(checkInterval); var nextRunTime = DateTime.Now.Add(checkInterval);
LogManager.AddLog($"次回チェック予定: {nextRunTime:yyyy-MM-dd HH:mm:ss} ({checkInterval.TotalMinutes}分後)"); LogManager.AddSuccess($"================================================================================");
LogManager.AddSuccess($"全プレイリストのチェックが完了しました。次回実行まで {checkInterval.TotalHours:0.#} 時間待機します。");
LogManager.AddSuccess($"次回実行予定: {nextRunTime:yyyy-MM-dd HH:mm:ss}");
LogManager.AddSuccess($"================================================================================");
await Task.Delay(checkInterval); await Task.Delay(checkInterval);
} }
@@ -13,7 +13,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("MusicDownloader")] [assembly: System.Reflection.AssemblyCompanyAttribute("MusicDownloader")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+be6183f05e9d9fbda85b7d3b7e659fc9b11a1bc1")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+c0fdf1708a8b2c265224253be801c8f0d7fc3b3e")]
[assembly: System.Reflection.AssemblyProductAttribute("MusicDownloader")] [assembly: System.Reflection.AssemblyProductAttribute("MusicDownloader")]
[assembly: System.Reflection.AssemblyTitleAttribute("MusicDownloader")] [assembly: System.Reflection.AssemblyTitleAttribute("MusicDownloader")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -11,7 +11,7 @@ build_property.EnforceExtendedAnalyzerRules =
build_property.EntryPointFilePath = build_property.EntryPointFilePath =
build_property._SupportedPlatformList = Linux,macOS,Windows build_property._SupportedPlatformList = Linux,macOS,Windows
build_property.RootNamespace = MusicDownloader build_property.RootNamespace = MusicDownloader
build_property.ProjectDir = c:\VS2026\MusicDownloader\MusicDownloader\ build_property.ProjectDir = C:\VS2026\MusicDownloader\MusicDownloader\
build_property.EnableComHosting = build_property.EnableComHosting =
build_property.EnableGeneratedComInterfaceComImportInterop = build_property.EnableGeneratedComInterfaceComImportInterop =
build_property.EffectiveAnalysisLevelStyle = 10.0 build_property.EffectiveAnalysisLevelStyle = 10.0
@@ -1,17 +1,17 @@
{ {
"format": 1, "format": 1,
"restore": { "restore": {
"c:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj": {} "C:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj": {}
}, },
"projects": { "projects": {
"c:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj": { "C:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj": {
"version": "1.0.0", "version": "1.0.0",
"restore": { "restore": {
"projectUniqueName": "c:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj", "projectUniqueName": "C:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj",
"projectName": "MusicDownloader", "projectName": "MusicDownloader",
"projectPath": "c:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj", "projectPath": "C:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj",
"packagesPath": "C:\\Users\\uduki\\.nuget\\packages\\", "packagesPath": "C:\\Users\\uduki\\.nuget\\packages\\",
"outputPath": "c:\\VS2026\\MusicDownloader\\MusicDownloader\\obj\\", "outputPath": "C:\\VS2026\\MusicDownloader\\MusicDownloader\\obj\\",
"projectStyle": "PackageReference", "projectStyle": "PackageReference",
"fallbackFolders": [ "fallbackFolders": [
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages", "C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages",
@@ -86,7 +86,7 @@
"privateAssets": "all" "privateAssets": "all"
} }
}, },
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\10.0.400/PortableRuntimeIdentifierGraph.json", "runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\10.0.401/PortableRuntimeIdentifierGraph.json",
"packagesToPrune": { "packagesToPrune": {
"Microsoft.CSharp": "(,4.7.32767]", "Microsoft.CSharp": "(,4.7.32767]",
"Microsoft.VisualBasic": "(,10.4.32767]", "Microsoft.VisualBasic": "(,10.4.32767]",
@@ -13,7 +13,7 @@ using System.Reflection;
[assembly: System.Reflection.AssemblyCompanyAttribute("MusicDownloader")] [assembly: System.Reflection.AssemblyCompanyAttribute("MusicDownloader")]
[assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")]
[assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")]
[assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+be6183f05e9d9fbda85b7d3b7e659fc9b11a1bc1")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0+c0fdf1708a8b2c265224253be801c8f0d7fc3b3e")]
[assembly: System.Reflection.AssemblyProductAttribute("MusicDownloader")] [assembly: System.Reflection.AssemblyProductAttribute("MusicDownloader")]
[assembly: System.Reflection.AssemblyTitleAttribute("MusicDownloader")] [assembly: System.Reflection.AssemblyTitleAttribute("MusicDownloader")]
[assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")]
@@ -11,7 +11,7 @@ build_property.EnforceExtendedAnalyzerRules =
build_property.EntryPointFilePath = build_property.EntryPointFilePath =
build_property._SupportedPlatformList = Linux,macOS,Windows build_property._SupportedPlatformList = Linux,macOS,Windows
build_property.RootNamespace = MusicDownloader build_property.RootNamespace = MusicDownloader
build_property.ProjectDir = c:\VS2026\MusicDownloader\MusicDownloader\ build_property.ProjectDir = C:\VS2026\MusicDownloader\MusicDownloader\
build_property.EnableComHosting = build_property.EnableComHosting =
build_property.EnableGeneratedComInterfaceComImportInterop = build_property.EnableGeneratedComInterfaceComImportInterop =
build_property.EffectiveAnalysisLevelStyle = 10.0 build_property.EffectiveAnalysisLevelStyle = 10.0
@@ -0,0 +1,20 @@
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\MusicDownloader.exe
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\MusicDownloader.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\MusicDownloader.deps.json
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\MusicDownloader.runtimeconfig.json
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\MusicDownloader.pdb
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\CliWrap.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Configuration.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Configuration.Abstractions.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Configuration.Binder.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.DependencyInjection.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.DependencyInjection.Abstractions.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Diagnostics.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Diagnostics.Abstractions.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Http.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Logging.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Logging.Abstractions.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Options.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Options.ConfigurationExtensions.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\Microsoft.Extensions.Primitives.dll
C:\VS2026\MusicDownloader\MusicDownloader\bin\Release\net10.0\publish\TagLibSharp.dll
+4 -4
View File
@@ -797,11 +797,11 @@
"project": { "project": {
"version": "1.0.0", "version": "1.0.0",
"restore": { "restore": {
"projectUniqueName": "c:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj", "projectUniqueName": "C:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj",
"projectName": "MusicDownloader", "projectName": "MusicDownloader",
"projectPath": "c:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj", "projectPath": "C:\\VS2026\\MusicDownloader\\MusicDownloader\\MusicDownloader.csproj",
"packagesPath": "C:\\Users\\uduki\\.nuget\\packages\\", "packagesPath": "C:\\Users\\uduki\\.nuget\\packages\\",
"outputPath": "c:\\VS2026\\MusicDownloader\\MusicDownloader\\obj\\", "outputPath": "C:\\VS2026\\MusicDownloader\\MusicDownloader\\obj\\",
"projectStyle": "PackageReference", "projectStyle": "PackageReference",
"fallbackFolders": [ "fallbackFolders": [
"C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages", "C:\\Program Files (x86)\\Microsoft Visual Studio\\Shared\\NuGetPackages",
@@ -876,7 +876,7 @@
"privateAssets": "all" "privateAssets": "all"
} }
}, },
"runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\10.0.400/PortableRuntimeIdentifierGraph.json", "runtimeIdentifierGraphPath": "C:\\Program Files\\dotnet\\sdk\\10.0.401/PortableRuntimeIdentifierGraph.json",
"packagesToPrune": { "packagesToPrune": {
"Microsoft.CSharp": "(,4.7.32767]", "Microsoft.CSharp": "(,4.7.32767]",
"Microsoft.VisualBasic": "(,10.4.32767]", "Microsoft.VisualBasic": "(,10.4.32767]",
+7 -5
View File
@@ -3,19 +3,21 @@ services:
build: . build: .
image: local-musicdownloader:latest image: local-musicdownloader:latest
container_name: MusicDownloader container_name: MusicDownloader
# 完了後に自動停止する場合は "no"、定期チェック常駐させる場合は "unless-stopped" # 完了後も2時間待機ループで常駐させるため unless-stopped
restart: "no" restart: unless-stopped
mem_limit: 512m mem_limit: 768m
memswap_limit: 512m memswap_limit: 768m
deploy: deploy:
resources: resources:
limits: limits:
memory: 512M memory: 768M
environment: environment:
- TZ=Asia/Tokyo - TZ=Asia/Tokyo
# .NET GC設定: Workstation GC強制、ヒープ制限50%で省メモリ化 # .NET GC設定: Workstation GC強制、ヒープ制限50%で省メモリ化
- DOTNET_gcServer=0 - DOTNET_gcServer=0
- DOTNET_GCHeapHardLimitPercent=50 - DOTNET_GCHeapHardLimitPercent=50
# 定期チェック間隔(時間単位、デフォルト2時間)
- CHECK_INTERVAL_HOURS=2
# プレイリストURLをコンテナ側から上書きしたい場合に指定 # プレイリストURLをコンテナ側から上書きしたい場合に指定
# - PLAYLIST_URL=https://www.youtube.com/playlist?list=... # - PLAYLIST_URL=https://www.youtube.com/playlist?list=...
volumes: volumes: