lbry-desktop/ui/component/viewers/videoViewer/view.jsx

459 lines
14 KiB
React
Raw Permalink Normal View History

2019-08-02 08:28:14 +02:00
// @flow
2021-04-12 18:43:47 +02:00
import { ENABLE_PREROLL_ADS } from 'config';
import * as PAGES from 'constants/pages';
import * as ICONS from 'constants/icons';
2020-04-16 23:43:09 +02:00
import React, { useEffect, useState, useContext, useCallback } from 'react';
2019-08-02 08:28:14 +02:00
import { stopContextMenu } from 'util/context-menu';
2020-04-28 21:33:30 +02:00
import type { Player } from './internal/videojs';
import VideoJs from './internal/videojs';
2020-01-22 18:19:49 +01:00
import analytics from 'analytics';
import { EmbedContext } from 'page/embedWrapper/view';
2020-04-14 01:48:11 +02:00
import classnames from 'classnames';
2020-03-27 17:49:41 +01:00
import { FORCE_CONTENT_TYPE_PLAYER } from 'constants/claim';
2020-04-14 01:48:11 +02:00
import AutoplayCountdown from 'component/autoplayCountdown';
import usePrevious from 'effects/use-previous';
import FileViewerEmbeddedEnded from 'web/component/fileViewerEmbeddedEnded';
import FileViewerEmbeddedTitle from 'component/fileViewerEmbeddedTitle';
2020-04-16 23:43:09 +02:00
import LoadingScreen from 'component/common/loading-screen';
2021-01-08 16:21:27 +01:00
import { addTheaterModeButton } from './internal/theater-mode';
2021-08-25 15:33:27 +02:00
import { addAutoplayNextButton } from './internal/autoplay-next';
2021-08-25 14:08:30 +02:00
import { addPlayNextButton } from './internal/play-next';
2021-08-25 13:25:55 +02:00
import { addPlayPreviousButton } from './internal/play-previous';
2021-04-12 18:43:47 +02:00
import { useGetAds } from 'effects/use-get-ads';
import Button from 'component/button';
import I18nMessage from 'component/i18nMessage';
import { useHistory } from 'react-router';
2021-07-17 00:20:22 +02:00
import { getAllIds } from 'util/buildHomepage';
import type { HomepageCat } from 'util/buildHomepage';
2021-08-25 14:08:30 +02:00
import { formatLbryUrlForWeb } from 'util/url';
import { COLLECTIONS_CONSTS } from 'lbry-redux';
2019-08-02 08:28:14 +02:00
2020-04-28 21:33:30 +02:00
const PLAY_TIMEOUT_ERROR = 'play_timeout_error';
const PLAY_TIMEOUT_LIMIT = 2000;
2020-04-28 21:33:30 +02:00
2019-08-02 08:28:14 +02:00
type Props = {
2019-09-06 02:26:03 +02:00
position: number,
changeVolume: (number) => void,
changeMute: (boolean) => void,
2019-08-02 08:28:14 +02:00
source: string,
contentType: string,
thumbnail: string,
2020-08-07 22:59:20 +02:00
claim: StreamClaim,
2020-04-16 23:43:09 +02:00
muted: boolean,
videoPlaybackRate: number,
2020-04-16 23:43:09 +02:00
volume: number,
2020-04-14 01:48:11 +02:00
uri: string,
autoplaySetting: boolean,
autoplayIfEmbedded: boolean,
desktopPlayStartTime?: number,
2020-04-14 01:48:11 +02:00
doAnalyticsView: (string, number) => Promise<any>,
2020-08-07 22:59:20 +02:00
doAnalyticsBuffer: (string, any) => void,
2020-04-14 01:48:11 +02:00
claimRewards: () => void,
savePosition: (string, number) => void,
clearPosition: (string) => void,
2021-01-08 16:21:27 +01:00
toggleVideoTheaterMode: () => void,
2021-08-25 15:33:27 +02:00
toggleAutoplayNext: () => void,
setVideoPlaybackRate: (number) => void,
2021-08-25 14:08:30 +02:00
doSetPlayingUri: (string, string) => void,
doPlayUri: (string) => void,
playNextUri: string,
2021-08-25 13:25:55 +02:00
playPreviousUri: string,
2021-04-12 18:43:47 +02:00
authenticated: boolean,
userId: number,
2021-07-17 00:20:22 +02:00
homepageData?: { [string]: HomepageCat },
shareTelemetry: boolean,
videoTheaterMode: boolean,
2021-08-25 14:08:30 +02:00
collectionId: string,
isFloating: boolean,
2019-08-02 08:28:14 +02:00
};
2020-04-16 01:21:17 +02:00
/*
codesandbox of idealized/clean videojs and react 16+
https://codesandbox.io/s/71z2lm4ko6
*/
2019-08-02 08:28:14 +02:00
function VideoViewer(props: Props) {
const {
contentType,
source,
changeVolume,
changeMute,
videoPlaybackRate,
thumbnail,
2020-03-19 21:25:37 +01:00
position,
claim,
2020-04-14 01:48:11 +02:00
uri,
2020-04-16 23:43:09 +02:00
muted,
volume,
2020-04-14 01:48:11 +02:00
autoplaySetting,
autoplayIfEmbedded,
doAnalyticsView,
2020-08-07 22:59:20 +02:00
doAnalyticsBuffer,
2020-04-14 01:48:11 +02:00
claimRewards,
savePosition,
clearPosition,
desktopPlayStartTime,
2021-01-08 16:21:27 +01:00
toggleVideoTheaterMode,
2021-08-25 15:33:27 +02:00
toggleAutoplayNext,
setVideoPlaybackRate,
2021-08-25 14:08:30 +02:00
doSetPlayingUri,
doPlayUri,
playNextUri,
2021-08-25 13:25:55 +02:00
playPreviousUri,
2021-04-12 18:43:47 +02:00
homepageData,
authenticated,
userId,
shareTelemetry,
videoTheaterMode,
2021-08-25 14:08:30 +02:00
collectionId,
isFloating,
} = props;
2021-07-17 00:20:22 +02:00
const adApprovedChannelIds = homepageData ? getAllIds(homepageData) : [];
2020-01-22 18:19:49 +01:00
const claimId = claim && claim.claim_id;
2021-04-12 18:43:47 +02:00
const channelClaimId = claim && claim.signing_channel && claim.signing_channel.claim_id;
const isAudio = contentType.includes('audio');
2020-03-27 17:49:41 +01:00
const forcePlayer = FORCE_CONTENT_TYPE_PLAYER.includes(contentType);
2021-04-12 18:43:47 +02:00
const {
location: { pathname },
2021-08-25 14:08:30 +02:00
push,
2021-04-12 18:43:47 +02:00
} = useHistory();
2020-04-14 01:48:11 +02:00
const [isPlaying, setIsPlaying] = useState(false);
2021-08-25 15:33:27 +02:00
const [ended, setEnded] = useState(false);
2020-04-14 01:48:11 +02:00
const [showAutoplayCountdown, setShowAutoplayCountdown] = useState(false);
const [isEndededEmbed, setIsEndededEmbed] = useState(false);
const vjsCallbackDataRef: any = React.useRef();
2021-04-12 18:43:47 +02:00
const previousUri = usePrevious(uri);
const embedded = useContext(EmbedContext);
const approvedVideo = Boolean(channelClaimId) && adApprovedChannelIds.includes(channelClaimId);
const adsEnabled = ENABLE_PREROLL_ADS && !authenticated && !embedded && approvedVideo;
const [adUrl, setAdUrl, isFetchingAd] = useGetAds(approvedVideo, adsEnabled);
2020-04-26 22:32:39 +02:00
/* isLoading was designed to show loading screen on first play press, rather than completely black screen, but
breaks because some browsers (e.g. Firefox) block autoplay but leave the player.play Promise pending */
2020-04-16 23:43:09 +02:00
const [isLoading, setIsLoading] = useState(false);
2021-08-20 12:28:38 +02:00
const [replay, setReplay] = useState(false);
2021-08-25 14:08:30 +02:00
const [startPlayNext, setStartPlayNext] = useState(false);
2021-08-25 13:25:55 +02:00
const [startPlayPrevious, setStartPlayPrevious] = useState(false);
const [videoNode, setVideoNode] = useState(false);
2021-08-25 15:33:27 +02:00
const getNavigateUrl = React.useCallback(
(playUri: string) => {
let navigateUrl;
if (playUri) {
navigateUrl = formatLbryUrlForWeb(playUri);
if (collectionId) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
navigateUrl = navigateUrl + `?` + collectionParams.toString();
}
2021-08-25 13:25:55 +02:00
}
2021-08-25 15:33:27 +02:00
return navigateUrl;
},
[collectionId]
);
2020-04-16 23:43:09 +02:00
// force everything to recent when URI changes, can cause weird corner cases otherwise (e.g. navigate while autoplay is true)
useEffect(() => {
if (uri && previousUri && uri !== previousUri) {
setShowAutoplayCountdown(false);
setIsEndededEmbed(false);
setIsLoading(false);
}
}, [uri, previousUri]);
// Update vjsCallbackDataRef (ensures videojs callbacks are not using stale values):
useEffect(() => {
vjsCallbackDataRef.current = {
embedded: embedded,
videoPlaybackRate: videoPlaybackRate,
};
}, [embedded, videoPlaybackRate]);
2021-08-25 14:08:30 +02:00
useEffect(() => {
if (startPlayNext) {
2021-08-25 13:25:55 +02:00
const navigateUrl = getNavigateUrl(playNextUri);
2021-08-25 14:08:30 +02:00
if (!isFloating && navigateUrl) {
push(navigateUrl);
}
if (playNextUri) {
doSetPlayingUri(playNextUri, collectionId);
doPlayUri(playNextUri);
}
setStartPlayNext(false);
}
2021-08-25 13:25:55 +02:00
if (videoNode) {
const currentTime = videoNode.currentTime;
if (startPlayPrevious) {
if (currentTime > 5) {
videoNode.currentTime = 0;
} else {
const navigateUrl = getNavigateUrl(playPreviousUri);
if (!isFloating && navigateUrl) {
push(navigateUrl);
}
if (playPreviousUri) {
doSetPlayingUri(playPreviousUri, collectionId);
doPlayUri(playPreviousUri);
}
}
setStartPlayPrevious(false);
}
}
2021-08-25 15:33:27 +02:00
}, [
isFloating,
push,
doSetPlayingUri,
playNextUri,
doPlayUri,
startPlayNext,
collectionId,
getNavigateUrl,
videoNode,
startPlayPrevious,
playPreviousUri,
]);
2021-08-25 14:08:30 +02:00
2020-04-16 01:21:17 +02:00
function doTrackingBuffered(e: Event, data: any) {
fetch(source, { method: 'HEAD', cache: 'no-store' }).then((response) => {
data.playerPoweredBy = response.headers.get('x-powered-by');
doAnalyticsBuffer(uri, data);
});
2020-04-16 01:21:17 +02:00
}
2019-08-13 07:35:13 +02:00
2020-04-16 01:21:17 +02:00
function doTrackingFirstPlay(e: Event, data: any) {
let timeToStart = data.secondsToLoad;
if (desktopPlayStartTime !== undefined) {
const differenceToAdd = Date.now() - desktopPlayStartTime;
timeToStart += differenceToAdd;
}
2020-11-26 22:06:58 +01:00
analytics.playerStartedEvent(embedded);
fetch(source, { method: 'HEAD', cache: 'no-store' }).then((response) => {
let playerPoweredBy = response.headers.get('x-powered-by') || '';
analytics.videoStartEvent(claimId, timeToStart, playerPoweredBy, userId, claim.canonical_url, this);
});
doAnalyticsView(uri, timeToStart).then(() => {
2020-04-16 01:21:17 +02:00
claimRewards();
});
}
2020-04-14 01:48:11 +02:00
2021-08-25 15:33:27 +02:00
React.useEffect(() => {
if (ended) {
analytics.videoIsPlaying(false);
2021-08-25 15:33:27 +02:00
if (adUrl) {
setAdUrl(null);
return;
}
2021-04-12 18:43:47 +02:00
2021-08-25 15:33:27 +02:00
if (embedded) {
setIsEndededEmbed(true);
} else if (autoplaySetting) {
setShowAutoplayCountdown(true);
}
2021-08-25 15:33:27 +02:00
clearPosition(uri);
}
}, [
embedded,
setIsEndededEmbed,
autoplaySetting,
setShowAutoplayCountdown,
adUrl,
setAdUrl,
clearPosition,
uri,
ended,
]);
function onPlay(player) {
2020-04-16 23:43:09 +02:00
setIsLoading(false);
2020-04-16 01:21:17 +02:00
setIsPlaying(true);
setShowAutoplayCountdown(false);
setIsEndededEmbed(false);
2021-08-20 12:28:38 +02:00
setReplay(false);
analytics.videoIsPlaying(true, player);
2020-04-16 01:21:17 +02:00
}
function onPause(event, player) {
setIsPlaying(false);
handlePosition(player);
analytics.videoIsPlaying(false, player);
}
function onDispose(event, player) {
handlePosition(player);
analytics.videoIsPlaying(false, player);
}
function handlePosition(player) {
savePosition(uri, player.currentTime());
}
function restorePlaybackRate(player) {
if (!vjsCallbackDataRef.current.embedded) {
player.playbackRate(vjsCallbackDataRef.current.videoPlaybackRate);
}
}
2021-04-12 18:43:47 +02:00
const playerReadyDependencyList = [uri, adUrl, embedded, autoplayIfEmbedded];
if (!IS_WEB) {
playerReadyDependencyList.push(desktopPlayStartTime);
}
2021-08-25 13:25:55 +02:00
const onPlayerReady = useCallback((player: Player, videoNode: any) => {
2021-04-12 18:43:47 +02:00
if (!embedded) {
2021-08-25 13:25:55 +02:00
setVideoNode(videoNode);
2021-04-12 18:43:47 +02:00
player.muted(muted);
player.volume(volume);
player.playbackRate(videoPlaybackRate);
addTheaterModeButton(player, toggleVideoTheaterMode);
2021-08-25 13:25:55 +02:00
if (collectionId) {
addPlayNextButton(player, () => setStartPlayNext(true));
addPlayPreviousButton(player, () => setStartPlayPrevious(true));
2021-08-25 15:33:27 +02:00
} else {
addAutoplayNextButton(player, toggleAutoplayNext, autoplaySetting);
2021-08-25 13:25:55 +02:00
}
2021-04-12 18:43:47 +02:00
}
2020-04-27 21:23:07 +02:00
2021-04-12 18:43:47 +02:00
const shouldPlay = !embedded || autoplayIfEmbedded;
// https://blog.videojs.com/autoplay-best-practices-with-video-js/#Programmatic-Autoplay-and-Success-Failure-Detection
if (shouldPlay) {
const playPromise = player.play();
const timeoutPromise = new Promise((resolve, reject) =>
setTimeout(() => reject(PLAY_TIMEOUT_ERROR), PLAY_TIMEOUT_LIMIT)
);
2020-04-28 19:25:13 +02:00
2021-04-12 18:43:47 +02:00
Promise.race([playPromise, timeoutPromise]).catch((error) => {
if (typeof error === 'object' && error.name && error.name === 'NotAllowedError') {
if (player.autoplay() && !player.muted()) {
// player.muted(true);
// another version had player.play()
}
}
setIsLoading(false);
setIsPlaying(false);
});
2021-04-12 18:43:47 +02:00
}
2021-04-12 18:43:47 +02:00
setIsLoading(shouldPlay); // if we are here outside of an embed, we're playing
// PR: #5535
// Move the restoration to a later `loadedmetadata` phase to counter the
// delay from the header-fetch. This is a temp change until the next
// re-factoring.
player.on('loadedmetadata', () => restorePlaybackRate(player));
// used for tracking buffering for watchman
2021-04-12 18:43:47 +02:00
player.on('tracking:buffered', doTrackingBuffered);
// first play tracking, used for initializing the watchman api
2021-04-12 18:43:47 +02:00
player.on('tracking:firstplay', doTrackingFirstPlay);
2021-08-25 15:33:27 +02:00
player.on('ended', () => setEnded(true));
player.on('play', onPlay);
player.on('pause', (event) => onPause(event, player));
player.on('dispose', (event) => onDispose(event, player));
2021-04-12 18:43:47 +02:00
player.on('error', () => {
const error = player.error();
if (error) {
analytics.sentryError('Video.js error', error);
2020-04-16 23:43:09 +02:00
}
2021-04-12 18:43:47 +02:00
});
player.on('volumechange', () => {
if (player) {
changeVolume(player.volume());
changeMute(player.muted());
}
});
player.on('ratechange', () => {
const HAVE_NOTHING = 0; // https://docs.videojs.com/player#readyState
if (player && player.readyState() !== HAVE_NOTHING) {
// The playbackRate occasionally resets to 1, typically when loading a fresh video or when 'src' changes.
// Videojs says it's a browser quirk (https://github.com/videojs/video.js/issues/2516).
// [x] Don't update 'videoPlaybackRate' in this scenario.
// [ ] Ideally, the controlBar should be hidden to prevent users from changing the rate while loading.
setVideoPlaybackRate(player.playbackRate());
}
});
if (position) {
player.currentTime(position);
}
}, playerReadyDependencyList); // eslint-disable-line
2020-03-19 21:25:37 +01:00
2019-08-02 08:28:14 +02:00
return (
2020-04-14 01:48:11 +02:00
<div
className={classnames('file-viewer', {
'file-viewer--is-playing': isPlaying,
2020-04-16 23:43:09 +02:00
'file-viewer--ended-embed': isEndededEmbed,
2020-04-14 01:48:11 +02:00
})}
onContextMenu={stopContextMenu}
>
2021-08-20 12:28:38 +02:00
{showAutoplayCountdown && <AutoplayCountdown uri={uri} setReplay={setReplay} />}
2020-04-14 01:48:11 +02:00
{isEndededEmbed && <FileViewerEmbeddedEnded uri={uri} />}
{embedded && !isEndededEmbed && <FileViewerEmbeddedTitle uri={uri} />}
2020-04-26 22:32:39 +02:00
{/* disable this loading behavior because it breaks when player.play() promise hangs */}
2020-04-28 19:25:13 +02:00
{isLoading && <LoadingScreen status={__('Loading')} />}
2021-04-12 18:43:47 +02:00
{!isFetchingAd && adUrl && (
<>
<span className="ads__video-notify">
{__('Advertisement')}{' '}
<Button
className="ads__video-close"
icon={ICONS.REMOVE}
title={__('Close')}
onClick={() => setAdUrl(null)}
/>
</span>
<span className="ads__video-nudge">
<I18nMessage
tokens={{
sign_up: (
<Button
button="secondary"
className="ads__video-link"
label={__('Sign Up')}
navigate={`/$/${PAGES.AUTH}?redirect=${pathname}&src=video-ad`}
/>
),
}}
>
%sign_up% to turn ads off.
</I18nMessage>
</span>
</>
)}
{!isFetchingAd && (
<VideoJs
adUrl={adUrl}
source={adUrl || source}
sourceType={forcePlayer || adUrl ? 'video/mp4' : contentType}
isAudio={isAudio}
poster={isAudio || (embedded && !autoplayIfEmbedded) ? thumbnail : ''}
onPlayerReady={onPlayerReady}
startMuted={autoplayIfEmbedded}
toggleVideoTheaterMode={toggleVideoTheaterMode}
autoplay={!embedded || autoplayIfEmbedded}
2021-08-25 15:33:27 +02:00
autoplaySetting={autoplaySetting}
claimId={claimId}
userId={userId}
allowPreRoll={!embedded && !authenticated}
shareTelemetry={shareTelemetry}
2021-08-20 12:28:38 +02:00
replay={replay}
videoTheaterMode={videoTheaterMode}
2021-08-25 14:08:30 +02:00
setStartPlayNext={setStartPlayNext}
2021-08-25 13:25:55 +02:00
setStartPlayPrevious={setStartPlayPrevious}
/>
2021-04-12 18:43:47 +02:00
)}
2019-08-02 08:28:14 +02:00
</div>
);
}
export default VideoViewer;