Back

79.71% Statements 55/69
76.08% Branches 35/46
100% Functions 7/7
79.71% Lines 55/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226                                        34x     34x                 7x 13x 13x 12x 2x           5x                   34x                   7x 7x   7x         7x                   7x   7x   2x 2x 1x   2x             5x 5x 5x 5x 5x         7x   7x 7x 23x 22x       7x           7x               7x   6x     6x     6x       6x     1x         1x     5x 5x       1x 1x                                   7x 7x   7x             7x 7x       7x 7x                               7x     7x 5x 5x                 7x 7x        
/**
 * External dependencies
 */
import debugFactory from 'debug';
/**
 * Internal dependencies
 */
import { VideoGUID } from '../../block-editor/blocks/video/types';
import { MEDIA_TOKEN_SCOPES } from './types';
/**
 * Types
 */
import type {
	MediaTokenScopeProps,
	MediaTokenScopeAdminAjaxResponseBodyProps,
	MediaTokenProps,
	AdminAjaxTokenProps,
	GetMediaTokenArgsProps,
} from './types';
 
const debug = debugFactory( 'videopress:get-media-token' );
 
// Lifetime of the token in milliseconds.
const TOKEN_LIFETIME = 1000 * 60 * 60 * 24; // 24 hours
 
/**
 * Return GutenbergKit's authenticated `wp.apiFetch`, if any. The token bridge
 * runs in the player's sandbox, so it also checks the same-origin parent window.
 *
 * @return {WpGlobal['apiFetch']} GutenbergKit's apiFetch, or undefined outside GutenbergKit.
 */
function getGutenbergKitApiFetch(): WpGlobal[ 'apiFetch' ] {
	for ( const win of [ window, window.parent ] ) {
		try {
			const apiFetch = ( win.wp as WpGlobal | undefined )?.apiFetch;
			if ( win.GBKit && typeof apiFetch === 'function' ) {
				return apiFetch;
			}
		} catch {
			// A cross-origin parent throws on access; fall back to plain fetch.
		}
	}
	return undefined;
}
 
/**
 * Request media token data hiting the admin-ajax endpoint.
 *
 * @param {MediaTokenScopeProps}   scope - The scope of the token to request.
 * @param {GetMediaTokenArgsProps} args  - function arguments.
 * @return {MediaTokenProps}             Media token data.
 */
const requestMediaToken = function (
	scope: MediaTokenScopeProps,
	args: GetMediaTokenArgsProps = {}
): Promise< MediaTokenProps > {
	const {
		id = 0,
		guid,
		subscriptionPlanId = 0,
		adminAjaxAPI: adminAjaxAPIArgument,
		filename,
	} = args;
	return new Promise( function ( resolve, reject ) {
		const adminAjaxAPI =
			adminAjaxAPIArgument ||
			window.videopressAjax?.ajaxUrl ||
			window?.ajaxurl ||
			'/wp-admin/admin-ajax.php';
 
		Iif ( ! MEDIA_TOKEN_SCOPES.includes( scope ) ) {
			return reject( 'Invalid scope' );
		}
 
		const fetchData: {
			action: AdminAjaxTokenProps;
			guid?: VideoGUID;
			subscription_plan_id?: number;
			post_id?: string;
			filename?: string;
		} = { action: 'videopress-get-playback-jwt' };
 
		switch ( scope ) {
			case 'upload':
				fetchData.action = 'videopress-get-upload-token';
				if ( filename ) {
					fetchData.filename = filename;
				}
				break;
 
			case 'upload-jwt':
				fetchData.action = 'videopress-get-upload-jwt';
				break;
 
			case 'playback':
				fetchData.action = 'videopress-get-playback-jwt';
				fetchData.guid = guid;
				fetchData.post_id = String( id );
				fetchData.subscription_plan_id = subscriptionPlanId;
				break;
		}
 
		// GutenbergKit's apiFetch carries the app's credentials, which cookie-only
		// fetch lacks; everywhere else, wp.apiFetch may not be enqueued.
		const apiFetch = getGutenbergKitApiFetch();
 
		const body = new URLSearchParams();
		for ( const [ key, value ] of Object.entries( fetchData ) ) {
			if ( value !== undefined ) {
				body.append( key, String( value ) );
			}
		}
 
		const fetchOptions: RequestInit = {
			method: 'POST',
			credentials: 'same-origin',
			body,
		};
 
		const fetchPromise: Promise< Response > = apiFetch
			? apiFetch( {
					url: adminAjaxAPI,
					...fetchOptions,
					parse: false,
				} )
			: fetch( adminAjaxAPI, fetchOptions );
 
		fetchPromise
			.then( response => {
				Iif ( ! response.ok ) {
					throw new Error( 'Network response was not ok' );
				}
				return response.json();
			} )
			.then( ( response: MediaTokenScopeAdminAjaxResponseBodyProps ) => {
				Iif ( ! response.success ) {
					throw new Error( 'Token is not achievable' );
				}
 
				switch ( scope ) {
					case 'upload':
					case 'upload-jwt':
						resolve( {
							token: response.data.upload_token,
							blogId: response.data.upload_blog_id,
							url: response.data.upload_action_url,
						} );
						break;
 
					case 'playback':
						resolve( { token: response.data.jwt } );
						break;
				}
			} )
			.catch( error => {
				debug( 'Token request failed: %o', error );
				resolve( { token: null } );
			} );
	} );
};
 
/**
 * Return media token data
 * from the localStore in case it is still valid,
 * otherwise request it from the admin-ajax endpoint.
 *
 * @param {MediaTokenScopeProps}   scope - The scope of the token to request.
 * @param {GetMediaTokenArgsProps} args  - function arguments.
 * @return {MediaTokenProps}             Media token data.
 */
async function getMediaToken(
	scope: MediaTokenScopeProps,
	args: GetMediaTokenArgsProps = {}
): Promise< MediaTokenProps > {
	const { id = 0, guid = 0, flushToken } = args;
	const key = `vpc-${ scope }-${ id }-${ guid }`;
 
	const context = window?.videopressAjax?.context || 'main';
 
	let storedToken: {
		data: MediaTokenProps;
		expire: number;
	};
 
	const storedRawTokenData = localStorage.getItem( key );
	Iif ( flushToken ) {
		debug( '(%s) Flushing %o token', context, key );
		localStorage.removeItem( key );
	} else {
		try {
			Iif ( storedRawTokenData ) {
				storedToken = await JSON.parse( storedRawTokenData );
				if ( storedToken && storedToken.expire > Date.now() ) {
					debug( '(%s) Providing %o token from the store', context, key );
					return storedToken.data;
				}
 
				// Remove expired token.
				debug( '(%s) Token %o expired. Clean.', context, key );
				localStorage.removeItem( key );
			}
		} catch {
			debug( 'Invalid token in the localStore' );
		}
	}
 
	const tokenData = await requestMediaToken( scope, args );
 
	// Only store valid playback tokens.
	if ( 'playback' === scope && tokenData?.token ) {
		debug( '(%s) Storing %o token', context, key );
		localStorage.setItem(
			key,
			JSON.stringify( {
				data: tokenData,
				expire: Date.now() + TOKEN_LIFETIME,
			} )
		);
	}
 
	debug( '(%s) Providing %o token from request/response', context, key );
	return tokenData;
}
 
export default getMediaToken;