From 3ed425f550a4c13a59648ff54e3a8b6c9c499f40 Mon Sep 17 00:00:00 2001 From: uduki Date: Thu, 1 Oct 2026 09:41:33 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=88=9D=E5=9B=9E=E3=82=B3=E3=83=9F?= =?UTF-8?q?=E3=83=83=E3=83=88=20(FeedConfigEditor)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 10 + FeedConfigEditor.sln | 34 + FeedConfigEditor.slnx | 3 + FeedConfigEditor/FeedConfigEditor.csproj | 25 + FeedConfigEditor/MainForm.cs | 939 ++++++++++++++++++ FeedConfigEditor/Models/FeedTargetItem.cs | 124 +++ FeedConfigEditor/Program.cs | 18 + .../Services/ConfigFileService.cs | 128 +++ FeedConfigEditor/Services/UrlHelper.cs | 107 ++ 9 files changed, 1388 insertions(+) create mode 100644 .gitignore create mode 100644 FeedConfigEditor.sln create mode 100644 FeedConfigEditor.slnx create mode 100644 FeedConfigEditor/FeedConfigEditor.csproj create mode 100644 FeedConfigEditor/MainForm.cs create mode 100644 FeedConfigEditor/Models/FeedTargetItem.cs create mode 100644 FeedConfigEditor/Program.cs create mode 100644 FeedConfigEditor/Services/ConfigFileService.cs create mode 100644 FeedConfigEditor/Services/UrlHelper.cs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c3cc3fd --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +## Visual Studio 2026 / .NET .gitignore +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ +.vs/ +*.user +*.suo +*.userosscache +*.sln.docstates diff --git a/FeedConfigEditor.sln b/FeedConfigEditor.sln new file mode 100644 index 0000000..76b5167 --- /dev/null +++ b/FeedConfigEditor.sln @@ -0,0 +1,34 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "FeedConfigEditor", "FeedConfigEditor\FeedConfigEditor.csproj", "{D33225C7-64E8-4C44-BB40-D28618EDD6F0}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Debug|x64.ActiveCfg = Debug|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Debug|x64.Build.0 = Debug|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Debug|x86.ActiveCfg = Debug|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Debug|x86.Build.0 = Debug|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Release|Any CPU.Build.0 = Release|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Release|x64.ActiveCfg = Release|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Release|x64.Build.0 = Release|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Release|x86.ActiveCfg = Release|Any CPU + {D33225C7-64E8-4C44-BB40-D28618EDD6F0}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal diff --git a/FeedConfigEditor.slnx b/FeedConfigEditor.slnx new file mode 100644 index 0000000..cfa133b --- /dev/null +++ b/FeedConfigEditor.slnx @@ -0,0 +1,3 @@ + + + diff --git a/FeedConfigEditor/FeedConfigEditor.csproj b/FeedConfigEditor/FeedConfigEditor.csproj new file mode 100644 index 0000000..bcc0522 --- /dev/null +++ b/FeedConfigEditor/FeedConfigEditor.csproj @@ -0,0 +1,25 @@ + + + + WinExe + net10.0-windows + enable + true + enable + SystemAware + フィード設定エディタ + FeedConfigEditor + + + + + + Z:\自作ソフト\FeedConfigEditor\ + + + + + + + + \ No newline at end of file diff --git a/FeedConfigEditor/MainForm.cs b/FeedConfigEditor/MainForm.cs new file mode 100644 index 0000000..df09fc5 --- /dev/null +++ b/FeedConfigEditor/MainForm.cs @@ -0,0 +1,939 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Diagnostics; +using System.Drawing; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using System.Windows.Forms; +using FeedConfigEditor.Models; +using FeedConfigEditor.Services; + +namespace FeedConfigEditor; + +/// +/// メインウィンドウフォーム +/// 初心者にも直感的でわかりやすいフィード設定(youtube.json等)エディタ +/// +public partial class MainForm : Form +{ + // 全アイテム一覧 + private readonly List _allItems = new(); + // 画面表示用バインディングリスト + private readonly BindingList _displayedItems = new(); + + // UIコンポーネント + private ComboBox cmbConfigFiles = null!; + private Button btnReload = null!; + private Button btnOpenFolder = null!; + + private TextBox txtUrl = null!; + private TextBox txtName = null!; + private ComboBox cmbCategory = null!; + private CheckBox chkEnabled = null!; + private Button btnAdd = null!; + private Button btnUpdate = null!; + private Button btnClear = null!; + + private TextBox txtSearch = null!; + private ComboBox cmbFilterCategory = null!; + private Label lblItemCount = null!; + + private DataGridView dgvItems = null!; + private Button btnSave = null!; + private Button btnDelete = null!; + private StatusStrip statusStrip = null!; + private ToolStripStatusLabel lblStatus = null!; + + // 編集中行の保持 + private FeedTargetItem? _selectedItem; + private bool _isUpdatingForm; + + public MainForm() + { + InitializeComponent(); + } + + private void InitializeComponent() + { + this.SuspendLayout(); + + // フォーム基本設定 + this.Text = "フィード設定エディタ - FeedConfigEditor"; + this.Size = new Size(1100, 750); + this.MinimumSize = new Size(900, 600); + this.StartPosition = FormStartPosition.CenterScreen; + this.Font = new Font("Meiryo UI", 9.5f, FontStyle.Regular); + this.BackColor = Color.FromArgb(248, 249, 250); + + // 全体コンテナパネル (Dock = Fill, Margin = 12) + var mainContainer = new Panel + { + Dock = DockStyle.Fill, + Padding = new Padding(16, 12, 16, 8) + }; + this.Controls.Add(mainContainer); + + // ------------------------------------------------------------- + // 1. 上部ヘッダー(ファイル選択・再読込・フォルダを開く) + // ------------------------------------------------------------- + var headerPanel = new Panel + { + Dock = DockStyle.Top, + Height = 44, + Padding = new Padding(0, 0, 0, 8) + }; + + var lblFileTitle = new Label + { + Text = "編集対象ファイル:", + AutoSize = true, + Location = new Point(0, 8), + Font = new Font("Meiryo UI", 9.5f, FontStyle.Bold), + ForeColor = Color.FromArgb(33, 37, 41) + }; + + cmbConfigFiles = new ComboBox + { + Location = new Point(130, 4), + Width = 240, + DropDownStyle = ComboBoxStyle.DropDownList, + Font = new Font("Meiryo UI", 9.5f) + }; + cmbConfigFiles.SelectedIndexChanged += async (s, e) => await LoadCurrentFileAsync(); + + btnReload = new Button + { + Text = "🔄 最新を再読込", + Location = new Point(380, 3), + Size = new Size(120, 30), + Cursor = Cursors.Hand, + BackColor = Color.FromArgb(233, 236, 239) + }; + btnReload.Click += async (s, e) => await LoadCurrentFileAsync(); + + btnOpenFolder = new Button + { + Text = "📁 フォルダを開く", + Location = new Point(510, 3), + Size = new Size(130, 30), + Cursor = Cursors.Hand, + BackColor = Color.FromArgb(233, 236, 239) + }; + btnOpenFolder.Click += (s, e) => ConfigFileService.OpenFolderInExplorer(); + + headerPanel.Controls.AddRange(new Control[] { lblFileTitle, cmbConfigFiles, btnReload, btnOpenFolder }); + + // ------------------------------------------------------------- + // 2. 入力フォーム(チャンネル追加・編集グループボックス) + // ------------------------------------------------------------- + var grpEdit = new GroupBox + { + Dock = DockStyle.Top, + Height = 155, + Text = " チャンネル・URLの追加 / 編集 ", + Font = new Font("Meiryo UI", 9.5f, FontStyle.Bold), + ForeColor = Color.FromArgb(13, 110, 253), + Padding = new Padding(12) + }; + + var formTable = new TableLayoutPanel + { + Dock = DockStyle.Fill, + ColumnCount = 6, + RowCount = 3, + Font = new Font("Meiryo UI", 9.5f, FontStyle.Regular), + ForeColor = Color.FromArgb(33, 37, 41) + }; + formTable.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 110)); // ラベル + formTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 50)); // URL + formTable.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 90)); // ラベル + formTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 35)); // 名称 + formTable.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 90)); // ラベル + formTable.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 15)); // カテゴリ + + // 1行目: URL入力 + var lblUrl = new Label { Text = "URL / ID :", AutoSize = true, Anchor = AnchorStyles.Left | AnchorStyles.Right, TextAlign = ContentAlignment.MiddleRight }; + txtUrl = new TextBox { Dock = DockStyle.Fill, PlaceholderText = "例: https://www.youtube.com/@mikazukin または UC... / @ハンドル" }; + txtUrl.TextChanged += TxtUrl_TextChanged; + + var lblName = new Label { Text = "名称 :", AutoSize = true, Anchor = AnchorStyles.Left | AnchorStyles.Right, TextAlign = ContentAlignment.MiddleRight }; + txtName = new TextBox { Dock = DockStyle.Fill, PlaceholderText = "チャンネル名・表示名" }; + + var lblCat = new Label { Text = "カテゴリ :", AutoSize = true, Anchor = AnchorStyles.Left | AnchorStyles.Right, TextAlign = ContentAlignment.MiddleRight }; + cmbCategory = new ComboBox { Dock = DockStyle.Fill, DropDownStyle = ComboBoxStyle.DropDown }; + + formTable.Controls.Add(lblUrl, 0, 0); + formTable.Controls.Add(txtUrl, 1, 0); + formTable.Controls.Add(lblName, 2, 0); + formTable.Controls.Add(txtName, 3, 0); + formTable.Controls.Add(lblCat, 4, 0); + formTable.Controls.Add(cmbCategory, 5, 0); + + // 2行目: 補足ヒント & 有効チェックボックス + var lblHint = new Label + { + Text = "💡 YouTubeのURL(https://www.youtube.com/@... や UC...)をそのまま貼り付け可能です。自動で整形されます。", + ForeColor = Color.Gray, + AutoSize = true, + Anchor = AnchorStyles.Left, + Font = new Font("Meiryo UI", 8.5f) + }; + formTable.SetColumnSpan(lblHint, 4); + + chkEnabled = new CheckBox + { + Text = "有効にする", + Checked = true, + AutoSize = true, + Anchor = AnchorStyles.Left, + Font = new Font("Meiryo UI", 9.5f, FontStyle.Bold) + }; + formTable.SetColumnSpan(chkEnabled, 2); + + formTable.Controls.Add(lblHint, 0, 1); + formTable.Controls.Add(chkEnabled, 4, 1); + + // 3行目: 操作ボタンパネル + var buttonPanel = new FlowLayoutPanel + { + Dock = DockStyle.Fill, + FlowDirection = FlowDirection.LeftToRight, + WrapContents = false, + Margin = new Padding(0, 4, 0, 0) + }; + formTable.SetColumnSpan(buttonPanel, 6); + + btnAdd = new Button + { + Text = "➕ リストに追加", + Size = new Size(130, 32), + BackColor = Color.FromArgb(13, 110, 253), + ForeColor = Color.White, + FlatStyle = FlatStyle.Flat, + Font = new Font("Meiryo UI", 9.5f, FontStyle.Bold), + Cursor = Cursors.Hand + }; + btnAdd.FlatAppearance.BorderSize = 0; + btnAdd.Click += BtnAdd_Click; + + btnUpdate = new Button + { + Text = "✎ 選択行を更新", + Size = new Size(130, 32), + BackColor = Color.FromArgb(25, 135, 84), + ForeColor = Color.White, + FlatStyle = FlatStyle.Flat, + Font = new Font("Meiryo UI", 9.5f, FontStyle.Bold), + Cursor = Cursors.Hand, + Enabled = false + }; + btnUpdate.FlatAppearance.BorderSize = 0; + btnUpdate.Click += BtnUpdate_Click; + + btnClear = new Button + { + Text = "✕ 入力をクリア", + Size = new Size(110, 32), + BackColor = Color.FromArgb(233, 236, 239), + FlatStyle = FlatStyle.Flat, + Cursor = Cursors.Hand + }; + btnClear.FlatAppearance.BorderSize = 0; + btnClear.Click += (s, e) => ClearInputForm(); + + buttonPanel.Controls.AddRange(new Control[] { btnAdd, btnUpdate, btnClear }); + formTable.Controls.Add(buttonPanel, 0, 2); + + grpEdit.Controls.Add(formTable); + + // ------------------------------------------------------------- + // 3. 検索・絞り込みバー + // ------------------------------------------------------------- + var filterPanel = new Panel + { + Dock = DockStyle.Top, + Height = 44, + Padding = new Padding(0, 8, 0, 4) + }; + + var lblSearch = new Label + { + Text = "🔍 検索:", + AutoSize = true, + Location = new Point(4, 14), + Font = new Font("Meiryo UI", 9.5f, FontStyle.Bold) + }; + + txtSearch = new TextBox + { + Location = new Point(65, 10), + Width = 240, + PlaceholderText = "名前・URLで絞り込み..." + }; + txtSearch.TextChanged += (s, e) => ApplyFilter(); + + var lblFilterCat = new Label + { + Text = "カテゴリ絞込:", + AutoSize = true, + Location = new Point(325, 14), + Font = new Font("Meiryo UI", 9.5f, FontStyle.Bold) + }; + + cmbFilterCategory = new ComboBox + { + Location = new Point(420, 10), + Width = 180, + DropDownStyle = ComboBoxStyle.DropDownList + }; + cmbFilterCategory.SelectedIndexChanged += (s, e) => ApplyFilter(); + + lblItemCount = new Label + { + Text = "件数: 0 件", + AutoSize = true, + Location = new Point(620, 14), + ForeColor = Color.FromArgb(108, 117, 125) + }; + + filterPanel.Controls.AddRange(new Control[] { lblSearch, txtSearch, lblFilterCat, cmbFilterCategory, lblItemCount }); + + // ------------------------------------------------------------- + // 4. 下部アクションバー(保存ボタン・削除ボタン) + // ------------------------------------------------------------- + var bottomPanel = new Panel + { + Dock = DockStyle.Bottom, + Height = 58, + Padding = new Padding(0, 10, 0, 4) + }; + + btnSave = new Button + { + Text = "💾 設定を保存する (C:\\feeds\\src\\youtube.json)", + Size = new Size(360, 40), + Dock = DockStyle.Left, + BackColor = Color.FromArgb(25, 135, 84), + ForeColor = Color.White, + FlatStyle = FlatStyle.Flat, + Font = new Font("Meiryo UI", 11f, FontStyle.Bold), + Cursor = Cursors.Hand + }; + btnSave.FlatAppearance.BorderSize = 0; + btnSave.Click += async (s, e) => await SaveToFileAsync(); + + btnDelete = new Button + { + Text = "🗑️ 選択行を削除", + Size = new Size(140, 40), + Dock = DockStyle.Right, + BackColor = Color.FromArgb(220, 53, 69), + ForeColor = Color.White, + FlatStyle = FlatStyle.Flat, + Font = new Font("Meiryo UI", 9.5f, FontStyle.Bold), + Cursor = Cursors.Hand, + Enabled = false + }; + btnDelete.FlatAppearance.BorderSize = 0; + btnDelete.Click += BtnDelete_Click; + + bottomPanel.Controls.Add(btnSave); + bottomPanel.Controls.Add(btnDelete); + + // ------------------------------------------------------------- + // 5. 一覧グリッド (DataGridView) + // ------------------------------------------------------------- + dgvItems = new DataGridView + { + Dock = DockStyle.Fill, + AutoGenerateColumns = false, + AllowUserToAddRows = false, + AllowUserToDeleteRows = false, + SelectionMode = DataGridViewSelectionMode.FullRowSelect, + MultiSelect = false, + RowHeadersVisible = false, + BackgroundColor = Color.White, + BorderStyle = BorderStyle.Fixed3D, + Font = new Font("Meiryo UI", 9.5f) + }; + dgvItems.AlternatingRowsDefaultCellStyle.BackColor = Color.FromArgb(248, 249, 250); + dgvItems.RowTemplate.Height = 32; + + // 列定義 + var colEnabled = new DataGridViewCheckBoxColumn + { + DataPropertyName = nameof(FeedTargetItem.Enabled), + HeaderText = "有効", + Width = 60, + SortMode = DataGridViewColumnSortMode.Automatic + }; + + var colName = new DataGridViewTextBoxColumn + { + DataPropertyName = nameof(FeedTargetItem.Name), + HeaderText = "名称 (チャンネル名・サイト名)", + Width = 260, + SortMode = DataGridViewColumnSortMode.Automatic + }; + + var colUrl = new DataGridViewTextBoxColumn + { + DataPropertyName = nameof(FeedTargetItem.Url), + HeaderText = "URL / チャンネルID / ハンドル", + Width = 320, + SortMode = DataGridViewColumnSortMode.Automatic + }; + + var colCat = new DataGridViewTextBoxColumn + { + DataPropertyName = nameof(FeedTargetItem.Category), + HeaderText = "カテゴリ", + Width = 140, + SortMode = DataGridViewColumnSortMode.Automatic + }; + + var colAction = new DataGridViewButtonColumn + { + HeaderText = "確認", + Text = "🌐 ブラウザで開く", + UseColumnTextForButtonValue = true, + Width = 130 + }; + + dgvItems.Columns.AddRange(colEnabled, colName, colUrl, colCat, colAction); + dgvItems.DataSource = _displayedItems; + + // イベント設定 + dgvItems.SelectionChanged += DgvItems_SelectionChanged; + dgvItems.CellContentClick += DgvItems_CellContentClick; + dgvItems.CellDoubleClick += (s, e) => + { + if (e.RowIndex >= 0 && e.RowIndex < _displayedItems.Count) + { + OpenInBrowser(_displayedItems[e.RowIndex]); + } + }; + + // 右クリックメニュー + var contextMenu = new ContextMenuStrip(); + var menuOpen = new ToolStripMenuItem("🌐 ブラウザで開く", null, (s, e) => + { + if (_selectedItem != null) OpenInBrowser(_selectedItem); + }); + var menuCopyUrl = new ToolStripMenuItem("📋 URL/IDをコピー", null, (s, e) => + { + if (_selectedItem != null && !string.IsNullOrEmpty(_selectedItem.Url)) + { + Clipboard.SetText(_selectedItem.Url); + SetStatus($"クリップボードにコピーしました: {_selectedItem.Url}"); + } + }); + var menuToggle = new ToolStripMenuItem("🔄 有効/無効の切り替え", null, (s, e) => + { + if (_selectedItem != null) + { + _selectedItem.Enabled = !_selectedItem.Enabled; + dgvItems.Refresh(); + } + }); + var menuDel = new ToolStripMenuItem("🗑️ 選択行を削除", null, (s, e) => BtnDelete_Click(s, e)); + + contextMenu.Items.AddRange(new ToolStripItem[] { menuOpen, menuCopyUrl, menuToggle, new ToolStripSeparator(), menuDel }); + dgvItems.ContextMenuStrip = contextMenu; + + // ------------------------------------------------------------- + // 6. ステータスストリップ(最下部) + // ------------------------------------------------------------- + statusStrip = new StatusStrip(); + lblStatus = new ToolStripStatusLabel + { + Text = "準備完了", + Spring = true, + TextAlign = ContentAlignment.MiddleLeft + }; + statusStrip.Items.Add(lblStatus); + this.Controls.Add(statusStrip); + + // コントロール配置(下から順にDock配置) + mainContainer.Controls.Add(dgvItems); + mainContainer.Controls.Add(filterPanel); + mainContainer.Controls.Add(grpEdit); + mainContainer.Controls.Add(headerPanel); + mainContainer.Controls.Add(bottomPanel); + + this.ResumeLayout(false); + this.PerformLayout(); + + // 起動時初期化 + this.Load += async (s, e) => await InitializeAppAsync(); + } + + /// + /// アプリケーション起動時の初期データロード + /// + private async Task InitializeAppAsync() + { + try + { + var files = ConfigFileService.GetAvailableConfigFiles(); + cmbConfigFiles.Items.Clear(); + foreach (var f in files) + { + cmbConfigFiles.Items.Add(f); + } + + if (cmbConfigFiles.Items.Count > 0) + { + cmbConfigFiles.SelectedIndex = 0; + } + else + { + await LoadCurrentFileAsync(); + } + } + catch (Exception ex) + { + MessageBox.Show($"初期化中にエラーが発生しました:\n{ex.Message}", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + + /// + /// 選択された設定ファイルからアイテムを読み込みます + /// + private async Task LoadCurrentFileAsync() + { + string fileName = cmbConfigFiles.SelectedItem?.ToString() ?? ConfigFileService.DefaultFileName; + btnSave.Text = $"💾 設定を保存する ({fileName})"; + + try + { + SetStatus($"読み込み中: {fileName}..."); + var items = await ConfigFileService.LoadAsync(fileName); + + _allItems.Clear(); + _allItems.AddRange(DeduplicateItems(items)); + + RefreshCategoryDropdowns(); + ApplyFilter(); + ClearInputForm(); + + SetStatus($"読み込み完了: {fileName} (計 {_allItems.Count} 件)"); + } + catch (Exception ex) + { + MessageBox.Show($"設定ファイルの読み込みに失敗しました:\n{ex.Message}", "読み込みエラー", MessageBoxButtons.OK, MessageBoxIcon.Error); + SetStatus($"読み込み失敗: {ex.Message}"); + } + } + + /// + /// カテゴリ選択コンボボックスの選択肢を更新 + /// + private void RefreshCategoryDropdowns() + { + var categories = _allItems + .Select(i => string.IsNullOrWhiteSpace(i.Category) ? "その他" : i.Category.Trim()) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(c => c) + .ToList(); + + if (!categories.Contains("その他")) categories.Insert(0, "その他"); + if (!categories.Contains("ゲーム")) categories.Add("ゲーム"); + + // 入力用コンボボックス + string currentInputCat = cmbCategory.Text; + cmbCategory.Items.Clear(); + foreach (var c in categories) cmbCategory.Items.Add(c); + cmbCategory.Text = string.IsNullOrEmpty(currentInputCat) ? (categories.FirstOrDefault() ?? "その他") : currentInputCat; + + // 絞り込み用コンボボックス + string currentFilter = cmbFilterCategory.SelectedItem?.ToString() ?? "すべて"; + cmbFilterCategory.Items.Clear(); + cmbFilterCategory.Items.Add("すべて"); + foreach (var c in categories) cmbFilterCategory.Items.Add(c); + + if (cmbFilterCategory.Items.Contains(currentFilter)) + { + cmbFilterCategory.SelectedItem = currentFilter; + } + else + { + cmbFilterCategory.SelectedIndex = 0; + } + } + + /// + /// 検索条件およびカテゴリ絞り込みを適用 + /// + private void ApplyFilter() + { + string keyword = txtSearch.Text.Trim(); + string selectedCat = cmbFilterCategory.SelectedItem?.ToString() ?? "すべて"; + + IEnumerable query = _allItems; + + // カテゴリ絞り込み + if (!string.IsNullOrEmpty(selectedCat) && selectedCat != "すべて") + { + query = query.Where(i => string.Equals(i.Category, selectedCat, StringComparison.OrdinalIgnoreCase)); + } + + // キーワード検索 + if (!string.IsNullOrEmpty(keyword)) + { + query = query.Where(i => + (i.Name != null && i.Name.Contains(keyword, StringComparison.OrdinalIgnoreCase)) || + (i.Url != null && i.Url.Contains(keyword, StringComparison.OrdinalIgnoreCase)) || + (i.Category != null && i.Category.Contains(keyword, StringComparison.OrdinalIgnoreCase))); + } + + var filtered = query.ToList(); + + _displayedItems.Clear(); + foreach (var item in filtered) + { + _displayedItems.Add(item); + } + + lblItemCount.Text = $"全 {_allItems.Count} 件 (表示中: {_displayedItems.Count} 件)"; + } + + /// + /// URL入力時の自動解析と補完アシスト + /// https://www.youtube.com/@mikazukin 等の入力を即座に検出・整形します + /// + private void TxtUrl_TextChanged(object? sender, EventArgs e) + { + if (_isUpdatingForm) return; + + string input = txtUrl.Text.Trim(); + if (string.IsNullOrEmpty(input)) return; + + // URL形式(http:// または https://)が含まれている場合、自動正規化 + if (input.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + input.StartsWith("https://", StringComparison.OrdinalIgnoreCase) || + input.Contains("youtube.com/")) + { + var (normalized, suggestedName) = UrlHelper.NormalizeInput(input); + if (!string.IsNullOrEmpty(normalized) && normalized != input) + { + _isUpdatingForm = true; + txtUrl.Text = normalized; + txtUrl.SelectionStart = txtUrl.Text.Length; + + // 名称欄が空で推奨名称があれば自動補完 + if (string.IsNullOrWhiteSpace(txtName.Text) && !string.IsNullOrEmpty(suggestedName)) + { + txtName.Text = suggestedName; + } + _isUpdatingForm = false; + + SetStatus($"URLを検出・自動正規化しました: {normalized}"); + } + } + } + + /// + /// 新規追加ボタン押下 + /// 同一URLが既に存在する場合は新規作成せず、既存アイテムの内容を上書き更新して重複を防ぎます。 + /// + private void BtnAdd_Click(object? sender, EventArgs e) + { + string rawUrl = txtUrl.Text.Trim(); + if (string.IsNullOrWhiteSpace(rawUrl)) + { + MessageBox.Show("URL または チャンネルID / ハンドル を入力してください。", "入力確認", MessageBoxButtons.OK, MessageBoxIcon.Warning); + txtUrl.Focus(); + return; + } + + // URL正規化 + var (cleanUrl, suggestedName) = UrlHelper.NormalizeInput(rawUrl); + string finalUrl = string.IsNullOrEmpty(cleanUrl) ? rawUrl : cleanUrl; + string name = string.IsNullOrWhiteSpace(txtName.Text) + ? (!string.IsNullOrEmpty(suggestedName) ? suggestedName : finalUrl) + : txtName.Text.Trim(); + + string category = string.IsNullOrWhiteSpace(cmbCategory.Text) ? "その他" : cmbCategory.Text.Trim(); + + // 重複チェック: 既に同一URLが存在する場合は上書き更新 + var existing = _allItems.FirstOrDefault(i => string.Equals(i.Url, finalUrl, StringComparison.OrdinalIgnoreCase)); + if (existing != null) + { + // 既存データを上書き更新 + existing.Name = name; + existing.Category = category; + existing.Enabled = chkEnabled.Checked; + + RefreshCategoryDropdowns(); + ApplyFilter(); + SelectRowByItem(existing); + ClearInputForm(); + + SetStatus($"🔄 既に登録済みのURLのため上書き更新しました: {name} ({finalUrl})"); + + MessageBox.Show( + $"同じURL/ID({finalUrl})が既に登録されていたため、既存のデータを最新の内容で上書き更新しました。\n\n" + + $"名称: {name}\nカテゴリ: {category}\n状態: {(chkEnabled.Checked ? "有効" : "無効")}", + "上書き更新完了", + MessageBoxButtons.OK, + MessageBoxIcon.Information); + return; + } + + var newItem = new FeedTargetItem + { + Url = finalUrl, + Name = name, + Category = category, + Enabled = chkEnabled.Checked + }; + + _allItems.Add(newItem); + RefreshCategoryDropdowns(); + ApplyFilter(); + + // 追加した行を選択 + SelectRowByItem(newItem); + SetStatus($"追加しました: {name} ({finalUrl})"); + + ClearInputForm(); + } + + /// + /// 更新ボタン押下 + /// 他の行とURLが重複する場合は統合して上書きします。 + /// + private void BtnUpdate_Click(object? sender, EventArgs e) + { + if (_selectedItem == null) return; + + string rawUrl = txtUrl.Text.Trim(); + if (string.IsNullOrWhiteSpace(rawUrl)) + { + MessageBox.Show("URL または チャンネルID / ハンドル を入力してください。", "入力確認", MessageBoxButtons.OK, MessageBoxIcon.Warning); + txtUrl.Focus(); + return; + } + + var (cleanUrl, _) = UrlHelper.NormalizeInput(rawUrl); + string finalUrl = string.IsNullOrEmpty(cleanUrl) ? rawUrl : cleanUrl; + string name = string.IsNullOrWhiteSpace(txtName.Text) ? finalUrl : txtName.Text.Trim(); + string category = string.IsNullOrWhiteSpace(cmbCategory.Text) ? "その他" : cmbCategory.Text.Trim(); + + // 選択中以外の行に同一URLが存在する場合、重複を防ぐため統合 + var conflict = _allItems.FirstOrDefault(i => i != _selectedItem && string.Equals(i.Url, finalUrl, StringComparison.OrdinalIgnoreCase)); + if (conflict != null) + { + _allItems.Remove(conflict); + SetStatus($"重複していた既存行({conflict.Name})を統合し、上書き更新しました: {finalUrl}"); + } + + _selectedItem.Url = finalUrl; + _selectedItem.Name = name; + _selectedItem.Category = category; + _selectedItem.Enabled = chkEnabled.Checked; + + dgvItems.Refresh(); + RefreshCategoryDropdowns(); + ApplyFilter(); + SelectRowByItem(_selectedItem); + + SetStatus($"更新しました: {_selectedItem.Name} ({_selectedItem.Url})"); + } + + /// + /// 削除ボタン押下 + /// + private void BtnDelete_Click(object? sender, EventArgs e) + { + if (_selectedItem == null) return; + + var res = MessageBox.Show( + $"以下のアイテムをリストから削除しますか?\n\n名称: {_selectedItem.Name}\nURL: {_selectedItem.Url}\nカテゴリ: {_selectedItem.Category}", + "削除確認", + MessageBoxButtons.YesNo, + MessageBoxIcon.Question); + + if (res == DialogResult.Yes) + { + string name = _selectedItem.Name ?? _selectedItem.Url; + _allItems.Remove(_selectedItem); + RefreshCategoryDropdowns(); + ApplyFilter(); + ClearInputForm(); + + SetStatus($"削除しました: {name}"); + } + } + + /// + /// アイテム一覧からURL重複を排除・統合します(後勝ちマージ) + /// + private List DeduplicateItems(IEnumerable items) + { + var dict = new Dictionary(StringComparer.OrdinalIgnoreCase); + foreach (var item in items) + { + string key = (item.Url ?? "").Trim(); + if (string.IsNullOrEmpty(key)) continue; + + // 同一URLがある場合は最新のもので上書き + dict[key] = item; + } + return dict.Values.ToList(); + } + + /// + /// ファイルへ保存 + /// 保存前に念のため重複排除を実行し、重複データが存在しないようにします。 + /// + private async Task SaveToFileAsync() + { + string fileName = cmbConfigFiles.SelectedItem?.ToString() ?? ConfigFileService.DefaultFileName; + + try + { + // 保存前に念のため重複を排除 + var uniqueItems = DeduplicateItems(_allItems); + if (uniqueItems.Count != _allItems.Count) + { + int diff = _allItems.Count - uniqueItems.Count; + _allItems.Clear(); + _allItems.AddRange(uniqueItems); + RefreshCategoryDropdowns(); + ApplyFilter(); + SetStatus($"重複していた {diff} 件のデータを統合しました。"); + } + + SetStatus($"保存中: {fileName}..."); + await ConfigFileService.SaveAsync(fileName, _allItems); + + SetStatus($"✅ 保存完了: {fileName}(計 {_allItems.Count} 件)※ 重複なし・バックアップ .bak も作成されました"); + + MessageBox.Show( + $"設定ファイル '{fileName}' を正常に保存しました!(全 {_allItems.Count} 件)\n\n" + + $"※ 重複データはすべて統合・上書きされ、rss-generator に即時反映されます。", + "保存完了", + MessageBoxButtons.OK, + MessageBoxIcon.Information); + } + catch (Exception ex) + { + MessageBox.Show($"保存中にエラーが発生しました:\n{ex.Message}", "保存エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); + SetStatus($"保存失敗: {ex.Message}"); + } + } + + /// + /// DataGridViewの行選択イベント + /// + private void DgvItems_SelectionChanged(object? sender, EventArgs e) + { + if (dgvItems.SelectedRows.Count == 0) + { + _selectedItem = null; + btnUpdate.Enabled = false; + btnDelete.Enabled = false; + return; + } + + int index = dgvItems.SelectedRows[0].Index; + if (index >= 0 && index < _displayedItems.Count) + { + _selectedItem = _displayedItems[index]; + + _isUpdatingForm = true; + txtUrl.Text = _selectedItem.Url; + txtName.Text = _selectedItem.Name ?? string.Empty; + cmbCategory.Text = _selectedItem.Category; + chkEnabled.Checked = _selectedItem.Enabled; + _isUpdatingForm = false; + + btnUpdate.Enabled = true; + btnDelete.Enabled = true; + } + } + + /// + /// ボタン列セルクリックイベント(ブラウザで開く) + /// + private void DgvItems_CellContentClick(object? sender, DataGridViewCellEventArgs e) + { + if (e.RowIndex >= 0 && e.ColumnIndex == 4) // 確認ボタン列 + { + if (e.RowIndex < _displayedItems.Count) + { + OpenInBrowser(_displayedItems[e.RowIndex]); + } + } + } + + /// + /// ブラウザで対象を開く + /// + private void OpenInBrowser(FeedTargetItem item) + { + string fullUrl = UrlHelper.GetBrowserUrl(item.Url); + if (!string.IsNullOrEmpty(fullUrl)) + { + try + { + Process.Start(new ProcessStartInfo + { + FileName = fullUrl, + UseShellExecute = true + }); + SetStatus($"ブラウザで開きました: {fullUrl}"); + } + catch (Exception ex) + { + MessageBox.Show($"ブラウザを開けませんでした:\n{ex.Message}", "エラー", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + } + } + + /// + /// 入力フォームのクリア + /// + private void ClearInputForm() + { + _selectedItem = null; + _isUpdatingForm = true; + txtUrl.Clear(); + txtName.Clear(); + chkEnabled.Checked = true; + _isUpdatingForm = false; + + btnUpdate.Enabled = false; + btnDelete.Enabled = false; + dgvItems.ClearSelection(); + txtUrl.Focus(); + } + + /// + /// 指定アイテムの行を選択 + /// + private void SelectRowByItem(FeedTargetItem item) + { + for (int i = 0; i < dgvItems.Rows.Count; i++) + { + if (dgvItems.Rows[i].DataBoundItem == item) + { + dgvItems.Rows[i].Selected = true; + dgvItems.FirstDisplayedScrollingRowIndex = i; + break; + } + } + } + + /// + /// ステータスメッセージの設定 + /// + private void SetStatus(string message) + { + lblStatus.Text = $"[{DateTime.Now:HH:mm:ss}] {message}"; + } +} diff --git a/FeedConfigEditor/Models/FeedTargetItem.cs b/FeedConfigEditor/Models/FeedTargetItem.cs new file mode 100644 index 0000000..3550967 --- /dev/null +++ b/FeedConfigEditor/Models/FeedTargetItem.cs @@ -0,0 +1,124 @@ +using System.ComponentModel; +using System.Text.Json.Serialization; + +namespace FeedConfigEditor.Models; + +/// +/// フィード設定のターゲットアイテム(JSONの1要素) +/// +public class FeedTargetItem : INotifyPropertyChanged +{ + private string _url = string.Empty; + private string? _name; + private string _category = "その他"; + private bool _enabled = true; + + /// + /// 有効/無効フラグ + /// + [JsonPropertyName("enabled")] + [DisplayName("有効")] + public bool Enabled + { + get => _enabled; + set + { + if (_enabled != value) + { + _enabled = value; + OnPropertyChanged(nameof(Enabled)); + } + } + } + + /// + /// チャンネル名・サイト名 + /// + [JsonPropertyName("name")] + [DisplayName("名称")] + public string? Name + { + get => _name; + set + { + if (_name != value) + { + _name = value; + OnPropertyChanged(nameof(Name)); + } + } + } + + /// + /// 対象URL(またはチャンネルID・ハンドル) + /// + [JsonPropertyName("url")] + [DisplayName("URL / ID")] + public string Url + { + get => _url; + set + { + if (_url != value) + { + _url = value; + OnPropertyChanged(nameof(Url)); + } + } + } + + /// + /// 出力カテゴリ名(ゲーム、野球、音楽など) + /// + [JsonPropertyName("category")] + [DisplayName("カテゴリ")] + public string Category + { + get => _category; + set + { + if (_category != value) + { + _category = value; + OnPropertyChanged(nameof(Category)); + } + } + } + + /// + /// 旧形式(idOrHandle)の読み込み互換用プロパティ + /// 書き出し時は出力されません + /// + [JsonPropertyName("idOrHandle")] + public string? LegacyIdOrHandle + { + set + { + if (!string.IsNullOrEmpty(value) && string.IsNullOrEmpty(_url)) + { + Url = value; + } + } + } + + /// + /// オブジェクトの複製を作成します + /// + public FeedTargetItem Clone() + { + return new FeedTargetItem + { + Url = this.Url, + Name = this.Name, + Category = this.Category, + Enabled = this.Enabled + }; + } + + public event PropertyChangedEventHandler? PropertyChanged; + + protected void OnPropertyChanged(string propertyName) + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } +} diff --git a/FeedConfigEditor/Program.cs b/FeedConfigEditor/Program.cs new file mode 100644 index 0000000..a8be6f6 --- /dev/null +++ b/FeedConfigEditor/Program.cs @@ -0,0 +1,18 @@ +using System; +using System.Windows.Forms; + +namespace FeedConfigEditor; + +static class Program +{ + /// + /// アプリケーションのメインエントリーポイント + /// + [STAThread] + static void Main() + { + // 高DPI対応、デフォルトフォント、VisualStylesの初期化 + ApplicationConfiguration.Initialize(); + Application.Run(new MainForm()); + } +} \ No newline at end of file diff --git a/FeedConfigEditor/Services/ConfigFileService.cs b/FeedConfigEditor/Services/ConfigFileService.cs new file mode 100644 index 0000000..5026cfe --- /dev/null +++ b/FeedConfigEditor/Services/ConfigFileService.cs @@ -0,0 +1,128 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Text.Encodings.Web; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using FeedConfigEditor.Models; + +namespace FeedConfigEditor.Services; + +/// +/// 設定ファイル(C:\feeds\src\*.json)の読み込み・保存・バックアップを管理するサービスクラス +/// +public static class ConfigFileService +{ + public const string DefaultDirectory = @"C:\feeds\src"; + public const string DefaultFileName = "youtube.json"; + + private static readonly JsonSerializerOptions JsonOptions = new() + { + WriteIndented = true, + Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, + PropertyNameCaseInsensitive = true, + ReadCommentHandling = JsonCommentHandling.Skip, + AllowTrailingCommas = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull + }; + + /// + /// ディレクトリが存在することを確認し、パスを返します + /// + public static string EnsureDirectory(string? dirPath = null) + { + string path = string.IsNullOrWhiteSpace(dirPath) ? DefaultDirectory : dirPath; + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + return path; + } + + /// + /// ディレクトリ配下の全 JSON ファイル名一覧を取得します + /// + public static List GetAvailableConfigFiles(string? dirPath = null) + { + string dir = EnsureDirectory(dirPath); + var files = Directory.GetFiles(dir, "*.json"); + var result = new List(); + + foreach (var file in files) + { + result.Add(Path.GetFileName(file)); + } + + if (!result.Contains(DefaultFileName, StringComparer.OrdinalIgnoreCase)) + { + result.Insert(0, DefaultFileName); + } + + return result; + } + + /// + /// 設定ファイルからアイテム一覧を読み込みます + /// + public static async Task> LoadAsync(string fileName, string? dirPath = null) + { + string dir = EnsureDirectory(dirPath); + string filePath = Path.Combine(dir, fileName); + + if (!File.Exists(filePath)) + { + return new List(); + } + + using var stream = File.OpenRead(filePath); + var items = await JsonSerializer.DeserializeAsync>(stream, JsonOptions); + return items ?? new List(); + } + + /// + /// 設定ファイルにアイテム一覧を保存します。 + /// 保存前に .bak バックアップファイルを自動生成します。 + /// + public static async Task SaveAsync(string fileName, IEnumerable items, string? dirPath = null) + { + string dir = EnsureDirectory(dirPath); + string filePath = Path.Combine(dir, fileName); + + // 既存ファイルがあればバックアップ作成 + if (File.Exists(filePath)) + { + string bakPath = filePath + ".bak"; + try + { + File.Copy(filePath, bakPath, overwrite: true); + } + catch + { + // バックアップ作成失敗でも保存処理は継続 + } + } + + using var stream = File.Create(filePath); + await JsonSerializer.SerializeAsync(stream, items, JsonOptions); + } + + /// + /// エクスプローラーでフォルダを開きます + /// + public static void OpenFolderInExplorer(string? dirPath = null) + { + string dir = EnsureDirectory(dirPath); + try + { + Process.Start(new ProcessStartInfo + { + FileName = dir, + UseShellExecute = true + }); + } + catch { } + } +} diff --git a/FeedConfigEditor/Services/UrlHelper.cs b/FeedConfigEditor/Services/UrlHelper.cs new file mode 100644 index 0000000..17a5f00 --- /dev/null +++ b/FeedConfigEditor/Services/UrlHelper.cs @@ -0,0 +1,107 @@ +using System; +using System.Text.RegularExpressions; + +namespace FeedConfigEditor.Services; + +/// +/// YouTubeや各種URLの解析・正規化・ブラウザリンク生成を行うユーティリティ +/// +public static class UrlHelper +{ + /// + /// 入力された文字列(URLやチャンネルID等)を解析・正規化します。 + /// https://www.youtube.com/@mikazukin などのURLからクリーンな識別子と推奨名称を抽出します。 + /// + /// 入力文字列 + /// (正規化されたURL/ID, 推奨される名前) + public static (string NormalizedUrl, string SuggestedName) NormalizeInput(string rawInput) + { + if (string.IsNullOrWhiteSpace(rawInput)) + { + return (string.Empty, string.Empty); + } + + string text = rawInput.Trim(); + + // 1. YouTube ハンドルURL: https://www.youtube.com/@username... + var matchHandle = Regex.Match(text, @"(?:https?:\/\/)?(?:www\.)?youtube\.com\/(@[a-zA-Z0-9_\-\.]+)", RegexOptions.IgnoreCase); + if (matchHandle.Success) + { + string handle = matchHandle.Groups[1].Value; + string suggestedName = handle.TrimStart('@'); + return (handle, suggestedName); + } + + // 2. YouTube チャンネルID URL: https://www.youtube.com/channel/(UC...) + var matchChannel = Regex.Match(text, @"(?:https?:\/\/)?(?:www\.)?youtube\.com\/channel\/(UC[a-zA-Z0-9_\-]+)", RegexOptions.IgnoreCase); + if (matchChannel.Success) + { + string channelId = matchChannel.Groups[1].Value; + return (channelId, string.Empty); + } + + // 3. YouTube カスタムURL: https://www.youtube.com/c/xxx または /user/xxx + var matchCustom = Regex.Match(text, @"(?:https?:\/\/)?(?:www\.)?youtube\.com\/(?:c|user)\/([a-zA-Z0-9_\-\.]+)", RegexOptions.IgnoreCase); + if (matchCustom.Success) + { + string customName = matchCustom.Groups[1].Value; + return ($"@{customName}", customName); + } + + // 4. @から始まるハンドル直打ち: @mikazukin + if (text.StartsWith("@")) + { + return (text, text.TrimStart('@')); + } + + // 5. チャンネルID直打ち: UC... + if (text.StartsWith("UC", StringComparison.OrdinalIgnoreCase) && text.Length >= 20) + { + return (text, string.Empty); + } + + // 6. 一般的なWebサイトURLの場合 + if (text.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + text.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + try + { + var uri = new Uri(text); + string clean = $"{uri.Scheme}://{uri.Host}{uri.AbsolutePath.TrimEnd('/')}"; + return (clean, string.Empty); + } + catch + { + return (text, string.Empty); + } + } + + return (text, string.Empty); + } + + /// + /// ブラウザで表示するための完全なURLを返します。 + /// + public static string GetBrowserUrl(string urlOrId) + { + if (string.IsNullOrWhiteSpace(urlOrId)) return string.Empty; + + string target = urlOrId.Trim(); + if (target.StartsWith("@")) + { + return $"https://www.youtube.com/{target}"; + } + if (target.StartsWith("UC", StringComparison.OrdinalIgnoreCase)) + { + return $"https://www.youtube.com/channel/{target}"; + } + if (target.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || + target.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) + { + return target; + } + + // @なしの場合はYouTubeハンドルとして扱う + return $"https://www.youtube.com/@{target}"; + } +}