commit fdf0c890bb81a87d9906e357487e8370dcbd092e Author: uduki Date: Thu Oct 1 09:42:29 2026 +0900 feat: 初回コミット (MomongaDownloader) 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/MomongaDownloader.slnx b/MomongaDownloader.slnx new file mode 100644 index 0000000..7c4701d --- /dev/null +++ b/MomongaDownloader.slnx @@ -0,0 +1,3 @@ + + + diff --git a/MomongaDownloader/Form1.Designer.cs b/MomongaDownloader/Form1.Designer.cs new file mode 100644 index 0000000..e453da6 --- /dev/null +++ b/MomongaDownloader/Form1.Designer.cs @@ -0,0 +1,72 @@ +namespace MomongaDownloader +{ + partial class Form1 + { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() + { + txtURL = new TextBox(); + btnDownload = new Button(); + SuspendLayout(); + // + // txtURL + // + txtURL.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right; + txtURL.Location = new Point(12, 12); + txtURL.Name = "txtURL"; + txtURL.Size = new Size(695, 23); + txtURL.TabIndex = 0; + // + // btnDownload + // + btnDownload.Anchor = AnchorStyles.Top | AnchorStyles.Right; + btnDownload.Location = new Point(713, 12); + btnDownload.Name = "btnDownload"; + btnDownload.Size = new Size(75, 23); + btnDownload.TabIndex = 1; + btnDownload.Text = "実行"; + btnDownload.UseVisualStyleBackColor = true; + btnDownload.Click += btnDownload_Click; + // + // Form1 + // + AutoScaleDimensions = new SizeF(7F, 15F); + AutoScaleMode = AutoScaleMode.Font; + ClientSize = new Size(800, 450); + Controls.Add(btnDownload); + Controls.Add(txtURL); + Name = "Form1"; + Text = "Form1"; + ResumeLayout(false); + PerformLayout(); + } + + #endregion + + private TextBox txtURL; + private Button btnDownload; + } +} diff --git a/MomongaDownloader/Form1.cs b/MomongaDownloader/Form1.cs new file mode 100644 index 0000000..ad0672f --- /dev/null +++ b/MomongaDownloader/Form1.cs @@ -0,0 +1,213 @@ +using AngleSharp; +using System.IO.Compression; +using System.ServiceModel.Syndication; +using System.Xml; + +namespace MomongaDownloader +{ + public partial class Form1 : Form + { + // HttpClientはアプリケーション全体で使い回すため、static readonlyで定義します + private static readonly HttpClient _httpClient = new HttpClient(); + public Form1() + { + InitializeComponent(); + + txtURL.Text = ""; + + // サーバー側でボットとして弾かれないよう、一般的なブラウザのユーザーエージェントを設定します + _httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"); + } + + private async void btnDownload_Click(object sender, EventArgs e) + { + var pageMaster = "https://momon-ga.com/fanzine"; + + var linkList = new List(); + for (int pageId = 1; pageId <= 50; pageId++) + { + var pageURL = $"{pageMaster}/feed/atom/{(pageId > 1 ? $"?paged={pageId}" : "")}"; + linkList.Add(pageURL); + } + + var tasks = linkList.Select(url => GetFeedItems(_httpClient, url)).ToList(); + var results = await Task.WhenAll(tasks); + var allItems = results.SelectMany(items => items).ToList(); + + var urlList = new List(); + foreach (var originalItem in allItems) + { + + var link = originalItem.Links.FirstOrDefault()?.Uri; + if (link != null) + { + urlList.Add(link.ToString()); + } + } + + foreach (var urlString in urlList) + { + this.DownloadZip(urlString); + } + } + + private async void DownloadZip(string urlString) + { + try + { + + // URLの形式が正しいかチェック + if (string.IsNullOrWhiteSpace(urlString) || !Uri.TryCreate(urlString, UriKind.Absolute, out Uri baseUri)) + { + // 有効なURLを入力してください。 + return; + } + + try + { + // UI操作を一時無効化(連打防止) + btnDownload.Enabled = false; + + // 1. AngleSharpを使ってHTMLドキュメントを取得・解析 + var config = Configuration.Default.WithDefaultLoader(); + using var context = BrowsingContext.New(config); + using var document = await context.OpenAsync(urlString); + + // 2. h1タグの値を取得してファイル名を生成し、使用不可文字をサニタイズ + var h1Element = document.QuerySelector("h1"); + string title = h1Element != null ? h1Element.TextContent.Trim() : "download"; + string safeFileName = SanitizeFileName(title); + if (string.IsNullOrEmpty(safeFileName)) + { + safeFileName = "download"; + } + + // 3. 対象のdivタグ以下のimgタグからURLを抽出 + var imgElements = document.QuerySelectorAll("#post-hentai img"); + var imageUrls = new List(); + + foreach (var img in imgElements) + { + string src = img.GetAttribute("src"); + if (!string.IsNullOrEmpty(src)) + { + // 相対URLの場合も考慮して、絶対URLに解決する + if (Uri.TryCreate(baseUri, src, out Uri absoluteUri)) + { + imageUrls.Add(absoluteUri); + } + } + } + + if (imageUrls.Count == 0) + { + // 指定された条件の画像が見つかりませんでした。 + return; + } + + // 4. SemaphoreSlimを用いて同時接続数を制限し、画像を並列ダウンロード + int maxDegreeOfParallelism = 5; // 同時ダウンロード数の上限(適宜調整) + using var semaphore = new SemaphoreSlim(maxDegreeOfParallelism); + + // 抽出した順番通りにタスクを作成 + var downloadTasks = imageUrls.Select(async uri => + { + await semaphore.WaitAsync(); + try + { + return await _httpClient.GetByteArrayAsync(uri); + } + catch (Exception) + { + // ダウンロード失敗時はnullを返すなどのエラーハンドリング + return null; + } + finally + { + semaphore.Release(); + } + }).ToList(); + + // 全タスクを待機 + byte[][] downloadedImages = await Task.WhenAll(downloadTasks); + + // 5. exeのディレクトリを取得し、ZIPファイルへの絶対パスを構築 + string exeDir = AppContext.BaseDirectory; + string zipFilePath = Path.Combine(exeDir, $"{safeFileName}.zip"); + + // 6. ZipArchiveを用いて圧縮と保存 + using (var fileStream = new FileStream(zipFilePath, FileMode.Create)) + using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, false)) + { + for (int i = 0; i < downloadedImages.Length; i++) + { + var imgData = downloadedImages[i]; + if (imgData == null) continue; // ダウンロードに失敗した画像はスキップ + + // 拡張子を取得(不明な場合は.jpgをデフォルトに) + string extension = Path.GetExtension(imageUrls[i].AbsolutePath); + if (string.IsNullOrEmpty(extension)) + { + extension = ".jpg"; + } + + // 元のHTMLの順序通りに連番でファイル名を付ける + string entryName = $"image_{i + 1:D3}{extension}"; + var zipEntry = archive.CreateEntry(entryName); + + using (var entryStream = zipEntry.Open()) + using (var ms = new MemoryStream(imgData)) + { + await ms.CopyToAsync(entryStream); + } + } + } + + //MessageBox.Show($"ダウンロードとZIP圧縮が完了しました。\n保存先: {zipFilePath}"); + } + catch (Exception ex) + { + // $"処理中にエラーが発生しました: {ex.Message}" + } + finally + { + // UI操作を再度有効化 + btnDownload.Enabled = true; + } + } + catch (Exception) + { + + } + finally + { + + } + return; + } + + // ファイル名として使用できない文字をアンダースコアに置換するメソッド + private string SanitizeFileName(string fileName) + { + var invalidChars = Path.GetInvalidFileNameChars(); + return string.Join("_", fileName.Split(invalidChars, StringSplitOptions.RemoveEmptyEntries)); + } + + public static async Task> GetFeedItems(HttpClient client, string url) + { + try + { + using var stream = await client.GetStreamAsync(url); + using var reader = XmlReader.Create(stream); + var feed = SyndicationFeed.Load(reader); + + return feed?.Items ?? Enumerable.Empty(); + } + catch (Exception ex) + { + return Enumerable.Empty(); + } + } + + } +} diff --git a/MomongaDownloader/Form1.resx b/MomongaDownloader/Form1.resx new file mode 100644 index 0000000..8b2ff64 --- /dev/null +++ b/MomongaDownloader/Form1.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/MomongaDownloader/MomongaDownloader.csproj b/MomongaDownloader/MomongaDownloader.csproj new file mode 100644 index 0000000..6bd7568 --- /dev/null +++ b/MomongaDownloader/MomongaDownloader.csproj @@ -0,0 +1,16 @@ + + + + WinExe + net10.0-windows + enable + true + enable + + + + + + + + \ No newline at end of file diff --git a/MomongaDownloader/Program.cs b/MomongaDownloader/Program.cs new file mode 100644 index 0000000..e550d21 --- /dev/null +++ b/MomongaDownloader/Program.cs @@ -0,0 +1,17 @@ +namespace MomongaDownloader +{ + internal static class Program + { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() + { + // To customize application configuration such as set high DPI settings or default font, + // see https://aka.ms/applicationconfiguration. + ApplicationConfiguration.Initialize(); + Application.Run(new Form1()); + } + } +} \ No newline at end of file