Compare commits

..
Author SHA1 Message Date
infinite-persistence 290ec29fd8 SBL 2021-10-01 04:34:08 -04:00
137 changed files with 3911 additions and 1288 deletions

No files matched your search

+9
View File
@@ -41,5 +41,14 @@ module.name_mapper='^web\/component\(.*\)$' -> '<PROJECT_ROOT>/web/component\1'
module.name_mapper='^web\/effects\(.*\)$' -> '<PROJECT_ROOT>/web/effects\1'
module.name_mapper='^web\/page\(.*\)$' -> '<PROJECT_ROOT>/web/page\1'
module.name_mapper='^homepage\(.*\)$' -> '<PROJECT_ROOT>/ui/util/homepage\1'
module.name_mapper='^scss\/component\(.*\)$' -> '<PROJECT_ROOT>/ui/scss/component/\1'
; Extensions
module.file_ext=.js
module.file_ext=.jsx
module.file_ext=.json
module.file_ext=.css
module.file_ext=.scss
[strict]
+4
View File
@@ -12,6 +12,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- 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))
- Added Channel Mention selection ability while creating a comment ([#7151](https://github.com/lbryio/lbry-desktop/pull/7151))
### Changed
- Changing the supported language from Filipino to Tagalog _community pr!_ ([#6951](https://github.com/lbryio/lbry-desktop/pull/6951))
@@ -22,6 +23,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
- 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))
- Stream Key is now hidden _community pr!_ ([#7127](https://github.com/lbryio/lbry-desktop/pull/7127))
- Fix playlist preview thumbnail ([#7178](https://github.com/lbryio/lbry-desktop/pull/7178)
- Fixed “Your Account” popup on mobile ([#7172](https://github.com/lbryio/lbry-desktop/pull/7172))
## [0.51.2] - [2021-08-20]
+62
View File
@@ -20,6 +20,13 @@ declare type Comment = {
is_fiat?: boolean,
};
declare type CommentronAuth = {
channel_name: string,
channel_id: string,
signature: string,
signing_ts: string,
};
declare type PerChannelSettings = {
words?: Array<string>,
comments_enabled?: boolean,
@@ -43,6 +50,7 @@ declare type CommentsState = {
linkedCommentAncestors: { [string]: Array<string> }, // {"linkedCommentId": ["parentId", "grandParentId", ...]}
pinnedCommentsById: {}, // ClaimId -> array of pinned comment IDs
isLoading: boolean,
isLoadingById: boolean,
isLoadingByParentId: { [string]: boolean },
myComments: ?Set<string>,
isFetchingReacts: boolean,
@@ -67,6 +75,10 @@ declare type CommentsState = {
settingsByChannelId: { [string]: PerChannelSettings }, // ChannelID -> settings
fetchingSettings: boolean,
fetchingBlockedWords: boolean,
sblMine: any,
sblInvited: Array<any>,
fetchingSblMine: boolean,
fetchingSblInvited: boolean,
};
declare type CommentReactParams = {
@@ -297,3 +309,53 @@ declare type BlockWordParams = {
signing_ts: string,
words: string, // CSV list of containing words to block comment on content
};
declare type SblUpdate = {
name?: string, // A user friendly identifier for the owner/users.
category?: string, // The category of block list this is so others search
description?: string,
member_invite_enabled?: boolean, // Can members invite others contributors?
// Strikes are number of hours a user should be banned for if
// part of this blocked list. Strikes 1,2,3 are intended to be
// progressively higher. Strike 3 is the highest.
strike_one?: number,
strike_two?: number,
strike_three?: number,
invite_expiration?: number, // The number of hours until a sent invite expires.
// Curse jar allows automatic appeals. If they tip the owner of
// the shared blocked list their appeal is automatically accepted.
curse_jar_amount?: number,
remove?: boolean,
};
declare type SharedBlockedListUpdateArgs = CommentronAuth & SblUpdate;
declare type SblGet = {
blocked_list_id?: number,
status: number, // @see: SBL_INVITE_STATUS
};
declare type SharedBlockedListGetArgs = ?CommentronAuth & SblGet;
declare type SblInvite = {
blocked_list_id?: number,
invitee_channel_name: string,
invitee_channel_id: string,
message: string,
};
declare type SharedBlockedListInviteArgs = CommentronAuth & SblInvite;
declare type SblInviteAccept = {
blocked_list_id: number,
accepted: boolean,
};
declare type SharedBlockedListInviteAcceptArgs = CommentronAuth & SblInviteAccept;
declare type SblRescind = {
invited_channel_name: string,
invited_channel_id: string,
};
declare type SharedBlockedListRescindArgs = CommentronAuth & SblRescind;
+14
View File
@@ -24,4 +24,18 @@ declare type LivestreamReplayData = Array<LivestreamReplayItem>;
declare type LivestreamState = {
fetchingById: {},
viewersById: {},
fetchingActiveLivestreams: boolean,
activeLivestreams: ?LivestreamInfo,
activeLivestreamsLastFetchedDate: number,
activeLivestreamsLastFetchedOptions: {},
}
declare type LivestreamInfo = {
[/* creatorId */ string]: {
live: boolean,
viewCount: number,
creatorId: string,
latestClaimId: string,
latestClaimUri: string,
}
}
+2 -1
View File
@@ -37,6 +37,7 @@
"build": "cross-env NODE_ENV=production yarn compile:electron && electron-builder build",
"build:dir": "yarn build -- --dir -c.compression=store -c.mac.identity=null",
"crossenv": "./node_modules/cross-env/dist/bin/cross-env",
"flow": "flow",
"lint": "eslint 'ui/**/*.{js,jsx}' && eslint 'web/**/*.{js,jsx}' && eslint 'electron/**/*.js' && flow",
"lint-fix": "eslint --fix --quiet 'ui/**/*.{js,jsx}' && eslint --fix --quiet 'web/**/*.{js,jsx}' && eslint --fix --quiet 'electron/**/*.js'",
"format": "prettier 'src/**/*.{js,jsx,scss,json}' --write",
@@ -156,7 +157,7 @@
"json-loader": "^0.5.4",
"lbry-format": "https://github.com/lbryio/lbry-format.git",
"lbry-redux": "lbryio/lbry-redux#32b578707116d45f5b51b7ab523d200e75668676",
"lbryinc": "lbryio/lbryinc#c9ced4f226e06f4f188cb8dc31b561e1c27c5266",
"lbryinc": "lbryio/lbryinc#0b4e41ef90d6347819dd3453f2f9398a5c1b4f36",
"lint-staged": "^7.0.2",
"localforage": "^1.7.1",
"lodash-es": "^4.17.14",
+21 -11
View File
@@ -51,7 +51,6 @@
"Description of your content": "Description of your content",
"Price": "Price",
"Free": "Free",
"Learn more": "Learn more",
"Name": "Name",
"Deposit": "Deposit",
"Language": "Language",
@@ -103,7 +102,6 @@
"Enter a URL for your thumbnail.": "Enter a URL for your thumbnail.",
"Thumbnail Preview": "Thumbnail Preview",
"Use thumbnail upload tool": "Use thumbnail upload tool",
"Thumbnails that entice a viewer to watch a video work best": "Thumbnails that entice a viewer to watch a video work best",
"Create a URL for this content. Simpler names are easier to find and remember.": "Create a URL for this content. Simpler names are easier to find and remember.",
"Open file": "Open file",
"Delete": "Delete",
@@ -175,7 +173,6 @@
"Continue": "Continue",
"This file has been shared with you by other people.": "This file has been shared with you by other people.",
"LBRY Inc is not responsible for its content, click continue to proceed at your own risk.": "LBRY Inc is not responsible for its content, click continue to proceed at your own risk.",
"Find what you were looking for?": "Find what you were looking for?",
"Yes": "Yes",
"No": "No",
"These search results are provided by LBRY, Inc.": "These search results are provided by LBRY, Inc.",
@@ -207,6 +204,9 @@
"View": "View",
"Edit": "Edit",
"Copied": "Copied",
"Copied stream key.": "Copied stream key.",
"Copied stream server URL.": "Copied stream server URL.",
"Failed to copy.": "Failed to copy.",
"The publisher has chosen to charge %lbc% to view this content. Your balance is currently too low to view it. Check out %reward_link% for free %lbc% or send more %lbc% to your wallet. You can also %buy_link% more %lbc%.": "The publisher has chosen to charge %lbc% to view this content. Your balance is currently too low to view it. Check out %reward_link% for free %lbc% or send more %lbc% to your wallet. You can also %buy_link% more %lbc%.",
"Connecting...": "Connecting...",
"Comments": "Comments",
@@ -314,6 +314,8 @@
"Confirm Thumbnail Upload": "Confirm Thumbnail Upload",
"Upload": "Upload",
"upload": "upload",
"Your uploads": "Your uploads",
"Invalid thumbnail": "Invalid thumbnail",
"Uploading thumbnail": "Uploading thumbnail",
"Please wait for thumbnail to finish uploading": "Please wait for thumbnail to finish uploading",
"A thumbnail is required. Please upload or provide an image URL above.": "A thumbnail is required. Please upload or provide an image URL above.",
@@ -538,6 +540,7 @@
"Create a new account or sign in.": "Create a new account or sign in.",
"Terms of Service": "Terms of Service",
"Learn More": "Learn More",
"Learn more": "Learn more",
"Community": "Community",
"Resources": "Resources",
"Policies": "Policies",
@@ -780,6 +783,7 @@
"There was an error reposting this claim. Please try again later.": "There was an error reposting this claim. Please try again later.",
"Claim ID": "Claim ID",
"Official YouTube Creator": "Official YouTube Creator",
"YouTube Sync": "YouTube Sync",
"Last checked %time_ago%": "Last checked %time_ago%",
"Install Now": "Install Now",
"Invite Link": "Invite Link",
@@ -1397,8 +1401,8 @@
"Gaming": "Gaming",
"Game": "Game",
"Nice People": "Nice People",
"Tech": "Tech",
"Lab": "Lab",
"Tech": "Tech",
"Technology": "Technology",
"Movies": "Movies",
"News": "News",
@@ -1752,12 +1756,8 @@
"Moderator": "Moderator",
"Global Unblock Channel": "Global Unblock Channel",
"Global Block Channel": "Global Block Channel",
"Moderator tools": "Moderator tools",
"Global Block": "Global Block",
"Block this channel as global admin": "Block this channel as global admin",
"Moderator Block": "Moderator Block",
"Block this channel on behalf of %creator%": "Block this channel on behalf of %creator%",
"creator": "creator",
"Block this channel on behalf of %creator%.": "Block this channel on behalf of %creator%.",
"Block this channel on behalf of the creator.": "Block this channel on behalf of the creator.",
"Enter the timeout duration. Examples: %examples%": "Enter the timeout duration. Examples: %examples%",
"Wow, banned for more than 100 years?": "Wow, banned for more than 100 years?",
"Invalid duration.": "Invalid duration.",
@@ -1775,12 +1775,15 @@
"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.",
"Add as moderator": "Add as moderator",
"Assign this user to moderate %channel%": "Assign this user to moderate %channel%",
"Assign this user to moderate %channel%.": "Assign this user to moderate %channel%.",
"Assign this user to moderate your channel.": "Assign this user to moderate your channel.",
"Mute (m)": "Mute (m)",
"Playback Rate (<, >)": "Playback Rate (<, >)",
"Fullscreen (f)": "Fullscreen (f)",
"Pause (space)": "Pause (space)",
"Play (space)": "Play (space)",
"Play Next (SHIFT+N)": "Play Next (SHIFT+N)",
"Play Previous (SHIFT+P)": "Play Previous (SHIFT+P)",
"Unmute (m)": "Unmute (m)",
"Exit Fullscreen (f)": "Exit Fullscreen (f)",
"Theater Mode (t)": "Theater Mode (t)",
@@ -2108,6 +2111,7 @@
"Manage Card": "Manage Card",
"Card Details": "Card Details",
"Remove Card": "Remove Card",
"Sorry, there was an error in processing your payment!": "Sorry, there was an error in processing your payment!",
"Congratulations! Your account has been connected with Odysee.": "Congratulations! Your account has been connected with Odysee.",
"Your account balance is %balance% USD. Functionality to view your transactions and withdraw your balance will be landing shortly.": "Your account balance is %balance% USD. Functionality to view your transactions and withdraw your balance will be landing shortly.",
"Your account balance is $0 USD. When you receive a tip you will see it here.": "Your account balance is $0 USD. When you receive a tip you will see it here.",
@@ -2169,5 +2173,11 @@
"Content Page": "Content Page",
"Card Last 4": "Card Last 4",
"Search blocked channel name": "Search blocked channel name",
"Discuss": "Discuss",
"lbry.tv has been retired. You have been magically transported to Odysee.com. %more%": "lbry.tv has been retired. You have been magically transported to Odysee.com. %more%",
"Show more livestreams": "Show more livestreams",
"Creator": "Creator",
"From comments": "From comments",
"From search": "From search",
"--end--": "--end--"
}
+6
View File
@@ -36,6 +36,12 @@ const Comments = {
setting_update: (params: UpdateSettingsParams) => fetchCommentsApi('setting.Update', params),
setting_get: (params: SettingsParams) => fetchCommentsApi('setting.Get', params),
super_list: (params: SuperListParams) => fetchCommentsApi('comment.SuperChatList', params),
sbl_update: (params: SharedBlockedListUpdateArgs) => fetchCommentsApi('blockedlist.Update', params),
sbl_get: (params: SharedBlockedListGetArgs) => fetchCommentsApi('blockedlist.Get', params),
sbl_invite: (params: SharedBlockedListInviteArgs) => fetchCommentsApi('blockedlist.Invite', params),
sbl_list_invites: (params: CommentronAuth) => fetchCommentsApi('blockedlist.ListInvites', params),
sbl_accept: (params: SharedBlockedListInviteAcceptArgs) => fetchCommentsApi('blockedlist.Accept', params),
sbl_rescind: (params: SharedBlockedListRescindArgs) => fetchCommentsApi('blockedlist.Rescind', params),
};
function fetchCommentsApi(method: string, params: {}) {
+33
View File
@@ -0,0 +1,33 @@
import { connect } from 'react-redux';
import { doOpenModal } from 'redux/actions/app';
import { doSblGet, doSblAccept, doSblListInvites, doSblRescind, doSblDelete } from 'redux/actions/comments';
import { doToast } from 'redux/actions/notifications';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import {
selectSblMine,
selectFetchingSblMine,
selectFetchingSblInvited,
selectSblInvited,
} from 'redux/selectors/comments';
import BlockListShared from './view';
const select = (state) => ({
activeChannelClaim: selectActiveChannelClaim(state),
sblMine: selectSblMine(state),
sblInvited: selectSblInvited(state),
fetchingSblMine: selectFetchingSblMine(state),
fetchingSblInvited: selectFetchingSblInvited(state),
});
const perform = (dispatch) => ({
doSblGet: (channelClaim, params) => dispatch(doSblGet(channelClaim, params)),
doSblListInvites: (channelClaim) => dispatch(doSblListInvites(channelClaim)),
doSblAccept: (channelClaim, params, onComplete) => dispatch(doSblAccept(channelClaim, params, onComplete)),
doSblRescind: (channelClaim, params, onComplete) => dispatch(doSblRescind(channelClaim, params, onComplete)),
doSblDelete: (channelClaim) => dispatch(doSblDelete(channelClaim)),
doOpenModal: (modal, props) => dispatch(doOpenModal(modal, props)),
doToast: (options) => dispatch(doToast(options)),
});
export default connect(select, perform)(BlockListShared);
+452
View File
@@ -0,0 +1,452 @@
// @flow
import React from 'react';
import { useHistory } from 'react-router';
import Button from 'component/button';
import Card from 'component/common/card';
import CreditAmount from 'component/common/credit-amount';
import Empty from 'component/common/empty';
import LbcSymbol from 'component/common/lbc-symbol';
import TruncatedText from 'component/common/truncated-text';
import ChannelSelector from 'component/channelSelector';
import ClaimList from 'component/claimList';
import I18nMessage from 'component/i18nMessage';
import Spinner from 'component/spinner';
import { SBL_INVITE_STATUS } from 'constants/comment';
import * as ICONS from 'constants/icons';
import * as MODALS from 'constants/modal_types';
import * as PAGES from 'constants/pages';
import useFetched from 'effects/use-fetched';
import { getHoursStr, getYesNoStr } from 'util/string';
import { isURIValid } from 'lbry-redux';
const PARAM_BLOCKLIST_ID = 'id';
type Props = {
activeChannelClaim: ?ChannelClaim,
sblMine: any,
sblInvited: any,
fetchingSblMine: boolean,
fetchingSblInvited: boolean,
doSblGet: (channelClaim: ?ChannelClaim, params: SblGet) => void,
doSblListInvites: (channelClaim: ChannelClaim) => void,
doSblAccept: (channelClaim: ChannelClaim, params: SblInviteAccept, onComplete: (err: string) => void) => void,
doSblRescind: (channelClaim: ChannelClaim, params: SblRescind, onComplete: (err: string) => void) => void,
doSblDelete: (channelClaim: ChannelClaim) => void,
doOpenModal: (string, {}) => void,
doToast: ({ message: string }) => void,
};
export default function BlockListShared(props: Props) {
const {
activeChannelClaim,
sblMine,
sblInvited,
fetchingSblMine,
fetchingSblInvited,
doSblGet,
doSblListInvites,
doSblAccept,
doSblRescind,
doSblDelete,
doOpenModal,
doToast,
} = props;
const { push } = useHistory();
const [showMembers, setShowMembers] = React.useState(false);
const [expandInvite, setExpandInvite] = React.useState({});
const members = sblMine && sblMine.invited_members;
const memberUris = members && members.map((m) => `lbry://${m.invited_channel_name}#${m.invited_channel_id}`);
// I think the only way to check if my SBL is active is by checking whether we accepted any invites to other SBLs.
const isMySblActive = sblMine && (!sblInvited || !sblInvited.some((i) => i.invitation.status === 'accepted'));
const mySblId = sblMine && sblMine.shared_blocked_list.id;
const isUpdating = fetchingSblMine || fetchingSblInvited;
const fetchedOnce = useFetched(isUpdating);
// **************************************************************************
// **************************************************************************
function fetchSblInfo() {
if (activeChannelClaim) {
doSblGet(activeChannelClaim, {
blocked_list_id: undefined,
status: SBL_INVITE_STATUS.ALL,
});
doSblListInvites(activeChannelClaim);
}
}
function handleSblDelete() {
doOpenModal(MODALS.CONFIRM, {
title: __('Delete'),
body: (
<>
<p>{__('Are you sure you want to delete the shared blocklist?')}</p>
<p className="empty__text">{sblMine.shared_blocked_list.name.substring(0, 256)}</p>
</>
),
onConfirm: (closeModal) => {
if (activeChannelClaim) {
doSblDelete(activeChannelClaim);
}
closeModal();
},
});
}
function handleSblAccept(sblId: number, accepted: boolean) {
doOpenModal(MODALS.CONFIRM, {
title: accepted ? __('Accept invite') : __('Reject invite'),
body: accepted ? (
<>
<p>{__('Participate in the selected shared blocklist?')}</p>
<p className="help">{__('Any channels that you block in the future will be added to the list.')}</p>
<p className="help">
{__(
'This will become the active shared blocklist, replacing your own (if exists) or any shared blocklist that you are currently participating.'
)}
</p>
</>
) : (
<>
<p>{__('Stop participating from the selected shared blocklist?')}</p>
</>
),
onConfirm: (closeModal, setIsBusy) => {
if (activeChannelClaim) {
const params = {
blocked_list_id: sblId,
accepted: accepted,
};
setIsBusy(true);
doSblAccept(activeChannelClaim, params, (err: string) => {
if (err) {
doToast({ message: err, isError: true });
} else {
fetchSblInfo();
setTimeout(() => {
setIsBusy(false);
closeModal();
doToast({ message: accepted ? __('Invite accepted.') : __('Invite rejected.') });
}, 2000);
}
});
}
},
});
}
function handleRescind(memberClaim, expired) {
doOpenModal(MODALS.CONFIRM, {
title: expired ? __('Remove') : __('Rescind'),
body: (
<>
{expired && <p>{__('Remove the invitation for the following member?')}</p>}
{!expired && <p>{__('Rescind the invitation for the following member?')}</p>}
<p className="empty__text">{memberClaim.name.substring(0, 256)}</p>
</>
),
onConfirm: (closeModal, setIsBusy) => {
if (activeChannelClaim) {
const params = {
invited_channel_name: memberClaim.name,
invited_channel_id: memberClaim.claim_id,
};
setIsBusy(true);
doSblRescind(activeChannelClaim, params, (/* err */) => {
// Fetch the new data and wait a bit before we dismiss the modal.
// If you hate the hardcoded timeout, then add a callback for the
// fetch actions.
fetchSblInfo();
setTimeout(() => {
setIsBusy(false);
closeModal();
}, 2000);
});
}
},
});
}
function getHelpElem() {
return (
<I18nMessage
// TODO: Need URL
tokens={{
learn_more: <Button button="link" label={__('Learn more')} href="https://odysee.com/@OdyseeHelp:b" />,
}}
>
Shared blocklists allow a group of creators to all mutually manage a set of blocks that applies to all of their
channels. %learn_more%
</I18nMessage>
);
}
function getRowElem(label: string, value: any, truncate: boolean = false) {
return (
<tr>
<td>{label}</td>
{truncate && (
<td>
<TruncatedText lines={1} text={value} showTooltip />
</td>
)}
{!truncate && <td>{value}</td>}
</tr>
);
}
function getSwearJarAmountElem(amount: number) {
return (amount && <CreditAmount amount={amount} precision={4} />) || <LbcSymbol prefix={__('---')} size={14} />;
}
function getSblStatusElem(active) {
if (active) {
return (
<div className="sbl-status--active" title={__('This is the current active shared blocklist.')}>
{__('Active')}
</div>
);
} else {
return (
<div
className="sbl-status--inactive"
title={__('This blocklist is currently inactive. Only 1 blocklist can be active at a time.')}
>
{__('Inactive')}
</div>
);
}
}
function getSblInfoElem(sbl) {
const expanded = expandInvite[sbl.id] || sbl.id === mySblId;
return (
<div className="sbl-info">
{expanded && (
<table className="table table--condensed table--publish-preview table--no-row-lines">
<tbody>
{getRowElem(__('Name'), sbl.name)}
{getRowElem(__('Description'), sbl.description)}
{getRowElem(__('Category'), sbl.category)}
{getRowElem(__('Strike 1'), getHoursStr(sbl.strike_one))}
{getRowElem(__('Strike 2'), getHoursStr(sbl.strike_two))}
{getRowElem(__('Strike 3'), getHoursStr(sbl.strike_three))}
{getRowElem(__('Auto-appeal minimum'), getSwearJarAmountElem(sbl.curse_jar_amount))}
{getRowElem(__('Invite expiration'), getHoursStr(sbl.invite_expiration))}
{getRowElem(__('Allow members to invite others'), getYesNoStr(sbl.member_invite_enabled))}
</tbody>
</table>
)}
{sbl.id !== mySblId && (
<Button
button="link"
className="expandable__button"
icon={expanded ? ICONS.UP : ICONS.DOWN}
onClick={() => setExpandInvite({ ...expandInvite, [sbl.id]: !expanded })}
/>
)}
</div>
);
}
function getMySblElem() {
if (sblMine) {
const sbl = sblMine.shared_blocked_list;
return (
<Card
title={
<div>
{__('Your Shared Blocklist')}
{isUpdating && <Spinner type="small" />}
</div>
}
actions={
<>
<div className="section__actions--between">
<div className="section__actions">
<Button
button="alt"
label={__('Invite')}
title={__('Invite others to your shared blocklist.')}
icon={ICONS.INVITE}
navigate={`/$/${PAGES.SHARED_BLOCKLIST_INVITE}?${PARAM_BLOCKLIST_ID}=${sbl.id}`}
disabled={!isMySblActive}
/>
<Button
button="alt"
label={__('Edit')}
title={__('Make changes to your shared blocklist.')}
icon={ICONS.EDIT}
onClick={() => {
push({
pathname: `/$/${PAGES.SHARED_BLOCKLIST_EDIT}`,
state: sbl,
});
}}
/>
<Button
button="alt"
label={__('Delete')}
title={__('Delete your shared blocklist.')}
icon={ICONS.DELETE}
onClick={handleSblDelete}
/>
</div>
{getSblStatusElem(isMySblActive)}
</div>
<div className="section__actions">{getSblInfoElem(sbl)}</div>
<div className="section__actions">
<Button
button="link"
label={showMembers ? __('Hide members') : __('Show members')}
icon={showMembers ? ICONS.UP : ICONS.DOWN}
onClick={() => setShowMembers(!showMembers)}
/>
</div>
<div className="section">{getMembersElem()}</div>
</>
}
/>
);
} else {
return (
<Card
title={__('Your Shared Blocklist')}
actions={<Button button="primary" label={__('Create list')} navigate={`/$/${PAGES.SHARED_BLOCKLIST_EDIT}`} />}
/>
);
}
}
function getMembersElem() {
if (!showMembers) {
return null;
}
const getInviteStatus = (members, claim) => {
const member = members.find((x) => x.invited_channel_id === claim.claim_id);
return member && member.status;
};
// This is required until Commentron filters bad invites.
const sanitizedMemberUris = memberUris && memberUris.filter((uri) => isURIValid(uri));
if (sanitizedMemberUris && sanitizedMemberUris.length > 0) {
return (
<ClaimList
uris={sanitizedMemberUris}
hideMenu
renderProperties={(claim) => {
const status = getInviteStatus(members, claim);
return status === 'expired' ? (
<div className="sbl_invite_expired">{__('Expired')}</div>
) : status === 'accepted' ? (
<div className="sbl_invite_accepted">{__('Accepted')}</div>
) : null;
}}
renderActions={(claim) => {
const expired = getInviteStatus(members, claim) === 'expired';
return (
<div className="section__actions">
<Button
button={expired ? 'alt' : 'secondary'}
icon={ICONS.REMOVE}
label={expired ? __('Remove') : __('Rescind')}
onClick={() => handleRescind(claim, expired)}
/>
</div>
);
}}
/>
);
} else {
return <Empty text={__('No members invited.')} />;
}
}
function getInvitedSblElem() {
if (sblInvited && sblInvited.length > 0) {
return (
<Card
title={__('Invitations')}
isBodyList
body={
<>
{sblInvited.map((i) => {
return (
<div key={i.shared_blocked_list.id} className="card__main-actions">
<div className="section__actions--between">
<div className="section__actions">
<Button
button="alt"
label={i.invitation.status === 'accepted' ? __('Disable') : __('Enable')}
title={
i.invitation.status === 'accepted'
? __('Stop using this blocklist.')
: __('Accept and activate this blocklist.')
}
icon={i.invitation.status === 'accepted' ? ICONS.REMOVE : undefined}
onClick={() => handleSblAccept(i.shared_blocked_list.id, i.invitation.status !== 'accepted')}
/>
{i.invitation.status === 'accepted' && i.shared_blocked_list.member_invite_enabled && (
<Button
button="alt"
label={__('Invite')}
title={__('Invite others to this shared blocklist on behalf of the owner.')}
icon={ICONS.INVITE}
navigate={`/$/${PAGES.SHARED_BLOCKLIST_INVITE}?${PARAM_BLOCKLIST_ID}=${i.shared_blocked_list.id}`}
/>
)}
</div>
{getSblStatusElem(i.invitation.status === 'accepted')}
</div>
<div className="section">
<table className="table table--condensed table--publish-preview table--no-row-lines">
<tbody>
{getRowElem(__('From'), i.invitation.invited_by_channel_name)}
{getRowElem(__('Message'), i.invitation.message, !expandInvite[i.shared_blocked_list.id])}
</tbody>
</table>
{getSblInfoElem(i.shared_blocked_list)}
</div>
</div>
);
})}
</>
}
/>
);
}
}
// **************************************************************************
// **************************************************************************
React.useEffect(() => {
fetchSblInfo();
}, [activeChannelClaim, doSblGet, doSblListInvites]); // eslint-disable-line react-hooks/exhaustive-deps
return (
<div className={!fetchedOnce ? 'card--disabled' : isUpdating ? 'card--disable-interaction' : ''}>
<div className="section help--notice">{getHelpElem()}</div>
<div className="section">
<ChannelSelector hideAnon />
</div>
<div className="section sbl">{getMySblElem()}</div>
<div className="section sbl">{getInvitedSblElem()}</div>
</div>
);
}
+1
View File
@@ -154,6 +154,7 @@ const Button = forwardRef<any, {}>((props: Props, ref: any) => {
title={title}
onClick={onClick}
aria-label={ariaLabel}
disabled={disabled} // is there a reason this wasn't here before?
>
{content}
</a>
@@ -0,0 +1,10 @@
import { connect } from 'react-redux';
import { makeSelectClaimForUri, makeSelectIsUriResolving } from 'lbry-redux';
import ChannelMentionSuggestion from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
isResolvingUri: makeSelectIsUriResolving(props.uri)(state),
});
export default connect(select)(ChannelMentionSuggestion);
@@ -0,0 +1,32 @@
// @flow
import { ComboboxOption } from '@reach/combobox';
import ChannelThumbnail from 'component/channelThumbnail';
import React from 'react';
type Props = {
claim: ?Claim,
uri?: string,
isResolvingUri: boolean,
};
export default function ChannelMentionSuggestion(props: Props) {
const { claim, uri, isResolvingUri } = props;
return !claim ? null : (
<ComboboxOption value={uri}>
{isResolvingUri ? (
<div className="channel-mention__suggestion">
<div className="media__thumb media__thumb--resolving" />
</div>
) : (
<div className="channel-mention__suggestion">
<ChannelThumbnail xsmall uri={uri} />
<span className="channel-mention__suggestion-label">
<div className="channel-mention__suggestion-title">{(claim.value && claim.value.title) || claim.name}</div>
<div className="channel-mention__suggestion-name">{claim.name}</div>
</span>
</div>
)}
</ComboboxOption>
);
}
@@ -0,0 +1,36 @@
import { connect } from 'react-redux';
import { selectShowMatureContent } from 'redux/selectors/settings';
import { selectSubscriptions } from 'redux/selectors/subscriptions';
import { withRouter } from 'react-router';
import { doResolveUris, makeSelectClaimForUri } from 'lbry-redux';
import { makeSelectTopLevelCommentsForUri } from 'redux/selectors/comments';
import ChannelMentionSuggestions from './view';
const select = (state, props) => {
const subscriptionUris = selectSubscriptions(state).map(({ uri }) => uri);
const topLevelComments = makeSelectTopLevelCommentsForUri(props.uri)(state);
const commentorUris = [];
// Avoid repeated commentors
topLevelComments.map(({ channel_url }) => !commentorUris.includes(channel_url) && commentorUris.push(channel_url));
const getUnresolved = (uris) =>
uris.map((uri) => !makeSelectClaimForUri(uri)(state) && uri).filter((uri) => uri !== false);
const getCanonical = (uris) =>
uris
.map((uri) => makeSelectClaimForUri(uri)(state) && makeSelectClaimForUri(uri)(state).canonical_url)
.filter((uri) => Boolean(uri));
return {
commentorUris,
subscriptionUris,
unresolvedCommentors: getUnresolved(commentorUris),
unresolvedSubscriptions: getUnresolved(subscriptionUris),
canonicalCreator: getCanonical([props.creatorUri])[0],
canonicalCommentors: getCanonical(commentorUris),
canonicalSubscriptions: getCanonical(subscriptionUris),
showMature: selectShowMatureContent(state),
};
};
export default withRouter(connect(select, { doResolveUris })(ChannelMentionSuggestions));
@@ -0,0 +1,285 @@
// @flow
import { Combobox, ComboboxInput, ComboboxPopover, ComboboxList } from '@reach/combobox';
import { Form } from 'component/common/form';
import { parseURI, regexInvalidURI } from 'lbry-redux';
import { SEARCH_OPTIONS } from 'constants/search';
import * as KEYCODES from 'constants/keycodes';
import ChannelMentionSuggestion from 'component/channelMentionSuggestion';
import ChannelMentionTopSuggestion from 'component/channelMentionTopSuggestion';
import React from 'react';
import Spinner from 'component/spinner';
import type { ElementRef } from 'react';
import useLighthouse from 'effects/use-lighthouse';
const INPUT_DEBOUNCE_MS = 1000;
const LIGHTHOUSE_MIN_CHARACTERS = 3;
type Props = {
inputRef: any,
mentionTerm: string,
noTopSuggestion?: boolean,
showMature: boolean,
isLivestream: boolean,
creatorUri: string,
commentorUris: Array<string>,
subscriptionUris: Array<string>,
unresolvedCommentors: Array<string>,
unresolvedSubscriptions: Array<string>,
canonicalCreator: string,
canonicalCommentors: Array<string>,
canonicalSubscriptions: Array<string>,
doResolveUris: (Array<string>) => void,
customSelectAction?: (string, number) => void,
};
export default function ChannelMentionSuggestions(props: Props) {
const {
unresolvedCommentors,
unresolvedSubscriptions,
canonicalCreator,
isLivestream,
creatorUri,
inputRef,
showMature,
noTopSuggestion,
mentionTerm,
doResolveUris,
customSelectAction,
} = props;
const comboboxInputRef: ElementRef<any> = React.useRef();
const comboboxListRef: ElementRef<any> = React.useRef();
const mainEl = document.querySelector('.channel-mention__suggestions');
const [debouncedTerm, setDebouncedTerm] = React.useState('');
const [mostSupported, setMostSupported] = React.useState('');
const [canonicalResults, setCanonicalResults] = React.useState([]);
const isRefFocused = (ref) => ref && ref.current === document.activeElement;
const subscriptionUris = props.subscriptionUris.filter((uri) => uri !== creatorUri);
const canonicalSubscriptions = props.canonicalSubscriptions.filter((uri) => uri !== canonicalCreator);
const commentorUris = props.commentorUris.filter((uri) => uri !== creatorUri && !subscriptionUris.includes(uri));
const canonicalCommentors = props.canonicalCommentors.filter(
(uri) => uri !== canonicalCreator && !canonicalSubscriptions.includes(uri)
);
const termToMatch = mentionTerm && mentionTerm.replace('@', '').toLowerCase();
const allShownUris = [creatorUri, ...subscriptionUris, ...commentorUris];
const allShownCanonical = [canonicalCreator, ...canonicalSubscriptions, ...canonicalCommentors];
const possibleMatches = allShownUris.filter((uri) => {
try {
const { channelName } = parseURI(uri);
return channelName.toLowerCase().includes(termToMatch);
} catch (e) {}
});
const searchSize = 5;
const additionalOptions = { isBackgroundSearch: false, [SEARCH_OPTIONS.CLAIM_TYPE]: SEARCH_OPTIONS.INCLUDE_CHANNELS };
const { results, loading } = useLighthouse(debouncedTerm, showMature, searchSize, additionalOptions, 0);
const stringifiedResults = JSON.stringify(results);
const hasMinLength = mentionTerm && mentionTerm.length >= LIGHTHOUSE_MIN_CHARACTERS;
const isTyping = debouncedTerm !== mentionTerm;
const showPlaceholder = isTyping || loading;
const isUriFromTermValid = !regexInvalidURI.test(mentionTerm.substring(1));
const handleSelect = React.useCallback(
(value, key) => {
if (customSelectAction) {
// Give them full results, as our resolved one might truncate the claimId.
customSelectAction(value || (results && results.find((r) => r.startsWith(value))) || '', Number(key));
}
},
[customSelectAction, results]
);
React.useEffect(() => {
const timer = setTimeout(() => {
if (isTyping) setDebouncedTerm(!hasMinLength ? '' : mentionTerm);
}, INPUT_DEBOUNCE_MS);
return () => clearTimeout(timer);
}, [hasMinLength, isTyping, mentionTerm]);
React.useEffect(() => {
if (!mainEl) return;
const header = document.querySelector('.header__navigation');
function handleReflow() {
const boxAtTopOfPage = header && mainEl.getBoundingClientRect().top <= header.offsetHeight;
const boxAtBottomOfPage = mainEl.getBoundingClientRect().bottom >= window.innerHeight;
if (boxAtTopOfPage) {
mainEl.setAttribute('flow-bottom', '');
}
if (mainEl.getAttribute('flow-bottom') !== null && boxAtBottomOfPage) {
mainEl.removeAttribute('flow-bottom');
}
}
handleReflow();
window.addEventListener('scroll', handleReflow);
return () => window.removeEventListener('scroll', handleReflow);
}, [mainEl]);
React.useEffect(() => {
if (!inputRef || !comboboxInputRef || !mentionTerm) return;
function handleKeyDown(event) {
const { keyCode } = event;
const activeElement = document.activeElement;
if (keyCode === KEYCODES.UP || keyCode === KEYCODES.DOWN) {
if (isRefFocused(comboboxInputRef)) {
const selectedId = activeElement && activeElement.getAttribute('aria-activedescendant');
const selectedItem = selectedId && document.querySelector(`li[id="${selectedId}"]`);
if (selectedItem) selectedItem.scrollIntoView({ block: 'nearest', inline: 'nearest' });
} else {
// $FlowFixMe
comboboxInputRef.current.focus();
}
} else {
if ((isRefFocused(comboboxInputRef) || isRefFocused(inputRef)) && keyCode === KEYCODES.TAB) {
event.preventDefault();
const activeValue = activeElement && activeElement.getAttribute('value');
if (activeValue) {
handleSelect(activeValue, keyCode);
} else if (possibleMatches.length) {
// $FlowFixMe
const suggest = allShownCanonical.find((matchUri) => possibleMatches.find((uri) => uri.includes(matchUri)));
if (suggest) handleSelect(suggest, keyCode);
} else if (results) {
handleSelect(mentionTerm, keyCode);
}
}
if (isRefFocused(comboboxInputRef)) {
// $FlowFixMe
inputRef.current.focus();
}
}
}
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [allShownCanonical, handleSelect, inputRef, mentionTerm, possibleMatches, results]);
React.useEffect(() => {
if (!stringifiedResults) return;
const arrayResults = JSON.parse(stringifiedResults);
if (arrayResults && arrayResults.length > 0) {
// $FlowFixMe
doResolveUris(arrayResults).then((response) => {
try {
// $FlowFixMe
const canonical_urls = Object.values(response).map(({ canonical_url }) => canonical_url);
setCanonicalResults(canonical_urls);
} catch (e) {}
});
}
}, [doResolveUris, stringifiedResults]);
// Only resolve commentors on Livestreams when actually mentioning/looking for it
React.useEffect(() => {
if (isLivestream && unresolvedCommentors && mentionTerm) doResolveUris(unresolvedCommentors);
}, [doResolveUris, isLivestream, mentionTerm, unresolvedCommentors]);
// Only resolve the subscriptions that match the mention term, instead of all
React.useEffect(() => {
if (isTyping) return;
const urisToResolve = [];
subscriptionUris.map(
(uri) =>
hasMinLength &&
possibleMatches.includes(uri) &&
unresolvedSubscriptions.includes(uri) &&
urisToResolve.push(uri)
);
if (urisToResolve.length > 0) doResolveUris(urisToResolve);
}, [doResolveUris, hasMinLength, isTyping, possibleMatches, subscriptionUris, unresolvedSubscriptions]);
const suggestionsRow = (
label: string,
suggestions: Array<string>,
canonical: Array<string>,
hasSuggestionsBelow: boolean
) => {
if (mentionTerm.length > 1 && suggestions !== results) {
suggestions = suggestions.filter((uri) => possibleMatches.includes(uri));
} else if (suggestions === results) {
suggestions = suggestions.filter((uri) => !allShownUris.includes(uri));
}
// $FlowFixMe
suggestions = suggestions
.map((matchUri) => canonical.find((uri) => matchUri.includes(uri)))
.filter((uri) => Boolean(uri));
if (canonical === canonicalResults) {
suggestions = suggestions.filter((uri) => uri !== mostSupported);
}
return !suggestions.length ? null : (
<>
<div className="channel-mention__label">{label}</div>
{suggestions.map((uri) => (
<ChannelMentionSuggestion key={uri} uri={uri} />
))}
{hasSuggestionsBelow && <hr className="channel-mention__top-separator" />}
</>
);
};
return isRefFocused(inputRef) || isRefFocused(comboboxInputRef) ? (
<Form onSubmit={() => handleSelect(mentionTerm)}>
<Combobox className="channel-mention" onSelect={handleSelect}>
<ComboboxInput ref={comboboxInputRef} className="channel-mention__input--none" value={mentionTerm} />
{mentionTerm && isUriFromTermValid && (
<ComboboxPopover portal={false} className="channel-mention__suggestions">
<ComboboxList ref={comboboxListRef}>
{creatorUri &&
suggestionsRow(
__('Creator'),
[creatorUri],
[canonicalCreator],
canonicalSubscriptions.length > 0 || commentorUris.length > 0 || !showPlaceholder
)}
{canonicalSubscriptions.length > 0 &&
suggestionsRow(
__('Following'),
subscriptionUris,
canonicalSubscriptions,
commentorUris.length > 0 || !showPlaceholder
)}
{commentorUris.length > 0 &&
suggestionsRow(__('From comments'), commentorUris, canonicalCommentors, !showPlaceholder)}
{hasMinLength &&
(showPlaceholder ? (
<Spinner type="small" />
) : (
results && (
<>
{!noTopSuggestion && (
<ChannelMentionTopSuggestion
query={debouncedTerm}
shownUris={allShownCanonical}
setMostSupported={(winningUri) => setMostSupported(winningUri)}
/>
)}
{suggestionsRow(__('From search'), results, canonicalResults, false)}
</>
)
))}
</ComboboxList>
</ComboboxPopover>
)}
</Combobox>
</Form>
) : null;
}
@@ -0,0 +1,15 @@
import { connect } from 'react-redux';
import { makeSelectIsUriResolving, doResolveUri } from 'lbry-redux';
import { makeSelectWinningUriForQuery } from 'redux/selectors/search';
import ChannelMentionTopSuggestion from './view';
const select = (state, props) => {
const uriFromQuery = `lbry://${props.query}`;
return {
uriFromQuery,
isResolvingUri: makeSelectIsUriResolving(uriFromQuery)(state),
winningUri: makeSelectWinningUriForQuery(props.query)(state),
};
};
export default connect(select, { doResolveUri })(ChannelMentionTopSuggestion);
@@ -0,0 +1,49 @@
// @flow
import ChannelMentionSuggestion from 'component/channelMentionSuggestion';
import LbcSymbol from 'component/common/lbc-symbol';
import React from 'react';
type Props = {
uriFromQuery: string,
winningUri: string,
isResolvingUri: boolean,
shownUris: Array<string>,
setMostSupported: (string) => void,
doResolveUri: (string) => void,
};
export default function ChannelMentionTopSuggestion(props: Props) {
const { uriFromQuery, winningUri, isResolvingUri, shownUris, setMostSupported, doResolveUri } = props;
React.useEffect(() => {
if (uriFromQuery) doResolveUri(uriFromQuery);
}, [doResolveUri, uriFromQuery]);
React.useEffect(() => {
if (winningUri) setMostSupported(winningUri);
}, [setMostSupported, winningUri]);
if (isResolvingUri) {
return (
<div className="channel-mention__winning-claim">
<div className="channel-mention__label channel-mention__placeholder-label" />
<div className="channel-mention__suggestion channel-mention__placeholder-suggestion">
<div className="channel-mention__placeholder-thumbnail" />
<div className="channel-mention__placeholder-info" />
</div>
<hr className="channel-mention__top-separator" />
</div>
);
}
return !winningUri || shownUris.includes(winningUri) ? null : (
<>
<div className="channel-mention__label">
<LbcSymbol prefix={__('Most Supported')} />
</div>
<ChannelMentionSuggestion uri={winningUri} />
<hr className="channel-mention__top-separator" />
</>
);
}
+20 -10
View File
@@ -1,22 +1,32 @@
import { connect } from 'react-redux';
import { doResolveUri, makeSelectTitleForUri, makeSelectClaimForUri, makeSelectIsUriResolving } from 'lbry-redux';
import { doResolveUri, makeSelectClaimForUri, makeSelectIsUriResolving } from 'lbry-redux';
import { doSetPlayingUri } from 'redux/actions/content';
import { selectBlackListedOutpoints } from 'lbryinc';
import { selectPlayingUri } from 'redux/selectors/content';
import { doSetPlayingUri } from 'redux/actions/content';
import ClaimLink from './view';
const select = (state, props) => {
let uri = props.uri;
let claim;
function getValidClaim(testUri) {
claim = makeSelectClaimForUri(testUri)(state);
if (claim === null) {
getValidClaim(testUri.substring(0, testUri.length - 1));
} else {
uri = testUri;
}
}
getValidClaim(uri);
return {
uri: props.uri,
claim: makeSelectClaimForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
isResolvingUri: makeSelectIsUriResolving(props.uri)(state),
uri,
claim,
fullUri: props.uri,
isResolvingUri: makeSelectIsUriResolving(uri)(state),
blackListedOutpoints: selectBlackListedOutpoints(state),
playingUri: selectPlayingUri(state),
};
};
export default connect(select, {
doResolveUri,
doSetPlayingUri,
})(ClaimLink);
export default connect(select, { doResolveUri, doSetPlayingUri })(ClaimLink);
+11 -6
View File
@@ -1,14 +1,15 @@
// @flow
import * as React from 'react';
import classnames from 'classnames';
import EmbedPlayButton from 'component/embedPlayButton';
import Button from 'component/button';
import UriIndicator from 'component/uriIndicator';
import { INLINE_PLAYER_WRAPPER_CLASS } from 'component/fileRenderFloating/view';
import { SIMPLE_SITE } from 'config';
import * as React from 'react';
import Button from 'component/button';
import classnames from 'classnames';
import EmbedPlayButton from 'component/embedPlayButton';
import UriIndicator from 'component/uriIndicator';
type Props = {
uri: string,
fullUri: string,
claim: StreamClaim,
children: React.Node,
description: ?string,
@@ -68,6 +69,7 @@ class ClaimLink extends React.Component<Props> {
render() {
const {
uri,
fullUri,
claim,
children,
isResolvingUri,
@@ -92,7 +94,10 @@ class ClaimLink extends React.Component<Props> {
const isChannel = valueType === 'channel';
return isChannel ? (
<UriIndicator uri={uri} link />
<>
<UriIndicator uri={uri} link />
<span>{fullUri.length > uri.length ? fullUri.substring(uri.length, fullUri.length) : ''}</span>
</>
) : allowPreview ? (
<div className={classnames('claim-link')}>
<div
+1 -3
View File
@@ -1,12 +1,10 @@
import { connect } from 'react-redux';
import ClaimList from './view';
import { SETTINGS, selectClaimSearchByQuery, selectClaimsByUri } from 'lbry-redux';
import { SETTINGS } from 'lbry-redux';
import { makeSelectClientSetting } from 'redux/selectors/settings';
const select = (state) => ({
searchInLanguage: makeSelectClientSetting(SETTINGS.SEARCH_IN_LANGUAGE)(state),
claimSearchByQuery: selectClaimSearchByQuery(state),
claimsByUri: selectClaimsByUri(state),
});
export default connect(select)(ClaimList);
+8 -24
View File
@@ -9,7 +9,6 @@ import { FormField } from 'component/common/form';
import usePersistedState from 'effects/use-persisted-state';
import debounce from 'util/debounce';
import ClaimPreviewTile from 'component/claimPreviewTile';
import { prioritizeActiveLivestreams } from 'component/claimTilesDiscover/view';
const DEBOUNCE_SCROLL_HANDLER_MS = 150;
const SORT_NEW = 'new';
@@ -17,6 +16,7 @@ const SORT_OLD = 'old';
type Props = {
uris: Array<string>,
prefixUris?: Array<string>,
header: Node | boolean,
headerAltControls: Node,
loading: boolean,
@@ -41,9 +41,6 @@ type Props = {
hideMenu?: boolean,
claimSearchByQuery: { [string]: Array<string> },
claimsByUri: { [string]: any },
liveLivestreamsFirst?: boolean,
livestreamMap?: { [string]: any },
searchOptions?: any,
collectionId?: string,
showNoSourceClaims?: boolean,
onClick?: (e: any, claim?: ?Claim, index?: number) => void,
@@ -53,6 +50,7 @@ export default function ClaimList(props: Props) {
const {
activeUri,
uris,
prefixUris,
headerAltControls,
loading,
persistedStorageKey,
@@ -73,37 +71,25 @@ export default function ClaimList(props: Props) {
renderProperties,
searchInLanguage,
hideMenu,
claimSearchByQuery,
claimsByUri,
liveLivestreamsFirst,
livestreamMap,
searchOptions,
collectionId,
showNoSourceClaims,
onClick,
} = props;
const [currentSort, setCurrentSort] = usePersistedState(persistedStorageKey, SORT_NEW);
// Exclude prefix uris in these results variables. We don't want to show
// anything if the search failed or timed out.
const timedOut = uris === null;
const urisLength = (uris && uris.length) || 0;
const liveUris = [];
if (liveLivestreamsFirst && livestreamMap) {
prioritizeActiveLivestreams(uris, liveUris, livestreamMap, claimsByUri, claimSearchByQuery, searchOptions);
}
const tileUris = (prefixUris || []).concat(uris);
const sortedUris = (urisLength > 0 && (currentSort === SORT_NEW ? tileUris : tileUris.slice().reverse())) || [];
const sortedUris = (urisLength > 0 && (currentSort === SORT_NEW ? uris : uris.slice().reverse())) || [];
const noResultMsg = searchInLanguage
? __('No results. Contents may be hidden by the Language filter.')
: __('No results');
const resolveLive = (index) => {
if (liveLivestreamsFirst && livestreamMap && index < liveUris.length) {
return true;
}
return undefined;
};
function handleSortChange() {
setCurrentSort(currentSort === SORT_NEW ? SORT_OLD : SORT_NEW);
}
@@ -138,13 +124,12 @@ export default function ClaimList(props: Props) {
return tileLayout && !header ? (
<section className="claim-grid">
{urisLength > 0 &&
uris.map((uri, index) => (
tileUris.map((uri) => (
<ClaimPreviewTile
key={uri}
uri={uri}
showHiddenByUser={showHiddenByUser}
properties={renderProperties}
live={resolveLive(index)}
collectionId={collectionId}
showNoSourceClaims={showNoSourceClaims}
/>
@@ -216,7 +201,6 @@ export default function ClaimList(props: Props) {
// https://github.com/lbryio/lbry-redux/blob/master/src/redux/actions/publish.js#L74-L79
return claim.name.length === 24 && !claim.name.includes(' ') && claim.value.author === 'Spee.ch';
}}
live={resolveLive(index)}
onClick={(e, claim, index) => handleClaimClicked(e, claim, index)}
/>
</React.Fragment>
+14 -82
View File
@@ -13,11 +13,12 @@ import ClaimPreview from 'component/claimPreview';
import ClaimPreviewTile from 'component/claimPreviewTile';
import I18nMessage from 'component/i18nMessage';
import ClaimListHeader from 'component/claimListHeader';
import useFetchViewCount from 'effects/use-fetch-view-count';
import { useIsLargeScreen } from 'effects/use-screensize';
import { getLivestreamOnlyOptions } from 'util/search';
type Props = {
uris: Array<string>,
prefixUris?: Array<string>,
name?: string,
type: string,
pageSize?: number,
@@ -31,7 +32,6 @@ type Props = {
includeSupportAction?: boolean,
infiniteScroll?: Boolean,
isChannel?: boolean,
liveLivestreamsFirst?: boolean,
personalView: boolean,
showHeader: boolean,
showHiddenByUser?: boolean,
@@ -64,7 +64,6 @@ type Props = {
channelIds?: Array<string>,
claimIds?: Array<string>,
subscribedChannels: Array<Subscription>,
livestreamMap?: { [string]: any },
header?: Node,
headerLabel?: string | Node,
@@ -137,6 +136,7 @@ function ClaimListDiscover(props: Props) {
injectedItem,
feeAmount,
uris,
prefixUris,
tileLayout,
hideFilters = false,
claimIds,
@@ -148,8 +148,6 @@ function ClaimListDiscover(props: Props) {
releaseTime,
scrollAnchor,
showHiddenByUser = false,
liveLivestreamsFirst,
livestreamMap,
hasSource,
hasNoSource,
isChannel = false,
@@ -380,9 +378,9 @@ function ClaimListDiscover(props: Props) {
const hasMatureTags = tagsParam && tagsParam.split(',').some((t) => MATURE_TAGS.includes(t));
const mainSearchKey = createNormalizedClaimSearchKey(options);
let claimSearchResult = claimSearchByQuery[mainSearchKey];
const claimSearchResultLastPageReached = claimSearchByQueryLastPageReached[mainSearchKey];
const searchKey = createNormalizedClaimSearchKey(options);
const claimSearchResult = claimSearchByQuery[searchKey];
const claimSearchResultLastPageReached = claimSearchByQueryLastPageReached[searchKey];
// uncomment to fix an item on a page
// const fixUri = 'lbry://@corbettreport#0/lbryodysee#5';
@@ -400,14 +398,6 @@ function ClaimListDiscover(props: Props) {
// claimSearchResult.splice(2, 0, fixUri);
// }
const livestreamSearchKey = liveLivestreamsFirst
? createNormalizedClaimSearchKey(getLivestreamOnlyOptions(options))
: undefined;
const livestreamSearchResult = livestreamSearchKey && claimSearchByQuery[livestreamSearchKey];
const [finalUris, setFinalUris] = React.useState(
getFinalUrisInitialState(history.action === 'POP', claimSearchResult)
);
const [prevOptions, setPrevOptions] = React.useState(null);
if (!isJustScrollingToNewPage(prevOptions, options)) {
@@ -469,6 +459,8 @@ function ClaimListDiscover(props: Props) {
</div>
);
const renderUris = uris || claimSearchResult;
// **************************************************************************
// Helpers
// **************************************************************************
@@ -514,41 +506,6 @@ function ClaimListDiscover(props: Props) {
}
}
function urisEqual(prev: Array<string>, next: Array<string>) {
if (!prev || !next) {
// From 'ClaimList', "null" and "undefined" have special meaning,
// so we can't just compare array length here.
// - null = "timed out"
// - undefined = "no result".
return prev === next;
}
return prev.length === next.length && prev.every((value, index) => value === next[index]);
}
function getFinalUrisInitialState(isNavigatingBack, claimSearchResult) {
if (isNavigatingBack && claimSearchResult && claimSearchResult.length > 0) {
return claimSearchResult;
} else {
return [];
}
}
function fetchViewCountForUris(uris) {
const claimIds = [];
if (uris) {
uris.forEach((uri) => {
if (claimsByUri[uri]) {
claimIds.push(claimsByUri[uri].claim_id);
}
});
}
if (claimIds.length > 0) {
doFetchViewCount(claimIds.join(','));
}
}
function resolveOrderByOption(orderBy: string | Array<string>, sortBy: string | Array<string>) {
const order_by =
orderBy === CS.ORDER_BY_TRENDING
@@ -567,38 +524,15 @@ function ClaimListDiscover(props: Props) {
// **************************************************************************
// **************************************************************************
useFetchViewCount(fetchViewCount, renderUris, claimsByUri, doFetchViewCount);
React.useEffect(() => {
if (shouldPerformSearch) {
const searchOptions = JSON.parse(optionsStringForEffect);
doClaimSearch(searchOptions);
if (liveLivestreamsFirst && options.page === 1) {
doClaimSearch(getLivestreamOnlyOptions(searchOptions));
}
}
}, [doClaimSearch, shouldPerformSearch, optionsStringForEffect, forceRefresh]);
// Resolve 'finalUri'
React.useEffect(() => {
if (uris) {
if (!urisEqual(uris, finalUris)) {
setFinalUris(uris);
}
} else {
// Wait until all queries are done before updating the uris to avoid layout shifts.
const pending = claimSearchResult === undefined || (liveLivestreamsFirst && livestreamSearchResult === undefined);
if (!pending && !urisEqual(claimSearchResult, finalUris)) {
setFinalUris(claimSearchResult);
}
}
}, [uris, claimSearchResult, finalUris, setFinalUris, liveLivestreamsFirst, livestreamSearchResult]);
React.useEffect(() => {
if (fetchViewCount) {
fetchViewCountForUris(finalUris);
}
}, [finalUris]); // eslint-disable-line react-hooks/exhaustive-deps
const headerToUse = header || (
<ClaimListHeader
channelIds={channelIds}
@@ -636,7 +570,8 @@ function ClaimListDiscover(props: Props) {
<ClaimList
tileLayout
loading={loading}
uris={finalUris}
uris={renderUris}
prefixUris={prefixUris}
onScrollBottom={handleScrollBottom}
page={page}
pageSize={dynamicPageSize}
@@ -645,8 +580,6 @@ function ClaimListDiscover(props: Props) {
includeSupportAction={includeSupportAction}
injectedItem={injectedItem}
showHiddenByUser={showHiddenByUser}
liveLivestreamsFirst={liveLivestreamsFirst}
livestreamMap={livestreamMap}
searchOptions={options}
showNoSourceClaims={showNoSourceClaims}
empty={empty}
@@ -670,7 +603,8 @@ function ClaimListDiscover(props: Props) {
<ClaimList
type={type}
loading={loading}
uris={finalUris}
uris={renderUris}
prefixUris={prefixUris}
onScrollBottom={handleScrollBottom}
page={page}
pageSize={dynamicPageSize}
@@ -679,8 +613,6 @@ function ClaimListDiscover(props: Props) {
includeSupportAction={includeSupportAction}
injectedItem={injectedItem}
showHiddenByUser={showHiddenByUser}
liveLivestreamsFirst={liveLivestreamsFirst}
livestreamMap={livestreamMap}
searchOptions={options}
showNoSourceClaims={hasNoSource || showNoSourceClaims}
empty={empty}
+2
View File
@@ -20,6 +20,7 @@ import {
} from 'lbry-redux';
import { selectMutedChannels, makeSelectChannelIsMuted } from 'redux/selectors/blocked';
import { selectBlackListedOutpoints, selectFilteredOutpoints } from 'lbryinc';
import { makeSelectIsActiveLivestream } from 'redux/selectors/livestream';
import { selectShowMatureContent } from 'redux/selectors/settings';
import { makeSelectHasVisitedUri } from 'redux/selectors/content';
import { makeSelectIsSubscribed } from 'redux/selectors/subscriptions';
@@ -56,6 +57,7 @@ const select = (state, props) => {
streamingUrl: props.uri && makeSelectStreamingUrlForUri(props.uri)(state),
wasPurchased: props.uri && makeSelectClaimWasPurchased(props.uri)(state),
isLivestream: makeSelectClaimIsStreamPlaceholder(props.uri)(state),
isLivestreamActive: makeSelectIsActiveLivestream(props.uri)(state),
isCollectionMine: makeSelectCollectionIsMine(props.collectionId)(state),
collectionUris: makeSelectUrlsForCollectionId(props.collectionId)(state),
collectionIndex: makeSelectIndexForUrlInCollection(props.uri, props.collectionId)(state),
+5 -5
View File
@@ -80,7 +80,7 @@ type Props = {
repostUrl?: string,
hideMenu?: boolean,
isLivestream?: boolean,
live?: boolean,
isLivestreamActive: boolean,
collectionId?: string,
editCollection: (string, CollectionEditParams) => void,
isCollectionMine: boolean,
@@ -145,7 +145,7 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
hideMenu = false,
// repostUrl,
isLivestream, // need both? CHECK
live,
isLivestreamActive,
collectionId,
collectionIndex,
editCollection,
@@ -336,7 +336,7 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
}
let liveProperty = null;
if (live === true) {
if (isLivestreamActive === true) {
liveProperty = (claim) => <>LIVE</>;
}
@@ -349,7 +349,7 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
'claim-preview__wrapper--channel': isChannelUri && type !== 'inline',
'claim-preview__wrapper--inline': type === 'inline',
'claim-preview__wrapper--small': type === 'small',
'claim-preview__live': live,
'claim-preview__live': isLivestreamActive,
'claim-preview__active': active,
})}
>
@@ -386,7 +386,7 @@ const ClaimPreview = forwardRef<any, {}>((props: Props, ref: any) => {
)}
</div>
{/* @endif */}
{!isLivestream && (
{(!isLivestream || isLivestreamActive) && (
<div className="claim-preview__file-property-overlay">
<PreviewOverlayProperties uri={uri} small={type === 'small'} properties={liveProperty} />
</div>
@@ -16,6 +16,7 @@ type Props = {
isLivestream: boolean,
};
// previews used in channel overview and homepage (and other places?)
function ClaimPreviewSubtitle(props: Props) {
const { pending, uri, claim, type, beginPublish, isLivestream } = props;
const claimsInChannel = (claim && claim.meta.claims_in_channel) || 0;
+4 -1
View File
@@ -12,7 +12,8 @@ import {
makeSelectDateForUri,
} from 'lbry-redux';
import { selectMutedChannels } from 'redux/selectors/blocked';
import { selectBlackListedOutpoints, selectFilteredOutpoints } from 'lbryinc';
import { makeSelectViewCountForUri, selectBlackListedOutpoints, selectFilteredOutpoints } from 'lbryinc';
import { makeSelectIsActiveLivestream } from 'redux/selectors/livestream';
import { selectShowMatureContent } from 'redux/selectors/settings';
import ClaimPreviewTile from './view';
import formatMediaDuration from 'util/formatMediaDuration';
@@ -36,6 +37,8 @@ const select = (state, props) => {
showMature: selectShowMatureContent(state),
isMature: makeSelectClaimIsNsfw(props.uri)(state),
isLivestream: makeSelectClaimIsStreamPlaceholder(props.uri)(state),
isLivestreamActive: makeSelectIsActiveLivestream(props.uri)(state),
viewCount: makeSelectViewCountForUri(props.uri)(state),
};
};
+48 -8
View File
@@ -48,13 +48,14 @@ type Props = {
showMature: boolean,
showHiddenByUser?: boolean,
properties?: (Claim) => void,
live?: boolean,
collectionId?: string,
showNoSourceClaims?: boolean,
isLivestream: boolean,
viewCount: string,
isLivestreamActive: boolean,
};
// preview image cards used in related video functionality
// preview image cards used in related video functionality, channel overview page and homepage
function ClaimPreviewTile(props: Props) {
const {
history,
@@ -75,11 +76,12 @@ function ClaimPreviewTile(props: Props) {
showMature,
showHiddenByUser,
properties,
live,
showNoSourceClaims,
isLivestream,
isLivestreamActive,
collectionId,
mediaDuration,
viewCount,
} = props;
const isRepost = claim && claim.repost_channel_url;
const isCollection = claim && claim.value_type === 'collection';
@@ -177,6 +179,10 @@ function ClaimPreviewTile(props: Props) {
return null;
}
const isChannelPage = window.location.pathname.startsWith('/@');
const shouldShowViewCount = !(!viewCount || (claim && claim.repost_url) || isLivestream || !isChannelPage);
if (placeholder || (!claim && isResolvingUri)) {
return (
<li className={classnames('claim-preview--tile', {})}>
@@ -185,14 +191,16 @@ function ClaimPreviewTile(props: Props) {
</div>
<div className="placeholder__wrapper">
<div className="placeholder claim-tile__title" />
<div className="placeholder claim-tile__info" />
<div className={classnames('claim-tile__info placeholder', {
'contains_view_count': shouldShowViewCount,
})} />
</div>
</li>
);
}
let liveProperty = null;
if (live === true) {
if (isLivestreamActive === true) {
liveProperty = (claim) => <>LIVE</>;
}
@@ -201,7 +209,7 @@ function ClaimPreviewTile(props: Props) {
onClick={handleClick}
className={classnames('card claim-preview--tile', {
'claim-preview__wrapper--channel': isChannel,
'claim-preview__live': live,
'claim-preview__live': isLivestreamActive,
})}
>
<NavLink {...navLinkProps} role="none" tabIndex={-1} aria-hidden>
@@ -245,7 +253,9 @@ function ClaimPreviewTile(props: Props) {
<ClaimMenuList uri={uri} collectionId={listId} channelUri={channelUri} />
</div>
<div>
<div className="claim-tile__info">
<div className={classnames('claim-tile__info', {
'contains_view_count': shouldShowViewCount,
})}>
{isChannel ? (
<div className="claim-tile__about--channel">
<SubscribeButton uri={repostedChannelUri || uri} />
@@ -276,4 +286,34 @@ function ClaimPreviewTile(props: Props) {
);
}
export default withRouter(ClaimPreviewTile);
export default React.memo<Props>(withRouter(ClaimPreviewTile), areEqual);
const BLOCKLIST_KEYS = ['blackListedOutpoints', 'filteredOutpoints', 'blockedChannelUris'];
const HANDLED_KEYS = [...BLOCKLIST_KEYS, 'date'];
function areEqual(prev: Props, next: Props) {
for (let i = 0; i < BLOCKLIST_KEYS.length; ++i) {
const key = BLOCKLIST_KEYS[i];
const a = prev[key];
const b = next[key];
if (((!a || !b) && a !== b) || (a && b && a.length !== b.length)) {
// The arrays are huge, so just compare the length instead of each entry.
return false;
}
}
if (Number(prev.date) !== Number(next.date)) {
return false;
}
const propKeys = Object.keys(next);
for (let i = 0; i < propKeys.length; ++i) {
const pk = propKeys[i];
if (!HANDLED_KEYS.includes(pk) && prev[pk] !== next[pk]) {
return false;
}
}
return true;
}
+114 -12
View File
@@ -1,27 +1,36 @@
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import {
doClaimSearch,
selectClaimSearchByQuery,
selectFetchingClaimSearchByQuery,
SETTINGS,
selectClaimsByUri,
MATURE_TAGS,
} from 'lbry-redux';
import { doFetchViewCount } from 'lbryinc';
import { doToggleTagFollowDesktop } from 'redux/actions/tags';
import { makeSelectClientSetting, selectShowMatureContent } from 'redux/selectors/settings';
import { selectModerationBlockList } from 'redux/selectors/comments';
import { selectMutedChannels } from 'redux/selectors/blocked';
import { selectMutedAndBlockedChannelIds } from 'redux/selectors/blocked';
import { ENABLE_NO_SOURCE_CLAIMS, SIMPLE_SITE } from 'config';
import * as CS from 'constants/claim_search';
import ClaimListDiscover from './view';
const select = (state) => ({
claimSearchByQuery: selectClaimSearchByQuery(state),
claimsByUri: selectClaimsByUri(state),
fetchingClaimSearchByQuery: selectFetchingClaimSearchByQuery(state),
showNsfw: selectShowMatureContent(state),
hideReposts: makeSelectClientSetting(SETTINGS.HIDE_REPOSTS)(state),
mutedUris: selectMutedChannels(state),
blockedUris: selectModerationBlockList(state),
});
const select = (state, props) => {
const showNsfw = selectShowMatureContent(state);
const hideReposts = makeSelectClientSetting(SETTINGS.HIDE_REPOSTS)(state);
const mutedAndBlockedChannelIds = selectMutedAndBlockedChannelIds(state);
return {
claimSearchByQuery: selectClaimSearchByQuery(state),
claimsByUri: selectClaimsByUri(state),
fetchingClaimSearchByQuery: selectFetchingClaimSearchByQuery(state),
showNsfw,
hideReposts,
options: resolveSearchOptions({ showNsfw, hideReposts, mutedAndBlockedChannelIds, pageSize: 8, ...props }),
};
};
const perform = {
doClaimSearch,
@@ -29,4 +38,97 @@ const perform = {
doFetchViewCount,
};
export default connect(select, perform)(ClaimListDiscover);
export default withRouter(connect(select, perform)(ClaimListDiscover));
// ****************************************************************************
// ****************************************************************************
function resolveSearchOptions(props) {
const {
showNsfw,
hideReposts,
mutedAndBlockedChannelIds,
location,
pageSize,
claimType,
tags,
languages,
channelIds,
orderBy,
streamTypes,
hasNoSource,
hasSource,
releaseTime,
feeAmount,
limitClaimsPerChannel,
timestamp,
claimIds,
} = props;
const urlParams = new URLSearchParams(location.search);
const feeAmountInUrl = urlParams.get('fee_amount');
const feeAmountParam = feeAmountInUrl || feeAmount;
let streamTypesParam;
if (streamTypes) {
streamTypesParam = streamTypes;
} else if (SIMPLE_SITE && !hasNoSource && streamTypes !== null) {
streamTypesParam = [CS.FILE_VIDEO, CS.FILE_AUDIO];
}
const options = {
page_size: pageSize,
claim_type: claimType || ['stream', 'repost', 'channel'],
// no_totals makes it so the sdk doesn't have to calculate total number pages for pagination
// it's faster, but we will need to remove it if we start using total_pages
no_totals: true,
any_tags: tags || [],
not_tags: !showNsfw ? MATURE_TAGS : [],
any_languages: languages,
channel_ids: channelIds || [],
not_channel_ids: mutedAndBlockedChannelIds,
order_by: orderBy || ['trending_group', 'trending_mixed'],
stream_types: streamTypesParam,
};
if (ENABLE_NO_SOURCE_CLAIMS && hasNoSource) {
options.has_no_source = true;
} else if (hasSource || (!ENABLE_NO_SOURCE_CLAIMS && (!claimType || claimType === 'stream'))) {
options.has_source = true;
}
if (releaseTime) {
options.release_time = releaseTime;
}
if (feeAmountParam) {
options.fee_amount = feeAmountParam;
}
if (limitClaimsPerChannel) {
options.limit_claims_per_channel = limitClaimsPerChannel;
}
// https://github.com/lbryio/lbry-desktop/issues/3774
if (hideReposts) {
if (Array.isArray(options.claim_type)) {
options.claim_type = options.claim_type.filter((claimType) => claimType !== 'repost');
} else {
options.claim_type = ['stream', 'channel'];
}
}
if (claimType) {
options.claim_type = claimType;
}
if (timestamp) {
options.timestamp = timestamp;
}
if (claimIds) {
options.claim_ids = claimIds;
}
return options;
}
+133 -272
View File
@@ -1,83 +1,42 @@
// @flow
import { ENABLE_NO_SOURCE_CLAIMS, SIMPLE_SITE } from 'config';
import * as CS from 'constants/claim_search';
import type { Node } from 'react';
import React from 'react';
import { createNormalizedClaimSearchKey, MATURE_TAGS, splitBySeparator } from 'lbry-redux';
import { createNormalizedClaimSearchKey } from 'lbry-redux';
import ClaimPreviewTile from 'component/claimPreviewTile';
import { useHistory } from 'react-router';
import { getLivestreamOnlyOptions } from 'util/search';
import useFetchViewCount from 'effects/use-fetch-view-count';
import usePrevious from 'effects/use-previous';
/**
* Updates 'uris' by adding and/or moving active livestreams to the front of
* list.
* 'liveUris' is also updated with any entries that were moved to the
* front, for convenience.
*
* @param uris [Ref]
* @param liveUris [Ref]
* @param livestreamMap
* @param claimsByUri
* @param claimSearchByQuery
* @param options
*/
export function prioritizeActiveLivestreams(
uris: Array<string>,
liveUris: Array<string>,
livestreamMap: { [string]: any },
claimsByUri: { [string]: any },
claimSearchByQuery: { [string]: Array<string> },
options: any
) {
if (!livestreamMap || !uris) return;
type SearchOptions = {
page_size: number,
no_totals: boolean,
any_tags: Array<string>,
channel_ids: Array<string>,
claim_ids?: Array<string>,
not_channel_ids: Array<string>,
not_tags: Array<string>,
order_by: Array<string>,
languages?: Array<string>,
release_time?: string,
claim_type?: string | Array<string>,
timestamp?: string,
fee_amount?: string,
limit_claims_per_channel?: number,
stream_types?: Array<string>,
has_source?: boolean,
has_no_source?: boolean,
};
const claimIsLive = (claim, liveChannelIds) => {
// This function relies on:
// 1. Only 1 actual livestream per channel (i.e. all other livestream-claims
// for that channel actually point to the same source).
// 2. 'liveChannelIds' needs to be pruned after being accounted for,
// otherwise all livestream-claims will be "live" (we'll only take the
// latest one as "live" ).
return (
claim &&
claim.value_type === 'stream' &&
claim.value.source === undefined &&
claim.signing_channel &&
liveChannelIds.includes(claim.signing_channel.claim_id)
);
};
let liveChannelIds = Object.keys(livestreamMap);
// 1. Collect active livestreams from the primary search to put in front.
uris.forEach((uri) => {
const claim = claimsByUri[uri];
if (claimIsLive(claim, liveChannelIds)) {
liveUris.push(uri);
// This live channel has been accounted for, so remove it.
liveChannelIds.splice(liveChannelIds.indexOf(claim.signing_channel.claim_id), 1);
}
});
// 2. Now, repeat on the secondary search.
if (options) {
const livestreamsOnlySearchCacheQuery = createNormalizedClaimSearchKey(getLivestreamOnlyOptions(options));
const livestreamsOnlyUris = claimSearchByQuery[livestreamsOnlySearchCacheQuery];
if (livestreamsOnlyUris) {
livestreamsOnlyUris.forEach((uri) => {
const claim = claimsByUri[uri];
if (!uris.includes(uri) && claimIsLive(claim, liveChannelIds)) {
liveUris.push(uri);
// This live channel has been accounted for, so remove it.
liveChannelIds.splice(liveChannelIds.indexOf(claim.signing_channel.claim_id), 1);
}
});
}
function urisEqual(prev: ?Array<string>, next: ?Array<string>) {
if (!prev || !next) {
// ClaimList: "null" and "undefined" have special meaning,
// so we can't just compare array length here.
// - null = "timed out"
// - undefined = "no result".
return prev === next;
}
// 3. Finalize uris by putting live livestreams in front.
const newUris = liveUris.concat(uris.filter((uri) => !liveUris.includes(uri)));
uris.splice(0, uris.length, ...newUris);
// $FlowFixMe - already checked for null above.
return prev.length === next.length && prev.every((value, index) => value === next[index]);
}
// ****************************************************************************
@@ -88,8 +47,6 @@ type Props = {
prefixUris?: Array<string>,
pinUrls?: Array<string>,
uris: Array<string>,
liveLivestreamsFirst?: boolean,
livestreamMap?: { [string]: any },
showNoSourceClaims?: boolean,
renderProperties?: (Claim) => ?Node,
fetchViewCount?: boolean,
@@ -109,13 +66,13 @@ type Props = {
hasSource?: boolean,
hasNoSource?: boolean,
// --- select ---
location: { search: string },
claimSearchByQuery: { [string]: Array<string> },
claimsByUri: { [string]: any },
fetchingClaimSearchByQuery: { [string]: boolean },
showNsfw: boolean,
hideReposts: boolean,
mutedUris: Array<string>,
blockedUris: Array<string>,
options: SearchOptions,
// --- perform ---
doClaimSearch: ({}) => void,
doFetchViewCount: (claimIdCsv: string) => void,
@@ -126,234 +83,78 @@ function ClaimTilesDiscover(props: Props) {
doClaimSearch,
claimSearchByQuery,
claimsByUri,
showNsfw,
hideReposts,
fetchViewCount,
// Below are options to pass that are forwarded to claim_search
tags,
channelIds,
claimIds,
orderBy,
pageSize = 8,
releaseTime,
languages,
claimType,
streamTypes,
timestamp,
feeAmount,
limitClaimsPerChannel,
fetchingClaimSearchByQuery,
hasSource,
hasNoSource,
renderProperties,
blockedUris,
mutedUris,
liveLivestreamsFirst,
livestreamMap,
pinUrls,
prefixUris,
showNoSourceClaims,
doFetchViewCount,
pageSize = 8,
options,
} = props;
const { location } = useHistory();
const urlParams = new URLSearchParams(location.search);
const feeAmountInUrl = urlParams.get('fee_amount');
const feeAmountParam = feeAmountInUrl || feeAmount;
const mutedAndBlockedChannelIds = Array.from(
new Set(mutedUris.concat(blockedUris).map((uri) => splitBySeparator(uri)[1]))
);
const liveUris = [];
let streamTypesParam;
if (streamTypes) {
streamTypesParam = streamTypes;
} else if (SIMPLE_SITE && !hasNoSource && streamTypes !== null) {
streamTypesParam = [CS.FILE_VIDEO, CS.FILE_AUDIO];
}
const [prevUris, setPrevUris] = React.useState([]);
const options: {
page_size: number,
no_totals: boolean,
any_tags: Array<string>,
channel_ids: Array<string>,
claim_ids?: Array<string>,
not_channel_ids: Array<string>,
not_tags: Array<string>,
order_by: Array<string>,
languages?: Array<string>,
release_time?: string,
claim_type?: string | Array<string>,
timestamp?: string,
fee_amount?: string,
limit_claims_per_channel?: number,
stream_types?: Array<string>,
has_source?: boolean,
has_no_source?: boolean,
} = {
page_size: pageSize,
claim_type: claimType || ['stream', 'repost', 'channel'],
// no_totals makes it so the sdk doesn't have to calculate total number pages for pagination
// it's faster, but we will need to remove it if we start using total_pages
no_totals: true,
any_tags: tags || [],
not_tags: !showNsfw ? MATURE_TAGS : [],
any_languages: languages,
channel_ids: channelIds || [],
not_channel_ids: mutedAndBlockedChannelIds,
order_by: orderBy || ['trending_group', 'trending_mixed'],
stream_types: streamTypesParam,
};
if (ENABLE_NO_SOURCE_CLAIMS && hasNoSource) {
options.has_no_source = true;
} else if (hasSource || (!ENABLE_NO_SOURCE_CLAIMS && (!claimType || claimType === 'stream'))) {
options.has_source = true;
}
if (releaseTime) {
options.release_time = releaseTime;
}
if (feeAmountParam) {
options.fee_amount = feeAmountParam;
}
if (limitClaimsPerChannel) {
options.limit_claims_per_channel = limitClaimsPerChannel;
}
// https://github.com/lbryio/lbry-desktop/issues/3774
if (hideReposts) {
if (Array.isArray(options.claim_type)) {
options.claim_type = options.claim_type.filter((claimType) => claimType !== 'repost');
} else {
options.claim_type = ['stream', 'channel'];
}
}
if (claimType) {
options.claim_type = claimType;
}
if (timestamp) {
options.timestamp = timestamp;
}
if (claimIds) {
options.claim_ids = claimIds;
}
const mainSearchKey = createNormalizedClaimSearchKey(options);
const livestreamSearchKey = liveLivestreamsFirst
? createNormalizedClaimSearchKey(getLivestreamOnlyOptions(options))
: undefined;
let uris = (prefixUris || []).concat(claimSearchByQuery[mainSearchKey] || []);
const isLoading = fetchingClaimSearchByQuery[mainSearchKey];
if (liveLivestreamsFirst && livestreamMap && !isLoading) {
prioritizeActiveLivestreams(uris, liveUris, livestreamMap, claimsByUri, claimSearchByQuery, options);
}
const searchKey = createNormalizedClaimSearchKey(options);
const fetchingClaimSearch = fetchingClaimSearchByQuery[searchKey];
const claimSearchUris = claimSearchByQuery[searchKey] || [];
const isUnfetchedClaimSearch = claimSearchByQuery[searchKey] === undefined;
// Don't use the query from createNormalizedClaimSearchKey for the effect since that doesn't include page & release_time
const optionsStringForEffect = JSON.stringify(options);
const shouldPerformSearch = !isLoading && uris.length === 0;
const shouldPerformSearch = !fetchingClaimSearch && claimSearchUris.length === 0;
if (
prefixUris === undefined &&
(claimSearchByQuery[mainSearchKey] === undefined ||
(livestreamSearchKey && claimSearchByQuery[livestreamSearchKey] === undefined))
) {
// This is a new query and we don't have results yet ...
if (prevUris.length !== 0) {
// ... but we have previous results. Use it until new results are here.
uris = prevUris;
}
}
const uris = (prefixUris || []).concat(claimSearchUris);
const modifiedUris = uris ? uris.slice() : [];
const fixUris = pinUrls || [];
if (pinUrls && modifiedUris && modifiedUris.length > 2 && window.location.pathname === '/') {
fixUris.forEach((fixUri) => {
if (modifiedUris.indexOf(fixUri) !== -1) {
modifiedUris.splice(modifiedUris.indexOf(fixUri), 1);
if (pinUrls && uris && uris.length > 2 && window.location.pathname === '/') {
pinUrls.forEach((pin) => {
if (uris.indexOf(pin) !== -1) {
uris.splice(uris.indexOf(pin), 1);
} else {
modifiedUris.pop();
uris.pop();
}
});
modifiedUris.splice(2, 0, ...fixUris);
uris.splice(2, 0, ...pinUrls);
}
// **************************************************************************
// **************************************************************************
function resolveLive(index) {
if (liveLivestreamsFirst && livestreamMap && index < liveUris.length) {
return true;
}
return undefined;
if (uris.length > 0 && uris.length < pageSize && shouldPerformSearch) {
// prefixUri and pinUrls might already be present while waiting for the
// remaining claim_search results. Fill the space to prevent layout shifts.
uris.push(...Array(pageSize - uris.length).fill(''));
}
function fetchViewCountForUris(uris) {
const claimIds = [];
const prevUris = usePrevious(uris);
if (uris) {
uris.forEach((uri) => {
if (claimsByUri[uri]) {
claimIds.push(claimsByUri[uri].claim_id);
}
});
}
if (claimIds.length > 0) {
doFetchViewCount(claimIds.join(','));
}
}
// **************************************************************************
// **************************************************************************
useFetchViewCount(fetchViewCount, uris, claimsByUri, doFetchViewCount);
// Run `doClaimSearch`
React.useEffect(() => {
if (shouldPerformSearch) {
const searchOptions = JSON.parse(optionsStringForEffect);
doClaimSearch(searchOptions);
if (liveLivestreamsFirst) {
doClaimSearch(getLivestreamOnlyOptions(searchOptions));
}
}
}, [doClaimSearch, shouldPerformSearch, optionsStringForEffect, liveLivestreamsFirst]);
}, [doClaimSearch, shouldPerformSearch, optionsStringForEffect]);
React.useEffect(() => {
if (JSON.stringify(prevUris) !== JSON.stringify(uris) && !shouldPerformSearch) {
// Stash new results for next render cycle:
setPrevUris(uris);
// Fetch view count:
if (fetchViewCount) {
fetchViewCountForUris(uris);
}
}
}, [shouldPerformSearch, prevUris, uris]); // eslint-disable-line react-hooks/exhaustive-deps
// **************************************************************************
// **************************************************************************
// Show previous results while we fetch to avoid blinkies and poor CLS.
const finalUris = isUnfetchedClaimSearch && prevUris ? prevUris : uris;
return (
<ul className="claim-grid">
{modifiedUris && modifiedUris.length
? modifiedUris.map((uri, index) => (
<ClaimPreviewTile
showNoSourceClaims={hasNoSource || showNoSourceClaims}
key={uri}
uri={uri}
properties={renderProperties}
live={resolveLive(index)}
/>
))
{finalUris && finalUris.length
? finalUris.map((uri, i) => {
if (uri) {
return (
<ClaimPreviewTile
showNoSourceClaims={hasNoSource || showNoSourceClaims}
key={uri}
uri={uri}
properties={renderProperties}
/>
);
} else {
return <ClaimPreviewTile showNoSourceClaims={hasNoSource || showNoSourceClaims} key={i} placeholder />;
}
})
: new Array(pageSize)
.fill(1)
.map((x, i) => (
@@ -362,4 +163,64 @@ function ClaimTilesDiscover(props: Props) {
</ul>
);
}
export default ClaimTilesDiscover;
export default React.memo<Props>(ClaimTilesDiscover, areEqual);
function debug_trace(val) {
if (process.env.DEBUG_TRACE) console.log(`Render due to: ${val}`);
}
function areEqual(prev: Props, next: Props) {
const prevOptions: SearchOptions = prev.options;
const nextOptions: SearchOptions = next.options;
const prevSearchKey = createNormalizedClaimSearchKey(prevOptions);
const nextSearchKey = createNormalizedClaimSearchKey(nextOptions);
if (prevSearchKey !== nextSearchKey) {
debug_trace('search key');
return false;
}
// --- Deep-compare ---
if (!urisEqual(prev.claimSearchByQuery[prevSearchKey], next.claimSearchByQuery[nextSearchKey])) {
debug_trace('claimSearchByQuery');
return false;
}
const ARRAY_KEYS = ['prefixUris', 'channelIds'];
for (let i = 0; i < ARRAY_KEYS.length; ++i) {
const key = ARRAY_KEYS[i];
if (!urisEqual(prev[key], next[key])) {
debug_trace(`${key}`);
return false;
}
}
// --- Default the rest(*) to shallow-compare ---
// (*) including new props introduced in the future, in case developer forgets
// to update this function. Better to render more than miss an important one.
const KEYS_TO_IGNORE = [
...ARRAY_KEYS,
'claimSearchByQuery',
'fetchingClaimSearchByQuery', // We are showing previous results while fetching.
'options', // Covered by search-key comparison.
'location',
'history',
'match',
'claimsByUri',
'doClaimSearch',
'doToggleTagFollowDesktop',
];
const propKeys = Object.keys(next);
for (let i = 0; i < propKeys.length; ++i) {
const pk = propKeys[i];
if (!KEYS_TO_IGNORE.includes(pk) && prev[pk] !== next[pk]) {
debug_trace(`${pk}`);
return false;
}
}
return true;
}
@@ -7,6 +7,7 @@ import {
makeSelectNameForCollectionId,
makeSelectPendingCollectionForId,
makeSelectCountForCollectionId,
doFetchItemsInCollection,
} from 'lbry-redux';
import CollectionPreviewOverlay from './view';
@@ -27,4 +28,8 @@ const select = (state, props) => {
};
};
export default connect(select)(CollectionPreviewOverlay);
const perform = (dispatch) => ({
fetchCollectionItems: (claimId) => dispatch(doFetchItemsInCollection({ collectionId: claimId })), // if collection not resolved, resolve it
});
export default connect(select, perform)(CollectionPreviewOverlay);
@@ -12,10 +12,17 @@ type Props = {
pendingCollection?: Collection,
claim: ?Claim,
collectionItemUrls: Array<string>,
fetchCollectionItems: (string) => void,
};
function CollectionPreviewOverlay(props: Props) {
const { collectionItemUrls } = props;
const { collectionId, collectionItemUrls, fetchCollectionItems } = props;
React.useEffect(() => {
if (!collectionItemUrls) {
fetchCollectionItems(collectionId);
}
}, [collectionId, collectionItemUrls, fetchCollectionItems]);
if (collectionItemUrls && collectionItemUrls.length > 0) {
return (
-5
View File
@@ -6,16 +6,13 @@ import {
selectFetchingMyChannels,
doSendTip,
} from 'lbry-redux';
import { doOpenModal, doSetActiveChannel } from 'redux/actions/app';
import { doCommentCreate, doFetchCreatorSettings, doCommentById } from 'redux/actions/comments';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import { selectSettingsByChannelId } from 'redux/selectors/comments';
import { CommentCreate } from './view';
import { doToast } from 'redux/actions/notifications';
const select = (state, props) => ({
commentingEnabled: IS_WEB ? Boolean(selectUserVerifiedEmail(state)) : true,
claim: makeSelectClaimForUri(props.uri)(state),
channels: selectMyChannelClaims(state),
isFetchingChannels: selectFetchingMyChannels(state),
@@ -38,8 +35,6 @@ const perform = (dispatch, ownProps) => ({
environment
)
),
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
setActiveChannel: (claimId) => dispatch(doSetActiveChannel(claimId)),
sendTip: (params, callback, errorCallback) => dispatch(doSendTip(params, false, callback, errorCallback, false)),
doToast: (options) => dispatch(doToast(options)),
doFetchCreatorSettings: (channelClaimId) => dispatch(doFetchCreatorSettings(channelClaimId)),
+115 -53
View File
@@ -1,40 +1,39 @@
// @flow
import type { ElementRef } from 'react';
import { SIMPLE_SITE } from 'config';
import * as PAGES from 'constants/pages';
import * as ICONS from 'constants/icons';
import * as KEYCODES from 'constants/keycodes';
import React from 'react';
import classnames from 'classnames';
import { FormField, Form } from 'component/common/form';
import Icon from 'component/common/icon';
import Button from 'component/button';
import SelectChannel from 'component/selectChannel';
import usePersistedState from 'effects/use-persisted-state';
import { FF_MAX_CHARS_IN_COMMENT, FF_MAX_CHARS_IN_LIVESTREAM_COMMENT } from 'constants/form-field';
import { useHistory } from 'react-router';
import WalletTipAmountSelector from 'component/walletTipAmountSelector';
import CreditAmount from 'component/common/credit-amount';
import ChannelThumbnail from 'component/channelThumbnail';
import I18nMessage from 'component/i18nMessage';
import UriIndicator from 'component/uriIndicator';
import Empty from 'component/common/empty';
import { FormField, Form } from 'component/common/form';
import { getChannelIdFromClaim } from 'util/claim';
import { Lbryio } from 'lbryinc';
import { SIMPLE_SITE } from 'config';
import { useHistory } from 'react-router';
import * as ICONS from 'constants/icons';
import * as KEYCODES from 'constants/keycodes';
import * as PAGES from 'constants/pages';
import Button from 'component/button';
import ChannelMentionSuggestions from 'component/channelMentionSuggestions';
import ChannelThumbnail from 'component/channelThumbnail';
import classnames from 'classnames';
import CreditAmount from 'component/common/credit-amount';
import Empty from 'component/common/empty';
import I18nMessage from 'component/i18nMessage';
import Icon from 'component/common/icon';
import React from 'react';
import SelectChannel from 'component/selectChannel';
import type { ElementRef } from 'react';
import UriIndicator from 'component/uriIndicator';
import usePersistedState from 'effects/use-persisted-state';
import WalletTipAmountSelector from 'component/walletTipAmountSelector';
import { getStripeEnvironment } from 'util/stripe';
let stripeEnvironment = getStripeEnvironment();
const TAB_FIAT = 'TabFiat';
const TAB_LBC = 'TabLBC';
const MENTION_DEBOUNCE_MS = 100;
type Props = {
uri: string,
claim: StreamClaim,
createComment: (string, string, string, ?string, ?string, ?string) => Promise<any>,
channels: ?Array<ChannelClaim>,
onDoneReplying?: () => void,
onCancelReplying?: () => void,
isNested: boolean,
isFetchingChannels: boolean,
parentId: string,
@@ -44,25 +43,26 @@ type Props = {
bottom: boolean,
livestream?: boolean,
embed?: boolean,
toast: (string) => void,
claimIsMine: boolean,
sendTip: ({}, (any) => void, (any) => void) => void,
doToast: ({ message: string }) => void,
supportDisabled: boolean,
doFetchCreatorSettings: (channelId: string) => Promise<any>,
settingsByChannelId: { [channelId: string]: PerChannelSettings },
shouldFetchComment: boolean,
doToast: ({ message: string }) => void,
createComment: (string, string, string, ?string, ?string, ?string) => Promise<any>,
onDoneReplying?: () => void,
onCancelReplying?: () => void,
toast: (string) => void,
sendTip: ({}, (any) => void, (any) => void) => void,
doFetchCreatorSettings: (channelId: string) => Promise<any>,
setQuickReply: (any) => void,
fetchComment: (commentId: string) => Promise<any>,
shouldFetchComment: boolean,
};
export function CommentCreate(props: Props) {
const {
createComment,
uri,
claim,
channels,
onDoneReplying,
onCancelReplying,
isNested,
isFetchingChannels,
isReply,
@@ -72,36 +72,64 @@ export function CommentCreate(props: Props) {
livestream,
embed,
claimIsMine,
sendTip,
doToast,
doFetchCreatorSettings,
settingsByChannelId,
supportDisabled,
shouldFetchComment,
doToast,
createComment,
onDoneReplying,
onCancelReplying,
sendTip,
doFetchCreatorSettings,
setQuickReply,
fetchComment,
shouldFetchComment,
} = props;
const formFieldRef: ElementRef<any> = React.useRef();
const formFieldInputRef = formFieldRef && formFieldRef.current && formFieldRef.current.input;
const selectionIndex = formFieldInputRef && formFieldInputRef.current && formFieldInputRef.current.selectionStart;
const buttonRef: ElementRef<any> = React.useRef();
const {
push,
location: { pathname },
} = useHistory();
const [isSubmitting, setIsSubmitting] = React.useState(false);
const [commentFailure, setCommentFailure] = React.useState(false);
const [successTip, setSuccessTip] = React.useState({ txid: undefined, tipAmount: undefined });
const claimId = claim && claim.claim_id;
const [isSupportComment, setIsSupportComment] = React.useState();
const [isReviewingSupportComment, setIsReviewingSupportComment] = React.useState();
const [tipAmount, setTipAmount] = React.useState(1);
const [commentValue, setCommentValue] = React.useState('');
const [advancedEditor, setAdvancedEditor] = usePersistedState('comment-editor-mode', false);
const hasChannels = channels && channels.length;
const charCount = commentValue.length;
const [activeTab, setActiveTab] = React.useState('');
const [tipError, setTipError] = React.useState();
const [deletedComment, setDeletedComment] = React.useState(false);
const disabled = deletedComment || isSubmitting || isFetchingChannels || !commentValue.length;
const [pauseQuickSend, setPauseQuickSend] = React.useState(false);
const [shouldDisableReviewButton, setShouldDisableReviewButton] = React.useState();
const selectedMentionIndex =
commentValue.indexOf('@', selectionIndex) === selectionIndex
? commentValue.indexOf('@', selectionIndex)
: commentValue.lastIndexOf('@', selectionIndex);
const modifierIndex = commentValue.indexOf(':', selectedMentionIndex);
const spaceIndex = commentValue.indexOf(' ', selectedMentionIndex);
const mentionLengthIndex =
modifierIndex >= 0 && (spaceIndex === -1 || modifierIndex < spaceIndex)
? modifierIndex
: spaceIndex >= 0 && (modifierIndex === -1 || spaceIndex < modifierIndex)
? spaceIndex
: commentValue.length;
const channelMention =
selectedMentionIndex >= 0 && selectionIndex <= mentionLengthIndex
? commentValue.substring(selectedMentionIndex, mentionLengthIndex)
: '';
const claimId = claim && claim.claim_id;
const signingChannel = (claim && claim.signing_channel) || claim;
const channelUri = signingChannel && signingChannel.permanent_url;
const hasChannels = channels && channels.length;
const charCount = commentValue ? commentValue.length : 0;
const disabled = deletedComment || isSubmitting || isFetchingChannels || !commentValue.length || pauseQuickSend;
const channelId = getChannelIdFromClaim(claim);
const channelSettings = channelId ? settingsByChannelId[channelId] : undefined;
const minSuper = (channelSettings && channelSettings.min_tip_amount_super_chat) || 0;
@@ -109,15 +137,6 @@ export function CommentCreate(props: Props) {
const minAmount = minTip || minSuper || 0;
const minAmountMet = minAmount === 0 || tipAmount >= minAmount;
// Fetch top-level comments to identify if it has been deleted and can reply to it
React.useEffect(() => {
if (shouldFetchComment && fetchComment) {
fetchComment(parentId).then((result) => {
setDeletedComment(String(result).includes('Error'));
});
}
}, [fetchComment, shouldFetchComment, parentId]);
const minAmountRef = React.useRef(minAmount);
minAmountRef.current = minAmount;
@@ -157,6 +176,20 @@ export function CommentCreate(props: Props) {
setCommentValue(commentValue);
}
function handleSelectMention(mentionValue, key) {
let newMentionValue = mentionValue.replace('lbry://', '');
if (newMentionValue.includes('#')) newMentionValue = newMentionValue.replace('#', ':');
if (livestream && key !== KEYCODES.TAB) setPauseQuickSend(true);
setCommentValue(
commentValue.substring(0, selectedMentionIndex) +
`${newMentionValue}` +
(commentValue.length > mentionLengthIndex + 1
? commentValue.substring(mentionLengthIndex, commentValue.length)
: ' ')
);
}
function altEnterListener(e: SyntheticKeyboardEvent<*>) {
if ((livestream || e.ctrlKey || e.metaKey) && e.keyCode === KEYCODES.ENTER) {
e.preventDefault();
@@ -365,10 +398,6 @@ export function CommentCreate(props: Props) {
});
}
function toggleEditorMode() {
setAdvancedEditor(!advancedEditor);
}
// **************************************************************************
// Effects
// **************************************************************************
@@ -378,7 +407,28 @@ export function CommentCreate(props: Props) {
if (!channelSettings && channelId) {
doFetchCreatorSettings(channelId);
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
}, [channelId, channelSettings, doFetchCreatorSettings]);
// Notifications: Fetch top-level comments to identify if it has been deleted and can reply to it
React.useEffect(() => {
if (shouldFetchComment && fetchComment) {
fetchComment(parentId).then((result) => {
setDeletedComment(String(result).includes('Error'));
});
}
}, [fetchComment, shouldFetchComment, parentId]);
// Debounce for disabling the submit button when mentioning a user with Enter
// so that the comment isn't sent at the same time
React.useEffect(() => {
const timer = setTimeout(() => {
if (pauseQuickSend) {
setPauseQuickSend(false);
}
}, MENTION_DEBOUNCE_MS);
return () => clearTimeout(timer);
}, [pauseQuickSend]);
// **************************************************************************
// Render
@@ -466,10 +516,22 @@ export function CommentCreate(props: Props) {
'comment__create--bottom': bottom,
})}
>
{!advancedEditor && (
<ChannelMentionSuggestions
uri={uri}
isLivestream={livestream}
inputRef={formFieldInputRef}
mentionTerm={channelMention}
creatorUri={channelUri}
customSelectAction={handleSelectMention}
/>
)}
<FormField
disabled={isFetchingChannels}
type={SIMPLE_SITE ? 'textarea' : advancedEditor && !isReply ? 'markdown' : 'textarea'}
name={isReply ? 'content_reply' : 'content_description'}
ref={formFieldRef}
className={isReply ? 'content_reply' : 'content_comment'}
label={
<span className="comment-new__label-wrapper">
{!livestream && (
@@ -481,7 +543,7 @@ export function CommentCreate(props: Props) {
quickActionLabel={
!SIMPLE_SITE && (isReply ? undefined : advancedEditor ? __('Simple Editor') : __('Advanced Editor'))
}
quickActionHandler={!SIMPLE_SITE && toggleEditorMode}
quickActionHandler={() => !SIMPLE_SITE && setAdvancedEditor(!advancedEditor)}
onFocus={onTextareaFocus}
onBlur={onTextareaBlur}
placeholder={__('Say something about this...')}
+11 -11
View File
@@ -171,20 +171,27 @@ function CommentMenuList(props: Props) {
</MenuItem>
)}
{activeChannelIsCreator && (
{activeChannelIsCreator && activeChannelClaim && activeChannelClaim.permanent_url !== authorUri && (
<MenuItem className="comment__menu-option" onSelect={assignAsModerator}>
<div className="menu__link">
<Icon aria-hidden icon={ICONS.ADD} />
{__('Add as moderator')}
</div>
<span className="comment__menu-help">
{__('Assign this user to moderate %channel%', {
channel: activeChannelClaim ? activeChannelClaim.name : __('your channel'),
})}
{activeChannelClaim
? __('Assign this user to moderate %channel%.', { channel: activeChannelClaim.name })
: __('Assign this user to moderate your channel.')}
</span>
</MenuItem>
)}
{commentIsMine && activeChannelClaim && activeChannelClaim.permanent_url === authorUri && !disableEdit && (
<MenuItem className="comment__menu-option menu__link" onSelect={handleEditComment}>
<Icon aria-hidden icon={ICONS.EDIT} />
{__('Edit')}
</MenuItem>
)}
{!disableRemove &&
activeChannelClaim &&
(activeChannelClaim.permanent_url === authorUri ||
@@ -197,13 +204,6 @@ function CommentMenuList(props: Props) {
</MenuItem>
)}
{commentIsMine && activeChannelClaim && activeChannelClaim.permanent_url === authorUri && !disableEdit && (
<MenuItem className="comment__menu-option menu__link" onSelect={handleEditComment}>
<Icon aria-hidden icon={ICONS.EDIT} />
{__('Edit')}
</MenuItem>
)}
{!commentIsMine && (
<MenuItem className="comment__menu-option" onSelect={handleCommentBlock}>
{getBlockOptionElem()}
+2
View File
@@ -9,6 +9,7 @@ import {
makeSelectTopLevelCommentsForUri,
makeSelectTopLevelTotalPagesForUri,
selectIsFetchingComments,
selectIsFetchingCommentsById,
selectIsFetchingReacts,
makeSelectTotalCommentsCountForUri,
selectOthersReactsById,
@@ -33,6 +34,7 @@ const select = (state, props) => {
claim: makeSelectClaimForUri(props.uri)(state),
claimIsMine: makeSelectClaimIsMine(props.uri)(state),
isFetchingComments: selectIsFetchingComments(state),
isFetchingCommentsById: selectIsFetchingCommentsById(state),
isFetchingReacts: selectIsFetchingReacts(state),
fetchingChannels: selectFetchingMyChannels(state),
settingsByChannelId: selectSettingsByChannelId(state),
+29 -19
View File
@@ -14,14 +14,12 @@ import usePersistedState from 'effects/use-persisted-state';
import { ENABLE_COMMENT_REACTIONS } from 'config';
import Empty from 'component/common/empty';
import debounce from 'util/debounce';
import { useIsMobile } from 'effects/use-screensize';
import useFetched from 'effects/use-fetched';
import { useIsMobile, useIsMediumScreen } from 'effects/use-screensize';
import { getChannelIdFromClaim } from 'util/claim';
const DEBOUNCE_SCROLL_HANDLER_MS = 200;
// "3" due to 2 separate fetches needed + 1 buffer just in case.
const MAX_LINKED_COMMENT_SCROLL_ATTEMPTS = 3;
function scaleToDevicePixelRatio(value) {
const devicePixelRatio = window.devicePixelRatio || 1.0;
if (devicePixelRatio < 1.0) {
@@ -44,6 +42,7 @@ type Props = {
claimIsMine: boolean,
myChannels: ?Array<ChannelClaim>,
isFetchingComments: boolean,
isFetchingCommentsById: boolean,
isFetchingReacts: boolean,
linkedCommentId?: string,
totalComments: number,
@@ -69,6 +68,7 @@ function CommentList(props: Props) {
claimIsMine,
myChannels,
isFetchingComments,
isFetchingCommentsById,
isFetchingReacts,
linkedCommentId,
totalComments,
@@ -83,14 +83,15 @@ function CommentList(props: Props) {
const DEFAULT_SORT = ENABLE_COMMENT_REACTIONS ? SORT_BY.POPULARITY : SORT_BY.NEWEST;
const [sort, setSort] = usePersistedState('comment-sort-by', DEFAULT_SORT);
const [page, setPage] = React.useState(0);
const [lcScrollAttempts, setLcScrollAttempts] = React.useState(
linkedCommentId ? 0 : MAX_LINKED_COMMENT_SCROLL_ATTEMPTS
);
const isMobile = useIsMobile();
const [expandedComments, setExpandedComments] = React.useState(!isMobile);
const isMediumScreen = useIsMediumScreen();
const [expandedComments, setExpandedComments] = React.useState(!isMobile && !isMediumScreen);
const totalFetchedComments = allCommentIds ? allCommentIds.length : 0;
const channelId = getChannelIdFromClaim(claim);
const channelSettings = channelId ? settingsByChannelId[channelId] : undefined;
const fetchedCommentsOnce = useFetched(isFetchingComments);
const fetchedReactsOnce = useFetched(isFetchingReacts);
const fetchedLinkedComment = useFetched(isFetchingCommentsById);
// Display comments immediately if not fetching reactions
// If not, wait to show comments until reactions are fetched
@@ -202,19 +203,19 @@ function CommentList(props: Props) {
// Scroll to linked-comment
useEffect(() => {
if (lcScrollAttempts < MAX_LINKED_COMMENT_SCROLL_ATTEMPTS && readyToDisplayComments && !isFetchingComments) {
if (fetchedLinkedComment && fetchedCommentsOnce && fetchedReactsOnce) {
const elems = document.getElementsByClassName(COMMENT_HIGHLIGHTED);
if (elems.length > 0) {
setLcScrollAttempts(MAX_LINKED_COMMENT_SCROLL_ATTEMPTS);
const ROUGH_HEADER_HEIGHT = 125; // @see: --header-height
const linkedComment = elems[0];
linkedComment.scrollIntoView({ block: 'start' });
window.scrollBy(0, -125);
} else {
setLcScrollAttempts(lcScrollAttempts + 1);
window.scrollTo({
top: linkedComment.getBoundingClientRect().top + window.scrollY - ROUGH_HEADER_HEIGHT,
left: 0,
behavior: 'smooth',
});
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [readyToDisplayComments, isFetchingComments]); // We just want to respond to these, nothing else.
}, [fetchedLinkedComment, fetchedCommentsOnce, fetchedReactsOnce]);
// Infinite scroll
useEffect(() => {
@@ -243,7 +244,7 @@ function CommentList(props: Props) {
}
const handleCommentScroll = debounce(() => {
if (!isMobile && shouldFetchNextPage(page, topLevelTotalPages, window, document)) {
if (!isMobile && !isMediumScreen && shouldFetchNextPage(page, topLevelTotalPages, window, document)) {
setPage(page + 1);
}
}, DEBOUNCE_SCROLL_HANDLER_MS);
@@ -258,6 +259,7 @@ function CommentList(props: Props) {
}
}, [
isMobile,
isMediumScreen,
page,
moreBelow,
spinnerRef,
@@ -267,8 +269,16 @@ function CommentList(props: Props) {
topLevelTotalPages,
]);
// Expand comments
useEffect(() => {
if (!isMobile && !isMediumScreen && !expandedComments) {
setExpandedComments(true);
}
}, [isMobile, isMediumScreen, expandedComments]);
return (
<Card
className="card--enable-overflow"
title={
totalComments > 0
? totalComments === 1
@@ -340,7 +350,7 @@ function CommentList(props: Props) {
{readyToDisplayComments && topLevelComments && getCommentElems(topLevelComments)}
</ul>
{isMobile && (
{(isMobile || isMediumScreen) && (
<div className="card__bottom-actions--comments">
{(!expandedComments || moreBelow) && (
<Button
@@ -369,7 +379,7 @@ function CommentList(props: Props) {
</div>
)}
{(isFetchingComments || (!isMobile && moreBelow)) && (
{(isFetchingComments || (!isMobile && !isMediumScreen && moreBelow)) && (
<div className="main--empty" ref={spinnerRef}>
<Spinner type="small" />
</div>
+65
View File
@@ -2439,6 +2439,14 @@ export const icons = {
/>
</svg>
),
[ICONS.APPEAL]: buildIcon(
<g>
<path d="M13.54,8.58l9.33,8.79a1.31,1.31,0,0,1,0,1.85l-.93.93a1.31,1.31,0,0,1-1.85,0L11.3,10.82" />
<path d="M3.85,8.54a19.06,19.06,0,0,0,7.41-7.41,1.31,1.31,0,0,1,1.85,0l3.51,3.51a1.32,1.32,0,0,1,0,1.86,18.09,18.09,0,0,0-7.41,7.4,1.31,1.31,0,0,1-1.85,0L3.85,10.39A1.31,1.31,0,0,1,3.85,8.54Z" />
<path d="M12.75,20.75h0a1.5,1.5,0,0,0-1.5-1.5H3.75a1.5,1.5,0,0,0-1.5,1.5h0v2.5h10.5Z" />
<line x1="0.75" y1="23.25" x2="14.25" y2="23.25" />
</g>
),
[ICONS.PLAY]: buildIcon(<polygon points="5 3 19 12 5 21 5 3" />),
[ICONS.PLAY_PREVIOUS]: buildIcon(
<g>
@@ -2469,4 +2477,61 @@ export const icons = {
<line x1="4" y1="4" x2="9" y2="9" />
</g>
),
[ICONS.HOLD_PHONE]: buildIcon(
<g>
<path d="M12 17.491L1.5 17.491" />
<path d="M8,19.241H8a.25.25,0,0,1,.25.25h0a.25.25,0,0,1-.25.25H8a.25.25,0,0,1-.25-.25h0a.25.25,0,0,1,.25-.25" />
<path d="M12.5,21.491h-9a2,2,0,0,1-2-2v-17a2,2,0,0,1,2-2h9a2,2,0,0,1,2,2V13.265" />
<path d="M22.5,23.487l-3-4.393V13.372c0-2.127-3.46-3.9-5-5.08" />
<path d="M16.5,14.868l-3.727-2.987a1.331,1.331,0,0,0-1.883,1.883l3.61,4.079V20.4c0,1.206,1.724,3.111,1.724,3.111" />
<path d="M5.750 5.741 A2.250 2.250 0 1 0 10.250 5.741 A2.250 2.250 0 1 0 5.750 5.741 Z" />
<path d="M12.11,11.524a4.628,4.628,0,0,0-8.61.967" />
</g>
),
[ICONS.LIFE]: buildIcon(
<g>
<path d="M12 23.5L12 6.836" />
<path d="M12,6.836s2-1.291,2-3.228a4.144,4.144,0,0,0-1.69-3,.49.49,0,0,0-.621,0,4.143,4.143,0,0,0-1.689,3C10,5.545,12,6.836,12,6.836Z" />
<path d="M12,10.455s.9-4.038,6.093-4.038a.5.5,0,0,1,.419.8A7.942,7.942,0,0,1,12,10.455Z" />
<path d="M12,10.455s-.9-4.038-6.093-4.038a.5.5,0,0,0-.419.8A7.942,7.942,0,0,0,12,10.455Z" />
<path d="M12,15.455s1.809-4.31,7.6-3.2a.5.5,0,0,1,.262.858A8.855,8.855,0,0,1,12,15.455Z" />
<path d="M12,15.455s-1.809-4.31-7.6-3.2a.5.5,0,0,0-.262.858A8.855,8.855,0,0,0,12,15.455Z" />
<path d="M12,19.955s-2.767-3.766-8.139-1.331a.505.505,0,0,0-.054.9A8.853,8.853,0,0,0,12,19.955Z" />
<path d="M12,19.955s2.767-3.766,8.139-1.331a.505.505,0,0,1,.054.9A8.853,8.853,0,0,1,12,19.955Z" />
</g>
),
[ICONS.ARTISTS]: buildIcon(
<g>
<path d="M10.107,16.884,22.372,4.657a2.5,2.5,0,0,0-3.744-3.314L7.954,15.04" />
<path d="M1.285,22.879a.5.5,0,0,1,.027-.915C3.693,21,2.926,18.286,3.633,16.835a3.56,3.56,0,0,1,4.728-1.627C13.677,17.8,7.349,25.765,1.285,22.879Z" />
</g>
),
[ICONS.MYSTERIES]: buildIcon(
<g>
<path d="M9.926,14.581c-6.5,0-5.912-5.912-5.912-5.912C11.108,8.669,9.926,14.581,9.926,14.581Z" />
<path d="M14.074,14.581c6.5,0,5.912-5.912,5.912-5.912C12.892,8.669,14.074,14.581,14.074,14.581Z" />
<path d="M22.5,10.25c0,6.352-7.5,13-10.5,13S1.5,16.6,1.5,10.25,5.648.75,12,.75,22.5,3.9,22.5,10.25Z" />
</g>
),
[ICONS.TECHNOLOGY]: buildIcon(
<g>
<rect x="0.5" y="13.5" width="23" height="10" rx="2" ry="2" />
<path d="M3.5,13.5v-1a3,3,0,0,1,3-3H20a3.5,3.5,0,0,0,0-7H13.5A1.5,1.5,0,0,1,12,1V.5" />
<line x1="4" y1="20.5" x2="5" y2="20.5" />
<line x1="4" y1="18.5" x2="5" y2="18.5" />
<line x1="7" y1="18.5" x2="8" y2="18.5" />
<line x1="10" y1="18.5" x2="11" y2="18.5" />
<line x1="13" y1="18.5" x2="14" y2="18.5" />
<line x1="16" y1="18.5" x2="17" y2="18.5" />
<line x1="19" y1="18.5" x2="20" y2="18.5" />
<line x1="4" y1="16.5" x2="5" y2="16.5" />
<line x1="7" y1="16.5" x2="8" y2="16.5" />
<line x1="10" y1="16.5" x2="11" y2="16.5" />
<line x1="13" y1="16.5" x2="14" y2="16.5" />
<line x1="16" y1="16.5" x2="17" y2="16.5" />
<line x1="19" y1="16.5" x2="20" y2="16.5" />
<line x1="7" y1="20.5" x2="17" y2="20.5" />
<line x1="19" y1="20.5" x2="20" y2="20.5" />
</g>
),
};
+31 -20
View File
@@ -12,23 +12,38 @@ type Props = {
primaryButton?: boolean,
name?: string,
onCopy?: (string) => string,
enableInputMask?: boolean,
};
export default function CopyableText(props: Props) {
const { copyable, doToast, snackMessage, label, primaryButton = false, name, onCopy } = props;
const { copyable, doToast, snackMessage, label, primaryButton = false, name, onCopy, enableInputMask } = props;
const [maskInput, setMaskInput] = React.useState(enableInputMask);
const input = useRef();
function copyToClipboard() {
const topRef = input.current;
if (topRef && topRef.input && topRef.input.current) {
topRef.input.current.select();
if (onCopy) {
onCopy(topRef.input.current);
function handleCopyText() {
if (enableInputMask) {
navigator.clipboard
.writeText(copyable)
.then(() => {
doToast({ message: snackMessage || __('Text copied') });
})
.catch(() => {
doToast({ message: __('Failed to copy.'), isError: true });
});
} else {
const topRef = input.current;
if (topRef && topRef.input && topRef.input.current) {
topRef.input.current.select();
if (onCopy) {
// Allow clients to change the selection before making the copy.
onCopy(topRef.input.current);
}
}
}
document.execCommand('copy');
document.execCommand('copy');
doToast({ message: snackMessage || __('Text copied') });
}
}
function onFocus() {
@@ -41,7 +56,7 @@ export default function CopyableText(props: Props) {
return (
<FormField
type="text"
type={maskInput ? 'password' : 'text'}
className="form-field--copyable"
readOnly
name={name}
@@ -50,16 +65,12 @@ export default function CopyableText(props: Props) {
ref={input}
onFocus={onFocus}
inputButton={
<Button
button={primaryButton ? 'primary' : 'secondary'}
icon={ICONS.COPY}
onClick={() => {
copyToClipboard();
doToast({
message: snackMessage || __('Text copied'),
});
}}
/>
<Button button={primaryButton ? 'primary' : 'secondary'} icon={ICONS.COPY} onClick={handleCopyText} />
}
helper={
enableInputMask && (
<Button button="link" onClick={() => setMaskInput(!maskInput)} label={maskInput ? __('Show') : __('Hide')} />
)
}
/>
);
+2 -2
View File
@@ -104,11 +104,11 @@ class DateTime extends React.Component<Props, State> {
return null;
}
return <span title={moment(date).format(`MMMM Do, YYYY ${clockFormat}`)}>{DateTime.getTimeAgoStr(date)}</span>;
return <span className="date_time" title={moment(date).format(`MMMM Do, YYYY ${clockFormat}`)}>{DateTime.getTimeAgoStr(date)}</span>;
}
return (
<span>
<span className="date_time">
{date && show === DateTime.SHOW_DATE && moment(date).format('MMMM Do, YYYY')}
{date && show === DateTime.SHOW_TIME && moment(date).format(clockFormat)}
{!date && '...'}
+1
View File
@@ -65,6 +65,7 @@ const perform = (dispatch) => ({
),
dispatch(doSetPlayingUri({ uri, collectionId }))
),
clearSecondarySource: (uri) => dispatch(doSetPlayingUri({ uri })),
});
export default withRouter(connect(select, perform)(FileRenderFloating));
+25 -5
View File
@@ -31,6 +31,7 @@ type Props = {
title: ?string,
floatingPlayerEnabled: boolean,
closeFloatingPlayer: () => void,
clearSecondarySource: (string) => void,
renderMode: string,
playingUri: ?PlayingUri,
primaryUri: ?string,
@@ -53,6 +54,7 @@ export default function FileRenderFloating(props: Props) {
title,
isFloating,
closeFloatingPlayer,
clearSecondarySource,
floatingPlayerEnabled,
renderMode,
playingUri,
@@ -68,8 +70,11 @@ export default function FileRenderFloating(props: Props) {
} = props;
const { location, push } = useHistory();
const hideFloatingPlayer = location.state && location.state.hideFloatingPlayer;
const playingUriSource = playingUri && playingUri.source;
const isComment = playingUriSource === 'comment';
const isMobile = useIsMobile();
const mainFilePlaying = !isFloating && isURIEqual(uri, primaryUri);
const [fileViewerRect, setFileViewerRect] = useState();
const [desktopPlayStartTime, setDesktopPlayStartTime] = useState();
const [wasDragging, setWasDragging] = useState(false);
@@ -86,11 +91,11 @@ export default function FileRenderFloating(props: Props) {
});
const navigateUrl =
playingUri && playingUri.primaryUri + (collectionId ? generateListSearchUrlParams(collectionId) : '');
playingUri &&
(playingUri.primaryUri || playingUri.uri) + (collectionId ? generateListSearchUrlParams(collectionId) : '');
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));
const loadingMessage =
@@ -145,13 +150,28 @@ export default function FileRenderFloating(props: Props) {
const jsonPosition = JSON.parse(stringifiedPosition);
if (isFloating) {
// When the player begins floating, remove the comment source
// so that it doesn't try to resize again in case of going back
// to the origin's comment section and fail to position correctly
if (isComment && playingUri) clearSecondarySource(playingUri.uri);
let pos = { x: jsonPosition.x, y: jsonPosition.y };
clampToScreen(pos);
if (pos.x !== position.x || pos.y !== position.y) {
setPosition({ x: pos.x, y: pos.y });
}
}
}, [clampToScreen, isFloating, position.x, position.y, setPosition, stringifiedPosition]);
}, [
clampToScreen,
clearSecondarySource,
isComment,
isFloating,
playingUri,
position.x,
position.y,
setPosition,
stringifiedPosition,
]);
// Listen to main-window resizing and adjust the fp position accordingly:
useEffect(() => {
@@ -197,7 +217,7 @@ export default function FileRenderFloating(props: Props) {
}, [mainFilePlaying]);
useEffect(() => {
if (playingUri && playingUri.primaryUri) {
if (playingUri && (playingUri.primaryUri || playingUri.uri)) {
handleResize();
setCountdownCanceled(false);
}
@@ -312,7 +332,7 @@ export default function FileRenderFloating(props: Props) {
className={classnames('content__viewer', {
'content__viewer--floating': isFloating,
'content__viewer--inline': !isFloating,
'content__viewer--secondary': playingUriSource === 'comment',
'content__viewer--secondary': isComment,
'content__viewer--theater-mode': !isFloating && videoTheaterMode,
})}
style={
+9 -2
View File
@@ -1,5 +1,6 @@
// @flow
import React from 'react';
import 'scss/component/_view_count.scss';
type Props = {
uri: string,
@@ -15,16 +16,22 @@ export default function FileViewCountInline(props: Props) {
let formattedViewCount;
try {
// SI notation that changes 1234 to 1.2K, look up Intl.NumberFormat() for docs
formattedViewCount = Number(viewCount).toLocaleString(lang || 'en', {
compactDisplay: 'short',
notation: 'compact',
});
} catch (err) {
// No soup for you!
formattedViewCount = Number(viewCount).toLocaleString();
}
if (!viewCount || (claim && claim.repost_url) || isLivestream) {
// Limit the view-count visibility to Channel Pages for now. I believe we'll
// eventually show it everywhere, so this band-aid would be the easiest to
// clean up (only one place edit/remove).
const isChannelPage = window.location.pathname.startsWith('/@');
// dont show if no view count, if it's a repost, a livestream or isn't a channel page
if (!viewCount || (claim && claim.repost_url) || isLivestream || !isChannelPage) {
// (1) Currently, makeSelectViewCountForUri doesn't differentiate between
// un-fetched 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.
@@ -1,9 +1,11 @@
import { connect } from 'react-redux';
import fileViewerEmbeddedTitle from './view';
import { makeSelectTitleForUri } from 'lbry-redux';
import { makeSelectTagInClaimOrChannelForUri, makeSelectTitleForUri } from 'lbry-redux';
import { PREFERENCE_EMBED } from 'constants/tags';
export default connect((state, props) => {
return {
title: makeSelectTitleForUri(props.uri)(state),
preferEmbed: makeSelectTagInClaimOrChannelForUri(props.uri, PREFERENCE_EMBED)(state),
};
})(fileViewerEmbeddedTitle);
+17 -9
View File
@@ -11,10 +11,11 @@ type Props = {
uri: string,
title: ?string,
isInApp: boolean,
preferEmbed: boolean,
};
function FileViewerEmbeddedTitle(props: Props) {
const { uri, title, isInApp } = props;
const { uri, title, isInApp, preferEmbed } = props;
let contentLink = `${formatLbryUrlForWeb(uri)}`;
@@ -28,15 +29,22 @@ function FileViewerEmbeddedTitle(props: Props) {
return (
<div className="file-viewer__embedded-header">
<div className="file-viewer__embedded-gradient" />
<Button
label={title}
aria-label={title}
button="link"
className="file-viewer__embedded-title"
{...contentLinkProps}
/>
{preferEmbed ? (
<div className="file-viewer__embedded-title ">
<span dir="auto">{title}</span>
</div>
) : (
<Button
label={title}
aria-label={title}
button="link"
className="file-viewer__embedded-title"
{...contentLinkProps}
/>
)}
<div className="file-viewer__embedded-info">
<Button className="file-viewer__overlay-logo" aria-label={__('Home')} {...lbryLinkProps}>
<Button className="file-viewer__overlay-logo" disabled={preferEmbed} aria-label={__('Home')} {...lbryLinkProps}>
<Logo type={'embed'} />
</Button>
{isInApp && <FilePrice uri={uri} />}
+3
View File
@@ -0,0 +1,3 @@
import FormFieldDuration from './view';
export default FormFieldDuration;
+88
View File
@@ -0,0 +1,88 @@
// @flow
import type { Node } from 'react';
import React from 'react';
import parseDuration from 'parse-duration';
import { FormField } from 'component/common/form';
import Icon from 'component/common/icon';
import * as ICONS from 'constants/icons';
const INPUT_EXAMPLES = '\n- 30s\n- 10m\n- 1h\n- 2d\n- 3mo\n- 1y';
const ONE_HUNDRED_YEARS_IN_SECONDS = 3154000000;
type Props = {
name: string,
label?: string | Node,
placeholder?: string | number,
value: string | number,
onChange: (any) => void,
onResolve: (valueInSeconds: number) => void, // Returns parsed/resolved value in seconds; "-1" for invalid input.
maxDurationInSeconds?: number,
};
export default function FormFieldDuration(props: Props) {
const { name, label, placeholder, value, onChange, onResolve, maxDurationInSeconds } = props;
const [valueSec, setValueSec] = React.useState(-1);
const [valueErr, setValueErr] = React.useState('');
React.useEffect(() => {
const handleInvalidInput = (errMsg: string) => {
if (valueSec !== -1) {
setValueSec(-1);
onResolve(-1);
}
if (valueErr !== errMsg) {
setValueErr(errMsg);
}
};
const handleValidInput = (seconds) => {
if (seconds !== valueSec) {
setValueSec(seconds);
onResolve(seconds);
}
if (valueErr) {
setValueErr('');
}
};
if (!value) {
handleValidInput(-1); // Reset
return;
}
const seconds = parseDuration(value, 's');
if (Number.isInteger(seconds) && seconds > 0) {
const max = maxDurationInSeconds || ONE_HUNDRED_YEARS_IN_SECONDS;
if (seconds > max) {
handleInvalidInput(__('Value exceeded maximum.'));
} else {
handleValidInput(seconds);
}
} else {
handleInvalidInput(__('Invalid duration.'));
}
}, [value, valueSec, valueErr, maxDurationInSeconds, onResolve]);
return (
<FormField
name={name}
type="text"
label={
<>
{label || __('Duration')}
<Icon
customTooltipText={__('Examples: %examples%', { examples: INPUT_EXAMPLES })}
className="icon--help"
icon={ICONS.HELP}
tooltip
size={16}
/>
</>
}
placeholder={placeholder || '30s, 10m, 1h, 2d, 3mo, 1y'}
value={value}
onChange={onChange}
error={valueErr}
/>
);
}
+5 -1
View File
@@ -106,7 +106,11 @@ export default function Notification(props: Props) {
urlParams.append('lc', notification_parameters.dynamic.hash);
}
let channelName = channelUrl && '@' + channelUrl.split('@')[1].split('#')[0];
let channelName;
try {
const { claimName } = parseURI(channelUrl);
channelName = claimName;
} catch (e) {}
const notificationTitle = notification_parameters.device.title;
const titleSplit = notificationTitle.split(' ');
+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);
+6 -1
View File
@@ -449,7 +449,12 @@ function PublishFile(props: Props) {
{publishing && <Spinner type={'small'} />}
{inProgress && (
<div>
<Button button="close" label={__('New')} icon={ICONS.REFRESH} onClick={clearPublish} />
<Button
button="close"
label={__('New --[clears Publish Form]--')}
icon={ICONS.REFRESH}
onClick={clearPublish}
/>
</div>
)}
</div>
+9 -16
View File
@@ -1,31 +1,24 @@
import { connect } from 'react-redux';
import { makeSelectClaimIsNsfw, makeSelectClaimForUri } from 'lbry-redux';
import { doRecommendationUpdate, doRecommendationClicked } from 'redux/actions/content';
import { makeSelectClaimForUri } from 'lbry-redux';
import { doFetchRecommendedContent } from 'redux/actions/search';
import { makeSelectRecommendedContentForUri, selectIsSearching } from 'redux/selectors/search';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { makeSelectNextUnplayedRecommended } from 'redux/selectors/content';
import RecommendedContent from './view';
const select = (state, props) => {
const claim = makeSelectClaimForUri(props.uri)(state);
const { claim_id: claimId } = claim;
const recommendedContentUris = makeSelectRecommendedContentForUri(props.uri)(state);
const nextRecommendedUri = recommendedContentUris && recommendedContentUris[0];
return {
mature: makeSelectClaimIsNsfw(props.uri)(state),
recommendedContentUris: makeSelectRecommendedContentForUri(props.uri)(state),
nextRecommendedUri: makeSelectNextUnplayedRecommended(props.uri)(state),
isSearching: selectIsSearching(state),
isAuthenticated: selectUserVerifiedEmail(state),
claim,
claimId,
recommendedContentUris,
nextRecommendedUri,
isSearching: selectIsSearching(state),
isAuthenticated: selectUserVerifiedEmail(state),
};
};
const perform = (dispatch) => ({
doFetchRecommendedContent: (uri, mature) => dispatch(doFetchRecommendedContent(uri, mature)),
doRecommendationUpdate: (claimId, urls, id, parentId) =>
dispatch(doRecommendationUpdate(claimId, urls, id, parentId)),
doRecommendationClicked: (claimId, index) => dispatch(doRecommendationClicked(claimId, index)),
});
export default connect(select, perform)(RecommendedContent);
export default connect(select, { doFetchRecommendedContent })(RecommendedContent);
+13 -41
View File
@@ -18,11 +18,9 @@ type Props = {
recommendedContentUris: Array<string>,
nextRecommendedUri: string,
isSearching: boolean,
doFetchRecommendedContent: (string, boolean) => void,
mature: boolean,
doFetchRecommendedContent: (string) => void,
isAuthenticated: boolean,
claim: ?StreamClaim,
doRecommendationUpdate: (claimId: string, urls: Array<string>, id: string, parentId: string) => void,
claimId: string,
};
@@ -30,7 +28,6 @@ export default React.memo<Props>(function RecommendedContent(props: Props) {
const {
uri,
doFetchRecommendedContent,
mature,
recommendedContentUris,
nextRecommendedUri,
isSearching,
@@ -39,53 +36,29 @@ export default React.memo<Props>(function RecommendedContent(props: Props) {
claimId,
} = props;
const [viewMode, setViewMode] = React.useState(VIEW_ALL_RELATED);
const [recommendationUrls, setRecommendationUrls] = React.useState();
const signingChannel = claim && claim.signing_channel;
const channelName = signingChannel ? signingChannel.name : null;
const isMobile = useIsMobile();
const isMedium = useIsMediumScreen();
const { onRecsLoaded: onRecommendationsLoaded, onClickedRecommended: onRecommendationClicked } = RecSys;
React.useEffect(() => {
function moveAutoplayNextItemToTop(recommendedContent) {
let newList = recommendedContent;
if (newList) {
const index = newList.indexOf(nextRecommendedUri);
if (index > 0) {
const a = newList[0];
newList[0] = nextRecommendedUri;
newList[index] = a;
}
}
return newList;
}
function listEq(prev, next) {
if (prev && next) {
return prev.length === next.length && prev.every((value, index) => value === next[index]);
} else {
return prev === next;
}
}
const newRecommendationUrls = moveAutoplayNextItemToTop(recommendedContentUris);
if (claim && !listEq(recommendationUrls, newRecommendationUrls)) {
setRecommendationUrls(newRecommendationUrls);
}
}, [recommendedContentUris, nextRecommendedUri, recommendationUrls, setRecommendationUrls, claim]);
React.useEffect(() => {
doFetchRecommendedContent(uri, mature);
}, [uri, mature, doFetchRecommendedContent]);
doFetchRecommendedContent(uri);
}, [uri, doFetchRecommendedContent]);
React.useEffect(() => {
// Right now we only want to record the recs if they actually saw them.
if (recommendationUrls && recommendationUrls.length && nextRecommendedUri && viewMode === VIEW_ALL_RELATED) {
onRecommendationsLoaded(claimId, recommendationUrls);
if (
recommendedContentUris &&
recommendedContentUris.length &&
nextRecommendedUri &&
viewMode === VIEW_ALL_RELATED
) {
onRecommendationsLoaded(claimId, recommendedContentUris);
}
}, [recommendationUrls, onRecommendationsLoaded, claimId, nextRecommendedUri, viewMode]);
}, [recommendedContentUris, onRecommendationsLoaded, claimId, nextRecommendedUri, viewMode]);
function handleRecommendationClicked(e, clickedClaim, index: number) {
function handleRecommendationClicked(e, clickedClaim) {
if (claim) {
onRecommendationClicked(claim.claim_id, clickedClaim.claim_id);
}
@@ -124,7 +97,7 @@ export default React.memo<Props>(function RecommendedContent(props: Props) {
<ClaimList
type="small"
loading={isSearching}
uris={recommendationUrls}
uris={recommendedContentUris}
hideMenu={isMobile}
injectedItem={SHOW_ADS && IS_WEB && !isAuthenticated && <Ads small type={'video'} />}
empty={__('No related content found')}
@@ -164,7 +137,6 @@ function areEqual(prevProps: Props, nextProps: Props) {
a.nextRecommendedUri !== b.nextRecommendedUri ||
a.isAuthenticated !== b.isAuthenticated ||
a.isSearching !== b.isSearching ||
a.mature !== b.mature ||
(a.recommendedContentUris && !b.recommendedContentUris) ||
(!a.recommendedContentUris && b.recommendedContentUris) ||
(a.claim && !b.claim) ||
+10
View File
@@ -37,6 +37,8 @@ const SwapPage = lazyImport(() => import('page/swap' /* webpackChunkName: "secon
const WalletPage = lazyImport(() => import('page/wallet' /* webpackChunkName: "secondary" */));
// Chunk: none
const AppealListOffences = lazyImport(() => import('page/appealListOffences' /* webpackChunkName: "appealOffences" */));
const AppealReview = lazyImport(() => import('page/appealReview' /* webpackChunkName: "appealReview" */));
const NotificationsPage = lazyImport(() => import('page/notifications' /* webpackChunkName: "secondary" */));
const CollectionPage = lazyImport(() => import('page/collection' /* webpackChunkName: "secondary" */));
const ChannelNew = lazyImport(() => import('page/channelNew' /* webpackChunkName: "secondary" */));
@@ -77,6 +79,10 @@ const SettingsNotificationsPage = lazyImport(() =>
import('page/settingsNotifications' /* webpackChunkName: "secondary" */)
);
const SettingsPage = lazyImport(() => import('page/settings' /* webpackChunkName: "secondary" */));
const SharedBlocklistEdit = lazyImport(() => import('page/sharedBlocklistEdit' /* webpackChunkName: "sblEdit" */));
const SharedBlocklistInvite = lazyImport(() =>
import('page/sharedBlocklistInvite' /* webpackChunkName: "sblInvite" */)
);
const ShowPage = lazyImport(() => import('page/show' /* webpackChunkName: "secondary" */));
const TagsFollowingManagePage = lazyImport(() =>
import('page/tagsFollowingManage' /* webpackChunkName: "secondary" */)
@@ -318,6 +324,10 @@ function AppRouter(props: Props) {
<PrivateRoute {...props} path={`/$/${PAGES.LISTS}`} component={ListsPage} />
<PrivateRoute {...props} path={`/$/${PAGES.TAGS_FOLLOWING_MANAGE}`} component={TagsFollowingManagePage} />
<PrivateRoute {...props} path={`/$/${PAGES.SETTINGS_BLOCKED_MUTED}`} component={ListBlockedPage} />
<PrivateRoute {...props} path={`/$/${PAGES.SHARED_BLOCKLIST_EDIT}`} component={SharedBlocklistEdit} />
<PrivateRoute {...props} path={`/$/${PAGES.SHARED_BLOCKLIST_INVITE}`} component={SharedBlocklistInvite} />
<PrivateRoute {...props} path={`/$/${PAGES.APPEAL_LIST_OFFENCES}`} component={AppealListOffences} />
<PrivateRoute {...props} path={`/$/${PAGES.APPEAL_CREATOR_REVIEW}`} component={AppealReview} />
<PrivateRoute {...props} path={`/$/${PAGES.SETTINGS_CREATOR}`} component={SettingsCreatorPage} />
<PrivateRoute {...props} path={`/$/${PAGES.WALLET}`} exact component={WalletPage} />
<PrivateRoute {...props} path={`/$/${PAGES.CHANNELS}`} component={ChannelsPage} />
+3 -3
View File
@@ -17,8 +17,8 @@ type Props = {
winningUri: ?string,
doResolveUris: (Array<string>) => void,
hideLink?: boolean,
setChannelActive: boolean => void,
beginPublish: string => void,
setChannelActive: (boolean) => void,
beginPublish: (string) => void,
pendingIds: Array<string>,
isResolvingWinningUri: boolean,
winningClaim: ?Claim,
@@ -92,7 +92,7 @@ export default function SearchTopClaim(props: Props) {
hideRepostLabel
showNullPlaceholder
uri={winningUri}
properties={claim => (
properties={(claim) => (
<span className="claim-preview__custom-properties">
<ClaimRepostAuthor short uri={winningUri} />
<ClaimEffectiveAmount uri={winningUri} />
+8 -3
View File
@@ -22,10 +22,14 @@ const channelsToSubscribe = AUTO_FOLLOW_CHANNELS.trim()
function UserChannelFollowIntro(props: Props) {
const { subscribedChannels, channelSubscribe, onContinue, homepageData, prefsReady } = props;
const { PRIMARY_CONTENT } = homepageData;
const { PRIMARY_CONTENT, LATEST } = homepageData;
let channelIds;
if (PRIMARY_CONTENT && CUSTOM_HOMEPAGE) {
channelIds = PRIMARY_CONTENT.channelIds;
if (CUSTOM_HOMEPAGE) {
if (LATEST) {
channelIds = LATEST.channelIds;
} else if (PRIMARY_CONTENT) {
channelIds = PRIMARY_CONTENT.channelIds;
}
}
const followingCount = (subscribedChannels && subscribedChannels.length) || 0;
const followingCountIgnoringAutoFollows = (subscribedChannels || []).filter(
@@ -59,6 +63,7 @@ function UserChannelFollowIntro(props: Props) {
<div className="section__body">
<ClaimListDiscover
hideFilters={SIMPLE_SITE}
hideAdvancedFilter={SIMPLE_SITE}
meta={
<Button
button={subscribedChannels.length < 1 ? 'alt' : 'primary'}
+4 -7
View File
@@ -16,12 +16,8 @@ import {
} from 'redux/actions/app';
import { selectVolume, selectMute } from 'redux/selectors/app';
import { savePosition, clearPosition, doPlayUri, doSetPlayingUri } from 'redux/actions/content';
import {
makeSelectContentPositionForUri,
makeSelectIsPlayerFloating,
makeSelectNextUnplayedRecommended,
selectPlayingUri,
} from 'redux/selectors/content';
import { makeSelectContentPositionForUri, makeSelectIsPlayerFloating, selectPlayingUri } from 'redux/selectors/content';
import { makeSelectRecommendedContentForUri } from 'redux/selectors/search';
import VideoViewer from './view';
import { withRouter } from 'react-router';
import { doClaimEligiblePurchaseRewards } from 'redux/actions/rewards';
@@ -47,7 +43,8 @@ const select = (state, props) => {
nextRecommendedUri = makeSelectNextUrlForCollectionAndUrl(collectionId, uri)(state);
previousListUri = makeSelectPreviousUrlForCollectionAndUrl(collectionId, uri)(state);
} else {
nextRecommendedUri = makeSelectNextUnplayedRecommended(uri)(state);
const recommendedContent = makeSelectRecommendedContentForUri(uri)(state);
nextRecommendedUri = recommendedContent && recommendedContent[0];
}
return {
+2 -1
View File
@@ -2,7 +2,7 @@ import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import WalletSwap from './view';
import { doOpenModal } from 'redux/actions/app';
import { doAddCoinSwap, doQueryCoinSwapStatus } from 'redux/actions/coinSwap';
import { doAddCoinSwap, doRemoveCoinSwap, doQueryCoinSwapStatus } from 'redux/actions/coinSwap';
import { doToast } from 'redux/actions/notifications';
import { selectCoinSwaps } from 'redux/selectors/coinSwap';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
@@ -18,6 +18,7 @@ const perform = (dispatch) => ({
openModal: (modal, props) => dispatch(doOpenModal(modal, props)),
doToast: (options) => dispatch(doToast(options)),
addCoinSwap: (coinSwap) => dispatch(doAddCoinSwap(coinSwap)),
removeCoinSwap: (chargeCode) => dispatch(doRemoveCoinSwap(chargeCode)),
getNewAddress: () => dispatch(doGetNewAddress()),
checkAddressIsMine: (address) => dispatch(doCheckAddressIsMine(address)),
queryCoinSwapStatus: (sendAddress) => dispatch(doQueryCoinSwapStatus(sendAddress)),
+12 -4
View File
@@ -59,6 +59,7 @@ type Props = {
isAuthenticated: boolean,
doToast: ({ message: string }) => void,
addCoinSwap: (CoinSwapInfo) => void,
removeCoinSwap: (string) => void,
getNewAddress: () => void,
checkAddressIsMine: (string) => void,
openModal: (string, {}) => void,
@@ -72,6 +73,7 @@ function WalletSwap(props: Props) {
coinSwaps,
isAuthenticated,
addCoinSwap,
removeCoinSwap,
getNewAddress,
checkAddressIsMine,
openModal,
@@ -103,9 +105,15 @@ function WalletSwap(props: Props) {
setSwap(null);
}
function removeCoinSwap(chargeCode) {
openModal(MODALS.CONFIRM_REMOVE_BTC_SWAP_ADDRESS, {
chargeCode: chargeCode,
function handleRemoveSwap(chargeCode) {
openModal(MODALS.CONFIRM, {
title: __('Remove Swap'),
subtitle: <I18nMessage tokens={{ address: <em>{`${chargeCode}`}</em> }}>Remove %address%?</I18nMessage>,
body: <p className="help--warning">{__('This process cannot be reversed.')}</p>,
onConfirm: (closeModal) => {
removeCoinSwap(chargeCode);
closeModal();
},
});
}
@@ -657,7 +665,7 @@ function WalletSwap(props: Props) {
button="link"
icon={ICONS.REMOVE}
title={__('Remove swap')}
onClick={() => removeCoinSwap(x.chargeCode)}
onClick={() => handleRemoveSwap(x.chargeCode)}
/>
</td>
</tr>
+11 -3
View File
@@ -1,7 +1,14 @@
import { connect } from 'react-redux';
import { doResolveUris, makeSelectClaimForUri, makeSelectIsUriResolving, parseURI } from 'lbry-redux';
import {
doResolveUris,
makeSelectClaimForUri,
makeSelectIsUriResolving,
makeSelectTagInClaimOrChannelForUri,
parseURI,
} from 'lbry-redux';
import { makeSelectWinningUriForQuery } from 'redux/selectors/search';
import WunderbarTopSuggestion from './view';
import { PREFERENCE_EMBED } from 'constants/tags';
const select = (state, props) => {
const uriFromQuery = `lbry://${props.query}`;
@@ -16,11 +23,12 @@ const select = (state, props) => {
}
} catch (e) {}
const resolvingUris = uris.some(uri => makeSelectIsUriResolving(uri)(state));
const resolvingUris = uris.some((uri) => makeSelectIsUriResolving(uri)(state));
const winningUri = makeSelectWinningUriForQuery(props.query)(state);
const winningClaim = winningUri ? makeSelectClaimForUri(winningUri)(state) : undefined;
const preferEmbed = makeSelectTagInClaimOrChannelForUri(winningUri, PREFERENCE_EMBED)(state);
return { resolvingUris, winningUri, winningClaim, uris };
return { resolvingUris, winningUri, winningClaim, uris, preferEmbed };
};
export default connect(select, {
+3 -2
View File
@@ -8,10 +8,11 @@ type Props = {
doResolveUris: (Array<string>) => void,
uris: Array<string>,
resolvingUris: boolean,
preferEmbed: boolean,
};
export default function WunderbarTopSuggestion(props: Props) {
const { uris, resolvingUris, winningUri, doResolveUris } = props;
const { uris, resolvingUris, winningUri, doResolveUris, preferEmbed } = props;
const stringifiedUris = JSON.stringify(uris);
React.useEffect(() => {
@@ -38,7 +39,7 @@ export default function WunderbarTopSuggestion(props: Props) {
);
}
if (!winningUri) {
if (!winningUri || preferEmbed) {
return null;
}
+12
View File
@@ -253,6 +253,7 @@ export const COMMENT_LIST_STARTED = 'COMMENT_LIST_STARTED';
export const COMMENT_LIST_COMPLETED = 'COMMENT_LIST_COMPLETED';
export const COMMENT_LIST_FAILED = 'COMMENT_LIST_FAILED';
export const COMMENT_LIST_RESET = 'COMMENT_LIST_RESET';
export const COMMENT_BY_ID_STARTED = 'COMMENT_BY_ID_STARTED';
export const COMMENT_BY_ID_COMPLETED = 'COMMENT_BY_ID_COMPLETED';
export const COMMENT_CREATE_STARTED = 'COMMENT_CREATE_STARTED';
export const COMMENT_CREATE_COMPLETED = 'COMMENT_CREATE_COMPLETED';
@@ -300,6 +301,13 @@ export const COMMENT_RECEIVED = 'COMMENT_RECEIVED';
export const COMMENT_SUPER_CHAT_LIST_STARTED = 'COMMENT_SUPER_CHAT_LIST_STARTED';
export const COMMENT_SUPER_CHAT_LIST_COMPLETED = 'COMMENT_SUPER_CHAT_LIST_COMPLETED';
export const COMMENT_SUPER_CHAT_LIST_FAILED = 'COMMENT_SUPER_CHAT_LIST_FAILED';
export const COMMENT_SBL_FETCH_STARTED = 'COMMENT_SBL_FETCH_STARTED';
export const COMMENT_SBL_FETCH_FAILED = 'COMMENT_SBL_FETCH_FAILED';
export const COMMENT_SBL_FETCH_COMPLETED = 'COMMENT_SBL_FETCH_COMPLETED';
export const COMMENT_SBL_FETCH_INVITES_STARTED = 'COMMENT_SBL_FETCH_INVITES_STARTED';
export const COMMENT_SBL_FETCH_INVITES_FAILED = 'COMMENT_SBL_FETCH_INVITES_FAILED';
export const COMMENT_SBL_FETCH_INVITES_COMPLETED = 'COMMENT_SBL_FETCH_INVITES_COMPLETED';
export const COMMENT_SBL_DELETED = 'COMMENT_SBL_DELETED';
// Blocked channels
export const TOGGLE_BLOCK_CHANNEL = 'TOGGLE_BLOCK_CHANNEL';
@@ -352,3 +360,7 @@ export const FETCH_NO_SOURCE_CLAIMS_STARTED = 'FETCH_NO_SOURCE_CLAIMS_STARTED';
export const FETCH_NO_SOURCE_CLAIMS_COMPLETED = 'FETCH_NO_SOURCE_CLAIMS_COMPLETED';
export const FETCH_NO_SOURCE_CLAIMS_FAILED = 'FETCH_NO_SOURCE_CLAIMS_FAILED';
export const VIEWERS_RECEIVED = 'VIEWERS_RECEIVED';
export const FETCH_ACTIVE_LIVESTREAMS_STARTED = 'FETCH_ACTIVE_LIVESTREAMS_STARTED';
export const FETCH_ACTIVE_LIVESTREAMS_FAILED = 'FETCH_ACTIVE_LIVESTREAMS_FAILED';
export const FETCH_ACTIVE_LIVESTREAMS_SKIPPED = 'FETCH_ACTIVE_LIVESTREAMS_SKIPPED';
export const FETCH_ACTIVE_LIVESTREAMS_COMPLETED = 'FETCH_ACTIVE_LIVESTREAMS_COMPLETED';
+12
View File
@@ -19,3 +19,15 @@ export const BLOCK_LEVEL = {
export const COMMENT_PAGE_SIZE_TOP_LEVEL = 10;
export const COMMENT_PAGE_SIZE_REPLIES = 10;
// ***************************************************************************
// SBL: Shared Blocked List
// ***************************************************************************
export const SBL_INVITE_STATUS = {
ALL: 0,
PENDING: 1,
ACCEPTED: 2,
REJECTED: 3,
NONE: 4,
};
+6
View File
@@ -171,6 +171,12 @@ export const STAR = 'star';
export const MUSIC = 'MusicCategory';
export const BADGE_MOD = 'BadgeMod';
export const BADGE_STREAMER = 'BadgeStreamer';
export const APPEAL = 'JudgeHammer';
export const REPLAY = 'Replay';
export const REPEAT = 'Repeat';
export const SHUFFLE = 'Shuffle';
export const HOLD_PHONE = 'HOLD_PHONE';
export const LIFE = 'Life';
export const ARTISTS = 'Artists';
export const MYSTERIES = 'Mysteries';
export const TECHNOLOGY = 'Technology';
+1 -1
View File
@@ -1,3 +1,4 @@
export const CONFIRM = 'confirm';
export const CONFIRM_FILE_REMOVE = 'confirm_file_remove';
export const CONFIRM_EXTERNAL_RESOURCE = 'confirm_external_resource';
export const COMMENT_ACKNOWEDGEMENT = 'comment_acknowlegement';
@@ -42,7 +43,6 @@ export const SYNC_ENABLE = 'SYNC_ENABLE';
export const IMAGE_UPLOAD = 'image_upload';
export const MOBILE_SEARCH = 'mobile_search';
export const VIEW_IMAGE = 'view_image';
export const CONFIRM_REMOVE_BTC_SWAP_ADDRESS = 'confirm_remove_btc_swap_address';
export const BLOCK_CHANNEL = 'block_channel';
export const COLLECTION_ADD = 'collection_add';
export const COLLECTION_DELETE = 'collection_delete';
+8 -4
View File
@@ -1,6 +1,7 @@
// Customer-facing title for a page.
//
// Primarily used for the browser tab and history title.
// Ensure new strings are added to 'app-string.json' for localization.
import * as PAGES from 'constants/pages';
@@ -9,14 +10,16 @@ export const PAGE_TITLE = {
[PAGES.BIG_HITS]: 'Big Hits',
[PAGES.DISCOVER]: 'Wild West',
// [PAGES.ENLIGHTENMENT] = 'Enlightenment',
[PAGES.FINANCE]: 'Finance',
[PAGES.FINANCE]: 'Finance 2.0',
[PAGES.GAMING]: 'Gaming',
[PAGES.GENERAL]: 'Cheese',
[PAGES.LAB]: 'Lab',
[PAGES.MOVIES]: 'Movies',
[PAGES.MUSIC]: 'Music',
[PAGES.NEWS]: 'News & Politics',
// [PAGES.RABBIT_HOLE] = 'The Rabbit Hole';
// [PAGES.RABBIT_HOLE]: 'The Rabbit Hole';
[PAGES.TECH]: 'Tech',
[PAGES.UNIVERSE]: 'The Universe',
[PAGES.WILD_WEST]: 'Wild West',
// --- Everything else in alphabetical order ---
@@ -46,8 +49,8 @@ export const PAGE_TITLE = {
[PAGES.SETTINGS_BLOCKED_MUTED]: 'Block and muted channels',
[PAGES.SETTINGS_CREATOR]: 'Creator settings',
[PAGES.SETTINGS_NOTIFICATIONS]: 'Manage notifications',
[PAGES.SETTINGS_STRIPE_ACCOUNT]: 'settings/tip_account',
[PAGES.SETTINGS_STRIPE_CARD]: 'settings/card',
[PAGES.SETTINGS_STRIPE_ACCOUNT]: 'Bank Accounts',
[PAGES.SETTINGS_STRIPE_CARD]: 'Payment Methods',
[PAGES.SETTINGS_UPDATE_PWD]: 'Update password',
[PAGES.SWAP]: 'Swap Credits',
[PAGES.TAGS_FOLLOWING]: 'Tags',
@@ -56,4 +59,5 @@ export const PAGE_TITLE = {
[PAGES.UPLOADS]: 'Your uploads',
[PAGES.WALLET]: 'Wallet',
[PAGES.WELCOME]: 'Welcome',
[PAGES.YOUTUBE_SYNC]: 'YouTube Sync',
};
+8
View File
@@ -20,6 +20,8 @@ exports.NEWS = 'news';
exports.RABBIT_HOLE = 'rabbithole';
exports.SCIENCE = 'science';
exports.TECHNOLOGY = 'technology';
exports.TECH = 'tech';
exports.UNIVERSE = 'universe';
exports.WILD_WEST = 'wildwest';
exports.HOME = 'home';
exports.HELP = 'help';
@@ -72,5 +74,11 @@ exports.NOTIFICATIONS = 'notifications';
exports.YOUTUBE_SYNC = 'youtube';
exports.LIVESTREAM = 'livestream';
exports.LIVESTREAM_CURRENT = 'live';
exports.SHARED_BLOCKLIST_EDIT = 'sharedblocklist/edit';
exports.SHARED_BLOCKLIST_INVITE = 'sharedblocklist/invite';
exports.APPEAL_LIST_OFFENCES = 'appeal/offences';
exports.APPEAL_FILE = 'appeal/file';
exports.APPEAL_FILED = 'appeal/filed';
exports.APPEAL_CREATOR_REVIEW = 'appeal/review';
exports.GENERAL = 'general';
exports.LIST = 'list';
+3
View File
@@ -13,9 +13,11 @@ export const SEARCH_TYPES = {
export const SEARCH_OPTIONS = {
RESULT_COUNT: 'size',
CLAIM_TYPE: 'claimType',
RELATED_TO: 'related_to',
INCLUDE_FILES: 'file',
INCLUDE_CHANNELS: 'channel',
INCLUDE_FILES_AND_CHANNELS: 'file,channel',
INCLUDE_MATURE: 'nsfw',
MEDIA_AUDIO: 'audio',
MEDIA_VIDEO: 'video',
MEDIA_TEXT: 'text',
@@ -25,6 +27,7 @@ export const SEARCH_OPTIONS = {
SORT_ACCENDING: '^release_time',
SORT_DESCENDING: 'release_time',
EXACT: 'exact',
PRICE_FILTER_FREE: 'free_only',
TIME_FILTER: 'time_filter',
TIME_FILTER_LAST_HOUR: 'lasthour',
TIME_FILTER_TODAY: 'today',
+3 -1
View File
@@ -14,8 +14,10 @@ export const DEFAULT_FOLLOWED_TAGS = [
];
export const DISABLE_COMMENTS_TAG = 'disable-comments';
export const DISABLE_SUPPORT_TAG = 'disable-support';
export const PREFERENCE_EMBED = 'preference-embed';
export const UTILITY_TAGS = [DISABLE_COMMENTS_TAG];
export const UTILITY_TAGS = [DISABLE_COMMENTS_TAG, DISABLE_SUPPORT_TAG, PREFERENCE_EMBED];
export const MATURE_TAGS = [
'porn',
+24
View File
@@ -0,0 +1,24 @@
// @flow
import { useState, useEffect } from 'react';
export default function useFetchViewCount(
shouldFetch: ?boolean,
uris: Array<string>,
claimsByUri: any,
doFetchViewCount: (string) => void
) {
const [fetchedUris, setFetchedUris] = useState([]);
useEffect(() => {
if (shouldFetch && uris && uris.length > 0) {
const urisToFetch = uris.filter((uri) => uri && !fetchedUris.includes(uri) && Boolean(claimsByUri[uri]));
if (urisToFetch.length > 0) {
const claimIds = urisToFetch.map((uri) => claimsByUri[uri].claim_id);
doFetchViewCount(claimIds.join(','));
setFetchedUris([...fetchedUris, ...urisToFetch]);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [uris]);
}
-55
View File
@@ -1,55 +0,0 @@
// @flow
import React from 'react';
import { LIVESTREAM_LIVE_API } from 'constants/livestream';
/**
* Gets latest livestream info list. Returns null (instead of a blank object)
* when there are no active livestreams.
*
* @param minViewers
* @param refreshMs
* @returns {{livestreamMap: null, loading: boolean}}
*/
export default function useGetLivestreams(minViewers: number = 0, refreshMs: number = 0) {
const [loading, setLoading] = React.useState(true);
const [livestreamMap, setLivestreamMap] = React.useState(null);
React.useEffect(() => {
function checkCurrentLivestreams() {
fetch(LIVESTREAM_LIVE_API)
.then((res) => res.json())
.then((res) => {
setLoading(false);
if (!res.data) {
setLivestreamMap(null);
return;
}
const livestreamMap = res.data.reduce((acc, curr) => {
if (curr.viewCount >= minViewers) {
acc[curr.claimId] = curr;
}
return acc;
}, {});
setLivestreamMap(livestreamMap);
})
.catch((err) => {
setLoading(false);
});
}
checkCurrentLivestreams();
if (refreshMs > 0) {
let fetchInterval = setInterval(checkCurrentLivestreams, refreshMs);
return () => {
if (fetchInterval) {
clearInterval(fetchInterval);
}
};
}
}, []);
return { livestreamMap, loading };
}
+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());
+6 -63
View File
@@ -1,14 +1,12 @@
// @flow
import React from 'react';
import classnames from 'classnames';
import parseDuration from 'parse-duration';
import Button from 'component/button';
import ChannelThumbnail from 'component/channelThumbnail';
import ClaimPreview from 'component/claimPreview';
import Card from 'component/common/card';
import { FormField } from 'component/common/form';
import Icon from 'component/common/icon';
import * as ICONS from 'constants/icons';
import FormFieldDuration from 'component/formFieldDuration';
import usePersistedState from 'effects/use-persisted-state';
import { Modal } from 'modal/modal';
import { getChannelFromClaim } from 'util/claim';
@@ -67,7 +65,6 @@ export default function ModalBlockChannel(props: Props) {
const [tab, setTab] = usePersistedState('ModalBlockChannel:tab', TAB.PERSONAL);
const [blockType, setBlockType] = usePersistedState('ModalBlockChannel:blockType', BLOCK.PERMANENT);
const [timeoutInput, setTimeoutInput] = usePersistedState('ModalBlockChannel:timeoutInput', '10m');
const [timeoutInputErr, setTimeoutInputErr] = React.useState('');
const [timeoutSec, setTimeoutSec] = React.useState(-1);
const isPersonalTheOnlyTab = !activeChannelIsModerator && !activeChannelIsAdmin;
@@ -92,45 +89,6 @@ export default function ModalBlockChannel(props: Props) {
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
// 'timeoutInput' to 'timeoutSec' conversion.
React.useEffect(() => {
const handleInvalidInput = (errMsg: string) => {
if (timeoutSec !== -1) {
setTimeoutSec(-1);
}
if (timeoutInputErr !== errMsg) {
setTimeoutInputErr(errMsg);
}
};
const handleValidInput = (seconds) => {
if (seconds !== timeoutSec) {
setTimeoutSec(seconds);
}
if (timeoutInputErr) {
setTimeoutInputErr('');
}
};
if (!timeoutInput) {
handleValidInput(-1); // Reset
return;
}
const ONE_HUNDRED_YEARS_IN_SECONDS = 3154000000;
const seconds = parseDuration(timeoutInput, 's');
if (Number.isInteger(seconds) && seconds > 0) {
if (seconds > ONE_HUNDRED_YEARS_IN_SECONDS) {
handleInvalidInput(__('Wow, banned for more than 100 years?'));
} else {
handleValidInput(seconds);
}
} else {
handleInvalidInput(__('Invalid duration.'));
}
}, [timeoutInput, timeoutInputErr, timeoutSec]);
// **************************************************************************
// **************************************************************************
@@ -153,9 +111,9 @@ export default function ModalBlockChannel(props: Props) {
case TAB.MODERATOR:
return (
<p className="help">
{__('Block this channel on behalf of %creator%', {
creator: contentChannelClaim ? contentChannelClaim.name : __('creator'),
})}
{contentChannelClaim
? __('Block this channel on behalf of %creator%.', { creator: contentChannelClaim.name })
: __('Block this channel on behalf of the creator.')}
</p>
);
case TAB.ADMIN:
@@ -178,27 +136,12 @@ export default function ModalBlockChannel(props: Props) {
}
function getTimeoutDurationElem() {
const examples = '\n- 30s\n- 10m\n- 1h\n- 2d\n- 3mo\n- 1y';
return (
<FormField
<FormFieldDuration
name="time_out"
label={
<>
{__('Duration')}
<Icon
customTooltipText={__('Enter the timeout duration. Examples: %examples%', { examples })}
className="icon--help"
icon={ICONS.HELP}
tooltip
size={16}
/>
</>
}
type="text"
placeholder="30s, 10m, 1h, 2d, 3mo, 1y"
value={timeoutInput}
onChange={(e) => setTimeoutInput(e.target.value)}
error={timeoutInputErr}
onResolve={(valueInSeconds) => setTimeoutSec(valueInSeconds)}
/>
);
}
+10
View File
@@ -0,0 +1,10 @@
import { connect } from 'react-redux';
import { doHideModal } from 'redux/actions/app';
import ModalConfirm from './view';
const perform = (dispatch) => ({
doHideModal: () => dispatch(doHideModal()),
});
export default connect(null, perform)(ModalConfirm);
+55
View File
@@ -0,0 +1,55 @@
// @flow
import React from 'react';
import type { Node } from 'react';
import Button from 'component/button';
import Card from 'component/common/card';
import Spinner from 'component/spinner';
import { Modal } from 'modal/modal';
type Props = {
title: string,
subtitle?: string | Node,
body?: string | Node,
labelOk?: string,
labelCancel?: string,
onConfirm: (closeModal: () => void, setIsBusy: (boolean) => void) => void,
// --- perform ---
doHideModal: () => void,
};
export default function ModalConfirm(props: Props) {
const { title, subtitle, body, labelOk, labelCancel, onConfirm, doHideModal } = props;
const [isBusy, setIsBusy] = React.useState(false);
function handleOnClick() {
if (onConfirm) {
onConfirm(doHideModal, setIsBusy);
}
}
function getOkLabel() {
return isBusy ? <Spinner type="small" /> : labelOk || __('OK');
}
function getCancelLabel() {
return labelCancel || __('Cancel');
}
return (
<Modal isOpen type="card" onAborted={doHideModal}>
<Card
title={title}
subtitle={subtitle}
body={body}
actions={
<>
<div className="section__actions">
<Button button="primary" label={getOkLabel()} disabled={isBusy} onClick={handleOnClick} />
<Button button="link" label={getCancelLabel()} disabled={isBusy} onClick={doHideModal} />
</div>
</>
}
/>
</Modal>
);
}
@@ -1,13 +0,0 @@
import { connect } from 'react-redux';
import { doHideModal } from 'redux/actions/app';
import ModalRemoveBtcSwapAddress from './view';
import { doRemoveCoinSwap } from 'redux/actions/coinSwap';
const select = (state, props) => ({});
const perform = (dispatch) => ({
removeCoinSwap: (chargeCode) => dispatch(doRemoveCoinSwap(chargeCode)),
closeModal: () => dispatch(doHideModal()),
});
export default connect(select, perform)(ModalRemoveBtcSwapAddress);
@@ -1,43 +0,0 @@
// @flow
import React from 'react';
import { Modal } from 'modal/modal';
import Button from 'component/button';
import Card from 'component/common/card';
import I18nMessage from 'component/i18nMessage';
type Props = {
chargeCode: string,
removeCoinSwap: (string) => void,
closeModal: () => void,
};
function ModalRemoveBtcSwapAddress(props: Props) {
const { chargeCode, removeCoinSwap, closeModal } = props;
return (
<Modal isOpen contentLabel={__('Confirm Swap Removal')} type="card" onAborted={closeModal}>
<Card
title={__('Remove Swap')}
subtitle={<I18nMessage tokens={{ address: <em>{`${chargeCode}`}</em> }}>Remove %address%?</I18nMessage>}
body={<p className="help--warning">{__('This process cannot be reversed.')}</p>}
actions={
<>
<div className="section__actions">
<Button
button="primary"
label={__('OK')}
onClick={() => {
removeCoinSwap(chargeCode);
closeModal();
}}
/>
<Button button="link" label={__('Cancel')} onClick={closeModal} />
</div>
</>
}
/>
</Modal>
);
}
export default ModalRemoveBtcSwapAddress;
+3 -5
View File
@@ -23,6 +23,7 @@ const ModalClaimCollectionAdd = lazyImport(() =>
const ModalCommentAcknowledgement = lazyImport(() =>
import('modal/modalCommentAcknowledgement' /* webpackChunkName: "modalCommentAcknowledgement" */)
);
const ModalConfirm = lazyImport(() => import('modal/modalConfirm' /* webpackChunkName: "modalConfirm" */));
const ModalConfirmAge = lazyImport(() => import('modal/modalConfirmAge' /* webpackChunkName: "modalConfirmAge" */));
const ModalConfirmThumbnailUpload = lazyImport(() =>
import('modal/modalConfirmThumbnailUpload' /* webpackChunkName: "modalConfirmThumbnailUpload" */)
@@ -63,9 +64,6 @@ const ModalPublish = lazyImport(() => import('modal/modalPublish' /* webpackChun
const ModalPublishPreview = lazyImport(() =>
import('modal/modalPublishPreview' /* webpackChunkName: "modalPublishPreview" */)
);
const ModalRemoveBtcSwapAddress = lazyImport(() =>
import('modal/modalRemoveBtcSwapAddress' /* webpackChunkName: "modalRemoveBtcSwapAddress" */)
);
const ModalRemoveCard = lazyImport(() => import('modal/modalRemoveCard' /* webpackChunkName: "modalRemoveCard" */));
const ModalRemoveComment = lazyImport(() =>
import('modal/modalRemoveComment' /* webpackChunkName: "modalRemoveComment" */)
@@ -124,6 +122,8 @@ function ModalRouter(props: Props) {
function getModal(id) {
switch (id) {
case MODALS.CONFIRM:
return ModalConfirm;
case MODALS.UPGRADE:
return ModalUpgrade;
case MODALS.DOWNLOADING:
@@ -198,8 +198,6 @@ function ModalRouter(props: Props) {
return ModalViewImage;
case MODALS.MASS_TIP_UNLOCK:
return ModalMassTipsUnlock;
case MODALS.CONFIRM_REMOVE_BTC_SWAP_ADDRESS:
return ModalRemoveBtcSwapAddress;
case MODALS.BLOCK_CHANNEL:
return ModalBlockChannel;
case MODALS.COLLECTION_ADD:
+12
View File
@@ -0,0 +1,12 @@
import { connect } from 'react-redux';
import { doOpenModal } from 'redux/actions/app';
import AppealListOffences from './view';
const select = (state) => ({});
const perform = (dispatch) => ({
doOpenModal: (modal, props) => dispatch(doOpenModal(modal, props)),
});
export default connect(select, perform)(AppealListOffences);
+60
View File
@@ -0,0 +1,60 @@
// @flow
import React from 'react';
import Button from 'component/button';
import ClaimList from 'component/claimList';
import Page from 'component/page';
import * as ICONS from 'constants/icons';
import * as MODALS from 'constants/modal_types';
type Props = {
doOpenModal: (id: string, {}) => void,
};
export default function AppealListOffences(props: Props) {
const { doOpenModal } = props;
const blockerUris = [
'lbry://@grumpy#3c98c9fc7988a1de4ac4ccfddab47416d9871c0d',
'lbry://@timeout#8237fcdf9c3288d49cff1a3a609d680d486447ff',
];
return (
<Page noSideNavigation className="main--half-width" backout={{ backoutLabel: __('Cancel'), title: __('Offences') }}>
<div className="help--notice">{HELP.OFFENCES}</div>
<div className="section">
<ClaimList
uris={blockerUris}
hideMenu
renderProperties={() => null}
renderActions={(claim) => {
return (
<div className="section__actions">
<Button
button="secondary"
icon={ICONS.APPEAL}
label={__('Appeal')}
title={__(HELP.MANUAL_APPEAL)}
onClick={() => doOpenModal(MODALS.CONFIRM, { title: 'Not implemented yet.' })}
/>
<Button
button="secondary"
icon={ICONS.LBC}
label={__('Auto Appeal')}
title={__(HELP.AUTO_APPEAL)}
onClick={() => doOpenModal(MODALS.CONFIRM, { title: 'Not implemented yet.' })}
/>
</div>
);
}}
/>
</div>
</Page>
);
}
// prettier-ignore
const HELP = {
OFFENCES: 'These are creators that have blocked you. You can choose to appeal to the creator. If the creator has enabled automatic appeal (a.k.a swear jar), you can have your offences automatically pardoned by tipping the creator.',
MANUAL_APPEAL: 'Appeal to the creator to remove you from their blocklist.',
AUTO_APPEAL: 'The creator has enabled the auto-appeal process, where your offence can be automatically pardoned by tipping the creator.',
};
+12
View File
@@ -0,0 +1,12 @@
import { connect } from 'react-redux';
import { doOpenModal } from 'redux/actions/app';
import AppealReview from './view';
const select = (state) => ({});
const perform = (dispatch) => ({
doOpenModal: (modal, props) => dispatch(doOpenModal(modal, props)),
});
export default connect(select, perform)(AppealReview);
+60
View File
@@ -0,0 +1,60 @@
// @flow
import React from 'react';
import Button from 'component/button';
import ClaimList from 'component/claimList';
import Page from 'component/page';
import * as ICONS from 'constants/icons';
import * as MODALS from 'constants/modal_types';
type Props = {
doOpenModal: (id: string, {}) => void,
};
export default function AppealReview(props: Props) {
const { doOpenModal } = props;
const appellantUris = [
'lbry://@grumpy#3c98c9fc7988a1de4ac4ccfddab47416d9871c0d',
'lbry://@timeout#8237fcdf9c3288d49cff1a3a609d680d486447ff',
];
return (
<Page
noSideNavigation
className="main--half-width"
backout={{ backoutLabel: __('Cancel'), title: __('Review Appeals') }}
>
<div className="help--notice">{HELP.APPELLANTS}</div>
<div className="section">
<ClaimList
uris={appellantUris}
hideMenu
renderProperties={() => null}
renderActions={(claim) => {
return (
<div className="section__actions">
<Button
button="secondary"
icon={ICONS.COMPLETE}
label={__('Approve')}
onClick={() => doOpenModal(MODALS.CONFIRM, { title: 'Not implemented -- waiting for API' })}
/>
<Button
button="secondary"
icon={ICONS.REMOVE}
label={__('Reject')}
onClick={() => doOpenModal(MODALS.CONFIRM, { title: 'Not implemented -- waiting for API' })}
/>
</div>
);
}}
/>
</div>
</Page>
);
}
// prettier-ignore
const HELP = {
APPELLANTS: 'The following users have requested an appeal against blocking their channel.',
};
+7 -2
View File
@@ -1,13 +1,18 @@
import { connect } from 'react-redux';
import { SETTINGS } from 'lbry-redux';
import { doFetchActiveLivestreams } from 'redux/actions/livestream';
import { selectActiveLivestreams } from 'redux/selectors/livestream';
import { selectSubscriptions } from 'redux/selectors/subscriptions';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import ChannelsFollowingPage from './view';
const select = state => ({
const select = (state) => ({
subscribedChannels: selectSubscriptions(state),
tileLayout: makeSelectClientSetting(SETTINGS.TILE_LAYOUT)(state),
activeLivestreams: selectActiveLivestreams(state),
});
export default connect(select)(ChannelsFollowingPage);
export default connect(select, {
doFetchActiveLivestreams,
})(ChannelsFollowingPage);
+12 -6
View File
@@ -9,24 +9,32 @@ import ClaimListDiscover from 'component/claimListDiscover';
import Page from 'component/page';
import Button from 'component/button';
import Icon from 'component/common/icon';
import useGetLivestreams from 'effects/use-get-livestreams';
import { splitBySeparator } from 'lbry-redux';
import { getLivestreamUris } from 'util/livestream';
type Props = {
subscribedChannels: Array<Subscription>,
tileLayout: boolean,
activeLivestreams: ?LivestreamInfo,
doFetchActiveLivestreams: () => void,
};
function ChannelsFollowingPage(props: Props) {
const { subscribedChannels, tileLayout } = props;
const { subscribedChannels, tileLayout, activeLivestreams, doFetchActiveLivestreams } = props;
const hasSubsribedChannels = subscribedChannels.length > 0;
const { livestreamMap } = useGetLivestreams();
const channelIds = subscribedChannels.map((sub) => splitBySeparator(sub.uri)[1]);
React.useEffect(() => {
doFetchActiveLivestreams();
}, []);
return !hasSubsribedChannels ? (
<ChannelsFollowingDiscoverPage />
) : (
<Page noFooter fullWidthPage={tileLayout}>
<ClaimListDiscover
prefixUris={getLivestreamUris(activeLivestreams, channelIds)}
hideAdvancedFilter={SIMPLE_SITE}
streamType={SIMPLE_SITE ? CS.CONTENT_ALL : undefined}
tileLayout={tileLayout}
@@ -37,7 +45,7 @@ function ChannelsFollowingPage(props: Props) {
</span>
}
defaultOrderBy={CS.ORDER_BY_NEW}
channelIds={subscribedChannels.map((sub) => splitBySeparator(sub.uri)[1])}
channelIds={channelIds}
meta={
<Button
icon={ICONS.SEARCH}
@@ -46,8 +54,6 @@ function ChannelsFollowingPage(props: Props) {
navigate={`/$/${PAGES.CHANNELS_FOLLOWING_DISCOVER}`}
/>
}
liveLivestreamsFirst
livestreamMap={livestreamMap}
showNoSourceClaims={ENABLE_NO_SOURCE_CLAIMS}
hasSource
/>
+7 -3
View File
@@ -28,10 +28,14 @@ type ChannelsFollowingItem = {
function ChannelsFollowingDiscover(props: Props) {
const { followedTags, subscribedChannels, blockedChannels, homepageData } = props;
const { PRIMARY_CONTENT } = homepageData;
const { PRIMARY_CONTENT, LATEST } = homepageData;
let channelIds;
if (PRIMARY_CONTENT && CUSTOM_HOMEPAGE) {
channelIds = PRIMARY_CONTENT.channelIds;
if (CUSTOM_HOMEPAGE) {
if (LATEST) {
channelIds = LATEST.channelIds;
} else if (PRIMARY_CONTENT) {
channelIds = PRIMARY_CONTENT.channelIds;
}
}
let rowData: Array<ChannelsFollowingItem> = [];
const notChannels = subscribedChannels
+4
View File
@@ -1,6 +1,8 @@
import * as CS from 'constants/claim_search';
import { connect } from 'react-redux';
import { makeSelectClaimForUri, doResolveUri, SETTINGS } from 'lbry-redux';
import { doFetchActiveLivestreams } from 'redux/actions/livestream';
import { selectActiveLivestreams } from 'redux/selectors/livestream';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectFollowedTags } from 'redux/selectors/tags';
import { doToggleTagFollowDesktop } from 'redux/actions/tags';
@@ -18,10 +20,12 @@ const select = (state, props) => {
repostedClaim: repostedUri ? makeSelectClaimForUri(repostedUri)(state) : null,
isAuthenticated: selectUserVerifiedEmail(state),
tileLayout: makeSelectClientSetting(SETTINGS.TILE_LAYOUT)(state),
activeLivestreams: selectActiveLivestreams(state),
};
};
export default connect(select, {
doToggleTagFollowDesktop,
doResolveUri,
doFetchActiveLivestreams,
})(Tags);
+92 -40
View File
@@ -8,15 +8,17 @@ import Page from 'component/page';
import ClaimListDiscover from 'component/claimListDiscover';
import Button from 'component/button';
import useHover from 'effects/use-hover';
import { useIsMobile } from 'effects/use-screensize';
import { useIsMobile, useIsLargeScreen } from 'effects/use-screensize';
import analytics from 'analytics';
import HiddenNsfw from 'component/common/hidden-nsfw';
import Icon from 'component/common/icon';
import Ads from 'web/component/ads';
import LbcSymbol from 'component/common/lbc-symbol';
import I18nMessage from 'component/i18nMessage';
import useGetLivestreams from 'effects/use-get-livestreams';
import moment from 'moment';
import { getLivestreamUris } from 'util/livestream';
const DEFAULT_LIVESTREAM_TILE_LIMIT = 8;
type Props = {
location: { search: string },
@@ -28,6 +30,8 @@ type Props = {
isAuthenticated: boolean,
dynamicRouteProps: RowDataItem,
tileLayout: boolean,
activeLivestreams: ?LivestreamInfo,
doFetchActiveLivestreams: (orderBy?: Array<string>, pageSize?: number, forceFetch?: boolean) => void,
};
function DiscoverPage(props: Props) {
@@ -40,12 +44,14 @@ function DiscoverPage(props: Props) {
doResolveUri,
isAuthenticated,
tileLayout,
activeLivestreams,
doFetchActiveLivestreams,
dynamicRouteProps,
} = props;
const buttonRef = useRef();
const isHovering = useHover(buttonRef);
const isMobile = useIsMobile();
const { livestreamMap } = useGetLivestreams();
const isLargeScreen = useIsLargeScreen();
const urlParams = new URLSearchParams(search);
const claimType = urlParams.get('claim_type');
@@ -58,6 +64,8 @@ function DiscoverPage(props: Props) {
// Eventually allow more than one tag on this page
// Restricting to one to make follow/unfollow simpler
const tag = (tags && tags[0]) || null;
const channelIds =
(dynamicRouteProps && dynamicRouteProps.options && dynamicRouteProps.options.channelIds) || undefined;
const isFollowing = followedTags.map(({ name }) => name).includes(tag);
let label = isFollowing ? __('Following --[button label indicating a channel has been followed]--') : __('Follow');
@@ -65,6 +73,46 @@ function DiscoverPage(props: Props) {
label = __('Unfollow');
}
const initialLivestreamTileLimit = getPageSize(DEFAULT_LIVESTREAM_TILE_LIMIT);
const [showViewMoreLivestreams, setShowViewMoreLivestreams] = React.useState(!dynamicRouteProps);
const livestreamUris = getLivestreamUris(activeLivestreams, channelIds);
const useDualList = showViewMoreLivestreams && livestreamUris.length > initialLivestreamTileLimit;
function getElemMeta() {
return !dynamicRouteProps ? (
<a
className="help"
href="https://lbry.com/faq/trending"
title={__('Learn more about LBRY Credits on %DOMAIN%', { DOMAIN })}
>
<I18nMessage
tokens={{
lbc: <LbcSymbol />,
}}
>
Results boosted by %lbc%
</I18nMessage>
</a>
) : (
tag && !isMobile && (
<Button
ref={buttonRef}
button="alt"
icon={ICONS.SUBSCRIBE}
iconColor="red"
onClick={handleFollowClick}
requiresAuth={IS_WEB}
label={label}
/>
)
);
}
function getPageSize(originalSize) {
return isLargeScreen ? originalSize * (3 / 2) : originalSize;
}
React.useEffect(() => {
if (repostedUri && !repostedClaimIsResolved) {
doResolveUri(repostedUri);
@@ -106,16 +154,53 @@ function DiscoverPage(props: Props) {
);
}
React.useEffect(() => {
if (showViewMoreLivestreams) {
doFetchActiveLivestreams(CS.ORDER_BY_TRENDING_VALUE);
} else {
doFetchActiveLivestreams();
}
}, []);
return (
<Page noFooter fullWidthPage={tileLayout}>
{useDualList && (
<>
<ClaimListDiscover
uris={livestreamUris.slice(0, initialLivestreamTileLimit)}
headerLabel={headerLabel}
header={repostedUri ? <span /> : undefined}
tileLayout={repostedUri ? false : tileLayout}
hideAdvancedFilter
hideFilters
infiniteScroll={false}
showNoSourceClaims={ENABLE_NO_SOURCE_CLAIMS}
meta={getElemMeta()}
/>
<div className="livestream-list--view-more">
<Button
label={__('Show more livestreams')}
button="link"
iconRight={ICONS.ARROW_RIGHT}
className="claim-grid__title--secondary"
onClick={() => {
doFetchActiveLivestreams();
setShowViewMoreLivestreams(false);
}}
/>
</div>
</>
)}
<ClaimListDiscover
prefixUris={useDualList ? undefined : livestreamUris}
hideAdvancedFilter={SIMPLE_SITE}
hideFilters={SIMPLE_SITE ? !dynamicRouteProps : undefined}
header={repostedUri ? <span /> : undefined}
header={useDualList ? <span /> : repostedUri ? <span /> : undefined}
tileLayout={repostedUri ? false : tileLayout}
defaultOrderBy={SIMPLE_SITE ? (dynamicRouteProps ? undefined : CS.ORDER_BY_TRENDING) : undefined}
claimType={claimType ? [claimType] : undefined}
headerLabel={headerLabel}
headerLabel={!useDualList && headerLabel}
tags={tags}
hiddenNsfwMessage={<HiddenNsfw type="page" />}
repostedClaimId={repostedClaim ? repostedClaim.claim_id : null}
@@ -133,47 +218,14 @@ function DiscoverPage(props: Props) {
: undefined
}
feeAmount={SIMPLE_SITE ? !dynamicRouteProps && CS.FEE_AMOUNT_ANY : undefined}
channelIds={
(dynamicRouteProps && dynamicRouteProps.options && dynamicRouteProps.options.channelIds) || undefined
}
channelIds={channelIds}
limitClaimsPerChannel={
SIMPLE_SITE
? (dynamicRouteProps && dynamicRouteProps.options && dynamicRouteProps.options.limitClaimsPerChannel) ||
undefined
: 3
}
meta={
!dynamicRouteProps ? (
<a
className="help"
href="https://lbry.com/faq/trending"
title={__('Learn more about LBRY Credits on %DOMAIN%', { DOMAIN })}
>
<I18nMessage
tokens={{
lbc: <LbcSymbol />,
}}
>
Results boosted by %lbc%
</I18nMessage>
</a>
) : (
tag &&
!isMobile && (
<Button
ref={buttonRef}
button="alt"
icon={ICONS.SUBSCRIBE}
iconColor="red"
onClick={handleFollowClick}
requiresAuth={IS_WEB}
label={label}
/>
)
)
}
liveLivestreamsFirst
livestreamMap={livestreamMap}
meta={!useDualList && getElemMeta()}
hasSource
showNoSourceClaims={ENABLE_NO_SOURCE_CLAIMS}
/>
+6 -1
View File
@@ -1,4 +1,6 @@
import { connect } from 'react-redux';
import { doFetchActiveLivestreams } from 'redux/actions/livestream';
import { selectActiveLivestreams } from 'redux/selectors/livestream';
import { selectFollowedTags } from 'redux/selectors/tags';
import { selectUserVerifiedEmail } from 'redux/selectors/user';
import { selectSubscriptions } from 'redux/selectors/subscriptions';
@@ -12,8 +14,11 @@ const select = (state) => ({
authenticated: selectUserVerifiedEmail(state),
showNsfw: selectShowMatureContent(state),
homepageData: selectHomepageData(state),
activeLivestreams: selectActiveLivestreams(state),
});
const perform = {};
const perform = (dispatch) => ({
doFetchActiveLivestreams: () => dispatch(doFetchActiveLivestreams()),
});
export default connect(select, perform)(DiscoverPage);
+18 -5
View File
@@ -9,8 +9,8 @@ import ClaimTilesDiscover from 'component/claimTilesDiscover';
import ClaimPreviewTile from 'component/claimPreviewTile';
import Icon from 'component/common/icon';
import WaitUntilOnPage from 'component/common/wait-until-on-page';
import useGetLivestreams from 'effects/use-get-livestreams';
import { GetLinksData } from 'util/buildHomepage';
import { getLivestreamUris } from 'util/livestream';
// @if TARGET='web'
import Pixel from 'web/component/pixel';
@@ -23,14 +23,23 @@ type Props = {
subscribedChannels: Array<Subscription>,
showNsfw: boolean,
homepageData: any,
activeLivestreams: any,
doFetchActiveLivestreams: () => void,
};
function HomePage(props: Props) {
const { followedTags, subscribedChannels, authenticated, showNsfw, homepageData } = props;
const {
followedTags,
subscribedChannels,
authenticated,
showNsfw,
homepageData,
activeLivestreams,
doFetchActiveLivestreams,
} = props;
const showPersonalizedChannels = (authenticated || !IS_WEB) && subscribedChannels && subscribedChannels.length > 0;
const showPersonalizedTags = (authenticated || !IS_WEB) && followedTags && followedTags.length > 0;
const showIndividualTags = showPersonalizedTags && followedTags.length < 5;
const { livestreamMap } = useGetLivestreams();
const rowData: Array<RowDataItem> = GetLinksData(
homepageData,
@@ -52,13 +61,13 @@ function HomePage(props: Props) {
))}
</ul>
);
const claimTiles = (
<ClaimTilesDiscover
{...options}
liveLivestreamsFirst
livestreamMap={livestreamMap}
showNoSourceClaims={ENABLE_NO_SOURCE_CLAIMS}
hasSource
prefixUris={getLivestreamUris(activeLivestreams, options.channelIds)}
pinUrls={pinUrls}
/>
);
@@ -95,6 +104,10 @@ function HomePage(props: Props) {
);
}
React.useEffect(() => {
doFetchActiveLivestreams();
}, []);
return (
<Page fullWidthPage>
{!SIMPLE_SITE && (authenticated || !IS_WEB) && !subscribedChannels.length && (
+27 -18
View File
@@ -6,6 +6,7 @@ import classnames from 'classnames';
import moment from 'moment';
import humanizeDuration from 'humanize-duration';
import BlockList from 'component/blockList';
import BlockListShared from 'component/blockListShared';
import ClaimPreview from 'component/claimPreview';
import Page from 'component/page';
import Spinner from 'component/spinner';
@@ -17,6 +18,7 @@ import ChannelMuteButton from 'component/channelMuteButton';
const VIEW = {
BLOCKED: 'blocked',
ADMIN: 'admin',
SHARED: 'shared',
MODERATOR: 'moderator',
MUTED: 'muted',
};
@@ -221,15 +223,17 @@ function ListBlocked(props: Props) {
function getRefreshElem() {
return (
<Button
icon={ICONS.REFRESH}
button="alt"
label={__('Refresh')}
onClick={() => {
fetchModBlockedList();
fetchModAmIList();
}}
/>
myChannelClaims && (
<Button
icon={ICONS.REFRESH}
button="alt"
label={__('Refresh')}
onClick={() => {
fetchModBlockedList();
fetchModAmIList();
}}
/>
)
);
}
@@ -264,19 +268,24 @@ function ListBlocked(props: Props) {
{isAdmin && getViewElem(VIEW.ADMIN, 'Global', ICONS.BLOCK)}
{isModerator && getViewElem(VIEW.MODERATOR, 'Moderator', ICONS.BLOCK)}
{getViewElem(VIEW.MUTED, 'Muted', ICONS.MUTE)}
{getViewElem(VIEW.SHARED, 'Shared Blocklist', ICONS.SHARE)}
</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}
/>
{viewMode === VIEW.SHARED && <BlockListShared />}
{viewMode !== VIEW.SHARED && (
<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}
/>
)}
</>
)}
</Page>
+3 -2
View File
@@ -184,14 +184,15 @@ export default function LivestreamSetupPage(props: Props) {
name="stream-server"
label={__('Stream server')}
copyable={LIVESTREAM_RTMP_URL}
snackMessage={__('Copied')}
snackMessage={__('Copied stream server URL.')}
/>
<CopyableText
primaryButton
enableInputMask
name="livestream-key"
label={__('Stream key')}
copyable={streamKey}
snackMessage={__('Copied')}
snackMessage={__('Copied stream key.')}
/>
</>
}
+17
View File
@@ -0,0 +1,17 @@
import { connect } from 'react-redux';
import { doSblUpdate } from 'redux/actions/comments';
import { doToast } from 'redux/actions/notifications';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import SharedBlocklistEdit from './view';
const select = (state) => ({
activeChannelClaim: selectActiveChannelClaim(state),
});
const perform = (dispatch) => ({
doSblUpdate: (channelClaim, params, onComplete) => dispatch(doSblUpdate(channelClaim, params, onComplete)),
doToast: (options) => dispatch(doToast(options)),
});
export default connect(select, perform)(SharedBlocklistEdit);
+206
View File
@@ -0,0 +1,206 @@
// @flow
import React from 'react';
import { useHistory } from 'react-router';
import Button from 'component/button';
import ChannelSelector from 'component/channelSelector';
import Card from 'component/common/card';
import { Form, FormField } from 'component/common/form';
import LbcSymbol from 'component/common/lbc-symbol';
import I18nMessage from 'component/i18nMessage';
import Page from 'component/page';
import Spinner from 'component/spinner';
import usePersistedState from 'effects/use-persisted-state';
const DEFAULT_STRIKE_HOURS = 4;
type Props = {
activeChannelClaim: ?ChannelClaim,
doSblUpdate: (channelClaim: ChannelClaim, params: SblUpdate, onComplete: (error: string) => void) => void,
doToast: ({ message: string }) => void,
};
export default function SharedBlocklistEdit(props: Props) {
const { activeChannelClaim, doSblUpdate, doToast } = props;
const { goBack, location } = useHistory();
const sbl = location.state;
const [name, setName] = React.useState('');
const [category, setCategory] = React.useState('');
const [description, setDescription] = React.useState('');
const [strike1, setStrike1] = React.useState(DEFAULT_STRIKE_HOURS);
const [strike2, setStrike2] = React.useState(DEFAULT_STRIKE_HOURS);
const [strike3, setStrike3] = React.useState(DEFAULT_STRIKE_HOURS);
const [appealAmount, setAppealAmount] = React.useState(0);
const [memberInviteEnabled, setMemberInviteEnabled] = usePersistedState('sblEdit:memberInviteEnabled', true);
const [inviteExpiration, setInviteExpiration] = usePersistedState('sblEdit:inviteExpiration', 0);
const [submitting, setSubmitting] = React.useState(false);
const [error, setError] = React.useState('');
const submitDisabled = !name || !description;
function submitForm() {
const params: SblUpdate = {
name,
category,
description,
strike_one: strike1,
strike_two: strike2,
strike_three: strike3,
curse_jar_amount: appealAmount,
member_invite_enabled: memberInviteEnabled,
invite_expiration: inviteExpiration,
};
if (activeChannelClaim) {
setError('');
setSubmitting(true);
doSblUpdate(activeChannelClaim, params, handleUpdateCompleted);
}
}
function handleUpdateCompleted(error: string) {
setSubmitting(false);
if (error) {
setError(error);
} else {
doToast({ message: __('Shared blocklist updated.') });
goBack();
}
}
// Reload data from existing sbl
React.useEffect(() => {
if (sbl) {
setName(sbl.name);
setCategory(sbl.category);
setDescription(sbl.description);
setStrike1(sbl.strike_one);
setStrike2(sbl.strike_two);
setStrike3(sbl.strike_three);
setAppealAmount(sbl.curse_jar_amount);
setMemberInviteEnabled(sbl.member_invite_enabled);
setInviteExpiration(sbl.invite_expiration);
}
}, []); // eslint-disable-line react-hooks/exhaustive-deps
return (
<Page
noSideNavigation
className="main--half-width"
backout={{
backoutLabel: __('Cancel'),
title: sbl ? __('Edit shared blocklist') : __('Create shared blocklist'),
}}
>
<Form onSubmit={submitForm}>
<Card
className={submitting ? 'sbl-edit card--disabled' : 'sbl-edit '}
body={
<>
<ChannelSelector hideAnon />
<FormField
label={__('Blocklist name')}
type="text"
name="name"
value={name}
onChange={(e) => setName(e.target.value)}
/>
<FormField
label={__('Category')}
type="text"
name="category"
value={category}
onChange={(e) => setCategory(e.target.value)}
/>
<FormField
label={__('Description')}
type="textarea"
name="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
textAreaMaxLength={1000}
noEmojis
/>
<fieldset-section>
<label>{__('Timeout (hours)')}</label>
<div className="section section__flex">
<FormField
label={__('Strike 1')}
placeholder={__('Strike 1 timeout in hours')}
type="number"
name="strike_one"
min={0}
step={1}
value={strike1}
onChange={(e) => setStrike1(parseInt(e.target.value))}
/>
<FormField
label={__('Strike 2')}
placeholder={__('Strike 2 timeout in hours')}
type="number"
name="strike_two"
min={0}
step={1}
value={strike2}
onChange={(e) => setStrike2(parseInt(e.target.value))}
/>
<FormField
label={__('Strike 3')}
placeholder={__('Strike 3 timeout in hours')}
type="number"
name="strike_three"
min={0}
step={1}
value={strike3}
onChange={(e) => setStrike3(parseInt(e.target.value))}
/>
</div>
</fieldset-section>
<FormField
label={<I18nMessage tokens={{ lbc: <LbcSymbol /> }}>Auto-appeal minimum %lbc%</I18nMessage>}
name="curse_jar_amount"
className="form-field--price-amount"
type="number"
placeholder="1"
value={appealAmount}
onChange={(e) => setAppealAmount(parseFloat(e.target.value))}
/>
<FormField
label={__('Invite expiration (hours)')}
placeholder={__('Set to 0 for no expiration.')}
type="number"
name="invite_expiration"
min={0}
step={1}
value={inviteExpiration}
onChange={(e) => setInviteExpiration(parseInt(e.target.value))}
/>
<FormField
label={__('Allow members to invite others')}
type="checkbox"
name="member_invite_enabled"
checked={memberInviteEnabled}
onChange={() => setMemberInviteEnabled(!memberInviteEnabled)}
/>
</>
}
actions={
<>
<div className="section__actions">
<Button
label={submitting ? <Spinner type="small" /> : __('Done')}
button="primary"
type="submit"
disabled={submitDisabled}
/>
<Button button="link" label={__('Cancel')} onClick={() => goBack()} />
</div>
{error && <div className="help--error">{__(error)}</div>}
</>
}
/>
</Form>
</Page>
);
}
+17
View File
@@ -0,0 +1,17 @@
import { connect } from 'react-redux';
import { doSblInvite } from 'redux/actions/comments';
import { doToast } from 'redux/actions/notifications';
import { selectActiveChannelClaim } from 'redux/selectors/app';
import SharedBlocklistInvite from './view';
const select = (state) => ({
activeChannelClaim: selectActiveChannelClaim(state),
});
const perform = (dispatch) => ({
doSblInvite: (channelClaim, paramList, onComplete) => dispatch(doSblInvite(channelClaim, paramList, onComplete)),
doToast: (options) => dispatch(doToast(options)),
});
export default connect(select, perform)(SharedBlocklistInvite);
+125
View File
@@ -0,0 +1,125 @@
// @flow
import React from 'react';
import { useHistory } from 'react-router';
import Button from 'component/button';
import Card from 'component/common/card';
import { Form, FormField } from 'component/common/form';
import Page from 'component/page';
import SearchChannelField from 'component/searchChannelField';
import Spinner from 'component/spinner';
const PARAM_BLOCKLIST_ID = 'id';
type Props = {
activeChannelClaim: ?ChannelClaim,
doSblInvite: (channelClaim: ChannelClaim, paramList: Array<SblInvite>, onComplete: (err: string) => void) => void,
doToast: ({ message: string }) => void,
};
export default function SharedBlocklistInvite(props: Props) {
const { activeChannelClaim, doSblInvite, doToast } = props;
const { goBack, location } = useHistory();
const urlParams = new URLSearchParams(location.search);
const id = urlParams.get(PARAM_BLOCKLIST_ID);
const [invitees, setInvitees] = React.useState([]);
const [message, setMessage] = React.useState('');
const [submitting, setSubmitting] = React.useState(false);
const [error, setError] = React.useState('');
const isInputValid = activeChannelClaim && invitees && invitees.length !== 0;
function submitForm() {
if (activeChannelClaim && isInputValid) {
const paramList = invitees.map((invitee) => {
const inviteeInfo = invitee.split('#');
const params: SblInvite = {
blocked_list_id: id ? parseInt(id) : undefined,
invitee_channel_name: inviteeInfo[0],
invitee_channel_id: inviteeInfo[1],
message,
};
return params;
});
setError('');
setSubmitting(true);
doSblInvite(activeChannelClaim, paramList, handleInviteCompleted);
}
}
function handleInviteCompleted(error: string) {
setSubmitting(false);
if (error) {
setError(error);
} else {
const multipleInvitees = invitees && invitees.length > 1;
doToast({ message: multipleInvitees ? __('Invites sent.') : __('Invite sent.') });
goBack();
}
}
function handleInviteeAdded(channelUri: string) {
setInvitees([...invitees, channelUri]);
}
function handleInviteeRemoved(channelUri: string) {
setInvitees(invitees.filter((x) => x !== channelUri));
}
return (
<Page
noSideNavigation
className="main--half-width"
backout={{
backoutLabel: __('Cancel'),
title: __('Invite'),
}}
>
<Form onSubmit={submitForm}>
<Card
title={__('Invite others to use and contribute to this blocklist.')}
subtitle={' '}
className={submitting ? 'card--disabled' : ''}
body={
<>
<SearchChannelField
label={__('Invitees')}
labelAddNew={__('Add invitee')}
labelFoundAction={__('Add')}
values={invitees}
onAdd={handleInviteeAdded}
onRemove={handleInviteeRemoved}
/>
<FormField
label={__('Message')}
type="textarea"
name="message"
value={message}
onChange={(e) => setMessage(e.target.value)}
textAreaMaxLength={1000}
noEmojis
/>
</>
}
actions={
<>
<div className="section__actions">
<Button
label={submitting ? <Spinner type="small" /> : __('Send')}
disabled={!isInputValid}
button="primary"
type="submit"
/>
<Button label={__('Cancel')} button="link" onClick={() => goBack()} />
</div>
{error && <div className="help--error">{__(error)}</div>}
</>
}
/>
</Form>
</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 });
+272 -14
View File
@@ -21,6 +21,7 @@ import { doAlertWaitingForSync } from 'redux/actions/app';
const isDev = process.env.NODE_ENV !== 'production';
const FETCH_API_FAILED_TO_FETCH = 'Failed to fetch';
const PROMISE_FULFILLED = 'fulfilled';
declare type CommentronErrorMap = {
[string]: {
@@ -48,6 +49,8 @@ const ERR_MAP: CommentronErrorMap = {
BLOCKED_BY_CREATOR: {
commentron: 'channel is blocked by publisher',
replacement: 'Unable to comment. This channel has blocked you.',
linkText: 'Appeal',
linkTarget: `/${PAGES.APPEAL_LIST_OFFENCES}`,
},
BLOCKED_BY_ADMIN: {
commentron: 'channel is not allowed to post comments',
@@ -61,6 +64,12 @@ const ERR_MAP: CommentronErrorMap = {
commentron: 'duplicate comment!',
replacement: 'Please do not spam.',
},
TIMEOUT_BANNED: {
commentron: /^publisher (.*) has given you a temporary ban with (.*) remaining.$/,
replacement: '%1% has given you a temporary ban with %2% remaining.', // TODO: The duration is not localizable.
linkText: 'Appeal',
linkTarget: `/${PAGES.APPEAL_LIST_OFFENCES}`,
},
};
function devToast(dispatch, msg) {
@@ -202,6 +211,10 @@ export function doCommentList(
export function doCommentById(commentId: string, toastIfNotFound: boolean = true) {
return (dispatch: Dispatch, getState: GetState) => {
dispatch({
type: ACTIONS.COMMENT_BY_ID_STARTED,
});
return Comments.comment_by_id({ comment_id: commentId, with_ancestors: true })
.then((result: CommentByIdResponse) => {
const { item, items, ancestors } = result;
@@ -1054,6 +1067,10 @@ export function doFetchModBlockedList() {
return async (dispatch: Dispatch, getState: GetState) => {
const state = getState();
const myChannels = selectMyChannelClaims(state);
if (!myChannels) {
dispatch({ type: ACTIONS.COMMENT_MODERATION_BLOCK_LIST_FAILED });
return;
}
dispatch({
type: ACTIONS.COMMENT_MODERATION_BLOCK_LIST_STARTED,
@@ -1376,10 +1393,12 @@ export function doFetchCommentModAmIList(channelClaim: ChannelClaim) {
return async (dispatch: Dispatch, getState: GetState) => {
const state = getState();
const myChannels = selectMyChannelClaims(state);
if (!myChannels) {
dispatch({ type: ACTIONS.COMMENT_MODERATION_AM_I_LIST_FAILED });
return;
}
dispatch({
type: ACTIONS.COMMENT_MODERATION_AM_I_LIST_STARTED,
});
dispatch({ type: ACTIONS.COMMENT_MODERATION_AM_I_LIST_STARTED });
let channelSignatures = [];
@@ -1399,13 +1418,13 @@ export function doFetchCommentModAmIList(channelClaim: ChannelClaim) {
})
)
)
.then((res) => {
.then((results) => {
const delegatorsById = {};
channelSignatures.forEach((chanSig, index) => {
if (chanSig && res[index]) {
const value = res[index].value;
delegatorsById[chanSig.claim_id] = {
results.forEach((result, index) => {
if (result.status === PROMISE_FULFILLED) {
const value = result.value;
delegatorsById[value.channel_id] = {
global: value ? value.type === 'Global' : false,
delegators: value && value.authorized_channels ? value.authorized_channels : {},
};
@@ -1418,15 +1437,12 @@ export function doFetchCommentModAmIList(channelClaim: ChannelClaim) {
});
})
.catch((err) => {
dispatch({
type: ACTIONS.COMMENT_MODERATION_AM_I_LIST_FAILED,
});
devToast(dispatch, `AmI: ${err}`);
dispatch({ type: ACTIONS.COMMENT_MODERATION_AM_I_LIST_FAILED });
});
})
.catch(() => {
dispatch({
type: ACTIONS.COMMENT_MODERATION_AM_I_LIST_FAILED,
});
dispatch({ type: ACTIONS.COMMENT_MODERATION_AM_I_LIST_FAILED });
});
};
}
@@ -1616,3 +1632,245 @@ export const doFetchBlockedWords = () => {
});
};
};
export const doSblUpdate = (channelClaim: ChannelClaim, params: SblUpdate, onComplete: (error: string) => void) => {
return async (dispatch: Dispatch) => {
const channelSignature = await channelSignName(channelClaim.claim_id, channelClaim.name);
if (!channelSignature) {
devToast(dispatch, 'doSblUpdate: failed to sign channel name');
return;
}
return Comments.sbl_update({
channel_name: channelClaim.name,
channel_id: channelClaim.claim_id,
signature: channelSignature.signature,
signing_ts: channelSignature.signing_ts,
...params,
})
.then(() => {
if (onComplete) {
onComplete('');
}
})
.catch((err) => {
dispatch(doToast({ message: err.message, isError: true }));
if (onComplete) {
onComplete(err.message);
}
});
};
};
export const doSblDelete = (channelClaim: ChannelClaim) => {
return async (dispatch: Dispatch) => {
const channelSignature = await channelSignName(channelClaim.claim_id, channelClaim.name);
if (!channelSignature) {
devToast(dispatch, 'doSblDelete: failed to sign channel name');
return;
}
return Comments.sbl_update({
channel_name: channelClaim.name,
channel_id: channelClaim.claim_id,
signature: channelSignature.signature,
signing_ts: channelSignature.signing_ts,
remove: true,
})
.then((resp) => {
dispatch({
type: ACTIONS.COMMENT_SBL_DELETED,
});
dispatch(doToast({ message: __('Shared blocklist deleted.') }));
})
.catch((err) => {
dispatch(doToast({ message: err.message, isError: true }));
});
};
};
export const doSblGet = (channelClaim: ?ChannelClaim, params: SblGet) => {
return async (dispatch: Dispatch, getState: GetState) => {
let channelSignature;
if (channelClaim) {
channelSignature = await channelSignName(channelClaim.claim_id, channelClaim.name);
if (!channelSignature) {
devToast(dispatch, 'doSblGet: failed to sign channel name');
return;
}
}
dispatch({
type: ACTIONS.COMMENT_SBL_FETCH_STARTED,
});
const authParams =
channelClaim && channelSignature
? {
channel_name: channelClaim.name,
channel_id: channelClaim.claim_id,
signature: channelSignature.signature,
signing_ts: channelSignature.signing_ts,
}
: {};
return Comments.sbl_get({ ...authParams, ...params })
.then((resp) => {
dispatch({
type: ACTIONS.COMMENT_SBL_FETCH_COMPLETED,
data: resp,
});
})
.catch((err) => {
if (err.message !== 'blocked list not found') {
dispatch(doToast({ message: err.message, isError: true }));
}
dispatch({
type: ACTIONS.COMMENT_SBL_FETCH_FAILED,
});
});
};
};
export const doSblInvite = (
channelClaim: ChannelClaim,
paramList: Array<SblInvite>,
onComplete: (error: string) => void
) => {
return async (dispatch: Dispatch) => {
const channelSignature = await channelSignName(channelClaim.claim_id, channelClaim.name);
if (!channelSignature) {
devToast(dispatch, 'doSblInvite: failed to sign channel name');
return;
}
// $FlowFixMe
return Promise.allSettled(
paramList.map((params) => {
return Comments.sbl_invite({
channel_name: channelClaim.name,
channel_id: channelClaim.claim_id,
signature: channelSignature.signature,
signing_ts: channelSignature.signing_ts,
...params,
});
})
)
.then((results) => {
const errors: Array<string> = [];
results.forEach((result) => {
if (result.status === 'rejected') {
errors.push(result.reason.message);
}
});
if (onComplete) {
onComplete(errors.join(' • '));
}
})
.catch((err) => {
dispatch(doToast({ message: err.message, isError: true }));
if (onComplete) {
onComplete(err.message);
}
});
};
};
export const doSblListInvites = (channelClaim: ChannelClaim) => {
return async (dispatch: Dispatch) => {
const channelSignature = await channelSignName(channelClaim.claim_id, channelClaim.name);
if (!channelSignature) {
devToast(dispatch, 'SBL Invite: failed to sign channel name');
return;
}
dispatch({
type: ACTIONS.COMMENT_SBL_FETCH_INVITES_STARTED,
});
return Comments.sbl_list_invites({
channel_name: channelClaim.name,
channel_id: channelClaim.claim_id,
signature: channelSignature.signature,
signing_ts: channelSignature.signing_ts,
})
.then((resp) => {
dispatch({
type: ACTIONS.COMMENT_SBL_FETCH_INVITES_COMPLETED,
data: resp,
});
})
.catch((err) => {
dispatch(doToast({ message: err.message, isError: true }));
dispatch({
type: ACTIONS.COMMENT_SBL_FETCH_INVITES_FAILED,
});
});
};
};
export const doSblAccept = (
channelClaim: ChannelClaim,
params: SblInviteAccept,
onComplete: (error: string) => void
) => {
return async (dispatch: Dispatch) => {
const channelSignature = await channelSignName(channelClaim.claim_id, channelClaim.name);
if (!channelSignature) {
devToast(dispatch, 'doSblAccept: failed to sign channel name');
return;
}
return Comments.sbl_accept({
channel_name: channelClaim.name,
channel_id: channelClaim.claim_id,
signature: channelSignature.signature,
signing_ts: channelSignature.signing_ts,
...params,
})
.then((resp) => {
if (onComplete) {
onComplete('');
}
})
.catch((err) => {
dispatch(doToast({ message: err.message, isError: true }));
if (onComplete) {
onComplete(err.message);
}
});
};
};
export const doSblRescind = (channelClaim: ChannelClaim, params: SblRescind, onComplete: (error: string) => void) => {
return async (dispatch: Dispatch) => {
const channelSignature = await channelSignName(channelClaim.claim_id, channelClaim.name);
if (!channelSignature) {
devToast(dispatch, 'doSblRescind: failed to sign channel name');
return;
}
return Comments.sbl_rescind({
channel_name: channelClaim.name,
channel_id: channelClaim.claim_id,
signature: channelSignature.signature,
signing_ts: channelSignature.signing_ts,
...params,
})
.then((resp) => {
if (onComplete) {
onComplete('');
}
dispatch(
doToast({ message: __('Membership for %member% rescinded.', { member: params.invited_channel_name }) })
);
})
.catch((err) => {
dispatch(doToast({ message: err.message, isError: true }));
if (onComplete) {
onComplete(err.message);
}
});
};
};
+88
View File
@@ -1,6 +1,7 @@
// @flow
import * as ACTIONS from 'constants/action_types';
import { doClaimSearch } from 'lbry-redux';
import { LIVESTREAM_LIVE_API } from 'constants/livestream';
export const doFetchNoSourceClaims = (channelId: string) => async (dispatch: Dispatch, getState: GetState) => {
dispatch({
@@ -31,3 +32,90 @@ export const doFetchNoSourceClaims = (channelId: string) => async (dispatch: Dis
});
}
};
const FETCH_ACTIVE_LIVESTREAMS_MIN_INTERVAL_MS = 5 * 60 * 1000;
export const doFetchActiveLivestreams = (
orderBy: Array<string> = ['release_time'],
pageSize: number = 50,
forceFetch: boolean = false
) => {
return async (dispatch: Dispatch, getState: GetState) => {
const state = getState();
const now = Date.now();
const timeDelta = now - state.livestream.activeLivestreamsLastFetchedDate;
const prevOptions = state.livestream.activeLivestreamsLastFetchedOptions;
const nextOptions = { page_size: pageSize, order_by: orderBy };
const sameOptions = JSON.stringify(prevOptions) === JSON.stringify(nextOptions);
if (!forceFetch && sameOptions && timeDelta < FETCH_ACTIVE_LIVESTREAMS_MIN_INTERVAL_MS) {
dispatch({ type: ACTIONS.FETCH_ACTIVE_LIVESTREAMS_SKIPPED });
return;
}
dispatch({ type: ACTIONS.FETCH_ACTIVE_LIVESTREAMS_STARTED });
fetch(LIVESTREAM_LIVE_API)
.then((res) => res.json())
.then((res) => {
if (!res.data) {
dispatch({ type: ACTIONS.FETCH_ACTIVE_LIVESTREAMS_FAILED });
return;
}
const activeLivestreams: LivestreamInfo = res.data.reduce((acc, curr) => {
acc[curr.claimId] = {
live: curr.live,
viewCount: curr.viewCount,
creatorId: curr.claimId,
};
return acc;
}, {});
dispatch(
// ** Creators can have multiple livestream claims (each with unique
// chat), and all of them will play the same stream when creator goes
// live. The UI usually just wants to report the latest claim, so we
// query that store it in `latestClaimUri`.
doClaimSearch({
page_size: nextOptions.page_size,
has_no_source: true,
channel_ids: Object.keys(activeLivestreams),
claim_type: ['stream'],
order_by: nextOptions.order_by, // **
limit_claims_per_channel: 1, // **
no_totals: true,
})
)
.then((resolveInfo) => {
Object.values(resolveInfo).forEach((x) => {
// $FlowFixMe
const channelId = x.stream.signing_channel.claim_id;
activeLivestreams[channelId] = {
...activeLivestreams[channelId],
// $FlowFixMe
latestClaimId: x.stream.claim_id,
// $FlowFixMe
latestClaimUri: x.stream.canonical_url,
};
});
dispatch({
type: ACTIONS.FETCH_ACTIVE_LIVESTREAMS_COMPLETED,
data: {
activeLivestreams,
activeLivestreamsLastFetchedDate: now,
activeLivestreamsLastFetchedOptions: nextOptions,
},
});
})
.catch(() => {
dispatch({ type: ACTIONS.FETCH_ACTIVE_LIVESTREAMS_FAILED });
});
})
.catch((err) => {
dispatch({ type: ACTIONS.FETCH_ACTIVE_LIVESTREAMS_FAILED });
});
};
};
+16 -13
View File
@@ -1,11 +1,19 @@
// @flow
import * as ACTIONS from 'constants/action_types';
import { SEARCH_OPTIONS } from 'constants/search';
import { buildURI, doResolveUris, batchActions, isURIValid, makeSelectClaimForUri } from 'lbry-redux';
import { selectShowMatureContent } from 'redux/selectors/settings';
import {
buildURI,
doResolveUris,
batchActions,
isURIValid,
makeSelectClaimForUri,
makeSelectClaimIsNsfw,
} from 'lbry-redux';
import { makeSelectSearchUrisForQuery, selectSearchValue } from 'redux/selectors/search';
import handleFetchResponse from 'util/handle-fetch';
import { getSearchQueryString } from 'util/query-params';
import { SIMPLE_SITE, SEARCH_SERVER_API } from 'config';
import { getRecommendationSearchOptions } from 'util/search';
import { SEARCH_SERVER_API } from 'config';
type Dispatch = (action: any) => any;
type GetState = () => { search: SearchState };
@@ -125,21 +133,16 @@ export const doUpdateSearchOptions = (newOptions: SearchOptions, additionalOptio
}
};
export const doFetchRecommendedContent = (uri: string, mature: boolean) => (dispatch: Dispatch, getState: GetState) => {
export const doFetchRecommendedContent = (uri: string) => (dispatch: Dispatch, getState: GetState) => {
const state = getState();
const claim = makeSelectClaimForUri(uri)(state);
const matureEnabled = selectShowMatureContent(state);
const claimIsMature = makeSelectClaimIsNsfw(uri)(state);
if (claim && claim.value && claim.claim_id) {
const options: SearchOptions = { size: 20, related_to: claim.claim_id, isBackgroundSearch: true };
if (!mature) {
options['nsfw'] = false;
}
if (SIMPLE_SITE) {
options[SEARCH_OPTIONS.CLAIM_TYPE] = SEARCH_OPTIONS.INCLUDE_FILES;
options[SEARCH_OPTIONS.MEDIA_VIDEO] = true;
}
const options: SearchOptions = getRecommendationSearchOptions(matureEnabled, claimIsMature, claim.claim_id);
const { title } = claim.value;
if (title && options) {
dispatch(doSearch(title, options));
}
+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());
+48 -3
View File
@@ -21,6 +21,7 @@ const defaultState: CommentsState = {
superChatsByUri: {},
pinnedCommentsById: {}, // ClaimId -> array of pinned comment IDs
isLoading: false,
isLoadingById: false,
isLoadingByParentId: {},
isCommenting: false,
myComments: undefined,
@@ -47,6 +48,10 @@ const defaultState: CommentsState = {
settingsByChannelId: {}, // ChannelId -> PerChannelSettings
fetchingSettings: false,
fetchingBlockedWords: false,
sblMine: undefined,
sblInvited: [],
fetchingSblMine: false,
fetchingSblInvited: false,
};
function pushToArrayInObject(obj, key, valueToPush) {
@@ -335,6 +340,8 @@ export default handleActions(
};
},
[ACTIONS.COMMENT_BY_ID_STARTED]: (state) => ({ ...state, isLoadingById: true }),
[ACTIONS.COMMENT_BY_ID_COMPLETED]: (state: CommentsState, action: any) => {
const { comment, ancestors } = action.data;
const claimId = comment.claim_id;
@@ -349,9 +356,7 @@ export default handleActions(
const linkedCommentAncestors = Object.assign({}, state.linkedCommentAncestors);
const updateStore = (comment, commentById, byId, repliesByParentId, topLevelCommentsById) => {
// 'comment.ByID' doesn't populate 'replies'. We should have at least 1
// at the moment, and the correct value will populated by 'comment.List'.
commentById[comment.comment_id] = { ...comment, replies: 1 };
commentById[comment.comment_id] = comment;
byId[claimId] ? byId[claimId].unshift(comment.comment_id) : (byId[claimId] = [comment.comment_id]);
const parentId = comment.parent_id;
@@ -377,6 +382,7 @@ export default handleActions(
return {
...state,
isLoadingById: false,
topLevelCommentsById,
topLevelTotalCommentsById,
topLevelTotalPagesById,
@@ -1070,6 +1076,45 @@ export default handleActions(
fetchingBlockedWords: false,
};
},
[ACTIONS.COMMENT_SBL_FETCH_STARTED]: (state: CommentsState) => ({
...state,
fetchingSblMine: true,
}),
[ACTIONS.COMMENT_SBL_FETCH_FAILED]: (state: CommentsState) => ({
...state,
sblMine: null,
fetchingSblMine: false,
}),
[ACTIONS.COMMENT_SBL_FETCH_COMPLETED]: (state: CommentsState, action: any) => {
return {
...state,
sblMine: action.data,
fetchingSblMine: false,
};
},
[ACTIONS.COMMENT_SBL_FETCH_INVITES_STARTED]: (state: CommentsState) => ({
...state,
fetchingSblInvited: true,
}),
[ACTIONS.COMMENT_SBL_FETCH_INVITES_FAILED]: (state: CommentsState) => ({
...state,
sblInvited: null,
fetchingSblInvited: false,
}),
[ACTIONS.COMMENT_SBL_FETCH_INVITES_COMPLETED]: (state: CommentsState, action: any) => {
return {
...state,
sblInvited: action.data.invitations,
fetchingSblInvited: false,
};
},
[ACTIONS.COMMENT_SBL_DELETED]: (state: CommentsState) => ({
...state,
sblMine: null,
}),
},
defaultState
);
+20
View File
@@ -5,6 +5,10 @@ import { handleActions } from 'util/redux-utils';
const defaultState: LivestreamState = {
fetchingById: {},
viewersById: {},
fetchingActiveLivestreams: false,
activeLivestreams: null,
activeLivestreamsLastFetchedDate: 0,
activeLivestreamsLastFetchedOptions: {},
};
export default handleActions(
@@ -36,6 +40,22 @@ export default handleActions(
newViewersById[claimId] = connected;
return { ...state, viewersById: newViewersById };
},
[ACTIONS.FETCH_ACTIVE_LIVESTREAMS_STARTED]: (state: LivestreamState) => {
return { ...state, fetchingActiveLivestreams: true };
},
[ACTIONS.FETCH_ACTIVE_LIVESTREAMS_FAILED]: (state: LivestreamState) => {
return { ...state, fetchingActiveLivestreams: false };
},
[ACTIONS.FETCH_ACTIVE_LIVESTREAMS_COMPLETED]: (state: LivestreamState, action: any) => {
const { activeLivestreams, activeLivestreamsLastFetchedDate, activeLivestreamsLastFetchedOptions } = action.data;
return {
...state,
fetchingActiveLivestreams: false,
activeLivestreams,
activeLivestreamsLastFetchedDate,
activeLivestreamsLastFetchedOptions,
};
},
},
defaultState
);
+1 -1
View File
@@ -70,7 +70,6 @@ const defaultState = {
// Content
[SETTINGS.SHOW_MATURE]: false,
[SETTINGS.AUTOPLAY_MEDIA]: true,
[SETTINGS.AUTOPLAY_NEXT]: [SETTINGS.AUTOPLAY_MEDIA],
[SETTINGS.FLOATING_PLAYER]: true,
[SETTINGS.AUTO_DOWNLOAD]: true,
[SETTINGS.HIDE_REPOSTS]: SIMPLE_SITE,
@@ -80,6 +79,7 @@ const defaultState = {
[SETTINGS.TO_TRAY_WHEN_CLOSED]: true,
},
};
defaultState.clientSettings[SETTINGS.AUTOPLAY_NEXT] = defaultState.clientSettings[SETTINGS.AUTOPLAY_MEDIA];
reducers[ACTIONS.REHYDRATE] = (state, action) => {
const { clientSettings } = state;
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff. Show more