Back

96.93% Statements 95/98
91.3% Branches 42/46
96.15% Functions 25/26
96.73% Lines 89/92

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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272                                                                  4x 4x                                                 2306x 37x           2306x     1971x 138x   4x 121x 121x 121x 121x       4x 156x 156x 305x     4x 99x 132x           35x                   42x 42x 17x   25x 25x   16x   25x     25x 18x 18x         14x 1x     1x         14x   21x 21x 21x 21x 8x     4x                   58x 58x 6x   60x 52x 20x   32x 32x 32x 32x 26x 26x 26x   32x 4x     4x                 4x   32x 32x           3x 1x       24x 2x   22x 22x 22x                             511x 511x   511x   28x 28x     28x 28x         511x   6x 1x 1x   5x 1x   4x 4x         511x   18x 18x 18x 18x           511x   1x         511x                  
import { isSimpleSite } from '@automattic/jetpack-script-data';
import { useQueryClient } from '@tanstack/react-query';
import apiFetch from '@wordpress/api-fetch';
import { dispatch } from '@wordpress/data';
import { useCallback, useSyncExternalStore } from '@wordpress/element';
import { store as noticesStore } from '@wordpress/notices';
import resumableFileUploader from '../../client/lib/resumable-file-uploader';
import { syncChapters } from '../../client/utils/video-chapters/sync-chapters';
import { LIBRARY_QUERY_KEY, toLibraryItem } from './use-library';
import { patchToApi } from './use-update-video-meta';
import type { ApiMediaItem } from './use-library';
import type { VideoMediaProps } from '../../client/lib/resumable-file-uploader/types';
import type { VideoDetailsPatch } from '../types/library';
import type { QueryClient } from '@tanstack/react-query';
 
export type UploadStatus = 'pending' | 'uploading' | 'success' | 'failed';
 
export type UploadItem = {
	id: string;
	file: File;
	progress: number;
	status: UploadStatus;
	error?: string;
	errorCode?: string;
	attachmentId?: number;
	mediaId?: string;
	media?: VideoMediaProps;
	/** The metadata accepted by Save, excluding any subsequent form edits. */
	details?: VideoDetailsPatch;
	isSavingDetails?: boolean;
	detailsError?: boolean;
};
 
const STORE_KEY = '__jetpackVideopressUploadStore' as const;
const SUCCESS_REMOVAL_DELAY_MS = 2_000;
 
type UploadSnapshot = {
	queue: UploadItem[];
	completed: Record< string, string >;
};
 
type UploadStore = {
	snapshot: UploadSnapshot;
	activeId: string | null;
	subscribers: Set< () => void >;
};
 
declare global {
	interface Window {
		[ STORE_KEY ]?: UploadStore;
	}
}
 
/**
 * Share the queue and its worker across separately built route bundles.
 *
 * @return The upload store.
 */
function getStore(): UploadStore {
	if ( ! window[ STORE_KEY ] ) {
		window[ STORE_KEY ] = {
			snapshot: { queue: [], completed: {} },
			activeId: null,
			subscribers: new Set(),
		};
	}
	return window[ STORE_KEY ];
}
 
const readSnapshot = () => getStore().snapshot;
const readItem = ( id: string ) => readSnapshot().queue.find( item => item.id === id );
 
const subscribeStore = ( notify: () => void ) => {
	const store = getStore();
	store.subscribers.add( notify );
	return () => {
		store.subscribers.delete( notify );
	};
};
 
const updateSnapshot = ( patch: Partial< UploadSnapshot > ) => {
	const store = getStore();
	store.snapshot = { ...store.snapshot, ...patch };
	store.subscribers.forEach( notify => notify() );
};
 
const updateItem = ( id: string, patch: Partial< UploadItem > ) => {
	updateSnapshot( {
		queue: readSnapshot().queue.map( item => ( item.id === id ? { ...item, ...patch } : item ) ),
	} );
};
 
/** Reset the upload store between tests. */
export function __resetUploadStoreForTests(): void {
	delete window[ STORE_KEY ];
}
 
/**
 * Save deferred edits before handing the temporary route over to its attachment.
 *
 * @param id     - Temporary upload ID.
 * @param client - Shared query client.
 */
async function finishUpload( id: string, client: QueryClient ): Promise< void > {
	const initial = readItem( id );
	if ( ! initial?.media || initial.isSavingDetails ) {
		return;
	}
	updateItem( id, { isSavingDetails: true, detailsError: false } );
	if ( initial.details ) {
		// The free-tier count skips finished uploads, so list this one while its edits save.
		void client.invalidateQueries( { queryKey: [ LIBRARY_QUERY_KEY ] } );
	}
	try {
		let saved: VideoDetailsPatch | undefined;
		// Save clicks during a request must be applied before the form changes routes.
		while ( readItem( id )?.details !== saved ) {
			const details = readItem( id )?.details;
			await apiFetch( {
				path: '/wpcom/v2/videopress/meta',
				method: 'POST',
				data: { id: initial.media.id, ...patchToApi( details ) },
			} );
			if ( details.description !== undefined ) {
				const raw = await apiFetch< ApiMediaItem >( {
					path: `/wp/v2/media/${ initial.media.id }`,
				} );
				await syncChapters( toLibraryItem( raw, isSimpleSite() ), details.description, {
					onWarning: message =>
						dispatch( noticesStore ).createWarningNotice( message, { type: 'snackbar' } ),
				} );
			}
			saved = details;
		}
		updateItem( id, { isSavingDetails: false } );
		updateSnapshot( { completed: { ...readSnapshot().completed, [ id ]: initial.mediaId } } );
		await client.invalidateQueries( { queryKey: [ LIBRARY_QUERY_KEY ] } );
		window.setTimeout( () => {
			updateSnapshot( { queue: readSnapshot().queue.filter( item => item.id !== id ) } );
		}, SUCCESS_REMOVAL_DELAY_MS );
	} catch {
		updateItem( id, { isSavingDetails: false, detailsError: true } );
	}
}
 
/**
 * Run one transport at a time, independently of the route that enqueued it.
 *
 * @param client - Shared query client.
 */
async function startNextPending( client: QueryClient ): Promise< void > {
	const store = getStore();
	if ( store.activeId ) {
		return;
	}
	const next = readSnapshot().queue.find( item => item.status === 'pending' );
	if ( ! next ) {
		return;
	}
	const { id, file } = next;
	store.activeId = id;
	let settled = false;
	const settle = () => {
		settled = true;
		store.activeId = null;
		void startNextPending( client );
	};
	const onError = ( error: unknown ) => {
		Iif ( settled || store.activeId !== id ) {
			return;
		}
		updateItem( id, {
			status: 'failed',
			attachmentId: ( error as { attachmentId?: number } )?.attachmentId ?? next.attachmentId,
			error: error instanceof Error ? error.message : String( error ),
			errorCode:
				typeof ( error as { code?: unknown } )?.code === 'string'
					? ( error as { code: string } ).code
					: undefined,
		} );
		settle();
	};
	try {
		resumableFileUploader( {
			file,
			tokenData: next.attachmentId
				? { token: null, url: window.videopressUpload?.url, attachmentId: next.attachmentId }
				: undefined,
			onProgress: ( sent, total ) => {
				if ( ! settled && store.activeId === id ) {
					updateItem( id, { progress: total > 0 ? sent / total : 0, status: 'uploading' } );
				}
			},
			onSuccess: media => {
				if ( settled || store.activeId !== id ) {
					return;
				}
				updateItem( id, { progress: 1, status: 'success', mediaId: String( media.id ), media } );
				settle();
				void finishUpload( id, client );
			},
			onError,
		} );
	} catch ( error ) {
		onError( error );
	}
}
 
/**
 * Observe uploads and edit their drafts without tying the worker to a React mount.
 *
 * @return Upload state and handlers.
 */
export function useUpload() {
	const client = useQueryClient();
	const { queue, completed } = useSyncExternalStore( subscribeStore, readSnapshot, readSnapshot );
 
	const startUpload = useCallback(
		( file: File ): string => {
			const id = `upload-${ Date.now() }-${ Math.random().toString( 36 ).slice( 2, 10 ) }`;
			updateSnapshot( {
				queue: [ ...readSnapshot().queue, { id, file, progress: 0, status: 'pending' } ],
			} );
			void startNextPending( client );
			return id;
		},
		[ client ]
	);
 
	const retryUpload = useCallback(
		( id: string ) => {
			if ( readItem( id )?.detailsError ) {
				void finishUpload( id, client );
				return;
			}
			if ( readItem( id )?.status !== 'failed' ) {
				return;
			}
			updateItem( id, { status: 'pending', progress: 0, error: undefined, errorCode: undefined } );
			void startNextPending( client );
		},
		[ client ]
	);
 
	const saveUploadDetails = useCallback(
		( id: string, patch: VideoDetailsPatch ) => {
			const item = readItem( id );
			Eif ( item && ! readSnapshot().completed[ id ] ) {
				updateItem( id, { details: { ...item.details, ...patch } } );
				void finishUpload( id, client );
			}
		},
		[ client ]
	);
 
	const retryUploadDetails = useCallback(
		( id: string ) => {
			void finishUpload( id, client );
		},
		[ client ]
	);
 
	return {
		uploadQueue: queue,
		completedUploads: completed,
		startUpload,
		retryUpload,
		saveUploadDetails,
		retryUploadDetails,
	};
}