| 1 |
import { getImagesShape } from '@auto-launch/fetchers/shape'; |
| 2 |
import { collectBuiltPageImageUrls } from '@auto-launch/functions/get-imported-images'; |
| 3 |
import { |
| 4 |
failWithFallback, |
| 5 |
fetchWithTimeout, |
| 6 |
retryTwice, |
| 7 |
setStatus, |
| 8 |
} from '@auto-launch/functions/helpers'; |
| 9 |
import { IMAGES_HOST } from '@constants'; |
| 10 |
import { reqDataBasics } from '@shared/lib/data'; |
| 11 |
import { __ } from '@wordpress/i18n'; |
| 12 |
|
| 13 |
const fallback = { siteImages: [] }; |
| 14 |
const url = `${IMAGES_HOST}/api/search`; |
| 15 |
const method = 'POST'; |
| 16 |
const headers = { 'Content-Type': 'application/json' }; |
| 17 |
const MIN_POOL_SIZE = 10; |
| 18 |
|
| 19 |
export const handleSiteImages = async ({ siteProfile, designBuild }) => { |
| 20 |
// translators: this is for a action log UI. Keep it short |
| 21 |
setStatus(__('Finding the perfect images', 'extendify-local')); |
| 22 |
|
| 23 |
// Reuse the design preview's own images; only search for what is missing. |
| 24 |
const seeded = collectBuiltPageImageUrls(designBuild?.builtPages); |
| 25 |
if (seeded.length >= MIN_POOL_SIZE) return { siteImages: seeded }; |
| 26 |
|
| 27 |
const body = JSON.stringify({ |
| 28 |
...reqDataBasics, |
| 29 |
siteProfile, |
| 30 |
source: 'auto-launch', |
| 31 |
}); |
| 32 |
|
| 33 |
const response = await retryTwice(() => |
| 34 |
fetchWithTimeout(url, { method, headers, body }), |
| 35 |
); |
| 36 |
|
| 37 |
if (!response?.ok) return { siteImages: seeded }; |
| 38 |
|
| 39 |
const { siteImages: found } = await failWithFallback( |
| 40 |
async () => getImagesShape.parse(await response.json()), |
| 41 |
fallback, |
| 42 |
{ caller: 'handleSiteImages' }, |
| 43 |
); |
| 44 |
|
| 45 |
if (!seeded.length) return { siteImages: found }; |
| 46 |
|
| 47 |
const seededSet = new Set(seeded); |
| 48 |
const topup = found |
| 49 |
.filter((u) => !seededSet.has(u)) |
| 50 |
.slice(0, MIN_POOL_SIZE - seeded.length); |
| 51 |
return { siteImages: [...seeded, ...topup] }; |
| 52 |
}; |
| 53 |
|