| 1 |
import { getLogoShape } from '@auto-launch/fetchers/shape'; |
| 2 |
import { |
| 3 |
failWithFallback, |
| 4 |
fetchWithTimeout, |
| 5 |
retryTwice, |
| 6 |
setStatus, |
| 7 |
} from '@auto-launch/functions/helpers'; |
| 8 |
import { updateOption } from '@auto-launch/functions/wp'; |
| 9 |
import { AI_HOST } from '@constants'; |
| 10 |
import { reqDataBasics } from '@shared/lib/data'; |
| 11 |
import { __ } from '@wordpress/i18n'; |
| 12 |
import { uploadMedia } from '@wordpress/media-utils'; |
| 13 |
|
| 14 |
const { showAILogo } = window.extSharedData; |
| 15 |
const fallback = { |
| 16 |
logoUrl: |
| 17 |
'https://images.extendify-cdn.com/demo-content/logos/ext-custom-logo-default.webp', |
| 18 |
}; |
| 19 |
const url = `${AI_HOST}/api/site-profile/generate-logo`; |
| 20 |
const method = 'POST'; |
| 21 |
const headers = { 'Content-Type': 'application/json' }; |
| 22 |
|
| 23 |
export const handleSiteLogo = async ({ siteProfile }) => { |
| 24 |
if (!showAILogo) return fallback; |
| 25 |
|
| 26 |
// translators: this is for a action log UI. Keep it short |
| 27 |
setStatus(__('Generating a logo', 'extendify-local')); |
| 28 |
|
| 29 |
const { logoObjectName: objectName } = siteProfile; |
| 30 |
const body = JSON.stringify({ ...reqDataBasics, objectName }); |
| 31 |
const response = await retryTwice(() => |
| 32 |
fetchWithTimeout(url, { method, headers, body }), |
| 33 |
); |
| 34 |
|
| 35 |
if (!response?.ok) return fallback; |
| 36 |
|
| 37 |
const logoUrl = await failWithFallback(async () => { |
| 38 |
const { logoUrl } = getLogoShape.parse(await response.json()); |
| 39 |
return logoUrl; |
| 40 |
}, fallback.logoUrl); |
| 41 |
|
| 42 |
// If this errors we just move on. |
| 43 |
await uploadLogo(logoUrl); |
| 44 |
|
| 45 |
return getLogoShape.parse({ logoUrl }); |
| 46 |
}; |
| 47 |
|
| 48 |
export const uploadLogo = async (url) => { |
| 49 |
const blob = await (await fetch(url)).blob(); |
| 50 |
const type = blob.type; |
| 51 |
const fileExtension = type.replace('image/', ''); |
| 52 |
const logoName = `ext-custom-logo-${Date.now()}`; |
| 53 |
const image = new File([blob], `${logoName}.${fileExtension}`, { type }); |
| 54 |
|
| 55 |
await uploadMedia({ |
| 56 |
filesList: [image], |
| 57 |
onFileChange: async ([fileObj]) => { |
| 58 |
if (!fileObj?.id) return; |
| 59 |
await updateOption('site_logo', fileObj.id); |
| 60 |
}, |
| 61 |
onError: console.error, |
| 62 |
}); |
| 63 |
}; |
| 64 |
|