Back

100% Statements 40/40
87.5% Branches 7/8
100% Functions 14/14
100% Lines 36/36

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                                  4x                                                             17x                                                               4x         16x             16x 16x 16x                   5x 5x 5x       5x 5x       2x 1x     1x 1x           1x     1x 1x 1x 1x     2x 2x 2x       5x   1x 1x     1x 1x       5x                 2x 2x 1x 1x     1x     16x        
/**
 * External dependencies
 */
import { useState } from '@wordpress/element';
import debugFactory from 'debug';
/**
 * Internal dependencies
 */
import resumableFileUploader from '../../lib/resumable-file-uploader';
import { UPLOAD_TOKEN_ERROR_CODE } from '../../lib/resumable-file-uploader/token-error';
export {
	UPLOAD_TOKEN_ERROR_CODE,
	UploadTokenError,
} from '../../lib/resumable-file-uploader/token-error';
import { VideoMediaProps } from '../../lib/resumable-file-uploader/types';
import type { ChangeEvent } from 'react';
 
const debug = debugFactory( 'videopress:use-resumable-uploader' );
 
/**
 * A failure as it reaches `onError` and the returned `error`.
 *
 * Always an `Error`, but the extras depend on where it came from: `code` on
 * failures raised here (see `UploadTokenError`), `originalResponse` on tus
 * transport failures. Consumers branch on both, so they are declared optional
 * rather than left off the type.
 */
export type ResumableUploadError = Error & {
	code?: string;
	originalResponse?: { getBody?: () => string };
};
 
/**
 * Whether a failed upload may be blamed on the Jetpack connection.
 *
 * A missing token means the upload never reached WordPress.com, but not why; only
 * a connection error alongside it justifies naming the connection. Both checks are
 * needed, because each rules out a different mistake. Shared so the dashboard's
 * `classifyUploadFailure()` and the block editor's `getErrorMessage()` cannot drift.
 *
 * @param {string}  errorCode          - The `code` carried by the failure, if it carried one.
 * @param {boolean} hasConnectionError - Whether the connection store is reporting an error.
 * @return {boolean} Whether the failure should be attributed to the connection.
 */
export function isConnectionAttributedFailure(
	errorCode: string | undefined,
	hasConnectionError: boolean
): boolean {
	return errorCode === UPLOAD_TOKEN_ERROR_CODE && hasConnectionError;
}
 
type UploadingStatusProp = 'idle' | 'resumed' | 'aborted' | 'uploading' | 'done' | 'error';
 
type UploadingDataProps = {
	bytesSent: number;
	bytesTotal: number;
	percent: number;
	status: UploadingStatusProp;
};
 
type ResumaHandlerProps = {
	start: () => void;
	abort: () => void;
};
 
type UseResumableUploader = {
	onUploadHandler: ( event: ChangeEvent< HTMLInputElement > ) => void;
	uploadHandler: ( file: File ) => void;
	resumeHandler: ResumaHandlerProps;
	uploadingData: UploadingDataProps;
	media: VideoMediaProps;
	error: ResumableUploadError | null;
};
 
type UseResumableUploaderProps = {
	onProgress: ( bytesSent: number, bytesTotal: number ) => void;
	onSuccess: ( data: VideoMediaProps ) => void;
	onError: ( error: ResumableUploadError ) => void;
};
 
const useResumableUploader = ( {
	onProgress,
	onSuccess,
	onError,
}: UseResumableUploaderProps ): UseResumableUploader => {
	const [ uploadingData, setUploadingData ] = useState< UploadingDataProps >( {
		bytesSent: 0,
		bytesTotal: 0,
		percent: 0,
		status: 'idle',
	} );
 
	const [ media, setMedia ] = useState< VideoMediaProps >();
	const [ error, setError ] = useState< ResumableUploadError | null >( null );
	const [ resumeHandler, setResumeHandler ] = useState< ResumaHandlerProps >();
 
	/**
	 * Upload a file
	 *
	 * @param {File} file - the file to upload
	 * @return {*} ???
	 */
	async function uploadHandler( file: File ) {
		// The file starts to upload automatically, so we need to set the status to uploading
		Eif ( uploadingData.status === 'idle' ) {
			setUploadingData( prev => {
				return { ...prev, status: 'uploading' };
			} );
		}
 
		let isDone = false;
		const resumableHandler = resumableFileUploader( {
			file,
			onProgress: ( bytesSent: number, bytesTotal: number ) => {
				// If the upload is done, don't update the progress
				if ( isDone ) {
					return;
				}
 
				const percent = Math.round( ( bytesSent / bytesTotal ) * 100 );
				setUploadingData( {
					bytesSent,
					bytesTotal,
					percent,
					status: 'uploading',
				} );
				onProgress( bytesSent, bytesTotal );
			},
			onSuccess: ( data: VideoMediaProps ) => {
				isDone = true;
				setUploadingData( prev => ( { ...prev, status: 'done' } ) );
				setMedia( data );
				onSuccess( data );
			},
			onError: ( err: ResumableUploadError ) => {
				setUploadingData( prev => ( { ...prev, status: 'error' } ) );
				setError( err );
				onError( err );
			},
		} );
 
		const resumable = {
			start: () => {
				setUploadingData( prev => ( { ...prev, status: 'uploading' } ) );
				resumableHandler.start();
			},
			abort: () => {
				setUploadingData( prev => ( { ...prev, status: 'aborted' } ) );
				resumableHandler.abort();
			},
		};
 
		setResumeHandler( resumable );
	}
 
	/**
	 * Handler for the file upload
	 *
	 * @param {ChangeEvent< HTMLInputElement >} event - the event object
	 */
	function onUploadHandler( event: ChangeEvent< HTMLInputElement > ) {
		const file = event.target.files[ 0 ];
		if ( ! file ) {
			debug( 'No file selected. Bail early' );
			return;
		}
 
		uploadHandler( file );
	}
 
	return { onUploadHandler, uploadHandler, resumeHandler, uploadingData, media, error };
};
 
export default useResumableUploader;