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

96 lines
2.6 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';
import { THUMBNAIL_CDN_SIZE_LIMIT_BYTES } from 'config';
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 generateImg = (quality: number) => {
const imageBuffer = captureSnapshot(quality);
2019-11-22 22:13:00 +01:00
// $FlowFixMe
const file = new File([imageBuffer], 'thumbnail.jpeg', { type: 'image/jpeg' });
return { imageBuffer, file };
};
let img = generateImg(1.0);
if (img.file && img.file.size > THUMBNAIL_CDN_SIZE_LIMIT_BYTES) {
img = generateImg(0.8);
}
if (img.imageBuffer) {
upload(img.file);
2019-05-21 23:18:11 +02:00
closeModal();
} else {
onError();
}
}
function captureSnapshot(quality: number): ?Buffer {
2019-05-21 23:18:11 +02:00
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('image/jpeg', quality);
2019-05-21 23:18:11 +02:00
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;