lbry-desktop/ui/component/app/view.jsx

316 lines
10 KiB
React
Raw Normal View History

2018-03-26 14:32:43 -07:00
// @flow
2019-10-22 13:57:32 -04:00
import * as PAGES from 'constants/pages';
2019-10-15 00:20:12 -04:00
import React, { useEffect, useRef, useState } from 'react';
2019-10-09 12:34:18 -04:00
import classnames from 'classnames';
2019-07-21 22:28:49 -04:00
import analytics from 'analytics';
import { buildURI, parseURI } from 'lbry-redux';
import Router from 'component/router/index';
import ModalRouter from 'modal/modalRouter';
import ReactModal from 'react-modal';
2019-01-23 10:38:40 -05:00
import { openContextMenu } from 'util/context-menu';
2019-06-11 14:10:58 -04:00
import useKonamiListener from 'util/enhanced-layout';
2019-03-04 23:46:57 -05:00
import Yrbl from 'component/yrbl';
import FileRenderFloating from 'component/fileRenderFloating';
2019-08-13 01:35:13 -04:00
import { withRouter } from 'react-router';
2019-09-27 14:56:15 -04:00
import usePrevious from 'effects/use-previous';
2019-12-06 16:12:48 -05:00
import Nag from 'component/common/nag';
2020-01-14 15:44:07 -05:00
import { rewards as REWARDS } from 'lbryinc';
2020-02-21 15:44:58 -05:00
import usePersistedState from 'effects/use-persisted-state';
2019-12-05 00:24:54 -05:00
// @if TARGET='web'
import OpenInAppLink from 'lbrytv/component/openInAppLink';
import YoutubeWelcome from 'lbrytv/component/youtubeReferralWelcome';
import NagDegradedPerformance from 'lbrytv/component/nag-degraded-performance';
import NagDataCollection from 'lbrytv/component/nag-data-collection';
2019-12-05 00:24:54 -05:00
// @endif
import {
useDegradedPerformance,
STATUS_OK,
STATUS_DEGRADED,
2020-03-26 16:17:41 -04:00
STATUS_FAILING,
STATUS_DOWN,
} from 'lbrytv/effects/use-degraded-performance';
2019-06-27 02:18:45 -04:00
export const MAIN_WRAPPER_CLASS = 'main-wrapper';
// @if TARGET='app'
export const IS_MAC = process.platform === 'darwin';
// @endif
2019-10-15 17:23:51 -04:00
const SYNC_INTERVAL = 1000 * 60 * 5; // 5 minutes
2019-06-27 02:18:45 -04:00
// button numbers pulled from https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
const MOUSE_BACK_BTN = 3;
const MOUSE_FORWARD_BTN = 4;
2018-03-26 14:32:43 -07:00
type Props = {
alertError: (string | {}) => void,
pageTitle: ?string,
2019-06-07 17:10:47 -04:00
language: string,
2019-11-08 15:51:42 -05:00
languages: Array<string>,
2018-10-19 11:27:14 -04:00
theme: string,
user: ?{ id: string, has_verified_email: boolean, is_reward_approved: boolean },
2020-01-14 15:44:07 -05:00
location: { pathname: string, hash: string, search: string },
history: {
goBack: () => void,
goForward: () => void,
index: number,
length: number,
push: string => void,
},
2019-08-06 12:53:59 -04:00
fetchAccessToken: () => void,
fetchChannelListMine: () => void,
2019-10-01 00:53:33 -04:00
signIn: () => void,
requestDownloadUpgrade: () => void,
2019-09-26 12:07:11 -04:00
onSignedIn: () => void,
2019-11-08 15:51:42 -05:00
setLanguage: string => void,
isUpgradeAvailable: boolean,
autoUpdateDownloaded: boolean,
2019-10-15 17:23:51 -04:00
checkSync: () => void,
updatePreferences: () => void,
2019-10-15 17:23:51 -04:00
syncEnabled: boolean,
uploadCount: number,
balance: ?number,
2019-10-22 13:57:32 -04:00
syncError: ?string,
2020-01-14 15:44:07 -05:00
rewards: Array<Reward>,
setReferrer: (string, boolean) => void,
analyticsTagSync: () => void,
isAuthenticated: boolean,
2018-03-26 14:32:43 -07:00
};
2017-04-07 12:15:22 +07:00
2019-06-11 14:10:58 -04:00
function App(props: Props) {
const {
theme,
user,
fetchAccessToken,
2019-09-26 12:07:11 -04:00
fetchChannelListMine,
2019-10-01 00:53:33 -04:00
signIn,
autoUpdateDownloaded,
isUpgradeAvailable,
requestDownloadUpgrade,
2019-10-15 17:23:51 -04:00
syncEnabled,
checkSync,
uploadCount,
2019-10-22 13:57:32 -04:00
history,
syncError,
2019-11-08 15:51:42 -05:00
language,
languages,
setLanguage,
updatePreferences,
2020-01-14 15:44:07 -05:00
rewards,
setReferrer,
analyticsTagSync,
isAuthenticated,
} = props;
2019-06-11 14:10:58 -04:00
const appRef = useRef();
const isEnhancedLayout = useKonamiListener();
2019-10-15 00:20:12 -04:00
const [hasSignedIn, setHasSignedIn] = useState(false);
2019-07-21 22:28:49 -04:00
const userId = user && user.id;
const hasVerifiedEmail = user && user.has_verified_email;
const isRewardApproved = user && user.is_reward_approved;
const previousUserId = usePrevious(userId);
const previousHasVerifiedEmail = usePrevious(hasVerifiedEmail);
const previousRewardApproved = usePrevious(isRewardApproved);
2020-02-21 15:44:58 -05:00
// @if TARGET='web'
const [showAnalyticsNag, setShowAnalyticsNag] = usePersistedState('analytics-nag', true);
// @endif
const [lbryTvApiStatus, setLbryTvApiStatus] = useState(STATUS_OK);
2020-01-14 15:44:07 -05:00
const { pathname, hash, search } = props.location;
const showUpgradeButton = autoUpdateDownloaded || (process.platform === 'linux' && isUpgradeAvailable);
2020-01-14 15:44:07 -05:00
// referral claiming
const referredRewardAvailable = rewards && rewards.some(reward => reward.reward_type === REWARDS.TYPE_REFEREE);
const urlParams = new URLSearchParams(search);
const rawReferrerParam = urlParams.get('r');
const sanitizedReferrerParam = rawReferrerParam && rawReferrerParam.replace(':', '#');
const shouldHideNag = pathname.startsWith(`/$/${PAGES.EMBED}`) || pathname.startsWith(`/$/${PAGES.AUTH_VERIFY}`);
2019-08-13 01:35:13 -04:00
let uri;
try {
2019-08-30 14:12:52 -04:00
const newpath = buildURI(parseURI(pathname.slice(1).replace(/:/g, '#')));
uri = newpath + hash;
2019-08-13 01:35:13 -04:00
} catch (e) {}
2020-02-21 15:44:58 -05:00
// @if TARGET='web'
function handleAnalyticsDismiss() {
setShowAnalyticsNag(false);
}
// @endif
useEffect(() => {
if (!uploadCount) return;
const handleBeforeUnload = event => {
event.preventDefault();
event.returnValue = 'magic'; // without setting this to something it doesn't work
};
window.addEventListener('beforeunload', handleBeforeUnload);
return () => window.removeEventListener('beforeunload', handleBeforeUnload);
}, [uploadCount]);
// allows user to navigate history using the forward and backward buttons on a mouse
useEffect(() => {
const handleForwardAndBackButtons = e => {
switch (e.button) {
case MOUSE_BACK_BTN:
history.index > 0 && history.goBack();
break;
case MOUSE_FORWARD_BTN:
history.index < history.length - 1 && history.goForward();
break;
}
};
window.addEventListener('mouseup', handleForwardAndBackButtons);
return () => window.removeEventListener('mouseup', handleForwardAndBackButtons);
});
2020-01-14 15:44:07 -05:00
useEffect(() => {
if (referredRewardAvailable && sanitizedReferrerParam && isRewardApproved) {
setReferrer(sanitizedReferrerParam, true);
} else if (referredRewardAvailable && sanitizedReferrerParam) {
setReferrer(sanitizedReferrerParam, false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
2020-01-14 15:44:07 -05:00
}, [sanitizedReferrerParam, isRewardApproved, referredRewardAvailable]);
2019-06-11 14:10:58 -04:00
useEffect(() => {
2020-03-27 12:49:41 -04:00
const { current: wrapperElement } = appRef;
2020-02-06 13:49:05 -05:00
if (wrapperElement) {
ReactModal.setAppElement(wrapperElement);
}
2019-08-06 12:53:59 -04:00
fetchAccessToken();
2019-06-27 02:18:45 -04:00
// @if TARGET='app'
2019-09-26 12:07:11 -04:00
fetchChannelListMine(); // This needs to be done for web too...
2019-06-27 02:18:45 -04:00
// @endif
}, [appRef, fetchAccessToken, fetchChannelListMine]);
2018-10-18 11:45:24 -05:00
2019-06-11 14:10:58 -04:00
useEffect(() => {
2018-10-18 11:45:24 -05:00
// $FlowFixMe
2019-11-22 16:13:00 -05:00
document.documentElement.setAttribute('theme', theme);
2019-06-11 14:10:58 -04:00
}, [theme]);
2018-11-07 11:03:42 -05:00
2019-11-08 15:51:42 -05:00
useEffect(() => {
if (!languages.includes(language)) {
setLanguage(language);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
2019-11-08 15:51:42 -05:00
}, [language, languages]);
2019-07-21 22:28:49 -04:00
useEffect(() => {
if (previousUserId === undefined && userId) {
2019-07-21 22:28:49 -04:00
analytics.setUser(userId);
}
}, [previousUserId, userId]);
useEffect(() => {
2019-08-14 23:09:34 -04:00
// Check that previousHasVerifiedEmail was not undefined instead of just not truthy
// This ensures we don't fire the emailVerified event on the initial user fetch
2019-09-26 12:07:11 -04:00
if (previousHasVerifiedEmail === false && hasVerifiedEmail) {
analytics.emailVerifiedEvent();
}
2019-10-01 00:53:33 -04:00
}, [previousHasVerifiedEmail, hasVerifiedEmail, signIn]);
useEffect(() => {
2019-09-26 12:07:11 -04:00
if (previousRewardApproved === false && isRewardApproved) {
analytics.rewardEligibleEvent();
}
}, [previousRewardApproved, isRewardApproved]);
2019-07-21 22:28:49 -04:00
2019-09-26 12:07:11 -04:00
// Keep this at the end to ensure initial setup effects are run first
useEffect(() => {
2019-10-08 14:11:52 -04:00
// Wait for balance to be populated on desktop so we know when we can begin syncing
2019-10-15 17:23:51 -04:00
if (!hasSignedIn && hasVerifiedEmail) {
2019-10-01 00:53:33 -04:00
signIn();
2019-10-15 00:20:12 -04:00
setHasSignedIn(true);
}
2019-10-15 17:23:51 -04:00
}, [hasVerifiedEmail, signIn, hasSignedIn]);
2019-12-21 13:43:42 -05:00
// @if TARGET='app'
useEffect(() => {
updatePreferences();
// eslint-disable-next-line react-hooks/exhaustive-deps
2019-12-21 13:43:42 -05:00
}, []);
// @endif
2019-10-15 17:23:51 -04:00
useEffect(() => {
if (hasVerifiedEmail && syncEnabled) {
2019-10-15 17:23:51 -04:00
checkSync();
analyticsTagSync();
2019-10-15 17:23:51 -04:00
let syncInterval = setInterval(() => {
checkSync();
}, SYNC_INTERVAL);
return () => {
clearInterval(syncInterval);
};
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hasVerifiedEmail, syncEnabled, checkSync]);
2019-10-22 13:57:32 -04:00
useEffect(() => {
if (syncError && isAuthenticated) {
2019-10-22 16:43:51 -04:00
history.push(`/$/${PAGES.AUTH}?redirect=${pathname}`);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [syncError, pathname, isAuthenticated]);
2019-10-22 13:57:32 -04:00
// @if TARGET='web'
useDegradedPerformance(setLbryTvApiStatus);
// @endif
// @if TARGET='web'
// Require an internal-api user on lbry.tv
// This also prevents the site from loading in the un-authed state while we wait for internal-apis to return for the first time
// It's not needed on desktop since there is no un-authed state
2020-01-14 15:01:37 -05:00
if (!user) {
return null;
}
// @endif
2019-06-11 14:10:58 -04:00
return (
2019-10-09 12:34:18 -04:00
<div
className={classnames(MAIN_WRAPPER_CLASS, {
// @if TARGET='app'
[`${MAIN_WRAPPER_CLASS}--mac`]: IS_MAC,
// @endif
})}
2019-10-09 12:34:18 -04:00
ref={appRef}
2019-11-01 16:44:26 -04:00
onContextMenu={IS_WEB ? undefined : e => openContextMenu(e)}
2019-10-09 12:34:18 -04:00
>
{IS_WEB && lbryTvApiStatus === STATUS_DOWN ? (
<Yrbl
className="main--empty"
title={__('lbry.tv is currently down')}
2020-03-17 16:13:35 -04:00
subtitle={__('My wheel broke, but the good news is that someone from LBRY is working on it.')}
/>
) : (
2020-02-21 16:05:20 -05:00
<React.Fragment>
<Router />
<ModalRouter />
<FileRenderFloating pageUri={uri} />
{isEnhancedLayout && <Yrbl className="yrbl--enhanced" />}
{/* @if TARGET='app' */}
{showUpgradeButton && (
2020-02-21 16:05:20 -05:00
<Nag
message={__('An upgrade is available.')}
actionText={__('Install Now')}
onClick={requestDownloadUpgrade}
2020-02-21 16:05:20 -05:00
/>
)}
{/* @endif */}
{/* @if TARGET='web' */}
<YoutubeWelcome />
2020-03-27 09:57:11 -04:00
{!shouldHideNag && <OpenInAppLink uri={uri} />}
{(lbryTvApiStatus === STATUS_DEGRADED || lbryTvApiStatus === STATUS_FAILING) && !shouldHideNag && (
<NagDegradedPerformance onClose={() => setLbryTvApiStatus(STATUS_OK)} />
)}
{lbryTvApiStatus === STATUS_OK && showAnalyticsNag && !shouldHideNag && (
<NagDataCollection onClose={handleAnalyticsDismiss} />
)}
{/* @endif */}
2020-02-21 16:05:20 -05:00
</React.Fragment>
2020-02-21 15:44:58 -05:00
)}
2019-06-11 14:10:58 -04:00
</div>
);
2017-05-03 23:44:08 -04:00
}
2017-04-07 12:15:22 +07:00
2019-08-13 01:35:13 -04:00
export default withRouter(App);