pixiv取得追加

This commit is contained in:
armonica committed 2026-09-03 14:00:43 +09:00
1 parent ae678704dc
commit e07668dc12
4 files changed
+583 -1

No files matched your search

@@ -0,0 +1,473 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.ServiceModel.Syndication;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using static rss_generator.Class.LogManager;
namespace rss_generator.Class.RSS.Pixiv;
/// <summary>
/// Pixiv RSS 生成における接続情報管理、API通信、データ変換、XML出力を担当する共通クラス
/// </summary>
internal static class pixiv_common
{
private const string BASE_API_URL = "https://www.pixiv.net/ajax/follow_latest/illust";
private const string REFERER_URL = "https://www.pixiv.net/";
/// <summary>
/// Pixiv 接続用 Cookie(PHPSESSID 等)。
/// 環境変数 PIXIV_COOKIE または PIXIV_PHPSESSID が設定されている場合はそちらが優先されます。
/// </summary>
public static string Cookie { get; set; } = "3229160_PQaR8plmeUDAmlNsKS6cb5qB7cLL4hGI";
/// <summary>
/// ブラウザ偽装用 User-Agent
/// </summary>
public static string UserAgent { get; set; } = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36";
/// <summary>
/// RSSリーダー等で画像直リンク時の403エラーを回避するため、画像プロキシ(i.pixiv.re)を利用するかどうか
/// </summary>
public static bool UseImageProxy { get; set; } = true;
/// <summary>
/// 画像プロキシホスト名(UseImageProxy が有効な場合に i.pximg.net を置換)
/// </summary>
public static string ImageProxyHost { get; set; } = "i.pixiv.re";
/// <summary>
/// 1回の生成で取得する最大ページ数(1ページあたり約60作品)
/// </summary>
public static int MaxPagesPerRun { get; set; } = 1;
/// <summary>
/// 有効な Cookie 文字列を取得します(環境変数を優先し、PHPSESSID= がない場合は自動補完します)
/// </summary>
public static string GetEffectiveCookie()
{
string rawCookie = "";
// 1. 環境変数 PIXIV_COOKIE
var envCookie = Environment.GetEnvironmentVariable("PIXIV_COOKIE");
if (!string.IsNullOrWhiteSpace(envCookie))
{
rawCookie = envCookie.Trim();
}
else
{
// 2. 環境変数 PIXIV_PHPSESSID
var envPhpSessId = Environment.GetEnvironmentVariable("PIXIV_PHPSESSID");
if (!string.IsNullOrWhiteSpace(envPhpSessId))
{
rawCookie = envPhpSessId.Trim();
}
else
{
// 3. 静的プロパティ設定値
rawCookie = Cookie.Trim();
}
}
if (string.IsNullOrWhiteSpace(rawCookie))
{
return "";
}
// セッションIDの文字列のみが直接渡された場合(イコール記号が含まれない場合)、"PHPSESSID={id};" に自動補完
if (!rawCookie.Contains("="))
{
return $"PHPSESSID={rawCookie};";
}
return rawCookie;
}
/// <summary>
/// 指定されたモード("all" または "r18")のフォロー新着イラスト一覧を取得します。
/// </summary>
/// <param name="client">HttpClient インスタンス</param>
/// <param name="mode">"all" (全年齢/全体) または "r18" (R-18)</param>
/// <param name="maxPages">取得する最大ページ数</param>
/// <returns>作品リスト</returns>
public static async Task<List<PixivIllustItem>> FetchFollowLatestIllustsAsync(HttpClient client, string mode, int maxPages = 1)
{
var resultList = new List<PixivIllustItem>();
var seenIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
var effectiveCookie = GetEffectiveCookie();
if (string.IsNullOrWhiteSpace(effectiveCookie))
{
AddLog($"[警告] [pixiv_common] Cookie (PHPSESSID) が設定されていません。環境変数 PIXIV_COOKIE または pixiv_common.Cookie を設定してください。");
}
for (int page = 1; page <= maxPages; page++)
{
try
{
var requestUrl = $"{BASE_API_URL}?p={page}&mode={mode}&lang=ja";
using var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
if (!string.IsNullOrWhiteSpace(effectiveCookie))
{
request.Headers.Add("Cookie", effectiveCookie);
}
request.Headers.Add("User-Agent", UserAgent);
request.Headers.Referrer = new Uri(REFERER_URL);
request.Headers.Add("Accept", "application/json");
using var response = await client.SendAsync(request);
var jsonString = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
AddLog($"[警告] [pixiv_common] APIリクエスト失敗 (URL={requestUrl}, Status={(int)response.StatusCode} {response.ReasonPhrase}, Body={jsonString})");
break;
}
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.AllowReadingFromString
};
options.Converters.Add(new FlexibleStringConverter());
var apiResponse = JsonSerializer.Deserialize<PixivFollowLatestResponse>(jsonString, options);
if (apiResponse == null)
{
AddLog($"[警告] [pixiv_common] レスポンスのJSONパースに失敗しました (page={page}, mode={mode})");
break;
}
if (apiResponse.Error)
{
AddLog($"[エラー] [pixiv_common] Pixiv APIエラー: {apiResponse.Message} (page={page}, mode={mode})");
break;
}
var illustList = apiResponse.Body?.Thumbnails?.Illust;
if (illustList == null || illustList.Count == 0)
{
// これ以上作品がない場合は終了
break;
}
foreach (var illust in illustList)
{
if (string.IsNullOrWhiteSpace(illust.Id)) continue;
if (seenIds.Add(illust.Id))
{
resultList.Add(illust);
}
}
// 最終ページフラグがある場合は終了
if (apiResponse.Body?.Page?.IsLastPage == true)
{
break;
}
}
catch (Exception ex)
{
AddLog($"[エラー] [pixiv_common] フォロー新着取得中に例外が発生しました (page={page}, mode={mode}): {ex.Message}");
CmnUtil.PrintCallStackToEvent(ex);
break;
}
}
return resultList;
}
/// <summary>
/// Pixiv の作品アイテムリストを SyndicationItem のリストに変換します。
/// </summary>
/// <param name="illusts">Pixiv 作品アイテム列挙</param>
/// <returns>SyndicationItem リスト</returns>
public static List<SyndicationItem> ConvertToSyndicationItems(IEnumerable<PixivIllustItem> illusts)
{
var items = new List<SyndicationItem>();
foreach (var illust in illusts)
{
try
{
var itemUrl = $"https://www.pixiv.net/artworks/{illust.Id}";
var authorUrl = $"https://www.pixiv.net/users/{illust.UserId}";
var item = new SyndicationItem
{
Title = new TextSyndicationContent(string.IsNullOrWhiteSpace(illust.Title) ? $"作品 #{illust.Id}" : illust.Title),
Id = CmnUtil.CreateGuid($"pixiv_{illust.Id}")
};
// 作品ページへのリンク
if (Uri.TryCreate(itemUrl, UriKind.Absolute, out var uri))
{
item.Links.Add(new SyndicationLink(uri));
}
// 公開・更新日時
var parsedDate = DateTimeOffset.Now;
if (!string.IsNullOrWhiteSpace(illust.CreateDate) && DateTimeOffset.TryParse(illust.CreateDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out var cDate))
{
parsedDate = cDate;
}
else if (!string.IsNullOrWhiteSpace(illust.UpdateDate) && DateTimeOffset.TryParse(illust.UpdateDate, CultureInfo.InvariantCulture, DateTimeStyles.None, out var uDate))
{
parsedDate = uDate;
}
item.PublishDate = parsedDate;
item.LastUpdatedTime = parsedDate;
// 作者情報
if (!string.IsNullOrWhiteSpace(illust.UserName))
{
item.Authors.Add(new SyndicationPerson { Name = illust.UserName, Uri = authorUrl });
}
// タグをカテゴリとして追加
if (illust.Tags != null)
{
foreach (var tag in illust.Tags)
{
if (!string.IsNullOrWhiteSpace(tag))
{
item.Categories.Add(new SyndicationCategory(tag));
}
}
}
// 年齢制限タグの補完
if (illust.XRestrict == 1 && !item.Categories.Any(c => c.Name.Equals("R-18", StringComparison.OrdinalIgnoreCase)))
{
item.Categories.Add(new SyndicationCategory("R-18"));
}
else if (illust.XRestrict == 2 && !item.Categories.Any(c => c.Name.Equals("R-18G", StringComparison.OrdinalIgnoreCase)))
{
item.Categories.Add(new SyndicationCategory("R-18G"));
}
// AI 生成タグの補完 (aiType: 2 は AI生成作品)
if (illust.AiType == 2 && !item.Categories.Any(c => c.Name.Contains("AI")))
{
item.Categories.Add(new SyndicationCategory("AI生成"));
}
// 本文 HTML の生成
var body = new StringBuilder();
// 画像 URL の決定(プロキシ適用)
var displayImageUrl = illust.Url;
if (UseImageProxy && !string.IsNullOrWhiteSpace(displayImageUrl))
{
displayImageUrl = displayImageUrl.Replace("i.pximg.net", ImageProxyHost);
}
if (!string.IsNullOrWhiteSpace(displayImageUrl))
{
body.Append($"<div>");
body.Append($"<a href=\"{itemUrl}\" target=\"_blank\" rel=\"noopener noreferrer\">");
body.Append($"<img src=\"{displayImageUrl}\" referrerpolicy=\"no-referrer\" alt=\"{WebUtility.HtmlEncode(illust.Title)}\" style=\"max-width: 100%; height: auto; display: block; margin-bottom: 10px;\" />");
body.Append($"</a>");
body.Append($"</div>");
}
// 作者・作品メタ情報
body.Append($"<p>");
body.Append($"作者: <a href=\"{authorUrl}\" target=\"_blank\" rel=\"noopener noreferrer\">{WebUtility.HtmlEncode(illust.UserName)}</a>");
if (illust.PageCount > 1)
{
body.Append($" | ページ数: {illust.PageCount}P");
}
if (illust.AiType == 2)
{
body.Append($" | <strong>[AI生成]</strong>");
}
if (illust.XRestrict >= 1)
{
body.Append($" | <strong style=\"color: red;\">[R-18]</strong>");
}
body.Append($"</p>");
// キャプション / 説明文
if (!string.IsNullOrWhiteSpace(illust.Description))
{
body.Append($"<div style=\"margin-top: 8px; margin-bottom: 12px;\">");
body.Append(illust.Description);
body.Append($"</div>");
}
// タグ一覧
if (illust.Tags != null && illust.Tags.Count > 0)
{
body.Append($"<p style=\"font-size: 0.9em; color: #666;\">");
body.Append($"タグ: {string.Join(" ", illust.Tags.Select(t => $"#{WebUtility.HtmlEncode(t)}"))}");
body.Append($"</p>");
}
item.Summary = new TextSyndicationContent(body.ToString(), TextSyndicationContentKind.Html);
items.Add(item);
}
catch (Exception ex)
{
AddLog($"[エラー] [pixiv_common] SyndicationItem 変換中にエラー (ID={illust.Id}): {ex.Message}");
}
}
return items;
}
/// <summary>
/// SyndicationFeed を作成し、指定されたファイル名の XML として出力します。
/// </summary>
/// <param name="feedTitle">フィードのタイトル</param>
/// <param name="feedDescription">フィードの説明</param>
/// <param name="feedLink">フィードのWebサイトリンク</param>
/// <param name="fileName">出力XMLファイル名 (例: pixiv_r18.xml)</param>
/// <param name="items">フィードアイテムリスト</param>
public static void CreateAndExportFeed(string feedTitle, string feedDescription, string feedLink, string fileName, List<SyndicationItem> items)
{
var feed = new SyndicationFeed(
feedTitle,
feedDescription,
new Uri(feedLink),
items
);
CmnUtil.ExportXMLFile(fileName, feed);
AddLog($"[情報] {fileName} を正常に出力しました (作品数: {items.Count})");
}
#region Pixiv API レスポンス用データモデル
public class PixivFollowLatestResponse
{
[JsonPropertyName("error")]
public bool Error { get; set; }
[JsonPropertyName("message")]
public string Message { get; set; } = string.Empty;
[JsonPropertyName("body")]
public PixivFollowLatestBody? Body { get; set; }
}
public class PixivFollowLatestBody
{
[JsonPropertyName("page")]
public PixivPageInfo? Page { get; set; }
[JsonPropertyName("thumbnails")]
public PixivThumbnails? Thumbnails { get; set; }
}
public class PixivPageInfo
{
[JsonPropertyName("ids")]
public List<string>? Ids { get; set; }
[JsonPropertyName("isLastPage")]
public bool IsLastPage { get; set; }
}
public class PixivThumbnails
{
[JsonPropertyName("illust")]
public List<PixivIllustItem>? Illust { get; set; }
}
public class PixivIllustItem
{
[JsonPropertyName("id")]
public string Id { get; set; } = string.Empty;
[JsonPropertyName("title")]
public string Title { get; set; } = string.Empty;
[JsonPropertyName("illustType")]
public int IllustType { get; set; }
/// <summary>
/// 年齢制限 (0: 全年齢, 1: R-18, 2: R-18G)
/// </summary>
[JsonPropertyName("xRestrict")]
public int XRestrict { get; set; }
[JsonPropertyName("restrict")]
public int Restrict { get; set; }
[JsonPropertyName("sl")]
public int Sl { get; set; }
[JsonPropertyName("url")]
public string Url { get; set; } = string.Empty;
[JsonPropertyName("description")]
public string Description { get; set; } = string.Empty;
[JsonPropertyName("tags")]
public List<string> Tags { get; set; } = new();
[JsonPropertyName("userId")]
public string UserId { get; set; } = string.Empty;
[JsonPropertyName("userName")]
public string UserName { get; set; } = string.Empty;
[JsonPropertyName("width")]
public int Width { get; set; }
[JsonPropertyName("height")]
public int Height { get; set; }
[JsonPropertyName("pageCount")]
public int PageCount { get; set; }
[JsonPropertyName("bookmarkCount")]
public int BookmarkCount { get; set; }
[JsonPropertyName("createDate")]
public string CreateDate { get; set; } = string.Empty;
[JsonPropertyName("updateDate")]
public string UpdateDate { get; set; } = string.Empty;
/// <summary>
/// AI 生成タイプ (1: 通常, 2: AI生成作品)
/// </summary>
[JsonPropertyName("aiType")]
public int AiType { get; set; }
}
/// <summary>
/// 数値や文字列など様々な型のJSONトークンを安全に string として読み込むコンバータ
/// </summary>
public class FlexibleStringConverter : JsonConverter<string>
{
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.TokenType switch
{
JsonTokenType.String => reader.GetString(),
JsonTokenType.Number => reader.TryGetInt64(out long l) ? l.ToString() : reader.GetDouble().ToString(CultureInfo.InvariantCulture),
JsonTokenType.True => "true",
JsonTokenType.False => "false",
JsonTokenType.Null => null,
_ => reader.GetString()
};
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
}
#endregion
}
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using static rss_generator.Class.LogManager;
namespace rss_generator.Class.RSS.Pixiv;
/// <summary>
/// Pixiv のフォロー中ユーザーの最新全年齢(非R-18)作品フィード (pixiv_non_r18.xml) を生成するクラス
/// </summary>
internal class pixiv_non_r18
{
private const string FEED_TITLE = "Pixiv (Follow General)";
private const string FEED_DESCRIPTION = "Pixiv のフォロー中ユーザーによる最新全年齢作品フィード";
private const string FEED_LINK = "https://www.pixiv.net/bookmark_new_illust.php";
private const string XML_FILE_NAME = "pixiv_non_r18.xml";
/// <summary>
/// Pixiv のフォロー新着から全年齢作品を取得し、pixiv_non_r18.xml を生成します。
/// </summary>
/// <param name="client">HttpClient インスタンス</param>
public static async Task CreateRSSAsync(HttpClient client)
{
try
{
// mode="all" でフォロー新着作品を取得
var illusts = await pixiv_common.FetchFollowLatestIllustsAsync(client, mode: "all", maxPages: pixiv_common.MaxPagesPerRun);
// 全年齢作品のみ (xRestrict == 0) を抽出
var generalIllusts = illusts.Where(x => x.XRestrict == 0).ToList();
// SyndicationItem のリストに変換
var items = pixiv_common.ConvertToSyndicationItems(generalIllusts);
// フィード作成と XML 出力
pixiv_common.CreateAndExportFeed(
FEED_TITLE,
FEED_DESCRIPTION,
FEED_LINK,
XML_FILE_NAME,
items
);
}
catch (Exception ex)
{
AddLog($"[エラー] [pixiv_non_r18]: {ex.Message}");
CmnUtil.PrintCallStackToEvent(ex);
}
}
}
@@ -0,0 +1,52 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using static rss_generator.Class.LogManager;
namespace rss_generator.Class.RSS.Pixiv;
/// <summary>
/// Pixiv のフォロー中ユーザーの最新 R-18 作品フィード (pixiv_r18.xml) を生成するクラス
/// </summary>
internal class pixiv_r18
{
private const string FEED_TITLE = "Pixiv (Follow R-18)";
private const string FEED_DESCRIPTION = "Pixiv のフォロー中ユーザーによる最新 R-18 作品フィード";
private const string FEED_LINK = "https://www.pixiv.net/bookmark_new_illust_r18.php";
private const string XML_FILE_NAME = "pixiv_r18.xml";
/// <summary>
/// Pixiv のフォロー新着から R-18 作品を取得し、pixiv_r18.xml を生成します。
/// </summary>
/// <param name="client">HttpClient インスタンス</param>
public static async Task CreateRSSAsync(HttpClient client)
{
try
{
// mode="r18" でフォロー新着作品を取得
var illusts = await pixiv_common.FetchFollowLatestIllustsAsync(client, mode: "r18", maxPages: pixiv_common.MaxPagesPerRun);
// 安全のため R-18 以上の作品 (xRestrict >= 1) のみ抽出
var r18Illusts = illusts.Where(x => x.XRestrict >= 1).ToList();
// SyndicationItem のリストに変換
var items = pixiv_common.ConvertToSyndicationItems(r18Illusts);
// フィード作成と XML 出力
pixiv_common.CreateAndExportFeed(
FEED_TITLE,
FEED_DESCRIPTION,
FEED_LINK,
XML_FILE_NAME,
items
);
}
catch (Exception ex)
{
AddLog($"[エラー] [pixiv_r18]: {ex.Message}");
CmnUtil.PrintCallStackToEvent(ex);
}
}
}
+6 -1
View File
@@ -3,6 +3,7 @@ using rss_generator.Class;
using rss_generator.Class.RSS; using rss_generator.Class.RSS;
using rss_generator.Class.RSS.e_hentai; using rss_generator.Class.RSS.e_hentai;
using rss_generator.Class.RSS.hitomi_la; using rss_generator.Class.RSS.hitomi_la;
using rss_generator.Class.RSS.Pixiv;
using rss_generator.Class.RSS.YouTube; using rss_generator.Class.RSS.YouTube;
using System.Diagnostics; using System.Diagnostics;
@@ -79,7 +80,9 @@ while (true)
tasks.Add(momonga_magazine.CreateRSSAsync(client)); tasks.Add(momonga_magazine.CreateRSSAsync(client));
} }
#if DEBUG #if DEBUG
tasks.Add(aurahentai.CreateRSSAsync(client)); //tasks.Add(aurahentai.CreateRSSAsync(client));
tasks.Add(pixiv_r18.CreateRSSAsync(client));
tasks.Add(pixiv_non_r18.CreateRSSAsync(client));
//tasks.Add(YouTubeFeedManager.CreateRSSAsync(client)); //tasks.Add(YouTubeFeedManager.CreateRSSAsync(client));
//tasks.Add(momonga_fanzine.CreateRSSAsync(client)); //tasks.Add(momonga_fanzine.CreateRSSAsync(client));
//tasks.Add(momonga_magazine.CreateRSSAsync(client)); //tasks.Add(momonga_magazine.CreateRSSAsync(client));
@@ -101,6 +104,8 @@ while (true)
tasks.Add(mangalear.CreateRSSAsync(client)); tasks.Add(mangalear.CreateRSSAsync(client));
tasks.Add(e_hentai_ai.CreateRSSAsync(client)); tasks.Add(e_hentai_ai.CreateRSSAsync(client));
tasks.Add(e_hentai_non_ai.CreateRSSAsync(client)); tasks.Add(e_hentai_non_ai.CreateRSSAsync(client));
tasks.Add(pixiv_r18.CreateRSSAsync(client));
tasks.Add(pixiv_non_r18.CreateRSSAsync(client));
tasks.Add(index_japanese.CreateRSSAsync(client)); tasks.Add(index_japanese.CreateRSSAsync(client));
#endif #endif