Compare commits
2
Commits
5157a175c1
...
aa76a3d868
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa76a3d868 | ||
|
|
7243b64cdc |
No files matched your search
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 外部設定ファイル(C:\feeds\src\*.json)の変更を監視し、
|
||||
/// 変更されたファイルに対応するRSS生成アクションを即座に実行するウォッチャークラス
|
||||
/// </summary>
|
||||
public class ExternalConfigWatcher : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// ファイル名に対応するハンドラー情報
|
||||
/// </summary>
|
||||
private readonly Dictionary<string, (string DisplayName, Func<HttpClient, Task> Action)> _handlers =
|
||||
new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 各ファイルの最終更新日時(UTC)記録用(ポーリング監視および重複発火防止用)
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<string, DateTime> _lastWriteTimes =
|
||||
new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 変更検知後のデバウンス用キュー(ファイル名 -> 検知時刻)
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<string, DateTime> _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;
|
||||
|
||||
/// <summary>
|
||||
/// コンストラクタ
|
||||
/// </summary>
|
||||
/// <param name="httpClientFactory">HttpClientFactory インスタンス</param>
|
||||
/// <param name="executionLock">定期実行との競合を防ぐ排他ロックセマフォ</param>
|
||||
public ExternalConfigWatcher(IHttpClientFactory httpClientFactory, SemaphoreSlim executionLock)
|
||||
{
|
||||
_httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
|
||||
_executionLock = executionLock ?? throw new ArgumentNullException(nameof(executionLock));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 監視対象ファイルと、変更時に実行するアクションを登録します。
|
||||
/// </summary>
|
||||
/// <param name="fileName">監視する設定ファイル名(例: "youtube.json")</param>
|
||||
/// <param name="displayName">ログ表示用の名称(例: "YouTube")</param>
|
||||
/// <param name="action">実行するRSS生成非同期メソッド</param>
|
||||
public void RegisterHandler(string fileName, string displayName, Func<HttpClient, Task> action)
|
||||
{
|
||||
_handlers[fileName] = (displayName, action);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 監視を開始します。
|
||||
/// </summary>
|
||||
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}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 起動時の既存ファイル更新日時を記録します。
|
||||
/// </summary>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// FileSystemWatcher イベントハンドラ
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// バックグラウンドポーリングおよびデバウンス処理ループ
|
||||
/// </summary>
|
||||
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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ファイル変更に伴う該当フィードの個別取得処理を実行します。
|
||||
/// </summary>
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <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}");
|
||||
}
|
||||
}
|
||||
@@ -37,10 +37,12 @@ internal static class LogManager // 実際のクラス名に合わせてくだ
|
||||
/// </summary>
|
||||
public static void AddLog(string? message)
|
||||
{
|
||||
string text = message?.TrimEnd('\r', '\n') ?? string.Empty;
|
||||
Console.WriteLine($"[{DateTime.Now:HH:mm:ss}] {text}");
|
||||
|
||||
var log = new LogMessage
|
||||
{
|
||||
Message = message!.TrimEnd('\r', '\n'),
|
||||
Message = text,
|
||||
Timestamp = DateTime.Now // ログが発生した瞬間の時間を保持
|
||||
};
|
||||
|
||||
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// 出力対象とするYouTubeチャンネル・ユーザーの固定一覧。
|
||||
/// ここにチャンネルID(UC...)またはハンドル(@...)を追加してください。
|
||||
/// 設定ファイル名(C:\feeds\src\youtube.json)
|
||||
/// </summary>
|
||||
public static readonly List<YouTubeChannelTarget> Channels = new()
|
||||
public const string ConfigFileName = "youtube.json";
|
||||
|
||||
/// <summary>
|
||||
/// 出力対象とするYouTubeチャンネル・ユーザーの一覧。
|
||||
/// 外部ファイル(C:\feeds\src\youtube.json)から読み込まれます。
|
||||
/// </summary>
|
||||
public static List<YouTubeChannelTarget> Channels { get; private set; }
|
||||
|
||||
static YouTubeConfig()
|
||||
{
|
||||
Channels = new(DefaultChannels);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 外部ファイル(C:\feeds\src\youtube.json)から最新のチャンネル設定を読み込みます。
|
||||
/// ファイルが存在しない場合は DefaultChannels の内容で自動作成されます。
|
||||
/// </summary>
|
||||
public static async Task LoadAsync()
|
||||
{
|
||||
Channels = await ExternalFeedConfigManager.LoadTargetsAsync<YouTubeChannelTarget>(
|
||||
ConfigFileName,
|
||||
DefaultChannels
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 初期移行用およびフォールバック用のデフォルトチャンネル一覧
|
||||
/// </summary>
|
||||
public static readonly List<YouTubeChannelTarget> DefaultChannels = new()
|
||||
{
|
||||
// === ゲームカテゴリ ===
|
||||
new YouTubeChannelTarget { IdOrHandle = "UC4jVPBw6dP3mXCGJvRi3Xbw", Name = "0m0ti channel", Category = "ゲーム" },
|
||||
|
||||
@@ -26,6 +26,9 @@ public static class YouTubeFeedManager
|
||||
|
||||
try
|
||||
{
|
||||
// 外部ファイル(C:\feeds\src\youtube.json)から最新のチャンネル設定を読み込み
|
||||
await YouTubeConfig.LoadAsync();
|
||||
|
||||
var allLiveItems = new List<YouTubeVideoItem>();
|
||||
var allVideoItems = new List<YouTubeVideoItem>();
|
||||
var allShortsItems = new List<YouTubeVideoItem>();
|
||||
|
||||
@@ -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
|
||||
|
||||
/// <summary>
|
||||
/// 監視対象チャンネル・ユーザーの設定情報
|
||||
/// 共通モデル ExternalFeedTarget を継承し、YouTube固有のURL生成ロジックを持ちます。
|
||||
/// </summary>
|
||||
public class YouTubeChannelTarget
|
||||
public class YouTubeChannelTarget : ExternalFeedTarget
|
||||
{
|
||||
/// <summary>
|
||||
/// チャンネルID(例: "UCdn5BQ06XqgXoAxIhbqw5Rg")またはハンドル名(例: "@ShirakamiFubuki")
|
||||
/// 旧プロパティ名との後方互換用エイリアス(Urlと同じ値を参照・設定)
|
||||
/// </summary>
|
||||
public string IdOrHandle { get; set; } = "";
|
||||
[JsonIgnore]
|
||||
public string IdOrHandle
|
||||
{
|
||||
get => Url;
|
||||
set => Url = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// チャンネル名(未指定の場合は自動取得またはIdOrHandleを使用)
|
||||
/// JSON読み込み時の旧フォーマット(idOrHandle)対応用プロパティ
|
||||
/// 書き出し時は出力されません
|
||||
/// </summary>
|
||||
public string? Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 出力カテゴリ名(例: "その他", "野球", "ゲーム", "音楽", "ニュース" 等)
|
||||
/// カテゴリごとに独立したRSSフィード(XML)が出力されます。
|
||||
/// </summary>
|
||||
public string Category { get; set; } = "その他";
|
||||
[JsonPropertyName("idOrHandle")]
|
||||
public string? LegacyIdOrHandle
|
||||
{
|
||||
set
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value) && string.IsNullOrEmpty(Url))
|
||||
{
|
||||
Url = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 指定したタブ種別に応じたURLを取得します。
|
||||
/// </summary>
|
||||
public string GetTabUrl(YouTubeFeedType type)
|
||||
{
|
||||
string baseTarget = IdOrHandle.Trim();
|
||||
string baseTarget = (Url ?? "").Trim();
|
||||
string baseUrl;
|
||||
|
||||
if (baseTarget.StartsWith("@"))
|
||||
|
||||
@@ -50,11 +50,19 @@ var serviceProvider = services.BuildServiceProvider();
|
||||
// ファクトリインスタンスを取り出す
|
||||
var httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>();
|
||||
|
||||
// 定期実行とファイル変更監視トリガーとの排他制御用セマフォ
|
||||
var executionLock = new SemaphoreSlim(1, 1);
|
||||
|
||||
// 外部設定ファイル(C:\feeds\src\*.json)の変更監視を開始
|
||||
using var configWatcher = new ExternalConfigWatcher(httpClientFactory, executionLock);
|
||||
configWatcher.RegisterHandler(YouTubeConfig.ConfigFileName, "YouTube", client => YouTubeFeedManager.CreateRSSAsync(client));
|
||||
configWatcher.Start();
|
||||
|
||||
LogManager.AddLog($"[情報] rss-generatorの起動");
|
||||
var isFirst = true;
|
||||
|
||||
// 生成完了後の待機時間(固定で30分)
|
||||
TimeSpan waitInterval = TimeSpan.FromMinutes(30);
|
||||
// 生成完了後の待機時間(固定で5分)
|
||||
TimeSpan waitInterval = TimeSpan.FromMinutes(5);
|
||||
|
||||
while (true)
|
||||
{
|
||||
@@ -67,13 +75,15 @@ while (true)
|
||||
#if DEBUG
|
||||
#else
|
||||
var nextRunTime = DateTime.Now.Add(waitInterval);
|
||||
LogManager.AddLog($"[情報] 次回実行予定: {nextRunTime:HH:mm:ss} (固定で30分待機)");
|
||||
LogManager.AddLog($"[情報] 次回実行予定: {nextRunTime:HH:mm:ss} (固定で5分待機)");
|
||||
|
||||
// 生成完了後、固定で30分待機(非同期スリープ)
|
||||
// 生成完了後、固定で5分待機(非同期スリープ)
|
||||
await Task.Delay(waitInterval);
|
||||
#endif
|
||||
}
|
||||
|
||||
// 定期実行の排他ロックを取得
|
||||
await executionLock.WaitAsync();
|
||||
// 指定時刻になったら処理を実行
|
||||
Stopwatch totalSw = Stopwatch.StartNew();
|
||||
Stopwatch sw = Stopwatch.StartNew();
|
||||
@@ -91,7 +101,7 @@ while (true)
|
||||
var feedActions = new List<(string Name, Func<Task> Action)>();
|
||||
|
||||
#if DEBUG
|
||||
feedActions.Add(("movie.eroterest.net", () => MovieEroterestFeedManager.CreateAllRSSAsync(client)));
|
||||
feedActions.Add(("YouTube", () => YouTubeFeedManager.CreateRSSAsync(client)));
|
||||
#else
|
||||
feedActions.Add(("movie.eroterest.net", () => MovieEroterestFeedManager.CreateAllRSSAsync(client)));
|
||||
feedActions.Add(("YouTube", () => YouTubeFeedManager.CreateRSSAsync(client)));
|
||||
@@ -161,4 +171,8 @@ while (true)
|
||||
LogManager.AddLog($"{ex.StackTrace}");
|
||||
//await LogManager.FlushAndCloseAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
executionLock.Release();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user