lbry-desktop/ui/modal/modalAutoGenerateThumbnail/view.jsx

88 lines
2.3 KiB
React
Raw Normal View History

2019-05-21 23:18:11 +02:00
// @flow
import React, { useRef } from 'react';
import { Modal } from 'modal/modal';
import { formatFileSystemPath } from 'util/url';
2019-05-21 23:18:11 +02:00
type Props = {
upload: WebFile => void,
2019-05-21 23:18:11 +02:00
filePath: string,
closeModal: () => void,
showToast: ({}) => void,
};
function ModalAutoGenerateThumbnail(props: Props) {
const { closeModal, filePath, upload, showToast } = props;
const playerRef = useRef();
let videoSrc;
if (typeof filePath === 'string') {
videoSrc = formatFileSystemPath(filePath);
} else {
videoSrc = URL.createObjectURL(filePath);
}
2019-05-21 23:18:11 +02:00
function uploadImage() {
const imageBuffer = captureSnapshot();
2019-11-22 22:13:00 +01:00
// $FlowFixMe
const file = new File([imageBuffer], 'thumbnail.png', { type: 'image/png' });
2019-11-22 22:13:00 +01:00
2019-05-21 23:18:11 +02:00
if (imageBuffer) {
2019-11-22 22:13:00 +01:00
// $FlowFixMe
upload(file);
2019-05-21 23:18:11 +02:00
closeModal();
} else {
onError();
}
}
function captureSnapshot(): ?Buffer {
const player = playerRef.current;
if (!player) {
return;
}
const canvas = document.createElement('canvas');
canvas.width = player.videoWidth;
canvas.height = player.videoHeight;
const context = canvas.getContext('2d');
context.drawImage(player, 0, 0, canvas.width, canvas.height);
const dataURL = canvas.toDataURL();
const rawData = dataURL.replace(/data:image\/\w+;base64,/i, '');
canvas.remove();
return Buffer.from(rawData, 'base64');
}
function resize(): void {
const player = playerRef.current;
if (!player) {
return;
}
const fixedWidth = 450;
const videoWidth = player.videoWidth;
const videoHeight = player.videoHeight;
player.width = fixedWidth;
player.height = Math.floor(videoHeight * (fixedWidth / videoWidth));
}
function onError(): void {
showToast({ isError: true, message: __("Something didn't work. Please try again.") });
}
return (
<Modal
isOpen
2020-08-26 22:28:33 +02:00
title={__('Upload thumbnail')}
2019-05-21 23:18:11 +02:00
contentLabel={__('Confirm Thumbnail Upload')}
type="confirm"
confirmButtonLabel={__('Upload')}
onConfirmed={uploadImage}
onAborted={closeModal}
>
2019-11-22 22:13:00 +01:00
<p className="section__subtitle">{__('Pause at any time to select a thumbnail from your video')}.</p>
2019-07-21 23:31:22 +02:00
<video ref={playerRef} src={videoSrc} onLoadedMetadata={resize} onError={onError} controls />
2019-05-21 23:18:11 +02:00
</Modal>
);
}
export default ModalAutoGenerateThumbnail;