Initial commit: AutoBlogger v0.1.0

WordPress plugin that auto-researches topics from Reddit, generates
SEO-optimized articles via OpenRouter LLMs, runs them through a chief
editor agent, and publishes on a daily schedule.

Includes:
- Full generation pipeline (collect → analyze → score → generate → review → publish)
- Cost tracking and budget enforcement
- Admin UI: settings, review queue, metrics, activity log
- CI/CD pipeline (GitHub Actions → WordPress REST deploy)
- Unit test suite (PHPUnit + Brain Monkey)
- Structured logging with configurable verbosity

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Terence Ong
2026-04-10 16:10:27 +07:00
commit 68c6f67bcf
65 changed files with 8833 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* Instagram source provider — STUB for future implementation.
*
* Will integrate with Instagram's Graph API to collect post captions,
* comments, and hashtag trends. Requires Meta developer app credentials.
*
* Triggered by: Source_Collector when 'instagram' is in enabled_sources.
* Dependencies: TBD — Instagram Graph API credentials.
*
* @see interface-source-provider.php — Interface this class implements.
*/
class Autoblogger_Instagram_Provider implements Autoblogger_Source_Provider_Interface {
/**
* @param array<string, mixed> $config
* @return Autoblogger_Source_Data[]
* @throws \RuntimeException Always — not yet implemented.
*/
public function collect_data( array $config ): array {
throw new \RuntimeException(
__( 'Instagram source provider is not yet implemented. Remove "instagram" from enabled sources.', 'autoblogger' )
);
}
public function get_source_type(): string {
return 'instagram';
}
public function validate_credentials(): bool {
return false;
}
public function get_rate_limit_status(): array {
return [ 'remaining' => 0, 'limit' => 0, 'resets_at' => '' ];
}
}

View File

@@ -0,0 +1,137 @@
<?php
declare(strict_types=1);
/**
* OpenRouter model pricing and availability lookup.
*
* Manages pricing tables, model lists, and cost estimation. Decoupled from
* the request logic for easy updates and testing.
*
* Triggered by: Autoblogger_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 ARCHITECTURE.md — Model selection flow.
*/
class Autoblogger_OpenRouter_Pricing {
/**
* Known model pricing (per million tokens, in USD).
* Updated periodically. Falls back to API-reported pricing if available.
*
* @var array<string, array{prompt: float, completion: float}>
*/
private const MODEL_PRICING = [
'anthropic/claude-3.5-haiku' => [ 'prompt' => 0.80, 'completion' => 4.00 ],
'anthropic/claude-sonnet-4' => [ 'prompt' => 3.00, 'completion' => 15.00 ],
'anthropic/claude-opus-4' => [ 'prompt' => 15.00, 'completion' => 75.00 ],
'openai/gpt-4o' => [ 'prompt' => 2.50, 'completion' => 10.00 ],
'openai/gpt-4o-mini' => [ 'prompt' => 0.15, 'completion' => 0.60 ],
'google/gemini-2.0-flash' => [ 'prompt' => 0.10, 'completion' => 0.40 ],
'meta-llama/llama-3.3-70b' => [ 'prompt' => 0.40, 'completion' => 0.40 ],
];
/**
* Get available models from OpenRouter's /models endpoint.
*
* Caches the result in a transient for 24 hours to avoid repeated API calls.
*
* Side effects: HTTP request (if cache miss), sets transient.
*
* @return array<int, array{id: string, name: string, context_length: int, pricing: array{prompt: float, completion: float}}>
*/
public function get_available_models(): array {
$cached = get_transient( 'autoblogger_openrouter_models' );
if ( false !== $cached && is_array( $cached ) ) {
return $cached;
}
$api_key = $this->get_api_key();
if ( '' === $api_key ) {
return [];
}
$response = wp_remote_get(
'https://openrouter.ai/api/v1/models',
[
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . $api_key,
],
]
);
if ( is_wp_error( $response ) || 200 !== wp_remote_retrieve_response_code( $response ) ) {
Autoblogger_Logger::instance()->warning( 'Failed to fetch OpenRouter models list.', 'openrouter' );
return [];
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
$models = [];
if ( isset( $data['data'] ) && is_array( $data['data'] ) ) {
foreach ( $data['data'] as $model ) {
$models[] = [
'id' => $model['id'] ?? '',
'name' => $model['name'] ?? $model['id'] ?? '',
'context_length' => (int) ( $model['context_length'] ?? 0 ),
'pricing' => [
'prompt' => (float) ( $model['pricing']['prompt'] ?? 0 ) * 1000000,
'completion' => (float) ( $model['pricing']['completion'] ?? 0 ) * 1000000,
],
];
}
}
set_transient( 'autoblogger_openrouter_models', $models, DAY_IN_SECONDS );
return $models;
}
/**
* Estimate the cost of an API call in USD.
*
* Uses hardcoded pricing first, falls back to cached model data.
*
* @param string $model Model identifier.
* @param int $prompt_tokens Input tokens.
* @param int $completion_tokens Output tokens.
*
* @return float Estimated cost in USD.
*/
public function estimate_cost( string $model, int $prompt_tokens, int $completion_tokens ): float {
$pricing = self::MODEL_PRICING[ $model ] ?? null;
// Fall back to cached model list pricing.
if ( null === $pricing ) {
$models = $this->get_available_models();
foreach ( $models as $m ) {
if ( $m['id'] === $model && isset( $m['pricing'] ) ) {
$pricing = $m['pricing'];
break;
}
}
}
if ( null === $pricing ) {
// Unknown model — use a conservative estimate.
Autoblogger_Logger::instance()->warning( "Unknown model pricing for '{$model}'. Using conservative estimate.", 'openrouter' );
$pricing = [ 'prompt' => 10.0, 'completion' => 30.0 ];
}
return ( $prompt_tokens * $pricing['prompt'] / 1000000 )
+ ( $completion_tokens * $pricing['completion'] / 1000000 );
}
/**
* Get the decrypted API key from options.
*
* @return string Decrypted API key, or empty string if not set.
*/
private function get_api_key(): string {
$encrypted = get_option( 'autoblogger_openrouter_api_key', '' );
if ( '' === $encrypted ) {
return '';
}
return Autoblogger_Encryption::decrypt( $encrypted );
}
}

View File

@@ -0,0 +1,253 @@
<?php
declare(strict_types=1);
/**
* OpenRouter API integration for all LLM calls (analysis, writing, editing).
*
* OpenRouter provides a unified API to access models from Anthropic, OpenAI,
* Google, Meta, and others. This lets users pick any model without us maintaining
* separate provider integrations.
*
* Triggered by: Content_Analyzer, Content_Generator, Chief_Editor, Metrics_Collector.
* Dependencies: Autoblogger_Encryption (for API key decryption), wp_remote_post(), Autoblogger_OpenRouter_Pricing.
*
* @see interface-llm-provider.php — Interface this class implements.
* @see class-openrouter-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.
*/
class Autoblogger_OpenRouter_Provider implements Autoblogger_LLM_Provider_Interface {
private const API_BASE_URL = 'https://openrouter.ai/api/v1';
/**
* Send a chat completion request to OpenRouter.
*
* Retries with exponential backoff on transient failures (5xx, timeout).
* Logs every attempt. Fails loudly after exhausting retries.
*
* Side effects: HTTP request to OpenRouter API.
*
* @param array<int, array{role: string, content: string}> $messages Chat messages.
* @param string $model Model identifier (e.g., 'anthropic/claude-sonnet-4').
* @param array{
* temperature?: float,
* max_tokens?: int,
* response_format?: array{type: string},
* } $options Optional parameters.
*
* @return array{
* content: string,
* model: string,
* prompt_tokens: int,
* completion_tokens: int,
* total_tokens: int,
* finish_reason: string,
* }
*
* @throws \RuntimeException On API error after retries exhausted.
*/
public function send_chat_completion( array $messages, string $model, array $options = [] ): array {
$api_key = $this->get_api_key();
if ( '' === $api_key ) {
throw new \RuntimeException(
__( 'OpenRouter API key is not configured. Go to AutoBlogger → Settings.', 'autoblogger' )
);
}
$body = [
'model' => $model,
'messages' => $messages,
];
if ( isset( $options['temperature'] ) ) {
$body['temperature'] = $options['temperature'];
}
if ( isset( $options['max_tokens'] ) ) {
$body['max_tokens'] = $options['max_tokens'];
}
if ( isset( $options['response_format'] ) ) {
$body['response_format'] = $options['response_format'];
}
$last_error = '';
for ( $attempt = 1; $attempt <= AUTOBLOGGER_MAX_RETRIES; $attempt++ ) {
$response = wp_remote_post(
self::API_BASE_URL . '/chat/completions',
[
'timeout' => AUTOBLOGGER_API_TIMEOUT_SECONDS,
'headers' => [
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json',
'HTTP-Referer' => home_url(),
'X-Title' => 'AutoBlogger WordPress Plugin',
],
'body' => wp_json_encode( $body ),
]
);
if ( is_wp_error( $response ) ) {
$last_error = $response->get_error_message();
Autoblogger_Logger::instance()->warning(
sprintf( 'OpenRouter request failed (attempt %d/%d): %s', $attempt, AUTOBLOGGER_MAX_RETRIES, $last_error ),
'openrouter'
);
if ( $attempt < AUTOBLOGGER_MAX_RETRIES ) {
$delay = AUTOBLOGGER_RETRY_BASE_DELAY_SECONDS * pow( 2, $attempt - 1 );
sleep( (int) $delay );
}
continue;
}
$status_code = wp_remote_retrieve_response_code( $response );
$body_raw = wp_remote_retrieve_body( $response );
$data = json_decode( $body_raw, true );
// Rate limited or server error — retry.
if ( $status_code >= 429 || $status_code >= 500 ) {
$last_error = sprintf( 'HTTP %d: %s', $status_code, $body_raw );
Autoblogger_Logger::instance()->warning(
sprintf( 'OpenRouter HTTP %d (attempt %d/%d): %s', $status_code, $attempt, AUTOBLOGGER_MAX_RETRIES, substr( $body_raw, 0, 500 ) ),
'openrouter'
);
if ( $attempt < AUTOBLOGGER_MAX_RETRIES ) {
// Respect Retry-After header if present.
$retry_after = wp_remote_retrieve_header( $response, 'retry-after' );
$delay = $retry_after
? min( (int) $retry_after, 60 )
: AUTOBLOGGER_RETRY_BASE_DELAY_SECONDS * pow( 2, $attempt - 1 );
sleep( (int) $delay );
}
continue;
}
// Client error — don't retry, fail immediately.
if ( $status_code >= 400 ) {
$error_msg = isset( $data['error']['message'] )
? $data['error']['message']
: 'HTTP ' . $status_code;
throw new \RuntimeException(
sprintf(
/* translators: %d: HTTP status code, %s: error message */
__( 'OpenRouter API error (HTTP %1$d): %2$s', 'autoblogger' ),
$status_code,
$error_msg
)
);
}
// Success — parse response.
if ( ! isset( $data['choices'][0]['message']['content'] ) ) {
throw new \RuntimeException(
__( 'OpenRouter returned unexpected response format.', 'autoblogger' )
);
}
$usage = $data['usage'] ?? [];
return [
'content' => $data['choices'][0]['message']['content'],
'model' => $data['model'] ?? $model,
'prompt_tokens' => (int) ( $usage['prompt_tokens'] ?? 0 ),
'completion_tokens' => (int) ( $usage['completion_tokens'] ?? 0 ),
'total_tokens' => (int) ( $usage['total_tokens'] ?? 0 ),
'finish_reason' => $data['choices'][0]['finish_reason'] ?? 'unknown',
];
}
// All retries exhausted.
throw new \RuntimeException(
sprintf(
/* translators: %d: max retries, %s: last error message */
__( 'OpenRouter API failed after %1$d attempts. Last error: %2$s', 'autoblogger' ),
AUTOBLOGGER_MAX_RETRIES,
$last_error
)
);
}
/**
* Get available models from OpenRouter's /models endpoint.
*
* Caches the result in a transient for 24 hours to avoid repeated API calls.
*
* Side effects: HTTP request (if cache miss), sets transient.
*
* @return array<int, array{id: string, name: string, context_length: int, pricing: array{prompt: float, completion: float}}>
*/
public function get_available_models(): array {
$pricing = new Autoblogger_OpenRouter_Pricing();
return $pricing->get_available_models();
}
/**
* Estimate the cost of an API call in USD.
*
* Uses hardcoded pricing first, falls back to cached model data.
*
* @param string $model Model identifier.
* @param int $prompt_tokens Input tokens.
* @param int $completion_tokens Output tokens.
*
* @return float Estimated cost in USD.
*/
public function estimate_cost( string $model, int $prompt_tokens, int $completion_tokens ): float {
$pricing = new Autoblogger_OpenRouter_Pricing();
return $pricing->estimate_cost( $model, $prompt_tokens, $completion_tokens );
}
/**
* @return string
*/
public function get_provider_name(): string {
return 'OpenRouter';
}
/**
* Validate that the OpenRouter API key is configured and working.
*
* Makes a lightweight request to the /auth/key endpoint.
*
* Side effects: HTTP request to OpenRouter.
*
* @return bool
*/
public function validate_credentials(): bool {
$api_key = $this->get_api_key();
if ( '' === $api_key ) {
return false;
}
$response = wp_remote_get(
self::API_BASE_URL . '/auth/key',
[
'timeout' => 15,
'headers' => [
'Authorization' => 'Bearer ' . $api_key,
],
]
);
if ( is_wp_error( $response ) ) {
return false;
}
return 200 === wp_remote_retrieve_response_code( $response );
}
/**
* Get the decrypted API key from options.
*
* @return string Decrypted API key, or empty string if not set.
*/
private function get_api_key(): string {
$encrypted = get_option( 'autoblogger_openrouter_api_key', '' );
if ( '' === $encrypted ) {
return '';
}
return Autoblogger_Encryption::decrypt( $encrypted );
}
}

View File

@@ -0,0 +1,207 @@
<?php
declare(strict_types=1);
/**
* Reddit API HTTP client for authenticated requests.
*
* Encapsulates OAuth2 token management, rate limit tracking, and HTTP methods
* for the Reddit API. Decoupled from collection logic for testability.
*
* Triggered by: Autoblogger_Reddit_Provider calls fetch methods here.
* Dependencies: Autoblogger_Encryption (for client secret), wp_remote_post/get().
*
* @see providers/class-reddit-provider.php — Instantiates this class.
* @see ARCHITECTURE.md — External API integrations table.
*/
class Autoblogger_Reddit_API_Client {
private const AUTH_URL = 'https://www.reddit.com/api/v1/access_token';
private const API_BASE = 'https://oauth.reddit.com';
private const USER_AGENT = 'AutoBlogger/0.1.0 (WordPress Plugin)';
/**
* Get an OAuth2 access token, using cached transient if available.
*
* Reddit script apps use client_credentials grant type.
*
* Side effects: HTTP request, sets transient.
*
* @param bool $force_refresh Bypass cache and request a new token.
*
* @return string Access token, or empty string on failure.
*/
public function get_access_token( bool $force_refresh = false ): string {
if ( ! $force_refresh ) {
$cached = get_transient( 'autoblogger_reddit_token' );
if ( false !== $cached && is_string( $cached ) ) {
return $cached;
}
}
$client_id = get_option( 'autoblogger_reddit_client_id', '' );
$client_secret = Autoblogger_Encryption::decrypt(
get_option( 'autoblogger_reddit_client_secret', '' )
);
if ( '' === $client_id || '' === $client_secret ) {
return '';
}
$response = wp_remote_post(
self::AUTH_URL,
[
'timeout' => 15,
'headers' => [
// phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
'Authorization' => 'Basic ' . base64_encode( $client_id . ':' . $client_secret ),
'User-Agent' => self::USER_AGENT,
],
'body' => [
'grant_type' => 'client_credentials',
],
]
);
if ( is_wp_error( $response ) ) {
Autoblogger_Logger::instance()->error( 'Reddit OAuth failed: ' . $response->get_error_message(), 'reddit' );
return '';
}
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
Autoblogger_Logger::instance()->error( 'Reddit OAuth HTTP ' . wp_remote_retrieve_response_code( $response ), 'reddit' );
return '';
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! isset( $data['access_token'] ) ) {
Autoblogger_Logger::instance()->error( 'Reddit OAuth response missing access_token.', 'reddit' );
return '';
}
$token = $data['access_token'];
$expires = isset( $data['expires_in'] ) ? (int) $data['expires_in'] - 60 : 3540;
set_transient( 'autoblogger_reddit_token', $token, $expires );
return $token;
}
/**
* Fetch posts from a subreddit.
*
* @param string $token OAuth access token.
* @param string $subreddit Subreddit name (without r/ prefix).
* @param int $limit Max posts to fetch.
* @param string $time_filter Time filter for /top (hour, day, week, month, year, all).
*
* @return array<int, array<string, mixed>> Array of post data.
*/
public function fetch_posts( string $token, string $subreddit, int $limit, string $time_filter ): array {
$url = sprintf(
'%s/r/%s/hot?limit=%d&t=%s',
self::API_BASE,
rawurlencode( $subreddit ),
min( $limit, 100 ),
rawurlencode( $time_filter )
);
$response = $this->api_get( $token, $url );
if ( null === $response || ! isset( $response['data']['children'] ) ) {
return [];
}
$posts = [];
foreach ( $response['data']['children'] as $child ) {
if ( isset( $child['data'] ) ) {
$posts[] = $child['data'];
}
}
return $posts;
}
/**
* Fetch top comments for a specific post.
*
* @param string $token OAuth access token.
* @param string $subreddit Subreddit name.
* @param string $post_id Reddit post ID (without t3_ prefix).
* @param int $limit Max comments to fetch.
*
* @return array<int, array<string, mixed>> Array of comment data.
*/
public function fetch_comments( string $token, string $subreddit, string $post_id, int $limit ): array {
$url = sprintf(
'%s/r/%s/comments/%s?limit=%d&sort=top&depth=1',
self::API_BASE,
rawurlencode( $subreddit ),
rawurlencode( $post_id ),
min( $limit, 50 )
);
$response = $this->api_get( $token, $url );
// Comments endpoint returns [post_listing, comments_listing].
if ( ! is_array( $response ) || ! isset( $response[1]['data']['children'] ) ) {
return [];
}
$comments = [];
foreach ( $response[1]['data']['children'] as $child ) {
if ( isset( $child['data'] ) && 't1' === ( $child['kind'] ?? '' ) ) {
$comments[] = $child['data'];
}
}
return $comments;
}
/**
* Make an authenticated GET request to the Reddit API.
*
* Updates rate limit tracking from response headers.
*
* @param string $token OAuth access token.
* @param string $url Full API URL.
*
* @return array<string, mixed>|null Decoded response, or null on failure.
*/
public function api_get( string $token, string $url ): ?array {
$response = wp_remote_get(
$url,
[
'timeout' => 30,
'headers' => [
'Authorization' => 'Bearer ' . $token,
'User-Agent' => self::USER_AGENT,
],
]
);
if ( is_wp_error( $response ) ) {
Autoblogger_Logger::instance()->error( 'Reddit API GET failed: ' . $response->get_error_message(), 'reddit' );
return null;
}
// Track rate limits from response headers.
$rate_remaining = wp_remote_retrieve_header( $response, 'x-ratelimit-remaining' );
$rate_limit = wp_remote_retrieve_header( $response, 'x-ratelimit-used' );
$rate_reset = wp_remote_retrieve_header( $response, 'x-ratelimit-reset' );
if ( '' !== $rate_remaining ) {
set_transient( 'autoblogger_reddit_rate_limit', [
'remaining' => (int) $rate_remaining,
'limit' => (int) $rate_limit + (int) $rate_remaining,
'resets_at' => gmdate( 'Y-m-d H:i:s', time() + (int) $rate_reset ),
], 120 );
}
$status_code = wp_remote_retrieve_response_code( $response );
if ( 200 !== $status_code ) {
Autoblogger_Logger::instance()->error( sprintf( 'Reddit API HTTP %d: %s', $status_code, substr( wp_remote_retrieve_body( $response ), 0, 300 ) ), 'reddit' );
return null;
}
return json_decode( wp_remote_retrieve_body( $response ), true );
}
}

View File

@@ -0,0 +1,178 @@
<?php
declare(strict_types=1);
/**
* Reddit API integration for collecting posts and comments from target subreddits.
*
* Uses Reddit's OAuth2 "script" app type for server-to-server authentication.
* Collects hot/top posts and their top comments from configured subreddits,
* storing them in the ab_source_data table.
*
* Triggered by: Source_Collector calls collect_data() on each enabled provider.
* Dependencies: Autoblogger_Reddit_API_Client (for HTTP calls and auth).
*
* @see interface-source-provider.php — Interface this class implements.
* @see providers/class-reddit-api-client.php — HTTP client for Reddit API.
* @see core/class-source-collector.php — Orchestrates collection from all providers.
* @see ARCHITECTURE.md — External API integrations table.
*/
class Autoblogger_Reddit_Provider implements Autoblogger_Source_Provider_Interface {
/**
* Collect posts and comments from configured subreddits.
*
* For each subreddit: fetches hot posts, then fetches top comments for
* the most-engaged posts. Returns an array of Source_Data objects.
*
* Side effects: HTTP requests to Reddit API, uses/sets transients for OAuth token.
*
* @param array{
* subreddits?: string[],
* limit?: int,
* time_filter?: string,
* include_comments?: bool,
* comments_per_post?: int,
* } $config Collection configuration.
*
* @return Autoblogger_Source_Data[]
*
* @throws \RuntimeException On authentication failure or API error.
*/
public function collect_data( array $config ): array {
$api_client = new Autoblogger_Reddit_API_Client();
$token = $api_client->get_access_token();
if ( '' === $token ) {
throw new \RuntimeException(
__( 'Reddit authentication failed. Check client ID and secret in settings.', 'autoblogger' )
);
}
$subreddits = $config['subreddits'] ?? $this->get_configured_subreddits();
$limit = $config['limit'] ?? 25;
$time_filter = $config['time_filter'] ?? 'day';
$include_comments = $config['include_comments'] ?? true;
$comments_limit = $config['comments_per_post'] ?? 10;
$collected = [];
foreach ( $subreddits as $subreddit ) {
$subreddit = sanitize_text_field( $subreddit );
try {
$posts = $api_client->fetch_posts( $token, $subreddit, $limit, $time_filter );
foreach ( $posts as $post ) {
$collected[] = new Autoblogger_Source_Data( [
'source_type' => 'reddit',
'source_id' => 't3_' . $post['id'],
'subreddit' => $subreddit,
'title' => $post['title'] ?? '',
'content' => $post['selftext'] ?? '',
'author' => $post['author'] ?? '[deleted]',
'score' => (int) ( $post['score'] ?? 0 ),
'comment_count' => (int) ( $post['num_comments'] ?? 0 ),
'permalink' => 'https://reddit.com' . ( $post['permalink'] ?? '' ),
'collected_at' => current_time( 'mysql' ),
'metadata' => [
'post_type' => $post['is_self'] ? 'self' : 'link',
'flair' => $post['link_flair_text'] ?? null,
'created_utc' => $post['created_utc'] ?? 0,
'upvote_ratio' => $post['upvote_ratio'] ?? 0,
'is_original' => $post['is_original_content'] ?? false,
],
] );
// Collect top comments for high-engagement posts.
if ( $include_comments && ( $post['num_comments'] ?? 0 ) > 5 ) {
$comments = $api_client->fetch_comments(
$token,
$subreddit,
$post['id'],
$comments_limit
);
foreach ( $comments as $comment ) {
$collected[] = new Autoblogger_Source_Data( [
'source_type' => 'reddit',
'source_id' => 't1_' . $comment['id'],
'subreddit' => $subreddit,
'title' => null,
'content' => $comment['body'] ?? '',
'author' => $comment['author'] ?? '[deleted]',
'score' => (int) ( $comment['score'] ?? 0 ),
'comment_count' => 0,
'permalink' => 'https://reddit.com' . ( $comment['permalink'] ?? '' ),
'collected_at' => current_time( 'mysql' ),
'metadata' => [
'parent_post_id' => 't3_' . $post['id'],
'parent_title' => $post['title'] ?? '',
'is_comment' => true,
'created_utc' => $comment['created_utc'] ?? 0,
],
] );
}
}
}
} catch ( \Exception $e ) {
// Log but continue with other subreddits.
Autoblogger_Logger::instance()->error(
sprintf( 'Reddit: Failed to collect from r/%s: %s', $subreddit, $e->getMessage() ),
'reddit'
);
}
}
return $collected;
}
/**
* @return string
*/
public function get_source_type(): string {
return 'reddit';
}
/**
* Validate Reddit API credentials.
*
* Side effects: HTTP request to Reddit OAuth endpoint.
*
* @return bool
*/
public function validate_credentials(): bool {
$api_client = new Autoblogger_Reddit_API_Client();
$token = $api_client->get_access_token( true );
return '' !== $token;
}
/**
* Get current rate limit status from last response headers.
*
* @return array{remaining: int, limit: int, resets_at: string}
*/
public function get_rate_limit_status(): array {
// Reddit rate limits are tracked per-response via headers.
// We store the last seen values in a transient.
$status = get_transient( 'autoblogger_reddit_rate_limit' );
if ( is_array( $status ) ) {
return $status;
}
return [
'remaining' => 100,
'limit' => 100,
'resets_at' => '',
];
}
/**
* Get the list of subreddits configured in plugin settings.
*
* @return string[]
*/
private function get_configured_subreddits(): array {
$json = get_option( 'autoblogger_target_subreddits', '[]' );
$list = json_decode( $json, true );
return is_array( $list ) ? $list : [];
}
}

View File

@@ -0,0 +1,40 @@
<?php
declare(strict_types=1);
/**
* TikTok source provider — STUB for future implementation.
*
* Will integrate with TikTok's API to collect video descriptions, comments,
* and trending topics. Requires TikTok developer app credentials.
*
* Triggered by: Source_Collector when 'tiktok' is in enabled_sources.
* Dependencies: TBD — TikTok API credentials.
*
* @see interface-source-provider.php — Interface this class implements.
* @see ARCHITECTURE.md — Planned source providers.
*/
class Autoblogger_Tiktok_Provider implements Autoblogger_Source_Provider_Interface {
/**
* @param array<string, mixed> $config
* @return Autoblogger_Source_Data[]
* @throws \RuntimeException Always — not yet implemented.
*/
public function collect_data( array $config ): array {
throw new \RuntimeException(
__( 'TikTok source provider is not yet implemented. Remove "tiktok" from enabled sources.', 'autoblogger' )
);
}
public function get_source_type(): string {
return 'tiktok';
}
public function validate_credentials(): bool {
return false;
}
public function get_rate_limit_status(): array {
return [ 'remaining' => 0, 'limit' => 0, 'resets_at' => '' ];
}
}

View File

@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
/**
* YouTube source provider — STUB for future implementation.
*
* Will integrate with YouTube Data API v3 to collect video titles,
* descriptions, comments, and trending topics. Requires Google API key.
*
* Triggered by: Source_Collector when 'youtube' is in enabled_sources.
* Dependencies: TBD — YouTube Data API key.
*
* @see interface-source-provider.php — Interface this class implements.
*/
class Autoblogger_Youtube_Provider implements Autoblogger_Source_Provider_Interface {
/**
* @param array<string, mixed> $config
* @return Autoblogger_Source_Data[]
* @throws \RuntimeException Always — not yet implemented.
*/
public function collect_data( array $config ): array {
throw new \RuntimeException(
__( 'YouTube source provider is not yet implemented. Remove "youtube" from enabled sources.', 'autoblogger' )
);
}
public function get_source_type(): string {
return 'youtube';
}
public function validate_credentials(): bool {
return false;
}
public function get_rate_limit_status(): array {
return [ 'remaining' => 0, 'limit' => 0, 'resets_at' => '' ];
}
}

View File

@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
/**
* Contract for any LLM provider integration (OpenRouter, direct Anthropic, OpenAI, etc.).
*
* 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 CONVENTIONS.md — "How To: Add a New LLM Provider".
* @see ARCHITECTURE.md — External API integrations table.
*/
interface Autoblogger_LLM_Provider_Interface {
/**
* Send a chat completion request to the LLM.
*
* @param array<int, array{role: string, content: string}> $messages Chat messages array.
* @param string $model Model identifier (e.g., 'anthropic/claude-sonnet-4').
* @param array{
* temperature?: float,
* max_tokens?: int,
* response_format?: array{type: string},
* } $options Optional parameters for the API call.
*
* @return array{
* content: string,
* model: string,
* prompt_tokens: int,
* completion_tokens: int,
* total_tokens: int,
* finish_reason: string,
* } Normalized response.
*
* @throws \RuntimeException On API error after retries exhausted.
*/
public function send_chat_completion( array $messages, string $model, array $options = [] ): array;
/**
* Get the list of available models from the provider.
*
* @return array<int, array{id: string, name: string, context_length: int, pricing: array{prompt: float, completion: float}}> Available models.
*/
public function get_available_models(): array;
/**
* Estimate the cost of an API call based on token counts.
*
* @param string $model Model identifier.
* @param int $prompt_tokens Number of input tokens.
* @param int $completion_tokens Number of output tokens.
*
* @return float Estimated cost in USD.
*/
public function estimate_cost( string $model, int $prompt_tokens, int $completion_tokens ): float;
/**
* Get the human-readable name of this provider.
*
* @return string Provider name (e.g., 'OpenRouter').
*/
public function get_provider_name(): string;
/**
* Validate that the provider's credentials are configured and working.
*
* @return bool True if credentials are valid.
*/
public function validate_credentials(): bool;
}

View File

@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
/**
* Contract for any social media source provider (Reddit, TikTok, Instagram, YouTube).
*
* Any class implementing this interface can be registered as a data source.
* The Source_Collector iterates through enabled providers and calls collect_data().
*
* @see class-reddit-provider.php — Primary implementation (Reddit API).
* @see core/class-source-collector.php — Orchestrates collection from all providers.
* @see CONVENTIONS.md — "How To: Add a New Source Provider".
*/
interface Autoblogger_Source_Provider_Interface {
/**
* Collect posts/comments from this social platform.
*
* @param array{
* subreddits?: string[],
* limit?: int,
* time_filter?: string,
* keywords?: string[],
* } $config Source-specific configuration.
*
* @return Autoblogger_Source_Data[] Array of collected data objects.
*
* @throws \RuntimeException On API error after retries exhausted.
*/
public function collect_data( array $config ): array;
/**
* Get the source type identifier for this provider.
*
* Must match a valid value for ab_source_data.source_type.
*
* @return string Source type (e.g., 'reddit', 'tiktok', 'youtube').
*/
public function get_source_type(): string;
/**
* Validate that the provider's API credentials are configured and working.
*
* @return bool True if credentials are valid and API is reachable.
*/
public function validate_credentials(): bool;
/**
* Get current rate limit status for this provider's API.
*
* @return array{
* remaining: int,
* limit: int,
* resets_at: string,
* } Rate limit information.
*/
public function get_rate_limit_status(): array;
}