* @throws Action_Failed Сверка с фотосессией не удалась. */ public function list_for_window( int $product_id, string $photo_session_id, array $attachment_ids ): array { $context = array( 'product_id' => $product_id, 'photo_session_id' => $photo_session_id, ); $ids = self::product_photo_ids( $attachment_ids ); $alive = $this->photos_in_session( $product_id, $photo_session_id ); $photos = array(); foreach ( $ids as $attachment_id ) { $photos[] = array( 'attachmentId' => $attachment_id, 'thumbUrl' => Attachment_Info::thumb_url( $attachment_id ), // Полный размер — для просмотра по лупе в окне; в слотах и в списке — миниатюра. 'url' => Attachment_Info::full_url( $attachment_id ), 'fileName' => Attachment_Info::file_name( $attachment_id ), 'sourcePhoto' => $alive[ $attachment_id ] ?? null, ); } Logger::info( 'Product photos listed for the window', array_merge( $context, array( 'photos' => count( $photos ), 'in_session' => count( array_intersect_key( $alive, array_flip( $ids ) ) ), ) ) ); return $photos; } /** * Загружает одно фото товара в фотосессию — в слот, который назвало окно. * * Повтор просьбы, ответ на которую до окна не дошёл (окно не дождалось и попросило снова), * второй копии не создаёт: если это вложение уже загружено и фото вещи на месте, окну * уходит оно же. * * @param int $product_id Товар. * @param string $photo_session_id Фотосессия товара. * @param int $attachment_id Вложение — фото товара. * @param string $slot Свободный слот. * @return array Ответ для окна — Upload_Reply: «загружено» или «не прошло проверку». * @throws Action_Failed Сбой: текст для человека; признак temporary — поможет ли повтор. */ public function upload( int $product_id, string $photo_session_id, int $attachment_id, string $slot ): array { $context = array( 'product_id' => $product_id, 'photo_session_id' => $photo_session_id, 'attachment_id' => $attachment_id, 'slot' => $slot, ); if ( array( $attachment_id ) !== self::product_photo_ids( array( $attachment_id ) ) ) { Logger::warning( 'Upload refused: the attachment is not a product photo', $context ); throw new Action_Failed( __( 'This photo was not found in the Media Library. Reload the product page.', 'aimodelka' ) ); } $links_key = self::links_meta_key( $product_id, $photo_session_id ); $links = Source_Photo_Links::from_meta( get_post_meta( $product_id, $links_key, true ) ); if ( isset( $links[ $attachment_id ] ) ) { $alive = $this->photos_in_session( $product_id, $photo_session_id ); if ( isset( $alive[ $attachment_id ] ) ) { Logger::info( 'Product photo is already in the photo session and is not sent again', array_merge( $context, array( 'source_photo_id' => $alive[ $attachment_id ]['id'] ) ) ); return array( 'result' => Upload_Reply::UPLOADED, 'photo' => $alive[ $attachment_id ], ); } $links = Source_Photo_Links::from_meta( get_post_meta( $product_id, $links_key, true ) ); } wc_set_time_limit( self::TIME_LIMIT ); wp_raise_memory_limit( 'image' ); $file = Source_Photos::read( $attachment_id ); if ( null === $file ) { // Ни оригинал, ни копия WordPress не подходят aiModelka (например, AVIF или больше // пределов загрузки) — отправлять нечего, и повтор этого не изменит. Logger::warning( 'Product photo cannot be sent: no file aiModelka accepts', $context ); return Upload_Reply::rejected( '', __( 'This file can’t be sent to aiModelka: it isn’t a JPEG, PNG or WebP image, or it is too large.', 'aimodelka' ) ); } $sent = array( 'name' => $file['name'], 'bytes' => $file['bytes'], 'width' => $file['width'], 'height' => $file['height'], ); try { $photo = $this->client->upload_source_photo( $photo_session_id, $slot, $file['name'], $file['mime'], $file['contents'] ); } catch ( Api_Exception $exception ) { if ( Upload_Reply::is_rejection( $exception->kind ) ) { Logger::warning( 'Product photo was not accepted by aiModelka', array_merge( $context, array( 'error_code' => $exception->error_code ) ) ); return Upload_Reply::rejected( $exception->error_code, Texts::for_error( $exception->kind ) ); } throw Action_Failed::from_api( $exception ); } finally { unset( $file ); } $reply = Upload_Reply::uploaded( $photo ); if ( null === $reply ) { Logger::error( 'aiModelka answered the upload without a usable photo', $context ); throw new Action_Failed( __( 'aiModelka could not complete the request. Try again in a few minutes.', 'aimodelka' ), true ); } update_post_meta( $product_id, $links_key, Source_Photo_Links::remember( $links, $attachment_id, $reply['photo'] ) ); // Имя и размеры отправленного файла — в журнал: по ним видно, что ушёл оригинал, // а не уменьшенная копия WordPress. Logger::info( 'Product photo uploaded', array_merge( $context, array( 'source_photo_id' => $reply['photo']['id'], 'landed_in_slot' => $reply['photo']['slot'], 'file' => $sent['name'], 'bytes' => $sent['bytes'], 'width' => $sent['width'], 'height' => $sent['height'], ) ) ); return $reply; } /** * Какие фото товара сейчас в съёмке: записи меты, сверенные с фотосессией на сервере. * Записи о фото, которых в съёмке больше нет, из меты уходят. * * @param int $product_id Товар. * @param string $photo_session_id Фотосессия товара. * @return array Вложение → фото вещи. * @throws Action_Failed Фотосессию прочитать не удалось. */ private function photos_in_session( int $product_id, string $photo_session_id ): array { $links_key = self::links_meta_key( $product_id, $photo_session_id ); $links = Source_Photo_Links::from_meta( get_post_meta( $product_id, $links_key, true ) ); if ( array() === $links ) { return array(); } try { $session = $this->client->get_photo_session( $photo_session_id ); } catch ( Api_Exception $exception ) { throw Action_Failed::from_api( $exception ); } $alive = Source_Photo_Links::in_session( $links, (array) ( $session['sourcePhotos'] ?? array() ) ); $kept = Source_Photo_Links::only_alive( $links, $alive ); if ( count( $kept ) !== count( $links ) ) { update_post_meta( $product_id, $links_key, $kept ); Logger::info( 'Product photos left the photo session; their records are removed', array( 'product_id' => $product_id, 'photo_session_id' => $photo_session_id, 'attachments' => array_keys( array_diff_key( $links, $kept ) ), ) ); } return $alive; } /** * Поле меты с записями «фото товара → фото вещи» этой фотосессии. Адреса REST уже проверили, * что фотосессия — этого товара, поэтому тип находится всегда; запасной вариант — фото * на модели. * * @param int $product_id Товар. * @param string $photo_session_id Фотосессия товара. * @return string Имя поля меты. */ private static function links_meta_key( int $product_id, string $photo_session_id ): string { return Photo_Kinds::source_photos_meta_key( Photo_Kinds::of_session( $product_id, $photo_session_id ) ?? Photo_Kinds::ON_MODEL ); } /** * Какие из вложений — фото товара для окна: изображения из медиатеки, сделанные не aiModelka. * Порядок сохраняется, повторы и всё прочее отбрасываются. * * @param int[] $attachment_ids Id вложений. * @return int[] */ private static function product_photo_ids( array $attachment_ids ): array { $ids = Attachment_Info::image_ids( $attachment_ids, self::MAX_PHOTOS ); // Фото aiModelka — модель в одежде: проверка aiModelka такие не принимает, // и в съёмке как фото вещи им не место. $made_by_aimodelka = Image_Importer::made_by_aimodelka( $ids ); return array_values( array_diff( $ids, $made_by_aimodelka ) ); } }