Compare commits

..
Author SHA1 Message Date
Anthony 5f8c812b9d seems to be working 2021-09-10 13:01:46 -04:00
82 changed files with 1310 additions and 1657 deletions

No files matched your search

+10 -20
View File
@@ -3,26 +3,6 @@
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
## [Unreleased for Desktop]
### Added
- Added direct replying to notifications _community pr!_ ([#6935](https://github.com/lbryio/lbry-desktop/pull/6935))
- Added "Replay" option on autoplay countdown ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added "Loop" option on Lists ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added "Shuffle" option on Lists ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added Play Next/Previous buttons (with shortcuts SHIFT+N/SHIFT+P) ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added separate control for autoplay next on video player ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
### Changed
- Changing the supported language from Filipino to Tagalog _community pr!_ ([#6951](https://github.com/lbryio/lbry-desktop/pull/6951))
- Don't show countdown to next item in list ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Changed "View List" popup option to link, so can be opened on a new tab ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
### Fixed
- Clicking on the title of a floating player will take you back to the list ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Fix floating player stopping on markdown or image files ([#7073](https://github.com/lbryio/lbry-desktop/pull/7073))
- Fix list thumbnail upload ([#7074](https://github.com/lbryio/lbry-desktop/pull/7074))
## [0.51.2] - [2021-08-20]
### Added
@@ -31,6 +11,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Add confirmation on comment removal _community pr!_ ([#6563](https://github.com/lbryio/lbry-desktop/pull/6563))
- Show on content page if a file is part of a playlist already _community pr!_([#6393](https://github.com/lbryio/lbry-desktop/pull/6393))
- Add filtering to playlists ([#6905](https://github.com/lbryio/lbry-desktop/pull/6905))
- Added direct replying to notifications _community pr!_ ([#6935](https://github.com/lbryio/lbry-desktop/pull/6935))
- Added "Replay" option on autoplay countdown ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added "Loop" option on Lists ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added "Shuffle" option on Lists ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added Play Next/Previous buttons (with shortcuts SHIFT+N/SHIFT+P) ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Added separate control for autoplay next on video player ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
### Changed
- Use Canonical Url for copy link ([#6500](https://github.com/lbryio/lbry-desktop/pull/6500))
@@ -41,6 +27,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Update sockety api _community pr!_ ([#6747](https://github.com/lbryio/lbry-desktop/pull/6747))
- Use resolve for OG metadata instead of chainquery _community pr!_ ([#6787](https://github.com/lbryio/lbry-desktop/pull/6787))
- Improved clickability of notification links _community pr!_ ([#6711](https://github.com/lbryio/lbry-desktop/pull/6711))
- Changing the supported language from Filipino to Tagalog _community pr!_ ([#6951](https://github.com/lbryio/lbry-desktop/pull/6951))
- Don't show countdown to next item in list ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
- Changed "View List" popup option to link, so can be opened on a new tab ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
### Fixed
- App now supports '#' and ':' for claimId separator ([#6496](https://github.com/lbryio/lbry-desktop/pull/6496))
@@ -60,6 +49,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- Fix OG: "Unparsable data structure - Truncated Unicode character" _community pr!_ ([#6839](https://github.com/lbryio/lbry-desktop/pull/6839))
- Fix Paid embed warning overlay redirection button now links to odysee _community pr!_ ([#6819](https://github.com/lbryio/lbry-desktop/pull/6819))
- Fix comment section redirection to create channel _community pr!_ ([#6557](https://github.com/lbryio/lbry-desktop/pull/6557))
- Clicking on the title of a floating player will take you back to the list ([#6921](https://github.com/lbryio/lbry-desktop/pull/6921))
## [0.51.1] - [2021-06-26]
-1
View File
@@ -2,7 +2,6 @@
declare type PlayingUri = {
uri: string,
primaryUri: string,
pathname: string,
commentId?: string,
source?: string,
+2 -3
View File
@@ -56,7 +56,6 @@
"express": "^4.17.1",
"humanize-duration": "^3.27.0",
"if-env": "^1.0.4",
"match-sorter": "^6.3.0",
"parse-duration": "^1.0.0",
"react-datetime-picker": "^3.2.1",
"react-plastic": "^1.1.1",
@@ -155,8 +154,8 @@
"imagesloaded": "^4.1.4",
"json-loader": "^0.5.4",
"lbry-format": "https://github.com/lbryio/lbry-format.git",
"lbry-redux": "lbryio/lbry-redux#32b578707116d45f5b51b7ab523d200e75668676",
"lbryinc": "lbryio/lbryinc#c9ced4f226e06f4f188cb8dc31b561e1c27c5266",
"lbry-redux": "lbryio/lbry-redux#49b9db5aae8db84ec21231444bf8345d450812b2",
"lbryinc": "lbryio/lbryinc#0b4e41ef90d6347819dd3453f2f9398a5c1b4f36",
"lint-staged": "^7.0.2",
"localforage": "^1.7.1",
"lodash-es": "^4.17.14",
+3 -14
View File
@@ -30,9 +30,6 @@
"Send a tip": "Send a tip",
"Share": "Share",
"Play": "Play",
"Shuffle Play": "Shuffle Play",
"Shuffle": "Shuffle",
"Loop": "Loop",
"Subscribe": "Subscribe",
"Report content": "Report content",
"Report Content": "Report Content",
@@ -160,7 +157,7 @@
"Autoplay media files": "Autoplay media files",
"Autoplay video and audio files when navigating to a file.": "Autoplay video and audio files when navigating to a file.",
"Autoplay next recommended content": "Autoplay next recommended content",
"Autoplay the next related item when a file (video or audio) finishes playing.": "Autoplay the next related item when a file (video or audio) finishes playing.",
"Autoplay video and audio files as the next related item when a file finishes playing.": "Autoplay video and audio files as the next related item when a file finishes playing.",
"Clear application cache": "Clear application cache",
"Clear Cache": "Clear Cache",
"This might fix issues that you are having. Your wallet will not be affected.": "This might fix issues that you are having. Your wallet will not be affected.",
@@ -933,7 +930,6 @@
"Community Choice?": "Community Choice?",
"Download to your Library": "Download to your Library",
"Leave a Comment": "Leave a Comment",
"This comment has been deleted.": "This comment has been deleted.",
"That was pretty deep. What do you think?": "That was pretty deep. What do you think?",
"%repost_total% Reposts": "%repost_total% Reposts",
"File Description": "File Description",
@@ -1181,11 +1177,7 @@
"Tap to unmute": "Tap to unmute",
"Retry": "Retry",
"Playing in %seconds_left% seconds...": "Playing in %seconds_left% seconds...",
"Playing next free content in %seconds_left% seconds...": "Playing next free content in %seconds_left% seconds...",
"Autoplay timer paused.": "Autoplay timer paused.",
"Play Previous": "Play Previous",
"Purchase?": "Purchase?",
"Replay?": "Replay?",
"0 Bytes": "0 Bytes",
"Bytes": "Bytes",
"KB": "KB",
@@ -1769,8 +1761,7 @@
"Delegation": "Delegation",
"Add moderator": "Add moderator",
"Search channel": "Search channel",
"Enter a name, @username or URL": "Enter a name, @username or URL",
"Enter full channel name or URL": "Enter full channel name or URL",
"Enter a @username or URL": "Enter a @username or URL",
"Enter a channel name or URL to add as a moderator.\nExamples:\n - @channel\n - @channel#3\n - https://odysee.com/@Odysee:8\n - lbry://@Odysee#8": "Enter a channel name or URL to add as a moderator.\nExamples:\n - @channel\n - @channel#3\n - https://odysee.com/@Odysee:8\n - lbry://@Odysee#8",
"Moderators": "Moderators",
"Moderators can block channels on your behalf. Blocked channels will appear in your \"Blocked and Muted\" list.": "Moderators can block channels on your behalf. Blocked channels will appear in your \"Blocked and Muted\" list.",
@@ -1917,7 +1908,6 @@
"e.g. John Doe": "e.g. John Doe",
"e.g. john@example.com": "e.g. john@example.com",
"e.g. satoshi@example.com": "e.g. satoshi@example.com",
"e.g. odysee": "e.g. odysee",
"Your channel": "Your channel",
"Set to \"Anonymous\" if you do not want to associate your channel in this report.": "Set to \"Anonymous\" if you do not want to associate your channel in this report.",
"Send report?": "Send report?",
@@ -1994,6 +1984,7 @@
"Learn more and sign petition": "Learn more and sign petition",
"View claim details": "View claim details",
"Publishing...": "Publishing...",
"Enter a name, @username or URL": "Enter a name, @username or URL",
"Recipient search": "Recipient search",
"Fetch transaction data for export": "Fetch transaction data for export",
"Fetching data": "Fetching data",
@@ -2017,7 +2008,6 @@
"This channel isn't staking enough LBRY Credits for inline image previews.": "This channel isn't staking enough LBRY Credits for inline image previews.",
"Latest": "Latest",
"Channel Not Found": "Channel Not Found",
"Channel not found": "Channel not found",
"Probably because you didn't make it.": "Probably because you didn't make it.",
"Release date": "Release date",
"Set custom release date": "Set custom release date",
@@ -2168,6 +2158,5 @@
"Channel Page": "Channel Page",
"Content Page": "Content Page",
"Card Last 4": "Card Last 4",
"Search blocked channel name": "Search blocked channel name",
"--end--": "--end--"
}
+12 -46
View File
@@ -15,11 +15,8 @@ type Props = {
nextRecommendedClaim: ?StreamClaim,
nextRecommendedUri: string,
modal: { id: string, modalProps: {} },
skipPaid: boolean,
doNavigate: () => void,
doReplay: () => void,
doPrevious: () => void,
onCanceled: () => void,
};
function AutoplayCountdown(props: Props) {
@@ -28,11 +25,8 @@ function AutoplayCountdown(props: Props) {
nextRecommendedClaim,
history: { push },
modal,
skipPaid,
doNavigate,
doReplay,
doPrevious,
onCanceled,
} = props;
const nextTitle = nextRecommendedClaim && nextRecommendedClaim.value && nextRecommendedClaim.value.title;
@@ -50,14 +44,6 @@ function AutoplayCountdown(props: Props) {
return elm && elm.getBoundingClientRect().top < 0;
}
function getMsgPlayingNext() {
if (skipPaid) {
return __('Playing next free content in %seconds_left% seconds...', { seconds_left: timer });
} else {
return __('Playing in %seconds_left% seconds...', { seconds_left: timer });
}
}
// Update 'setTimerPaused'.
React.useEffect(() => {
// Ensure correct 'setTimerPaused' on initial render.
@@ -82,7 +68,6 @@ function AutoplayCountdown(props: Props) {
interval = setInterval(() => {
const newTime = timer - 1;
if (newTime === 0) {
if (skipPaid) setTimer(countdownTime);
doNavigate();
} else {
setTimer(timer - 1);
@@ -93,7 +78,7 @@ function AutoplayCountdown(props: Props) {
return () => {
clearInterval(interval);
};
}, [timer, doNavigate, push, timerCanceled, isTimerPaused, nextRecommendedUri, skipPaid]);
}, [timer, doNavigate, push, timerCanceled, isTimerPaused, nextRecommendedUri]);
if (timerCanceled || !nextRecommendedUri) {
return null;
@@ -120,38 +105,19 @@ function AutoplayCountdown(props: Props) {
)}
{!isTimerPaused && (
<div className="file-viewer__overlay-secondary autoplay-countdown__counter">
{getMsgPlayingNext()}{' '}
<Button
label={__('Cancel')}
button="link"
onClick={() => {
setTimerCanceled(true);
if (onCanceled) onCanceled();
}}
/>
{__('Playing in %seconds_left% seconds...', { seconds_left: timer })}{' '}
<Button label={__('Cancel')} button="link" onClick={() => setTimerCanceled(true)} />
</div>
)}
{skipPaid && doPrevious && (
<div>
<Button
label={__('Play Previous')}
button="link"
icon={ICONS.PLAY_PREVIOUS}
onClick={() => doPrevious()}
/>
</div>
)}
<div>
<Button
label={skipPaid ? __('Purchase?') : __('Replay?')}
button="link"
iconRight={skipPaid ? ICONS.WALLET : ICONS.REPLAY}
onClick={() => {
setTimerCanceled(true);
doReplay();
}}
/>
</div>
<Button
label={__('Replay?')}
button="link"
iconRight={ICONS.REPLAY}
onClick={() => {
setTimerCanceled(true);
doReplay();
}}
/>
</div>
</div>
</div>
-2
View File
@@ -1,2 +0,0 @@
import BlockList from './view';
export default BlockList;
-205
View File
@@ -1,205 +0,0 @@
// @flow
import { Combobox, ComboboxInput, ComboboxPopover, ComboboxList, ComboboxOption } from '@reach/combobox';
// import '@reach/combobox/styles.css'; --> 'scss/third-party.scss'
import { matchSorter } from 'match-sorter';
import React from 'react';
import classnames from 'classnames';
import Button from 'component/button';
import ClaimList from 'component/claimList';
import Icon from 'component/common/icon';
import Paginate from 'component/common/paginate';
import Yrbl from 'component/yrbl';
import * as ICONS from 'constants/icons';
import useThrottle from 'effects/use-throttle';
const PAGE_SIZE = 10;
function reduceUriToChannelName(uri: string) {
// 'parseURI' is too slow to handle a large list. Since our list should be
// kosher in the first place, just do a quick substring call. Add a
// try-catch just in case.
try {
return uri.substring(uri.indexOf('@') + 1, uri.indexOf('#'));
} catch {
return uri;
}
}
// ****************************************************************************
// BlockList
// ****************************************************************************
type Props = {
uris: Array<string>,
help: string,
titleEmptyList: string,
subtitleEmptyList: string,
getActionButtons?: (url: string) => React$Node,
className: ?string,
};
export default function BlockList(props: Props) {
const { uris: list, help, titleEmptyList, subtitleEmptyList, getActionButtons, className } = props;
// Keep a local list to allow for undoing actions in this component
const [localList, setLocalList] = React.useState(undefined);
const stringifiedList = JSON.stringify(list);
const hasLocalList = localList && localList.length > 0;
const justBlocked = list && localList && localList.length < list.length;
const [page, setPage] = React.useState(1);
const [searchList, setSearchList] = React.useState(null); // null: not searching; []: no results;
const isShowingSearchResults = searchList !== null;
let totalPages = 0;
let paginatedLocalList;
if (localList) {
paginatedLocalList = localList.slice((page - 1) * PAGE_SIZE, page * PAGE_SIZE);
totalPages = Math.ceil(localList.length / PAGE_SIZE);
}
// **************************************************************************
// **************************************************************************
function getRenderActions() {
if (getActionButtons) {
return (claim) => <div className="section__actions">{getActionButtons(claim.permanent_url)}</div>;
}
return undefined;
}
function formatSearchSuggestion(suggestion: string) {
return reduceUriToChannelName(suggestion);
}
function filterSearchResults(results: ?Array<string>) {
setSearchList(results);
}
// **************************************************************************
// **************************************************************************
React.useEffect(() => {
const list = stringifiedList && JSON.parse(stringifiedList);
if (!hasLocalList) {
setLocalList(list && list.length > 0 ? list : []);
}
}, [stringifiedList, hasLocalList]);
React.useEffect(() => {
if (justBlocked && stringifiedList) {
setLocalList(JSON.parse(stringifiedList));
}
}, [stringifiedList, justBlocked, setLocalList]);
// **************************************************************************
// **************************************************************************
if (paginatedLocalList === undefined) {
return null;
}
if (!hasLocalList) {
return (
<div className="main--empty">
<Yrbl
title={titleEmptyList}
subtitle={subtitleEmptyList}
actions={
<div className="section__actions">
<Button button="primary" label={__('Go Home')} navigate="/" />
</div>
}
/>
</div>
);
}
return (
<>
<div className="help--notice">{help}</div>
<div className="section">
<SearchList
list={localList}
placeholder={__('e.g. odysee')}
formatter={formatSearchSuggestion}
onResultsUpdated={filterSearchResults}
/>
</div>
<div className={classnames('section block-list', className)}>
<ClaimList
uris={searchList || paginatedLocalList}
showUnresolvedClaims
showHiddenByUser
hideMenu
renderActions={getRenderActions()}
/>
</div>
{!isShowingSearchResults && <Paginate totalPages={totalPages} disableHistory onPageChange={(p) => setPage(p)} />}
</>
);
}
// ****************************************************************************
// SearchList
// ****************************************************************************
type LsbProps = {
list: ?Array<string>,
placeholder?: string,
formatter?: (suggestion: string) => string,
onResultsUpdated?: (?Array<string>) => void,
};
function SearchList(props: LsbProps) {
const { list, placeholder, formatter, onResultsUpdated } = props;
const [term, setTerm] = React.useState('');
const results = useAuthorMatch(term, list);
const handleChange = (event) => setTerm(event.target.value);
const handleSelect = (e) => setTerm(e);
React.useEffect(() => {
if (onResultsUpdated) {
onResultsUpdated(results);
}
}, [results]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className="wunderbar__wrapper">
<label>{__('Search blocked channel name')}</label>
<Combobox className="wunderbar" onSelect={handleSelect}>
<Icon icon={ICONS.SEARCH} />
<ComboboxInput selectOnClick className="wunderbar__input" onChange={handleChange} placeholder={placeholder} />
{results && (
<ComboboxPopover className="wunderbar__suggestions" portal={false}>
{results.length > 0 ? (
<ComboboxList>
{results.slice(0, 10).map((result, index) => (
<ComboboxOption
className="wunderbar__more-results"
key={index}
value={formatter ? formatter(result) : result}
/>
))}
</ComboboxList>
) : (
<span style={{ display: 'block', margin: 8 }}>{__('No results')}</span>
)}
</ComboboxPopover>
)}
</Combobox>
</div>
);
}
function useAuthorMatch(term, list) {
const throttledTerm = useThrottle(term, 200);
return React.useMemo(() => {
return !throttledTerm || throttledTerm.trim() === ''
? null
: matchSorter(list, throttledTerm, {
keys: [(item) => reduceUriToChannelName(item)],
threshold: matchSorter.rankings.CONTAINS,
});
}, [throttledTerm]); // eslint-disable-line react-hooks/exhaustive-deps
}
+4 -2
View File
@@ -2,6 +2,7 @@
import React from 'react';
import Button from 'component/button';
import { BLOCK_LEVEL } from 'constants/comment';
import { parseURI } from 'lbry-redux';
type Props = {
uri: string,
@@ -47,10 +48,11 @@ function ChannelBlockButton(props: Props) {
case BLOCK_LEVEL.MODERATOR:
if (creatorUri) {
const { channelClaimId } = parseURI(creatorUri);
if (isBlocked) {
doCommentModUnBlockAsModerator(uri, creatorUri, '');
doCommentModUnBlockAsModerator(uri, channelClaimId, '');
} else {
doCommentModBlockAsModerator(uri, creatorUri, '');
doCommentModBlockAsModerator(uri, channelClaimId, '');
}
}
break;
+1 -1
View File
@@ -146,7 +146,7 @@ function ChannelContent(props: Props) {
defaultFreshness={CS.FRESH_ALL}
showHiddenByUser={viewHiddenChannels}
forceShowReposts
fetchViewCount
// fetchViewCount
hideFilters={!showFilters}
hideAdvancedFilter={!showFilters}
tileLayout={tileLayout}
+60 -84
View File
@@ -18,80 +18,68 @@ import { getLivestreamOnlyOptions } from 'util/search';
type Props = {
uris: Array<string>,
name?: string,
type: string,
pageSize?: number,
fetchViewCount?: boolean,
forceShowReposts?: boolean,
hasNoSource?: boolean,
hasSource?: boolean,
hideAdvancedFilter?: boolean,
hideFilters?: boolean,
includeSupportAction?: boolean,
infiniteScroll?: Boolean,
isChannel?: boolean,
liveLivestreamsFirst?: boolean,
personalView: boolean,
showHeader: boolean,
showHiddenByUser?: boolean,
showNoSourceClaims?: boolean,
tileLayout: boolean,
orderBy?: Array<string>, // Trending, New, Top
defaultOrderBy?: string,
sortBy?: Array<string>, // Newest First, Oldest First
freshness?: string,
defaultFreshness?: string,
tags: string, // these are just going to be string. pass a CSV if you want multi
defaultTags: string,
claimType?: string | Array<string>,
defaultClaimType?: Array<string>,
streamType?: string | Array<string>,
defaultStreamType?: string | Array<string>,
empty?: string,
feeAmount?: string,
releaseTime?: string,
repostedClaimId?: string,
scrollAnchor?: string,
maxPages?: number,
limitClaimsPerChannel?: number,
channelIds?: Array<string>,
claimIds?: Array<string>,
type: string,
subscribedChannels: Array<Subscription>,
livestreamMap?: { [string]: any },
header?: Node,
headerLabel?: string | Node,
hiddenNsfwMessage?: Node,
injectedItem: ?Node,
meta?: Node,
renderProperties?: (Claim) => Node,
history: { action: string, push: (string) => void, replace: (string) => void },
location: { search: string, pathname: string },
// --- select ---
followedTags?: Array<Tag>,
claimSearchByQuery: { [string]: Array<string> },
claimSearchByQueryLastPageReached: { [string]: boolean },
claimsByUri: { [string]: any },
doClaimSearch: ({}) => void,
loading: boolean,
personalView: boolean,
doToggleTagFollowDesktop: (string) => void,
meta?: Node,
showNsfw: boolean,
hideReposts: boolean,
languageSetting: string,
fetchViewCount?: boolean,
history: { action: string, push: (string) => void, replace: (string) => void },
location: { search: string, pathname: string },
claimSearchByQuery: {
[string]: Array<string>,
},
claimSearchByQueryLastPageReached: { [string]: boolean },
mutedUris: Array<string>,
blockedUris: Array<string>,
hiddenNsfwMessage?: Node,
channelIds?: Array<string>,
claimIds?: Array<string>,
tags: string, // these are just going to be string. pass a CSV if you want multi
defaultTags: string,
orderBy?: Array<string>,
defaultOrderBy?: string,
freshness?: string,
defaultFreshness?: string,
header?: Node,
headerLabel?: string | Node,
name?: string,
hideAdvancedFilter?: boolean,
claimType?: string | Array<string>,
defaultClaimType?: Array<string>,
streamType?: string | Array<string>,
defaultStreamType?: string | Array<string>,
renderProperties?: (Claim) => Node,
includeSupportAction?: boolean,
repostedClaimId?: string,
pageSize?: number,
followedTags?: Array<Tag>,
injectedItem: ?Node,
infiniteScroll?: Boolean,
feeAmount?: string,
tileLayout: boolean,
hideFilters?: boolean,
maxPages?: number,
forceShowReposts?: boolean,
languageSetting: string,
searchInLanguage: boolean,
// --- perform ---
doClaimSearch: ({}) => void,
doToggleTagFollowDesktop: (string) => void,
scrollAnchor?: string,
showHiddenByUser?: boolean,
liveLivestreamsFirst?: boolean,
livestreamMap?: { [string]: any },
hasSource?: boolean,
hasNoSource?: boolean,
limitClaimsPerChannel?: number,
releaseTime?: string,
showNoSourceClaims?: boolean,
isChannel?: boolean,
empty?: string,
claimsByUri: { [string]: any },
doFetchViewCount: (claimIdCsv: string) => void,
};
@@ -116,7 +104,6 @@ function ClaimListDiscover(props: Props) {
blockedUris,
hiddenNsfwMessage,
defaultOrderBy,
sortBy,
orderBy,
headerLabel,
header,
@@ -172,7 +159,6 @@ function ClaimListDiscover(props: Props) {
(urlParams.get(CS.TAGS_KEY) !== null && urlParams.get(CS.TAGS_KEY)) ||
(defaultTags && getParamFromTags(defaultTags));
const freshnessParam = freshness || urlParams.get(CS.FRESH_KEY) || defaultFreshness;
const sortByParam = sortBy || urlParams.get(CS.SORT_BY_KEY) || CS.SORT_BY.NEWEST.key;
const mutedAndBlockedChannelIds = Array.from(
new Set(mutedUris.concat(blockedUris).map((uri) => splitBySeparator(uri)[1]))
);
@@ -258,7 +244,12 @@ function ClaimListDiscover(props: Props) {
no_totals: true,
not_channel_ids: isChannel ? undefined : mutedAndBlockedChannelIds,
not_tags: !showNsfw ? MATURE_TAGS : [],
order_by: resolveOrderByOption(orderParam, sortByParam),
order_by:
orderParam === CS.ORDER_BY_TRENDING
? CS.ORDER_BY_TRENDING_VALUE
: orderParam === CS.ORDER_BY_NEW
? CS.ORDER_BY_NEW_VALUE
: CS.ORDER_BY_TOP_VALUE, // Sort by top
};
if (ENABLE_NO_SOURCE_CLAIMS && hasNoSource) {
@@ -549,21 +540,6 @@ function ClaimListDiscover(props: Props) {
}
}
function resolveOrderByOption(orderBy: string | Array<string>, sortBy: string | Array<string>) {
const order_by =
orderBy === CS.ORDER_BY_TRENDING
? CS.ORDER_BY_TRENDING_VALUE
: orderBy === CS.ORDER_BY_NEW
? CS.ORDER_BY_NEW_VALUE
: CS.ORDER_BY_TOP_VALUE;
if (orderBy === CS.ORDER_BY_NEW && sortBy === CS.SORT_BY.OLDEST.key) {
return order_by.map((x) => `${CS.SORT_BY.OLDEST.opt}${x}`);
}
return order_by;
}
// **************************************************************************
// **************************************************************************
+3 -38
View File
@@ -1,4 +1,5 @@
// @flow
import { SIMPLE_SITE } from 'config';
import * as CS from 'constants/claim_search';
import * as ICONS from 'constants/icons';
import type { Node } from 'react';
@@ -20,7 +21,6 @@ type Props = {
streamType?: string | Array<string>,
defaultStreamType?: string | Array<string>,
feeAmount: string,
sortBy?: string,
orderBy?: Array<string>,
defaultOrderBy?: string,
hideAdvancedFilter: boolean,
@@ -45,7 +45,6 @@ function ClaimListHeader(props: Props) {
streamType,
defaultStreamType,
feeAmount,
sortBy,
orderBy,
defaultOrderBy,
hideAdvancedFilter,
@@ -72,7 +71,6 @@ function ClaimListHeader(props: Props) {
streamType || (CS.FILE_TYPES.includes(contentTypeParam) && contentTypeParam) || defaultStreamType || null;
const durationParam = urlParams.get(CS.DURATION_KEY) || null;
const languageParam = urlParams.get(CS.LANGUAGE_KEY) || null;
const sortByParam = sortBy || urlParams.get(CS.SORT_BY_KEY) || null;
const channelIdsInUrl = urlParams.get(CS.CHANNEL_IDS_KEY);
const channelIdsParam = channelIdsInUrl ? channelIdsInUrl.split(',') : channelIds;
const feeAmountParam = urlParams.get('fee_amount') || feeAmount || CS.FEE_AMOUNT_ANY;
@@ -155,13 +153,6 @@ function ClaimListHeader(props: Props) {
case CS.ORDER_BY_KEY:
newUrlParams.set(CS.ORDER_BY_KEY, delta.value);
break;
case CS.SORT_BY_KEY:
if (delta.value === CS.SORT_BY.NEWEST.key) {
newUrlParams.delete(CS.SORT_BY_KEY);
} else {
newUrlParams.set(CS.SORT_BY_KEY, delta.value);
}
break;
case CS.FRESH_KEY:
if (delta.value === defaultFreshness || delta.value === CS.FRESH_DEFAULT) {
newUrlParams.delete(CS.FRESH_KEY);
@@ -249,7 +240,7 @@ function ClaimListHeader(props: Props) {
</div>
)}
<div className="claim-search__menu-group">
{!hideAdvancedFilter && (
{!hideAdvancedFilter && !SIMPLE_SITE && (
<Button
button="alt"
aria-label={__('More')}
@@ -275,7 +266,7 @@ function ClaimListHeader(props: Props) {
)}
</div>
</div>
{expanded && (
{expanded && !SIMPLE_SITE && (
<>
<div className={classnames(`card claim-search__menus`)}>
{/* FRESHNESS FIELD */}
@@ -458,32 +449,6 @@ function ClaimListHeader(props: Props) {
</FormField>
</div>
{/* SORT FIELD */}
{orderParam === CS.ORDER_BY_NEW && (
<div className={'claim-search__input-container'}>
<FormField
className={classnames('claim-search__dropdown', {
'claim-search__dropdown--selected': sortByParam,
})}
label={__('Sort By')}
type="select"
name="sort_by"
value={sortByParam || CS.SORT_BY.NEWEST.key}
onChange={(e) => handleChange({ key: CS.SORT_BY_KEY, value: e.target.value })}
>
{Object.entries(CS.SORT_BY).map(([key, value]) => {
return (
// $FlowFixMe https://github.com/facebook/flow/issues/2221
<option key={value.key} value={value.key}>
{/* $FlowFixMe */}
{__(value.str)}
</option>
);
})}
</FormField>
</div>
)}
{channelIdsInUrl && (
<div className={'claim-search__input-container'}>
<label>{__('Advanced Filters from URL')}</label>
+5 -6
View File
@@ -31,13 +31,14 @@ import { doChannelSubscribe, doChannelUnsubscribe } from 'redux/actions/subscrip
import { makeSelectIsSubscribed } from 'redux/selectors/subscriptions';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectListShuffle } from 'redux/selectors/content';
import { doToggleLoopList, doToggleShuffleList } from 'redux/actions/content';
import { doSetPlayingUri, doToggleShuffleList } from 'redux/actions/content';
import ClaimPreview from './view';
import fs from 'fs';
const select = (state, props) => {
const claim = makeSelectClaimForUri(props.uri, false)(state);
const collectionId = props.collectionId;
const resolvedList = makeSelectUrlsForCollectionId(collectionId)(state);
const repostedClaim = claim && claim.reposted_claim;
const contentClaim = repostedClaim || claim;
const contentSigningChannel = contentClaim && contentClaim.signing_channel;
@@ -72,7 +73,7 @@ const select = (state, props) => {
isMyCollection: makeSelectCollectionIsMine(collectionId)(state),
editedCollection: makeSelectEditedCollectionForId(collectionId)(state),
isAuthenticated: Boolean(selectUserVerifiedEmail(state)),
resolvedList: makeSelectUrlsForCollectionId(collectionId)(state),
resolvedList,
playNextUri,
};
};
@@ -101,10 +102,8 @@ const perform = (dispatch) => ({
doChannelUnsubscribe: (subscription) => dispatch(doChannelUnsubscribe(subscription)),
doCollectionEdit: (collection, props) => dispatch(doCollectionEdit(collection, props)),
fetchCollectionItems: (collectionId) => dispatch(doFetchItemsInCollection({ collectionId })),
doToggleShuffleList: (collectionId) => {
dispatch(doToggleLoopList(collectionId, false, true));
dispatch(doToggleShuffleList(undefined, collectionId, true, true));
},
doSetPlayingUri: (uri) => dispatch(doSetPlayingUri({ uri })),
doToggleShuffleList: (collectionId) => dispatch(doToggleShuffleList(undefined, collectionId, true, true)),
});
export default connect(select, perform)(ClaimPreview);
+86 -90
View File
@@ -7,13 +7,7 @@ import React from 'react';
import classnames from 'classnames';
import { Menu, MenuButton, MenuList, MenuItem } from '@reach/menu-button';
import Icon from 'component/common/icon';
import {
generateShareUrl,
generateRssUrl,
generateLbryContentUrl,
formatLbryUrlForWeb,
generateListSearchUrlParams,
} from 'util/url';
import { generateShareUrl, generateRssUrl, generateLbryContentUrl, formatLbryUrlForWeb } from 'util/url';
import { useHistory } from 'react-router';
import { buildURI, parseURI, COLLECTIONS_CONSTS } from 'lbry-redux';
@@ -65,6 +59,7 @@ type Props = {
playNextUri: string,
resolvedList: boolean,
fetchCollectionItems: (string) => void,
doSetPlayingUri: (string) => void,
doToggleShuffleList: (string) => void,
};
@@ -106,6 +101,7 @@ function ClaimMenuList(props: Props) {
playNextUri,
resolvedList,
fetchCollectionItems,
doSetPlayingUri,
doToggleShuffleList,
} = props;
const [doShuffle, setDoShuffle] = React.useState(false);
@@ -133,15 +129,15 @@ function ClaimMenuList(props: Props) {
if (doShuffle && resolvedList) {
doToggleShuffleList(collectionId);
if (playNextUri) {
const navigateUrl = formatLbryUrlForWeb(playNextUri);
push({
pathname: navigateUrl,
search: generateListSearchUrlParams(collectionId),
state: { collectionId, forceAutoplay: true },
});
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
const navigateUrl = formatLbryUrlForWeb(playNextUri) + `?` + collectionParams.toString();
setDoShuffle(false);
doSetPlayingUri(playNextUri);
push(navigateUrl);
}
}
}, [collectionId, doShuffle, doToggleShuffleList, playNextUri, push, resolvedList]);
}, [collectionId, doSetPlayingUri, doShuffle, doToggleShuffleList, playNextUri, push, resolvedList]);
if (!claim) {
return null;
@@ -263,7 +259,6 @@ function ClaimMenuList(props: Props) {
push(`/$/${PAGES.REPORT_CONTENT}?claimId=${contentClaim && contentClaim.claim_id}`);
}
const shouldShow = !IS_WEB || (IS_WEB && isAuthenticated);
return (
<Menu>
<MenuButton
@@ -276,93 +271,94 @@ function ClaimMenuList(props: Props) {
<Icon size={20} icon={ICONS.MORE_VERTICAL} />
</MenuButton>
<MenuList className="menu__list">
<>
{/* COLLECTION OPERATIONS */}
{collectionId && isCollectionClaim ? (
{(!IS_WEB || (IS_WEB && isAuthenticated)) && (
<>
<>
<MenuItem className="comment__menu-option" onSelect={() => push(`/$/${PAGES.LIST}/${collectionId}`)}>
<a className="menu__link" href={`/$/${PAGES.LIST}/${collectionId}`}>
<Icon aria-hidden icon={ICONS.VIEW} />
{__('View List')}
</a>
</MenuItem>
<MenuItem
className="comment__menu-option"
onSelect={() => {
if (!resolvedList) fetchItems();
setDoShuffle(true);
}}
>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.SHUFFLE} />
{__('Shuffle Play')}
</div>
</MenuItem>
{isMyCollection && (
{/* COLLECTION OPERATIONS */}
{collectionId && isCollectionClaim ? (
<>
<MenuItem
className="comment__menu-option"
onSelect={() => push(`/$/${PAGES.LIST}/${collectionId}?view=edit`)}
>
<div className="menu__link">
<Icon aria-hidden iconColor={'red'} icon={ICONS.PUBLISH} />
{editedCollection ? __('Publish') : __('Edit List')}
</div>
<MenuItem className="comment__menu-option" onSelect={() => push(`/$/${PAGES.LIST}/${collectionId}`)}>
<a className="menu__link" href={`/$/${PAGES.LIST}/${collectionId}`}>
<Icon aria-hidden icon={ICONS.VIEW} />
{__('View List')}
</a>
</MenuItem>
<MenuItem
className="comment__menu-option"
onSelect={() => openModal(MODALS.COLLECTION_DELETE, { collectionId })}
onSelect={() => {
if (!resolvedList) fetchItems();
setDoShuffle(true);
}}
>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.DELETE} />
{__('Delete List')}
<Icon aria-hidden icon={ICONS.SHUFFLE} />
{__('Shuffle Play')}
</div>
</MenuItem>
{isMyCollection && (
<>
<MenuItem
className="comment__menu-option"
onSelect={() => push(`/$/${PAGES.LIST}/${collectionId}?view=edit`)}
>
<div className="menu__link">
<Icon aria-hidden iconColor={'red'} icon={ICONS.PUBLISH} />
{editedCollection ? __('Publish') : __('Edit List')}
</div>
</MenuItem>
<MenuItem
className="comment__menu-option"
onSelect={() => openModal(MODALS.COLLECTION_DELETE, { collectionId })}
>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.DELETE} />
{__('Delete List')}
</div>
</MenuItem>
</>
)}
</>
) : (
isPlayable && (
<>
{/* WATCH LATER */}
<MenuItem
className="comment__menu-option"
onSelect={() =>
handleAdd(hasClaimInWatchLater, __('Watch Later'), COLLECTIONS_CONSTS.WATCH_LATER_ID)
}
>
<div className="menu__link">
<Icon aria-hidden icon={hasClaimInWatchLater ? ICONS.DELETE : ICONS.TIME} />
{hasClaimInWatchLater ? __('In Watch Later') : __('Watch Later')}
</div>
</MenuItem>
{/* FAVORITES LIST */}
<MenuItem
className="comment__menu-option"
onSelect={() => handleAdd(hasClaimInFavorites, __('Favorites'), COLLECTIONS_CONSTS.FAVORITES_ID)}
>
<div className="menu__link">
<Icon aria-hidden icon={hasClaimInFavorites ? ICONS.DELETE : ICONS.STAR} />
{hasClaimInFavorites ? __('In Favorites') : __('Favorites')}
</div>
</MenuItem>
{/* CURRENTLY ONLY SUPPORT PLAYLISTS FOR PLAYABLE; LATER DIFFERENT TYPES */}
<MenuItem
className="comment__menu-option"
onSelect={() => openModal(MODALS.COLLECTION_ADD, { uri, type: 'playlist' })}
>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.STACK} />
{__('Add to Lists')}
</div>
</MenuItem>
<hr className="menu__separator" />
</>
)
)}
</>
) : (
shouldShow &&
isPlayable && (
<>
{/* WATCH LATER */}
<MenuItem
className="comment__menu-option"
onSelect={() => handleAdd(hasClaimInWatchLater, __('Watch Later'), COLLECTIONS_CONSTS.WATCH_LATER_ID)}
>
<div className="menu__link">
<Icon aria-hidden icon={hasClaimInWatchLater ? ICONS.DELETE : ICONS.TIME} />
{hasClaimInWatchLater ? __('In Watch Later') : __('Watch Later')}
</div>
</MenuItem>
{/* FAVORITES LIST */}
<MenuItem
className="comment__menu-option"
onSelect={() => handleAdd(hasClaimInFavorites, __('Favorites'), COLLECTIONS_CONSTS.FAVORITES_ID)}
>
<div className="menu__link">
<Icon aria-hidden icon={hasClaimInFavorites ? ICONS.DELETE : ICONS.STAR} />
{hasClaimInFavorites ? __('In Favorites') : __('Favorites')}
</div>
</MenuItem>
{/* CURRENTLY ONLY SUPPORT PLAYLISTS FOR PLAYABLE; LATER DIFFERENT TYPES */}
<MenuItem
className="comment__menu-option"
onSelect={() => openModal(MODALS.COLLECTION_ADD, { uri, type: 'playlist' })}
>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.STACK} />
{__('Add to Lists')}
</div>
</MenuItem>
<hr className="menu__separator" />
</>
)
)}
</>
{shouldShow && (
<>
{!isChannelPage && (
<>
<MenuItem className="comment__menu-option" onSelect={handleSupport}>
@@ -439,9 +435,9 @@ function ClaimMenuList(props: Props) {
)}
</>
)}
<hr className="menu__separator" />
</>
)}
<hr className="menu__separator" />
<MenuItem className="comment__menu-option" onSelect={handleCopyLink}>
<div className="menu__link">
+2 -8
View File
@@ -195,12 +195,8 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
claim.value.stream_type &&
// $FlowFixMe
(claim.value.stream_type === 'audio' || claim.value.stream_type === 'video');
const isChannelUri = claim ? claim.value_type === 'channel' : false;
const isChannelUri = isValid ? parseURI(uri).isChannel : false;
const signingChannel = claim && claim.signing_channel;
const repostedChannelUri =
claim && claim.repost_channel_url && claim.value_type === 'channel'
? claim.permanent_url || claim.canonical_url
: undefined;
// Get channel title ( use name as fallback )
let channelTitle = null;
@@ -482,9 +478,7 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
)}
{isChannelUri && !channelIsBlocked && !claimIsMine && (
<SubscribeButton
uri={repostedChannelUri || (uri.startsWith('lbry://') ? uri : `lbry://${uri}`)}
/>
<SubscribeButton uri={uri.startsWith('lbry://') ? uri : `lbry://${uri}`} />
)}
{includeSupportAction && <ClaimSupportButton uri={uri} />}
+9 -7
View File
@@ -10,9 +10,9 @@ import ChannelThumbnail from 'component/channelThumbnail';
import FileViewCountInline from 'component/fileViewCountInline';
import SubscribeButton from 'component/subscribeButton';
import useGetThumbnail from 'effects/use-get-thumbnail';
import { formatLbryUrlForWeb, generateListSearchUrlParams } from 'util/url';
import { formatLbryUrlForWeb } from 'util/url';
import { formatClaimPreviewTitle } from 'util/formatAriaLabel';
import { parseURI, isURIEqual } from 'lbry-redux';
import { parseURI, COLLECTIONS_CONSTS, isURIEqual } from 'lbry-redux';
import PreviewOverlayProperties from 'component/previewOverlayProperties';
import FileDownloadLink from 'component/fileDownloadLink';
import FileWatchLaterLink from 'component/fileWatchLaterLink';
@@ -97,10 +97,13 @@ function ClaimPreviewTile(props: Props) {
const shouldFetch = claim === undefined;
const thumbnailUrl = useGetThumbnail(uri, claim, streamingUrl, getFile, placeholder) || thumbnail;
const canonicalUrl = claim && claim.canonical_url;
const permanentUrl = claim && claim.permanent_url;
let navigateUrl = formatLbryUrlForWeb(canonicalUrl || uri || '/');
const listId = collectionId || collectionClaimId;
const navigateUrl =
formatLbryUrlForWeb(canonicalUrl || uri || '/') + (listId ? generateListSearchUrlParams(listId) : '');
if (listId) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, listId);
navigateUrl = navigateUrl + `?` + collectionParams.toString();
}
const navLinkProps = {
to: navigateUrl,
onClick: (e) => e.stopPropagation(),
@@ -120,7 +123,6 @@ function ClaimPreviewTile(props: Props) {
const isChannel = claim && claim.value_type === 'channel';
const channelUri = !isChannel ? signingChannel && signingChannel.permanent_url : claim && claim.permanent_url;
const channelTitle = signingChannel && ((signingChannel.value && signingChannel.value.title) || signingChannel.name);
const repostedChannelUri = isRepost && isChannel ? permanentUrl || canonicalUrl : undefined;
// Aria-label value for claim preview
let ariaLabelData = isChannel ? title : formatClaimPreviewTitle(title, channelTitle, date, mediaDuration);
@@ -248,7 +250,7 @@ function ClaimPreviewTile(props: Props) {
<div className="claim-tile__info">
{isChannel ? (
<div className="claim-tile__about--channel">
<SubscribeButton uri={repostedChannelUri || uri} />
<SubscribeButton uri={uri} />
</div>
) : (
<React.Fragment>
+15 -5
View File
@@ -1,13 +1,17 @@
import { connect } from 'react-redux';
import {
makeSelectClaimIsMine,
makeSelectClaimForUri,
selectMyChannelClaims,
makeSelectClaimIsPending,
makeSelectCollectionIsMine,
makeSelectEditedCollectionForId,
} from 'lbry-redux';
import { makeSelectCostInfoForUri } from 'lbryinc';
import { doToast } from 'redux/actions/notifications';
import { doOpenModal } from 'redux/actions/app';
import { selectListShuffle } from 'redux/selectors/content';
import { doToggleShuffleList, doToggleLoopList } from 'redux/actions/content';
import { doPlayUri, doSetPlayingUri, doToggleShuffleList, doToggleLoopList } from 'redux/actions/content';
import CollectionActions from './view';
const select = (state, props) => {
@@ -27,23 +31,29 @@ const select = (state, props) => {
const shuffleList = selectListShuffle(state);
const shuffle = shuffleList && shuffleList.collectionId === collectionId && shuffleList.newUrls;
const playNextUri = shuffle && shuffle[0];
const playNextClaim = makeSelectClaimForUri(playNextUri)(state);
return {
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
myChannels: selectMyChannelClaims(state),
claimIsPending: makeSelectClaimIsPending(props.uri)(state),
isMyCollection: makeSelectCollectionIsMine(collectionId)(state),
collectionHasEdits: Boolean(makeSelectEditedCollectionForId(collectionId)(state)),
firstItem,
playNextUri,
playNextClaim,
};
};
const perform = (dispatch) => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
doToggleShuffleList: (collectionId, shuffle) => {
dispatch(doToggleLoopList(collectionId, false, true));
dispatch(doToggleShuffleList(undefined, collectionId, shuffle, true));
},
doToast: (options) => dispatch(doToast(options)),
doPlayUri: (uri) => dispatch(doPlayUri(uri)),
doSetPlayingUri: (uri) => dispatch(doSetPlayingUri({ uri })),
doToggleShuffleList: (collectionId, shuffle) => dispatch(doToggleShuffleList(undefined, collectionId, shuffle, true)),
doToggleLoopList: (collectionId, loop) => dispatch(doToggleLoopList(collectionId, loop)),
});
export default connect(select, perform)(CollectionActions);
+24 -12
View File
@@ -11,12 +11,15 @@ import { useHistory } from 'react-router';
import { EDIT_PAGE, PAGE_VIEW_QUERY } from 'page/collection/view';
import classnames from 'classnames';
import { ENABLE_FILE_REACTIONS } from 'config';
import { formatLbryUrlForWeb, generateListSearchUrlParams } from 'util/url';
import { COLLECTIONS_CONSTS } from 'lbry-redux';
import { formatLbryUrlForWeb } from 'util/url';
type Props = {
uri: string,
claim: StreamClaim,
openModal: (id: string, {}) => void,
openModal: (id: string, { uri: string, claimIsMine?: boolean, isSupport?: boolean }) => void,
myChannels: ?Array<ChannelClaim>,
doToast: ({ message: string }) => void,
claimIsPending: boolean,
isMyCollection: boolean,
collectionId: string,
@@ -25,7 +28,11 @@ type Props = {
collectionHasEdits: boolean,
isBuiltin: boolean,
doToggleShuffleList: (string, boolean) => void,
doToggleLoopList: (string, boolean) => void,
playNextUri: string,
playNextClaim: StreamClaim,
doPlayUri: (string) => void,
doSetPlayingUri: (string) => void,
firstItem: string,
};
@@ -42,7 +49,11 @@ function CollectionActions(props: Props) {
collectionHasEdits,
isBuiltin,
doToggleShuffleList,
doToggleLoopList,
playNextUri,
playNextClaim,
doPlayUri,
doSetPlayingUri,
firstItem,
} = props;
const [doShuffle, setDoShuffle] = React.useState(false);
@@ -52,23 +63,23 @@ function CollectionActions(props: Props) {
const webShareable = true; // collections have cost?
const doPlay = React.useCallback(
(playUri) => {
const navigateUrl = formatLbryUrlForWeb(playUri);
push({
pathname: navigateUrl,
search: generateListSearchUrlParams(collectionId),
state: { forceAutoplay: true },
});
(uri) => {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
const navigateUrl = formatLbryUrlForWeb(uri) + `?` + collectionParams.toString();
push(navigateUrl);
doSetPlayingUri(uri);
doPlayUri(uri);
},
[collectionId, push]
[collectionId, push, doSetPlayingUri, doPlayUri]
);
React.useEffect(() => {
if (playNextUri && doShuffle) {
if (playNextClaim && doShuffle) {
setDoShuffle(false);
doPlay(playNextUri);
}
}, [doPlay, doShuffle, playNextUri]);
}, [doPlay, doShuffle, playNextClaim, playNextUri]);
const lhsSection = (
<>
@@ -79,6 +90,7 @@ function CollectionActions(props: Props) {
title={__('Play')}
onClick={() => {
doToggleShuffleList(collectionId, false);
doToggleLoopList(collectionId, false);
doPlay(firstItem);
}}
/>
@@ -45,7 +45,7 @@ export default function CollectionContent(props: Props) {
<span className="file-page__recommended-collection__row">
<Button
button="alt"
title={__('Loop')}
title="Loop"
icon={ICONS.REPEAT}
iconColor={loop && 'blue'}
className="button--file-action"
@@ -53,7 +53,7 @@ export default function CollectionContent(props: Props) {
/>
<Button
button="alt"
title={__('Shuffle')}
title="Shuffle"
icon={ICONS.SHUFFLE}
iconColor={shuffle && 'blue'}
className="button--file-action"
+2 -3
View File
@@ -17,10 +17,10 @@ import {
makeSelectClaimIdsForCollectionId,
ACTIONS as LBRY_REDUX_ACTIONS,
} from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app';
import CollectionForm from './view';
import { selectActiveChannelClaim, selectIncognito } from 'redux/selectors/app';
import { doSetActiveChannel, doSetIncognito } from 'redux/actions/app';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
@@ -44,11 +44,10 @@ const select = (state, props) => ({
});
const perform = (dispatch) => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
publishCollectionUpdate: (params) => dispatch(doCollectionPublishUpdate(params)),
publishCollection: (params, collectionId) => dispatch(doCollectionPublish(params, collectionId)),
clearCollectionErrors: () => dispatch({ type: LBRY_REDUX_ACTIONS.CLEAR_COLLECTION_ERRORS }),
setActiveChannel: (claimId) => dispatch(doSetActiveChannel(claimId)),
setIncognito: (incognito) => dispatch(doSetIncognito(incognito)),
});
export default connect(select, perform)(CollectionForm);
+61 -114
View File
@@ -10,9 +10,9 @@ import ChannelSelector from 'component/channelSelector';
import ClaimList from 'component/claimList';
import Card from 'component/common/card';
import LbcSymbol from 'component/common/lbc-symbol';
import SelectThumbnail from 'component/selectThumbnail';
import ThumbnailPicker from 'component/thumbnailPicker';
import { useHistory } from 'react-router-dom';
import { isNameValid, regexInvalidURI, THUMBNAIL_STATUSES } from 'lbry-redux';
import { isNameValid, regexInvalidURI } from 'lbry-redux';
import { Tabs, TabList, Tab, TabPanels, TabPanel } from 'component/common/tabs';
import { FormField } from 'component/common/form';
import { handleBidChange } from 'util/publish';
@@ -21,7 +21,6 @@ import { INVALID_NAME_ERROR } from 'constants/claim';
import SUPPORTED_LANGUAGES from 'constants/supported_languages';
import * as PAGES from 'constants/pages';
import analytics from 'analytics';
const LANG_NONE = 'none';
const MAX_TAG_SELECT = 5;
@@ -40,20 +39,23 @@ type Props = {
tags: Array<string>,
locations: Array<string>,
languages: Array<string>,
collectionId: string,
collection: Collection,
collectionClaimIds: Array<string>,
collectionUrls: Array<string>,
publishCollectionUpdate: (CollectionUpdateParams) => Promise<any>,
updatingCollection: boolean,
updateError: string,
publishCollection: (CollectionPublishParams, string) => Promise<any>,
createError: string,
creatingCollection: boolean,
publishCollectionUpdate: (CollectionUpdateParams) => Promise<any>,
publishCollection: (CollectionPublishParams, string) => Promise<any>,
clearCollectionErrors: () => void,
onDone: (string) => void,
setActiveChannel: (string) => void,
setIncognito: (boolean) => void,
openModal: (
id: string,
{ onUpdate: (string) => void, assetName: string, helpText: string, currentValue: string, title: string }
) => void,
};
function CollectionForm(props: Props) {
@@ -70,8 +72,11 @@ function CollectionForm(props: Props) {
locations,
languages = [],
// rest
onDone,
publishCollectionUpdate,
updateError,
updatingCollection,
publishCollection,
creatingCollection,
createError,
disabled,
@@ -81,12 +86,7 @@ function CollectionForm(props: Props) {
collection,
collectionUrls,
collectionClaimIds,
publishCollectionUpdate,
publishCollection,
clearCollectionErrors,
setActiveChannel,
setIncognito,
onDone,
} = props;
const activeChannelName = activeChannelClaim && activeChannelClaim.name;
let prefix = IS_WEB ? `${DOMAIN}/` : 'lbry://';
@@ -95,27 +95,18 @@ function CollectionForm(props: Props) {
}
const activeChannelId = activeChannelClaim && activeChannelClaim.claim_id;
const collectionName = (claim && claim.name) || (collection && collection.name);
const collectionChannel = claim && claim.signing_channel ? claim.signing_channel.claim_id : undefined;
const hasClaim = !!claim;
const [initialized, setInitialized] = React.useState(false);
const [nameError, setNameError] = React.useState(undefined);
const [bidError, setBidError] = React.useState('');
const [thumbStatus, setThumbStatus] = React.useState('');
const [thumbError, setThumbError] = React.useState('');
const [params, setParams]: [any, (any) => void] = React.useState({});
const [params, setParams]: [any, (any) => void] = React.useState(getCollectionParams());
const name = params.name;
const isNewCollection = !uri;
const { replace } = useHistory();
const languageParam = params.languages || [];
const languageParam = params.languages;
const primaryLanguage = Array.isArray(languageParam) && languageParam.length && languageParam[0];
const secondaryLanguage = Array.isArray(languageParam) && languageParam.length >= 2 && languageParam[1];
const hasClaims = params.claims && params.claims.length;
const collectionClaimIdsString = JSON.stringify(collectionClaimIds);
const itemError = !hasClaims ? __('Cannot publish empty list') : '';
const thumbnailError =
(thumbError && thumbStatus !== THUMBNAIL_STATUSES.COMPLETE && __('Invalid thumbnail')) ||
(thumbStatus === THUMBNAIL_STATUSES.IN_PROGRESS && __('Please wait for thumbnail to finish uploading'));
const submitError = nameError || bidError || itemError || updateError || createError || thumbnailError;
function parseName(newName) {
let INVALID_URI_CHARS = new RegExp(regexInvalidURI, 'gu');
@@ -126,42 +117,6 @@ function CollectionForm(props: Props) {
setParams({ ...params, ...paramObj });
}
function updateParams(paramsObj) {
setParams({ ...params, ...paramsObj });
}
// TODO remove this or better decide whether app should delete languages[2+]
// This was added because a previous update setting was duplicating language codes
function dedupeLanguages(languages) {
if (languages.length <= 1) {
return languages;
} else if (languages.length === 2) {
if (languages[0] !== languages[1]) {
return languages;
} else {
return [languages[0]];
}
} else if (languages.length > 2) {
const newLangs = [];
languages.forEach((l) => {
if (!newLangs.includes(l)) {
newLangs.push(l);
}
});
return newLangs;
}
}
function handleUpdateThumbnail(update: { [string]: string }) {
if (update.thumbnail_url) {
setParam(update);
} else if (update.thumbnail_status) {
setThumbStatus(update.thumbnail_status);
} else {
setThumbError(update.thumbnail_error);
}
}
function getCollectionParams() {
const collectionParams: {
thumbnail_url?: string,
@@ -177,25 +132,41 @@ function CollectionForm(props: Props) {
claims: ?Array<string>,
} = {
thumbnail_url: thumbnailUrl,
name: parseName(collectionName),
description,
title: claim ? title : collectionName,
bid: String(amount || 0.001),
languages: languages ? dedupeLanguages(languages) : [],
languages: languages || [],
locations: locations || [],
tags: tags
? tags.map((tag) => {
return { name: tag };
})
: [],
claim_id: claim ? claim.claim_id : undefined,
channel_id: claim ? collectionChannel : activeChannelId || undefined,
claims: collectionClaimIds,
};
collectionParams['name'] = parseName(collectionName);
if (activeChannelId) {
collectionParams['channel_id'] = activeChannelId;
}
if (!claim) {
collectionParams['title'] = collectionName;
}
if (claim) {
collectionParams['claim_id'] = claim.claim_id;
collectionParams['title'] = title;
}
return collectionParams;
}
React.useEffect(() => {
const collectionClaimIds = JSON.parse(collectionClaimIdsString);
setParams({ ...params, claims: collectionClaimIds });
clearCollectionErrors();
}, [collectionClaimIdsString, setParams]);
function handleLanguageChange(index, code) {
let langs = [...languageParam];
if (index === 0) {
@@ -204,9 +175,6 @@ function CollectionForm(props: Props) {
langs = [];
} else {
langs[0] = code;
if (langs[0] === langs[1]) {
langs.length = 1;
}
}
} else {
if (code === LANG_NONE || code === langs[0]) {
@@ -218,6 +186,10 @@ function CollectionForm(props: Props) {
setParams({ ...params, languages: langs });
}
function handleThumbnailChange(thumbnailUrl: string) {
setParams({ ...params, thumbnail_url: thumbnailUrl });
}
function handleSubmit() {
if (uri) {
publishCollectionUpdate(params).then((pendingClaim) => {
@@ -238,12 +210,6 @@ function CollectionForm(props: Props) {
}
}
React.useEffect(() => {
const collectionClaimIds = JSON.parse(collectionClaimIdsString);
setParams({ ...params, claims: collectionClaimIds });
clearCollectionErrors();
}, [collectionClaimIdsString, setParams]);
React.useEffect(() => {
let nameError;
if (!name && name !== undefined) {
@@ -255,38 +221,19 @@ function CollectionForm(props: Props) {
setNameError(nameError);
}, [name]);
// on mount, if we get a collectionChannel, set it.
React.useEffect(() => {
if (hasClaim && !initialized) {
if (collectionChannel) {
setActiveChannel(collectionChannel);
setIncognito(false);
} else if (!collectionChannel && hasClaim) {
setIncognito(true);
}
setInitialized(true);
if (incognito) {
const newParams = Object.assign({}, params);
delete newParams.channel_id;
setParams(newParams);
} else if (activeChannelId) {
setParams({ ...params, channel_id: activeChannelId });
}
}, [setInitialized, setActiveChannel, collectionChannel, setIncognito, hasClaim, incognito, initialized]);
}, [activeChannelId, incognito, setParams]);
// every time activechannel or incognito changes, set it.
React.useEffect(() => {
if (initialized) {
if (activeChannelId) {
setParam({ channel_id: activeChannelId });
} else if (incognito) {
setParam({ channel_id: undefined });
}
}
}, [activeChannelId, incognito, initialized]);
const itemError = !params.claims.length ? __('Cannot publish empty list') : '';
const submitError = nameError || bidError || itemError || updateError || createError;
// setup initial params after we're sure if it's published or not
React.useEffect(() => {
if (!uri || (uri && hasClaim)) {
updateParams(getCollectionParams());
}
}, [uri, hasClaim]);
console.log('params', params);
return (
<>
<div className={classnames('main--contained', { 'card--disabled': disabled })}>
@@ -305,6 +252,11 @@ function CollectionForm(props: Props) {
<Card
body={
<>
<fieldset-group className="fieldset-group--smushed fieldset-group--disabled-prefix">
<fieldset-section>
<label htmlFor="channel_name">{__('Channel')}</label>
</fieldset-section>
</fieldset-group>
<fieldset-group class="fieldset-group--smushed fieldset-group--disabled-prefix">
<fieldset-section>
<label htmlFor="channel_name">{__('Name')}</label>
@@ -334,14 +286,11 @@ function CollectionForm(props: Props) {
value={params.title}
onChange={(e) => setParams({ ...params, title: e.target.value })}
/>
<fieldset-section>
<SelectThumbnail
thumbnailParam={params.thumbnail_url}
thumbnailParamError={thumbError}
thumbnailParamStatus={thumbStatus}
updateThumbnailParams={handleUpdateThumbnail}
/>
</fieldset-section>
<ThumbnailPicker
inline
thumbnailParam={params.thumbnail_url}
updateThumbnailParam={handleThumbnailChange}
/>
<FormField
type="markdown"
name="content_description2"
@@ -462,9 +411,7 @@ function CollectionForm(props: Props) {
<div className="section__actions">
<Button
button="primary"
disabled={
creatingCollection || updatingCollection || nameError || bidError || thumbnailError || !hasClaims
}
disabled={creatingCollection || updatingCollection || nameError || bidError || !params.claims.length}
label={creatingCollection || updatingCollection ? __('Submitting') : __('Submit')}
onClick={handleSubmit}
/>
+9 -11
View File
@@ -1,8 +1,8 @@
import { connect } from 'react-redux';
import { makeSelectNameForCollectionId } from 'lbry-redux';
import { doCollectionEdit, makeSelectNameForCollectionId, doCollectionDelete } from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app';
import { selectListShuffle } from 'redux/selectors/content';
import { doToggleLoopList, doToggleShuffleList } from 'redux/actions/content';
import { doSetPlayingUri, doToggleShuffleList } from 'redux/actions/content';
import CollectionMenuList from './view';
const select = (state, props) => {
@@ -17,12 +17,10 @@ const select = (state, props) => {
};
};
const perform = (dispatch) => ({
doOpenModal: (modal, props) => dispatch(doOpenModal(modal, props)),
doToggleShuffleList: (collectionId) => {
dispatch(doToggleLoopList(collectionId, false, true));
dispatch(doToggleShuffleList(undefined, collectionId, true, true));
},
});
export default connect(select, perform)(CollectionMenuList);
export default connect(select, {
doCollectionEdit,
doOpenModal,
doCollectionDelete,
doSetPlayingUri,
doToggleShuffleList,
})(CollectionMenuList);
+20 -11
View File
@@ -7,7 +7,8 @@ import { Menu, MenuButton, MenuList, MenuItem } from '@reach/menu-button';
import Icon from 'component/common/icon';
import * as PAGES from 'constants/pages';
import { useHistory } from 'react-router';
import { formatLbryUrlForWeb, generateListSearchUrlParams } from 'util/url';
import { formatLbryUrlForWeb } from 'util/url';
import { COLLECTIONS_CONSTS } from 'lbry-redux';
type Props = {
inline?: boolean,
@@ -15,26 +16,34 @@ type Props = {
collectionName?: string,
collectionId: string,
playNextUri: string,
doToggleShuffleList: (string) => void,
doSetPlayingUri: ({ uri: ?string }) => void,
doToggleShuffleList: (string, string, boolean, boolean) => void,
};
function CollectionMenuList(props: Props) {
const { inline = false, collectionId, collectionName, doOpenModal, playNextUri, doToggleShuffleList } = props;
const {
inline = false,
collectionId,
collectionName,
doOpenModal,
playNextUri,
doSetPlayingUri,
doToggleShuffleList,
} = props;
const [doShuffle, setDoShuffle] = React.useState(false);
const { push } = useHistory();
React.useEffect(() => {
if (playNextUri && doShuffle) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
const navigateUrl = formatLbryUrlForWeb(playNextUri) + `?` + collectionParams.toString();
setDoShuffle(false);
const navigateUrl = formatLbryUrlForWeb(playNextUri);
push({
pathname: navigateUrl,
search: generateListSearchUrlParams(collectionId),
state: { forceAutoplay: true },
});
doSetPlayingUri({ uri: playNextUri });
push(navigateUrl);
}
}, [collectionId, doShuffle, playNextUri, push]);
}, [push, doSetPlayingUri, collectionId, playNextUri, doShuffle]);
return (
<Menu>
@@ -59,7 +68,7 @@ function CollectionMenuList(props: Props) {
<MenuItem
className="comment__menu-option"
onSelect={() => {
doToggleShuffleList(collectionId);
doToggleShuffleList('', collectionId, true, true);
setDoShuffle(true);
}}
>
+9 -4
View File
@@ -7,7 +7,8 @@ import TruncatedText from 'component/common/truncated-text';
import CollectionCount from './collectionCount';
import CollectionPrivate from './collectionPrivate';
import CollectionMenuList from 'component/collectionMenuList';
import { formatLbryUrlForWeb, generateListSearchUrlParams } from 'util/url';
import { formatLbryUrlForWeb } from 'util/url';
import { COLLECTIONS_CONSTS } from 'lbry-redux';
import FileThumbnail from 'component/fileThumbnail';
type Props = {
@@ -61,12 +62,16 @@ function CollectionPreviewTile(props: Props) {
if (collectionId && hasClaim && resolveCollectionItems) {
resolveCollectionItems({ collectionId, page_size: 5 });
}
}, [collectionId, hasClaim, resolveCollectionItems]);
}, [collectionId, hasClaim]);
// const signingChannel = claim && claim.signing_channel;
const navigateUrl =
formatLbryUrlForWeb(collectionItemUrls[0] || '/') + (collectionId ? generateListSearchUrlParams(collectionId) : '');
let navigateUrl = formatLbryUrlForWeb(collectionItemUrls[0] || '/');
if (collectionId) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
navigateUrl = navigateUrl + `?` + collectionParams.toString();
}
function handleClick(e) {
if (navigateUrl) {
@@ -4,7 +4,6 @@ import {
selectMyPublishedPlaylistCollections,
selectMyUnpublishedCollections, // should probably distinguish types
// selectSavedCollections,
selectFetchingMyCollections,
} from 'lbry-redux';
import CollectionsListMine from './view';
@@ -13,7 +12,6 @@ const select = (state) => ({
publishedCollections: selectMyPublishedPlaylistCollections(state),
unpublishedCollections: selectMyUnpublishedCollections(state),
// savedCollections: selectSavedCollections(state),
fetchingCollections: selectFetchingMyCollections(state),
});
export default connect(select)(CollectionsListMine);
+2 -12
View File
@@ -18,7 +18,6 @@ type Props = {
publishedCollections: CollectionGroup,
unpublishedCollections: CollectionGroup,
// savedCollections: CollectionGroup,
fetchingCollections: boolean,
};
const ALL = 'All';
@@ -32,7 +31,6 @@ export default function CollectionsListMine(props: Props) {
publishedCollections,
unpublishedCollections,
// savedCollections, these are resolved on startup from sync'd claimIds or urls
fetchingCollections,
} = props;
const builtinCollectionsList = (Object.values(builtinCollections || {}): any);
@@ -131,10 +129,7 @@ export default function CollectionsListMine(props: Props) {
<div className="claim-grid__header section">
<h1 className="claim-grid__title">
{__('Playlists')}
{!hasCollections && !fetchingCollections && (
<div className="claim-grid__title--empty">{__('(Empty) --[indicates empty playlist]--')}</div>
)}
{!hasCollections && fetchingCollections && (
{!hasCollections && (
<div className="claim-grid__title--empty">{__('(Empty) --[indicates empty playlist]--')}</div>
)}
</h1>
@@ -179,16 +174,11 @@ export default function CollectionsListMine(props: Props) {
</div>
</div>
)}
{!hasCollections && !fetchingCollections && (
{!hasCollections && (
<div className="main--empty">
<Yrbl type={'sad'} title={__('You have no lists yet. Better start hoarding!')} />
</div>
)}
{!hasCollections && fetchingCollections && (
<div className="main--empty">
<h2 className="main--empty empty">{__('Loading...')}</h2>
</div>
)}
</div>
</>
);
-6
View File
@@ -2440,12 +2440,6 @@ export const icons = {
</svg>
),
[ICONS.PLAY]: buildIcon(<polygon points="5 3 19 12 5 21 5 3" />),
[ICONS.PLAY_PREVIOUS]: buildIcon(
<g>
<polygon points="19 20 9 12 19 4 19 20" />
<line x1="5" y1="19" x2="5" y2="5" />
</g>
),
[ICONS.REPLAY]: buildIcon(
<g>
<polyline points="1 4 1 10 7 10" />
+9 -15
View File
@@ -10,18 +10,16 @@ const PAGINATE_PARAM = 'page';
type Props = {
totalPages: number,
location: { search: string },
history: { push: (string) => void },
onPageChange?: (number) => void,
disableHistory?: boolean, // Disables the use of '&page=' param and history stack.
history: { push: string => void },
onPageChange?: number => void,
};
function Paginate(props: Props) {
const { totalPages = 1, location, history, onPageChange, disableHistory } = props;
const { totalPages = 1, location, history, onPageChange } = props;
const { search } = location;
const [textValue, setTextValue] = React.useState('');
const urlParams = new URLSearchParams(search);
const initialPage = disableHistory ? 1 : Number(urlParams.get(PAGINATE_PARAM)) || 1;
const [currentPage, setCurrentPage] = React.useState(initialPage);
const currentPage = Number(urlParams.get(PAGINATE_PARAM)) || 1;
const isMobile = useIsMobile();
function handleChangePage(newPageNumber: number) {
@@ -30,13 +28,9 @@ function Paginate(props: Props) {
}
if (currentPage !== newPageNumber) {
setCurrentPage(newPageNumber);
if (!disableHistory) {
const params = new URLSearchParams(search);
params.set(PAGINATE_PARAM, newPageNumber.toString());
history.push('?' + params.toString());
}
const params = new URLSearchParams(search);
params.set(PAGINATE_PARAM, newPageNumber.toString());
history.push('?' + params.toString());
}
}
@@ -64,7 +58,7 @@ function Paginate(props: Props) {
nextClassName="pagination__item pagination__item--next"
breakClassName="pagination__item pagination__item--break"
marginPagesDisplayed={2}
onPageChange={(e) => handleChangePage(e.selected + 1)}
onPageChange={e => handleChangePage(e.selected + 1)}
forcePage={currentPage - 1}
initialPage={currentPage - 1}
containerClassName="pagination"
@@ -73,7 +67,7 @@ function Paginate(props: Props) {
{!isMobile && (
<FormField
value={textValue}
onChange={(e) => setTextValue(e.target.value)}
onChange={e => setTextValue(e.target.value)}
className="paginate-channel"
label={__('Go to page:')}
type="text"
+5 -5
View File
@@ -12,12 +12,12 @@ type Props = {
uri: string,
thumbnail: string,
claim: ?Claim,
doResolveUri: (string) => void,
doFetchCostInfoForUri: (string) => void,
doResolveUri: string => void,
doFetchCostInfoForUri: string => void,
costInfo: ?{ cost: number },
floatingPlayerEnabled: boolean,
doPlayUri: (string, ?boolean, ?boolean, (GetResponse) => void) => void,
doAnaltyicsPurchaseEvent: (GetResponse) => void,
doAnaltyicsPurchaseEvent: GetResponse => void,
parentCommentId?: string,
isMarkdownPost: boolean,
doSetPlayingUri: ({}) => void,
@@ -69,8 +69,8 @@ export default function EmbedPlayButton(props: Props) {
const formattedUrl = formatLbryUrlForWeb(uri);
push(formattedUrl);
} else {
doPlayUri(uri, undefined, undefined, (fileInfo) => {
let playingOptions = { uri, pathname, source: undefined, commentId: undefined };
doPlayUri(uri, undefined, undefined, fileInfo => {
let playingOptions: PlayingUri = { uri, pathname };
if (parentCommentId) {
playingOptions.source = 'comment';
playingOptions.commentId = parentCommentId;
+2 -24
View File
@@ -4,9 +4,6 @@ import {
makeSelectTitleForUri,
makeSelectStreamingUrlForUri,
makeSelectClaimIsNsfw,
makeSelectClaimWasPurchased,
makeSelectNextUrlForCollectionAndUrl,
makeSelectPreviousUrlForCollectionAndUrl,
SETTINGS,
} from 'lbry-redux';
import {
@@ -16,10 +13,8 @@ import {
makeSelectFileRenderModeForUri,
} from 'redux/selectors/content';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { makeSelectCostInfoForUri } from 'lbryinc';
import { doPlayUri, doSetPlayingUri } from 'redux/actions/content';
import { doSetPlayingUri } from 'redux/actions/content';
import { doFetchRecommendedContent } from 'redux/actions/search';
import { doAnaltyicsPurchaseEvent } from 'redux/actions/app';
import { withRouter } from 'react-router';
import FileRenderFloating from './view';
@@ -35,16 +30,12 @@ const select = (state, props) => {
playingUri,
title: makeSelectTitleForUri(uri)(state),
fileInfo: makeSelectFileInfoForUri(uri)(state),
mature: makeSelectClaimIsNsfw(uri)(state),
mature: makeSelectClaimIsNsfw(props.uri)(state),
isFloating: makeSelectIsPlayerFloating(props.location)(state),
streamingUrl: makeSelectStreamingUrlForUri(uri)(state),
floatingPlayerEnabled: makeSelectClientSetting(SETTINGS.FLOATING_PLAYER)(state),
renderMode: makeSelectFileRenderModeForUri(uri)(state),
videoTheaterMode: makeSelectClientSetting(SETTINGS.VIDEO_THEATER_MODE)(state),
costInfo: makeSelectCostInfoForUri(uri)(state),
claimWasPurchased: makeSelectClaimWasPurchased(uri)(state),
nextListUri: collectionId && makeSelectNextUrlForCollectionAndUrl(collectionId, uri)(state),
previousListUri: collectionId && makeSelectPreviousUrlForCollectionAndUrl(collectionId, uri)(state),
collectionId,
};
};
@@ -52,19 +43,6 @@ const select = (state, props) => {
const perform = (dispatch) => ({
closeFloatingPlayer: () => dispatch(doSetPlayingUri({ uri: null })),
doFetchRecommendedContent: (uri, mature) => dispatch(doFetchRecommendedContent(uri, mature)),
doPlayUri: (uri, collectionId, hideFailModal) =>
dispatch(
doPlayUri(
uri,
false,
false,
(fileInfo) => {
dispatch(doAnaltyicsPurchaseEvent(fileInfo));
},
hideFailModal
),
dispatch(doSetPlayingUri({ uri, collectionId }))
),
});
export default withRouter(connect(select, perform)(FileRenderFloating));
+36 -93
View File
@@ -11,12 +11,10 @@ import usePersistedState from 'effects/use-persisted-state';
import { PRIMARY_PLAYER_WRAPPER_CLASS } from 'page/file/view';
import Draggable from 'react-draggable';
import { onFullscreenChange } from 'util/full-screen';
import { generateListSearchUrlParams, formatLbryUrlForWeb } from 'util/url';
import { useIsMobile } from 'effects/use-screensize';
import debounce from 'util/debounce';
import { useHistory } from 'react-router';
import { isURIEqual } from 'lbry-redux';
import AutoplayCountdown from 'component/autoplayCountdown';
import { isURIEqual, COLLECTIONS_CONSTS } from 'lbry-redux';
const IS_DESKTOP_MAC = typeof process === 'object' ? process.platform === 'darwin' : false;
const DEBOUNCE_WINDOW_RESIZE_HANDLER_MS = 60;
@@ -36,12 +34,7 @@ type Props = {
primaryUri: ?string,
videoTheaterMode: boolean,
doFetchRecommendedContent: (string, boolean) => void,
doPlayUri: (string, string, boolean) => void,
collectionId: string,
costInfo: any,
claimWasPurchased: boolean,
nextListUri: string,
previousListUri: string,
};
export default function FileRenderFloating(props: Props) {
@@ -59,23 +52,16 @@ export default function FileRenderFloating(props: Props) {
primaryUri,
videoTheaterMode,
doFetchRecommendedContent,
doPlayUri,
collectionId,
costInfo,
claimWasPurchased,
nextListUri,
previousListUri,
} = props;
const { location, push } = useHistory();
const hideFloatingPlayer = location.state && location.state.hideFloatingPlayer;
const {
location: { pathname },
} = useHistory();
const isMobile = useIsMobile();
const mainFilePlaying = !isFloating && isURIEqual(uri, primaryUri);
const mainFilePlaying = playingUri && isURIEqual(playingUri.uri, primaryUri);
const [fileViewerRect, setFileViewerRect] = useState();
const [desktopPlayStartTime, setDesktopPlayStartTime] = useState();
const [wasDragging, setWasDragging] = useState(false);
const [doNavigate, setDoNavigate] = useState(false);
const [playNextUrl, setPlayNextUrl] = useState(true);
const [countdownCanceled, setCountdownCanceled] = useState(false);
const [position, setPosition] = usePersistedState('floating-file-viewer:position', {
x: -25,
y: window.innerHeight - 400,
@@ -85,11 +71,13 @@ export default function FileRenderFloating(props: Props) {
y: 0,
});
const navigateUrl =
playingUri && playingUri.primaryUri + (collectionId ? generateListSearchUrlParams(collectionId) : '');
let navigateUrl;
if (collectionId) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
navigateUrl = uri + `?` + collectionParams.toString();
}
const isFree = costInfo && costInfo.cost === 0;
const canViewFile = isFree || claimWasPurchased;
const playingUriSource = playingUri && playingUri.source;
const isPlayable = RENDER_MODES.FLOATING_MODES.includes(renderMode);
const isReadyToPlay = isPlayable && (streamingUrl || (fileInfo && fileInfo.completed));
@@ -114,7 +102,7 @@ export default function FileRenderFloating(props: Props) {
}
}
const clampToScreen = React.useCallback((pos) => {
function clampToScreen(pos) {
const ESTIMATED_SCROLL_BAR_PX = 50;
const FLOATING_PLAYER_CLASS = 'content__viewer--floating';
const fpPlayerElem = document.querySelector(`.${FLOATING_PLAYER_CLASS}`);
@@ -127,7 +115,7 @@ export default function FileRenderFloating(props: Props) {
pos.y = getScreenHeight() - fpPlayerElem.getBoundingClientRect().height;
}
}
}, []);
}
// Updated 'relativePos' based on persisted 'position':
const stringifiedPosition = JSON.stringify(position);
@@ -151,11 +139,11 @@ export default function FileRenderFloating(props: Props) {
setPosition({ x: pos.x, y: pos.y });
}
}
}, [clampToScreen, isFloating, position.x, position.y, setPosition, stringifiedPosition]);
}, [isFloating, stringifiedPosition]);
// Listen to main-window resizing and adjust the fp position accordingly:
useEffect(() => {
const handleMainWindowResize = debounce(() => {
const handleMainWindowResize = debounce((e) => {
let newPos = {
x: Math.round(relativePos.x * getScreenWidth()),
y: Math.round(relativePos.y * getScreenHeight()),
@@ -169,18 +157,20 @@ export default function FileRenderFloating(props: Props) {
// 'relativePos' is needed in the dependency list to avoid stale closure.
// Otherwise, this could just be changed to a one-time effect.
}, [clampToScreen, relativePos.x, relativePos.y, setPosition]);
}, [relativePos]);
const handleResize = React.useCallback(() => {
function handleResize() {
const element = mainFilePlaying
? document.querySelector(`.${PRIMARY_PLAYER_WRAPPER_CLASS}`)
: document.querySelector(`.${INLINE_PLAYER_WRAPPER_CLASS}`);
if (!element) return;
if (!element) {
return;
}
const rect = element.getBoundingClientRect();
// getBoundingClientRect returns a DomRect, not an object
// getBoundingCLientRect returns a DomRect, not an object
const objectRect = {
top: rect.top,
right: rect.right,
@@ -194,14 +184,13 @@ export default function FileRenderFloating(props: Props) {
// $FlowFixMe
setFileViewerRect({ ...objectRect, windowOffset: window.pageYOffset });
}, [mainFilePlaying]);
}
useEffect(() => {
if (playingUri && playingUri.primaryUri) {
if (streamingUrl) {
handleResize();
setCountdownCanceled(false);
}
}, [handleResize, playingUri, videoTheaterMode]);
}, [streamingUrl, pathname, playingUriSource, isFloating, mainFilePlaying]);
useEffect(() => {
handleResize();
@@ -212,7 +201,7 @@ export default function FileRenderFloating(props: Props) {
window.removeEventListener('resize', handleResize);
onFullscreenChange(window, 'remove', handleResize);
};
}, [handleResize]);
}, [setFileViewerRect, isFloating, playingUriSource, mainFilePlaying, videoTheaterMode]);
useEffect(() => {
// @if TARGET='app'
@@ -230,46 +219,13 @@ export default function FileRenderFloating(props: Props) {
if (isFloating) {
doFetchRecommendedContent(uri, mature);
}
}, [doFetchRecommendedContent, isFloating, mature, uri]);
}, [uri, mature, isFloating]);
const doPlay = React.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, true);
}
},
[collectionId, doPlayUri, isFloating, push]
);
useEffect(() => {
if (!doNavigate) return;
if (playNextUrl && nextListUri) {
doPlay(nextListUri);
} else if (previousListUri) {
doPlay(previousListUri);
}
setPlayNextUrl(true);
}, [doNavigate, doPlay, nextListUri, playNextUrl, previousListUri]);
if (
!isPlayable ||
!uri ||
(isFloating && (isMobile || !floatingPlayerEnabled || hideFloatingPlayer)) ||
(collectionId && !isFloating && ((!canViewFile && !nextListUri) || countdownCanceled))
) {
if (!isPlayable || !uri || (isFloating && (isMobile || !floatingPlayerEnabled))) {
return null;
}
function handleDragStart() {
function handleDragStart(e, ui) {
// Not really necessary, but reset just in case 'handleStop' didn't fire.
setWasDragging(false);
}
@@ -285,7 +241,7 @@ export default function FileRenderFloating(props: Props) {
});
}
function handleDragStop(e) {
function handleDragStop(e, ui) {
if (wasDragging) {
e.stopPropagation();
setWasDragging(false);
@@ -351,30 +307,17 @@ export default function FileRenderFloating(props: Props) {
// @endif
/>
) : (
<>
{collectionId && !canViewFile ? (
<div className="content__loading">
<AutoplayCountdown
nextRecommendedUri={nextListUri}
doNavigate={() => setDoNavigate(true)}
doReplay={() => doPlayUri(uri, collectionId, false)}
doPrevious={() => {
setPlayNextUrl(false);
setDoNavigate(true);
}}
onCanceled={() => setCountdownCanceled(true)}
skipPaid
/>
</div>
) : (
<LoadingScreen status={loadingMessage} />
)}
</>
<LoadingScreen status={loadingMessage} />
)}
{isFloating && (
<div className="draggable content__info">
<div className="claim-preview__title" title={title || uri}>
<Button label={title || uri} navigate={navigateUrl} button="link" className="content__floating-link" />
<Button
label={title || uri}
navigate={navigateUrl || uri}
button="link"
className="content__floating-link"
/>
</div>
<UriIndicator link uri={uri} />
</div>
+7 -2
View File
@@ -4,6 +4,7 @@ import {
makeSelectFileInfoForUri,
makeSelectThumbnailForUri,
makeSelectClaimForUri,
makeSelectStreamingUrlForUri,
makeSelectClaimWasPurchased,
SETTINGS,
COLLECTIONS_CONSTS,
@@ -15,6 +16,7 @@ import { withRouter } from 'react-router';
import {
makeSelectIsPlaying,
makeSelectShouldObscurePreview,
selectPlayingUri,
makeSelectInsufficientCreditsForUri,
makeSelectFileRenderModeForUri,
} from 'redux/selectors/content';
@@ -31,8 +33,11 @@ const select = (state, props) => {
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
obscurePreview: makeSelectShouldObscurePreview(props.uri)(state),
isPlaying: makeSelectIsPlaying(props.uri)(state),
playingUri: selectPlayingUri(state),
insufficientCredits: makeSelectInsufficientCreditsForUri(props.uri)(state),
streamingUrl: makeSelectStreamingUrlForUri(props.uri)(state),
autoplay: makeSelectClientSetting(SETTINGS.AUTOPLAY_MEDIA)(state),
hasCostInfo: Boolean(makeSelectCostInfoForUri(props.uri)(state)),
costInfo: makeSelectCostInfoForUri(props.uri)(state),
renderMode: makeSelectFileRenderModeForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state),
@@ -43,9 +48,9 @@ const select = (state, props) => {
};
const perform = (dispatch) => ({
play: (uri, collectionId, isPlayable) => {
play: (uri, collectionId) => {
dispatch(doSetPrimaryUri(uri));
if (isPlayable) dispatch(doSetPlayingUri({ uri, collectionId }));
dispatch(doSetPlayingUri({ uri, collectionId }));
dispatch(doPlayUri(uri, undefined, undefined, (fileInfo) => dispatch(doAnaltyicsPurchaseEvent(fileInfo))));
},
});
+23 -17
View File
@@ -16,16 +16,18 @@ import Nag from 'component/common/nag';
import FileRenderPlaceholder from 'static/img/fileRenderPlaceholder.png';
type Props = {
play: (string, string, boolean) => void,
play: (string, string) => void,
isLoading: boolean,
isPlaying: boolean,
fileInfo: FileListItem,
uri: string,
history: { push: (string) => void },
location: { search: ?string, pathname: string, href: string, state: { forceAutoplay: boolean } },
location: { search: ?string, pathname: string },
obscurePreview: boolean,
insufficientCredits: boolean,
claimThumbnail?: string,
autoplay: boolean,
hasCostInfo: boolean,
costInfo: any,
inline: boolean,
renderMode: string,
@@ -48,6 +50,7 @@ export default function FileRenderInitiator(props: Props) {
location,
claimThumbnail,
renderMode,
hasCostInfo,
costInfo,
claimWasPurchased,
authenticated,
@@ -55,20 +58,24 @@ export default function FileRenderInitiator(props: Props) {
collectionId,
} = props;
// check if there is a time or autoplay parameter, if so force autoplay
const urlTimeParam = location && location.href && location.href.indexOf('t=') > -1;
const forceAutoplayParam = location && location.state && location.state.forceAutoplay;
const autoplay = forceAutoplayParam || urlTimeParam || props.autoplay;
// force autoplay if a timestamp is present
let autoplay = props.autoplay;
// get current url
const url = window.location.href;
// check if there is a time parameter, if so force autoplay
if (url.indexOf('t=') > -1) {
autoplay = true;
}
const isFree = costInfo && costInfo.cost === 0;
const canViewFile = isFree || claimWasPurchased;
const cost = costInfo && costInfo.cost;
const isFree = hasCostInfo && cost === 0;
const fileStatus = fileInfo && fileInfo.status;
const isPlayable = RENDER_MODES.FLOATING_MODES.includes(renderMode);
const isText = RENDER_MODES.TEXT_MODES.includes(renderMode);
const [thumbnail, setThumbnail] = React.useState(FileRenderPlaceholder);
const containerRef = React.useRef<any>();
useEffect(() => {
React.useEffect(() => {
if (claimThumbnail) {
setTimeout(() => {
let newThumbnail = claimThumbnail;
@@ -89,7 +96,7 @@ export default function FileRenderInitiator(props: Props) {
}
}, 200);
}
}, [claimThumbnail, thumbnail]);
}, [claimThumbnail]);
function doAuthRedirect() {
history.push(`/$/${PAGES.AUTH}?redirect=${encodeURIComponent(location.pathname)}`);
@@ -103,9 +110,9 @@ export default function FileRenderInitiator(props: Props) {
e.stopPropagation();
}
play(uri, collectionId, isPlayable);
play(uri, collectionId);
},
[play, uri, isPlayable, collectionId]
[play, uri, collectionId]
);
useEffect(() => {
@@ -130,20 +137,19 @@ export default function FileRenderInitiator(props: Props) {
useEffect(() => {
const videoOnPage = document.querySelector('video');
if (
(canViewFile || forceAutoplayParam) &&
((autoplay && (!videoOnPage || forceAutoplayParam) && isPlayable) ||
RENDER_MODES.AUTO_RENDER_MODES.includes(renderMode))
(isFree || claimWasPurchased) &&
((autoplay && !videoOnPage && isPlayable) || RENDER_MODES.AUTO_RENDER_MODES.includes(renderMode))
) {
viewFile();
}
}, [autoplay, canViewFile, forceAutoplayParam, isPlayable, renderMode, viewFile]);
}, [autoplay, viewFile, isFree, renderMode, isPlayable, claimWasPurchased]);
/*
once content is playing, let the appropriate <FileRender> take care of it...
but for playables, always render so area can be used to fill with floating player
*/
if (isPlaying && !isPlayable) {
if (canViewFile && !collectionId) {
if (isFree || claimWasPurchased) {
return null;
}
}
@@ -1,14 +1,12 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri } from 'lbry-redux';
import { makeSelectViewCountForUri } from 'lbryinc';
import { selectLanguage } from 'redux/selectors/settings';
import FileViewCountInline from './view';
const select = (state, props) => {
return {
claim: makeSelectClaimForUri(props.uri)(state),
viewCount: makeSelectViewCountForUri(props.uri)(state),
lang: selectLanguage(state),
};
};
+4 -15
View File
@@ -7,28 +7,17 @@ type Props = {
// --- select ---
claim: ?StreamClaim,
viewCount: string,
lang: ?string,
};
export default function FileViewCountInline(props: Props) {
const { isLivestream, claim, viewCount, lang } = props;
let formattedViewCount;
try {
formattedViewCount = Number(viewCount).toLocaleString(lang || 'en', {
compactDisplay: 'short',
notation: 'compact',
});
} catch (err) {
// No soup for you!
formattedViewCount = Number(viewCount).toLocaleString();
}
const { isLivestream, claim, viewCount } = props;
const formattedViewCount = Number(viewCount).toLocaleString();
if (!viewCount || (claim && claim.repost_url) || isLivestream) {
// (1) Currently, makeSelectViewCountForUri doesn't differentiate between
// un-fetched view-count vs zero view-count. But since it's probably not
// unfetched view-count vs zero view-count. But since it's probably not
// ideal to highlight that a view has 0 count, let's just not show anything.
// (2) No idea how to get the repost source's claim ID from the repost claim,
// (2) No idea how to get the repost src's claim ID from the repost claim,
// so hiding it for now.
return null;
}
+1 -1
View File
@@ -39,7 +39,7 @@ export default function LivestreamLayout(props: Props) {
{Boolean(chatDisabled) && (
<div className="help--notice">
{channelName
? __('%channel% has disabled chat for this stream. Enjoy the stream!', { channel: channelName })
? __('%channelName% has disabled chat for this stream. Enjoy the stream!', { channelName })
: __('This channel has disabled chat for this stream. Enjoy the stream!')}
</div>
)}
+8 -6
View File
@@ -1,3 +1,4 @@
import { DOMAIN } from 'config';
import { connect } from 'react-redux';
import { doSetDaemonSetting } from 'redux/actions/settings';
import { doSetWelcomeVersion, doToggle3PAnalytics, doSignOut } from 'redux/actions/app';
@@ -9,16 +10,17 @@ import { version as appVersion } from 'package.json';
import PrivacyAgreement from './view';
const select = (state) => ({
const select = state => ({
authenticated: selectUserVerifiedEmail(state),
});
const perform = (dispatch) => ({
setWelcomeVersion: (version) => dispatch(doSetWelcomeVersion(version || WELCOME_VERSION)),
setShareDataInternal: (share) => dispatch(doSetDaemonSetting(DAEMON_SETTINGS.SHARE_USAGE_DATA, share)),
setShareDataThirdParty: (share) => dispatch(doToggle3PAnalytics(share)),
const perform = dispatch => ({
setWelcomeVersion: version => dispatch(doSetWelcomeVersion(version || WELCOME_VERSION)),
setShareDataInternal: share => dispatch(doSetDaemonSetting(DAEMON_SETTINGS.SHARE_USAGE_DATA, share)),
setShareDataThirdParty: share => dispatch(doToggle3PAnalytics(share)),
signOut: () => dispatch(doSignOut()),
authenticateIfSharingData: () => dispatch(doAuthenticate(appVersion, undefined, undefined, true)), // appVersion, shareData?, shareCallback, callInstall
authenticateIfSharingData: () =>
dispatch(doAuthenticate(appVersion, undefined, undefined, true, undefined, undefined, DOMAIN)),
});
export default connect(select, perform)(PrivacyAgreement);
+2 -3
View File
@@ -46,11 +46,10 @@ function PublishFormErrors(props: Props) {
{!bid && <div>{__('A deposit amount is required')}</div>}
{bidError && <div>{__('Please check your deposit amount.')}</div>}
{isUploadingThumbnail && <div>{__('Please wait for thumbnail to finish uploading')}</div>}
{!isUploadingThumbnail && !thumbnail ? (
{!isUploadingThumbnail && !thumbnail && (
<div>{__('A thumbnail is required. Please upload or provide an image URL above.')}</div>
) : (
thumbnailError && !thumbnailUploaded && <div>{__('Thumbnail is invalid.')}</div>
)}
{thumbnailError && !thumbnailUploaded && <div>{__('Thumbnail is invalid.')}</div>}
{editingURI && !isStillEditing && !filePath && (
<div>{__('Please reselect a file after changing the LBRY URL')}</div>
)}
+8 -4
View File
@@ -6,19 +6,23 @@ import {
selectFileInfosByOutpoint,
doResetThumbnailStatus,
} from 'lbry-redux';
import { doOpenModal } from 'redux/actions/app';
import PublishPage from './view';
const select = (state) => ({
const select = state => ({
...selectPublishFormValues(state),
fileInfos: selectFileInfosByOutpoint(state),
myClaimForUri: selectMyClaimForUri(state),
});
const perform = (dispatch) => ({
updatePublishForm: (value) => dispatch(doUpdatePublishForm(value)),
const perform = dispatch => ({
updatePublishForm: value => dispatch(doUpdatePublishForm(value)),
resetThumbnailStatus: () => dispatch(doResetThumbnailStatus()),
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
});
export default connect(select, perform)(PublishPage);
export default connect(
select,
perform
)(PublishPage);
+138 -150
View File
@@ -18,178 +18,166 @@ type Props = {
uploadThumbnailStatus: string,
thumbnailPath: ?string,
thumbnailError: ?string,
thumbnailParam: ?string,
thumbnailParamError: boolean,
thumbnailParamStatus: string,
openModal: (id: string, {}) => void,
updatePublishForm: ({}) => void,
updateThumbnailParams: ({}) => void,
resetThumbnailStatus: () => void,
};
function SelectThumbnail(props: Props) {
const {
filePath,
fileInfos,
myClaimForUri,
formDisabled,
uploadThumbnailStatus: status,
openModal,
updatePublishForm,
thumbnailParam,
thumbnailParamStatus,
updateThumbnailParams,
thumbnailPath,
resetThumbnailStatus,
} = props;
const publishForm = !updateThumbnailParams;
const thumbnail = publishForm ? props.thumbnail : thumbnailParam;
const thumbnailError = publishForm ? props.thumbnailError : props.thumbnailParamError;
const accept = '.png, .jpg, .jpeg, .gif';
const manualInput = status === THUMBNAIL_STATUSES.API_DOWN || status === THUMBNAIL_STATUSES.MANUAL;
const thumbUploaded = status === THUMBNAIL_STATUSES.COMPLETE && thumbnail;
const isUrlInput = thumbnail !== ThumbnailMissingImage && thumbnail !== ThumbnailBrokenImage;
const outpoint = myClaimForUri ? `${myClaimForUri.txid}:${myClaimForUri.nout}` : undefined;
const fileInfo = outpoint ? fileInfos[outpoint] : undefined;
const downloadPath = fileInfo ? fileInfo.download_path : undefined;
const actualFilePath = filePath || downloadPath;
let isSupportedVideo = false;
if (typeof actualFilePath === 'string') {
isSupportedVideo = Lbry.getMediaType(null, actualFilePath) === 'video';
} else if (actualFilePath && actualFilePath.type) {
isSupportedVideo = actualFilePath.type.split('/')[0] === 'video';
class SelectThumbnail extends React.PureComponent<Props> {
constructor() {
super();
(this: any).handleThumbnailChange = this.handleThumbnailChange.bind(this);
}
function handleThumbnailChange(e: SyntheticInputEvent<*>) {
handleThumbnailChange(e: SyntheticInputEvent<*>) {
const { updatePublishForm } = this.props;
const newThumbnail = e.target.value.replace(' ', '');
if (updateThumbnailParams) {
updateThumbnailParams({ thumbnail_url: newThumbnail });
updatePublishForm({
thumbnail: newThumbnail,
thumbnailError: newThumbnail.startsWith('data:image'),
});
}
render() {
const {
filePath,
fileInfos,
myClaimForUri,
thumbnail,
formDisabled,
uploadThumbnailStatus: status,
openModal,
updatePublishForm,
thumbnailPath,
thumbnailError,
resetThumbnailStatus,
} = this.props;
const accept = '.png, .jpg, .jpeg, .gif';
const outpoint = myClaimForUri ? `${myClaimForUri.txid}:${myClaimForUri.nout}` : undefined;
const fileInfo = outpoint ? fileInfos[outpoint] : undefined;
const downloadPath = fileInfo ? fileInfo.download_path : undefined;
const actualFilePath = filePath || downloadPath;
let isSupportedVideo = false;
if (typeof actualFilePath === 'string') {
isSupportedVideo = Lbry.getMediaType(null, actualFilePath) === 'video';
} else if (actualFilePath && actualFilePath.type) {
isSupportedVideo = actualFilePath.type.split('/')[0] === 'video';
}
let thumbnailInputSrc;
if (!thumbnail) {
thumbnailInputSrc = ThumbnailMissingImage;
} else if (thumbnailError) {
thumbnailInputSrc = ThumbnailBrokenImage;
} else {
updatePublishForm({ thumbnail: newThumbnail });
thumbnailInputSrc = thumbnail;
}
}
React.useEffect(() => {
if (updateThumbnailParams && status !== thumbnailParamStatus) {
updateThumbnailParams({ thumbnail_status: status });
}
}, [status, thumbnailParamStatus, updateThumbnailParams]);
/*
Note:
We are using backgroundImage instead of an <img /> to zoom if the selected thumbnail isn't
the proper aspect ratio. This is to avoid blackbars on the side of images and inconsistent thumbnails
We still need to render the image to see if there is an error loading the url
*/
let thumbnailSrc;
if (!thumbnail) {
thumbnailSrc = ThumbnailMissingImage;
} else if (thumbnailError) {
thumbnailSrc =
(manualInput && ThumbnailBrokenImage) || (status !== THUMBNAIL_STATUSES.COMPLETE && ThumbnailMissingImage);
} else {
thumbnailSrc = thumbnail;
}
/*
Note:
We are using backgroundImage instead of an <img /> to zoom if the selected thumbnail isn't
the proper aspect ratio. This is to avoid blackbars on the side of images and inconsistent thumbnails
We still need to render the image to see if there is an error loading the url
*/
const thumbPreview = (
<div className="column__item thumbnail-picker__preview" style={{ backgroundImage: `url(${String(thumbnailSrc)})` }}>
{thumbUploaded && thumbnailError !== false && __('This will be visible in a few minutes.')}
<img
style={{ display: 'none' }}
src={thumbnail}
alt={__('Thumbnail Preview')}
onError={() =>
publishForm
? updatePublishForm({ thumbnailError: true })
: updateThumbnailParams({ thumbnail_error: Boolean(thumbnail) })
}
onLoad={() =>
publishForm
? updatePublishForm({ thumbnailError: !isUrlInput })
: updateThumbnailParams({ thumbnail_error: !isUrlInput })
}
/>
</div>
);
return (
<>
{status !== THUMBNAIL_STATUSES.IN_PROGRESS && (
<div className="column">
{thumbPreview}
{publishForm && thumbUploaded ? (
<div className="column__item">
<p>{__('Upload complete.')}</p>
<div className="section__actions">
<Button button="link" label={__('New thumbnail')} onClick={resetThumbnailStatus} />
</div>
return (
<div>
{status === THUMBNAIL_STATUSES.API_DOWN || status === THUMBNAIL_STATUSES.MANUAL ? (
<div className="column">
<div className="column__item thumbnail-preview" style={{ backgroundImage: `url(${thumbnailInputSrc})` }}>
<img
style={{ display: 'none' }}
src={thumbnailInputSrc}
alt={__('Thumbnail Preview')}
onError={() => updatePublishForm({ thumbnailError: true })}
/>
</div>
) : (
<div className="column__item">
{manualInput ? (
<FormField
type="text"
name="content_thumbnail"
label="URL"
placeholder="https://images.fbi.gov/alien"
value={thumbnail}
disabled={formDisabled}
onChange={handleThumbnailChange}
/>
) : (
<FileSelector
currentPath={thumbnailPath}
label={__('Thumbnail')}
placeholder={__('Choose an enticing thumbnail')}
accept={accept}
onFileChosen={(file) =>
openModal(MODALS.CONFIRM_THUMBNAIL_UPLOAD, {
file,
cb: (url) => !publishForm && updateThumbnailParams({ thumbnail_url: url }),
})
}
/>
)}
<FormField
type="text"
name="content_thumbnail"
label="URL"
placeholder="https://images.fbi.gov/alien"
value={thumbnail}
disabled={formDisabled}
onChange={this.handleThumbnailChange}
/>
<div className="card__actions">
<Button
button="link"
label={manualInput ? __('Use thumbnail upload tool') : __('Enter a thumbnail URL')}
onClick={() =>
updatePublishForm({
uploadThumbnailStatus: manualInput ? THUMBNAIL_STATUSES.READY : THUMBNAIL_STATUSES.MANUAL,
})
}
label={__('Use thumbnail upload tool')}
onClick={() => updatePublishForm({ uploadThumbnailStatus: THUMBNAIL_STATUSES.READY })}
/>
{status === THUMBNAIL_STATUSES.READY && isSupportedVideo && IS_WEB && (
// Disabled on desktop until this is resolved
// https://github.com/electron/electron/issues/20750#issuecomment-709505902
<Button
button="link"
label={__('Take a snapshot from your video')}
onClick={() => openModal(MODALS.AUTO_GENERATE_THUMBNAIL, { filePath: actualFilePath })}
/>
)}
</div>
</div>
)}
</div>
)}
</div>
) : (
<React.Fragment>
{status === THUMBNAIL_STATUSES.READY && (
<FileSelector
currentPath={thumbnailPath}
label={__('Thumbnail')}
placeholder={__('Choose an enticing thumbnail')}
accept={accept}
onFileChosen={(file) => openModal(MODALS.CONFIRM_THUMBNAIL_UPLOAD, { file })}
/>
)}
{status === THUMBNAIL_STATUSES.COMPLETE && thumbnail && (
<div className="column column--space-between">
<div className="column__item thumbnail-preview" style={{ backgroundImage: `url(${thumbnail})` }}>
{(thumbnailError !== false) && __('This will be visible in a few minutes.')}
<img
style={{ display: 'none' }}
src={thumbnail}
alt={__('Thumbnail Preview')}
onError={() => updatePublishForm({ thumbnailError: true })}
onLoad={() => updatePublishForm({ thumbnailError: false })}
/>
</div>
<div className="column__item">
<p>{__('Upload complete.')}</p>
<div className="section__actions">
<Button button="link" label={__('New thumbnail')} onClick={resetThumbnailStatus} />
</div>
</div>
</div>
)}
</React.Fragment>
)}
{status === THUMBNAIL_STATUSES.READY && (
<div className="section__actions">
<Button
button="link"
label={__('Enter a thumbnail URL')}
onClick={() => updatePublishForm({ uploadThumbnailStatus: THUMBNAIL_STATUSES.MANUAL })}
/>
{isSupportedVideo && IS_WEB && (
// Disabled on desktop until this is resolved
// https://github.com/electron/electron/issues/20750#issuecomment-709505902
<Button
button="link"
label={__('Take a snapshot from your video')}
onClick={() => openModal(MODALS.AUTO_GENERATE_THUMBNAIL, { filePath: actualFilePath })}
/>
)}
</div>
)}
{status === THUMBNAIL_STATUSES.IN_PROGRESS && <p>{__('Uploading thumbnail')}...</p>}
{!thumbUploaded && (
<p className="help">
{manualInput
? __('Enter a URL for your thumbnail.')
: __('Upload your thumbnail to %domain%. Recommended size is 16:9.', { domain: DOMAIN })}
</p>
)}
</>
);
{status === THUMBNAIL_STATUSES.IN_PROGRESS && <p>{__('Uploading thumbnail')}...</p>}
{status !== THUMBNAIL_STATUSES.COMPLETE && (
<p className="help">
{status === THUMBNAIL_STATUSES.API_DOWN
? __('Enter a URL for your thumbnail.')
: __('Upload your thumbnail to %domain%. Recommended size is 16:9.', { domain: DOMAIN })}
</p>
)}
</div>
);
}
}
export default SelectThumbnail;
+1 -1
View File
@@ -220,7 +220,7 @@ export default function SettingContent(props: Props) {
const HELP = {
FLOATING_PLAYER: 'Keep content playing in the corner when navigating to a different page.',
AUTOPLAY_MEDIA: 'Autoplay video and audio files when navigating to a file.',
AUTOPLAY_NEXT: 'Autoplay the next related item when a file (video or audio) finishes playing.',
AUTOPLAY_NEXT: 'Autoplay video and audio files as the next related item when a file finishes playing.',
HIDE_REPOSTS: 'You will not see reposts by people you follow or receive email notifying about them.',
SHOW_MATURE: 'Mature content may include nudity, intense sexuality, profanity, or other adult content. By displaying mature content, you are affirming you are of legal age to view mature content in your country or jurisdiction. ',
MAX_PURCHASE_PRICE: 'This will prevent you from purchasing any content over a certain cost, as a safety measure.',
+13 -15
View File
@@ -35,22 +35,20 @@ function SettingLanguage(props: Props) {
return (
<React.Fragment>
{!previousLanguage && (
<FormField
name="language_select"
type="select"
onChange={onLanguageChange}
value={language || getDefaultLanguage()}
>
{sortLanguageMap(SUPPORTED_LANGUAGES).map(([langKey, langName]) => (
<option key={langKey} value={langKey}>
{langName}
</option>
))}
</FormField>
)}
{previousLanguage && <Spinner type="small" />}
<FormField
name="language_select"
type="select"
onChange={onLanguageChange}
value={language || getDefaultLanguage()}
>
{sortLanguageMap(SUPPORTED_LANGUAGES).map(([langKey, langName]) => (
<option key={langKey} value={langKey}>
{langName}
</option>
))}
</FormField>
</React.Fragment>
);
}
+1 -5
View File
@@ -56,11 +56,7 @@ export default function SettingsSideNavigation() {
const TOP_MARGIN_PX = 20;
const element = document.getElementById(section);
if (element) {
window.scrollTo({
top: element.offsetTop - TOP_MARGIN_PX,
left: 0,
behavior: 'smooth',
});
window.scrollTo(0, element.offsetTop - TOP_MARGIN_PX);
}
}
+13
View File
@@ -0,0 +1,13 @@
import { connect } from 'react-redux';
import ThumbnailPicker from './view';
import { makeSelectThumbnailForUri } from 'lbry-redux';
const select = (state, props) => ({
thumbnailForUri: makeSelectThumbnailForUri(props.uri)(state),
});
// const perform = dispatch => ({
// });
export default connect(select)(ThumbnailPicker);
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.7 KiB

+116
View File
@@ -0,0 +1,116 @@
// @flow
import * as React from 'react';
import Card from 'component/common/card';
import ThumbnailMissingImage from './thumbnail-missing.png';
import SelectAsset from 'component/selectAsset';
type Props = {
// uploadThumbnailStatus: string,
thumbnailParam: string,
thumbnailForUri: string,
updateThumbnailParam: (string) => void,
inline?: boolean,
};
const ThumbnailPicker = (props: Props) => {
const { thumbnailForUri, thumbnailParam, updateThumbnailParam, inline } = props;
// uploadThumbnailStatus
// {status === THUMBNAIL_STATUSES.API_DOWN || status === THUMBNAIL_STATUSES.MANUAL ? (
// {status === THUMBNAIL_STATUSES.READY && (
// {status === THUMBNAIL_STATUSES.COMPLETE && thumbnail && (
const [thumbError, setThumbError] = React.useState(false); // possibly existing URL
const updateThumb = (thumb: string) => {
setThumbError(false);
updateThumbnailParam(thumb);
};
if (inline) {
return (
<fieldset-section>
<label>{__('Thumbnail')}</label>
<div className="column">
{thumbError && (
<div
className="column__item thumbnail-picker__preview"
style={{ backgroundImage: `url(${ThumbnailMissingImage})` }}
/>
)}
{!thumbError && (
<div
className="column__item thumbnail-picker__preview"
style={{ backgroundImage: `url(${thumbnailParam || thumbnailForUri})` }}
>
<img
style={{ display: 'none' }}
src={thumbnailParam || thumbnailForUri}
alt={__('Thumbnail Preview')}
onError={() => {
if (thumbnailParam) {
setThumbError(true);
}
}}
/>
</div>
)}
<div className="column__item">
{/* if upload */}
<SelectAsset
inline
onUpdate={updateThumb}
currentValue={thumbnailParam}
assetName={'Image'}
recommended={__('(16:9)')}
/>
</div>
</div>
</fieldset-section>
);
}
return (
<div>
<Card
body={
<div className="column">
{thumbError && (
<div
className="column__item thumbnail-preview"
style={{ backgroundImage: `url(${ThumbnailMissingImage})` }}
/>
)}
{!thumbError && (
<div
className="column__item thumbnail-preview"
style={{ backgroundImage: `url(${thumbnailParam || thumbnailForUri})` }}
>
<img
style={{ display: 'none' }}
src={thumbnailParam || thumbnailForUri}
alt={__('Thumbnail Preview')}
onError={() => {
if (thumbnailParam) {
setThumbError(true);
}
}}
/>
</div>
)}
<div className="column__item">
{/* if upload */}
<SelectAsset
inline
onUpdate={updateThumb}
currentValue={thumbnailParam}
assetName={'Thumbnail'}
recommended={__('(16:9)')}
/>
</div>
</div>
}
/>
</div>
);
};
export default ThumbnailPicker;
+2 -2
View File
@@ -57,8 +57,8 @@ class UriIndicator extends React.PureComponent<Props> {
}
const isChannelClaim = claim.value_type === 'channel';
const signingChannel = claim.signing_channel && claim.signing_channel.amount;
if (!signingChannel && !isChannelClaim) {
if (!claim.signing_channel && !isChannelClaim) {
if (hideAnonymous) {
return null;
}
+12 -28
View File
@@ -1,19 +1,14 @@
import { connect } from 'react-redux';
import {
makeSelectClaimForUri,
makeSelectFileInfoForUri,
makeSelectThumbnailForUri,
SETTINGS,
COLLECTIONS_CONSTS,
makeSelectNextUrlForCollectionAndUrl,
makeSelectPreviousUrlForCollectionAndUrl,
} from 'lbry-redux';
import {
doChangeVolume,
doChangeMute,
doAnalyticsView,
doAnalyticsBuffer,
doAnaltyicsPurchaseEvent,
} from 'redux/actions/app';
import { doChangeVolume, doChangeMute, doAnalyticsView, doAnalyticsBuffer } from 'redux/actions/app';
import { selectVolume, selectMute } from 'redux/selectors/app';
import { savePosition, clearPosition, doPlayUri, doSetPlayingUri } from 'redux/actions/content';
import {
@@ -39,7 +34,6 @@ const select = (state, props) => {
const userId = selectUser(state) && selectUser(state).id;
const playingUri = selectPlayingUri(state);
const collectionId = urlParams.get(COLLECTIONS_CONSTS.COLLECTION_ID) || (playingUri && playingUri.collectionId);
const isMarkdownOrComment = playingUri && (playingUri.source === 'markdown' || playingUri.source === 'comment');
let nextRecommendedUri;
let previousListUri;
@@ -51,23 +45,24 @@ const select = (state, props) => {
}
return {
position,
userId,
collectionId,
nextRecommendedUri,
previousListUri,
isMarkdownOrComment,
autoplayIfEmbedded: Boolean(autoplay),
autoplayNext: makeSelectClientSetting(SETTINGS.AUTOPLAY_NEXT)(state),
autoplayMedia: Boolean(makeSelectClientSetting(SETTINGS.AUTOPLAY_MEDIA)(state)),
autoplayNext: Boolean(makeSelectClientSetting(SETTINGS.AUTOPLAY_NEXT)(state)),
volume: selectVolume(state),
muted: selectMute(state),
videoPlaybackRate: makeSelectClientSetting(SETTINGS.VIDEO_PLAYBACK_RATE)(state),
position: position,
hasFileInfo: Boolean(makeSelectFileInfoForUri(uri)(state)),
thumbnail: makeSelectThumbnailForUri(uri)(state),
claim: makeSelectClaimForUri(uri)(state),
homepageData: selectHomepageData(state),
authenticated: selectUserVerifiedEmail(state),
userId: userId,
shareTelemetry: IS_WEB || selectDaemonSettings(state).share_usage_data,
isFloating: makeSelectIsPlayerFloating(props.location)(state),
collectionId,
nextRecommendedUri,
previousListUri,
videoTheaterMode: makeSelectClientSetting(SETTINGS.VIDEO_THEATER_MODE)(state),
};
};
@@ -83,19 +78,8 @@ const perform = (dispatch) => ({
toggleVideoTheaterMode: () => dispatch(toggleVideoTheaterMode()),
toggleAutoplayNext: () => dispatch(toggleAutoplayNext()),
setVideoPlaybackRate: (rate) => dispatch(doSetClientSetting(SETTINGS.VIDEO_PLAYBACK_RATE, rate)),
doPlayUri: (uri, collectionId) =>
dispatch(
doPlayUri(
uri,
false,
false,
(fileInfo) => {
dispatch(doAnaltyicsPurchaseEvent(fileInfo));
},
true
),
dispatch(doSetPlayingUri({ uri, collectionId }))
),
doPlayUri: (uri) => dispatch(doPlayUri(uri)),
doSetPlayingUri: (uri, collectionId) => dispatch(doSetPlayingUri({ uri, collectionId })),
});
export default withRouter(connect(select, perform)(VideoViewer));
@@ -151,8 +151,8 @@ const onPlayerReady = (player, options) => {
* Never shows if the endscreen plugin is present
*/
const mobileUi = function(options) {
// if (videojs.browser.IS_ANDROID || videojs.browser.IS_IOS) {
if (videojs.browser.IS_ANDROID) {
// target both iOS and Android
if (videojs.browser.IS_ANDROID || videojs.browser.IS_IOS) {
this.ready(() => {
onPlayerReady(this, videojs.mergeOptions(defaults, options));
});
@@ -283,10 +283,10 @@ export default React.memo<Props>(function VideoJs(props: Props) {
// as the listener to update static texts.
const setLabel = (controlBar, childName, label) => {
const c = controlBar.getChild(childName);
if (c) {
c.controlText(label);
}
// const c = controlBar.getChild(childName);
// if (c) {
// c.controlText(label);
// }
};
const player = playerRef.current;
+106 -73
View File
@@ -25,7 +25,8 @@ import I18nMessage from 'component/i18nMessage';
import { useHistory } from 'react-router';
import { getAllIds } from 'util/buildHomepage';
import type { HomepageCat } from 'util/buildHomepage';
import { formatLbryUrlForWeb, generateListSearchUrlParams } from 'util/url';
import { formatLbryUrlForWeb } from 'util/url';
import { COLLECTIONS_CONSTS } from 'lbry-redux';
const PLAY_TIMEOUT_ERROR = 'play_timeout_error';
const PLAY_TIMEOUT_LIMIT = 2000;
@@ -42,6 +43,7 @@ type Props = {
videoPlaybackRate: number,
volume: number,
uri: string,
autoplayMedia: boolean,
autoplayNext: boolean,
autoplayIfEmbedded: boolean,
desktopPlayStartTime?: number,
@@ -58,12 +60,12 @@ type Props = {
homepageData?: { [string]: HomepageCat },
shareTelemetry: boolean,
isFloating: boolean,
doPlayUri: (string, string) => void,
doPlayUri: (string) => void,
doSetPlayingUri: (string, string) => void,
collectionId: string,
nextRecommendedUri: string,
previousListUri: string,
videoTheaterMode: boolean,
isMarkdownOrComment: boolean,
};
/*
@@ -84,6 +86,7 @@ function VideoViewer(props: Props) {
uri,
muted,
volume,
autoplayMedia,
autoplayNext,
autoplayIfEmbedded,
doAnalyticsView,
@@ -101,12 +104,18 @@ function VideoViewer(props: Props) {
shareTelemetry,
isFloating,
doPlayUri,
doSetPlayingUri,
collectionId,
nextRecommendedUri,
previousListUri,
videoTheaterMode,
isMarkdownOrComment,
} = props;
const IS_IOS =
(/iPad|iPhone|iPod/.test(navigator.platform) ||
(navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1)) &&
!window.MSStream;
const permanentUrl = claim && claim.permanent_url;
const adApprovedChannelIds = homepageData ? getAllIds(homepageData) : [];
const claimId = claim && claim.claim_id;
@@ -180,81 +189,81 @@ function VideoViewer(props: Props) {
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);
let navigateUrl = formatLbryUrlForWeb(playUri);
if (collectionId) {
const collectionParams = new URLSearchParams();
collectionParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
navigateUrl = navigateUrl + `?` + collectionParams.toString();
clearPosition(playUri);
}
if (!isFloating) {
push(navigateUrl);
}
doPlayUri(playUri);
doSetPlayingUri(playUri, collectionId);
setDoNavigate(false);
},
[collectionId, doPlayUri, isFloating, push]
[clearPosition, collectionId, doPlayUri, doSetPlayingUri, isFloating, push]
);
useEffect(() => {
if (!doNavigate) return;
if (playNextUrl) {
if (permanentUrl !== nextRecommendedUri) {
if (nextRecommendedUri) {
if (collectionId) clearPosition(permanentUrl);
doPlay(nextRecommendedUri);
if (doNavigate) {
if (playNextUrl) {
if (permanentUrl !== nextRecommendedUri) {
if (nextRecommendedUri) doPlay(nextRecommendedUri);
} else {
setReplay(true);
}
} else {
setReplay(true);
}
} else {
if (videoNode) {
const currentTime = videoNode.currentTime;
if (videoNode) {
const currentTime = videoNode.currentTime;
if (currentTime <= 5) {
if (previousListUri && permanentUrl !== previousListUri) doPlay(previousListUri);
} else {
videoNode.currentTime = 0;
if (currentTime <= 5) {
if (previousListUri && permanentUrl !== previousListUri) doPlay(previousListUri);
} else {
videoNode.currentTime = 0;
}
setDoNavigate(false);
}
setDoNavigate(false);
}
if (!ended) setDoNavigate(false);
setEnded(false);
setPlayNextUrl(true);
}
if (!ended) setDoNavigate(false);
setEnded(false);
setPlayNextUrl(true);
}, [
clearPosition,
collectionId,
doNavigate,
doPlay,
ended,
nextRecommendedUri,
permanentUrl,
playNextUrl,
previousListUri,
videoNode,
]);
}, [doNavigate, doPlay, ended, nextRecommendedUri, permanentUrl, playNextUrl, previousListUri, videoNode]);
React.useEffect(() => {
if (!ended) return;
if (ended) {
analytics.videoIsPlaying(false);
analytics.videoIsPlaying(false);
if (adUrl) {
setAdUrl(null);
return;
}
if (adUrl) {
setAdUrl(null);
return;
if (embedded) {
setIsEndedEmbed(true);
} else if (!collectionId && autoplayNext) {
setShowAutoplayCountdown(true);
} else if (collectionId) {
setDoNavigate(true);
}
clearPosition(uri);
}
if (embedded) {
setIsEndedEmbed(true);
} else if (!collectionId && autoplayNext) {
setShowAutoplayCountdown(true);
} else if (collectionId) {
setDoNavigate(true);
}
clearPosition(uri);
}, [adUrl, autoplayNext, clearPosition, collectionId, embedded, ended, setAdUrl, uri]);
}, [
embedded,
setIsEndedEmbed,
autoplayMedia,
setShowAutoplayCountdown,
adUrl,
setAdUrl,
clearPosition,
uri,
ended,
collectionId,
autoplayNext,
]);
function onPlay(player) {
setEnded(false);
@@ -295,12 +304,12 @@ function VideoViewer(props: Props) {
const doPlayNext = () => {
setPlayNextUrl(true);
setEnded(true);
setDoNavigate(true);
};
const doPlayPrevious = () => {
setPlayNextUrl(false);
setEnded(true);
setDoNavigate(true);
};
const onPlayerReady = useCallback((player: Player, videoNode: any) => {
@@ -309,14 +318,12 @@ function VideoViewer(props: Props) {
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);
}
addTheaterModeButton(player, toggleVideoTheaterMode);
if (collectionId) {
addPlayNextButton(player, doPlayNext);
addPlayPreviousButton(player, doPlayPrevious);
} else {
addAutoplayNextButton(player, toggleAutoplayNext, autoplayNext);
}
}
@@ -334,6 +341,31 @@ function VideoViewer(props: Props) {
// player.muted(true);
// another version had player.play()
}
console.log('running here!')
} else {
console.log('running here123')
const isPaused = player.paused();
console.log('is paused');
console.log(isPaused)
if (IS_IOS && isPaused) {
document.getElementsByClassName('video-js--tap-to-unmute')[0].style.visibility = 'visible';
player.muted(true);
const iosResponse = player.play();
console.log(iosResponse)
}
setTimeout(function(){
console.log('running here124')
const isPaused = player.paused();
console.log('is paused');
console.log(isPaused)
if (IS_IOS && isPaused) {
document.getElementsByClassName('video-js--tap-to-unmute')[0].style.visibility = 'visible';
player.muted(true);
const iosResponse = player.play();
console.log(iosResponse)
}
}, 1000)
}
setIsLoading(false);
setIsPlaying(false);
@@ -396,6 +428,7 @@ function VideoViewer(props: Props) {
>
{showAutoplayCountdown && (
<AutoplayCountdown
uri={uri}
nextRecommendedUri={nextRecommendedUri}
doNavigate={() => setDoNavigate(true)}
doReplay={() => setReplay(true)}
+15 -21
View File
@@ -64,11 +64,7 @@ export default function WunderBarSuggestions(props: Props) {
customSelectAction,
} = props;
const inputRef: ElementRef<any> = React.useRef();
const viewResultsRef: ElementRef<any> = React.useRef();
const exploreTagRef: ElementRef<any> = React.useRef();
const isRefFocused = (ref) => ref && ref.current && ref.current === document.activeElement;
const isFocused = isRefFocused(inputRef) || isRefFocused(viewResultsRef) || isRefFocused(exploreTagRef);
const isFocused = inputRef && inputRef.current && inputRef.current === document.activeElement;
const {
push,
@@ -325,22 +321,6 @@ export default function WunderBarSuggestions(props: Props) {
className={classnames('wunderbar__suggestions', { 'wunderbar__suggestions--mobile': isMobile })}
>
<ComboboxList>
{!noBottomLinks && (
<div className="wunderbar__bottom-links">
<ComboboxOption value={term} className="wunderbar__more-results">
<Button ref={viewResultsRef} button="link" label={__('View All Results')} />
</ComboboxOption>
<ComboboxOption value={`${TAG_SEARCH_PREFIX}${term}`} className="wunderbar__more-results">
<Button ref={exploreTagRef} className="wunderbar__tag-search" button="link">
{__('Explore')}
<div className="tag">{term.split(' ').join('')}</div>
</Button>
</ComboboxOption>
</div>
)}
<hr className="wunderbar__top-separator" />
{uriFromQueryIsValid && !noTopSuggestion ? <WunderbarTopSuggestion query={nameFromQuery} /> : null}
<div className="wunderbar__label">{__('Search Results')}</div>
@@ -350,6 +330,20 @@ export default function WunderBarSuggestions(props: Props) {
{!showPlaceholder && results
? results.slice(0, isMobile ? 20 : 5).map((uri) => <WunderbarSuggestion key={uri} uri={uri} />)
: null}
{!noBottomLinks && (
<div className="wunderbar__bottom-links">
<ComboboxOption value={term} className="wunderbar__more-results">
<Button button="link" label={__('View All Results')} />
</ComboboxOption>
<ComboboxOption value={`${TAG_SEARCH_PREFIX}${term}`} className="wunderbar__more-results">
<Button className="wunderbar__tag-search" button="link">
{__('Explore')}
<div className="tag">{term.split(' ').join('')}</div>
</Button>
</ComboboxOption>
</div>
)}
</ComboboxList>
</ComboboxPopover>
)}
+1 -10
View File
@@ -1,8 +1,7 @@
export const PAGE_SIZE = 20;
export const FRESH_KEY = 'fresh';
export const ORDER_BY_KEY = 'order'; // Trending, Top, New
export const SORT_BY_KEY = 'sort'; // Newest vs Oldest First
export const ORDER_BY_KEY = 'order';
export const DURATION_KEY = 'duration';
export const LANGUAGE_KEY = 'language';
export const TAGS_KEY = 't';
@@ -40,14 +39,6 @@ export const DURATION_LONG = 'long';
export const DURATION_ALL = 'all';
export const DURATION_TYPES = [DURATION_ALL, DURATION_SHORT, DURATION_LONG];
export const SORT_BY = {
// key: Enumeration; can be anything as long as unique. Also used as URLParam.
// opt: Value to use for 'claim_search' options; for this case, it is the prefix to 'order_by'.
// str: Customer-facing string representation.
NEWEST: { key: 'new', opt: '', str: 'Newest first' },
OLDEST: { key: 'old', opt: '^', str: 'Oldest first' },
};
export const FILE_VIDEO = 'video';
export const FILE_AUDIO = 'audio';
export const FILE_DOCUMENT = 'document';
-1
View File
@@ -45,7 +45,6 @@ export const WEB = 'Globe';
export const SHARE = 'Share2';
export const EXTERNAL = 'ExternalLink';
export const PLAY = 'Play';
export const PLAY_PREVIOUS = 'Play Previous';
export const FACEBOOK = 'Facebook';
export const TWITTER = 'Twitter';
export const TELEGRAM = 'Telegram';
+17 -18
View File
@@ -14,7 +14,7 @@ import * as MODALS from 'constants/modal_types';
import React, { Fragment, useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { doLbryReady, doAutoUpdate, doOpenModal, doHideModal, doToggle3PAnalytics } from 'redux/actions/app';
import { doDaemonReady, doAutoUpdate, doOpenModal, doHideModal, doToggle3PAnalytics } from 'redux/actions/app';
import { Lbry, isURIValid, apiCall } from 'lbry-redux';
import { setSearchApi } from 'redux/actions/search';
import { doSetLanguage, doFetchLanguage, doUpdateIsNightAsync } from 'redux/actions/settings';
@@ -28,7 +28,12 @@ import { formatLbryUrlForWeb, formatInAppUrl } from 'util/url';
import { PersistGate } from 'redux-persist/integration/react';
import analytics from 'analytics';
import { doToast } from 'redux/actions/notifications';
import { getAuthToken, setAuthToken, doAuthTokenRefresh, deleteAuthToken, getTokens } from 'util/saved-passwords';
import {
getAuthToken,
setAuthToken,
doDeprecatedPasswordMigrationMarch2020,
doAuthTokenRefresh,
} from 'util/saved-passwords';
import { X_LBRY_AUTH_TOKEN } from 'constants/token';
import { LBRY_WEB_API, DEFAULT_LANGUAGE, LBRY_API_URL, LBRY_WEB_PUBLISH_API } from 'config';
@@ -107,34 +112,28 @@ if (process.env.SEARCH_API_URL) {
setSearchApi(process.env.SEARCH_API_URL);
}
// TODO KEYCLOAK
if (getTokens().auth_token) {
doAuthTokenRefresh();
}
// Fix to make sure old users' cookies are set to the correct domain
// This can be removed after March 11th, 2021
// https://github.com/lbryio/lbry-desktop/pull/3830
doDeprecatedPasswordMigrationMarch2020();
doAuthTokenRefresh();
// We need to override Lbryio for getting/setting the authToken
// We interact with ipcRenderer to get the auth key from a users keyring
// We keep a local variable for authToken because `ipcRenderer.send` does not
// contain a response, so there is no way to know when it's been set
let authToken;
Lbryio.setOverride('setAuthToken', (authToken) => {
setAuthToken(authToken); // set the cookie to auth_token=
setAuthToken(authToken);
return authToken;
});
Lbryio.setOverride('deleteAuthToken', () => deleteAuthToken());
Lbryio.setOverride(
'getTokens',
() =>
new Promise((resolve) => {
resolve(getTokens());
})
);
Lbryio.setOverride(
'getAuthToken',
() =>
new Promise((resolve) => {
resolve(getAuthToken());
const authTokenToReturn = authToken || getAuthToken();
resolve(authTokenToReturn);
})
);
@@ -267,7 +266,7 @@ function AppWrapper() {
app.store.dispatch(doFetchLanguage(DEFAULT_LANGUAGE));
}
app.store.dispatch(doUpdateIsNightAsync());
app.store.dispatch(doLbryReady()); // get tokens, users, startup stuff
app.store.dispatch(doDaemonReady());
app.store.dispatch(doBlackListedOutpointsSubscribe());
app.store.dispatch(doFilteredOutpointsSubscribe());
+5 -3
View File
@@ -15,9 +15,11 @@ const select = (state, props) => ({
const perform = (dispatch) => ({
closeModal: () => dispatch(doHideModal()),
commentModBlock: (a, b) => dispatch(doCommentModBlock(a, b)),
commentModBlockAsAdmin: (a, b, c) => dispatch(doCommentModBlockAsAdmin(a, b, c)),
commentModBlockAsModerator: (a, b, c, d) => dispatch(doCommentModBlockAsModerator(a, b, c, d)),
commentModBlock: (commenterUri, timeoutHours) => dispatch(doCommentModBlock(commenterUri, timeoutHours)),
commentModBlockAsAdmin: (commenterUri, blockerId, timeoutHours) =>
dispatch(doCommentModBlockAsAdmin(commenterUri, blockerId, timeoutHours)),
commentModBlockAsModerator: (commenterUri, creatorId, blockerId, timeoutHours) =>
dispatch(doCommentModBlockAsModerator(commenterUri, creatorId, blockerId, timeoutHours)),
});
export default connect(select, perform)(ModalBlockChannel);
+4 -14
View File
@@ -33,14 +33,9 @@ type Props = {
moderationDelegatorsById: { [string]: { global: boolean, delegators: { name: string, claimId: string } } },
// --- perform ---
closeModal: () => void,
commentModBlock: (commenterUri: string, timeoutSec: ?number) => void,
commentModBlockAsAdmin: (commenterUri: string, blockerId: string, timeoutSec: ?number) => void,
commentModBlockAsModerator: (
commenterUri: string,
creatorUri: string,
blockerId: string,
timeoutSec: ?number
) => void,
commentModBlock: (string, ?number) => void,
commentModBlockAsAdmin: (string, string, ?number) => void,
commentModBlockAsModerator: (string, string, string, ?number) => void,
};
export default function ModalBlockChannel(props: Props) {
@@ -232,12 +227,7 @@ export default function ModalBlockChannel(props: Props) {
case TAB.MODERATOR:
if (activeChannelClaim && contentChannelClaim) {
commentModBlockAsModerator(
commenterUri,
contentChannelClaim.permanent_url,
activeChannelClaim.claim_id,
duration
);
commentModBlockAsModerator(commenterUri, contentChannelClaim.claim_id, activeChannelClaim.claim_id, duration);
}
break;
@@ -3,10 +3,13 @@ import { doHideModal } from 'redux/actions/app';
import { doUploadThumbnail, doUpdatePublishForm } from 'lbry-redux';
import ModalConfirmThumbnailUpload from './view';
const perform = (dispatch) => ({
const perform = dispatch => ({
closeModal: () => dispatch(doHideModal()),
upload: (file, cb) => dispatch(doUploadThumbnail(null, file, null, null, file.path, cb)),
updatePublishForm: (value) => dispatch(doUpdatePublishForm(value)),
upload: file => dispatch(doUploadThumbnail(null, file, null, null, file.path)),
updatePublishForm: value => dispatch(doUpdatePublishForm(value)),
});
export default connect(null, perform)(ModalConfirmThumbnailUpload);
export default connect(
null,
perform
)(ModalConfirmThumbnailUpload);
@@ -4,18 +4,17 @@ import { Modal } from 'modal/modal';
import { DOMAIN } from 'config';
type Props = {
upload: WebFile => void,
file: WebFile,
upload: (WebFile, (string) => void) => void,
cb: (string) => void,
closeModal: () => void,
updatePublishForm: ({}) => void,
};
class ModalConfirmThumbnailUpload extends React.PureComponent<Props> {
upload() {
const { upload, updatePublishForm, cb, closeModal, file } = this.props;
const { upload, updatePublishForm, closeModal, file } = this.props;
if (file) {
upload(file, cb);
upload(file);
updatePublishForm({ thumbnailPath: file.path });
closeModal();
}
-3
View File
@@ -3,8 +3,6 @@ import React from 'react';
import { Modal } from 'modal/modal';
import LastReleaseChanges from 'component/lastReleaseChanges';
const IS_MAC = navigator.userAgent.indexOf('Mac OS X') !== -1;
type Props = {
downloadUpgrade: () => void,
skipUpgrade: () => void,
@@ -16,7 +14,6 @@ class ModalUpgrade extends React.PureComponent<Props> {
return (
<Modal
className={IS_MAC ? '' : 'main-wrapper--scrollbar'}
isOpen
contentLabel={__('Upgrade available')}
title={__('LBRY leveled up')}
+167 -81
View File
@@ -5,7 +5,7 @@ import React from 'react';
import classnames from 'classnames';
import moment from 'moment';
import humanizeDuration from 'humanize-duration';
import BlockList from 'component/blockList';
import ClaimList from 'component/claimList';
import ClaimPreview from 'component/claimPreview';
import Page from 'component/page';
import Spinner from 'component/spinner';
@@ -13,6 +13,7 @@ import Button from 'component/button';
import usePersistedState from 'effects/use-persisted-state';
import ChannelBlockButton from 'component/channelBlockButton';
import ChannelMuteButton from 'component/channelMuteButton';
import Yrbl from 'component/yrbl';
const VIEW = {
BLOCKED: 'blocked',
@@ -46,7 +47,7 @@ function ListBlocked(props: Props) {
personalTimeoutMap,
adminTimeoutMap,
moderatorTimeoutMap,
moderatorBlockListDelegatorsMap: delegatorsMap,
moderatorBlockListDelegatorsMap,
fetchingModerationBlockList,
fetchModBlockedList,
fetchModAmIList,
@@ -55,36 +56,55 @@ function ListBlocked(props: Props) {
} = props;
const [viewMode, setViewMode] = usePersistedState('blocked-muted:display', VIEW.BLOCKED);
const [localDelegatorsMap, setLocalDelegatorsMap] = React.useState(undefined);
// Keep a local list to allow for undoing actions in this component
const [localPersonalList, setLocalPersonalList] = React.useState(undefined);
const [localAdminList, setLocalAdminList] = React.useState(undefined);
const [localModeratorList, setLocalModeratorList] = React.useState(undefined);
const [localModeratorListDelegatorsMap, setLocalModeratorListDelegatorsMap] = React.useState(undefined);
const [localMutedList, setLocalMutedList] = React.useState(undefined);
const stringifiedDelegatorsMap = JSON.stringify(delegatorsMap);
const stringifiedLocalDelegatorsMap = JSON.stringify(localDelegatorsMap);
const hasLocalMuteList = localMutedList && localMutedList.length > 0;
const hasLocalPersonalList = localPersonalList && localPersonalList.length > 0;
const stringifiedMutedList = JSON.stringify(mutedUris);
const stringifiedPersonalList = JSON.stringify(personalBlockList);
const stringifiedAdminList = JSON.stringify(adminBlockList);
const stringifiedModeratorList = JSON.stringify(moderatorBlockList);
const stringifiedModeratorListDelegatorsMap = JSON.stringify(moderatorBlockListDelegatorsMap);
const stringifiedLocalAdminList = JSON.stringify(localAdminList);
const stringifiedLocalModeratorList = JSON.stringify(localModeratorList);
const stringifiedLocalModeratorListDelegatorsMap = JSON.stringify(localModeratorListDelegatorsMap);
const justMuted = localMutedList && mutedUris && localMutedList.length < mutedUris.length;
const justPersonalBlocked =
localPersonalList && personalBlockList && localPersonalList.length < personalBlockList.length;
const isAdmin =
myChannelClaims && myChannelClaims.some((c) => delegatorsById[c.claim_id] && delegatorsById[c.claim_id].global);
const isModerator =
myChannelClaims &&
myChannelClaims.some(
(c) => delegatorsById[c.claim_id] && Object.keys(delegatorsById[c.claim_id].delegators).length > 0
);
// **************************************************************************
const listForView = getLocalList(viewMode);
const showUris = listForView && listForView.length > 0;
function getList(view) {
function getLocalList(view) {
switch (view) {
case VIEW.BLOCKED:
return personalBlockList;
return localPersonalList;
case VIEW.ADMIN:
return adminBlockList;
return localAdminList;
case VIEW.MODERATOR:
return moderatorBlockList;
return localModeratorList;
case VIEW.MUTED:
return mutedUris;
return localMutedList;
}
}
function getActionButtons(uri) {
function getButtons(view, uri) {
const getDurationStr = (durationNs) => {
const NANO_TO_MS = 1000000;
return humanizeDuration(durationNs / NANO_TO_MS, { round: true });
@@ -107,7 +127,7 @@ function ListBlocked(props: Props) {
);
};
switch (viewMode) {
switch (view) {
case VIEW.BLOCKED:
return (
<>
@@ -126,21 +146,18 @@ function ListBlocked(props: Props) {
);
case VIEW.MODERATOR:
const delegatorUrisForBlockedUri = localDelegatorsMap && localDelegatorsMap[uri];
const delegatorUrisForBlockedUri = localModeratorListDelegatorsMap && localModeratorListDelegatorsMap[uri];
if (!delegatorUrisForBlockedUri) return null;
return (
<>
{delegatorUrisForBlockedUri.map((delegatorUri) => {
return (
<div className="block-list--delegator" key={delegatorUri}>
<label>{__('Blocked on behalf of:')}</label>
<ul className="section">
<div className="content__non-clickable">
<ClaimPreview uri={delegatorUri} hideMenu hideActions type="inline" properties={false} />
{moderatorTimeoutMap[uri] && getBanInfoElem(moderatorTimeoutMap[uri])}
</div>
<ChannelBlockButton uri={uri} blockLevel={BLOCK_LEVEL.MODERATOR} creatorUri={delegatorUri} />
<ul className="section content__non-clickable">
<ClaimPreview uri={delegatorUri} hideMenu hideActions type="small" />
</ul>
<ChannelBlockButton uri={uri} blockLevel={BLOCK_LEVEL.MODERATOR} creatorUri={delegatorUri} />
{moderatorTimeoutMap[uri] && getBanInfoElem(moderatorTimeoutMap[uri])}
</div>
);
})}
@@ -160,30 +177,26 @@ function ListBlocked(props: Props) {
function getHelpText(view) {
switch (view) {
case VIEW.BLOCKED:
return __(
"Blocked channels will be invisible to you in the app. They will not be able to comment on your content, nor reply to your comments left on other channels' content."
);
return "Blocked channels will be invisible to you in the app. They will not be able to comment on your content, nor reply to your comments left on other channels' content.";
case VIEW.ADMIN:
return __('This is the global block list.');
return 'This is the global block list.';
case VIEW.MODERATOR:
return __('List of channels that you have blocked as a moderator, along with the list of delegators.');
return 'List of channels that you have blocked as a moderator, along with the list of delegators.';
case VIEW.MUTED:
return __(
'Muted channels will be invisible to you in the app. They will not know they are muted and can still interact with you and your content.'
);
return 'Muted channels will be invisible to you in the app. They will not know they are muted and can still interact with you and your content.';
}
}
function getEmptyListTitle(view) {
switch (view) {
case VIEW.BLOCKED:
return __('You do not have any blocked channels');
return 'You do not have any blocked channels';
case VIEW.MUTED:
return __('You do not have any muted channels');
return 'You do not have any muted channels';
case VIEW.ADMIN:
return __('You do not have any globally-blocked channels');
return 'You do not have any globally-blocked channels';
case VIEW.MODERATOR:
return __('You do not have any blocked channels as a moderator');
return 'You do not have any blocked channels as a moderator';
}
}
@@ -205,43 +218,52 @@ function ListBlocked(props: Props) {
return source && (!local || local.length < source.length);
}
function getViewElem(view, label, icon) {
return (
<Button
icon={icon}
button="alt"
label={__(label)}
className={classnames(`button-toggle`, {
'button-toggle--active': viewMode === view,
})}
onClick={() => setViewMode(view)}
/>
);
}
function getRefreshElem() {
return (
<Button
icon={ICONS.REFRESH}
button="alt"
label={__('Refresh')}
onClick={() => {
fetchModBlockedList();
fetchModAmIList();
}}
/>
);
}
// **************************************************************************
React.useEffect(() => {
const jsonMutedChannels = stringifiedMutedList && JSON.parse(stringifiedMutedList);
if (!hasLocalMuteList && jsonMutedChannels && jsonMutedChannels.length > 0) {
setLocalMutedList(jsonMutedChannels);
}
}, [stringifiedMutedList, hasLocalMuteList]);
React.useEffect(() => {
if (stringifiedDelegatorsMap && isSourceListLarger(stringifiedDelegatorsMap, stringifiedLocalDelegatorsMap)) {
setLocalDelegatorsMap(JSON.parse(stringifiedDelegatorsMap));
const jsonBlockedChannels = stringifiedPersonalList && JSON.parse(stringifiedPersonalList);
if (!hasLocalPersonalList && jsonBlockedChannels && jsonBlockedChannels.length > 0) {
setLocalPersonalList(jsonBlockedChannels);
}
}, [stringifiedDelegatorsMap, stringifiedLocalDelegatorsMap]);
}, [stringifiedPersonalList, hasLocalPersonalList]);
// **************************************************************************
React.useEffect(() => {
if (stringifiedAdminList && isSourceListLarger(stringifiedAdminList, stringifiedLocalAdminList)) {
setLocalAdminList(JSON.parse(stringifiedAdminList));
}
}, [stringifiedAdminList, stringifiedLocalAdminList]);
React.useEffect(() => {
if (stringifiedModeratorList && isSourceListLarger(stringifiedModeratorList, stringifiedLocalModeratorList)) {
setLocalModeratorList(JSON.parse(stringifiedModeratorList));
}
}, [stringifiedModeratorList, stringifiedLocalModeratorList]);
React.useEffect(() => {
if (
stringifiedModeratorListDelegatorsMap &&
isSourceListLarger(stringifiedModeratorListDelegatorsMap, stringifiedLocalModeratorListDelegatorsMap)
) {
setLocalModeratorListDelegatorsMap(JSON.parse(stringifiedModeratorListDelegatorsMap));
}
}, [stringifiedModeratorListDelegatorsMap, stringifiedLocalModeratorListDelegatorsMap]);
React.useEffect(() => {
if (justMuted && stringifiedMutedList) {
setLocalMutedList(JSON.parse(stringifiedMutedList));
}
}, [stringifiedMutedList, justMuted, setLocalMutedList]);
React.useEffect(() => {
if (justPersonalBlocked && stringifiedPersonalList) {
setLocalPersonalList(JSON.parse(stringifiedPersonalList));
}
}, [stringifiedPersonalList, justPersonalBlocked, setLocalPersonalList]);
return (
<Page
@@ -260,23 +282,87 @@ function ListBlocked(props: Props) {
<>
<div className="section__header--actions">
<div className="section__actions--inline">
{getViewElem(VIEW.BLOCKED, 'Blocked', ICONS.BLOCK)}
{isAdmin && getViewElem(VIEW.ADMIN, 'Global', ICONS.BLOCK)}
{isModerator && getViewElem(VIEW.MODERATOR, 'Moderator', ICONS.BLOCK)}
{getViewElem(VIEW.MUTED, 'Muted', ICONS.MUTE)}
<Button
icon={ICONS.BLOCK}
button="alt"
label={__('Blocked')}
className={classnames(`button-toggle`, {
'button-toggle--active': viewMode === VIEW.BLOCKED,
})}
onClick={() => setViewMode(VIEW.BLOCKED)}
/>
{isAdmin && (
<Button
icon={ICONS.BLOCK}
button="alt"
label={__('Global')}
className={classnames(`button-toggle`, {
'button-toggle--active': viewMode === VIEW.ADMIN,
})}
onClick={() => setViewMode(VIEW.ADMIN)}
/>
)}
{isModerator && (
<Button
icon={ICONS.BLOCK}
button="alt"
label={__('Moderator')}
className={classnames(`button-toggle`, {
'button-toggle--active': viewMode === VIEW.MODERATOR,
})}
onClick={() => setViewMode(VIEW.MODERATOR)}
/>
)}
<Button
icon={ICONS.MUTE}
button="alt"
label={__('Muted')}
className={classnames(`button-toggle`, {
'button-toggle--active': viewMode === VIEW.MUTED,
})}
onClick={() => setViewMode(VIEW.MUTED)}
/>
</div>
<div className="section__actions--inline">
<Button
icon={ICONS.REFRESH}
button="alt"
label={__('Refresh')}
onClick={() => {
fetchModBlockedList();
fetchModAmIList();
}}
/>
</div>
<div className="section__actions--inline">{getRefreshElem()}</div>
</div>
<BlockList
key={viewMode}
uris={getList(viewMode)}
help={getHelpText(viewMode)}
titleEmptyList={getEmptyListTitle(viewMode)}
subtitle={getEmptyListSubtitle(viewMode)}
getActionButtons={getActionButtons}
className={viewMode === VIEW.MODERATOR ? 'block-list--moderator' : undefined}
/>
{showUris && <div className="help--notice">{getHelpText(viewMode)}</div>}
{showUris ? (
<div className={viewMode === VIEW.MODERATOR ? 'block-list--moderator' : 'block-list'}>
<ClaimList
uris={getLocalList(viewMode)}
showUnresolvedClaims
showHiddenByUser
hideMenu
renderActions={(claim) => {
return <div className="section__actions">{getButtons(viewMode, claim.permanent_url)}</div>;
}}
/>
</div>
) : (
<div className="main--empty">
<Yrbl
title={getEmptyListTitle(viewMode)}
subtitle={getEmptyListSubtitle(viewMode)}
actions={
<div className="section__actions">
<Button button="primary" label={__('Go Home')} navigate="/" />
</div>
}
/>
</div>
)}
</>
)}
</Page>
+6 -3
View File
@@ -6,7 +6,7 @@ import { ipcRenderer, remote } from 'electron';
import path from 'path';
import * as ACTIONS from 'constants/action_types';
import * as MODALS from 'constants/modal_types';
import { SIMPLE_SITE } from 'config';
import { DOMAIN, SIMPLE_SITE } from 'config';
import {
Lbry,
doBalanceSubscribe,
@@ -353,7 +353,7 @@ export function doAlertWaitingForSync() {
};
}
export function doLbryReady() {
export function doDaemonReady() {
return (dispatch, getState) => {
const state = getState();
@@ -363,6 +363,8 @@ export function doLbryReady() {
dispatch(
doAuthenticate(
appVersion,
undefined,
undefined,
shareUsageData,
(status) => {
const trendingAlgorithm =
@@ -375,7 +377,8 @@ export function doLbryReady() {
analytics.trendingAlgorithmEvent(trendingAlgorithm);
}
},
undefined
undefined,
DOMAIN
)
);
dispatch({ type: ACTIONS.DAEMON_READY });
+84 -113
View File
@@ -3,7 +3,15 @@ import * as ACTIONS from 'constants/action_types';
import * as REACTION_TYPES from 'constants/reactions';
import * as PAGES from 'constants/pages';
import { SORT_BY, BLOCK_LEVEL } from 'constants/comment';
import { Lbry, parseURI, buildURI, selectClaimsByUri, selectMyChannelClaims, isURIEqual } from 'lbry-redux';
import {
Lbry,
parseURI,
buildURI,
selectClaimsById,
selectClaimsByUri,
selectMyChannelClaims,
isURIEqual,
} from 'lbry-redux';
import { doToast, doSeeNotifications } from 'redux/actions/notifications';
import {
makeSelectMyReactionsForComment,
@@ -22,45 +30,19 @@ import { doAlertWaitingForSync } from 'redux/actions/app';
const isDev = process.env.NODE_ENV !== 'production';
const FETCH_API_FAILED_TO_FETCH = 'Failed to fetch';
declare type CommentronErrorMap = {
[string]: {
commentron: string | RegExp,
replacement: string,
linkText?: string,
linkTarget?: string,
},
const COMMENTRON_MSG_REMAP = {
// <-- Commentron msg --> : <-- App msg -->
'channel is blocked by publisher': 'Unable to comment. This channel has blocked you.',
'channel is not allowed to post comments': 'Unable to comment. Your channel has been blocked by an admin.',
'comments are disabled by the creator': 'Unable to comment. The content owner has disabled comments.',
'duplicate comment!': 'Please do not spam.',
};
// prettier-ignore
const ERR_MAP: CommentronErrorMap = {
SIMILAR_NAME: {
commentron: /^your user name (.*) is too close to the creator's user name (.*) and may cause confusion. Please use another identity.$/,
replacement: 'Your user name "%1%" is too close to the creator\'s user name "%2%" and may cause confusion. Please use another identity.',
},
SLOW_MODE_IS_ON: {
commentron: /^Slow mode is on. Please wait at most (.*) seconds before commenting again.$/,
replacement: 'Slow mode is on. Please wait up to %1% seconds before commenting again.',
},
HAS_MUTED_WORDS: {
commentron: /^the comment contents are blocked by (.*)$/,
replacement: 'The comment contains contents that are blocked by %1%.',
},
BLOCKED_BY_CREATOR: {
commentron: 'channel is blocked by publisher',
replacement: 'Unable to comment. This channel has blocked you.',
},
BLOCKED_BY_ADMIN: {
commentron: 'channel is not allowed to post comments',
replacement: 'Unable to comment. Your channel has been blocked by an admin.',
},
CREATOR_DISABLED: {
commentron: 'comments are disabled by the creator',
replacement: 'Unable to comment. The content owner has disabled comments.',
},
STOP_SPAMMING: {
commentron: 'duplicate comment!',
replacement: 'Please do not spam.',
},
const COMMENTRON_REGEX_MAP = {
// <-- App msg --> : <-- Regex of Commentron msg -->
'Your user name "%1%" is too close to the creator\'s user name "%2%" and may cause confusion. Please use another identity.': /^your user name (.*) is too close to the creator's user name (.*) and may cause confusion. Please use another identity.$/,
'Slow mode is on. Please wait up to %1% seconds before commenting again.': /^Slow mode is on. Please wait at most (.*) seconds before commenting again.$/,
'The comment contains contents that are blocked by %1%.': /^the comment contents are blocked by (.*)$/,
};
function devToast(dispatch, msg) {
@@ -70,45 +52,6 @@ function devToast(dispatch, msg) {
}
}
function resolveCommentronError(commentronMsg: string) {
for (const key in ERR_MAP) {
// noinspection JSUnfilteredForInLoop
const data = ERR_MAP[key];
if (typeof data.commentron === 'string') {
if (data.commentron === commentronMsg) {
return {
message: __(data.replacement),
linkText: data.linkText ? __(data.linkText) : undefined,
linkTarget: data.linkTarget,
isError: true,
};
}
} else {
const match = commentronMsg.match(data.commentron);
if (match) {
const subs = {};
for (let i = 1; i < match.length; ++i) {
subs[`${i}`] = match[i];
}
return {
message: __(data.replacement, subs),
linkText: data.linkText ? __(data.linkText) : undefined,
linkTarget: data.linkTarget,
isError: true,
};
}
}
}
return {
// Fallback to commentron original message. It will be in English
// only and most likely not capitalized correctly.
message: commentronMsg,
isError: true,
};
}
export function doCommentList(
uri: string,
parentId: string,
@@ -536,7 +479,39 @@ export function doCommentCreate(
})
.catch((error) => {
dispatch({ type: ACTIONS.COMMENT_CREATE_FAILED, data: error });
dispatch(doToast(resolveCommentronError(error.message)));
let toastMessage;
for (const commentronMsg in COMMENTRON_MSG_REMAP) {
if (error.message === commentronMsg) {
toastMessage = __(COMMENTRON_MSG_REMAP[commentronMsg]);
break;
}
}
if (!toastMessage) {
for (const i18nStr in COMMENTRON_REGEX_MAP) {
const regex = COMMENTRON_REGEX_MAP[i18nStr];
const match = error.message.match(regex);
if (match) {
const subs = {};
for (let i = 1; i < match.length; ++i) {
subs[`${i}`] = match[i];
}
toastMessage = __(i18nStr, subs);
break;
}
}
}
if (!toastMessage) {
// Fallback to commentron original message. It will be in English
// only and most likely not capitalized correctly.
toastMessage = error.message;
}
dispatch(doToast({ message: toastMessage, isError: true }));
return Promise.reject(error);
});
};
@@ -756,19 +731,11 @@ async function channelSignData(channelClaimId: string, data: string) {
return signedObject;
}
function safeParseURI(uri) {
try {
return parseURI(uri);
} catch {
return {};
}
}
// Hides a users comments from all creator's claims and prevent them from commenting in the future
function doCommentModToggleBlock(
unblock: boolean,
commenterUri: string,
creatorUri: string,
creatorId: string,
blockerIds: Array<string>, // [] = use all my channels
blockLevel: string,
timeoutSec?: number,
@@ -792,9 +759,6 @@ function doCommentModToggleBlock(
);
}
const { channelName, channelClaimId } = parseURI(commenterUri);
const { channelName: creatorName, channelClaimId: creatorId } = safeParseURI(creatorUri);
if (blockerIds.length === 0) {
// Specific blockers not provided, so find one based on block-level.
switch (blockLevel) {
@@ -822,15 +786,22 @@ function doCommentModToggleBlock(
break;
}
} else {
// Client wants to block for specific channels only. Ensure we own those channels.
blockerChannelClaims = blockerChannelClaims.filter((x) => blockerIds.includes(x.claim_id));
}
const { channelName, channelClaimId } = parseURI(commenterUri);
const creatorClaim = selectClaimsById(state)[creatorId];
if (creatorId && !creatorClaim) {
console.error("Can't find creator claim"); // eslint-disable-line
return;
}
dispatch({
type: unblock ? ACTIONS.COMMENT_MODERATION_UN_BLOCK_STARTED : ACTIONS.COMMENT_MODERATION_BLOCK_STARTED,
data: {
blockedUri: commenterUri,
creatorUri: creatorUri || undefined,
creatorUri: creatorClaim ? creatorClaim.permanent_url : undefined,
blockLevel: blockLevel,
},
});
@@ -869,8 +840,8 @@ function doCommentModToggleBlock(
signature: signatureData.signature,
// $FlowFixMe
signing_ts: signatureData.signing_ts,
creator_channel_id: creatorUri ? creatorId : undefined,
creator_channel_name: creatorUri ? creatorName : undefined,
creator_channel_id: creatorClaim ? creatorClaim.claim_id : undefined,
creator_channel_name: creatorClaim ? creatorClaim.name : undefined,
block_all: unblock ? undefined : blockLevel === BLOCK_LEVEL.ADMIN,
global_un_block: unblock ? blockLevel === BLOCK_LEVEL.ADMIN : undefined,
...sharedModBlockParams,
@@ -897,7 +868,7 @@ function doCommentModToggleBlock(
type: unblock ? ACTIONS.COMMENT_MODERATION_UN_BLOCK_FAILED : ACTIONS.COMMENT_MODERATION_BLOCK_FAILED,
data: {
blockedUri: commenterUri,
creatorUri: creatorUri || undefined,
creatorUri: creatorClaim ? creatorClaim.permanent_url : undefined,
blockLevel: blockLevel,
},
});
@@ -908,7 +879,7 @@ function doCommentModToggleBlock(
type: unblock ? ACTIONS.COMMENT_MODERATION_UN_BLOCK_COMPLETE : ACTIONS.COMMENT_MODERATION_BLOCK_COMPLETE,
data: {
blockedUri: commenterUri,
creatorUri: creatorUri || undefined,
creatorUri: creatorClaim ? creatorClaim.permanent_url : undefined,
blockLevel: blockLevel,
},
});
@@ -928,7 +899,7 @@ function doCommentModToggleBlock(
type: unblock ? ACTIONS.COMMENT_MODERATION_UN_BLOCK_FAILED : ACTIONS.COMMENT_MODERATION_BLOCK_FAILED,
data: {
blockedUri: commenterUri,
creatorUri: creatorUri || undefined,
creatorUri: creatorClaim ? creatorClaim.permanent_url : undefined,
blockLevel: blockLevel,
},
});
@@ -939,7 +910,7 @@ function doCommentModToggleBlock(
type: unblock ? ACTIONS.COMMENT_MODERATION_UN_BLOCK_FAILED : ACTIONS.COMMENT_MODERATION_BLOCK_FAILED,
data: {
blockedUri: commenterUri,
creatorUri: creatorUri || undefined,
creatorUri: creatorClaim ? creatorClaim.permanent_url : undefined,
blockLevel: blockLevel,
},
});
@@ -951,13 +922,13 @@ function doCommentModToggleBlock(
* Blocks the commenter for all channels that I own.
*
* @param commenterUri
* @param timeoutSec
* @param timeoutHours
* @param showLink
* @returns {function(Dispatch): *}
*/
export function doCommentModBlock(commenterUri: string, timeoutSec?: number, showLink: boolean = true) {
export function doCommentModBlock(commenterUri: string, timeoutHours?: number, showLink: boolean = true) {
return (dispatch: Dispatch) => {
return dispatch(doCommentModToggleBlock(false, commenterUri, '', [], BLOCK_LEVEL.SELF, timeoutSec, showLink));
return dispatch(doCommentModToggleBlock(false, commenterUri, '', [], BLOCK_LEVEL.SELF, timeoutHours, showLink));
};
}
@@ -966,13 +937,13 @@ export function doCommentModBlock(commenterUri: string, timeoutSec?: number, sho
*
* @param commenterUri
* @param blockerId
* @param timeoutSec
* @param timeoutHours
* @returns {function(Dispatch): *}
*/
export function doCommentModBlockAsAdmin(commenterUri: string, blockerId: string, timeoutSec?: number) {
export function doCommentModBlockAsAdmin(commenterUri: string, blockerId: string, timeoutHours?: number) {
return (dispatch: Dispatch) => {
return dispatch(
doCommentModToggleBlock(false, commenterUri, '', blockerId ? [blockerId] : [], BLOCK_LEVEL.ADMIN, timeoutSec)
doCommentModToggleBlock(false, commenterUri, '', blockerId ? [blockerId] : [], BLOCK_LEVEL.ADMIN, timeoutHours)
);
};
}
@@ -982,26 +953,26 @@ export function doCommentModBlockAsAdmin(commenterUri: string, blockerId: string
* moderation rights by the creator.
*
* @param commenterUri
* @param creatorUri
* @param creatorId
* @param blockerId
* @param timeoutSec
* @param timeoutHours
* @returns {function(Dispatch): *}
*/
export function doCommentModBlockAsModerator(
commenterUri: string,
creatorUri: string,
creatorId: string,
blockerId: string,
timeoutSec?: number
timeoutHours?: number
) {
return (dispatch: Dispatch) => {
return dispatch(
doCommentModToggleBlock(
false,
commenterUri,
creatorUri,
creatorId,
blockerId ? [blockerId] : [],
BLOCK_LEVEL.MODERATOR,
timeoutSec
timeoutHours
)
);
};
@@ -1038,14 +1009,14 @@ export function doCommentModUnBlockAsAdmin(commenterUri: string, blockerId: stri
* moderation rights by the creator.
*
* @param commenterUri
* @param creatorUri
* @param creatorId
* @param blockerId
* @returns {function(Dispatch): *}
*/
export function doCommentModUnBlockAsModerator(commenterUri: string, creatorUri: string, blockerId: string) {
export function doCommentModUnBlockAsModerator(commenterUri: string, creatorId: string, blockerId: string) {
return (dispatch: Dispatch) => {
return dispatch(
doCommentModToggleBlock(true, commenterUri, creatorUri, blockerId ? [blockerId] : [], BLOCK_LEVEL.MODERATOR)
doCommentModToggleBlock(true, commenterUri, creatorId, blockerId ? [blockerId] : [], BLOCK_LEVEL.MODERATOR)
);
};
}
+11 -12
View File
@@ -148,8 +148,7 @@ export function doPlayUri(
uri: string,
skipCostCheck: boolean = false,
saveFileOverride: boolean = false,
cb?: () => void,
hideFailModal: boolean = false
cb?: () => void
) {
return (dispatch: Dispatch, getState: () => any) => {
const state = getState();
@@ -184,7 +183,7 @@ export function doPlayUri(
!claimWasPurchased &&
(!instantPurchaseMax || !instantPurchaseEnabled || cost > instantPurchaseMax)
) {
if (!hideFailModal) dispatch(doOpenModal(MODALS.AFFIRM_PURCHASE, { uri }));
dispatch(doOpenModal(MODALS.AFFIRM_PURCHASE, { uri }));
} else {
beginGetFile();
}
@@ -291,10 +290,10 @@ export function doToggleLoopList(collectionId: string, loop: boolean, hideToast:
type: ACTIONS.TOGGLE_LOOP_LIST,
data: { collectionId, loop },
});
if (!hideToast) {
if (loop && !hideToast) {
dispatch(
doToast({
message: loop ? __('Loop is on.') : __('Loop is off.'),
message: __('Loop is on.'),
})
);
}
@@ -324,18 +323,18 @@ export function doToggleShuffleList(currentUri: string, collectionId: string, sh
type: ACTIONS.TOGGLE_SHUFFLE_LIST,
data: { collectionId, newUrls },
});
if (!hideToast) {
dispatch(
doToast({
message: __('Shuffle is on.'),
})
);
}
} else {
dispatch({
type: ACTIONS.TOGGLE_SHUFFLE_LIST,
data: { collectionId, newUrls: false },
});
}
if (!hideToast) {
dispatch(
doToast({
message: shuffle ? __('Shuffle is on.') : __('Shuffle is off.'),
})
);
}
};
}
-6
View File
@@ -432,11 +432,5 @@ export function toggleAutoplayNext() {
const autoplayNext = makeSelectClientSetting(SETTINGS.AUTOPLAY_NEXT)(state);
dispatch(doSetClientSetting(SETTINGS.AUTOPLAY_NEXT, !autoplayNext, ready));
dispatch(
doToast({
message: autoplayNext ? __('Autoplay Next is off.') : __('Autoplay Next is on.'),
})
);
};
}
+54 -38
View File
@@ -50,8 +50,11 @@ export function doFetchInviteStatus(shouldCallRewardList = true) {
};
}
export function doInstallNew(appVersion, callbackForUsersWhoAreSharingData, domain) {
export function doInstallNew(appVersion, os = null, firebaseToken = null, callbackForUsersWhoAreSharingData, domain) {
const payload = { app_version: appVersion, domain };
if (firebaseToken) {
payload.firebase_token = firebaseToken;
}
Lbry.status().then((status) => {
payload.app_id =
@@ -61,7 +64,7 @@ export function doInstallNew(appVersion, callbackForUsersWhoAreSharingData, doma
payload.node_id = status.lbry_id;
Lbry.version().then((version) => {
payload.daemon_version = version.lbrynet_version;
payload.operating_system = version.os_system;
payload.operating_system = os || version.os_system;
payload.platform = version.platform;
Lbryio.call('install', 'new', payload);
@@ -72,9 +75,33 @@ export function doInstallNew(appVersion, callbackForUsersWhoAreSharingData, doma
});
}
export function doInstallNewWithParams(
appVersion,
installationId,
nodeId,
lbrynetVersion,
os,
platform,
firebaseToken = null
) {
return () => {
const payload = { app_version: appVersion };
if (firebaseToken) {
payload.firebase_token = firebaseToken;
}
payload.app_id = installationId;
payload.node_id = nodeId;
payload.daemon_version = lbrynetVersion;
payload.operating_system = os;
payload.platform = platform;
Lbryio.call('install', 'new', payload);
};
}
function checkAuthBusy() {
let time = Date.now();
return new Promise(function (resolve, reject) {
return new Promise(function(resolve, reject) {
(function waitForAuth() {
try {
sessionStorage.setItem('test', 'available');
@@ -104,59 +131,48 @@ function checkAuthBusy() {
}
// TODO: Call doInstallNew separately so we don't have to pass appVersion and os_system params?
/**
*
* @param appVersion
* @param shareUsageData
* @param callbackForUsersWhoAreSharingData
* @param callInstall
* @returns {Function}
*
* Lbryio.fetchUser:
* getTokens then getCurrentUser, and if !user, call userNew and return the user
*
*/
export function doAuthenticate(
appVersion,
os = null,
firebaseToken = null,
shareUsageData = true,
callbackForUsersWhoAreSharingData,
callInstall = true
callInstall = true,
domain = null
) {
return async (dispatch) => {
return (dispatch) => {
dispatch({
type: ACTIONS.AUTHENTICATION_STARTED,
});
try {
await checkAuthBusy();
const user = await Lbryio.fetchUser(DOMAIN, getDefaultLanguage());
console.log('USER', user);
if (sessionStorageAvailable) window.sessionStorage.removeItem(AUTH_IN_PROGRESS);
// put this back: accessToken: tokens.access_token
if (user.error) {
throw new Error(user.error.message);
} else {
Lbryio.getTokens().then((tokens) => {
checkAuthBusy()
.then(() => {
return Lbryio.authenticate(DOMAIN, getDefaultLanguage());
})
.then((user) => {
if (sessionStorageAvailable) window.sessionStorage.removeItem(AUTH_IN_PROGRESS);
Lbryio.getAuthToken().then((token) => {
dispatch({
type: ACTIONS.AUTHENTICATION_SUCCESS,
data: { user, accessToken: tokens.auth_token }, // rename 'accessToken' = authToken
data: { user, accessToken: token },
});
if (shareUsageData) {
dispatch(doRewardList());
dispatch(doFetchInviteStatus(false));
if (callInstall) {
doInstallNew(appVersion, callbackForUsersWhoAreSharingData, DOMAIN);
doInstallNew(appVersion, os, firebaseToken, callbackForUsersWhoAreSharingData, domain);
}
}
});
}
} catch (error) {
if (sessionStorageAvailable) window.sessionStorage.removeItem(AUTH_IN_PROGRESS);
})
.catch((error) => {
if (sessionStorageAvailable) window.sessionStorage.removeItem(AUTH_IN_PROGRESS);
dispatch({
type: ACTIONS.AUTHENTICATION_FAILURE,
data: { error },
dispatch({
type: ACTIONS.AUTHENTICATION_FAILURE,
data: { error },
});
});
}
};
}
@@ -167,7 +183,7 @@ export function doUserFetch() {
type: ACTIONS.USER_FETCH_STARTED,
});
Lbryio.fetchCurrentUser()
Lbryio.getCurrentUser()
.then((user) => {
dispatch({
type: ACTIONS.USER_FETCH_SUCCESS,
@@ -188,7 +204,7 @@ export function doUserFetch() {
export function doUserCheckEmailVerified() {
// This will happen in the background so we don't need loading booleans
return (dispatch) => {
Lbryio.fetchCurrentUser().then((user) => {
Lbryio.getCurrentUser().then((user) => {
if (user.has_verified_email) {
dispatch(doRewardList());
+40 -47
View File
@@ -24,44 +24,37 @@ const defaultState = {
invitees: undefined,
referralLink: undefined,
referralCode: undefined,
user: { has_verified_email: false },
accessToken: undefined, // rename this
user: undefined,
accessToken: undefined,
youtubeChannelImportPending: false,
youtubeChannelImportErrorMessage: '',
referrerSetIsPending: false,
referrerSetError: '',
};
// does this do anything with user?
reducers[ACTIONS.AUTHENTICATION_STARTED] = (state) =>
reducers[ACTIONS.AUTHENTICATION_STARTED] = state =>
Object.assign({}, state, {
authenticationIsPending: true,
userIsPending: true,
// distinguish accessToken from authToken
accessToken: defaultState.accessToken,
});
reducers[ACTIONS.AUTHENTICATION_SUCCESS] = (state, action) => {
const newUserState = Object.assign({}, state, {
authenticationIsPending: false,
userIsPending: false,
});
if (action.data && action.data.user) {
newUserState.user = action.data.user;
}
if (action.data && action.data.accessToken) {
newUserState.accessToken = action.data.accessToken;
}
return newUserState;
};
reducers[ACTIONS.AUTHENTICATION_FAILURE] = (state) =>
reducers[ACTIONS.AUTHENTICATION_SUCCESS] = (state, action) =>
Object.assign({}, state, {
authenticationIsPending: false,
userIsPending: false,
accessToken: action.data.accessToken,
user: action.data.user,
});
reducers[ACTIONS.USER_FETCH_STARTED] = (state) =>
reducers[ACTIONS.AUTHENTICATION_FAILURE] = state =>
Object.assign({}, state, {
authenticationIsPending: false,
userIsPending: false,
user: null,
});
reducers[ACTIONS.USER_FETCH_STARTED] = state =>
Object.assign({}, state, {
userIsPending: true,
});
@@ -73,7 +66,7 @@ reducers[ACTIONS.USER_FETCH_SUCCESS] = (state, action) =>
emailToVerify: action.data.user.has_verified_email ? null : state.emailToVerify,
});
reducers[ACTIONS.USER_FETCH_FAILURE] = (state) =>
reducers[ACTIONS.USER_FETCH_FAILURE] = state =>
Object.assign({}, state, {
userIsPending: true,
user: null,
@@ -95,7 +88,7 @@ reducers[ACTIONS.USER_PHONE_NEW_SUCCESS] = (state, action) =>
phoneNewIsPending: false,
});
reducers[ACTIONS.USER_PHONE_RESET] = (state) =>
reducers[ACTIONS.USER_PHONE_RESET] = state =>
Object.assign({}, state, {
phoneToVerify: null,
});
@@ -106,7 +99,7 @@ reducers[ACTIONS.USER_PHONE_NEW_FAILURE] = (state, action) =>
phoneNewErrorMessage: action.data.error,
});
reducers[ACTIONS.USER_PHONE_VERIFY_STARTED] = (state) =>
reducers[ACTIONS.USER_PHONE_VERIFY_STARTED] = state =>
Object.assign({}, state, {
phoneVerifyIsPending: true,
phoneVerifyErrorMessage: '',
@@ -125,7 +118,7 @@ reducers[ACTIONS.USER_PHONE_VERIFY_FAILURE] = (state, action) =>
phoneVerifyErrorMessage: action.data.error,
});
reducers[ACTIONS.USER_EMAIL_NEW_STARTED] = (state) =>
reducers[ACTIONS.USER_EMAIL_NEW_STARTED] = state =>
Object.assign({}, state, {
emailNewIsPending: true,
emailNewErrorMessage: '',
@@ -143,12 +136,12 @@ reducers[ACTIONS.USER_EMAIL_NEW_SUCCESS] = (state, action) => {
});
};
reducers[ACTIONS.USER_EMAIL_NEW_EXISTS] = (state) =>
reducers[ACTIONS.USER_EMAIL_NEW_EXISTS] = state =>
Object.assign({}, state, {
emailAlreadyExists: true,
});
reducers[ACTIONS.USER_EMAIL_NEW_DOES_NOT_EXIST] = (state) =>
reducers[ACTIONS.USER_EMAIL_NEW_DOES_NOT_EXIST] = state =>
Object.assign({}, state, {
emailDoesNotExist: true,
});
@@ -159,7 +152,7 @@ reducers[ACTIONS.USER_EMAIL_NEW_FAILURE] = (state, action) =>
emailNewErrorMessage: action.data.error,
});
reducers[ACTIONS.USER_EMAIL_NEW_CLEAR_ENTRY] = (state) => {
reducers[ACTIONS.USER_EMAIL_NEW_CLEAR_ENTRY] = state => {
const newUser = { ...state.user };
delete newUser.primary_email;
@@ -173,7 +166,7 @@ reducers[ACTIONS.USER_EMAIL_NEW_CLEAR_ENTRY] = (state) => {
});
};
reducers[ACTIONS.USER_PASSWORD_SET_CLEAR] = (state) =>
reducers[ACTIONS.USER_PASSWORD_SET_CLEAR] = state =>
Object.assign({}, state, {
passwordResetSuccess: false,
passwordResetPending: false,
@@ -182,7 +175,7 @@ reducers[ACTIONS.USER_PASSWORD_SET_CLEAR] = (state) =>
passwordSetSuccess: false,
});
reducers[ACTIONS.USER_EMAIL_VERIFY_STARTED] = (state) =>
reducers[ACTIONS.USER_EMAIL_VERIFY_STARTED] = state =>
Object.assign({}, state, {
emailVerifyIsPending: true,
emailVerifyErrorMessage: '',
@@ -209,7 +202,7 @@ reducers[ACTIONS.USER_EMAIL_VERIFY_SET] = (state, action) =>
emailToVerify: action.data.email,
});
reducers[ACTIONS.USER_IDENTITY_VERIFY_STARTED] = (state) =>
reducers[ACTIONS.USER_IDENTITY_VERIFY_STARTED] = state =>
Object.assign({}, state, {
identityVerifyIsPending: true,
identityVerifyErrorMessage: '',
@@ -236,7 +229,7 @@ reducers[ACTIONS.FETCH_ACCESS_TOKEN_SUCCESS] = (state, action) => {
});
};
reducers[ACTIONS.USER_INVITE_STATUS_FETCH_STARTED] = (state) =>
reducers[ACTIONS.USER_INVITE_STATUS_FETCH_STARTED] = state =>
Object.assign({}, state, {
inviteStatusIsPending: true,
});
@@ -250,13 +243,13 @@ reducers[ACTIONS.USER_INVITE_STATUS_FETCH_SUCCESS] = (state, action) =>
referralCode: action.data.referralCode,
});
reducers[ACTIONS.USER_INVITE_NEW_STARTED] = (state) =>
reducers[ACTIONS.USER_INVITE_NEW_STARTED] = state =>
Object.assign({}, state, {
inviteNewIsPending: true,
inviteNewErrorMessage: '',
});
reducers[ACTIONS.USER_INVITE_NEW_SUCCESS] = (state) =>
reducers[ACTIONS.USER_INVITE_NEW_SUCCESS] = state =>
Object.assign({}, state, {
inviteNewIsPending: false,
inviteNewErrorMessage: '',
@@ -268,14 +261,14 @@ reducers[ACTIONS.USER_INVITE_NEW_FAILURE] = (state, action) =>
inviteNewErrorMessage: action.data.error.message,
});
reducers[ACTIONS.USER_INVITE_STATUS_FETCH_FAILURE] = (state) =>
reducers[ACTIONS.USER_INVITE_STATUS_FETCH_FAILURE] = state =>
Object.assign({}, state, {
inviteStatusIsPending: false,
invitesRemaining: null,
invitees: null,
});
reducers[ACTIONS.USER_YOUTUBE_IMPORT_STARTED] = (state) =>
reducers[ACTIONS.USER_YOUTUBE_IMPORT_STARTED] = state =>
Object.assign({}, state, {
youtubeChannelImportPending: true,
youtubeChannelImportErrorMessage: '',
@@ -300,28 +293,28 @@ reducers[ACTIONS.USER_YOUTUBE_IMPORT_FAILURE] = (state, action) =>
youtubeChannelImportErrorMessage: action.data,
});
reducers[ACTIONS.USER_EMAIL_VERIFY_RETRY_STARTED] = (state) =>
reducers[ACTIONS.USER_EMAIL_VERIFY_RETRY_STARTED] = state =>
Object.assign({}, state, {
resendingVerificationEmail: true,
});
reducers[ACTIONS.USER_EMAIL_VERIFY_RETRY_SUCCESS] = (state) =>
reducers[ACTIONS.USER_EMAIL_VERIFY_RETRY_SUCCESS] = state =>
Object.assign({}, state, {
resendingVerificationEmail: false,
});
reducers[ACTIONS.USER_EMAIL_VERIFY_RETRY_FAILURE] = (state) =>
reducers[ACTIONS.USER_EMAIL_VERIFY_RETRY_FAILURE] = state =>
Object.assign({}, state, {
resendingVerificationEmail: false,
});
reducers[ACTIONS.USER_SET_REFERRER_STARTED] = (state) =>
reducers[ACTIONS.USER_SET_REFERRER_STARTED] = state =>
Object.assign({}, state, {
referrerSetIsPending: true,
referrerSetError: defaultState.referrerSetError,
});
reducers[ACTIONS.USER_SET_REFERRER_SUCCESS] = (state) =>
reducers[ACTIONS.USER_SET_REFERRER_SUCCESS] = state =>
Object.assign({}, state, {
referrerSetIsPending: false,
referrerSetError: defaultState.referrerSetError,
@@ -333,25 +326,25 @@ reducers[ACTIONS.USER_SET_REFERRER_FAILURE] = (state, action) =>
referrerSetError: action.data.error.message,
});
reducers[ACTIONS.USER_SET_REFERRER_RESET] = (state) =>
reducers[ACTIONS.USER_SET_REFERRER_RESET] = state =>
Object.assign({}, state, {
referrerSetIsPending: false,
referrerSetError: defaultState.referrerSetError,
});
reducers[ACTIONS.USER_PASSWORD_EXISTS] = (state) =>
reducers[ACTIONS.USER_PASSWORD_EXISTS] = state =>
Object.assign({}, state, {
passwordExistsForUser: true,
});
reducers[ACTIONS.USER_PASSWORD_RESET_STARTED] = (state) =>
reducers[ACTIONS.USER_PASSWORD_RESET_STARTED] = state =>
Object.assign({}, state, {
passwordResetPending: true,
passwordResetSuccess: defaultState.passwordResetSuccess,
passwordResetError: null,
});
reducers[ACTIONS.USER_PASSWORD_RESET_SUCCESS] = (state) =>
reducers[ACTIONS.USER_PASSWORD_RESET_SUCCESS] = state =>
Object.assign({}, state, {
passwordResetPending: false,
passwordResetSuccess: true,
@@ -363,13 +356,13 @@ reducers[ACTIONS.USER_PASSWORD_RESET_FAILURE] = (state, action) =>
passwordResetError: action.data.error,
});
reducers[ACTIONS.USER_PASSWORD_SET_STARTED] = (state) =>
reducers[ACTIONS.USER_PASSWORD_SET_STARTED] = state =>
Object.assign({}, state, {
passwordSetPending: true,
passwordSetSuccess: defaultState.passwordSetSuccess,
});
reducers[ACTIONS.USER_PASSWORD_SET_SUCCESS] = (state) =>
reducers[ACTIONS.USER_PASSWORD_SET_SUCCESS] = state =>
Object.assign({}, state, {
passwordSetPending: false,
passwordSetSuccess: true,
+2 -2
View File
@@ -34,14 +34,14 @@ export const makeSelectIsPlaying = (uri: string) =>
createSelector(selectPrimaryUri, (primaryUri) => primaryUri === uri);
export const makeSelectIsPlayerFloating = (location: UrlLocation) =>
createSelector(selectPrimaryUri, selectPlayingUri, (primaryUri, playingUri) => {
createSelector(selectPrimaryUri, selectPlayingUri, selectClaimsByUri, (primaryUri, playingUri, claimsByUri) => {
const isInlineSecondaryPlayer =
playingUri &&
playingUri.uri !== primaryUri &&
location.pathname === playingUri.pathname &&
(playingUri.source === 'comment' || playingUri.source === 'markdown');
if ((playingUri && playingUri.primaryUri === primaryUri) || isInlineSecondaryPlayer) {
if ((playingUri && playingUri.uri === primaryUri) || isInlineSecondaryPlayer) {
return false;
}
-27
View File
@@ -15,33 +15,6 @@
.button--secondary {
margin-top: var(--spacing-xxs);
}
.claim-preview__wrapper {
border-bottom: none !important;
margin-bottom: var(--spacing-xs);
}
.claim-preview--inline {
.channel-thumbnail {
@include handleChannelGif(3rem);
}
}
.claim-preview__title {
font-size: var(--font-small);
}
.channel-name {
font-size: var(--font-xsmall);
}
.section {
margin-left: var(--spacing-m);
}
label {
font-style: italic;
}
}
.block-modal--values {
-2
View File
@@ -19,8 +19,6 @@
.claim-list__dropdown {
padding: 0 var(--spacing-m);
padding-right: var(--spacing-xl);
background-position: right var(--spacing-m) center;
@media (max-width: $breakpoint-small) {
margin-left: 0;
+1 -2
View File
@@ -26,10 +26,9 @@
.claim-search__dropdown {
padding: 0 var(--spacing-m);
padding-right: var(--spacing-xl);
padding-right: var(--spacing-l);
font-size: var(--font-body);
background-color: var(--color-card-background);
background-position: right var(--spacing-m) center;
}
.claim-search__dropdown--selected {
-4
View File
@@ -195,10 +195,6 @@
}
}
.file-viewer_embed-ended-title {
white-space: pre-wrap;
}
.content__viewer--floating {
.file-viewer__overlay-title,
.file-viewer__overlay-secondary {
+2 -2
View File
@@ -45,10 +45,10 @@ select {
select {
background-image: var(--select-toggle-background);
background-position: right var(--spacing-s) center;
background-position: 99% center;
background-repeat: no-repeat;
background-size: 1rem;
padding-right: var(--spacing-xl);
padding-right: var(--spacing-l);
padding-left: var(--spacing-s);
font-weight: bold;
}
-12
View File
@@ -142,7 +142,6 @@
.media__thumb {
flex-shrink: 0;
overflow: hidden;
$width: 5rem;
@include handleClaimListGifThumbnail($width);
width: $width;
@@ -264,17 +263,6 @@
:first-child {
flex: 1;
}
.wunderbar__more-results {
margin-top: 0;
margin-left: var(--spacing-xxs);
margin-bottom: 0;
@media (min-width: $breakpoint-small) {
margin-top: var(--spacing-xxs);
margin-bottom: 0;
}
}
}
[data-reach-combobox-option] {
+1 -1
View File
@@ -485,7 +485,7 @@ textarea {
.release__notes {
max-height: 50vh;
overflow: auto;
overflow: scroll;
}
.signup__odysee-logo {
+7 -9
View File
@@ -11,7 +11,7 @@ import { routerMiddleware } from 'connected-react-router';
import createRootReducer from './reducers';
import { Lbry, buildSharedStateMiddleware, ACTIONS as LBRY_REDUX_ACTIONS } from 'lbry-redux';
import { doSyncLoop } from 'redux/actions/sync';
import { getTokens } from 'util/saved-passwords';
import { getAuthToken } from 'util/saved-passwords';
import { generateInitialUrl } from 'util/url';
import { X_LBRY_AUTH_TOKEN } from 'constants/token';
@@ -189,14 +189,12 @@ const sharedStateCb = ({ dispatch, getState }) => {
const populateAuthTokenHeader = () => {
return (next) => (action) => {
if (action.type === ACTIONS.USER_FETCH_SUCCESS || action.type === ACTIONS.AUTHENTICATION_SUCCESS) {
if (action.data) {
}
const tokens = getTokens();
// if (tokens.access_token) {
// Lbry.setApiHeader('Authorization', 'Bearer ' + tokens.access_token);
// }
Lbry.setApiHeader(X_LBRY_AUTH_TOKEN, tokens.auth_token);
if (
(action.type === ACTIONS.USER_FETCH_SUCCESS || action.type === ACTIONS.AUTHENTICATION_SUCCESS) &&
action.data.user.has_verified_email === true
) {
const authToken = getAuthToken();
Lbry.setApiHeader(X_LBRY_AUTH_TOKEN, authToken);
}
return next(action);
+10 -16
View File
@@ -1,4 +1,4 @@
const { DOMAIN } = require('config.js');
const { DOMAIN } = require('../../config.js');
const AUTH_TOKEN = 'auth_token';
const SAVED_PASSWORD = 'saved_password';
const DEPRECATED_SAVED_PASSWORD = 'saved-password';
@@ -59,7 +59,7 @@ function deleteCookie(name) {
}
function setSavedPassword(value, saveToDisk) {
return new Promise((resolve) => {
return new Promise(resolve => {
const password = value === undefined || value === null ? '' : value;
sessionPassword = password;
@@ -74,17 +74,17 @@ function setSavedPassword(value, saveToDisk) {
}
function getSavedPassword() {
return new Promise((resolve) => {
return new Promise(resolve => {
if (sessionPassword) {
resolve(sessionPassword);
}
return getPasswordFromCookie().then((p) => resolve(p));
return getPasswordFromCookie().then(p => resolve(p));
});
}
function getPasswordFromCookie() {
return new Promise((resolve) => {
return new Promise(resolve => {
let password;
password = getCookie(SAVED_PASSWORD);
resolve(password);
@@ -92,7 +92,7 @@ function getPasswordFromCookie() {
}
function deleteSavedPassword() {
return new Promise((resolve) => {
return new Promise(resolve => {
deleteCookie(SAVED_PASSWORD);
resolve();
});
@@ -102,24 +102,19 @@ function getAuthToken() {
return getCookie(AUTH_TOKEN);
}
// will take oidc token getter
function getTokens() {
return { auth_token: getAuthToken(), access_token: null };
}
function setAuthToken(value) {
return setCookie(AUTH_TOKEN, value, 365);
}
function deleteAuthToken() {
return new Promise((resolve) => {
return new Promise(resolve => {
deleteCookie(AUTH_TOKEN);
resolve();
});
}
function doSignOutCleanup() {
return new Promise((resolve) => {
return new Promise(resolve => {
deleteAuthToken();
deleteSavedPassword();
resolve();
@@ -127,10 +122,10 @@ function doSignOutCleanup() {
}
function doAuthTokenRefresh() {
const { auth_token: authToken } = getAuthToken();
const authToken = getAuthToken();
if (authToken) {
deleteAuthToken();
setCookie(AUTH_TOKEN, authToken, 365);
setAuthToken(authToken);
}
}
@@ -152,7 +147,6 @@ module.exports = {
deleteSavedPassword,
getAuthToken,
setAuthToken,
getTokens,
deleteAuthToken,
doSignOutCleanup,
doAuthTokenRefresh,
-6
View File
@@ -156,9 +156,3 @@ export const generateRssUrl = (domain, channelClaim) => {
const url = `${domain}/$/rss/${channelClaim.canonical_url.replace('lbry://', '').replace('#', ':')}`;
return url;
};
export const generateListSearchUrlParams = (collectionId) => {
const urlParams = new URLSearchParams();
urlParams.set(COLLECTIONS_CONSTS.COLLECTION_ID, collectionId);
return `?` + urlParams.toString();
};
@@ -38,10 +38,10 @@ function FileViewerEmbeddedEnded(props: Props) {
<div className="file-viewer__overlay">
<div className="file-viewer__overlay-secondary">
<Button className="file-viewer__overlay-logo" href={URL}>
<Logo type={'embed'} />
<Logo type={'embed-ended'} />
</Button>
</div>
<div className="file-viewer__overlay-title file-viewer_embed-ended-title">{prompt}</div>
<div className="file-viewer__overlay-title">{prompt}</div>
<div className="file-viewer__overlay-actions">
<Button label={__('Rewatch or Discuss')} button="primary" href={lbrytvLink} />
{!isAuthenticated && (
+1 -1
View File
@@ -488,7 +488,7 @@ textarea {
.release__notes {
max-height: 50vh;
overflow: auto;
overflow: scroll;
}
.signup__odysee-logo {
+12
View File
@@ -0,0 +1,12 @@
const fs = require('fs');
const path = require('path');
let robots;
async function getRobots(ctx) {
if (!robots) {
robots = fs.readFileSync(path.join(__dirname, '/../dist/public/robots.txt'), 'utf8');
}
return robots;
}
module.exports = { getRobots };
+4 -17
View File
@@ -10139,18 +10139,18 @@ lazy-val@^1.0.4:
yargs "^13.2.2"
zstd-codec "^0.1.1"
lbry-redux@lbryio/lbry-redux#32b578707116d45f5b51b7ab523d200e75668676:
lbry-redux@lbryio/lbry-redux#49b9db5aae8db84ec21231444bf8345d450812b2:
version "0.0.1"
resolved "https://codeload.github.com/lbryio/lbry-redux/tar.gz/32b578707116d45f5b51b7ab523d200e75668676"
resolved "https://codeload.github.com/lbryio/lbry-redux/tar.gz/49b9db5aae8db84ec21231444bf8345d450812b2"
dependencies:
"@ungap/from-entries" "^0.2.1"
proxy-polyfill "0.1.6"
reselect "^3.0.0"
uuid "^8.3.1"
lbryinc@lbryio/lbryinc#c9ced4f226e06f4f188cb8dc31b561e1c27c5266:
lbryinc@lbryio/lbryinc#0b4e41ef90d6347819dd3453f2f9398a5c1b4f36:
version "0.0.1"
resolved "https://codeload.github.com/lbryio/lbryinc/tar.gz/c9ced4f226e06f4f188cb8dc31b561e1c27c5266"
resolved "https://codeload.github.com/lbryio/lbryinc/tar.gz/0b4e41ef90d6347819dd3453f2f9398a5c1b4f36"
dependencies:
reselect "^3.0.0"
@@ -10707,14 +10707,6 @@ marked@^1.2.3:
resolved "https://registry.yarnpkg.com/marked/-/marked-1.2.8.tgz#5008ece15cfa43e653e85845f3525af4beb6bdd4"
integrity sha512-lzmFjGnzWHkmbk85q/ILZjFoHHJIQGF+SxGEfIdGk/XhiTPhqGs37gbru6Kkd48diJnEyYwnG67nru0Z2gQtuQ==
match-sorter@^6.3.0:
version "6.3.0"
resolved "https://registry.yarnpkg.com/match-sorter/-/match-sorter-6.3.0.tgz#454a1b31ed218cddbce6231a0ecb5fdc549fed01"
integrity sha512-efYOf/wUpNb8FgNY+cOD2EIJI1S5I7YPKsw0LBp7wqPh5pmMS6i/wr3ZWwfwrAw1NvqTA2KUReVRWDX84lUcOQ==
dependencies:
"@babel/runtime" "^7.12.5"
remove-accents "0.4.2"
matcher@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/matcher/-/matcher-3.0.0.tgz#bd9060f4c5b70aa8041ccc6f80368760994f30ca"
@@ -14055,11 +14047,6 @@ remark@^9.0.0:
remark-stringify "^5.0.0"
unified "^6.0.0"
remove-accents@0.4.2:
version "0.4.2"
resolved "https://registry.yarnpkg.com/remove-accents/-/remove-accents-0.4.2.tgz#0a43d3aaae1e80db919e07ae254b285d9e1c7bb5"
integrity sha1-CkPTqq4egNuRngeuJUsoXZ4ce7U=
remove-markdown@^0.3.0:
version "0.3.0"
resolved "https://registry.yarnpkg.com/remove-markdown/-/remove-markdown-0.3.0.tgz#5e4b667493a93579728f3d52ecc1db9ca505dc98"