- ExternalFeedConfigManager.cs: 新規追加 - C:\feeds\src\ 配下の JSON ファイルから設定を読み込む共通マネージャー - ファイル不存在時はデフォルト値で自動生成 - ExternalConfigWatcher.cs: 新規追加 - FileSystemWatcher による設定ファイルの変更監視 - 変更検知時に登録ハンドラを呼び出しRSS即時再生成をトリガー - 定期実行との排他制御(SemaphoreSlim)に対応 - YouTubeConfig.cs: 外部ファイル読み込み対応にリファクタ - Channels を静的リストから LoadAsync() で動的ロードする方式に変更 - DefaultChannels として既存のハードコード一覧を保持 - YouTubeModels.cs: YouTubeChannelTarget を ExternalFeedTarget 継承に変更 - IdOrHandle を Url プロパティのエイリアスとして再定義 - 旧 JSON フォーマット(idOrHandle キー)との後方互換性を維持 - YouTubeFeedManager.cs: 実行前に YouTubeConfig.LoadAsync() を呼び出すよう変更
174 lines
7.0 KiB
C#
174 lines
7.0 KiB
C#
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;
|
||
|
||
/// <summary>
|
||
/// 外部フィード設定の共通ターゲットモデル
|
||
/// YouTubeや他の各種サイトにおける監視対象URL・チャンネル等の外部定義情報
|
||
/// </summary>
|
||
public class ExternalFeedTarget
|
||
{
|
||
/// <summary>
|
||
/// 対象URL(またはチャンネルID・識別子)
|
||
/// </summary>
|
||
[JsonPropertyName("url")]
|
||
public string Url { get; set; } = string.Empty;
|
||
|
||
/// <summary>
|
||
/// 対象名(チャンネル名・サイト名・ユーザー名など)
|
||
/// </summary>
|
||
[JsonPropertyName("name")]
|
||
public string? Name { get; set; }
|
||
|
||
/// <summary>
|
||
/// 出力カテゴリ名(例: "ゲーム", "野球", "音楽", "公式", "その他" など)
|
||
/// </summary>
|
||
[JsonPropertyName("category")]
|
||
public string Category { get; set; } = "その他";
|
||
|
||
/// <summary>
|
||
/// 有効フラグ(falseの場合は取得対象から除外)
|
||
/// </summary>
|
||
[JsonPropertyName("enabled")]
|
||
public bool Enabled { get; set; } = true;
|
||
}
|
||
|
||
/// <summary>
|
||
/// 外部設定ファイル(JSON)の読み込み・保存を管理する共通クラス
|
||
/// </summary>
|
||
public static class ExternalFeedConfigManager
|
||
{
|
||
/// <summary>
|
||
/// JSONシリアライズ/デシリアライズの共通オプション
|
||
/// 日本語文字列をUnicodeエスケープ(\uXXXX)せずにそのまま出力します
|
||
/// </summary>
|
||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||
{
|
||
WriteIndented = true,
|
||
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
|
||
PropertyNameCaseInsensitive = true,
|
||
ReadCommentHandling = JsonCommentHandling.Skip,
|
||
AllowTrailingCommas = true,
|
||
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
|
||
};
|
||
|
||
/// <summary>
|
||
/// 設定ファイルの格納ディレクトリパスを取得します。
|
||
/// Windowsホスト実行時は C:\feeds\src、Dockerコンテナ実行時はマウント先の /app/output/src を自動判定します。
|
||
/// </summary>
|
||
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";
|
||
}
|
||
|
||
/// <summary>
|
||
/// 設定ファイルの絶対パスを取得します。
|
||
/// </summary>
|
||
/// <param name="fileName">ファイル名(例: "youtube.json")</param>
|
||
public static string GetConfigFilePath(string fileName)
|
||
{
|
||
return Path.Combine(GetConfigDirectory(), fileName);
|
||
}
|
||
|
||
/// <summary>
|
||
/// 指定された設定ファイル(JSON)からターゲット一覧を読み込みます。
|
||
/// ファイルが存在しない場合、defaultTargets が指定されていれば初期ファイルとして自動保存します。
|
||
/// </summary>
|
||
/// <typeparam name="T">ターゲットモデルの型(ExternalFeedTargetの派生クラス)</typeparam>
|
||
/// <param name="fileName">設定ファイル名(例: "youtube.json")</param>
|
||
/// <param name="defaultTargets">ファイルが存在しない場合のデフォルトリスト</param>
|
||
/// <param name="onlyEnabled">有効(Enabled == true)なターゲットのみ取得するかどうか</param>
|
||
/// <returns>読み込まれたターゲット一覧</returns>
|
||
public static async Task<List<T>> LoadTargetsAsync<T>(
|
||
string fileName,
|
||
IEnumerable<T>? 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<T>();
|
||
}
|
||
|
||
using var stream = File.OpenRead(filePath);
|
||
var items = await JsonSerializer.DeserializeAsync<List<T>>(stream, JsonOptions);
|
||
|
||
if (items == null)
|
||
{
|
||
LogManager.AddLog($"[警告] 設定ファイルの内容が空または不正です: {filePath}");
|
||
return new List<T>();
|
||
}
|
||
|
||
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<T>();
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// ターゲット一覧を外部設定ファイル(JSON)に整形して保存します。
|
||
/// </summary>
|
||
/// <typeparam name="T">ターゲットモデルの型</typeparam>
|
||
/// <param name="fileName">設定ファイル名(例: "youtube.json")</param>
|
||
/// <param name="targets">保存するターゲット一覧</param>
|
||
public static async Task SaveTargetsAsync<T>(string fileName, IEnumerable<T> 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}");
|
||
}
|
||
}
|