File size: 1,079 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import wpcom from 'calypso/lib/wp';

export function getGoogleMediaViaProxy( mediaUrl: string ): Promise< Blob > {
	const params = {
		path: '/meta/external-media/proxy/google_photos',
		apiNamespace: 'wpcom/v2',
		body: {
			url: mediaUrl,
		},
	};

	return new Promise( ( resolve, reject ) => {
		return wpcom.req.post(
			{ ...params, responseType: 'blob' },
			( error: Error | null, data: Blob ) => {
				if ( error || ! ( data instanceof globalThis.Blob ) ) {
					reject( error );
				} else {
					resolve( data );
				}
			}
		);
	} );
}

export function getGoogleMediaViaProxyRetry( mediaUrl: string ): Promise< Blob | unknown > {
	let retries = 0;
	const request = () =>
		getGoogleMediaViaProxy( mediaUrl ).catch( ( error: Error ) => {
			// Retry three times with exponential backoff times
			if ( retries < 3 ) {
				return new Promise( ( resolve ) => {
					++retries;
					setTimeout(
						() => {
							resolve( request() );
						},
						( retries * retries * 1000 ) / 2
					);
				} );
			}

			return Promise.reject( error );
		} );

	return request();
}