license_key = get_option('ailm_saas_license_key', ''); $this->server_url = rtrim(get_option('ailm_saas_server_url', ''), '/'); $this->site_url = get_site_url(); } /** * Основной метод для отправки подписанных запросов на бэкенд. */ public function request_saas(string $endpoint, string $method = 'POST', array $payload = []) { if (empty($this->license_key) || empty($this->server_url)) { return new WP_Error('missing_credentials', 'SaaS License Key or Server URL is missing.'); } $url = $this->server_url . '/' . ltrim($endpoint, '/'); $body_json = empty($payload) ? '' : wp_json_encode($payload); // Генерация HMAC-SHA256 подписи (защита от подделки) $signature = hash_hmac('sha256', $body_json, $this->license_key); $args = [ 'method' => $method, 'timeout' => 45, 'headers' => [ 'Content-Type' => 'application/json', 'X-Site-URL' => $this->site_url, 'X-Signature' => $signature, ], ]; if ($method !== 'GET' && !empty($body_json)) { $args['body'] = $body_json; } $response = wp_remote_request($url, $args); if (is_wp_error($response)) { return $response; } $status_code = wp_remote_retrieve_response_code($response); $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // Обработка статус-кодов нашего Python-сервера if ($status_code === 401) { return new WP_Error('unauthorized', 'SaaS Error: Invalid License Key or Signature.'); } elseif ($status_code === 402) { return new WP_Error('payment_required', 'SaaS Error: Insufficient tokens balance.'); } elseif ($status_code === 403 && is_array($data) && isset($data['error']) && $data['error'] === 'limit_reached') { // Hard limit (10 000 posts) reached — save flag for UI blocking update_option('linkmesh_index_limit_reached', true); return new WP_Error('limit_reached', 'Index limit reached: 10 000 posts.', ['status' => 403]); } elseif ($status_code >= 400) { $err_msg = isset($data['detail']) ? (is_array($data['detail']) ? json_encode($data['detail']) : $data['detail']) : 'Unknown SaaS API Error'; return new WP_Error('saas_error', 'Server error ' . $status_code . ': ' . $err_msg); } // Sync token balance from any successful response (anchor generation, index, etc.) if (is_array($data)) { if (isset($data['tokens_balance'])) { update_option('linkmesh_tokens_balance', (int) $data['tokens_balance']); } elseif (isset($data['new_balance'])) { update_option('linkmesh_tokens_balance', (int) $data['new_balance']); } } return $data; } /** * Старый метод для генерации анкоров (для совместимости). * Теперь отправляет задачу на SaaS. */ public function generate_lsi_anchors(int $post_id, string $donor_text, string $target_title) { return $this->saas_generate_smart_append($post_id, $donor_text, $target_title); } /** * Заглушка для эмбеддингов. * Теперь сервер сам делает эмбеддинги при индексации. */ public function get_embedding(int $post_id, string $text) { return new WP_Error('deprecated', 'Embeddings are handled by the SaaS server.'); } // --- НОВЫЕ МЕТОДЫ ДЛЯ СВЯЗИ С Python API --- public function saas_index_document(int $post_id, string $raw_html) { $response = $this->request_saas('/api/v1/index/document', 'POST', [ 'post_id' => $post_id, 'raw_html' => $raw_html ]); // Reset limit flag on any successful response (self-healing mechanism) if (!is_wp_error($response)) { delete_option('linkmesh_index_limit_reached'); } return $response; } public function saas_get_opportunities(int $post_id, string $target_title) { // Передаем заголовок как query параметр, а ID сайта сервер вычислит по HMAC $endpoint = sprintf('/api/v1/sites/0/opportunities/%d?target_title=%s', $post_id, urlencode($target_title)); return $this->request_saas($endpoint, 'GET'); } public function saas_generate_smart_append(int $donor_id, string $donor_chunk, string $target_title, int $target_post_id = 0) { return $this->request_saas('/api/v1/generate/anchor', 'POST', [ 'donor_post_id' => $donor_id, 'donor_text' => $donor_chunk, 'target_text' => $target_title, 'target_post_id' => $target_post_id, ]); } public function saas_check_task_status(string $task_id) { return $this->request_saas('/api/v1/tasks/' . $task_id, 'GET'); } /** * Получает список ID всех проиндексированных статей с SaaS-сервера. */ public function saas_get_indexed_ids() { return $this->request_saas('/api/v1/index/sync', 'GET'); } /** * Purge ALL vector_chunks for the current site on the SaaS server. * Called before a full re-index so that sync returns accurate data. */ public function saas_purge_index() { return $this->request_saas('/api/v1/index/purge', 'DELETE'); } /** * Delete vector_chunks for a single post on the SaaS server. * Called when an article is modified (e.g. after applying a smart link). */ public function saas_delete_document(int $post_id) { return $this->request_saas('/api/v1/index/document/' . absint($post_id), 'DELETE'); } /** * Sends a link graph to the SaaS server for AILM Rank computation. * * @param array $nodes Array of all post_ids as keys. * @param array $edges Nested array: from_id -> [ to_id -> weight ]. * @param int $front_page_id The site's front page post ID. * @return array|WP_Error Array with 'scores' key or WP_Error on failure. */ public function saas_compute_pagerank(array $nodes, array $edges, int $front_page_id) { $payload = [ 'nodes' => $nodes, 'edges' => $edges, 'front_page_id' => $front_page_id, ]; return $this->request_saas('/api/v1/rank/compute', 'POST', $payload); } /** * Confirm a link has been applied — deducts 1 token on the server. * Called AFTER the link is saved in the WordPress database * (wp_ailm_link_rules) by handle_apply_smart_link(). * * This is the ONLY place where tokens should be deducted. * * @param int $donor_post_id The post where the link was inserted. * @param int $target_post_id The post the link points to. * @param string $anchor_text The anchor text used. * @return array|WP_Error */ public function saas_confirm_link(int $donor_post_id, int $target_post_id, string $anchor_text = '') { return $this->request_saas('/api/v1/links/confirm', 'POST', [ 'donor_post_id' => $donor_post_id, 'target_post_id' => $target_post_id, 'anchor_text' => $anchor_text, ]); } /** * Create a new batch generation job on the SaaS server. * * @param array $items Array of items, each with donor_post_id, donor_text, * target_post_id, target_text. * @return array|WP_Error {batch_id, status, total_items} */ public function saas_create_batch(array $items) { return $this->request_saas('/api/v1/batches', 'POST', [ 'items' => $items, ]); } /** * Get batch status and progress from the SaaS server. * * @param string $batch_id UUID of the batch. * @return array|WP_Error {batch_id, status, total_items, completed_items, * failed_items, progress_pct} */ public function saas_get_batch_status(string $batch_id) { return $this->request_saas('/api/v1/batches/' . sanitize_text_field($batch_id), 'GET'); } /** * Paginated results for a batch. * * @param string $batch_id UUID of the batch. * @param int $limit Page size (default 10). * @param int $offset Offset for pagination. * @return array|WP_Error */ public function saas_get_batch_results(string $batch_id, int $limit = 10, int $offset = 0) { $endpoint = sprintf( '/api/v1/batches/%s/results?limit=%d&offset=%d', sanitize_text_field($batch_id), $limit, $offset ); return $this->request_saas($endpoint, 'GET'); } /** * Inline edit a single batch item (e.g. anchor text) from Review Queue. * * @param string $batch_id UUID of the batch. * @param int $item_index 0-based index within the batch. * @param array $fields Fields to update (e.g. ['anchor' => '...']). * @return array|WP_Error */ public function saas_update_batch_item(string $batch_id, int $item_index, array $fields) { return $this->request_saas(sprintf( '/api/v1/batches/%s/items/%d', sanitize_text_field($batch_id), $item_index ), 'PATCH', $fields); } /** * Confirm selected items from a batch — atomically deducts tokens. * * @param string $batch_id UUID of the batch. * @param int[] $item_indices Array of 0-based indices to confirm. * @return array|WP_Error {confirmed_count, tokens_balance} */ public function saas_confirm_batch(string $batch_id, array $item_indices) { return $this->request_saas('/api/v1/links/confirm_batch', 'POST', [ 'batch_id' => $batch_id, 'item_indices' => array_map('intval', $item_indices), ]); } /** * Delete a completed batch and all its results from the SaaS server. * * @param string $batch_id UUID of the batch. * @return array|WP_Error */ public function saas_delete_batch(string $batch_id) { return $this->request_saas('/api/v1/batches/' . sanitize_text_field($batch_id), 'DELETE'); } /** * Outbound quick search: find best TARGET articles for a donor paragraph. * * Calls the new backend endpoint GET /api/v1/sites/{site_id}/opportunities/quick. * Used by the Gutenberg Sidebar (Link FROM this post) and Inline Toolbar. * * @param string $donor_text The paragraph / selected block text. * @param int $donor_post_id Optional donor post ID (excluded from results). * @return array|WP_Error */ public function saas_get_quick_opportunities(string $donor_text, int $donor_post_id = 0) { $endpoint = sprintf( '/api/v1/sites/0/opportunities/quick?donor_text=%s&donor_post_id=%d&limit=15', urlencode($donor_text), absint($donor_post_id) ); return $this->request_saas($endpoint, 'GET'); } }