diff --git a/rss-generator/Class/Common/ExternalConfigWatcher.cs b/rss-generator/Class/Common/ExternalConfigWatcher.cs
new file mode 100644
index 0000000..8f0e8e4
--- /dev/null
+++ b/rss-generator/Class/Common/ExternalConfigWatcher.cs
@@ -0,0 +1,282 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Net.Http;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace rss_generator.Class.Common;
+
+///
+/// 外部設定ファイル(C:\feeds\src\*.json)の変更を監視し、
+/// 変更されたファイルに対応するRSS生成アクションを即座に実行するウォッチャークラス
+///
+public class ExternalConfigWatcher : IDisposable
+{
+ ///
+ /// ファイル名に対応するハンドラー情報
+ ///
+ private readonly Dictionary Action)> _handlers =
+ new(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// 各ファイルの最終更新日時(UTC)記録用(ポーリング監視および重複発火防止用)
+ ///
+ private readonly ConcurrentDictionary _lastWriteTimes =
+ new(StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// 変更検知後のデバウンス用キュー(ファイル名 -> 検知時刻)
+ ///
+ private readonly ConcurrentDictionary _pendingTriggers =
+ new(StringComparer.OrdinalIgnoreCase);
+
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly SemaphoreSlim _executionLock;
+ private readonly CancellationTokenSource _cts = new();
+
+ private FileSystemWatcher? _watcher;
+ private Task? _monitorTask;
+ private bool _disposed;
+
+ ///
+ /// コンストラクタ
+ ///
+ /// HttpClientFactory インスタンス
+ /// 定期実行との競合を防ぐ排他ロックセマフォ
+ public ExternalConfigWatcher(IHttpClientFactory httpClientFactory, SemaphoreSlim executionLock)
+ {
+ _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
+ _executionLock = executionLock ?? throw new ArgumentNullException(nameof(executionLock));
+ }
+
+ ///
+ /// 監視対象ファイルと、変更時に実行するアクションを登録します。
+ ///
+ /// 監視する設定ファイル名(例: "youtube.json")
+ /// ログ表示用の名称(例: "YouTube")
+ /// 実行するRSS生成非同期メソッド
+ public void RegisterHandler(string fileName, string displayName, Func action)
+ {
+ _handlers[fileName] = (displayName, action);
+ }
+
+ ///
+ /// 監視を開始します。
+ ///
+ public void Start()
+ {
+ string watchDir = ExternalFeedConfigManager.GetConfigDirectory();
+ if (!Directory.Exists(watchDir))
+ {
+ Directory.CreateDirectory(watchDir);
+ }
+
+ // 初期ファイルの最終更新日時を記録(起動直後の誤検知を防止)
+ RecordInitialFileTimes(watchDir);
+
+ // 1. FileSystemWatcher による即時検知(Windowsホスト環境等向け)
+ try
+ {
+ _watcher = new FileSystemWatcher(watchDir, "*.json")
+ {
+ NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size,
+ IncludeSubdirectories = false,
+ EnableRaisingEvents = true
+ };
+
+ _watcher.Changed += OnFileEvent;
+ _watcher.Created += OnFileEvent;
+ _watcher.Renamed += (s, e) => OnFileEvent(s, new FileSystemEventArgs(WatcherChangeTypes.Changed, watchDir, e.Name));
+
+ LogManager.AddLog($"[情報] FileSystemWatcher による設定ファイル監視を開始しました: {watchDir}");
+ }
+ catch (Exception ex)
+ {
+ LogManager.AddLog($"[警告] FileSystemWatcher の初期化に失敗(ポーリングのみで監視を継続します): {ex.Message}");
+ }
+
+ // 2. バックグラウンドポーリングタスク(Dockerバインドマウント環境でも確実に検知するため2.5秒間隔で更新日時を走査)
+ _monitorTask = Task.Run(() => PollingLoopAsync(watchDir, _cts.Token));
+ LogManager.AddLog($"[情報] 外部設定ファイル監視ループを開始しました: {watchDir}");
+ }
+
+ ///
+ /// 起動時の既存ファイル更新日時を記録します。
+ ///
+ private void RecordInitialFileTimes(string watchDir)
+ {
+ try
+ {
+ var files = Directory.GetFiles(watchDir, "*.json");
+ foreach (var filePath in files)
+ {
+ string fileName = Path.GetFileName(filePath);
+ var lastWrite = File.GetLastWriteTimeUtc(filePath);
+ _lastWriteTimes[fileName] = lastWrite;
+ }
+ }
+ catch (Exception ex)
+ {
+ LogManager.AddLog($"[警告] 初期ファイル一覧の確認失敗: {ex.Message}");
+ }
+ }
+
+ ///
+ /// FileSystemWatcher イベントハンドラ
+ ///
+ private void OnFileEvent(object sender, FileSystemEventArgs e)
+ {
+ if (string.IsNullOrEmpty(e.Name)) return;
+
+ string fileName = Path.GetFileName(e.Name);
+ if (_handlers.ContainsKey(fileName))
+ {
+ // デバウンス用キューに記録(現在時刻で更新)
+ _pendingTriggers[fileName] = DateTime.UtcNow;
+ }
+ }
+
+ ///
+ /// バックグラウンドポーリングおよびデバウンス処理ループ
+ ///
+ private async Task PollingLoopAsync(string watchDir, CancellationToken ct)
+ {
+ while (!ct.IsCancellationRequested)
+ {
+ try
+ {
+ await Task.Delay(500, ct);
+
+ // ディレクトリ内の .json ファイルの最終更新日時をポーリング
+ if (Directory.Exists(watchDir))
+ {
+ var files = Directory.GetFiles(watchDir, "*.json");
+ foreach (var filePath in files)
+ {
+ string fileName = Path.GetFileName(filePath);
+ if (!_handlers.ContainsKey(fileName)) continue;
+
+ DateTime currentWriteTime;
+ try
+ {
+ currentWriteTime = File.GetLastWriteTimeUtc(filePath);
+ }
+ catch
+ {
+ continue;
+ }
+
+ if (_lastWriteTimes.TryGetValue(fileName, out var prevWriteTime))
+ {
+ if (currentWriteTime > prevWriteTime)
+ {
+ // 変更検知
+ _lastWriteTimes[fileName] = currentWriteTime;
+ _pendingTriggers[fileName] = DateTime.UtcNow;
+ }
+ }
+ else
+ {
+ // 新規作成ファイル
+ _lastWriteTimes[fileName] = currentWriteTime;
+ _pendingTriggers[fileName] = DateTime.UtcNow;
+ }
+ }
+ }
+
+ // デバウンス待機完了(変更検知から500ms以上経過したトリガー)の処理
+ var now = DateTime.UtcNow;
+ foreach (var kvp in _pendingTriggers.ToArray())
+ {
+ string fileName = kvp.Key;
+ DateTime triggeredTime = kvp.Value;
+
+ // 変更検知から500ms以上経過していたら実行
+ if ((now - triggeredTime).TotalMilliseconds >= 500)
+ {
+ _pendingTriggers.TryRemove(fileName, out _);
+ // 最新の更新日時を反映
+ string filePath = Path.Combine(watchDir, fileName);
+ if (File.Exists(filePath))
+ {
+ try { _lastWriteTimes[fileName] = File.GetLastWriteTimeUtc(filePath); } catch { }
+ }
+
+ // 非同期タスクとして排他実行
+ _ = Task.Run(async () => await ExecuteTriggerAsync(fileName), ct);
+ }
+ }
+ }
+ catch (OperationCanceledException)
+ {
+ break;
+ }
+ catch (Exception ex)
+ {
+ LogManager.AddLog($"[エラー] 外部設定ファイル監視ループ例外: {ex.Message}");
+ }
+ }
+ }
+
+ ///
+ /// ファイル変更に伴う該当フィードの個別取得処理を実行します。
+ ///
+ private async Task ExecuteTriggerAsync(string fileName)
+ {
+ if (!_handlers.TryGetValue(fileName, out var handler))
+ {
+ return;
+ }
+
+ LogManager.AddLog($"[情報] 外部設定ファイルの変更を検知しました: {fileName} -> 【{handler.DisplayName}】のRSS生成を開始します");
+
+ // 定期実行または他トリガーとの排他ロックを取得
+ await _executionLock.WaitAsync();
+ Stopwatch sw = Stopwatch.StartNew();
+
+ try
+ {
+ using var client = _httpClientFactory.CreateClient("webClient");
+ client.DefaultRequestHeaders.UserAgent.Clear();
+ client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36");
+ client.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
+
+ await handler.Action(client);
+
+ sw.Stop();
+ LogManager.AddLog($"[情報] 【{handler.DisplayName}】 外部設定変更に伴うRSS生成完了 ({sw.Elapsed.TotalSeconds:0.##}秒)");
+ }
+ catch (Exception ex)
+ {
+ LogManager.AddLog($"[エラー] 【{handler.DisplayName}】 外部設定変更トリガー実行時エラー: {ex.Message}");
+ CmnUtil.PrintCallStackToEvent(ex);
+ }
+ finally
+ {
+ // メモリ回収
+ GC.Collect(2, GCCollectionMode.Aggressive, true, true);
+ GC.WaitForPendingFinalizers();
+ GC.Collect(2, GCCollectionMode.Aggressive, true, true);
+
+ _executionLock.Release();
+ }
+ }
+
+ public void Dispose()
+ {
+ if (_disposed) return;
+ _disposed = true;
+
+ _cts.Cancel();
+ _cts.Dispose();
+
+ if (_watcher != null)
+ {
+ _watcher.EnableRaisingEvents = false;
+ _watcher.Dispose();
+ }
+ }
+}
diff --git a/rss-generator/Class/Common/ExternalFeedConfigManager.cs b/rss-generator/Class/Common/ExternalFeedConfigManager.cs
new file mode 100644
index 0000000..7b48c04
--- /dev/null
+++ b/rss-generator/Class/Common/ExternalFeedConfigManager.cs
@@ -0,0 +1,173 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text.Encodings.Web;
+using System.Text.Json;
+using System.Text.Json.Serialization;
+using System.Threading.Tasks;
+
+namespace rss_generator.Class.Common;
+
+///
+/// 外部フィード設定の共通ターゲットモデル
+/// YouTubeや他の各種サイトにおける監視対象URL・チャンネル等の外部定義情報
+///
+public class ExternalFeedTarget
+{
+ ///
+ /// 対象URL(またはチャンネルID・識別子)
+ ///
+ [JsonPropertyName("url")]
+ public string Url { get; set; } = string.Empty;
+
+ ///
+ /// 対象名(チャンネル名・サイト名・ユーザー名など)
+ ///
+ [JsonPropertyName("name")]
+ public string? Name { get; set; }
+
+ ///
+ /// 出力カテゴリ名(例: "ゲーム", "野球", "音楽", "公式", "その他" など)
+ ///
+ [JsonPropertyName("category")]
+ public string Category { get; set; } = "その他";
+
+ ///
+ /// 有効フラグ(falseの場合は取得対象から除外)
+ ///
+ [JsonPropertyName("enabled")]
+ public bool Enabled { get; set; } = true;
+}
+
+///
+/// 外部設定ファイル(JSON)の読み込み・保存を管理する共通クラス
+///
+public static class ExternalFeedConfigManager
+{
+ ///
+ /// JSONシリアライズ/デシリアライズの共通オプション
+ /// 日本語文字列をUnicodeエスケープ(\uXXXX)せずにそのまま出力します
+ ///
+ private static readonly JsonSerializerOptions JsonOptions = new()
+ {
+ WriteIndented = true,
+ Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
+ PropertyNameCaseInsensitive = true,
+ ReadCommentHandling = JsonCommentHandling.Skip,
+ AllowTrailingCommas = true,
+ DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
+ };
+
+ ///
+ /// 設定ファイルの格納ディレクトリパスを取得します。
+ /// Windowsホスト実行時は C:\feeds\src、Dockerコンテナ実行時はマウント先の /app/output/src を自動判定します。
+ ///
+ public static string GetConfigDirectory()
+ {
+ if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+ {
+ return @"C:\feeds\src";
+ }
+
+ // Dockerコンテナ内(/app/output がホストの C:\feeds にマウントされている環境)
+ string containerPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output", "src");
+ if (Directory.Exists(containerPath) || Directory.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "output")))
+ {
+ return containerPath;
+ }
+
+ return "/app/output/src";
+ }
+
+ ///
+ /// 設定ファイルの絶対パスを取得します。
+ ///
+ /// ファイル名(例: "youtube.json")
+ public static string GetConfigFilePath(string fileName)
+ {
+ return Path.Combine(GetConfigDirectory(), fileName);
+ }
+
+ ///
+ /// 指定された設定ファイル(JSON)からターゲット一覧を読み込みます。
+ /// ファイルが存在しない場合、defaultTargets が指定されていれば初期ファイルとして自動保存します。
+ ///
+ /// ターゲットモデルの型(ExternalFeedTargetの派生クラス)
+ /// 設定ファイル名(例: "youtube.json")
+ /// ファイルが存在しない場合のデフォルトリスト
+ /// 有効(Enabled == true)なターゲットのみ取得するかどうか
+ /// 読み込まれたターゲット一覧
+ public static async Task> LoadTargetsAsync(
+ string fileName,
+ IEnumerable? defaultTargets = null,
+ bool onlyEnabled = true) where T : ExternalFeedTarget, new()
+ {
+ string filePath = GetConfigFilePath(fileName);
+
+ try
+ {
+ if (!File.Exists(filePath))
+ {
+ if (defaultTargets != null && defaultTargets.Any())
+ {
+ LogManager.AddLog($"[情報] 設定ファイルが存在しないため、デフォルト設定を書き出します: {filePath}");
+ await SaveTargetsAsync(fileName, defaultTargets);
+ var defaults = defaultTargets.ToList();
+ return onlyEnabled ? defaults.Where(t => t.Enabled).ToList() : defaults;
+ }
+
+ LogManager.AddLog($"[警告] 設定ファイルが見つかりません: {filePath}");
+ return new List();
+ }
+
+ using var stream = File.OpenRead(filePath);
+ var items = await JsonSerializer.DeserializeAsync>(stream, JsonOptions);
+
+ if (items == null)
+ {
+ LogManager.AddLog($"[警告] 設定ファイルの内容が空または不正です: {filePath}");
+ return new List();
+ }
+
+ LogManager.AddLog($"[情報] 外部設定ファイル読み込み完了: {fileName} ({items.Count}件)");
+ return onlyEnabled ? items.Where(t => t.Enabled).ToList() : items;
+ }
+ catch (Exception ex)
+ {
+ LogManager.AddLog($"[エラー] 外部設定ファイル読み込み失敗 ({filePath}): {ex.Message}");
+ CmnUtil.PrintCallStackToEvent(ex);
+
+ // 読み込みに失敗した場合、デフォルトが指定されていればフォールバック
+ if (defaultTargets != null && defaultTargets.Any())
+ {
+ LogManager.AddLog($"[情報] デフォルト設定をフォールバックとして使用します: {fileName}");
+ var defaults = defaultTargets.ToList();
+ return onlyEnabled ? defaults.Where(t => t.Enabled).ToList() : defaults;
+ }
+
+ return new List();
+ }
+ }
+
+ ///
+ /// ターゲット一覧を外部設定ファイル(JSON)に整形して保存します。
+ ///
+ /// ターゲットモデルの型
+ /// 設定ファイル名(例: "youtube.json")
+ /// 保存するターゲット一覧
+ public static async Task SaveTargetsAsync(string fileName, IEnumerable targets)
+ {
+ string dir = GetConfigDirectory();
+ if (!Directory.Exists(dir))
+ {
+ Directory.CreateDirectory(dir);
+ }
+
+ string filePath = Path.Combine(dir, fileName);
+ using var stream = File.Create(filePath);
+ await JsonSerializer.SerializeAsync(stream, targets, JsonOptions);
+ LogManager.AddLog($"[情報] 設定ファイルを保存しました: {filePath}");
+ }
+}
diff --git a/rss-generator/Class/YouTube/YouTubeConfig.cs b/rss-generator/Class/YouTube/YouTubeConfig.cs
index e6640ae..5c78e3b 100644
--- a/rss-generator/Class/YouTube/YouTubeConfig.cs
+++ b/rss-generator/Class/YouTube/YouTubeConfig.cs
@@ -1,4 +1,6 @@
using System.Collections.Generic;
+using System.Threading.Tasks;
+using rss_generator.Class.Common;
namespace rss_generator.Class.YouTube;
@@ -8,10 +10,37 @@ namespace rss_generator.Class.YouTube;
public static class YouTubeConfig
{
///
- /// 出力対象とするYouTubeチャンネル・ユーザーの固定一覧。
- /// ここにチャンネルID(UC...)またはハンドル(@...)を追加してください。
+ /// 設定ファイル名(C:\feeds\src\youtube.json)
///
- public static readonly List Channels = new()
+ public const string ConfigFileName = "youtube.json";
+
+ ///
+ /// 出力対象とするYouTubeチャンネル・ユーザーの一覧。
+ /// 外部ファイル(C:\feeds\src\youtube.json)から読み込まれます。
+ ///
+ public static List Channels { get; private set; }
+
+ static YouTubeConfig()
+ {
+ Channels = new(DefaultChannels);
+ }
+
+ ///
+ /// 外部ファイル(C:\feeds\src\youtube.json)から最新のチャンネル設定を読み込みます。
+ /// ファイルが存在しない場合は DefaultChannels の内容で自動作成されます。
+ ///
+ public static async Task LoadAsync()
+ {
+ Channels = await ExternalFeedConfigManager.LoadTargetsAsync(
+ ConfigFileName,
+ DefaultChannels
+ );
+ }
+
+ ///
+ /// 初期移行用およびフォールバック用のデフォルトチャンネル一覧
+ ///
+ public static readonly List DefaultChannels = new()
{
// === ゲームカテゴリ ===
new YouTubeChannelTarget { IdOrHandle = "UC4jVPBw6dP3mXCGJvRi3Xbw", Name = "0m0ti channel", Category = "ゲーム" },
diff --git a/rss-generator/Class/YouTube/YouTubeFeedManager.cs b/rss-generator/Class/YouTube/YouTubeFeedManager.cs
index a7bd869..d698604 100644
--- a/rss-generator/Class/YouTube/YouTubeFeedManager.cs
+++ b/rss-generator/Class/YouTube/YouTubeFeedManager.cs
@@ -26,6 +26,9 @@ public static class YouTubeFeedManager
try
{
+ // 外部ファイル(C:\feeds\src\youtube.json)から最新のチャンネル設定を読み込み
+ await YouTubeConfig.LoadAsync();
+
var allLiveItems = new List();
var allVideoItems = new List();
var allShortsItems = new List();
diff --git a/rss-generator/Class/YouTube/YouTubeModels.cs b/rss-generator/Class/YouTube/YouTubeModels.cs
index c178133..a33345e 100644
--- a/rss-generator/Class/YouTube/YouTubeModels.cs
+++ b/rss-generator/Class/YouTube/YouTubeModels.cs
@@ -1,4 +1,6 @@
using System;
+using System.Text.Json.Serialization;
+using rss_generator.Class.Common;
namespace rss_generator.Class.YouTube;
@@ -17,31 +19,42 @@ public enum YouTubeFeedType
///
/// 監視対象チャンネル・ユーザーの設定情報
+/// 共通モデル ExternalFeedTarget を継承し、YouTube固有のURL生成ロジックを持ちます。
///
-public class YouTubeChannelTarget
+public class YouTubeChannelTarget : ExternalFeedTarget
{
///
- /// チャンネルID(例: "UCdn5BQ06XqgXoAxIhbqw5Rg")またはハンドル名(例: "@ShirakamiFubuki")
+ /// 旧プロパティ名との後方互換用エイリアス(Urlと同じ値を参照・設定)
///
- public string IdOrHandle { get; set; } = "";
+ [JsonIgnore]
+ public string IdOrHandle
+ {
+ get => Url;
+ set => Url = value;
+ }
///
- /// チャンネル名(未指定の場合は自動取得またはIdOrHandleを使用)
+ /// JSON読み込み時の旧フォーマット(idOrHandle)対応用プロパティ
+ /// 書き出し時は出力されません
///
- public string? Name { get; set; }
-
- ///
- /// 出力カテゴリ名(例: "その他", "野球", "ゲーム", "音楽", "ニュース" 等)
- /// カテゴリごとに独立したRSSフィード(XML)が出力されます。
- ///
- public string Category { get; set; } = "その他";
+ [JsonPropertyName("idOrHandle")]
+ public string? LegacyIdOrHandle
+ {
+ set
+ {
+ if (!string.IsNullOrEmpty(value) && string.IsNullOrEmpty(Url))
+ {
+ Url = value;
+ }
+ }
+ }
///
/// 指定したタブ種別に応じたURLを取得します。
///
public string GetTabUrl(YouTubeFeedType type)
{
- string baseTarget = IdOrHandle.Trim();
+ string baseTarget = (Url ?? "").Trim();
string baseUrl;
if (baseTarget.StartsWith("@"))