feat: v0.2.1 — fix encryption, diverse multi-topic generation, UX fixes
- Rewrite encryption with "enc:" prefix to permanently eliminate the double-encryption bug on settings save - Add one-time migration to clear legacy non-prefixed encrypted values - Rewrite content analyzer prompts to request N distinct diverse topics across 5 categories (question, complaint, comparison, news, guide) - Pass target_count*2 from pipeline to analyzer for headroom - Add skip_dedup flag so manual Generate Now always produces content - Generate Now button now sends force=1 to clear stale locks - Rename OpenRouter provider files to PSR-4 convention (hyphenated) - Switch default models to google/gemini-2.5-flash-lite - Clean up reddit_debug log channel to standard 'reddit' - Bump version to 0.2.1 Cost: ~$0.003/article with Gemini 2.0 Flash, ~34s pipeline. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2
includes/providers/class-openrouter-pricing.php → includes/providers/class-open-router-pricing.php
Executable file → Normal file
2
includes/providers/class-openrouter-pricing.php → includes/providers/class-open-router-pricing.php
Executable file → Normal file
@@ -10,7 +10,7 @@ declare(strict_types=1);
|
||||
* Triggered by: PRAutoBlogger_OpenRouter_Provider calls pricing methods.
|
||||
* Dependencies: None — pure data + calculation, no external calls by default.
|
||||
*
|
||||
* @see providers/class-openrouter-provider.php — Instantiates this class.
|
||||
* @see providers/class-open-router-provider.php — Instantiates this class.
|
||||
* @see ARCHITECTURE.md — Model selection flow.
|
||||
*/
|
||||
class PRAutoBlogger_OpenRouter_Pricing {
|
||||
74
includes/providers/class-openrouter-provider.php → includes/providers/class-open-router-provider.php
Executable file → Normal file
74
includes/providers/class-openrouter-provider.php → includes/providers/class-open-router-provider.php
Executable file → Normal file
@@ -12,7 +12,7 @@ declare(strict_types=1);
|
||||
* Dependencies: PRAutoBlogger_Encryption (for API key decryption), wp_remote_post(), PRAutoBlogger_OpenRouter_Pricing.
|
||||
*
|
||||
* @see interface-llm-provider.php — Interface this class implements.
|
||||
* @see class-openrouter-pricing.php — Pricing and model list lookups.
|
||||
* @see class-open-router-pricing.php — Pricing and model list lookups.
|
||||
* @see class-cost-tracker.php — Called after every request to log token usage.
|
||||
* @see ARCHITECTURE.md — Data flow diagram showing where this fits.
|
||||
*/
|
||||
@@ -211,16 +211,48 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
||||
*
|
||||
* Makes a lightweight request to the /auth/key endpoint.
|
||||
*
|
||||
* Side effects: HTTP request to OpenRouter.
|
||||
* Side effects: HTTP request to OpenRouter, logs diagnostic info.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function validate_credentials(): bool {
|
||||
$api_key = $this->get_api_key();
|
||||
if ( '' === $api_key ) {
|
||||
return false;
|
||||
$diag = $this->validate_credentials_detailed();
|
||||
return 'ok' === $diag['status'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate credentials with detailed diagnostic info.
|
||||
*
|
||||
* Returns an array with status ('ok' or 'error') and a human-readable
|
||||
* message explaining what went wrong if validation fails.
|
||||
*
|
||||
* Side effects: HTTP request to OpenRouter, logs diagnostic info.
|
||||
*
|
||||
* @return array{status: string, message: string, debug?: string}
|
||||
*/
|
||||
public function validate_credentials_detailed(): array {
|
||||
$encrypted = get_option( 'prautoblogger_openrouter_api_key', '' );
|
||||
if ( '' === $encrypted ) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => __( 'No API key saved. Enter your OpenRouter key in settings.', 'prautoblogger' ),
|
||||
'debug' => 'option_empty',
|
||||
];
|
||||
}
|
||||
|
||||
$api_key = PRAutoBlogger_Encryption::decrypt( $encrypted );
|
||||
if ( '' === $api_key ) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => __( 'API key decryption failed. Re-enter your key.', 'prautoblogger' ),
|
||||
'debug' => 'decrypt_failed:encrypted_len=' . strlen( $encrypted ),
|
||||
];
|
||||
}
|
||||
|
||||
// Sanity check: OpenRouter keys typically start with "sk-or-".
|
||||
$key_prefix = substr( $api_key, 0, 6 );
|
||||
$key_len = strlen( $api_key );
|
||||
|
||||
$response = wp_remote_get(
|
||||
self::API_BASE_URL . '/auth/key',
|
||||
[
|
||||
@@ -232,10 +264,38 @@ class PRAutoBlogger_OpenRouter_Provider implements PRAutoBlogger_LLM_Provider_In
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return false;
|
||||
$err_msg = $response->get_error_message();
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
sprintf( 'OpenRouter credential check wp_error: %s (key_prefix=%s, key_len=%d)', $err_msg, $key_prefix, $key_len ),
|
||||
'openrouter'
|
||||
);
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => sprintf( __( 'Network error reaching OpenRouter: %s', 'prautoblogger' ), $err_msg ),
|
||||
'debug' => 'wp_error:' . $err_msg,
|
||||
];
|
||||
}
|
||||
|
||||
return 200 === wp_remote_retrieve_response_code( $response );
|
||||
$status_code = wp_remote_retrieve_response_code( $response );
|
||||
$body_raw = wp_remote_retrieve_body( $response );
|
||||
|
||||
if ( 200 === $status_code ) {
|
||||
return [
|
||||
'status' => 'ok',
|
||||
'message' => __( 'OpenRouter connected.', 'prautoblogger' ),
|
||||
];
|
||||
}
|
||||
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
sprintf( 'OpenRouter credential check HTTP %d (key_prefix=%s, key_len=%d): %s', $status_code, $key_prefix, $key_len, substr( $body_raw, 0, 300 ) ),
|
||||
'openrouter'
|
||||
);
|
||||
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => sprintf( __( 'OpenRouter returned HTTP %d. %s', 'prautoblogger' ), $status_code, substr( $body_raw, 0, 200 ) ),
|
||||
'debug' => sprintf( 'http_%d:key_prefix=%s,key_len=%d', $status_code, $key_prefix, $key_len ),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -178,18 +178,19 @@ class PRAutoBlogger_PullPush_Client {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if PullPush API is reachable.
|
||||
* Check if PullPush API is reachable AND has reasonably fresh data.
|
||||
*
|
||||
* Makes a minimal request to verify connectivity. Used by the provider
|
||||
* to decide whether to fall back to Reddit .json endpoints.
|
||||
* PullPush can return HTTP 200 but have a stale index (months behind Reddit).
|
||||
* We check that the most recent post is no older than 7 days. If the index
|
||||
* is stale, we return false so the caller falls back to Reddit .json.
|
||||
*
|
||||
* Side effects: HTTP request.
|
||||
*
|
||||
* @return bool True if API responded with HTTP 200.
|
||||
* @return bool True if API responded with HTTP 200 and has data < 7 days old.
|
||||
*/
|
||||
public function is_available(): bool {
|
||||
// Minimal query: 1 submission from a popular subreddit.
|
||||
$url = self::API_BASE . '/search/submission?subreddit=all&size=1';
|
||||
// Fetch 1 recent submission sorted by date to check freshness.
|
||||
$url = self::API_BASE . '/search/submission?subreddit=all&size=1&sort_type=created_utc&sort=desc';
|
||||
$response = wp_remote_get(
|
||||
$url,
|
||||
[
|
||||
@@ -204,7 +205,36 @@ class PRAutoBlogger_PullPush_Client {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 200 === wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$body = json_decode( wp_remote_retrieve_body( $response ), true );
|
||||
$items = $body['data'] ?? [];
|
||||
|
||||
if ( empty( $items ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check that the most recent post is within the last 7 days.
|
||||
// If PullPush's index is stale (e.g. months behind), we should
|
||||
// fall back to Reddit .json which always has live data.
|
||||
$latest_utc = (int) ( $items[0]['created_utc'] ?? 0 );
|
||||
$seven_days = 7 * DAY_IN_SECONDS;
|
||||
$is_fresh = ( time() - $latest_utc ) < $seven_days;
|
||||
|
||||
if ( ! $is_fresh ) {
|
||||
PRAutoBlogger_Logger::instance()->warning(
|
||||
sprintf(
|
||||
'PullPush index is stale — latest post is from %s (%d days old). Falling back to Reddit .json.',
|
||||
gmdate( 'Y-m-d', $latest_utc ),
|
||||
(int) ( ( time() - $latest_utc ) / DAY_IN_SECONDS )
|
||||
),
|
||||
'pullpush'
|
||||
);
|
||||
}
|
||||
|
||||
return $is_fresh;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -73,7 +73,12 @@ class PRAutoBlogger_Reddit_JSON_Client {
|
||||
$response = $this->api_get( $url );
|
||||
|
||||
if ( null === $response || ! isset( $response['data']['children'] ) ) {
|
||||
return [];
|
||||
// .json endpoint failed (likely 403 IP block) — try RSS fallback.
|
||||
PRAutoBlogger_Logger::instance()->info(
|
||||
sprintf( 'Reddit .json failed for r/%s — trying RSS fallback.', $subreddit ),
|
||||
'reddit_json'
|
||||
);
|
||||
return $this->fetch_posts_via_rss( $subreddit, $limit );
|
||||
}
|
||||
|
||||
$posts = [];
|
||||
@@ -86,6 +91,161 @@ class PRAutoBlogger_Reddit_JSON_Client {
|
||||
return $posts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch posts from a subreddit via Reddit's RSS/Atom feed.
|
||||
*
|
||||
* RSS endpoints are less commonly blocked by Reddit than .json.
|
||||
* Returns data in the same format as fetch_posts() for compatibility,
|
||||
* but some fields (score, num_comments) are unavailable in RSS and
|
||||
* set to defaults.
|
||||
*
|
||||
* Side effects: HTTP request to Reddit.
|
||||
*
|
||||
* @param string $subreddit Subreddit name (without r/ prefix).
|
||||
* @param int $limit Max posts to fetch.
|
||||
*
|
||||
* @return array<int, array<string, mixed>> Array of post data.
|
||||
*/
|
||||
private function fetch_posts_via_rss( string $subreddit, int $limit ): array {
|
||||
$url = sprintf(
|
||||
'%s/r/%s/hot.rss?limit=%d',
|
||||
self::BASE_URL,
|
||||
rawurlencode( $subreddit ),
|
||||
min( $limit, 100 )
|
||||
);
|
||||
|
||||
$response = wp_remote_get(
|
||||
$url,
|
||||
[
|
||||
'timeout' => self::TIMEOUT_SECONDS,
|
||||
'headers' => [
|
||||
'User-Agent' => self::USER_AGENT,
|
||||
'Accept' => 'application/atom+xml, application/rss+xml',
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
'Reddit RSS GET failed: ' . $response->get_error_message(),
|
||||
'reddit_json'
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
$status_code = wp_remote_retrieve_response_code( $response );
|
||||
if ( 200 !== $status_code ) {
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
sprintf( 'Reddit RSS HTTP %d for r/%s', $status_code, $subreddit ),
|
||||
'reddit_json'
|
||||
);
|
||||
return [];
|
||||
}
|
||||
|
||||
$body = wp_remote_retrieve_body( $response );
|
||||
return $this->parse_atom_feed( $body, $subreddit );
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a Reddit Atom feed into post-data arrays matching .json format.
|
||||
*
|
||||
* Maps Atom entry fields to the standard Reddit post fields so the rest
|
||||
* of the pipeline can consume RSS data without changes. Fields unavailable
|
||||
* in RSS (score, num_comments, upvote_ratio) are set to reasonable defaults.
|
||||
*
|
||||
* @param string $xml Raw Atom XML string.
|
||||
* @param string $subreddit The subreddit name for context.
|
||||
*
|
||||
* @return array<int, array<string, mixed>> Parsed post data.
|
||||
*/
|
||||
private function parse_atom_feed( string $xml, string $subreddit ): array {
|
||||
// Suppress XML errors for malformed feeds.
|
||||
$prev_errors = libxml_use_internal_errors( true );
|
||||
$feed = simplexml_load_string( $xml );
|
||||
libxml_use_internal_errors( $prev_errors );
|
||||
|
||||
if ( false === $feed ) {
|
||||
PRAutoBlogger_Logger::instance()->error( 'Failed to parse Reddit RSS XML.', 'reddit_json' );
|
||||
return [];
|
||||
}
|
||||
|
||||
// Register the Atom namespace.
|
||||
$feed->registerXPathNamespace( 'atom', 'http://www.w3.org/2005/Atom' );
|
||||
$entries = $feed->xpath( '//atom:entry' );
|
||||
|
||||
if ( empty( $entries ) ) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$posts = [];
|
||||
foreach ( $entries as $entry ) {
|
||||
$title = (string) $entry->title;
|
||||
$link = '';
|
||||
$content = '';
|
||||
|
||||
// Get the HTML link (type="text/html").
|
||||
foreach ( $entry->link as $link_el ) {
|
||||
if ( 'text/html' === (string) $link_el['type'] || 'alternate' === (string) $link_el['rel'] ) {
|
||||
$link = (string) $link_el['href'];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Content is in <content> tag as HTML.
|
||||
if ( isset( $entry->content ) ) {
|
||||
// Strip HTML tags to get plain text for content field.
|
||||
$content = wp_strip_all_tags( (string) $entry->content );
|
||||
}
|
||||
|
||||
// Extract post ID from the entry id (format: /r/subreddit/comments/ID/...)
|
||||
$entry_id = (string) $entry->id;
|
||||
$post_id = '';
|
||||
if ( preg_match( '#/comments/([a-z0-9]+)#', $entry_id, $m ) ) {
|
||||
$post_id = $m[1];
|
||||
}
|
||||
|
||||
// Extract author name.
|
||||
$author = '[deleted]';
|
||||
if ( isset( $entry->author->name ) ) {
|
||||
$author = str_replace( '/u/', '', (string) $entry->author->name );
|
||||
}
|
||||
|
||||
// Parse published date to Unix timestamp.
|
||||
$published = (string) ( $entry->published ?? $entry->updated ?? '' );
|
||||
$created_utc = '' !== $published ? (int) strtotime( $published ) : time();
|
||||
|
||||
// Extract permalink (relative path) from full URL.
|
||||
$permalink = '';
|
||||
if ( '' !== $link ) {
|
||||
$parsed = wp_parse_url( $link );
|
||||
$permalink = $parsed['path'] ?? '';
|
||||
}
|
||||
|
||||
$posts[] = [
|
||||
'id' => $post_id,
|
||||
'title' => $title,
|
||||
'selftext' => $content,
|
||||
'author' => $author,
|
||||
'score' => 1, // Not available in RSS.
|
||||
'num_comments' => 0, // Not available in RSS.
|
||||
'permalink' => $permalink,
|
||||
'created_utc' => $created_utc,
|
||||
'is_self' => true,
|
||||
'link_flair_text' => null,
|
||||
'upvote_ratio' => null,
|
||||
'is_original_content' => false,
|
||||
'data_source' => 'reddit_rss', // Tag for debugging.
|
||||
];
|
||||
}
|
||||
|
||||
PRAutoBlogger_Logger::instance()->info(
|
||||
sprintf( 'Parsed %d posts from Reddit RSS for r/%s.', count( $posts ), $subreddit ),
|
||||
'reddit_json'
|
||||
);
|
||||
|
||||
return $posts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch top comments for a specific post via Reddit's .json endpoint.
|
||||
*
|
||||
@@ -128,16 +288,25 @@ class PRAutoBlogger_Reddit_JSON_Client {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Reddit .json endpoints are reachable from this server.
|
||||
* Check if Reddit .json or RSS endpoints are reachable from this server.
|
||||
*
|
||||
* Datacenter IPs are often blocked by Reddit. This quick check lets the
|
||||
* provider know whether this fallback is actually usable.
|
||||
* Datacenter IPs are often blocked by Reddit for .json endpoints.
|
||||
* We check .json first, then fall back to RSS availability.
|
||||
*
|
||||
* Side effects: HTTP request.
|
||||
*
|
||||
* @return bool True if we got a valid JSON response.
|
||||
* @return bool True if we got a valid response from either endpoint.
|
||||
*/
|
||||
public function is_available(): bool {
|
||||
return $this->is_json_available() || $this->is_rss_available();
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if Reddit .json endpoints are reachable.
|
||||
*
|
||||
* @return bool True if .json endpoint returns HTTP 200.
|
||||
*/
|
||||
public function is_json_available(): bool {
|
||||
$url = self::BASE_URL . '/r/all/hot.json?limit=1';
|
||||
$response = wp_remote_get(
|
||||
$url,
|
||||
@@ -153,10 +322,33 @@ class PRAutoBlogger_Reddit_JSON_Client {
|
||||
return false;
|
||||
}
|
||||
|
||||
$code = wp_remote_retrieve_response_code( $response );
|
||||
return 200 === wp_remote_retrieve_response_code( $response );
|
||||
}
|
||||
|
||||
// Reddit returns 429 when rate-limited and 403 when datacenter IP is blocked.
|
||||
return 200 === $code;
|
||||
/**
|
||||
* Check if Reddit RSS endpoints are reachable.
|
||||
*
|
||||
* RSS endpoints are less commonly blocked by Reddit than .json.
|
||||
*
|
||||
* @return bool True if RSS endpoint returns HTTP 200 with XML content.
|
||||
*/
|
||||
private function is_rss_available(): bool {
|
||||
$url = self::BASE_URL . '/r/all/hot.rss?limit=1';
|
||||
$response = wp_remote_get(
|
||||
$url,
|
||||
[
|
||||
'timeout' => 10,
|
||||
'headers' => [
|
||||
'User-Agent' => self::USER_AGENT,
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
if ( is_wp_error( $response ) ) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return 200 === wp_remote_retrieve_response_code( $response );
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -67,10 +67,23 @@ class PRAutoBlogger_Reddit_Provider implements PRAutoBlogger_Source_Provider_Int
|
||||
$use_pullpush = $this->is_pullpush_available();
|
||||
$collected = [];
|
||||
|
||||
PRAutoBlogger_Logger::instance()->info(
|
||||
sprintf(
|
||||
'Reddit collect_data: %d subreddits=%s, use_pullpush=%s, limit=%d, time=%s',
|
||||
count( $subreddits ),
|
||||
wp_json_encode( $subreddits ),
|
||||
$use_pullpush ? 'yes' : 'no',
|
||||
$limit,
|
||||
$time_filter
|
||||
),
|
||||
'reddit'
|
||||
);
|
||||
|
||||
foreach ( $subreddits as $subreddit ) {
|
||||
$subreddit = sanitize_text_field( $subreddit );
|
||||
|
||||
try {
|
||||
$before_count = count( $collected );
|
||||
if ( $use_pullpush ) {
|
||||
$collected = array_merge(
|
||||
$collected,
|
||||
@@ -82,6 +95,11 @@ class PRAutoBlogger_Reddit_Provider implements PRAutoBlogger_Source_Provider_Int
|
||||
$this->collect_from_reddit_json( $subreddit, $limit, $time_filter, $include_comments, $comments_limit )
|
||||
);
|
||||
}
|
||||
$added = count( $collected ) - $before_count;
|
||||
PRAutoBlogger_Logger::instance()->info(
|
||||
sprintf( 'Reddit r/%s: fetched %d items via %s', $subreddit, $added, $use_pullpush ? 'pullpush' : 'reddit_json' ),
|
||||
'reddit'
|
||||
);
|
||||
} catch ( \Exception $e ) {
|
||||
// Log but continue with other subreddits.
|
||||
PRAutoBlogger_Logger::instance()->error(
|
||||
|
||||
@@ -7,7 +7,7 @@ declare(strict_types=1);
|
||||
* Any class implementing this interface can be swapped in without changing the
|
||||
* content generation, analysis, or editor logic.
|
||||
*
|
||||
* @see class-openrouter-provider.php — Primary implementation (OpenRouter).
|
||||
* @see class-open-router-provider.php — Primary implementation (OpenRouter).
|
||||
* @see CONVENTIONS.md — "How To: Add a New LLM Provider".
|
||||
* @see ARCHITECTURE.md — External API integrations table.
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user