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 | 2x 2x 2x | /**
* 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
/**
* 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';
if ( ! 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;
}
// Use apiFetch when running inside GutenbergKit (for app password auth
// middleware), but fall back to native fetch everywhere else — including
// the block editor, token-bridge.js, and the front-end — where
// wp.apiFetch may not be enqueued.
const useApiFetch =
!! window?.GBKit && typeof ( window.wp as WpGlobal | undefined )?.apiFetch === 'function';
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 > = useApiFetch
? ( window.wp as Required< WpGlobal > ).apiFetch( {
url: adminAjaxAPI,
...fetchOptions,
parse: false,
} )
: fetch( adminAjaxAPI, fetchOptions );
fetchPromise
.then( response => {
if ( ! response.ok ) {
throw new Error( 'Network response was not ok' );
}
return response.json();
} )
.then( ( response: MediaTokenScopeAdminAjaxResponseBodyProps ) => {
if ( ! 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 );
if ( flushToken ) {
debug( '(%s) Flushing %o token', context, key );
localStorage.removeItem( key );
} else {
try {
if ( 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;
|