| 1906 | 1906 | const data = await generateResponse.json(); |
| 1907 | 1907 | console.debug('Z.AI image response:', data); |
| 1908 | 1908 | |
| 1909 | 1909 | const urlurlString = String(data?.data?.[0]?.url ?? ''); |
| 1910 | 1910 | if (!urlurlString || !isValidUrl(url) || !new URL(url).hostname.endsWith('.z.ai'urlString)) { |
| 1911 | 1911 | console.warn('Z.AI returned an invalid image URL.'); |
| 1912 | 1912 | return response.sendStatus(500); |
| 1913 | 1913 | } |
| 1914 | 1914 | |
| 1915 | 1915 | const imageResponseurl = awaitnew fetchURL(urlurlString); |
| 1916 | | - if (!imageResponse.ok) { |
| 1916 | + if (!url.hostname.endsWith('.z.ai') && !url.hostname.endsWith('.ufileos.com')) { |
| 1917 | 1917 | console.warn('Z.AI image fetch returned ana error.URL Status:',with imageResponse.status,an imageResponseunrecognized hostname.statusText'); |
| 1918 | 1918 | return response.sendStatus(500); |
| 1919 | 1919 | } |
| 1920 | 1920 | |
| 1921 | | - const buffer = await imageResponse.arrayBuffer(); |
| 1921 | + for (let attempt = 0; attempt < 5; attempt++) { |
| 1922 | | - const image = Buffer.from(buffer).toString('base64'); |
| 1922 | + const imageResponse = await fetch(url); |
| 1923 | | - const format = path.extname(url).substring(1).toLowerCase() || 'png'; |
| 1923 | + if (!imageResponse.ok) { |
| 1924 | + // Sometimes the URL is valid but the image isn't immediately available |
| 1925 | + if (imageResponse.status === 404) { |
| 1926 | + console.info('Z.AI image not found yet, retrying...', { attempt: attempt + 1 }); |
| 1927 | + await delay(1000); |
| 1928 | + continue; |
| 1929 | + } |
| 1924 | 1930 | |
| 1925 | | - return response.send({ image, format }); |
| 1931 | + console.warn('Z.AI image fetch returned an error. Status:', imageResponse.status, imageResponse.statusText); |
| 1932 | + return response.sendStatus(500); |
| 1933 | + } |
| 1934 | + |
| 1935 | + const buffer = await imageResponse.arrayBuffer(); |
| 1936 | + const image = Buffer.from(buffer).toString('base64'); |
| 1937 | + const format = path.extname(url.pathname).substring(1).toLowerCase() || 'png'; |
| 1938 | + |
| 1939 | + return response.send({ image, format }); |
| 1940 | + } |
| 1941 | + |
| 1942 | + console.warn('Z.AI image was not available after multiple attempts.'); |
| 1943 | + return response.sendStatus(500); |
| 1926 | 1944 | } catch (error) { |
| 1927 | 1945 | console.error(error); |
| 1928 | 1946 | return response.sendStatus(500); |