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

412 lines
12 KiB
React
Raw Normal View History

2019-08-02 08:28:14 +02:00
// @flow
2021-10-22 16:46:59 +02:00
import React, { useEffect, useState, 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';
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';
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';
import { addAutoplayNextButton } from './internal/autoplay-next';
import { addPlayNextButton } from './internal/play-next';
import { addPlayPreviousButton } from './internal/play-previous';
2021-04-12 18:43:47 +02:00
import { useHistory } from 'react-router';
2021-07-17 00:20:22 +02:00
import type { HomepageCat } from 'util/buildHomepage';
import { formatLbryUrlForWeb, generateListSearchUrlParams } from 'util/url';
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,
autoplayNext: 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,
toggleAutoplayNext: () => void,
setVideoPlaybackRate: (number) => void,
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,
isFloating: boolean,
doPlayUri: (string, string) => void,
collectionId: string,
nextRecommendedUri: string,
previousListUri: string,
videoTheaterMode: boolean,
isMarkdownOrComment: 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,
autoplayNext,
2020-04-14 01:48:11 +02:00
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,
toggleAutoplayNext,
setVideoPlaybackRate,
userId,
shareTelemetry,
isFloating,
doPlayUri,
collectionId,
nextRecommendedUri,
previousListUri,
videoTheaterMode,
isMarkdownOrComment,
} = props;
const permanentUrl = claim && claim.permanent_url;
2020-01-22 18:19:49 +01:00
const claimId = claim && claim.claim_id;
const isAudio = contentType.includes('audio');
2020-03-27 17:49:41 +01:00
const forcePlayer = FORCE_CONTENT_TYPE_PLAYER.includes(contentType);
2021-10-22 16:46:59 +02:00
const { push } = useHistory();
const [doNavigate, setDoNavigate] = useState(false);
const [playNextUrl, setPlayNextUrl] = useState(true);
2020-04-14 01:48:11 +02:00
const [isPlaying, setIsPlaying] = useState(false);
const [ended, setEnded] = useState(false);
2020-04-14 01:48:11 +02:00
const [showAutoplayCountdown, setShowAutoplayCountdown] = useState(false);
const vjsCallbackDataRef: any = React.useRef();
2021-04-12 18:43:47 +02:00
const previousUri = usePrevious(uri);
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);
const [replay, setReplay] = useState(false);
const [videoNode, setVideoNode] = useState();
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);
setIsLoading(false);
}
}, [uri, previousUri]);
// Update vjsCallbackDataRef (ensures videojs callbacks are not using stale values):
useEffect(() => {
vjsCallbackDataRef.current = {
videoPlaybackRate: videoPlaybackRate,
};
2021-10-22 16:46:59 +02:00
}, [videoPlaybackRate]);
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;
}
2021-10-22 16:46:59 +02:00
analytics.playerStartedEvent();
// convert bytes to bits, and then divide by seconds
const contentInBits = Number(claim.value.source.size) * 8;
const durationInSeconds = claim.value.video && claim.value.video.duration;
let bitrateAsBitsPerSecond;
if (durationInSeconds) {
bitrateAsBitsPerSecond = Math.round(contentInBits / durationInSeconds);
}
Implement Download Progress Implement Download Progress Revert "Stream Key Button (#7127)" I forgot to lint before merging. Reverting for now, will fix in a bit. This reverts commit 5c8878353f10696e4e20dd86ca32a63eee048764. Restore "Stream Key Button (#7127)" + lint and modifications - Consolidate functionality into existing component. - Use proper strings. Localize sunset nag Changed the text a bit so that we can re-use the existing 'Learn more'. Don't allow assigning yourself as moderator Also fixed split-string (hard to localize). Comment: Swap the order of "Edit" and "Remove" This order is more common. Blocklist page: fix perpetual spinner when trying to refresh with no channels There's nothing to do when you don't have a channel, so hide the button and ensure redux fails gracefully. i18n Livestream category improvements (#7115) * ❌ Remove old method of displaying active livestreams Completely remove it for now to make the commit deltas clearer. We'll replace it with the new method at the end. * Fetch and store active-livestream info in redux * Tiles can now query active-livestream state from redux instead of getting from parent. * ⏪ ClaimTilesDiscover: revert and cleanup - Simplify to just `uris` instead of having multiple arrays (`uris`, `modifiedUris`, `prevUris`) - The `prevUris` is for CLS prevention. With this removal, the CLS issue is back, but we'll handle it differently later. - Temporarily disable the view-count fetching. Code is left there so that I don't forget. - `shouldPerformSearch` was never true when `prefixUris` is present. Corrected the logic. - Aside: prefix and pin is so similar in function. Hm .... * ClaimTilesDiscover: factor out options Move the `option` code outside and passed in as a pre-calculated prop. To skip rendering while waiting for `claim_search`, we need to add `React.memo(areEqual)`. However, the flag that determines if we are fetching `claim_search` (fetchingClaimSearchByQuery[]) depends on the derived options as the key. Instead of calculating `options` twice, we moved it to the props so both sides can use it. It also makes the component a bit more readable. The downside is that the prop-passing might not be clear. * ClaimTilesDiscover: reduce ~17 renders at startup to just 2. * ClaimTilesDiscover: fill with placeholder while waiting for claim_search Livestream claims are fetched seperately, so they might already exists. While claim_search is running, the list only consists of livestreams (collapsed). Fill up the space with placeholders to prevent layout shift. * Add 'useFetchViewCount' to handle fetching from lists This effect also stashes fetched uris, so that we won't re-fetch the same uris during the same instance (e.g. during infinite scroll). * ⏪ ClaimListDiscover: revert and cleanup - Removed the 'finalUris' stuff that was meant to "pause" visual changes when fetching. I think it'll be cleaner to use React.memo to achieve that. - Added `renderUri` to make it clear which array that this component will render. - Re-do the way we fetch view counts now that 'finalUris' is gone. Not the best method, but at least correct for now. * ClaimListDiscover: add prefixUris, similar to ClaimTilesDiscover This will be initially used to append livestreams at the top. * ✅ Re-enable active livestream tiles using the new method * doFetchActiveLivestreams: add interval check - Added a default minimum of 5 minutes between fetches. Clients can bypass this through `forceFetch` if needed. * doFetchActiveLivestreams: add option check We'll need to support different 'orderBy', so adding an "options check" when determining if we just made the same fetch. * WildWest: limit livestream tiles + add ability to show more Most likely this behavior will change in the future, so we'll leave `ClaimListDiscover` untouched and handle the logic at the page level. This solution uses 2 `ClaimListDiscover` -- if the reduced livestream list is visible, it handles the header; else the normal list handles the header. * Use better tile-count on larger screens. Used the same method as how the homepage does it. Fix video embeds in comments not playing and resize issues (#7163) -- tmp revert -- This reverts commit 3b47edc3b9744418d8ea78bd30dcd2671633aebb to allow putting back in the original commits. ❌ Remove old method of displaying active livestreams Completely remove it for now to make the commit deltas clearer. We'll replace it with the new method at the end. Fetch and store active-livestream info in redux Tiles can now query active-livestream state from redux instead of getting from parent. ⏪ ClaimTilesDiscover: revert and cleanup - Simplify to just `uris` instead of having multiple arrays (`uris`, `modifiedUris`, `prevUris`) - The `prevUris` is for CLS prevention. With this removal, the CLS issue is back, but we'll handle it differently later. - Temporarily disable the view-count fetching. Code is left there so that I don't forget. - `shouldPerformSearch` was never true when `prefixUris` is present. Corrected the logic. - Aside: prefix and pin is so similar in function. Hm .... ClaimTilesDiscover: factor out options Move the `option` code outside and passed in as a pre-calculated prop. To skip rendering while waiting for `claim_search`, we need to add `React.memo(areEqual)`. However, the flag that determines if we are fetching `claim_search` (fetchingClaimSearchByQuery[]) depends on the derived options as the key. Instead of calculating `options` twice, we moved it to the props so both sides can use it. It also makes the component a bit more readable. The downside is that the prop-passing might not be clear. ClaimTilesDiscover: reduce ~17 renders at startup to just 2. ClaimTilesDiscover: fill with placeholder while waiting for claim_search Livestream claims are fetched seperately, so they might already exists. While claim_search is running, the list only consists of livestreams (collapsed). Fill up the space with placeholders to prevent layout shift. Add 'useFetchViewCount' to handle fetching from lists This effect also stashes fetched uris, so that we won't re-fetch the same uris during the same instance (e.g. during infinite scroll). ⏪ ClaimListDiscover: revert and cleanup - Removed the 'finalUris' stuff that was meant to "pause" visual changes when fetching. I think it'll be cleaner to use React.memo to achieve that. - Added `renderUri` to make it clear which array that this component will render. - Re-do the way we fetch view counts now that 'finalUris' is gone. Not the best method, but at least correct for now. ClaimListDiscover: add prefixUris, similar to ClaimTilesDiscover This will be initially used to append livestreams at the top. ✅ Re-enable active livestream tiles using the new method doFetchActiveLivestreams: add interval and options checking - Added a default minimum of 5 minutes between fetches. Clients can bypass this through `forceFetch` if needed. - We'll need to support different 'orderBy', so adding an "options check" when determining if we just made the same fetch. WildWest: limit livestream tiles + add ability to show more Most likely this behavior will change in the future, so we'll leave `ClaimListDiscover` untouched and handle the logic at the page level. This solution uses 2 `ClaimListDiscover` -- if the reduced livestream list is visible, it handles the header; else the normal list handles the header. Fix homepage tiles not filtering blocked channels 7165 homepage queries don't take into account blocked channel ids (mute does) resolveSearchOptions: was not grabbing redux data correctly. Adjust comment fade-out height 6944 Comment expansion sometimes doesn't reveal extra text (already showing everything) Reconcile some constants between JS and CSS. force mp3 extension vs mpga Fix autoplay next default value (#7173) Fix missed render when blocklist is fetched 7176 Pitfalls of pausing render via React.memo: - We'll miss the `doClaimSearch()` since that is sparked by an `useEffect`. Seems like we can't avoid having a redundant copy of the previously-displayed URIs. Memoize 'mutedAndBlockedChannelIds' It was being recalculated repeatedly. This memoizes it, although it still re-calculates occasionally despite none of the source arrays changed. I think it is due to the state change in the Preference Sync. Note: input selectors to `createSelector` needs to be extractions-only (i.e. must not have transformations). I think most of our `makeSelect*` selectors violate this and broke memoization. Fix “Your Account” popup on mobile (#5652) (#7172) * Fix “Your Account” popup on mobile (#5652) * Update changelog Co-authored-by: Branko Tomic <branko@spicefactory.co> Fix issue where channel upload viewcounts were creating a new line (#7154) * fix issue where viewcounts were creating a new line * conditionally add large view css * conditionally apply class based on if view count should be shown * last couple touchups * clean up the css * add scss to flow config * add scss component to flow config use homepage LATEST for following discover (#7185) Commentron now includes `replies` for `ByID` request Wasn't aware of that, and that was causing 7146 ("show replies" visible when there are no replies). Fix page titles for SiteLinks Part of `7166 improve search metadata`, where page titles are important clues for Google to generate Site-Links. Add icons (#7194) fix playlist resolving collectionurls (#7178) * fix playlist resolving collectionurls * Update CHANGELOG.md Co-authored-by: Thomas Zarebczan <tzarebczan@users.noreply.github.com> Fix plant icon (#7195) * Fix plant icon * Also change phone icon name Add Channel Mention selection ability (#7151) * Add Channel Mention selection ability * Fix mentioned user name being smaller than other text * Improve logic for locating a mention * Fix mentioning with enter on livestream * Fix breaking for invalid URI query * Handle punctuation after mention * Fix name display and appeareance * Use canonical url * Fix missing search i18n - ChannelMention and other fixes Fix wrong 'recsysId' sent due to search-key mismatch .../archives/C02FQBM00Q0/p1633044695010600 When querying a search key, it has to be an exact match. This was broken by the insertion of `free_only` in the fetch. Added a function to generate the options, so that all clients stay in sync. Fix linked-comment scrolling I think this the best solution so far, at the expense of a slight delay in scrolling if the network call stalls. - Added "fetching by ID" state so that we don't need to use the ugly N-retries method. - `scrollIntoView` doesn't work if the element is already in the viewport, and the `scrollBy` adjustment doesn't take into account the y-position restoration that we perform on certain type of pages. Use `window.scrollTo` instead and taking into account current scroll position. Prevent random description in Google Search results for "odysee" (#7206) 7166 improve search metadata Depending on the search term and timing, Google extracts data from the sidebar or page content to use as the search-result description. Defined `description` (on top of the existing `og:description` and `twitter:description`. While I couldn't find a definitive doc saying that this is the solution, this is present in all other sites (and matches their description in a Google Search results). Add favicon for Google Search results (#7205) - A side-quest from "7166 improve search metadata". - The favicon must be from the same domain as the homepage, so the CDN URL couldn't be used, hence the additional upload. - The favicon also needs to be multiples of 48x48 and above. - Wanted to use SVG for the smallest size possible, but seems like Safari does not fully support it. Got Dejan to give me a reasonably-sized PNG. https://developers.google.com/search/docs/advanced/appearance/favicon-in-search#guidelines List own comments (#7171) * Add option to pass in url-search params. Impetus: allow linked comment ID and setting the discussion tab when clicking on the `ClaimPreview`. * comment.list: fix typos and renamed variables - Switch from 'author' to 'creator' to disambiguate between comment author and content author. For comment author, we'll use 'commenter' from now on. - Corrected 'commenterClaimId' to 'creatorClaimId' (just a typo, no functional change). * doCommentReset: change param from uri to claimId This reduces one lookup as clients will always have the claimID ready, but might not have the full URI. It was using URI previously just to match the other APIs. * Add doCommentListOwn -- command to fetch own comments Since the redux slice is set up based on content or channel ID (for Channel Discussion page), re-use the channel ID for the case of "own comments". We always clear each ID when fetching page-0, so no worries of conflict when actually browsing the Channel Discussion page. * Comment: add option to hide the actions section * Implement own-comments page * Use new param to remove sort-pins-first. comment.List currently always pushes pins to the top to support pagination. This new param removes this behavior. Fix resolving invalid claims (#7210) Update icons.js --- tmp revert --- This reverts commit de6c6f9bfd0383e9087a38f1f54e13bb54754945. Add option to pass in url-search params. Impetus: allow linked comment ID and setting the discussion tab when clicking on the `ClaimPreview`. comment.list: fix typos and renamed variables - Switch from 'author' to 'creator' to disambiguate between comment author and content author. For comment author, we'll use 'commenter' from now on. - Corrected 'commenterClaimId' to 'creatorClaimId' (just a typo, no functional change). doCommentReset: change param from uri to claimId This reduces one lookup as clients will always have the claimID ready, but might not have the full URI. It was using URI previously just to match the other APIs. Add doCommentListOwn -- command to fetch own comments Since the redux slice is set up based on content or channel ID (for Channel Discussion page), re-use the channel ID for the case of "own comments". We always clear each ID when fetching page-0, so no worries of conflict when actually browsing the Channel Discussion page. Comment: add option to hide the actions section Implement own-comments page Use new param to remove sort-pins-first. comment.List currently always pushes pins to the top to support pagination. This new param removes this behavior. Corrected meta for "description" (patch for #7206) It should be `name`, not `property`. Copy-paste error from the OG version. Fix 'pinnedUrl' error. Part of "6989 Fix console spam in dev" EXTRA_SIDEBAR_LINKS should be a `SideNavLink` object, so trim down the return object from `GetLinksData`. Temp workaround SDK 0 count Temp workaround claims in channel count 0 patch creator analytics with hub without channel claim count patch hubs claims_in_channel temporarily OG: fix url for categories Category cards are showing up as "odysee.com" cards in Facebook. - `og:url` is supposed to be the canonical URL. It was hardcoded to "odysee.com", so every category was being redirected when the card is being generated. - Removed `twitter:url`. The documentation says it will fall back to `og:url`, so there is not need to define both if it's the same. OG: Technology category missing due to rename - 'technology' was renamed to 'tech'. - Leave both entries there for now. Not sure if other homepages still use the old link or not. Fix spacing / centering live stream + comments section (#7225) Add copy comment link menu option (#7224) adjust css for toast message so that it behaves as expected (text truncation via ellipsis) (#7213) Refactor commentsList Remove expand/collapse from channel discussion page Prevent comment content from breaking the layout on mobile ESLint fix Update Dark theme and fix playing issue Fix playlist strings Add sitemap to influence Sitelinks Part of `7166 improve search metadata` This is an experiment to influence the Sitelinks in our search results. Our current sitemap only consists of claims, so claims appear in Sitelinks more often. We (Julian) want categories to have higher priority, if possible. For now, the sitemap will be defined in Google Console instead of robots.txt. If it works, the file should be uploaded to sitemap.odysee.com, alongside the claim list sitemap. Revert "Add sitemap to influence Sitelinks" Seems like I messed up robots.txt? This reverts commit 95654955b1ef5c6ba55ada50f2419949c56cf10a. Bump url-parse from 1.5.1 to 1.5.3 (#7230) Bumps [url-parse](https://github.com/unshiftio/url-parse) from 1.5.1 to 1.5.3. - [Release notes](https://github.com/unshiftio/url-parse/releases) - [Commits](https://github.com/unshiftio/url-parse/compare/1.5.1...1.5.3) --- updated-dependencies: - dependency-name: url-parse dependency-type: indirect ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> fix notifications page on unauthed app (#7226) move file actions from lbry-redux Send video bitrate and user bandwidth to Watchman (#7145) * adding functionality to detect user download speed * calculating bandwidth speed more intelligently * saving download speed and updating it every 30s * all the functionality should be done needs testing * fix linting * use a 1mb file for calculating bandwidth * add optional chaining plugin to babel and get bitrate from texttrack * allow optional chaining for flow * ignore flow error * disable bandwidth checking functionality * fix flow error Fix ESLint Update Download Progress Update CSS
2021-10-01 22:00:57 +02:00
// convert bytes to bits, and then divide by seconds
const contentInBits = Number(claim.value.source.size) * 8;
const durationInSeconds = claim.value.video && claim.value.video.duration;
let bitrateAsBitsPerSecond;
if (durationInSeconds) {
bitrateAsBitsPerSecond = Math.round(contentInBits / durationInSeconds);
}
fetch(source, { method: 'HEAD', cache: 'no-store' }).then((response) => {
let playerPoweredBy = response.headers.get('x-powered-by') || '';
2021-10-22 16:46:59 +02:00
analytics.videoStartEvent(
claimId,
timeToStart,
playerPoweredBy,
userId,
claim.canonical_url,
this,
bitrateAsBitsPerSecond
);
});
doAnalyticsView(uri, timeToStart).then(() => {
2020-04-16 01:21:17 +02:00
claimRewards();
});
}
2020-04-14 01:48:11 +02:00
const doPlay = useCallback(
(playUri) => {
setDoNavigate(false);
if (!isFloating) {
const navigateUrl = formatLbryUrlForWeb(playUri);
push({
pathname: navigateUrl,
search: collectionId && generateListSearchUrlParams(collectionId),
state: { collectionId, forceAutoplay: true, hideFloatingPlayer: true },
});
} else {
doPlayUri(playUri, collectionId);
}
},
[collectionId, doPlayUri, isFloating, push]
);
useEffect(() => {
if (!doNavigate) return;
if (playNextUrl) {
if (permanentUrl !== nextRecommendedUri) {
if (nextRecommendedUri) {
if (collectionId) clearPosition(permanentUrl);
doPlay(nextRecommendedUri);
}
} else {
setReplay(true);
}
} else {
if (videoNode) {
const currentTime = videoNode.currentTime;
if (currentTime <= 5) {
if (previousListUri && permanentUrl !== previousListUri) doPlay(previousListUri);
} else {
videoNode.currentTime = 0;
}
setDoNavigate(false);
}
2021-04-12 18:43:47 +02:00
}
if (!ended) setDoNavigate(false);
setEnded(false);
setPlayNextUrl(true);
}, [
clearPosition,
collectionId,
doNavigate,
doPlay,
ended,
nextRecommendedUri,
permanentUrl,
playNextUrl,
previousListUri,
videoNode,
]);
2021-04-12 18:43:47 +02:00
React.useEffect(() => {
if (!ended) return;
analytics.videoIsPlaying(false);
2021-10-22 16:46:59 +02:00
if (!collectionId && autoplayNext) {
setShowAutoplayCountdown(true);
} else if (collectionId) {
setDoNavigate(true);
}
clearPosition(uri);
2021-10-22 16:46:59 +02:00
}, [autoplayNext, clearPosition, collectionId, ended, uri]);
function onPlay(player) {
setEnded(false);
2020-04-16 23:43:09 +02:00
setIsLoading(false);
2020-04-16 01:21:17 +02:00
setIsPlaying(true);
setShowAutoplayCountdown(false);
setReplay(false);
setDoNavigate(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-10-22 16:46:59 +02:00
const playerReadyDependencyList = [uri];
2021-04-12 18:43:47 +02:00
if (!IS_WEB) {
playerReadyDependencyList.push(desktopPlayStartTime);
}
const doPlayNext = () => {
setPlayNextUrl(true);
setEnded(true);
};
const doPlayPrevious = () => {
setPlayNextUrl(false);
setEnded(true);
};
const onPlayerReady = useCallback((player: Player, videoNode: any) => {
2021-10-22 16:46:59 +02:00
setVideoNode(videoNode);
player.muted(muted);
player.volume(volume);
player.playbackRate(videoPlaybackRate);
if (!isMarkdownOrComment) {
addTheaterModeButton(player, toggleVideoTheaterMode);
if (collectionId) {
addPlayNextButton(player, doPlayNext);
addPlayPreviousButton(player, doPlayPrevious);
} else {
addAutoplayNextButton(player, toggleAutoplayNext, autoplayNext);
}
2021-04-12 18:43:47 +02:00
}
2020-04-27 21:23:07 +02:00
2021-04-12 18:43:47 +02:00
// https://blog.videojs.com/autoplay-best-practices-with-video-js/#Programmatic-Autoplay-and-Success-Failure-Detection
2021-10-22 16:46:59 +02:00
const playPromise = player.play();
const timeoutPromise = new Promise((resolve, reject) =>
setTimeout(() => reject(PLAY_TIMEOUT_ERROR), PLAY_TIMEOUT_LIMIT)
);
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()
}
2021-10-22 16:46:59 +02:00
}
setIsLoading(false);
setIsPlaying(false);
});
2021-10-22 16:46:59 +02:00
setIsLoading(true); // if we are here outside of an embed, we're playing
2021-04-12 18:43:47 +02:00
// 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);
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,
})}
onContextMenu={stopContextMenu}
>
{showAutoplayCountdown && (
<AutoplayCountdown
nextRecommendedUri={nextRecommendedUri}
doNavigate={() => setDoNavigate(true)}
doReplay={() => setReplay(true)}
/>
)}
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-10-22 16:46:59 +02:00
<VideoJs
source={source}
sourceType={forcePlayer ? 'video/mp4' : contentType}
isAudio={isAudio}
poster={isAudio ? thumbnail : ''}
onPlayerReady={onPlayerReady}
toggleVideoTheaterMode={toggleVideoTheaterMode}
autoplay
autoplaySetting={autoplayNext}
claimId={claimId}
userId={userId}
shareTelemetry={shareTelemetry}
replay={replay}
videoTheaterMode={videoTheaterMode}
playNext={doPlayNext}
playPrevious={doPlayPrevious}
/>
2019-08-02 08:28:14 +02:00
</div>
);
}
export default VideoViewer;