Compare commits

..
156 changed files with 2790 additions and 7879 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2017-2019 LBRY Inc Copyright (c) 2017-2018 LBRY Inc
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+463 -475
View File
File diff suppressed because it is too large. Load diff
+8 -11
View File
@@ -12,31 +12,29 @@
"base-64": "^0.1.0", "base-64": "^0.1.0",
"@expo/vector-icons": "^8.1.0", "@expo/vector-icons": "^8.1.0",
"gfycat-style-urls": "^1.0.3", "gfycat-style-urls": "^1.0.3",
"lbry-redux": "lbryio/lbry-redux#9b11cfed62af7f0f8eb6fa3c88a1f8d2cce46afc", "lbry-redux": "lbryio/lbry-redux#67a654f60630710cae72419448a73a18d076d18a",
"lbryinc": "lbryio/lbryinc#9ffb883cc11e36d55a729c65b70c405a4a56d35e", "lbryinc": "lbryio/lbryinc",
"lodash": ">=4.17.11", "lodash": ">=4.17.11",
"merge": ">=1.2.1", "merge": ">=1.2.1",
"moment": "^2.22.1", "moment": "^2.22.1",
"react": "16.8.6", "react": "16.8.6",
"react-native": "0.59.10", "react-native": "0.59.10",
"@react-native-community/async-storage": "^1.5.1", "@react-native-community/async-storage": "^1.5.1",
"react-native-camera": "^2.11.1", "react-native-camera": "^2.11.0",
"react-native-country-picker-modal": "^0.6.2", "react-native-country-picker-modal": "^0.6.2",
"react-native-document-picker": "^2.3.0",
"react-native-exception-handler": "2.9.0", "react-native-exception-handler": "2.9.0",
"react-native-fast-image": "^6.1.1", "react-native-fast-image": "^5.0.3",
"react-native-fs": "^2.13.3", "react-native-fs": "^2.13.3",
"react-native-gesture-handler": "1.3.0", "react-native-gesture-handler": "^1.1.0",
"react-native-image-zoom-viewer": "^2.2.5", "react-native-image-zoom-viewer": "^2.2.5",
"react-native-password-strength-meter": "^0.0.2", "react-native-password-strength-meter": "^0.0.2",
"react-native-phone-input": "lbryio/react-native-phone-input", "react-native-phone-input": "lbryio/react-native-phone-input",
"react-native-reanimated": "1.2.0",
"react-native-super-grid": "^3.0.4", "react-native-super-grid": "^3.0.4",
"react-native-vector-icons": "^6.6.0", "react-native-vector-icons": "^6.4.2",
"react-native-video": "lbryio/react-native-video#exoplayer-lbry-android", "react-native-video": "lbryio/react-native-video#exoplayer-lbry-android",
"react-navigation": "^3.11.0", "react-navigation": "^3.11.0",
"react-navigation-drawer": "^1.4.0",
"react-navigation-redux-helpers": "^3.0.2", "react-navigation-redux-helpers": "^3.0.2",
"react-navigation-stack": "^1.8.1",
"react-redux": "^5.0.3", "react-redux": "^5.0.3",
"redux": "^4.0.4", "redux": "^4.0.4",
"redux-persist": "^5.10.0", "redux-persist": "^5.10.0",
@@ -44,8 +42,7 @@
"redux-persist-transform-compress": "^4.2.0", "redux-persist-transform-compress": "^4.2.0",
"redux-persist-transform-filter": "0.0.18", "redux-persist-transform-filter": "0.0.18",
"redux-thunk": "^2.3.0", "redux-thunk": "^2.3.0",
"rn-fetch-blob": "0.10.15", "rn-fetch-blob": "0.10.15"
"seedrandom": "3.0.3"
}, },
"devDependencies": { "devDependencies": {
"@babel/core": "^7.5.4", "@babel/core": "^7.5.4",
Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 278 KiB

+44 -118
View File
@@ -1,6 +1,5 @@
import React from 'react'; import React from 'react';
import AboutPage from 'page/about'; import AboutPage from 'page/about';
import ChannelCreatorPage from 'page/channelCreator';
import DiscoverPage from 'page/discover'; import DiscoverPage from 'page/discover';
import DownloadsPage from 'page/downloads'; import DownloadsPage from 'page/downloads';
import DrawerContent from 'component/drawerContent'; import DrawerContent from 'component/drawerContent';
@@ -18,29 +17,17 @@ import SubscriptionsPage from 'page/subscriptions';
import TransactionHistoryPage from 'page/transactionHistory'; import TransactionHistoryPage from 'page/transactionHistory';
import VerificationScreen from 'page/verification'; import VerificationScreen from 'page/verification';
import WalletPage from 'page/wallet'; import WalletPage from 'page/wallet';
import { NavigationActions } from 'react-navigation'; import { createDrawerNavigator, createStackNavigator, NavigationActions } from 'react-navigation';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { createStackNavigator } from 'react-navigation-stack';
import { import {
createReduxContainer, createReduxContainer,
createReactNavigationReduxMiddleware, createReactNavigationReduxMiddleware,
createNavigationReducer, createNavigationReducer,
} from 'react-navigation-redux-helpers'; } from 'react-navigation-redux-helpers';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { import { AppState, BackHandler, Linking, NativeModules, TextInput, ToastAndroid } from 'react-native';
AppState,
BackHandler,
DeviceEventEmitter,
Linking,
NativeModules,
StatusBar,
TextInput,
ToastAndroid,
} from 'react-native';
import { selectDrawerStack } from 'redux/selectors/drawer'; import { selectDrawerStack } from 'redux/selectors/drawer';
import { SETTINGS, doDismissToast, doPopulateSharedUserState, doPreferenceGet, doToast, selectToast } from 'lbry-redux'; import { SETTINGS, doDismissToast, doToast, selectToast } from 'lbry-redux';
import { import {
Lbryio,
doGetSync, doGetSync,
doUserCheckEmailVerified, doUserCheckEmailVerified,
doUserEmailVerify, doUserEmailVerify,
@@ -48,12 +35,11 @@ import {
selectEmailToVerify, selectEmailToVerify,
selectEmailVerifyIsPending, selectEmailVerifyIsPending,
selectEmailVerifyErrorMessage, selectEmailVerifyErrorMessage,
selectHashChanged,
selectUser, selectUser,
} from 'lbryinc'; } from 'lbryinc';
import { makeSelectClientSetting, selectFullscreenMode } from 'redux/selectors/settings'; import { makeSelectClientSetting } from 'redux/selectors/settings';
import { decode as atob } from 'base-64'; import { decode as atob } from 'base-64';
import { dispatchNavigateBack, dispatchNavigateToUri, transformUrl } from 'utils/helper'; import { dispatchNavigateBack, dispatchNavigateToUri } from 'utils/helper';
import AsyncStorage from '@react-native-community/async-storage'; import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
@@ -63,8 +49,6 @@ import discoverStyle from 'styles/discover';
import searchStyle from 'styles/search'; import searchStyle from 'styles/search';
import SearchRightHeaderIcon from 'component/searchRightHeaderIcon'; import SearchRightHeaderIcon from 'component/searchRightHeaderIcon';
const SYNC_GET_INTERVAL = 1000 * 60 * 5; // every 5 minutes
const menuNavigationButton = navigation => ( const menuNavigationButton = navigation => (
<NavigationButton <NavigationButton
name="bars" name="bars"
@@ -143,91 +127,79 @@ const walletStack = createStackNavigator(
} }
); );
const drawerIconSize = 18;
const drawer = createDrawerNavigator( const drawer = createDrawerNavigator(
{ {
DiscoverStack: { DiscoverStack: {
screen: discoverStack, screen: discoverStack,
navigationOptions: { navigationOptions: {
title: 'Explore', title: 'Explore',
drawerIcon: ({ tintColor }) => <Icon name="home" size={drawerIconSize} style={{ color: tintColor }} />, drawerIcon: ({ tintColor }) => <Icon name="home" size={20} style={{ color: tintColor }} />,
}, },
}, },
Trending: { TrendingStack: {
screen: TrendingPage, screen: TrendingPage,
navigationOptions: { navigationOptions: {
title: 'All Content', title: 'Trending',
drawerIcon: ({ tintColor }) => <Icon name="fire" size={drawerIconSize} style={{ color: tintColor }} />, drawerIcon: ({ tintColor }) => <Icon name="fire" size={20} style={{ color: tintColor }} />,
}, },
}, },
Subscriptions: { MySubscriptionsStack: {
screen: SubscriptionsPage, screen: SubscriptionsPage,
navigationOptions: { navigationOptions: {
title: 'Subscriptions', title: 'Subscriptions',
drawerIcon: ({ tintColor }) => <Icon name="heart" solid size={drawerIconSize} style={{ color: tintColor }} />, drawerIcon: ({ tintColor }) => <Icon name="heart" solid size={20} style={{ color: tintColor }} />,
}, },
}, },
WalletStack: { WalletStack: {
screen: walletStack, screen: walletStack,
navigationOptions: { navigationOptions: {
title: 'Wallet', title: 'Wallet',
drawerIcon: ({ tintColor }) => <Icon name="wallet" size={drawerIconSize} style={{ color: tintColor }} />, drawerIcon: ({ tintColor }) => <Icon name="wallet" size={20} style={{ color: tintColor }} />,
},
},
ChannelCreator: {
screen: ChannelCreatorPage,
navigationOptions: {
drawerIcon: ({ tintColor }) => <Icon name="at" size={drawerIconSize} style={{ color: tintColor }} />,
}, },
}, },
Publish: { Publish: {
screen: PublishPage, screen: PublishPage,
navigationOptions: { navigationOptions: {
drawerIcon: ({ tintColor }) => <Icon name="upload" size={drawerIconSize} style={{ color: tintColor }} />, drawerIcon: ({ tintColor }) => <Icon name="upload" size={20} style={{ color: tintColor }} />,
}, },
}, },
Publishes: { Publishes: {
screen: PublishesPage, screen: PublishesPage,
navigationOptions: { navigationOptions: {
drawerIcon: ({ tintColor }) => ( drawerIcon: ({ tintColor }) => <Icon name="cloud-upload-alt" size={20} style={{ color: tintColor }} />,
<Icon name="cloud-upload-alt" size={drawerIconSize} style={{ color: tintColor }} />
),
}, },
}, },
Rewards: { Rewards: {
screen: RewardsPage, screen: RewardsPage,
navigationOptions: { navigationOptions: {
drawerIcon: ({ tintColor }) => <Icon name="award" size={drawerIconSize} style={{ color: tintColor }} />, drawerIcon: ({ tintColor }) => <Icon name="award" size={20} style={{ color: tintColor }} />,
}, },
}, },
Downloads: { MyLBRYStack: {
screen: DownloadsPage, screen: DownloadsPage,
navigationOptions: { navigationOptions: {
title: 'Library', title: 'Library',
drawerIcon: ({ tintColor }) => <Icon name="download" size={drawerIconSize} style={{ color: tintColor }} />, drawerIcon: ({ tintColor }) => <Icon name="download" size={20} style={{ color: tintColor }} />,
}, },
}, },
Settings: { Settings: {
screen: SettingsPage, screen: SettingsPage,
navigationOptions: { navigationOptions: {
drawerLockMode: 'locked-closed', drawerLockMode: 'locked-closed',
drawerIcon: ({ tintColor }) => <Icon name="cog" size={drawerIconSize} style={{ color: tintColor }} />, drawerIcon: ({ tintColor }) => <Icon name="cog" size={20} style={{ color: tintColor }} />,
}, },
}, },
About: { About: {
screen: AboutPage, screen: AboutPage,
navigationOptions: { navigationOptions: {
drawerLockMode: 'locked-closed', drawerLockMode: 'locked-closed',
drawerIcon: ({ tintColor }) => <Icon name="info" size={drawerIconSize} style={{ color: tintColor }} />, drawerIcon: ({ tintColor }) => <Icon name="info" size={20} style={{ color: tintColor }} />,
}, },
}, },
}, },
{ {
drawerWidth: 300, drawerWidth: 300,
drawerBackgroundColor: 'transparent',
headerMode: 'none', headerMode: 'none',
backBehavior: 'none',
unmountInactiveRoutes: true,
contentComponent: DrawerContent, contentComponent: DrawerContent,
contentOptions: { contentOptions: {
activeTintColor: Colors.LbryGreen, activeTintColor: Colors.LbryGreen,
@@ -281,11 +253,9 @@ class AppWithNavigationState extends React.Component {
constructor() { constructor() {
super(); super();
this.emailVerifyCheckInterval = null; this.emailVerifyCheckInterval = null;
this.syncGetInterval = null;
this.state = { this.state = {
emailVerifyDone: false, emailVerifyDone: false,
verifyPending: false, verifyPending: false,
syncHashChanged: false,
}; };
} }
@@ -295,30 +265,29 @@ class AppWithNavigationState extends React.Component {
'hardwareBackPress', 'hardwareBackPress',
function() { function() {
const { dispatch, nav, drawerStack } = this.props; const { dispatch, nav, drawerStack } = this.props;
if (drawerStack.length > 1) { // There should be a better way to check this
dispatchNavigateBack(dispatch, nav, drawerStack); if (nav.routes.length > 0) {
return true; if (nav.routes[0].routeName === 'Main') {
const mainRoute = nav.routes[0];
if (
mainRoute.index > 0 ||
mainRoute.routes[0].index > 0 /* Discover stack index */ ||
mainRoute.routes[4].index > 0 /* Wallet stack index */ ||
mainRoute.index >= 5 /* Settings and About screens */
) {
dispatchNavigateBack(dispatch, nav, drawerStack);
return true;
}
}
} }
return false; return false;
}.bind(this) }.bind(this)
); );
} }
componentDidMount() { componentDidMount() {
const { dispatch, user } = this.props;
this.emailVerifyCheckInterval = setInterval(() => this.checkEmailVerification(), 5000); this.emailVerifyCheckInterval = setInterval(() => this.checkEmailVerification(), 5000);
Linking.addEventListener('url', this._handleUrl); Linking.addEventListener('url', this._handleUrl);
// call /sync/get with interval
this.syncGetInterval = setInterval(() => {
this.setState({ syncHashChanged: false }); // reset local state
if (user && user.has_verified_email) {
NativeModules.UtilityModule.getSecureValue(Constants.KEY_WALLET_PASSWORD).then(walletPassword => {
dispatch(doGetSync(walletPassword, () => this.getUserSettings()));
});
}
}, SYNC_GET_INTERVAL);
} }
checkEmailVerification = () => { checkEmailVerification = () => {
@@ -331,48 +300,27 @@ class AppWithNavigationState extends React.Component {
}); });
}; };
getUserSettings = () => {
const { dispatch } = this.props;
doPreferenceGet(
'shared',
preference => {
dispatch(doPopulateSharedUserState(preference));
},
error => {
/* failed */
}
);
};
componentWillUnmount() { componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange); AppState.removeEventListener('change', this._handleAppStateChange);
BackHandler.removeEventListener('hardwareBackPress'); BackHandler.removeEventListener('hardwareBackPress');
Linking.removeEventListener('url', this._handleUrl); Linking.removeEventListener('url', this._handleUrl);
if (this.emailVerifyCheckInterval > -1) {
clearInterval(this.emailVerifyCheckInterval);
}
if (this.syncGetInterval > -1) {
clearInterval(this.syncGetInterval);
}
} }
componentDidUpdate() { componentDidUpdate() {
const { dispatch, user, hashChanged } = this.props; const { dispatch, user } = this.props;
if (this.state.verifyPending && this.emailVerifyCheckInterval > 0 && user && user.has_verified_email) { if (this.state.verifyPending && this.emailVerifyCheckInterval > 0 && user && user.has_verified_email) {
clearInterval(this.emailVerifyCheckInterval); clearInterval(this.emailVerifyCheckInterval);
AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'false'); AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'false');
this.setState({ verifyPending: false }); this.setState({ verifyPending: false });
NativeModules.Firebase.track('email_verified', { email: user.primary_email }); ToastAndroid.show('Your email address was successfully verified.', ToastAndroid.LONG);
ToastAndroid.show(__('Your email address was successfully verified.'), ToastAndroid.LONG);
// get user settings after email verification // upon successful email verification, do wallet sync (if password has been set)
this.getUserSettings(); NativeModules.UtilityModule.getSecureValue(Constants.KEY_FIRST_RUN_PASSWORD).then(walletPassword => {
} if (walletPassword && walletPassword.trim().length > 0) {
dispatch(doGetSync(walletPassword));
if (hashChanged && !this.state.syncHashChanged) { }
this.setState({ syncHashChanged: true }); });
this.getUserSettings();
} }
} }
@@ -401,7 +349,7 @@ class AppWithNavigationState extends React.Component {
this.setState({ emailVerifyDone: true }); this.setState({ emailVerifyDone: true });
const message = emailVerifyErrorMessage const message = emailVerifyErrorMessage
? String(emailVerifyErrorMessage) ? String(emailVerifyErrorMessage)
: __('Your email address was successfully verified.'); : 'Your email address was successfully verified.';
if (!emailVerifyErrorMessage) { if (!emailVerifyErrorMessage) {
AsyncStorage.removeItem(Constants.KEY_FIRST_RUN_EMAIL); AsyncStorage.removeItem(Constants.KEY_FIRST_RUN_EMAIL);
} }
@@ -436,26 +384,6 @@ class AppWithNavigationState extends React.Component {
if (backgroundPlayEnabled || NativeModules.BackgroundMedia) { if (backgroundPlayEnabled || NativeModules.BackgroundMedia) {
NativeModules.BackgroundMedia.hidePlaybackNotification(); NativeModules.BackgroundMedia.hidePlaybackNotification();
} }
// check fullscreen mode and show / hide navigation bar accordingly
this.checkFullscreenMode();
}
};
checkFullscreenMode = () => {
const { fullscreenMode } = this.props;
StatusBar.setHidden(fullscreenMode);
if (fullscreenMode) {
// fullscreen, so change orientation to landscape mode
NativeModules.ScreenOrientation.lockOrientationLandscape();
// hide the navigation bar (on devices that have the soft navigation bar)
NativeModules.UtilityModule.hideNavigationBar();
} else {
// Switch back to portrait mode when the media is not fullscreen
NativeModules.ScreenOrientation.lockOrientationPortrait();
// hide the navigation bar (on devices that have the soft navigation bar)
NativeModules.UtilityModule.showNavigationBar();
} }
}; };
@@ -476,7 +404,7 @@ class AppWithNavigationState extends React.Component {
try { try {
dispatch(doUserEmailVerify(verification.token, verification.recaptcha)); dispatch(doUserEmailVerify(verification.token, verification.recaptcha));
} catch (error) { } catch (error) {
const message = __('Invalid Verification Token'); const message = 'Invalid Verification Token';
dispatch(doUserEmailVerifyFailure(message)); dispatch(doUserEmailVerifyFailure(message));
dispatch(doToast({ message })); dispatch(doToast({ message }));
} }
@@ -488,7 +416,7 @@ class AppWithNavigationState extends React.Component {
); );
} }
} else { } else {
dispatchNavigateToUri(dispatch, nav, transformUrl(evt.url)); dispatchNavigateToUri(dispatch, nav, evt.url);
} }
} }
}; };
@@ -500,7 +428,6 @@ class AppWithNavigationState extends React.Component {
const mapStateToProps = state => ({ const mapStateToProps = state => ({
backgroundPlayEnabled: makeSelectClientSetting(SETTINGS.BACKGROUND_PLAY_ENABLED)(state), backgroundPlayEnabled: makeSelectClientSetting(SETTINGS.BACKGROUND_PLAY_ENABLED)(state),
hashChanged: selectHashChanged(state),
keepDaemonRunning: makeSelectClientSetting(SETTINGS.KEEP_DAEMON_RUNNING)(state), keepDaemonRunning: makeSelectClientSetting(SETTINGS.KEEP_DAEMON_RUNNING)(state),
nav: state.nav, nav: state.nav,
toast: selectToast(state), toast: selectToast(state),
@@ -510,7 +437,6 @@ const mapStateToProps = state => ({
emailVerifyErrorMessage: selectEmailVerifyErrorMessage(state), emailVerifyErrorMessage: selectEmailVerifyErrorMessage(state),
showNsfw: makeSelectClientSetting(SETTINGS.SHOW_NSFW)(state), showNsfw: makeSelectClientSetting(SETTINGS.SHOW_NSFW)(state),
user: selectUser(state), user: selectUser(state),
fullscreenMode: selectFullscreenMode(state),
}); });
export default connect(mapStateToProps)(AppWithNavigationState); export default connect(mapStateToProps)(AppWithNavigationState);
+2 -2
View File
@@ -15,7 +15,7 @@ export default class Address extends React.PureComponent<Props> {
return ( return (
<View style={[walletStyle.row, style]}> <View style={[walletStyle.row, style]}>
<Text selectable numberOfLines={1} style={walletStyle.address}> <Text selectable={true} numberOfLines={1} style={walletStyle.address}>
{address || ''} {address || ''}
</Text> </Text>
<Button <Button
@@ -24,7 +24,7 @@ export default class Address extends React.PureComponent<Props> {
onPress={() => { onPress={() => {
Clipboard.setString(address); Clipboard.setString(address);
doToast({ doToast({
message: __('Address copied'), message: 'Address copied',
}); });
}} }}
/> />
+7 -2
View File
@@ -34,11 +34,16 @@ export default class Button extends React.PureComponent {
} }
let renderIcon = ( let renderIcon = (
<Icon name={icon} size={16} color={iconColor || (theme === 'light' ? Colors.DarkGrey : Colors.White)} /> <Icon name={icon} size={18} color={iconColor ? iconColor : 'light' === theme ? Colors.DarkGrey : Colors.White} />
); );
if (solid) { if (solid) {
renderIcon = ( renderIcon = (
<Icon name={icon} size={16} color={iconColor || (theme === 'light' ? Colors.DarkGrey : Colors.White)} solid /> <Icon
name={icon}
size={18}
color={iconColor ? iconColor : 'light' === theme ? Colors.DarkGrey : Colors.White}
solid
/>
); );
} }
+4
View File
@@ -0,0 +1,4 @@
import { connect } from 'react-redux';
import CategoryList from './view';
export default connect()(CategoryList);
+39
View File
@@ -0,0 +1,39 @@
import React from 'react';
import NavigationActions from 'react-navigation';
import { FlatList, Text, View } from 'react-native';
import { normalizeURI } from 'lbry-redux';
import FileItem from '/component/fileItem';
import discoverStyle from 'styles/discover';
class CategoryList extends React.PureComponent {
render() {
const { category, categoryMap, navigation } = this.props;
return (
<FlatList
style={discoverStyle.horizontalScrollContainer}
contentContainerStyle={discoverStyle.horizontalScrollPadding}
initialNumToRender={3}
maxToRenderPerBatch={3}
removeClippedSubviews={true}
renderItem={({ item }) => (
<FileItem
style={discoverStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={item}
uri={normalizeURI(item)}
navigation={navigation}
showDetails={true}
compactView={false}
/>
)}
horizontal={true}
showsHorizontalScrollIndicator={false}
data={categoryMap[category]}
keyExtractor={(item, index) => item}
/>
);
}
}
export default CategoryList;
+1 -8
View File
@@ -1,17 +1,10 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { import { doResolveUri, makeSelectClaimForUri, makeSelectThumbnailForUri, makeSelectIsUriResolving } from 'lbry-redux';
doResolveUri,
makeSelectClaimForUri,
makeSelectThumbnailForUri,
makeSelectTitleForUri,
makeSelectIsUriResolving,
} from 'lbry-redux';
import ChannelIconItem from './view'; import ChannelIconItem from './view';
const select = (state, props) => ({ const select = (state, props) => ({
thumbnail: makeSelectThumbnailForUri(props.uri)(state), thumbnail: makeSelectThumbnailForUri(props.uri)(state),
claim: makeSelectClaimForUri(props.uri)(state), claim: makeSelectClaimForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
isResolvingUri: makeSelectIsUriResolving(props.uri)(state), isResolvingUri: makeSelectIsUriResolving(props.uri)(state),
}); });
+8 -43
View File
@@ -1,40 +1,9 @@
import React from 'react'; import React from 'react';
import { ActivityIndicator, Image, Text, TouchableOpacity, View } from 'react-native'; import { ActivityIndicator, Image, Text, TouchableOpacity, View } from 'react-native';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import autothumbStyle from 'styles/autothumb';
import channelIconStyle from 'styles/channelIcon'; import channelIconStyle from 'styles/channelIcon';
export default class ChannelIconItem extends React.PureComponent { export default class ChannelIconItem extends React.PureComponent {
static AUTO_THUMB_STYLES = [
autothumbStyle.autothumbPurple,
autothumbStyle.autothumbRed,
autothumbStyle.autothumbPink,
autothumbStyle.autothumbIndigo,
autothumbStyle.autothumbBlue,
autothumbStyle.autothumbLightBlue,
autothumbStyle.autothumbCyan,
autothumbStyle.autothumbGreen,
autothumbStyle.autothumbYellow,
autothumbStyle.autothumbOrange,
autothumbStyle.autothumbDeepPurple,
autothumbStyle.autothumbAmber,
autothumbStyle.autothumbLime,
autothumbStyle.autothumbLightGreen,
autothumbStyle.autothumbDeepOrange,
autothumbStyle.autothumbBrown,
];
state = {
autoStyle: null,
};
componentWillMount() {
this.setState({
autoStyle:
ChannelIconItem.AUTO_THUMB_STYLES[Math.floor(Math.random() * ChannelIconItem.AUTO_THUMB_STYLES.length)],
});
}
componentDidMount() { componentDidMount() {
const { claim, isPlaceholder, uri, resolveUri } = this.props; const { claim, isPlaceholder, uri, resolveUri } = this.props;
if (!claim && !isPlaceholder) { if (!claim && !isPlaceholder) {
@@ -44,8 +13,6 @@ export default class ChannelIconItem extends React.PureComponent {
render() { render() {
const { claim, isPlaceholder, isResolvingUri, onPress, thumbnail, title } = this.props; const { claim, isPlaceholder, isResolvingUri, onPress, thumbnail, title } = this.props;
const displayName = title || (claim ? claim.name : '');
const substrIndex = displayName.startsWith('@') ? 1 : 0;
return ( return (
<TouchableOpacity style={channelIconStyle.container} onPress={onPress}> <TouchableOpacity style={channelIconStyle.container} onPress={onPress}>
@@ -58,26 +25,24 @@ export default class ChannelIconItem extends React.PureComponent {
style={[ style={[
channelIconStyle.thumbnailContainer, channelIconStyle.thumbnailContainer,
isPlaceholder ? channelIconStyle.borderedThumbnailContainer : null, isPlaceholder ? channelIconStyle.borderedThumbnailContainer : null,
isPlaceholder ? null : this.state.autoStyle,
]} ]}
> >
{isPlaceholder && ( {isPlaceholder && (
<View style={channelIconStyle.centered}> <View style={channelIconStyle.centered}>
<Text style={channelIconStyle.placeholderText}>{__('ALL')}</Text> <Text style={channelIconStyle.placeholderText}>ALL</Text>
</View> </View>
)} )}
{!isPlaceholder && thumbnail && ( {!isPlaceholder && (
<Image style={channelIconStyle.thumbnail} resizeMode={'cover'} source={{ uri: thumbnail }} /> <Image
)} style={channelIconStyle.thumbnail}
{!isPlaceholder && !thumbnail && ( resizeMode={'cover'}
<Text style={channelIconStyle.autothumbCharacter}> source={thumbnail ? { uri: thumbnail } : require('../../assets/default_avatar.jpg')}
{displayName.substring(substrIndex, substrIndex + 1).toUpperCase()} />
</Text>
)} )}
</View> </View>
{!isPlaceholder && ( {!isPlaceholder && (
<Text style={channelIconStyle.title} numberOfLines={1}> <Text style={channelIconStyle.title} numberOfLines={1}>
{displayName} {title || (claim ? claim.name : '')}
</Text> </Text>
)} )}
</TouchableOpacity> </TouchableOpacity>
@@ -1,4 +0,0 @@
import { connect } from 'react-redux';
import ChannelRewardsDriver from './view';
export default connect()(ChannelRewardsDriver);
@@ -1,24 +0,0 @@
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import Colors from 'styles/colors';
import Icon from 'react-native-vector-icons/FontAwesome5';
import publishStyle from 'styles/publish';
class ChannelRewardsDriver extends React.PureComponent<Props> {
render() {
const { navigation } = this.props;
return (
<TouchableOpacity style={publishStyle.rewardDriverCard} onPress={() => navigation.navigate('Rewards')}>
<Icon name="award" size={16} style={publishStyle.rewardIcon} />
<Text style={publishStyle.rewardDriverText}>
{__('Channel creation requires credits.')}
{'\n'}
{__('Tap here to get some for free.')}
</Text>
</TouchableOpacity>
);
}
}
export default ChannelRewardsDriver;
-2
View File
@@ -7,7 +7,6 @@ import {
doCreateChannel, doCreateChannel,
doToast, doToast,
} from 'lbry-redux'; } from 'lbry-redux';
import { doGetSync } from 'lbryinc';
import ChannelSelector from './view'; import ChannelSelector from './view';
const select = state => ({ const select = state => ({
@@ -20,7 +19,6 @@ const perform = dispatch => ({
notify: data => dispatch(doToast(data)), notify: data => dispatch(doToast(data)),
createChannel: (name, amount) => dispatch(doCreateChannel(name, amount)), createChannel: (name, amount) => dispatch(doCreateChannel(name, amount)),
fetchChannelListMine: () => dispatch(doFetchChannelListMine()), fetchChannelListMine: () => dispatch(doFetchChannelListMine()),
getSync: (password, callback) => dispatch(doGetSync(password, callback)),
}); });
export default connect( export default connect(
+31 -66
View File
@@ -1,10 +1,9 @@
import React from 'react'; import React from 'react';
import { CLAIM_VALUES, isNameValid } from 'lbry-redux'; import { CLAIM_VALUES, isNameValid } from 'lbry-redux';
import { ActivityIndicator, NativeModules, Picker, Text, TextInput, TouchableOpacity, View } from 'react-native'; import { ActivityIndicator, Picker, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { logPublish } from 'utils/helper';
import Button from 'component/button'; import Button from 'component/button';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import Icon from 'react-native-vector-icons/FontAwesome5'; import Icon from 'react-native-vector-icons/FontAwesome5';
import Link from 'component/link'; import Link from 'component/link';
import channelSelectorStyle from 'styles/channelSelector'; import channelSelectorStyle from 'styles/channelSelector';
@@ -27,20 +26,10 @@ export default class ChannelSelector extends React.PureComponent {
} }
componentDidMount() { componentDidMount() {
const { channels = [], channelName, fetchChannelListMine, fetchingChannels } = this.props; const { channels, fetchChannelListMine, fetchingChannels } = this.props;
if ((!channels || channels.length === 0) && !fetchingChannels) { if (!channels.length && !fetchingChannels) {
fetchChannelListMine(); fetchChannelListMine();
} }
this.setState({ currentSelectedValue: channelName });
}
componentWillReceiveProps(nextProps) {
const { channels: prevChannels = [], channelName } = this.props;
const { channels = [] } = nextProps;
if (channels && channels.length !== prevChannels.length && channelName !== this.state.currentSelectedValue) {
this.setState({ currentSelectedValue: channelName });
}
} }
handleCreateCancel = () => { handleCreateCancel = () => {
@@ -65,13 +54,13 @@ export default class ChannelSelector extends React.PureComponent {
if (channel === CLAIM_VALUES.CHANNEL_NEW) { if (channel === CLAIM_VALUES.CHANNEL_NEW) {
this.setState({ addingChannel: true }); this.setState({ addingChannel: true });
if (onChannelChange) { if (onChannelChange) {
onChannelChange(value); onChannelChange(channel);
} }
this.handleNewChannelBidChange(newChannelBid); this.handleNewChannelBidChange(newChannelBid);
} else { } else {
this.setState({ addingChannel: false }); this.setState({ addingChannel: false });
if (onChannelChange) { if (onChannelChange) {
onChannelChange(value); onChannelChange(channel);
} }
} }
}; };
@@ -79,22 +68,14 @@ export default class ChannelSelector extends React.PureComponent {
handleNewChannelNameChange = value => { handleNewChannelNameChange = value => {
const { notify } = this.props; const { notify } = this.props;
let newChannelName = value, let newChannelName = value;
newChannelNameError = '';
if (newChannelName.startsWith('@')) { if (newChannelName.startsWith('@')) {
newChannelName = newChannelName.slice(1); newChannelName = newChannelName.slice(1);
} }
if (newChannelName.trim().length > 0 && !isNameValid(newChannelName)) {
newChannelNameError = __('Your channel name contains invalid characters.');
} else if (this.channelExists(newChannelName)) {
newChannelNameError = __('You have already created a channel with the same name.');
}
this.setState({ this.setState({
newChannelName, newChannelName,
newChannelNameError,
}); });
}; };
@@ -118,21 +99,21 @@ export default class ChannelSelector extends React.PureComponent {
}; };
handleCreateChannelClick = () => { handleCreateChannelClick = () => {
const { balance, createChannel, getSync, onChannelChange, notify } = this.props; const { balance, createChannel, onChannelChange, notify } = this.props;
const { newChannelBid, newChannelName } = this.state; const { newChannelBid, newChannelName } = this.state;
if (newChannelName.trim().length === 0 || !isNameValid(newChannelName.substr(1), false)) { if (newChannelName.trim().length === 0 || !isNameValid(newChannelName.substr(1), false)) {
notify({ message: __('Your channel name contains invalid characters.') }); notify({ message: 'Your channel name contains invalid characters.' });
return; return;
} }
if (this.channelExists(newChannelName)) { if (this.channelExists(newChannelName)) {
notify({ message: __('You have already created a channel with the same name.') }); notify({ message: 'You have already created a channel with the same name.' });
return; return;
} }
if (newChannelBid > balance) { if (newChannelBid > balance) {
notify({ message: __('Deposit cannot be higher than your balance') }); notify({ message: 'Deposit cannot be higher than your balance' });
return; return;
} }
@@ -143,25 +124,21 @@ export default class ChannelSelector extends React.PureComponent {
createChannelError: undefined, createChannelError: undefined,
}); });
const success = channelClaim => { const success = () => {
this.setState({ this.setState({
creatingChannel: false, creatingChannel: false,
addingChannel: false, addingChannel: false,
currentSelectedValue: channelName, currentSelectedValue: channelName,
showCreateChannel: false, showCreateChannel: false,
}); });
logPublish(channelClaim);
if (onChannelChange) { if (onChannelChange) {
onChannelChange(channelName); onChannelChange(channelName);
} }
// sync wallet
NativeModules.UtilityModule.getSecureValue(Constants.KEY_WALLET_PASSWORD).then(password => getSync(password));
}; };
const failure = () => { const failure = () => {
notify({ message: __('Unable to create channel due to an internal error.') }); notify({ message: 'Unable to create channel due to an internal error.' });
this.setState({ this.setState({
creatingChannel: false, creatingChannel: false,
}); });
@@ -172,14 +149,12 @@ export default class ChannelSelector extends React.PureComponent {
channelExists = name => { channelExists = name => {
const { channels = [] } = this.props; const { channels = [] } = this.props;
if (channels) { for (let channel of channels) {
for (let channel of channels) { if (
if ( name.toLowerCase() === channel.name.toLowerCase() ||
name.toLowerCase() === channel.name.toLowerCase() || `@${name}`.toLowerCase() === channel.name.toLowerCase()
`@${name}`.toLowerCase() === channel.name.toLowerCase() ) {
) { return true;
return true;
}
} }
} }
@@ -188,11 +163,10 @@ export default class ChannelSelector extends React.PureComponent {
render() { render() {
const channel = this.state.addingChannel ? 'new' : this.props.channel; const channel = this.state.addingChannel ? 'new' : this.props.channel;
const { enabled, fetchingChannels, channels = [] } = this.props; const { fetchingChannels, channels = [] } = this.props;
const pickerItems = [Constants.ITEM_ANONYMOUS, Constants.ITEM_CREATE_A_CHANNEL].concat( const pickerItems = [{ name: Constants.ITEM_ANONYMOUS }, { name: Constants.ITEM_CREATE_A_CHANNEL }].concat(
channels ? channels.map(ch => ch.name) : [] channels
); );
const { const {
newChannelName, newChannelName,
newChannelNameError, newChannelNameError,
@@ -201,28 +175,22 @@ export default class ChannelSelector extends React.PureComponent {
creatingChannel, creatingChannel,
createChannelError, createChannelError,
addingChannel, addingChannel,
showCreateChannel,
} = this.state; } = this.state;
return ( return (
<View style={channelSelectorStyle.container}> <View style={channelSelectorStyle.container}>
<Picker <Picker
enabled={enabled}
selectedValue={this.state.currentSelectedValue} selectedValue={this.state.currentSelectedValue}
style={channelSelectorStyle.channelPicker} style={channelSelectorStyle.channelPicker}
itemStyle={channelSelectorStyle.channelPickerItem} itemStyle={channelSelectorStyle.channelPickerItem}
onValueChange={this.handlePickerValueChange} onValueChange={this.handlePickerValueChange}
> >
{pickerItems.map(item => ( {pickerItems.map(item => (
<Picker.Item <Picker.Item label={item.name} value={item.name} key={item.name} />
label={[Constants.ITEM_ANONYMOUS, Constants.ITEM_CREATE_A_CHANNEL].includes(item) ? __(item) : item}
value={item}
key={item}
/>
))} ))}
</Picker> </Picker>
{showCreateChannel && ( {this.state.showCreateChannel && (
<View style={channelSelectorStyle.createChannelContainer}> <View style={channelSelectorStyle.createChannelContainer}>
<View style={channelSelectorStyle.channelInputContainer}> <View style={channelSelectorStyle.channelInputContainer}>
<Text style={channelSelectorStyle.channelAt}>@</Text> <Text style={channelSelectorStyle.channelAt}>@</Text>
@@ -231,18 +199,15 @@ export default class ChannelSelector extends React.PureComponent {
style={channelSelectorStyle.channelNameInput} style={channelSelectorStyle.channelNameInput}
value={this.state.newChannelName} value={this.state.newChannelName}
onChangeText={this.handleNewChannelNameChange} onChangeText={this.handleNewChannelNameChange}
placeholder={__('Channel name')} placeholder={'Channel name'}
underlineColorAndroid={Colors.NextLbryGreen} underlineColorAndroid={Colors.NextLbryGreen}
/> />
</View> </View>
{newChannelNameError.length > 0 && (
<Text style={channelSelectorStyle.inlineError}>{newChannelNameError}</Text>
)}
<View style={channelSelectorStyle.bidRow}> <View style={channelSelectorStyle.bidRow}>
<Text style={channelSelectorStyle.label}>{__('Deposit')}</Text> <Text style={channelSelectorStyle.label}>Deposit</Text>
<TextInput <TextInput
style={channelSelectorStyle.bidAmountInput} style={channelSelectorStyle.bidAmountInput}
value={String(newChannelBid)} value={String(this.state.newChannelBid)}
onChangeText={this.handleNewChannelBidChange} onChangeText={this.handleNewChannelBidChange}
placeholder={'0.00'} placeholder={'0.00'}
keyboardType={'number-pad'} keyboardType={'number-pad'}
@@ -251,18 +216,18 @@ export default class ChannelSelector extends React.PureComponent {
<Text style={channelSelectorStyle.currency}>LBC</Text> <Text style={channelSelectorStyle.currency}>LBC</Text>
</View> </View>
<Text style={channelSelectorStyle.helpText}> <Text style={channelSelectorStyle.helpText}>
{__('This LBC remains yours. It is a deposit to reserve the name and can be undone at any time.')} This LBC remains yours. It is a deposit to reserve the name and can be undone at any time.
</Text> </Text>
<View style={channelSelectorStyle.buttonContainer}> <View style={channelSelectorStyle.buttonContainer}>
{creatingChannel && <ActivityIndicator size={'small'} color={Colors.LbryGreen} />} {creatingChannel && <ActivityIndicator size={'small'} color={Colors.LbryGreen} />}
{!creatingChannel && ( {!creatingChannel && (
<View style={channelSelectorStyle.buttons}> <View style={channelSelectorStyle.buttons}>
<Link style={channelSelectorStyle.cancelLink} text={__('Cancel')} onPress={this.handleCreateCancel} /> <Link style={channelSelectorStyle.cancelLink} text="Cancel" onPress={this.handleCreateCancel} />
<Button <Button
style={channelSelectorStyle.createButton} style={channelSelectorStyle.createButton}
disabled={!(newChannelName.trim().length > 0 && newChannelBid > 0)} disabled={!(this.state.newChannelName.trim().length > 0 && this.state.newChannelBid > 0)}
text={__('Create')} text="Create"
onPress={this.handleCreateChannelClick} onPress={this.handleCreateChannelClick}
/> />
</View> </View>
+31 -12
View File
@@ -2,25 +2,44 @@ import { connect } from 'react-redux';
import { import {
MATURE_TAGS, MATURE_TAGS,
doClaimSearch, doClaimSearch,
selectClaimSearchByQuery, doClaimSearchByTags,
selectClaimSearchByQueryLastPageReached, makeSelectClaimSearchUrisForTags,
selectFetchingClaimSearchByQuery, makeSelectFetchingClaimSearchForTags,
selectFetchingClaimSearch, selectFetchingClaimSearch,
selectLastClaimSearchUris,
} from 'lbry-redux'; } from 'lbry-redux';
import { selectShowNsfw } from 'redux/selectors/settings';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import ClaimList from './view'; import ClaimList from './view';
const select = state => ({ const select = (state, props) => {
showNsfwContent: selectShowNsfw(state), return {
claimSearchByQuery: selectClaimSearchByQuery(state), loading: makeSelectFetchingClaimSearchForTags(props.tags)(state),
lastPageReached: selectClaimSearchByQueryLastPageReached(state), uris: makeSelectClaimSearchUrisForTags(props.tags)(state),
loadingByQuery: selectFetchingClaimSearchByQuery(state), // for subscriptions
loading: selectFetchingClaimSearch(state), claimSearchLoading: selectFetchingClaimSearch(state),
}); claimSearchUris: selectLastClaimSearchUris(state),
};
};
const perform = dispatch => ({ const perform = dispatch => ({
claimSearch: options => dispatch(doClaimSearch(options)), claimSearch: options => dispatch(doClaimSearch(Constants.DEFAULT_PAGE_SIZE, options)),
searchByTags: (tags, orderBy = Constants.DEFAULT_ORDER_BY, page = 1, additionalOptions = {}) =>
dispatch(
doClaimSearchByTags(
tags,
Constants.DEFAULT_PAGE_SIZE,
Object.assign(
{},
{
no_totals: true,
order_by: orderBy,
page,
not_tags: MATURE_TAGS,
},
additionalOptions
)
)
),
}); });
export default connect( export default connect(
+112 -120
View File
@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import NavigationActions from 'react-navigation'; import NavigationActions from 'react-navigation';
import { ActivityIndicator, FlatList, Text, TouchableOpacity, View } from 'react-native'; import { ActivityIndicator, FlatList, Text, TouchableOpacity, View } from 'react-native';
import { MATURE_TAGS, normalizeURI, createNormalizedClaimSearchKey } from 'lbry-redux'; import { MATURE_TAGS, normalizeURI } from 'lbry-redux';
import _ from 'lodash'; import _ from 'lodash';
import FileItem from 'component/fileItem'; import FileItem from 'component/fileItem';
import FileListItem from 'component/fileListItem'; import FileListItem from 'component/fileListItem';
@@ -12,7 +12,7 @@ import claimListStyle from 'styles/claimList';
import discoverStyle from 'styles/discover'; import discoverStyle from 'styles/discover';
import moment from 'moment'; import moment from 'moment';
const horizontalLimit = 10; const horizontalLimit = 7;
const softLimit = 500; const softLimit = 500;
class ClaimList extends React.PureComponent { class ClaimList extends React.PureComponent {
@@ -21,82 +21,94 @@ class ClaimList extends React.PureComponent {
state = { state = {
currentPage: 1, // initial page load is page 1 currentPage: 1, // initial page load is page 1
subscriptionsView: false, // whether or not this claim list is for subscriptions subscriptionsView: false, // whether or not this claim list is for subscriptions
lastPageReached: false, trendingForAllView: false,
}; };
componentDidMount() { componentDidMount() {
const { channelIds } = this.props; const {
channelIds,
trendingForAll,
claimSearch,
orderBy = Constants.DEFAULT_ORDER_BY,
searchByTags,
tags,
time,
} = this.props;
if (channelIds || trendingForAll) {
const options = {
order_by: orderBy,
no_totals: true,
not_tags: MATURE_TAGS,
page: this.state.currentPage,
};
if (channelIds) {
this.setState({ subscriptionsView: true });
options.channel_ids = channelIds;
} else if (trendingForAll) {
this.setState({ trendingForAllView: true });
}
if (channelIds) { claimSearch(options);
this.setState({ subscriptionsView: true }); } else if (tags && tags.length > 0) {
const additionalOptions = {};
if (orderBy && orderBy[0] === Constants.ORDER_BY_EFFECTIVE_AMOUNT && Constants.TIME_ALL !== time) {
additionalOptions.release_time = this.getReleaseTimeOption(time);
}
searchByTags(tags, orderBy, this.state.currentPage, additionalOptions);
} }
this.doClaimSearch();
} }
componentDidUpdate(prevProps) { componentWillReceiveProps(nextProps) {
const { const {
claimSearchByQuery: prevClaimSearchByQuery, claimSearch,
orderBy: prevOrderBy, orderBy: prevOrderBy,
searchByTags, searchByTags,
tags: prevTags, tags: prevTags,
channelIds: prevChannelIds, channelIds: prevChannelIds,
trendingForAll: prevTrendingForAll,
time: prevTime, time: prevTime,
} = prevProps; } = this.props;
const { claimSearchByQuery, orderBy, tags, channelIds, time } = this.props; const { orderBy, tags, channelIds, trendingForAll, time } = nextProps;
if ( if (
!_.isEqual(orderBy, prevOrderBy) || !_.isEqual(orderBy, prevOrderBy) ||
!_.isEqual(tags, prevTags) || !_.isEqual(tags, prevTags) ||
!_.isEqual(channelIds, prevChannelIds) || !_.isEqual(channelIds, prevChannelIds) ||
time !== prevTime time !== prevTime ||
trendingForAll !== prevTrendingForAll
) { ) {
// reset to page 1 because the order, tags or channelIds changed // reset to page 1 because the order, tags or channelIds changed
this.setState({ currentPage: 1 }, () => { this.setState({ currentPage: 1 }, () => {
if (this.scrollView) { if (this.scrollView) {
this.scrollView.scrollToOffset({ animated: true, offset: 0 }); this.scrollView.scrollToOffset({ animated: true, offset: 0 });
} }
if (trendingForAll || (prevChannelIds && channelIds)) {
if (prevChannelIds && channelIds) { const options = {
order_by: orderBy,
no_totals: true,
not_tags: MATURE_TAGS,
page: this.state.currentPage,
};
if (channelIds) { if (channelIds) {
this.setState({ subscriptionsView: true }); this.setState({ subscriptionsView: true });
options.channel_ids = channelIds;
}
if (trendingForAll) {
this.setState({ trendingForAllView: true });
} }
} else if (tags && tags.length > 0) {
this.setState({ subscriptionsView: false });
}
this.doClaimSearch(); claimSearch(options);
} else if (tags && tags.length > 0) {
this.setState({ subscriptionsView: false, trendingForAllView: false });
const additionalOptions = {};
if (orderBy && orderBy[0] === Constants.ORDER_BY_EFFECTIVE_AMOUNT && Constants.TIME_ALL !== time) {
additionalOptions.release_time = this.getReleaseTimeOption(time);
}
searchByTags(tags, orderBy, this.state.currentPage, additionalOptions);
}
}); });
} }
} }
buildClaimSearchOptions() {
const { orderBy, channelIds, showNsfwContent, tags, time } = this.props;
const { currentPage, subscriptionsView } = this.state;
const options = {
order_by: orderBy,
no_totals: true,
page: currentPage,
page_size: Constants.DEFAULT_PAGE_SIZE,
};
if (channelIds) {
options.channel_ids = channelIds;
} else if (tags && tags.length > 0) {
options.any_tags = tags;
}
if (!showNsfwContent) {
options.not_tags = MATURE_TAGS;
}
if (orderBy && orderBy[0] === Constants.ORDER_BY_EFFECTIVE_AMOUNT && Constants.TIME_ALL !== time) {
options.release_time = this.getReleaseTimeOption(time);
}
return options;
}
getReleaseTimeOption = time => { getReleaseTimeOption = time => {
return `>${Math.floor( return `>${Math.floor(
moment() moment()
@@ -105,27 +117,36 @@ class ClaimList extends React.PureComponent {
)}`; )}`;
}; };
doClaimSearch() {
const { claimSearch } = this.props;
const options = this.buildClaimSearchOptions();
claimSearch(options);
}
handleVerticalEndReached = () => { handleVerticalEndReached = () => {
// fetch more content // fetch more content
const { claimSearchByQuery, lastPageReached } = this.props; const { channelIds, claimSearch, claimSearchUris, orderBy, searchByTags, tags, time, uris } = this.props;
const { subscriptionsView, trendingForAllView } = this.state;
const options = this.buildClaimSearchOptions(); if ((claimSearchUris && claimSearchUris.length >= softLimit) || (uris && uris.length >= softLimit)) {
const claimSearchKey = createNormalizedClaimSearchKey(options); // don't fetch more than the specified limit to be displayed
const uris = claimSearchByQuery[claimSearchKey];
if (
lastPageReached[claimSearchKey] ||
((uris.length > 0 && uris.length < Constants.DEFAULT_PAGE_SIZE) || uris.length >= softLimit)
) {
return; return;
} }
this.setState({ currentPage: this.state.currentPage + 1 }, () => this.doClaimSearch()); this.setState({ currentPage: this.state.currentPage + 1 }, () => {
if (subscriptionsView || trendingForAllView) {
const options = {
order_by: orderBy,
no_totals: true,
not_tags: MATURE_TAGS,
page: this.state.currentPage,
};
if (subscriptionsView) {
options.channel_ids = channelIds;
}
claimSearch(options);
} else {
const additionalOptions = {};
if (orderBy && orderBy[0] === Constants.ORDER_BY_EFFECTIVE_AMOUNT && Constants.TIME_ALL !== time) {
additionalOptions.release_time = this.getReleaseTimeOption(time);
}
searchByTags(tags, orderBy, this.state.currentPage, additionalOptions);
}
});
}; };
appendMorePlaceholder = items => { appendMorePlaceholder = items => {
@@ -140,7 +161,7 @@ class ClaimList extends React.PureComponent {
if (tags.length === 1) { if (tags.length === 1) {
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_TAG, key: 'tagPage', params: { tag: tags[0] } }); navigation.navigate({ routeName: Constants.DRAWER_ROUTE_TAG, key: 'tagPage', params: { tag: tags[0] } });
} else { } else {
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_TRENDING, params: { filterForTags: true } }); navigation.navigate({ routeName: Constants.FULL_ROUTE_NAME_TRENDING });
} }
}; };
@@ -153,66 +174,22 @@ class ClaimList extends React.PureComponent {
); );
}; };
verticalListEmptyComponent = () => {
return (
<Text style={claimListStyle.noContentText}>
{__('No content to display at this time. Please check back later.')}
</Text>
);
};
renderVerticalItem = ({ item }) => {
const { hideChannel, navigation } = this.props;
return (
<FileListItem
key={item}
uri={item}
hideChannel={hideChannel}
style={claimListStyle.verticalListItem}
navigation={navigation}
/>
);
};
renderHorizontalItem = ({ item }) => {
const { navigation } = this.props;
return item === Constants.MORE_PLACEHOLDER ? (
this.renderMorePlaceholder()
) : (
<FileItem
style={discoverStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={item}
uri={normalizeURI(item)}
navigation={navigation}
showDetails
compactView={false}
/>
);
};
render() { render() {
const { const {
ListHeaderComponent, ListHeaderComponent,
loading, loading,
claimSearchLoading,
claimSearchUris,
morePlaceholder, morePlaceholder,
navigation, navigation,
orientation = Constants.ORIENTATION_VERTICAL, orientation = Constants.ORIENTATION_VERTICAL,
style, style,
claimSearchByQuery, uris,
} = this.props; } = this.props;
const { subscriptionsView } = this.state; const { subscriptionsView, trendingForAllView } = this.state;
const options = this.buildClaimSearchOptions();
const claimSearchKey = createNormalizedClaimSearchKey(options);
let uris = claimSearchByQuery[claimSearchKey];
if (uris) {
uris = uris.filter(uri => uri && uri.length > 0);
}
if (Constants.ORIENTATION_VERTICAL === orientation) { if (Constants.ORIENTATION_VERTICAL === orientation) {
const data = subscriptionsView || trendingForAllView ? claimSearchUris : uris;
return ( return (
<View style={style}> <View style={style}>
<FlatList <FlatList
@@ -220,21 +197,22 @@ class ClaimList extends React.PureComponent {
this.scrollView = ref; this.scrollView = ref;
}} }}
ListHeaderComponent={ListHeaderComponent} ListHeaderComponent={ListHeaderComponent}
ListEmptyComponent={loading ? null : this.verticalListEmptyComponent}
style={claimListStyle.verticalScrollContainer} style={claimListStyle.verticalScrollContainer}
contentContainerStyle={claimListStyle.verticalScrollPadding} contentContainerStyle={claimListStyle.verticalScrollPadding}
initialNumToRender={10} initialNumToRender={10}
maxToRenderPerBatch={20} maxToRenderPerBatch={20}
removeClippedSubviews removeClippedSubviews
renderItem={this.renderVerticalItem} renderItem={({ item }) => (
data={uris} <FileListItem key={item} uri={item} style={claimListStyle.verticalListItem} navigation={navigation} />
)}
data={data}
keyExtractor={(item, index) => item} keyExtractor={(item, index) => item}
onEndReached={this.handleVerticalEndReached} onEndReached={this.handleVerticalEndReached}
onEndReachedThreshold={0.2} onEndReachedThreshold={0.2}
/> />
{loading && ( {(((subscriptionsView || trendingForAllView) && claimSearchLoading) || loading) && (
<View style={claimListStyle.verticalLoading}> <View style={claimListStyle.verticalLoading}>
<ActivityIndicator size={'small'} color={Colors.NextLbryGreen} /> <ActivityIndicator size={'small'} color={Colors.LbryGreen} />
</View> </View>
)} )}
</View> </View>
@@ -245,7 +223,7 @@ class ClaimList extends React.PureComponent {
if (loading) { if (loading) {
return ( return (
<View style={discoverStyle.listLoading}> <View style={discoverStyle.listLoading}>
<ActivityIndicator size={'small'} color={Colors.NextLbryGreen} /> <ActivityIndicator size={'small'} color={Colors.LbryGreen} />
</View> </View>
); );
} }
@@ -257,7 +235,21 @@ class ClaimList extends React.PureComponent {
initialNumToRender={3} initialNumToRender={3}
maxToRenderPerBatch={3} maxToRenderPerBatch={3}
removeClippedSubviews removeClippedSubviews
renderItem={this.renderHorizontalItem} renderItem={({ item }) => {
return item === Constants.MORE_PLACEHOLDER ? (
this.renderMorePlaceholder()
) : (
<FileItem
style={discoverStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={item}
uri={normalizeURI(item)}
navigation={navigation}
showDetails
compactView={false}
/>
);
}}
horizontal horizontal
showsHorizontalScrollIndicator={false} showsHorizontalScrollIndicator={false}
data={uris ? this.appendMorePlaceholder(uris.slice(0, horizontalLimit)) : []} data={uris ? this.appendMorePlaceholder(uris.slice(0, horizontalLimit)) : []}
+5 -5
View File
@@ -20,7 +20,7 @@ class CustomRewardCard extends React.PureComponent<Props> {
if (error && error.trim().length > 0) { if (error && error.trim().length > 0) {
notify({ message: error }); notify({ message: error });
} else { } else {
notify({ message: __('Reward successfully claimed!') }); notify({ message: 'Reward successfully claimed!' });
this.setState({ rewardCode: '' }); this.setState({ rewardCode: '' });
} }
this.setState({ claimStarted: false }); this.setState({ claimStarted: false });
@@ -37,12 +37,12 @@ class CustomRewardCard extends React.PureComponent<Props> {
if (showVerification) { if (showVerification) {
showVerification(); showVerification();
} }
notify({ message: __('Unfortunately, you are not eligible to claim this reward at this time.') }); notify({ message: 'Unfortunately, you are not eligible to claim this reward at this time.' });
return; return;
} }
if (!rewardCode || rewardCode.trim().length === 0) { if (!rewardCode || rewardCode.trim().length === 0) {
notify({ message: __('Please enter a reward code to claim.') }); notify({ message: 'Please enter a reward code to claim.' });
return; return;
} }
@@ -60,9 +60,9 @@ class CustomRewardCard extends React.PureComponent<Props> {
{rewardIsPending && <ActivityIndicator size="small" color={Colors.NextLbryGreen} />} {rewardIsPending && <ActivityIndicator size="small" color={Colors.NextLbryGreen} />}
</View> </View>
<View style={rewardStyle.midCol}> <View style={rewardStyle.midCol}>
<Text style={rewardStyle.rewardTitle}>{__('Custom Code')}</Text> <Text style={rewardStyle.rewardTitle}>Custom Code</Text>
<Text style={rewardStyle.rewardDescription}> <Text style={rewardStyle.rewardDescription}>
{__('Are you a supermodel or rockstar that received a custom reward code? Claim it here.')} Are you a supermodel or rockstar that received a custom reward code? Claim it here.
</Text> </Text>
<View> <View>
+1 -15
View File
@@ -1,18 +1,4 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { doFetchChannelListMine, selectMyChannelClaims } from 'lbry-redux';
import { selectUser } from 'lbryinc';
import DrawerContent from './view'; import DrawerContent from './view';
const select = state => ({ export default connect()(DrawerContent);
channels: selectMyChannelClaims(state),
user: selectUser(state),
});
const perform = dispatch => ({
fetchChannelListMine: () => dispatch(doFetchChannelListMine()),
});
export default connect(
select,
perform
)(DrawerContent);
+23 -171
View File
@@ -1,184 +1,36 @@
import React from 'react'; import React from 'react';
import { DrawerItems, SafeAreaView } from 'react-navigation'; import { DrawerItems, SafeAreaView } from 'react-navigation';
import { Image, ScrollView, Text, TouchableOpacity, View } from 'react-native'; import { ScrollView } from 'react-native';
import Button from 'component/button'; import Constants from 'constants';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import Icon from 'react-native-vector-icons/FontAwesome5';
import channelIconStyle from 'styles/channelIcon';
import discoverStyle from 'styles/discover'; import discoverStyle from 'styles/discover';
const groupedMenuItems = {
'Find content': [
{ icon: 'hashtag', label: 'Your Tags', route: Constants.DRAWER_ROUTE_DISCOVER },
{ icon: 'heart', solid: true, label: 'Subscriptions', route: Constants.DRAWER_ROUTE_SUBSCRIPTIONS },
{ icon: 'globe-americas', label: 'All Content', route: Constants.DRAWER_ROUTE_TRENDING },
],
'Your content': [
{ icon: 'at', label: 'Channels', route: Constants.DRAWER_ROUTE_CHANNEL_CREATOR },
{ icon: 'download', label: 'Library', route: Constants.DRAWER_ROUTE_MY_LBRY },
{ icon: 'cloud-upload-alt', label: 'Publishes', route: Constants.DRAWER_ROUTE_PUBLISHES },
{ icon: 'upload', label: 'New Publish', route: Constants.DRAWER_ROUTE_PUBLISH },
],
Wallet: [
{ icon: 'wallet', label: 'Wallet', route: Constants.DRAWER_ROUTE_WALLET },
{ icon: 'award', label: 'Rewards', route: Constants.DRAWER_ROUTE_REWARDS },
],
Settings: [
{ icon: 'cog', label: 'Settings', route: Constants.DRAWER_ROUTE_SETTINGS },
{ icon: 'info', label: 'About', route: Constants.DRAWER_ROUTE_ABOUT },
],
};
const groupNames = Object.keys(groupedMenuItems);
class DrawerContent extends React.PureComponent { class DrawerContent extends React.PureComponent {
componentDidMount() {
const { fetchChannelListMine } = this.props;
fetchChannelListMine();
}
getAvatarImageUrl = () => {
const { channels = [] } = this.props;
if (channels) {
// get the first channel thumbnail found. In the future, allow the user to select a default channel thumbnail?
for (let i = 0; i < channels.length; i++) {
if (channels[i].value && channels[i].value.thumbnail) {
return channels[i].value.thumbnail.url;
}
}
}
return null;
};
launchSignInFlow = () => {
// for now, sync flow (email, then password input) will be the default sign in flow
const { navigation } = this.props;
navigation.navigate({
routeName: 'Verification',
key: 'verification',
params: { syncFlow: true, signInFlow: true },
});
};
render() { render() {
const { activeTintColor, navigation, user, onItemPress } = this.props; const props = this.props;
const { state } = navigation; const { navigation, onItemPress } = props;
const activeItemKey = state.routes[state.index] ? state.routes[state.index].key : null;
const signedIn = user && user.has_verified_email;
const avatarImageUrl = this.getAvatarImageUrl();
return ( return (
<View style={discoverStyle.drawerContentArea}> <ScrollView>
{false && ( <SafeAreaView style={discoverStyle.drawerContentContainer} forceInset={{ top: 'always', horizontal: 'never' }}>
<View style={discoverStyle.signInContainer}> <DrawerItems
{!signedIn && ( {...props}
<Button onItemPress={route => {
style={discoverStyle.signInButton} const { routeName } = route.route;
theme={'light'} if (Constants.FULL_ROUTE_NAME_DISCOVER === routeName) {
text={__('Sign in')} navigation.navigate({ routeName: Constants.DRAWER_ROUTE_DISCOVER });
onPress={this.launchSignInFlow} return;
/> }
)}
{signedIn && (
<View style={discoverStyle.signedIn}>
<View style={discoverStyle.signedInAvatar}>
{avatarImageUrl && (
<Image
style={discoverStyle.signedInAvatarImage}
resizeMode={'cover'}
source={{ uri: avatarImageUrl }}
/>
)}
{!avatarImageUrl && (
<Text style={channelIconStyle.autothumbCharacter}>
{user.primary_email.substring(0, 1).toUpperCase()}
</Text>
)}
</View>
<Text style={discoverStyle.signedInEmail} numberOfLines={1}>
{user.primary_email}
</Text>
</View>
)}
</View>
)}
<ScrollView contentContainerStyle={discoverStyle.menuScrollContent}> if (Constants.FULL_ROUTE_NAME_WALLET === routeName) {
<SafeAreaView navigation.navigate({ routeName: Constants.DRAWER_ROUTE_WALLET });
style={discoverStyle.drawerContentContainer} return;
forceInset={{ top: 'always', horizontal: 'never' }} }
>
{!signedIn && (
<TouchableOpacity
accessible
accessibilityLabel={__('Sign In')}
onPress={this.launchSignInFlow}
delayPressIn={0}
style={[discoverStyle.signInMenuItem, discoverStyle.signInMenuItemButton]}
>
<Text style={discoverStyle.signInMenuItemButtonText}>{__('SIGN IN')}</Text>
</TouchableOpacity>
)}
{signedIn && ( onItemPress(route);
<View style={[discoverStyle.signInMenuItem, discoverStyle.signInMenuItemBorder]}> }}
<Text style={discoverStyle.signInMenuItemText} numberOfLines={1}> />
{user.primary_email.toUpperCase()} </SafeAreaView>
</Text> </ScrollView>
</View>
)}
{groupNames.map(groupName => {
const menuItems = groupedMenuItems[groupName];
return (
<View key={groupName} style={discoverStyle.menuGroup}>
{groupNames[3] !== groupName && (
<Text key={`${groupName}-title`} style={discoverStyle.menuGroupName}>
{__(groupName)}
</Text>
)}
{menuItems.map(item => {
const focused =
activeItemKey === item.route ||
(activeItemKey === Constants.FULL_ROUTE_NAME_DISCOVER &&
item.route === Constants.DRAWER_ROUTE_DISCOVER) ||
(activeItemKey === Constants.FULL_ROUTE_NAME_WALLET &&
item.route === Constants.DRAWER_ROUTE_WALLET);
return (
<TouchableOpacity
accessible
accessibilityLabel={__(item.label)}
style={[
discoverStyle.menuItemTouchArea,
focused ? discoverStyle.menuItemTouchAreaFocused : null,
]}
key={item.label}
onPress={() => navigation.navigate({ routeName: item.route })}
delayPressIn={0}
>
<View style={discoverStyle.menuItemIcon}>
<Icon
name={item.icon}
size={16}
solid={item.solid}
color={focused ? activeTintColor : null}
/>
</View>
<Text style={[discoverStyle.menuItem, focused ? discoverStyle.menuItemFocused : null]}>
{__(item.label)}
</Text>
</TouchableOpacity>
);
})}
</View>
);
})}
</SafeAreaView>
</ScrollView>
</View>
); );
} }
} }
-4
View File
@@ -1,4 +0,0 @@
import { connect } from 'react-redux';
import EmptyStateView from './view';
export default connect()(EmptyStateView);
-26
View File
@@ -1,26 +0,0 @@
import React from 'react';
import { NativeModules, Text, View, Image, TouchableOpacity } from 'react-native';
import Button from '../button';
import emptyStateStyle from 'styles/emptyState';
class EmptyStateView extends React.PureComponent {
render() {
const { message, buttonText, inner, onButtonPress } = this.props;
return (
<View
style={[emptyStateStyle.container, inner ? emptyStateStyle.innerContainer : emptyStateStyle.outerContainer]}
>
<Image style={emptyStateStyle.image} resizeMode={'stretch'} source={require('../../assets/gerbil-happy.png')} />
<Text style={emptyStateStyle.message}>{message}</Text>
{buttonText && (
<View style={emptyStateStyle.buttonContainer}>
<Button style={emptyStateStyle.button} text={buttonText} onPress={onButtonPress} />
</View>
)}
</View>
);
}
}
export default EmptyStateView;
+9 -7
View File
@@ -12,8 +12,8 @@ class FileDownloadButton extends React.PureComponent {
} }
componentWillReceiveProps(nextProps) { componentWillReceiveProps(nextProps) {
// this.checkAvailability(nextProps.uri); //this.checkAvailability(nextProps.uri);
// this.restartDownload(nextProps); //this.restartDownload(nextProps);
} }
restartDownload(props) { restartDownload(props) {
@@ -50,11 +50,13 @@ class FileDownloadButton extends React.PureComponent {
if ((fileInfo && !fileInfo.stopped) || loading || downloading) { if ((fileInfo && !fileInfo.stopped) || loading || downloading) {
const progress = fileInfo && fileInfo.written_bytes ? (fileInfo.written_bytes / fileInfo.total_bytes) * 100 : 0, const progress = fileInfo && fileInfo.written_bytes ? (fileInfo.written_bytes / fileInfo.total_bytes) * 100 : 0,
label = fileInfo ? progress.toFixed(0) + '% complete' : __('Connecting...'); label = fileInfo ? progress.toFixed(0) + '% complete' : 'Connecting...';
return ( return (
<View style={[style, fileDownloadButtonStyle.container]}> <View style={[style, fileDownloadButtonStyle.container]}>
<View style={{ width: `${progress}%`, backgroundColor: '#ff0000', position: 'absolute', left: 0, top: 0 }} /> <View
style={{ width: `${progress}%`, backgroundColor: '#ff0000', position: 'absolute', left: 0, top: 0 }}
></View>
<Text style={fileDownloadButtonStyle.text}>{label}</Text> <Text style={fileDownloadButtonStyle.text}>{label}</Text>
</View> </View>
); );
@@ -62,14 +64,14 @@ class FileDownloadButton extends React.PureComponent {
if (!costInfo) { if (!costInfo) {
return ( return (
<View style={[style, fileDownloadButtonStyle.container]}> <View style={[style, fileDownloadButtonStyle.container]}>
<Text style={fileDownloadButtonStyle.text}>{__('Fetching cost info...')}</Text> <Text style={fileDownloadButtonStyle.text}>Fetching cost info...</Text>
</View> </View>
); );
} }
return ( return (
<Button <Button
icon={isPlayable ? 'play' : null} icon={isPlayable ? 'play' : null}
text={isPlayable ? __('Play') : isViewable ? __('View') : __('Download')} text={isPlayable ? 'Play' : isViewable ? 'View' : 'Download'}
onLayout={onButtonLayout} onLayout={onButtonLayout}
style={[style, fileDownloadButtonStyle.container]} style={[style, fileDownloadButtonStyle.container]}
onPress={() => { onPress={() => {
@@ -96,7 +98,7 @@ class FileDownloadButton extends React.PureComponent {
style={[style, fileDownloadButtonStyle.container]} style={[style, fileDownloadButtonStyle.container]}
onPress={openFile} onPress={openFile}
> >
<Text style={fileDownloadButtonStyle.text}>{isViewable ? __('View') : __('Open')}</Text> <Text style={fileDownloadButtonStyle.text}>{isViewable ? 'View' : 'Open'}</Text>
</TouchableOpacity> </TouchableOpacity>
); );
} }
+2 -6
View File
@@ -8,22 +8,18 @@ import {
makeSelectTitleForUri, makeSelectTitleForUri,
makeSelectIsUriResolving, makeSelectIsUriResolving,
makeSelectClaimIsNsfw, makeSelectClaimIsNsfw,
makeSelectShortUrlForUri,
} from 'lbry-redux'; } from 'lbry-redux';
import { selectBlackListedOutpoints, selectFilteredOutpoints, selectRewardContentClaimIds } from 'lbryinc'; import { selectRewardContentClaimIds } from 'lbryinc';
import { selectShowNsfw } from 'redux/selectors/settings'; import { selectShowNsfw } from 'redux/selectors/settings';
import FileItem from './view'; import FileItem from './view';
const select = (state, props) => ({ const select = (state, props) => ({
blackListedOutpoints: selectBlackListedOutpoints(state),
claim: makeSelectClaimForUri(props.uri)(state), claim: makeSelectClaimForUri(props.uri)(state),
fileInfo: makeSelectFileInfoForUri(props.uri)(state), fileInfo: makeSelectFileInfoForUri(props.uri)(state),
filteredOutpoints: selectFilteredOutpoints(state),
metadata: makeSelectMetadataForUri(props.uri)(state), metadata: makeSelectMetadataForUri(props.uri)(state),
rewardedContentClaimIds: selectRewardContentClaimIds(state), rewardedContentClaimIds: selectRewardContentClaimIds(state, props),
isResolvingUri: makeSelectIsUriResolving(props.uri)(state), isResolvingUri: makeSelectIsUriResolving(props.uri)(state),
obscureNsfw: !selectShowNsfw(state), obscureNsfw: !selectShowNsfw(state),
shortUrl: makeSelectShortUrlForUri(props.uri)(state),
thumbnail: makeSelectThumbnailForUri(props.uri)(state), thumbnail: makeSelectThumbnailForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state), title: makeSelectTitleForUri(props.uri)(state),
nsfw: makeSelectClaimIsNsfw(props.uri)(state), nsfw: makeSelectClaimIsNsfw(props.uri)(state),
+10 -37
View File
@@ -30,62 +30,39 @@ class FileItem extends React.PureComponent {
} }
navigateToFileUri = () => { navigateToFileUri = () => {
const { claim, navigation, uri, shortUrl } = this.props; const { navigation, uri } = this.props;
const normalizedUri = normalizeURI(uri); const normalizedUri = normalizeURI(uri);
if (NativeModules.Firebase) { if (NativeModules.Firebase) {
NativeModules.Firebase.track('explore_click', { uri: normalizedUri, short_url: shortUrl }); NativeModules.Firebase.track('explore_click', { uri: normalizedUri });
} }
navigateToUri(navigation, shortUrl || uri, null, false, claim ? claim.permanent_url : null); navigateToUri(navigation, normalizedUri);
}; };
render() { render() {
const { const {
blackListedOutpoints,
claim, claim,
title, title,
thumbnail, thumbnail,
fileInfo, fileInfo,
filteredOutpoints,
metadata, metadata,
isResolvingUri, isResolvingUri,
rewardedContentClaimIds, rewardedContentClaimIds,
style, style,
mediaStyle, mediaStyle,
navigation, navigation,
nsfw,
obscureNsfw,
showDetails, showDetails,
compactView, compactView,
titleBeforeThumbnail, titleBeforeThumbnail,
} = this.props; } = this.props;
if (claim && claim.value_type === 'channel') {
// don't display channels in the lists on the Your tags page
return null;
}
let shouldHide = false;
if (blackListedOutpoints || filteredOutpoints) {
const outpointsToHide = !blackListedOutpoints
? filteredOutpoints
: blackListedOutpoints.concat(filteredOutpoints);
shouldHide = outpointsToHide.some(outpoint => outpoint.txid === claim.txid && outpoint.nout === claim.nout);
}
if (shouldHide) {
// don't display blacklisted or filtered outpoints on the Your tags page
return null;
}
const uri = normalizeURI(this.props.uri); const uri = normalizeURI(this.props.uri);
const obscure = obscureNsfw && nsfw; const obscureNsfw = this.props.obscureNsfw && metadata && metadata.nsfw;
const isRewardContent = claim && rewardedContentClaimIds.includes(claim.claim_id); const isRewardContent = claim && rewardedContentClaimIds.includes(claim.claim_id);
const signingChannel = claim ? claim.signing_channel : null; const signingChannel = claim ? claim.signing_channel : null;
const channelName = signingChannel ? signingChannel.name : null; const channelName = signingChannel ? signingChannel.name : null;
const channelClaimId = signingChannel ? signingChannel.claim_id : null; const channelClaimId = signingChannel ? signingChannel.claim_id : null;
const fullChannelUri = channelClaimId ? `${channelName}#${channelClaimId}` : channelName; const fullChannelUri = channelClaimId ? `${channelName}#${channelClaimId}` : channelName;
const shortChannelUri = signingChannel ? signingChannel.short_url : null;
const height = claim ? claim.height : null; const height = claim ? claim.height : null;
const duration = claim && claim.value && claim.value.video ? claim.value.video.duration : null;
return ( return (
<View style={style}> <View style={style}>
@@ -96,13 +73,14 @@ class FileItem extends React.PureComponent {
</Text> </Text>
)} )}
<FileItemMedia <FileItemMedia
duration={duration}
title={title} title={title}
thumbnail={thumbnail} thumbnail={thumbnail}
blurRadius={obscureNsfw ? 15 : 0}
resizeMode="cover" resizeMode="cover"
isResolvingUri={isResolvingUri} isResolvingUri={isResolvingUri}
style={mediaStyle} style={mediaStyle}
/> />
{!compactView && fileInfo && fileInfo.completed && fileInfo.download_path && ( {!compactView && fileInfo && fileInfo.completed && fileInfo.download_path && (
<Icon style={discoverStyle.downloadedIcon} solid color={Colors.NextLbryGreen} name={'folder'} size={16} /> <Icon style={discoverStyle.downloadedIcon} solid color={Colors.NextLbryGreen} name={'folder'} size={16} />
)} )}
@@ -124,22 +102,17 @@ class FileItem extends React.PureComponent {
style={discoverStyle.channelName} style={discoverStyle.channelName}
text={channelName} text={channelName}
onPress={() => { onPress={() => {
navigateToUri( navigateToUri(navigation, normalizeURI(fullChannelUri));
navigation,
normalizeURI(shortChannelUri || fullChannelUri),
null,
false,
fullChannelUri
);
}} }}
/> />
)} )}
{!channelName && !isResolvingUri && <Text style={discoverStyle.anonChannelName}>{__('Anonymous')}</Text>}
<DateTime style={discoverStyle.dateTime} textStyle={discoverStyle.dateTimeText} timeAgo uri={uri} /> <DateTime style={discoverStyle.dateTime} textStyle={discoverStyle.dateTimeText} timeAgo uri={uri} />
</View> </View>
)} )}
</TouchableOpacity> </TouchableOpacity>
{obscure && <NsfwOverlay onPress={() => navigation.navigate({ routeName: 'Settings', key: 'settingsPage' })} />} {obscureNsfw && (
<NsfwOverlay onPress={() => navigation.navigate({ routeName: 'Settings', key: 'settingsPage' })} />
)}
</View> </View>
); );
} }
+32 -39
View File
@@ -2,26 +2,24 @@ import React from 'react';
import { ActivityIndicator, Image, Text, View } from 'react-native'; import { ActivityIndicator, Image, Text, View } from 'react-native';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import FastImage from 'react-native-fast-image'; import FastImage from 'react-native-fast-image';
import VideoDuration from 'component/videoDuration';
import autothumbStyle from 'styles/autothumb';
import fileItemMediaStyle from 'styles/fileItemMedia'; import fileItemMediaStyle from 'styles/fileItemMedia';
class FileItemMedia extends React.PureComponent { class FileItemMedia extends React.PureComponent {
static AUTO_THUMB_STYLES = [ static AUTO_THUMB_STYLES = [
autothumbStyle.autothumbPurple, fileItemMediaStyle.autothumbPurple,
autothumbStyle.autothumbRed, fileItemMediaStyle.autothumbRed,
autothumbStyle.autothumbPink, fileItemMediaStyle.autothumbPink,
autothumbStyle.autothumbIndigo, fileItemMediaStyle.autothumbIndigo,
autothumbStyle.autothumbBlue, fileItemMediaStyle.autothumbBlue,
autothumbStyle.autothumbLightBlue, fileItemMediaStyle.autothumbLightBlue,
autothumbStyle.autothumbCyan, fileItemMediaStyle.autothumbCyan,
autothumbStyle.autothumbTeal, fileItemMediaStyle.autothumbTeal,
autothumbStyle.autothumbGreen, fileItemMediaStyle.autothumbGreen,
autothumbStyle.autothumbYellow, fileItemMediaStyle.autothumbYellow,
autothumbStyle.autothumbOrange, fileItemMediaStyle.autothumbOrange,
]; ];
state = { state: {
imageLoadFailed: false, imageLoadFailed: false,
}; };
@@ -50,7 +48,7 @@ class FileItemMedia extends React.PureComponent {
return false; return false;
} }
if (thumbnail.substring(0, 7) !== 'http://' && thumbnail.substring(0, 8) !== 'https://') { if (thumbnail.substring(0, 7) != 'http://' && thumbnail.substring(0, 8) != 'https://') {
return false; return false;
} }
@@ -59,35 +57,37 @@ class FileItemMedia extends React.PureComponent {
render() { render() {
let style = this.props.style; let style = this.props.style;
const { duration, isResolvingUri, thumbnail, title, resizeMode } = this.props; const { blurRadius, isResolvingUri, thumbnail, title, resizeMode } = this.props;
const atStyle = this.state.autoThumbStyle; const atStyle = this.state.autoThumbStyle;
if (this.isThumbnailValid(thumbnail) && !this.state.imageLoadFailed) { if (this.isThumbnailValid(thumbnail) && !this.state.imageLoadFailed) {
if (style == null) { if (style == null) {
style = fileItemMediaStyle.thumbnail; style = fileItemMediaStyle.thumbnail;
} }
return ( if (blurRadius > 0) {
<View style={style}> // No blur radius support in FastImage yet
<FastImage return (
<Image
source={{ uri: thumbnail }} source={{ uri: thumbnail }}
onError={() => this.setState({ imageLoadFailed: true })} blurRadius={blurRadius}
resizeMode={this.getFastImageResizeMode(resizeMode)} resizeMode={resizeMode ? resizeMode : 'cover'}
style={fileItemMediaStyle.image} style={style}
/> />
{duration && ( );
<VideoDuration }
duration={duration}
style={fileItemMediaStyle.duration} return (
textStyle={fileItemMediaStyle.durationText} <FastImage
/> source={{ uri: thumbnail }}
)} onError={() => this.setState({ imageLoadFailed: true })}
</View> resizeMode={this.getFastImageResizeMode(resizeMode)}
style={style}
/>
); );
} }
return ( return (
<View style={[style || fileItemMediaStyle.autothumb, atStyle]}> <View style={[style ? style : fileItemMediaStyle.autothumb, atStyle]}>
{isResolvingUri && ( {isResolvingUri && (
<View style={fileItemMediaStyle.resolving}> <View style={fileItemMediaStyle.resolving}>
<ActivityIndicator color={Colors.White} size={'large'} /> <ActivityIndicator color={Colors.White} size={'large'} />
@@ -104,13 +104,6 @@ class FileItemMedia extends React.PureComponent {
.toUpperCase()} .toUpperCase()}
</Text> </Text>
)} )}
{duration && (
<VideoDuration
duration={duration}
style={fileItemMediaStyle.duration}
textStyle={fileItemMediaStyle.durationText}
/>
)}
</View> </View>
); );
} }
+31 -31
View File
@@ -53,39 +53,39 @@ class FileList extends React.PureComponent<Props, State> {
dateNew: fileInfos => dateNew: fileInfos =>
this.props.sortByHeight this.props.sortByHeight
? fileInfos.slice().sort((fileInfo1, fileInfo2) => { ? fileInfos.slice().sort((fileInfo1, fileInfo2) => {
if (fileInfo1.pending) { if (fileInfo1.pending) {
return -1; return -1;
} }
const height1 = this.props.claimsById[fileInfo1.claim_id] const height1 = this.props.claimsById[fileInfo1.claim_id]
? this.props.claimsById[fileInfo1.claim_id].height ? this.props.claimsById[fileInfo1.claim_id].height
: 0; : 0;
const height2 = this.props.claimsById[fileInfo2.claim_id] const height2 = this.props.claimsById[fileInfo2.claim_id]
? this.props.claimsById[fileInfo2.claim_id].height ? this.props.claimsById[fileInfo2.claim_id].height
: 0; : 0;
if (height1 > height2) { if (height1 > height2) {
return -1; return -1;
} else if (height1 < height2) { } else if (height1 < height2) {
return 1; return 1;
} }
return 0; return 0;
}) })
: [...fileInfos].reverse(), : [...fileInfos].reverse(),
dateOld: fileInfos => dateOld: fileInfos =>
this.props.sortByHeight this.props.sortByHeight
? fileInfos.slice().sort((fileInfo1, fileInfo2) => { ? fileInfos.slice().sort((fileInfo1, fileInfo2) => {
const height1 = this.props.claimsById[fileInfo1.claim_id] const height1 = this.props.claimsById[fileInfo1.claim_id]
? this.props.claimsById[fileInfo1.claim_id].height ? this.props.claimsById[fileInfo1.claim_id].height
: 999999; : 999999;
const height2 = this.props.claimsById[fileInfo2.claim_id] const height2 = this.props.claimsById[fileInfo2.claim_id]
? this.props.claimsById[fileInfo2.claim_id].height ? this.props.claimsById[fileInfo2.claim_id].height
: 999999; : 999999;
if (height1 < height2) { if (height1 < height2) {
return -1; return -1;
} else if (height1 > height2) { } else if (height1 > height2) {
return 1; return 1;
} }
return 0; return 0;
}) })
: fileInfos, : fileInfos,
title: fileInfos => title: fileInfos =>
fileInfos.slice().sort((fileInfo1, fileInfo2) => { fileInfos.slice().sort((fileInfo1, fileInfo2) => {
@@ -160,7 +160,7 @@ class FileList extends React.PureComponent<Props, State> {
// This is unfortunate // This is unfortunate
// https://github.com/lbryio/lbry/issues/1159 // https://github.com/lbryio/lbry/issues/1159
const name = claimName || claimNameDownloaded; const name = claimName || claimNameDownloaded;
uriParams.claimName = name; uriParams.contentName = name;
uriParams.claimId = claimId; uriParams.claimId = claimId;
const uri = buildURI(uriParams); const uri = buildURI(uriParams);
@@ -179,7 +179,7 @@ class FileList extends React.PureComponent<Props, State> {
style={fileListStyle.fileItem} style={fileListStyle.fileItem}
uri={item} uri={item}
navigation={navigation} navigation={navigation}
showDetails showDetails={true}
compactView={false} compactView={false}
/> />
)} )}
+1 -6
View File
@@ -5,12 +5,10 @@ import {
makeSelectMetadataForUri, makeSelectMetadataForUri,
makeSelectFileInfoForUri, makeSelectFileInfoForUri,
makeSelectIsUriResolving, makeSelectIsUriResolving,
makeSelectClaimIsNsfw,
makeSelectShortUrlForUri,
makeSelectTitleForUri, makeSelectTitleForUri,
makeSelectThumbnailForUri, makeSelectThumbnailForUri,
} from 'lbry-redux'; } from 'lbry-redux';
import { selectBlackListedOutpoints, selectFilteredOutpoints, selectRewardContentClaimIds } from 'lbryinc'; import { selectBlackListedOutpoints, selectFilteredOutpoints } from 'lbryinc';
import { selectShowNsfw } from 'redux/selectors/settings'; import { selectShowNsfw } from 'redux/selectors/settings';
import FileListItem from './view'; import FileListItem from './view';
@@ -21,11 +19,8 @@ const select = (state, props) => ({
filteredOutpoints: selectFilteredOutpoints(state), filteredOutpoints: selectFilteredOutpoints(state),
isDownloaded: !!makeSelectFileInfoForUri(props.uri)(state), isDownloaded: !!makeSelectFileInfoForUri(props.uri)(state),
metadata: makeSelectMetadataForUri(props.uri)(state), metadata: makeSelectMetadataForUri(props.uri)(state),
nsfw: makeSelectClaimIsNsfw(props.uri)(state),
isResolvingUri: makeSelectIsUriResolving(props.uri)(state), isResolvingUri: makeSelectIsUriResolving(props.uri)(state),
obscureNsfw: !selectShowNsfw(state), obscureNsfw: !selectShowNsfw(state),
rewardedContentClaimIds: selectRewardContentClaimIds(state),
shortUrl: makeSelectShortUrlForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state), title: makeSelectTitleForUri(props.uri)(state),
thumbnail: makeSelectThumbnailForUri(props.uri)(state), thumbnail: makeSelectThumbnailForUri(props.uri)(state),
}); });
+18 -92
View File
@@ -3,7 +3,6 @@ import { normalizeURI, parseURI } from 'lbry-redux';
import { ActivityIndicator, Platform, Text, TouchableOpacity, View } from 'react-native'; import { ActivityIndicator, Platform, Text, TouchableOpacity, View } from 'react-native';
import { navigateToUri, formatBytes } from 'utils/helper'; import { navigateToUri, formatBytes } from 'utils/helper';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import DateTime from 'component/dateTime'; import DateTime from 'component/dateTime';
import FileItemMedia from 'component/fileItemMedia'; import FileItemMedia from 'component/fileItemMedia';
import Icon from 'react-native-vector-icons/FontAwesome5'; import Icon from 'react-native-vector-icons/FontAwesome5';
@@ -13,10 +12,6 @@ import ProgressBar from 'component/progressBar';
import fileListStyle from 'styles/fileList'; import fileListStyle from 'styles/fileList';
class FileListItem extends React.PureComponent { class FileListItem extends React.PureComponent {
state = {
url: null,
};
getStorageForFileInfo = fileInfo => { getStorageForFileInfo = fileInfo => {
if (!fileInfo.completed) { if (!fileInfo.completed) {
const written = formatBytes(fileInfo.written_bytes); const written = formatBytes(fileInfo.written_bytes);
@@ -40,36 +35,15 @@ class FileListItem extends React.PureComponent {
}; };
componentDidMount() { componentDidMount() {
const { claim, resolveUri, uri, batchResolve } = this.props; const { claim, resolveUri, uri } = this.props;
if (!claim && !batchResolve) { if (!claim) {
resolveUri(uri); resolveUri(uri);
} }
} }
componentDidUpdate() {
const { claim, resolveUri, uri } = this.props;
if (!claim && uri !== this.state.url) {
this.setState({ url: uri }, () => resolveUri(uri));
}
}
defaultOnPress = () => { defaultOnPress = () => {
const { autoplay, claim, featuredResult, navigation, uri, shortUrl } = this.props; const { navigation, uri } = this.props;
navigateToUri(navigation, uri);
if (featuredResult && !claim) {
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_PUBLISH, params: { vanityUrl: uri.trim() } });
} else {
navigateToUri(navigation, shortUrl || uri, { autoplay }, false, claim ? claim.permanent_url : null);
}
};
onPressHandler = () => {
const { claim, onPress } = this.props;
if (onPress) {
onPress(claim);
} else {
this.defaultOnPress();
}
}; };
render() { render() {
@@ -79,84 +53,50 @@ class FileListItem extends React.PureComponent {
fileInfo, fileInfo,
filteredOutpoints, filteredOutpoints,
metadata, metadata,
nsfw,
featuredResult, featuredResult,
isResolvingUri, isResolvingUri,
isDownloaded, isDownloaded,
style, style,
obscureNsfw,
onPress, onPress,
navigation, navigation,
rewardedContentClaimIds,
thumbnail, thumbnail,
hideChannel, hideChannel,
onLongPress,
selected,
title, title,
} = this.props; } = this.props;
const uri = normalizeURI(this.props.uri); const uri = normalizeURI(this.props.uri);
const obscure = obscureNsfw && nsfw; const obscureNsfw = this.props.obscureNsfw && metadata && metadata.nsfw;
const isResolving = !fileInfo && isResolvingUri; const isResolving = !fileInfo && isResolvingUri;
const duration = claim && claim.value && claim.value.video ? claim.value.video.duration : null;
let name, let name, channel, height, channelClaimId, fullChannelUri, shouldHide, signingChannel;
channel,
height,
isRewardContent,
channelClaimId,
fullChannelUri,
shortChannelUri,
shouldHide,
signingChannel;
if (claim) { if (claim) {
name = claim.name; name = claim.name;
signingChannel = claim.signing_channel; signingChannel = claim.signing_channel;
channel = signingChannel ? signingChannel.name : null; channel = signingChannel ? signingChannel.name : null;
height = claim.height; height = claim.height;
isRewardContent = rewardedContentClaimIds.includes(claim.claim_id);
channelClaimId = signingChannel ? signingChannel.claim_id : null; channelClaimId = signingChannel ? signingChannel.claim_id : null;
fullChannelUri = channelClaimId ? `${channel}#${channelClaimId}` : channel; fullChannelUri = channelClaimId ? `${channel}#${channelClaimId}` : channel;
shortChannelUri = signingChannel ? signingChannel.short_url : null;
if (blackListedOutpoints || filteredOutpoints) { if (blackListedOutpoints || filteredOutpoints) {
const outpointsToHide = !blackListedOutpoints const outpointsToHide = blackListedOutpoints.concat(filteredOutpoints);
? filteredOutpoints
: blackListedOutpoints.concat(filteredOutpoints);
shouldHide = outpointsToHide.some(outpoint => outpoint.txid === claim.txid && outpoint.nout === claim.nout); shouldHide = outpointsToHide.some(outpoint => outpoint.txid === claim.txid && outpoint.nout === claim.nout);
} }
// TODO: hide channels on tag pages?
// shouldHide = 'channel' === claim.value_type;
} }
if (shouldHide || (!isResolvingUri && !claim && !featuredResult)) { if (shouldHide || (featuredResult && !isResolvingUri && !claim && !title && !name)) {
return null; return null;
} }
return ( return (
<View style={style}> <View style={style}>
<TouchableOpacity <TouchableOpacity style={style} onPress={onPress || this.defaultOnPress}>
style={style}
onPress={this.onPressHandler}
onLongPress={() => {
if (onLongPress) {
onLongPress(claim);
}
}}
>
<FileItemMedia <FileItemMedia
style={fileListStyle.thumbnail} style={fileListStyle.thumbnail}
duration={duration} blurRadius={obscureNsfw ? 15 : 0}
resizeMode="cover" resizeMode="cover"
title={title || name || normalizeURI(uri).substring(7)} title={title || name}
thumbnail={thumbnail} thumbnail={thumbnail}
/> />
{selected && (
<View style={fileListStyle.selectedOverlay}>
<Icon name={'check-circle'} solid color={Colors.NextLbryGreen} size={32} />
</View>
)}
{fileInfo && fileInfo.completed && fileInfo.download_path && ( {fileInfo && fileInfo.completed && fileInfo.download_path && (
<Icon style={fileListStyle.downloadedIcon} solid color={Colors.NextLbryGreen} name={'folder'} size={16} /> <Icon style={fileListStyle.downloadedIcon} solid color={Colors.NextLbryGreen} name={'folder'} size={16} />
)} )}
@@ -179,32 +119,16 @@ class FileListItem extends React.PureComponent {
)} )}
{(title || name) && ( {(title || name) && (
<View style={fileListStyle.titleContainer}> <Text style={featuredResult ? fileListStyle.featuredTitle : fileListStyle.title}>
<Text style={featuredResult ? fileListStyle.featuredTitle : fileListStyle.title}> {this.formatTitle(title) || this.formatTitle(name)}
{this.formatTitle(title) || this.formatTitle(name)} </Text>
</Text>
{isRewardContent && <Icon style={fileListStyle.rewardIcon} name="award" size={12} />}
</View>
)} )}
{featuredResult && !isResolving && !claim && (
<View style={fileListStyle.titleContainer}>
<Text style={fileListStyle.featuredTitle}>{__('Nothing here. Publish something!')}</Text>
</View>
)}
{channel && !hideChannel && ( {channel && !hideChannel && (
<Link <Link
style={fileListStyle.publisher} style={fileListStyle.publisher}
text={channel} text={channel}
onPress={() => { onPress={() => {
navigateToUri( navigateToUri(navigation, normalizeURI(fullChannelUri));
navigation,
normalizeURI(shortChannelUri || fullChannelUri),
null,
false,
fullChannelUri
);
}} }}
/> />
)} )}
@@ -231,7 +155,9 @@ class FileListItem extends React.PureComponent {
)} )}
</View> </View>
</TouchableOpacity> </TouchableOpacity>
{obscure && <NsfwOverlay onPress={() => navigation.navigate({ routeName: 'Settings', key: 'settingsPage' })} />} {obscureNsfw && (
<NsfwOverlay onPress={() => navigation.navigate({ routeName: 'Settings', key: 'settingsPage' })} />
)}
</View> </View>
); );
} }
+4 -9
View File
@@ -42,16 +42,11 @@ class CreditAmount extends React.PureComponent {
let amountText; let amountText;
if (this.props.showFree && parseFloat(this.props.amount) === 0) { if (this.props.showFree && parseFloat(this.props.amount) === 0) {
amountText = __('FREE'); amountText = 'FREE';
} else { } else {
if (this.props.label) { if (this.props.label) {
const label = const label =
typeof this.props.label === 'string' typeof this.props.label === 'string' ? this.props.label : parseFloat(amount) == 1 ? 'credit' : 'credits';
? this.props.label
: parseFloat(amount) === 1
? __('credit')
: __('credits');
// TODO: handling singular / plural in other languages?
amountText = `${formattedAmount} ${label}`; amountText = `${formattedAmount} ${label}`;
} else { } else {
@@ -62,14 +57,14 @@ class CreditAmount extends React.PureComponent {
} }
} }
/* {this.props.isEstimate ? ( /*{this.props.isEstimate ? (
<span <span
className="credit-amount__estimate" className="credit-amount__estimate"
title={__('This is an estimate and does not include data fees')} title={__('This is an estimate and does not include data fees')}
> >
* *
</span> </span>
) : null} */ ) : null}*/
return <Text style={style}>{amountText}</Text>; return <Text style={style}>{amountText}</Text>;
} }
} }
+2 -2
View File
@@ -9,8 +9,8 @@ class FileRewardsDriver extends React.PureComponent<Props> {
return ( return (
<TouchableOpacity style={filePageStyle.rewardDriverCard} onPress={() => navigation.navigate('Rewards')}> <TouchableOpacity style={filePageStyle.rewardDriverCard} onPress={() => navigation.navigate('Rewards')}>
<Icon name="award" size={16} style={filePageStyle.rewardDriverIcon} /> <Icon name="award" size={16} style={filePageStyle.rewardIcon} />
<Text style={filePageStyle.rewardDriverText}>{__('Earn some credits to access this content.')}</Text> <Text style={filePageStyle.rewardDriverText}>Earn some credits to access this content.</Text>
</TouchableOpacity> </TouchableOpacity>
); );
} }
+2 -3
View File
@@ -23,7 +23,7 @@ class FloatingWalletBalance extends React.PureComponent<Props> {
style={floatingButtonStyle.pendingContainer} style={floatingButtonStyle.pendingContainer}
onPress={() => navigation && navigation.navigate({ routeName: 'Rewards' })} onPress={() => navigation && navigation.navigate({ routeName: 'Rewards' })}
> >
<Icon name="award" size={14} style={floatingButtonStyle.rewardIcon} /> <Icon name="award" size={18} style={floatingButtonStyle.rewardIcon} />
<Text style={floatingButtonStyle.text}>{unclaimedRewardAmount}</Text> <Text style={floatingButtonStyle.text}>{unclaimedRewardAmount}</Text>
</TouchableOpacity> </TouchableOpacity>
)} )}
@@ -31,10 +31,9 @@ class FloatingWalletBalance extends React.PureComponent<Props> {
style={floatingButtonStyle.container} style={floatingButtonStyle.container}
onPress={() => navigation && navigation.navigate({ routeName: 'WalletStack' })} onPress={() => navigation && navigation.navigate({ routeName: 'WalletStack' })}
> >
<Icon name="coins" size={12} style={floatingButtonStyle.balanceIcon} />
{isNaN(balance) && <ActivityIndicator size="small" color={Colors.White} />} {isNaN(balance) && <ActivityIndicator size="small" color={Colors.White} />}
{(!isNaN(balance) || balance === 0) && ( {(!isNaN(balance) || balance === 0) && (
<Text style={floatingButtonStyle.text}>{formatCredits(parseFloat(balance), 1, true)}</Text> <Text style={floatingButtonStyle.text}>{formatCredits(parseFloat(balance), 2) + ' LBC'}</Text>
)} )}
</TouchableOpacity> </TouchableOpacity>
</View> </View>
+1 -8
View File
@@ -418,13 +418,6 @@ class MediaPlayer extends React.PureComponent {
: mediaPlayerStyle.containedTrackingControls, : mediaPlayerStyle.containedTrackingControls,
]; ];
const seekerCircleStyle = [this.state.seeking ? mediaPlayerStyle.bigSeekerCircle : mediaPlayerStyle.seekerCircle];
if (!this.state.seeking) {
seekerCircleStyle.push(
this.state.fullscreenMode ? mediaPlayerStyle.seekerCircleTopFs : mediaPlayerStyle.seekerCircleTop
);
}
return ( return (
<View style={styles} onLayout={onLayout}> <View style={styles} onLayout={onLayout}>
<Video <Video
@@ -489,7 +482,7 @@ class MediaPlayer extends React.PureComponent {
]} ]}
{...this.seekResponder.panHandlers} {...this.seekResponder.panHandlers}
> >
<View style={seekerCircleStyle} /> <View style={this.state.seeking ? mediaPlayerStyle.bigSeekerCircle : mediaPlayerStyle.seekerCircle} />
</View> </View>
<TouchableOpacity <TouchableOpacity
style={[ style={[
+1 -1
View File
@@ -46,7 +46,7 @@ export default class ModalPicker extends React.PureComponent {
onPress={() => onItemSelected(item)} onPress={() => onItemSelected(item)}
> >
{item.icon && <Icon style={modalPickerStyle.itemIcon} name={item.icon} size={16} />} {item.icon && <Icon style={modalPickerStyle.itemIcon} name={item.icon} size={16} />}
<Text style={modalPickerStyle.itemLabel}>{__(item.label)}</Text> <Text style={modalPickerStyle.itemLabel}>{item.label}</Text>
{selectedItem && selectedItem.name === item.name && ( {selectedItem && selectedItem.name === item.name && (
<Icon style={modalPickerStyle.itemSelected} name={'check'} color={Colors.LbryGreen} size={16} /> <Icon style={modalPickerStyle.itemSelected} name={'check'} color={Colors.LbryGreen} size={16} />
)} )}
@@ -1,4 +0,0 @@
import { connect } from 'react-redux';
import ModalSuggestedSubscriptions from './view';
export default connect()(ModalSuggestedSubscriptions);
@@ -1,26 +0,0 @@
import React from 'react';
import { ScrollView, Text, TouchableOpacity, View } from 'react-native';
import modalStyle from 'styles/modal';
import subscriptionsStyle from 'styles/subscriptions';
import Button from 'component/button';
import Colors from 'styles/colors';
import SuggestedSubscriptions from 'component/suggestedSubscriptions';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import Icon from 'react-native-vector-icons/FontAwesome5';
export default class ModalSuggestedSubcriptions extends React.PureComponent {
render() {
const { navigation, onDonePress, onOverlayPress } = this.props;
return (
<TouchableOpacity style={modalStyle.overlay} activeOpacity={1} onPress={onOverlayPress}>
<TouchableOpacity style={[modalStyle.container, subscriptionsStyle.modalContainer]} activeOpacity={1}>
<SuggestedSubscriptions inModal navigation={navigation} />
<View style={modalStyle.buttons}>
<Button style={modalStyle.doneButton} text={__('Done')} onPress={onDonePress} />
</View>
</TouchableOpacity>
</TouchableOpacity>
);
}
}
+5 -18
View File
@@ -8,8 +8,7 @@ import Icon from 'react-native-vector-icons/FontAwesome5';
import Tag from 'component/tag'; import Tag from 'component/tag';
import TagSearch from 'component/tagSearch'; import TagSearch from 'component/tagSearch';
import modalTagSelectorStyle from 'styles/modalTagSelector'; import modalTagSelectorStyle from 'styles/modalTagSelector';
import { __ } from 'utils/helper';
const minimumTags = 2;
export default class ModalTagSelector extends React.PureComponent { export default class ModalTagSelector extends React.PureComponent {
handleAddTag = tag => { handleAddTag = tag => {
@@ -24,9 +23,6 @@ export default class ModalTagSelector extends React.PureComponent {
} }
this.props.doToggleTagFollow(tag); this.props.doToggleTagFollow(tag);
if (window.persistor) {
window.persistor.flush();
}
NativeModules.Firebase.track('tag_follow', { tag }); NativeModules.Firebase.track('tag_follow', { tag });
}; };
@@ -35,16 +31,7 @@ export default class ModalTagSelector extends React.PureComponent {
return; return;
} }
const { followedTags, doToast } = this.props;
if (followedTags.length <= minimumTags) {
doToast({ message: __(`You can follow a minimum of ${minimumTags} tags.`) });
return;
}
this.props.doToggleTagFollow(tag); this.props.doToggleTagFollow(tag);
if (window.persistor) {
window.persistor.flush();
}
NativeModules.Firebase.track('tag_unfollow', { tag }); NativeModules.Firebase.track('tag_unfollow', { tag });
}; };
@@ -54,9 +41,9 @@ export default class ModalTagSelector extends React.PureComponent {
return ( return (
<TouchableOpacity style={modalTagSelectorStyle.overlay} activeOpacity={1} onPress={onOverlayPress}> <TouchableOpacity style={modalTagSelectorStyle.overlay} activeOpacity={1} onPress={onOverlayPress}>
<TouchableOpacity style={modalTagSelectorStyle.container} activeOpacity={1}> <View style={modalTagSelectorStyle.container}>
<View style={modalTagSelectorStyle.titleRow}> <View style={modalTagSelectorStyle.titleRow}>
<Text style={modalTagSelectorStyle.title}>{__('Customize your tags')}</Text> <Text style={modalTagSelectorStyle.title}>Customize your tags</Text>
</View> </View>
<View style={modalTagSelectorStyle.tagList}> <View style={modalTagSelectorStyle.tagList}>
{tags && {tags &&
@@ -72,9 +59,9 @@ export default class ModalTagSelector extends React.PureComponent {
</View> </View>
<TagSearch handleAddTag={this.handleAddTag} selectedTags={tags} /> <TagSearch handleAddTag={this.handleAddTag} selectedTags={tags} />
<View style={modalTagSelectorStyle.buttons}> <View style={modalTagSelectorStyle.buttons}>
<Button style={modalTagSelectorStyle.doneButton} text={__('Done')} onPress={onDonePress} /> <Button style={modalTagSelectorStyle.doneButton} text={'Done'} onPress={onDonePress} />
</View> </View>
</TouchableOpacity> </View>
</TouchableOpacity> </TouchableOpacity>
); );
} }
+2 -2
View File
@@ -5,9 +5,9 @@ import discoverStyle from '../../styles/discover';
class NsfwOverlay extends React.PureComponent { class NsfwOverlay extends React.PureComponent {
render() { render() {
return ( return (
<TouchableOpacity style={discoverStyle.overlay} activeOpacity={1} onPress={this.props.onPress}> <TouchableOpacity style={discoverStyle.overlay} activeOpacity={0.95} onPress={this.props.onPress}>
<Text style={discoverStyle.overlayText}> <Text style={discoverStyle.overlayText}>
{__('This content is Not Safe For Work. To view adult content, please change your Settings.')} This content is Not Safe For Work. To view adult content, please change your Settings.
</Text> </Text>
</TouchableOpacity> </TouchableOpacity>
); );
+3 -7
View File
@@ -4,21 +4,17 @@ import Colors from 'styles/colors';
import Icon from 'react-native-vector-icons/FontAwesome5'; import Icon from 'react-native-vector-icons/FontAwesome5';
import publishStyle from 'styles/publish'; import publishStyle from 'styles/publish';
class PublishRewardsDriver extends React.PureComponent<Props> { class PublishRewadsDriver extends React.PureComponent<Props> {
render() { render() {
const { navigation } = this.props; const { navigation } = this.props;
return ( return (
<TouchableOpacity style={publishStyle.rewardDriverCard} onPress={() => navigation.navigate('Rewards')}> <TouchableOpacity style={publishStyle.rewardDriverCard} onPress={() => navigation.navigate('Rewards')}>
<Icon name="award" size={16} style={publishStyle.rewardIcon} /> <Icon name="award" size={16} style={publishStyle.rewardIcon} />
<Text style={publishStyle.rewardDriverText}> <Text style={publishStyle.rewardDriverText}>Earn some credits to be able to publish your content.</Text>
{__('Publishing requires credits.')}
{'\n'}
{__('Tap here to get some for free.')}
</Text>
</TouchableOpacity> </TouchableOpacity>
); );
} }
} }
export default PublishRewardsDriver; export default PublishRewadsDriver;
+2 -2
View File
@@ -1,11 +1,11 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { import {
doResolveUris,
makeSelectClaimForUri, makeSelectClaimForUri,
makeSelectRecommendedContentForUri, makeSelectRecommendedContentForUri,
makeSelectTitleForUri, makeSelectTitleForUri,
selectIsSearching, selectIsSearching,
} from 'lbry-redux'; } from 'lbry-redux';
import { doNativeSearch } from 'redux/actions/performance';
import RelatedContent from './view'; import RelatedContent from './view';
const select = (state, props) => ({ const select = (state, props) => ({
@@ -16,7 +16,7 @@ const select = (state, props) => ({
}); });
const perform = dispatch => ({ const perform = dispatch => ({
resolveUris: uris => dispatch(doResolveUris(uris)), search: query => dispatch(doNativeSearch(query, 20, undefined, true)),
}); });
export default connect( export default connect(
+44 -23
View File
@@ -1,6 +1,5 @@
import React from 'react'; import React from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native'; import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import { normalizeURI } from 'lbry-redux';
import { navigateToUri } from 'utils/helper'; import { navigateToUri } from 'utils/helper';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import FileListItem from 'component/fileListItem'; import FileListItem from 'component/fileListItem';
@@ -8,40 +7,62 @@ import fileListStyle from 'styles/fileList';
import relatedContentStyle from 'styles/relatedContent'; import relatedContentStyle from 'styles/relatedContent';
export default class RelatedContent extends React.PureComponent { export default class RelatedContent extends React.PureComponent {
state = { constructor() {
urlsResolved: false, super();
};
this.didSearch = undefined;
}
componentDidMount() {
this.getRecommendedContent();
}
componentDidUpdate(prevProps) { componentDidUpdate(prevProps) {
const { resolveUris, recommendedContent } = this.props; const { claim, uri } = this.props;
if (recommendedContent && recommendedContent.length > 0 && !this.state.urisResolved) { if (uri !== prevProps.uri) {
this.setState({ urisResolved: true }, () => { this.didSearch = false;
// batch resolve the uris }
resolveUris(recommendedContent);
}); if (claim && !this.didSearch) {
this.getRecommendedContent();
} }
} }
getRecommendedContent() {
const { search, title } = this.props;
if (title) {
search(title);
this.didSearch = true;
}
}
didSearch;
render() { render() {
const { recommendedContent, navigation, uri, fullUri } = this.props; const { recommendedContent, isSearching, navigation } = this.props;
if (!isSearching && (!recommendedContent || recommendedContent.length === 0)) {
return null;
}
return ( return (
<View style={relatedContentStyle.container}> <View style={relatedContentStyle.container}>
<Text style={relatedContentStyle.title}>Related Content</Text> <Text style={relatedContentStyle.title}>Related Content</Text>
{recommendedContent && {recommendedContent &&
recommendedContent recommendedContent.map(recommendedUri => (
.filter(recommendedUri => recommendedUri !== normalizeURI(fullUri)) <FileListItem
.map(recommendedUri => ( style={fileListStyle.item}
<FileListItem key={recommendedUri}
style={fileListStyle.item} uri={recommendedUri}
key={recommendedUri} navigation={navigation}
uri={recommendedUri} onPress={() => navigateToUri(navigation, recommendedUri, { autoplay: true })}
batchResolve />
navigation={navigation} ))}
autoplay {isSearching && (
/> <ActivityIndicator size="small" color={Colors.NextLbryGreen} style={relatedContentStyle.loading} />
))} )}
</View> </View>
); );
} }
+4 -20
View File
@@ -13,7 +13,6 @@ type Props = {
id: string, id: string,
reward_title: string, reward_title: string,
reward_amount: number, reward_amount: number,
reward_range?: string,
transaction_id: string, transaction_id: string,
created_at: string, created_at: string,
reward_description: string, reward_description: string,
@@ -34,7 +33,7 @@ class RewardCard extends React.PureComponent<Props> {
notify({ message: errorMessage }); notify({ message: errorMessage });
clearError(reward); clearError(reward);
} else { } else {
notify({ message: __('Reward successfully claimed!') }); notify({ message: 'Reward successfully claimed!' });
} }
this.setState({ claimStarted: false }); this.setState({ claimStarted: false });
} }
@@ -47,7 +46,7 @@ class RewardCard extends React.PureComponent<Props> {
if (showVerification) { if (showVerification) {
showVerification(); showVerification();
} }
notify({ message: __('Unfortunately, you are not eligible to claim this reward at this time.') }); notify({ message: 'Unfortunately, you are not eligible to claim this reward at this time.' });
return; return;
} }
@@ -56,21 +55,6 @@ class RewardCard extends React.PureComponent<Props> {
}); });
}; };
getDisplayAmount = () => {
const { reward } = this.props;
if (reward) {
const claimed = !!reward.transaction_id;
if (!claimed && reward.reward_range && reward.reward_range.includes('-')) {
return reward.reward_range.split('-')[0] + '+'; // ex: 5+
} else if (reward.reward_amount > 0) {
return reward.reward_amount;
}
}
// unknown amount which normally shouldn't happen
return '?';
};
render() { render() {
const { canClaim, isPending, onClaimPress, reward } = this.props; const { canClaim, isPending, onClaimPress, reward } = this.props;
const claimed = !!reward.transaction_id; const claimed = !!reward.transaction_id;
@@ -112,12 +96,12 @@ class RewardCard extends React.PureComponent<Props> {
style={rewardStyle.link} style={rewardStyle.link}
href={`https://explorer.lbry.com/tx/${reward.transaction_id}`} href={`https://explorer.lbry.com/tx/${reward.transaction_id}`}
text={reward.transaction_id.substring(0, 7)} text={reward.transaction_id.substring(0, 7)}
error={__('The transaction URL could not be opened')} error={'The transaction URL could not be opened'}
/> />
)} )}
</View> </View>
<View style={rewardStyle.rightCol}> <View style={rewardStyle.rightCol}>
<Text style={rewardStyle.rewardAmount}>{this.getDisplayAmount()}</Text> <Text style={rewardStyle.rewardAmount}>{reward.reward_amount}</Text>
<Text style={rewardStyle.rewardCurrency}>LBC</Text> <Text style={rewardStyle.rewardCurrency}>LBC</Text>
</View> </View>
</TouchableOpacity> </TouchableOpacity>
+8 -24
View File
@@ -1,8 +1,8 @@
import React from 'react'; import React from 'react';
import { Linking, NativeModules, Text, TouchableOpacity, View } from 'react-native'; import { NativeModules, Text, TouchableOpacity, View } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage'; import AsyncStorage from '@react-native-community/async-storage';
import Button from 'component/button'; import Button from 'component/button';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import Link from 'component/link'; import Link from 'component/link';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Icon from 'react-native-vector-icons/FontAwesome5'; import Icon from 'react-native-vector-icons/FontAwesome5';
@@ -24,42 +24,26 @@ class RewardEnrolment extends React.Component {
navigation.navigate({ routeName: 'Verification', key: 'verification', params: { syncFlow: false } }); navigation.navigate({ routeName: 'Verification', key: 'verification', params: { syncFlow: false } });
}; };
onLearnMorePressed = () => {
Linking.openURL('https://lbry.com/faq/earn-credits');
};
render() { render() {
const { fetching, navigation, unclaimedRewardAmount, user } = this.props; const { fetching, navigation, unclaimedRewardAmount, user } = this.props;
return ( return (
<View style={rewardStyle.enrollContainer}> <View style={rewardStyle.enrollContainer} onPress>
<View style={rewardStyle.summaryRow}> <View style={rewardStyle.summaryRow}>
<Icon name="award" size={36} color={Colors.White} /> <Icon name="award" size={36} color={Colors.White} />
<Text style={rewardStyle.summaryText}>{unclaimedRewardAmount} available credits</Text> <Text style={rewardStyle.summaryText}>{unclaimedRewardAmount} unclaimed credits</Text>
</View> </View>
<View style={rewardStyle.onboarding}> <View style={rewardStyle.onboarding}>
<Text style={rewardStyle.enrollDescText}> <Text style={rewardStyle.enrollDescText}>
{__('LBRY credits allow you to purchase content, publish content, and influence the network.')} LBRY credits allow you to purchase content, publish content, and influence the network. You can start
{'\n\n'} earning credits by watching videos on LBRY.
{__('You get credits for free for providing an email address and taking other basic actions.')}
{'\n\n'}
<Link style={rewardStyle.learnMoreLink} text={__('Learn more')} onPress={this.onLearnMorePressed} />.
</Text> </Text>
</View> </View>
<View style={rewardStyle.buttonRow}> <View style={rewardStyle.buttonRow}>
<Link <Link style={rewardStyle.notInterestedLink} text={'Not interested'} onPress={this.onNotInterestedPressed} />
style={rewardStyle.notInterestedLink} <Button style={rewardStyle.enrollButton} theme={'light'} text={'Enroll'} onPress={this.onEnrollPressed} />
text={__('Not interested')}
onPress={this.onNotInterestedPressed}
/>
<Button
style={rewardStyle.enrollButton}
theme={'light'}
text={__('Get started')}
onPress={this.onEnrollPressed}
/>
</View> </View>
</View> </View>
); );
+20
View File
@@ -0,0 +1,20 @@
import { connect } from 'react-redux';
import { doToast } from 'lbry-redux';
import { doRewardList, selectUnclaimedRewardValue, selectFetchingRewards, selectUser } from 'lbryinc';
import RewardSummary from './view';
const select = state => ({
unclaimedRewardAmount: selectUnclaimedRewardValue(state),
fetching: selectFetchingRewards(state),
user: selectUser(state),
});
const perform = dispatch => ({
fetchRewards: () => dispatch(doRewardList()),
notify: data => dispatch(doToast(data)),
});
export default connect(
select,
perform
)(RewardSummary);
+82
View File
@@ -0,0 +1,82 @@
import React from 'react';
import { NativeModules, Text, TouchableOpacity, View } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Button from 'component/button';
import Colors from 'styles/colors';
import Icon from 'react-native-vector-icons/FontAwesome5';
import rewardStyle from 'styles/reward';
class RewardSummary extends React.Component {
static itemKey = 'rewardSummaryDismissed';
state = {
actionsLeft: 0,
dismissed: false,
};
componentDidMount() {
this.props.fetchRewards();
AsyncStorage.getItem(RewardSummary.itemKey).then(isDismissed => {
if ('true' === isDismissed) {
this.setState({ dismissed: true });
}
const { user } = this.props;
let actionsLeft = 0;
if (!user || !user.has_verified_email) {
actionsLeft++;
}
if (!user || !user.is_identity_verified) {
actionsLeft++;
}
this.setState({ actionsLeft });
});
}
onDismissPressed = () => {
AsyncStorage.setItem(RewardSummary.itemKey, 'true');
this.setState({ dismissed: true });
this.props.notify({
message: 'You can always claim your rewards from the Rewards page.',
});
};
handleSummaryPressed = () => {
const { showVerification } = this.props;
if (showVerification) {
showVerification();
}
};
render() {
const { fetching, navigation, unclaimedRewardAmount, user } = this.props;
if (!user) {
return null;
}
if (
this.state.dismissed ||
(user && user.is_reward_approved) ||
this.state.actionsLeft === 0 ||
unclaimedRewardAmount === 0
) {
return null;
}
return (
<TouchableOpacity style={rewardStyle.summaryContainer} onPress={this.handleSummaryPressed}>
<View style={rewardStyle.summaryRow}>
<Icon name="award" size={36} color={Colors.White} />
<Text style={rewardStyle.summaryText}>{unclaimedRewardAmount} unclaimed credits</Text>
</View>
<Button style={rewardStyle.dismissButton} theme={'light'} text={'Dismiss'} onPress={this.onDismissPressed} />
</TouchableOpacity>
);
}
}
export default RewardSummary;
+19
View File
@@ -0,0 +1,19 @@
import { connect } from 'react-redux';
import { NativeModules } from 'react-native';
import { doSearch, doUpdateSearchQuery } from 'lbry-redux';
import SearchInput from './view';
const perform = dispatch => ({
search: search => {
if (NativeModules.Firebase) {
NativeModules.Firebase.track('search', { query: search });
}
return dispatch(doSearch(search));
},
updateSearchQuery: query => dispatch(doUpdateSearchQuery(query, false)),
});
export default connect(
null,
perform
)(SearchInput);
+41
View File
@@ -0,0 +1,41 @@
import React from 'react';
import { TextInput } from 'react-native';
class SearchInput extends React.PureComponent {
static INPUT_TIMEOUT = 500;
state = {
changeTextTimeout: -1,
};
handleChangeText = text => {
clearTimeout(this.state.changeTextTimeout);
if (!text || text.trim().length < 2) {
// only perform a search if 2 or more characters have been input
return;
}
const { search, updateSearchQuery } = this.props;
updateSearchQuery(text);
let timeout = setTimeout(() => {
search(text);
}, SearchInput.INPUT_TIMEOUT);
this.setState({ changeTextTimeout: timeout });
};
render() {
const { style, value } = this.props;
return (
<TextInput
style={style}
placeholder="Search"
underlineColorAndroid="transparent"
value={value}
onChangeText={text => this.handleChangeText(text)}
/>
);
}
}
export default SearchInput;
+8 -9
View File
@@ -1,9 +1,9 @@
import React from 'react'; import React from 'react';
import { normalizeURI, parseURI } from 'lbry-redux'; import { normalizeURI, parseURI } from 'lbry-redux';
import { ActivityIndicator, Platform, Switch, Text, TouchableOpacity, View } from 'react-native'; import { ActivityIndicator, Platform, Switch, Text, TouchableOpacity, View } from 'react-native';
import { formatBytes } from 'utils/helper'; import { formatBytes } from '../../utils/helper';
import Colors from 'styles/colors'; import Colors from '../../styles/colors';
import storageStatsStyle from 'styles/storageStats'; import storageStatsStyle from '../../styles/storageStats';
class StorageStatsCard extends React.PureComponent { class StorageStatsCard extends React.PureComponent {
state = { state = {
@@ -65,8 +65,7 @@ class StorageStatsCard extends React.PureComponent {
} }
render() { render() {
const { fileInfos } = this.props; if (this.state.totalBytes == 0) {
if (fileInfos.length === 0 || this.state.totalBytes === 0) {
return null; return null;
} }
@@ -98,28 +97,28 @@ class StorageStatsCard extends React.PureComponent {
{this.state.totalAudioBytes > 0 && ( {this.state.totalAudioBytes > 0 && (
<View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}> <View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}>
<View style={[storageStatsStyle.legendBox, storageStatsStyle.audioDistribution]} /> <View style={[storageStatsStyle.legendBox, storageStatsStyle.audioDistribution]} />
<Text style={storageStatsStyle.legendText}>{__('Audio')}</Text> <Text style={storageStatsStyle.legendText}>Audio</Text>
<Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalAudioBytes, 2)}</Text> <Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalAudioBytes, 2)}</Text>
</View> </View>
)} )}
{this.state.totalImageBytes > 0 && ( {this.state.totalImageBytes > 0 && (
<View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}> <View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}>
<View style={[storageStatsStyle.legendBox, storageStatsStyle.imageDistribution]} /> <View style={[storageStatsStyle.legendBox, storageStatsStyle.imageDistribution]} />
<Text style={storageStatsStyle.legendText}>{__('Images')}</Text> <Text style={storageStatsStyle.legendText}>Images</Text>
<Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalImageBytes, 2)}</Text> <Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalImageBytes, 2)}</Text>
</View> </View>
)} )}
{this.state.totalVideoBytes > 0 && ( {this.state.totalVideoBytes > 0 && (
<View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}> <View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}>
<View style={[storageStatsStyle.legendBox, storageStatsStyle.videoDistribution]} /> <View style={[storageStatsStyle.legendBox, storageStatsStyle.videoDistribution]} />
<Text style={storageStatsStyle.legendText}>{__('Videos')}</Text> <Text style={storageStatsStyle.legendText}>Videos</Text>
<Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalVideoBytes, 2)}</Text> <Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalVideoBytes, 2)}</Text>
</View> </View>
)} )}
{this.state.totalOtherBytes > 0 && ( {this.state.totalOtherBytes > 0 && (
<View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}> <View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}>
<View style={[storageStatsStyle.legendBox, storageStatsStyle.otherDistribution]} /> <View style={[storageStatsStyle.legendBox, storageStatsStyle.otherDistribution]} />
<Text style={storageStatsStyle.legendText}>{__('Other')}</Text> <Text style={storageStatsStyle.legendText}>Other</Text>
<Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalOtherBytes, 2)}</Text> <Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalOtherBytes, 2)}</Text>
</View> </View>
)} )}
@@ -5,27 +5,17 @@ import Button from 'component/button';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
class SubscribeNotificationButton extends React.PureComponent { class SubscribeNotificationButton extends React.PureComponent {
handlePress = () => { render() {
const { const {
uri,
name, name,
doChannelSubscriptionEnableNotifications, doChannelSubscriptionEnableNotifications,
doChannelSubscriptionDisableNotifications, doChannelSubscriptionDisableNotifications,
doToast, doToast,
enabledChannelNotifications, enabledChannelNotifications,
isSubscribed,
style,
} = this.props; } = this.props;
const shouldNotify = enabledChannelNotifications.indexOf(name) > -1;
if (shouldNotify) {
doChannelSubscriptionDisableNotifications(name);
doToast({ message: 'You will not receive notifications for new content.' });
} else {
doChannelSubscriptionEnableNotifications(name);
doToast({ message: 'You will receive all notifications for new content.' });
}
};
render() {
const { enabledChannelNotifications, name, uri, isSubscribed, style } = this.props;
if (!isSubscribed) { if (!isSubscribed) {
return null; return null;
@@ -41,14 +31,23 @@ class SubscribeNotificationButton extends React.PureComponent {
} }
const shouldNotify = enabledChannelNotifications.indexOf(name) > -1; const shouldNotify = enabledChannelNotifications.indexOf(name) > -1;
const { claimName } = parseURI(uri);
return ( return (
<Button <Button
style={styles} style={styles}
theme={'light'} theme={'light'}
icon={shouldNotify ? 'bell-slash' : 'bell'} icon={shouldNotify ? 'bell-slash' : 'bell'}
solid solid={true}
onPress={this.handlePress} onPress={() => {
if (shouldNotify) {
doChannelSubscriptionDisableNotifications(name);
doToast({ message: 'You will not receive notifications for new content.' });
} else {
doChannelSubscriptionEnableNotifications(name);
doToast({ message: 'You will receive all notifications for new content.' });
}
}}
/> />
); );
} }
@@ -1,13 +1,11 @@
import React from 'react'; import React from 'react';
import { buildURI, normalizeURI } from 'lbry-redux'; import { buildURI, normalizeURI } from 'lbry-redux';
import { ActivityIndicator, FlatList, Image, Text, View } from 'react-native'; import { ActivityIndicator, FlatList, Image, Text, View } from 'react-native';
import { navigateToUri } from 'utils/helper';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import discoverStyle from 'styles/discover'; import discoverStyle from 'styles/discover';
import FileItem from 'component/fileItem'; import FileItem from 'component/fileItem';
import SubscribeButton from 'component/subscribeButton'; import SubscribeButton from 'component/subscribeButton';
import subscriptionsStyle from 'styles/subscriptions'; import subscriptionsStyle from 'styles/subscriptions';
import Link from 'component/link';
import Tag from 'component/tag'; import Tag from 'component/tag';
class SuggestedSubscriptionItem extends React.PureComponent { class SuggestedSubscriptionItem extends React.PureComponent {
@@ -20,12 +18,9 @@ class SuggestedSubscriptionItem extends React.PureComponent {
render() { render() {
const { claim, isResolvingUri, navigation, thumbnail, title, uri } = this.props; const { claim, isResolvingUri, navigation, thumbnail, title, uri } = this.props;
let shortUrl, tags; let tags;
if (claim) { if (claim && claim.value) {
shortUrl = claim.short_url; tags = claim.value.tags;
if (claim.value) {
tags = claim.value.tags;
}
} }
if (isResolvingUri) { if (isResolvingUri) {
@@ -52,29 +47,20 @@ class SuggestedSubscriptionItem extends React.PureComponent {
{title} {title}
</Text> </Text>
)} )}
{claim && ( <Text style={subscriptionsStyle.suggestedItemName} numberOfLines={1}>
<Link {claim && claim.name}
style={subscriptionsStyle.suggestedItemName} </Text>
numberOfLines={1}
text={claim.name}
onPress={() => navigateToUri(navigation, normalizeURI(shortUrl || uri), null, false, claim.permanent_url)}
/>
)}
{tags && ( {tags && (
<View style={subscriptionsStyle.suggestedItemTagList}> <View style={subscriptionsStyle.suggestedItemTagList}>
{tags && {tags &&
tags tags
.slice(0, 3) .slice(0, 3)
.map(tag => ( .map(tag => <Tag style={subscriptionsStyle.tag} key={tag} name={tag} navigation={navigation} />)}
<Tag style={subscriptionsStyle.tag} key={tag} name={tag} navigation={navigation} truncate />
))}
</View> </View>
)} )}
</View> </View>
{claim && ( <SubscribeButton style={subscriptionsStyle.suggestedItemSubscribe} uri={normalizeURI(uri)} />
<SubscribeButton style={subscriptionsStyle.suggestedItemSubscribe} uri={normalizeURI(claim.permanent_url)} />
)}
</View> </View>
); );
} }
@@ -1,19 +1,17 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { doClaimSearch, selectFetchingClaimSearch, selectClaimSearchByQuery, selectFollowedTags } from 'lbry-redux'; import { doClaimSearch, selectFetchingClaimSearch, selectLastClaimSearchUris, selectFollowedTags } from 'lbry-redux';
import { selectSuggestedChannels, selectIsFetchingSuggested } from 'lbryinc'; import { selectSuggestedChannels, selectIsFetchingSuggested } from 'lbryinc';
import { selectShowNsfw } from 'redux/selectors/settings';
import SuggestedSubscriptions from './view'; import SuggestedSubscriptions from './view';
const select = state => ({ const select = state => ({
followedTags: selectFollowedTags(state), followedTags: selectFollowedTags(state),
suggested: selectSuggestedChannels(state), suggested: selectSuggestedChannels(state),
loading: selectIsFetchingSuggested(state) || selectFetchingClaimSearch(state), loading: selectIsFetchingSuggested(state) || selectFetchingClaimSearch(state),
claimSearchByQuery: selectClaimSearchByQuery(state), claimSearchUris: selectLastClaimSearchUris(state),
showNsfwContent: selectShowNsfw(state),
}); });
const perform = dispatch => ({ const perform = dispatch => ({
claimSearch: options => dispatch(doClaimSearch(options)), claimSearch: options => dispatch(doClaimSearch(10, options)),
}); });
export default connect( export default connect(
+13 -26
View File
@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { ActivityIndicator, SectionList, Text, View } from 'react-native'; import { ActivityIndicator, FlatList, SectionList, Text, View } from 'react-native';
import { MATURE_TAGS, createNormalizedClaimSearchKey, normalizeURI } from 'lbry-redux'; import { normalizeURI } from 'lbry-redux';
import { navigateToUri } from 'utils/helper'; import { __, navigateToUri } from 'utils/helper';
import SubscribeButton from 'component/subscribeButton'; import SubscribeButton from 'component/subscribeButton';
import SuggestedSubscriptionItem from 'component/suggestedSubscriptionItem'; import SuggestedSubscriptionItem from 'component/suggestedSubscriptionItem';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
@@ -11,45 +11,34 @@ import Link from 'component/link';
import _ from 'lodash'; import _ from 'lodash';
class SuggestedSubscriptions extends React.PureComponent { class SuggestedSubscriptions extends React.PureComponent {
state = {
options: {},
};
componentDidMount() { componentDidMount() {
const { claimSearch, followedTags, showNsfwContent } = this.props; const { claimSearch, followedTags } = this.props;
const options = { const options = {
any_tags: _.shuffle(followedTags.map(tag => tag.name)).slice(0, 3), any_tags: _.shuffle(followedTags.map(tag => tag.name)).slice(0, 2),
page: 1, page: 1,
no_totals: true, no_totals: true,
claim_type: 'channel', claim_type: 'channel',
}; };
if (!showNsfwContent) {
options.not_tags = MATURE_TAGS;
}
this.setState({ options });
claimSearch(options); claimSearch(options);
} }
buildSections = () => { buildSections = () => {
const { suggested, claimSearchByQuery } = this.props; const { suggested, claimSearchUris } = this.props;
const claimSearchKey = createNormalizedClaimSearchKey(this.state.options);
const claimSearchUris = claimSearchByQuery[claimSearchKey];
const suggestedUris = suggested ? suggested.map(suggested => suggested.uri) : []; const suggestedUris = suggested ? suggested.map(suggested => suggested.uri) : [];
return [ return [
{ {
title: __('Suggested channels'), title: __('You might like'),
data: claimSearchUris ? claimSearchUris.filter(uri => !suggestedUris.includes(uri)) : [], data: suggestedUris,
}, },
{ {
title: __('You might also like'), title: __('Tags you follow'),
data: _.shuffle(suggestedUris), data: claimSearchUris ? claimSearchUris.filter(uri => !suggestedUris.includes(uri)) : [],
}, },
]; ];
}; };
render() { render() {
const { suggested, inModal, loading, navigation } = this.props; const { suggested, loading, navigation } = this.props;
if (loading) { if (loading) {
return ( return (
@@ -61,10 +50,8 @@ class SuggestedSubscriptions extends React.PureComponent {
return ( return (
<SectionList <SectionList
style={inModal ? subscriptionsStyle.modalScrollContainer : subscriptionsStyle.scrollContainer} style={subscriptionsStyle.scrollContainer}
contentContainerStyle={ contentContainerStyle={subscriptionsStyle.suggestedScrollPadding}
inModal ? subscriptionsStyle.modalSuggestedScrollContent : subscriptionsStyle.suggestedScrollContent
}
renderItem={({ item, index, section }) => ( renderItem={({ item, index, section }) => (
<SuggestedSubscriptionItem key={item} uri={normalizeURI(item)} navigation={navigation} /> <SuggestedSubscriptionItem key={item} uri={normalizeURI(item)} navigation={navigation} />
)} )}
+3 -4
View File
@@ -1,6 +1,5 @@
import React from 'react'; import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native'; import { Text, TouchableOpacity, View } from 'react-native';
import { MATURE_TAGS } from 'lbry-redux';
import { formatTagName } from 'utils/helper'; import { formatTagName } from 'utils/helper';
import tagStyle from 'styles/tag'; import tagStyle from 'styles/tag';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
@@ -30,7 +29,7 @@ export default class Tag extends React.PureComponent {
}; };
render() { render() {
const { name, onPress, style, type, truncate } = this.props; const { name, onPress, style, type } = this.props;
let styles = []; let styles = [];
if (style) { if (style) {
@@ -42,7 +41,7 @@ export default class Tag extends React.PureComponent {
} }
styles.push({ styles.push({
backgroundColor: MATURE_TAGS.includes(name) ? Colors.TagGrape : Colors.TagGreen, backgroundColor: Colors.TagGreen,
borderRadius: 8, borderRadius: 8,
marginBottom: 4, marginBottom: 4,
}); });
@@ -50,7 +49,7 @@ export default class Tag extends React.PureComponent {
return ( return (
<TouchableOpacity style={styles} onPress={onPress || this.onPressDefault}> <TouchableOpacity style={styles} onPress={onPress || this.onPressDefault}>
<View style={tagStyle.content}> <View style={tagStyle.content}>
<Text style={tagStyle.text}>{truncate ? formatTagName(name) : name}</Text> <Text style={tagStyle.text}>{formatTagName(name)}</Text>
{type && <Icon style={tagStyle.icon} name={type === 'add' ? 'plus' : 'times'} size={8} />} {type && <Icon style={tagStyle.icon} name={type === 'add' ? 'plus' : 'times'} size={8} />}
</View> </View>
</TouchableOpacity> </TouchableOpacity>
+1 -19
View File
@@ -1,6 +1,5 @@
import React from 'react'; import React from 'react';
import { KeyboardAvoidingView, Text, TextInput, TouchableOpacity, View } from 'react-native'; import { KeyboardAvoidingView, Text, TextInput, TouchableOpacity, View } from 'react-native';
import { MATURE_TAGS } from 'lbry-redux';
import Tag from 'component/tag'; import Tag from 'component/tag';
import tagStyle from 'styles/tag'; import tagStyle from 'styles/tag';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
@@ -67,12 +66,11 @@ export default class TagSearch extends React.PureComponent {
}; };
render() { render() {
const { editable, name, style, type, selectedTags = [], showNsfwTags } = this.props; const { name, style, type, selectedTags = [] } = this.props;
return ( return (
<View> <View>
<TextInput <TextInput
editable={editable}
style={tagStyle.searchInput} style={tagStyle.searchInput}
placeholder={'Search for more tags'} placeholder={'Search for more tags'}
underlineColorAndroid={Colors.NextLbryGreen} underlineColorAndroid={Colors.NextLbryGreen}
@@ -87,22 +85,6 @@ export default class TagSearch extends React.PureComponent {
))} ))}
</View> </View>
</KeyboardAvoidingView> </KeyboardAvoidingView>
{showNsfwTags && (
<View style={tagStyle.nsfwTagsContainer}>
<Text style={tagStyle.nsfwTagsTitle}>{__('Mature tags')}</Text>
<View style={tagStyle.tagResultsList}>
{MATURE_TAGS.map(tag => (
<Tag
key={tag}
name={tag}
style={tagStyle.tag}
type="add"
onAddPress={name => this.onAddTagPress(name)}
/>
))}
</View>
</View>
)}
</View> </View>
); );
} }
@@ -2,10 +2,10 @@
import React from 'react'; import React from 'react';
import { Text, View, Linking } from 'react-native'; import { Text, View, Linking } from 'react-native';
import { buildURI, formatCredits } from 'lbry-redux'; import { buildURI, formatCredits } from 'lbry-redux';
import { navigateToUri } from 'utils/helper'; import { navigateToUri } from '../../../utils/helper';
import Link from 'component/link'; import Link from '../../link';
import moment from 'moment'; import moment from 'moment';
import transactionListStyle from 'styles/transactionList'; import transactionListStyle from '../../../styles/transactionList';
class TransactionListItem extends React.PureComponent { class TransactionListItem extends React.PureComponent {
capitalize(string: string) { capitalize(string: string) {
@@ -19,12 +19,11 @@ class TransactionListItem extends React.PureComponent {
return ( return (
<View style={transactionListStyle.listItem}> <View style={transactionListStyle.listItem}>
<View style={[transactionListStyle.row, transactionListStyle.topRow]}> <View style={[transactionListStyle.row, transactionListStyle.topRow]}>
<View style={[transactionListStyle.col, transactionListStyle.leftCol]}> <View style={transactionListStyle.col}>
<Text style={transactionListStyle.text}>{this.capitalize(type)}</Text> <Text style={transactionListStyle.text}>{this.capitalize(type)}</Text>
{name && claimId && ( {name && claimId && (
<Link <Link
style={transactionListStyle.link} style={transactionListStyle.link}
numberOfLines={1}
onPress={() => navigateToUri(navigation, buildURI({ claimName: name, claimId }))} onPress={() => navigateToUri(navigation, buildURI({ claimName: name, claimId }))}
text={name} text={name}
/> />
@@ -38,19 +37,19 @@ class TransactionListItem extends React.PureComponent {
</View> </View>
</View> </View>
<View style={transactionListStyle.row}> <View style={transactionListStyle.row}>
<View style={[transactionListStyle.col, transactionListStyle.leftCol]}> <View style={transactionListStyle.col}>
<Link <Link
style={transactionListStyle.smallLink} style={transactionListStyle.smallLink}
text={txid.substring(0, 8)} text={txid.substring(0, 8)}
href={`https://explorer.lbry.com/tx/${txid}`} href={`https://explorer.lbry.com/tx/${txid}`}
error={__('The transaction URL could not be opened')} error={'The transaction URL could not be opened'}
/> />
</View> </View>
<View style={transactionListStyle.col}> <View style={transactionListStyle.col}>
{date ? ( {date ? (
<Text style={transactionListStyle.smallText}>{moment(date).format('MMM D')}</Text> <Text style={transactionListStyle.smallText}>{moment(date).format('MMM D')}</Text>
) : ( ) : (
<Text style={transactionListStyle.smallText}>{__('Pending')}</Text> <Text style={transactionListStyle.smallText}>Pending</Text>
)} )}
</View> </View>
</View> </View>
+1 -1
View File
@@ -47,7 +47,7 @@ class TransactionList extends React.PureComponent {
return ( return (
<View> <View>
{!transactionList.length && ( {!transactionList.length && (
<Text style={transactionListStyle.noTransactions}>{emptyMessage || __('No transactions to list.')}</Text> <Text style={transactionListStyle.noTransactions}>{emptyMessage || 'No transactions to list.'}</Text>
)} )}
{!!transactionList.length && ( {!!transactionList.length && (
+10 -10
View File
@@ -1,12 +1,12 @@
// @flow // @flow
import React from 'react'; import React from 'react';
// import BusyIndicator from 'component/common/busy-indicator'; //import BusyIndicator from 'component/common/busy-indicator';
import { Text, View } from 'react-native'; import { Text, View } from 'react-native';
import Button from 'component/button'; import Button from '../button';
import Link from 'component/link'; import Link from '../link';
import TransactionList from 'component/transactionList'; import TransactionList from '../transactionList';
import type { Transaction } from 'component/transactionList/view'; import type { Transaction } from '../transactionList/view';
import walletStyle from 'styles/wallet'; import walletStyle from '../../styles/wallet';
type Props = { type Props = {
fetchTransactions: () => void, fetchTransactions: () => void,
@@ -27,14 +27,14 @@ class TransactionListRecent extends React.PureComponent<Props> {
<View style={walletStyle.transactionsCard}> <View style={walletStyle.transactionsCard}>
<View style={[walletStyle.row, walletStyle.transactionsHeader]}> <View style={[walletStyle.row, walletStyle.transactionsHeader]}>
<Text style={walletStyle.transactionsTitle}>Recent Transactions</Text> <Text style={walletStyle.transactionsTitle}>Recent Transactions</Text>
<Link style={walletStyle.link} navigation={navigation} text={__('View All')} href={'#TransactionHistory'} /> <Link style={walletStyle.link} navigation={navigation} text={'View All'} href={'#TransactionHistory'} />
</View> </View>
{fetchingTransactions && <Text style={walletStyle.infoText}>{__('Fetching transactions...')}</Text>} {fetchingTransactions && <Text style={walletStyle.infoText}>Fetching transactions...</Text>}
{!fetchingTransactions && ( {!fetchingTransactions && (
<TransactionList <TransactionList
navigation={navigation} navigation={navigation}
transactions={transactions.slice(0, 5)} transactions={transactions}
emptyMessage={__("Looks like you don't have any recent transactions.")} emptyMessage={"Looks like you don't have any recent transactions."}
/> />
)} )}
</View> </View>
-3
View File
@@ -4,10 +4,8 @@ import {
selectSearchState as selectSearch, selectSearchState as selectSearch,
selectSearchValue, selectSearchValue,
selectSearchSuggestions, selectSearchSuggestions,
SETTINGS,
} from 'lbry-redux'; } from 'lbry-redux';
import { selectCurrentRoute } from 'redux/selectors/drawer'; import { selectCurrentRoute } from 'redux/selectors/drawer';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import UriBar from './view'; import UriBar from './view';
const select = state => { const select = state => {
@@ -18,7 +16,6 @@ const select = state => {
query: selectSearchValue(state), query: selectSearchValue(state),
currentRoute: selectCurrentRoute(state), currentRoute: selectCurrentRoute(state),
suggestions: selectSearchSuggestions(state), suggestions: selectSearchSuggestions(state),
showUriBarSuggestions: makeSelectClientSetting(SETTINGS.SHOW_URI_BAR_SUGGESTIONS)(state),
}; };
}; };
@@ -20,10 +20,6 @@ class UriBarItem extends React.PureComponent {
icon = <Icon name="search" size={18} />; icon = <Icon name="search" size={18} />;
break; break;
case SEARCH_TYPES.TAG:
icon = <Icon name="hashtag" size={18} />;
break;
case SEARCH_TYPES.FILE: case SEARCH_TYPES.FILE:
default: default:
icon = <Icon name="file" size={18} />; icon = <Icon name="file" size={18} />;
@@ -41,7 +37,6 @@ class UriBarItem extends React.PureComponent {
{type === SEARCH_TYPES.SEARCH && `Search for '${value}'`} {type === SEARCH_TYPES.SEARCH && `Search for '${value}'`}
{type === SEARCH_TYPES.CHANNEL && `View the @${shorthand} channel`} {type === SEARCH_TYPES.CHANNEL && `View the @${shorthand} channel`}
{type === SEARCH_TYPES.FILE && `View content at ${value}`} {type === SEARCH_TYPES.FILE && `View content at ${value}`}
{type === SEARCH_TYPES.TAG && `Explore the '${value}' tag`}
</Text> </Text>
</View> </View>
</TouchableOpacity> </TouchableOpacity>
+87 -180
View File
@@ -1,12 +1,12 @@
// @flow // @flow
import React from 'react'; import React from 'react';
import { SEARCH_TYPES, isNameValid, isURIValid, normalizeURI } from 'lbry-redux'; import { SEARCH_TYPES, isNameValid, isURIValid, normalizeURI } from 'lbry-redux';
import { Dimensions, FlatList, Keyboard, Text, TextInput, TouchableOpacity, View } from 'react-native'; import { FlatList, Keyboard, TextInput, View } from 'react-native';
import { navigateToUri, transformUrl } from 'utils/helper'; import { navigateToUri } from 'utils/helper';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import UriBarItem from './internal/uri-bar-item'; import UriBarItem from './internal/uri-bar-item';
import Icon from 'react-native-vector-icons/FontAwesome5';
import NavigationButton from 'component/navigationButton'; import NavigationButton from 'component/navigationButton';
import discoverStyle from 'styles/discover';
import uriBarStyle from 'styles/uriBar'; import uriBarStyle from 'styles/uriBar';
class UriBar extends React.PureComponent { class UriBar extends React.PureComponent {
@@ -14,28 +14,14 @@ class UriBar extends React.PureComponent {
textInput = null; textInput = null;
keyboardDidShowListener = null;
keyboardDidHideListener = null; keyboardDidHideListener = null;
state = {
changeTextTimeout: null,
currentValue: null,
inputText: null,
focused: false,
keyboardHeight: 0,
};
componentDidMount() { componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide); this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
this.setSelection(); this.setSelection();
} }
componentWillUnmount() { componentWillUnmount() {
if (this.keyboardDidShowListener) {
this.keyboardDidShowListener.remove();
}
if (this.keyboardDidHideListener) { if (this.keyboardDidHideListener) {
this.keyboardDidHideListener.remove(); this.keyboardDidHideListener.remove();
} }
@@ -50,31 +36,40 @@ class UriBar extends React.PureComponent {
} }
} }
constructor(props) {
super(props);
this.state = {
changeTextTimeout: null,
currentValue: null,
inputText: null,
focused: false,
// TODO: Add a setting to enable / disable direct search?
directSearch: true,
};
}
handleChangeText = text => { handleChangeText = text => {
const newValue = text || ''; const newValue = text ? text : '';
clearTimeout(this.state.changeTextTimeout); clearTimeout(this.state.changeTextTimeout);
const { updateSearchQuery, onSearchSubmitted, showUriBarSuggestions, navigation } = this.props; const { updateSearchQuery, onSearchSubmitted, navigation } = this.props;
updateSearchQuery(text); let timeout = setTimeout(() => {
if (text.trim().length === 0) {
// don't do anything if the text is empty
return;
}
let timeout = -1; updateSearchQuery(text);
if (!showUriBarSuggestions) {
timeout = setTimeout(() => { if (!text.startsWith('lbry://')) {
if (text.trim().length === 0) { // not a URI input, so this is a search, perform a direct search
// don't do anything if the text is empty if (onSearchSubmitted) {
return; onSearchSubmitted(text);
} else {
navigation.navigate({ routeName: 'Search', key: 'searchPage', params: { searchQuery: text } });
} }
}
if (!text.startsWith('lbry://')) { }, UriBar.INPUT_TIMEOUT);
// not a URI input, so this is a search, perform a direct search
if (onSearchSubmitted) {
onSearchSubmitted(text);
} else {
navigation.navigate({ routeName: 'Search', key: 'searchPage', params: { searchQuery: text } });
}
}
}, UriBar.INPUT_TIMEOUT);
}
this.setState({ inputText: newValue, currentValue: newValue, changeTextTimeout: timeout }); this.setState({ inputText: newValue, currentValue: newValue, changeTextTimeout: timeout });
}; };
@@ -93,34 +88,18 @@ class UriBar extends React.PureComponent {
return; return;
} }
navigation.navigate({ navigation.navigate({ routeName: 'Search', key: 'searchPage', params: { searchQuery: value } });
routeName: Constants.DRAWER_ROUTE_SEARCH,
key: 'searchPage',
params: { searchQuery: value },
});
} else if (SEARCH_TYPES.TAG === type) {
navigation.navigate({
routeName: Constants.DRAWER_ROUTE_TAG,
key: 'tagPage',
params: {
tag: value.toLowerCase(),
},
});
} else { } else {
const uri = normalizeURI(value); const uri = normalizeURI(value);
navigateToUri(navigation, uri); navigateToUri(navigation, uri);
} }
}; };
_keyboardDidShow = evt => {
this.setState({ keyboardHeight: evt.endCoordinates.height });
};
_keyboardDidHide = () => { _keyboardDidHide = () => {
if (this.textInput) { if (this.textInput) {
this.textInput.blur(); this.textInput.blur();
} }
this.setState({ focused: false, keyboardHeight: 0 }); this.setState({ focused: false });
}; };
setSelection() { setSelection() {
@@ -132,19 +111,12 @@ class UriBar extends React.PureComponent {
handleSubmitEditing = () => { handleSubmitEditing = () => {
const { navigation, onSearchSubmitted, updateSearchQuery } = this.props; const { navigation, onSearchSubmitted, updateSearchQuery } = this.props;
if (this.state.inputText) { if (this.state.inputText) {
let inputText = this.state.inputText, let inputText = this.state.inputText;
inputTextIsUrl = false; if (inputText.startsWith('lbry://') && isURIValid(inputText)) {
if (inputText.startsWith('lbry://')) {
const transformedUrl = transformUrl(inputText);
// if it's a URI (lbry://...), open the file page // if it's a URI (lbry://...), open the file page
if (transformedUrl && isURIValid(transformedUrl)) { const uri = normalizeURI(inputText);
inputTextIsUrl = true; navigateToUri(navigation, uri);
navigateToUri(navigation, transformedUrl); } else {
}
}
// couldn't parse the inputText as a URL for some reason, so do a search instead
if (!inputTextIsUrl) {
updateSearchQuery(inputText); updateSearchQuery(inputText);
// Not a URI, default to a search request // Not a URI, default to a search request
if (onSearchSubmitted) { if (onSearchSubmitted) {
@@ -164,130 +136,65 @@ class UriBar extends React.PureComponent {
} }
render() { render() {
const { const { navigation, suggestions, query, value, belowOverlay } = this.props;
allowEdit,
belowOverlay,
navigation,
onExitSelectionMode,
onEditActionPressed,
onDeleteActionPressed,
query,
selectedItemCount,
selectionMode,
suggestions,
showUriBarSuggestions,
value,
} = this.props;
if (this.state.currentValue === null) { if (this.state.currentValue === null) {
this.setState({ currentValue: value }); this.setState({ currentValue: value });
} }
let style = [ let style = [uriBarStyle.overlay, belowOverlay ? null : uriBarStyle.overlayElevated];
uriBarStyle.overlay,
belowOverlay ? null : uriBarStyle.overlayElevated, // TODO: Add optional setting to enable URI / search bar suggestions
this.state.focused && showUriBarSuggestions ? uriBarStyle.inFocus : null, /*if (this.state.focused) { style.push(uriBarStyle.inFocus); }*/
];
// TODO: selectionModeActions should be dynamically created / specified
return ( return (
<View style={style}> <View style={style}>
<View style={[uriBarStyle.uriContainer, belowOverlay ? null : uriBarStyle.containerElevated]}> <View style={[uriBarStyle.uriContainer, belowOverlay ? null : uriBarStyle.containerElevated]}>
{selectionMode && ( <NavigationButton
<View style={uriBarStyle.selectionModeBar}> name="bars"
<View style={uriBarStyle.selectionModeLeftBar}> size={24}
<TouchableOpacity style={uriBarStyle.drawerMenuButton}
style={uriBarStyle.backTouchArea} iconStyle={discoverStyle.drawerHamburger}
onPress={() => { onPress={() => navigation.openDrawer()}
if (onExitSelectionMode) { />
onExitSelectionMode(); <TextInput
} ref={ref => {
}} this.textInput = ref;
> }}
<Icon name="arrow-left" size={20} /> style={uriBarStyle.uriText}
</TouchableOpacity> onLayout={() => {
{selectedItemCount > 0 && <Text style={uriBarStyle.itemCount}>{selectedItemCount}</Text>} this.setSelection();
</View> }}
selectTextOnFocus={true}
<View style={uriBarStyle.selectionModeActions}> placeholder={'Search movies, music, and more'}
{allowEdit && selectedItemCount === 1 && ( underlineColorAndroid={'transparent'}
<TouchableOpacity numberOfLines={1}
style={[uriBarStyle.actionTouchArea, uriBarStyle.leftAction]} clearButtonMode={'while-editing'}
onPress={() => { value={this.state.currentValue}
if (onEditActionPressed) { returnKeyType={'go'}
onEditActionPressed(); inlineImageLeft={'baseline_search_black_24'}
} inlineImagePadding={16}
}} onFocus={() => this.setState({ focused: true })}
> onBlur={() => {
<Icon name="edit" size={20} style={uriBarStyle.actionIcon} /> this.setState({ focused: false });
</TouchableOpacity> this.setSelection();
}}
onChangeText={this.handleChangeText}
onSubmitEditing={this.handleSubmitEditing}
/>
{this.state.focused && !this.state.directSearch && (
<View style={uriBarStyle.suggestions}>
<FlatList
style={uriBarStyle.suggestionList}
data={suggestions}
keyboardShouldPersistTaps={'handled'}
keyExtractor={(item, value) => item.value}
renderItem={({ item }) => (
<UriBarItem item={item} navigation={navigation} onPress={() => this.handleItemPress(item)} />
)} )}
/>
<TouchableOpacity
style={uriBarStyle.actionTouchArea}
onPress={() => {
if (onDeleteActionPressed) {
onDeleteActionPressed();
}
}}
>
<Icon name="trash-alt" solid={false} size={20} style={uriBarStyle.actionIcon} />
</TouchableOpacity>
</View>
</View> </View>
)} )}
{!selectionMode && (
<NavigationButton
name="bars"
size={24}
style={uriBarStyle.drawerMenuButton}
iconStyle={uriBarStyle.drawerHamburger}
onPress={() => navigation.openDrawer()}
/>
)}
{!selectionMode && (
<TextInput
ref={ref => {
this.textInput = ref;
}}
autoCorrect={false}
style={uriBarStyle.uriText}
onLayout={() => {
this.setSelection();
}}
selectTextOnFocus
placeholder={__('Search movies, music, and more')}
underlineColorAndroid={'transparent'}
numberOfLines={1}
clearButtonMode={'while-editing'}
value={this.state.currentValue}
returnKeyType={'go'}
inlineImageLeft={'baseline_search_black_24'}
inlineImagePadding={16}
onFocus={() => this.setState({ focused: true })}
onBlur={() => {
this.setState({ focused: false });
this.setSelection();
}}
onChangeText={this.handleChangeText}
onSubmitEditing={this.handleSubmitEditing}
/>
)}
</View> </View>
{this.state.focused && showUriBarSuggestions && (
<FlatList
style={[
uriBarStyle.suggestions,
{ height: Dimensions.get('window').height - this.state.keyboardHeight - 60 },
]}
data={suggestions}
keyboardShouldPersistTaps={'handled'}
keyExtractor={(item, value) => `${item.value}-${item.type}`}
renderItem={({ item }) => (
<UriBarItem item={item} navigation={navigation} onPress={() => this.handleItemPress(item)} />
)}
/>
)}
</View> </View>
); );
} }
-4
View File
@@ -1,4 +0,0 @@
import { connect } from 'react-redux';
import VideoDuration from './view';
export default connect()(VideoDuration);
-36
View File
@@ -1,36 +0,0 @@
import React from 'react';
import { Text, View } from 'react-native';
import fileListStyle from 'styles/fileList';
import _ from 'lodash';
export default class VideoDuration extends React.PureComponent {
getDurationString = duration => {
let seconds = duration;
const hours = Math.floor(seconds / 3600);
seconds = duration - hours * 3600;
const minutes = Math.floor(seconds / 60);
seconds = seconds % 60;
let durationString = '';
if (hours > 0) {
durationString += hours + ':';
}
durationString += _.padStart(minutes, hours > 0 ? 2 : 0, '0') + ':';
durationString += _.padStart(seconds, 2, '0');
return durationString;
};
render() {
const { duration, style, textStyle } = this.props;
if (!duration || isNaN(parseFloat(duration))) {
return null;
}
return (
<View style={style}>
<Text style={textStyle}>{this.getDurationString(duration)}</Text>
</View>
);
}
}
+5 -6
View File
@@ -27,22 +27,21 @@ class WalletAddress extends React.PureComponent<Props> {
return ( return (
<View style={walletStyle.card}> <View style={walletStyle.card}>
<Text style={walletStyle.title}>{__('Receive Credits')}</Text> <Text style={walletStyle.title}>Receive Credits</Text>
<Text style={[walletStyle.text, walletStyle.bottomMarginMedium]}> <Text style={[walletStyle.text, walletStyle.bottomMarginMedium]}>
{__('Use this wallet address to receive credits sent by another user (or yourself).')} Use this wallet address to receive credits sent by another user (or yourself).
</Text> </Text>
<Address address={receiveAddress} style={walletStyle.bottomMarginSmall} /> <Address address={receiveAddress} style={walletStyle.bottomMarginSmall} />
<Button <Button
style={[walletStyle.button, walletStyle.bottomMarginLarge]} style={[walletStyle.button, walletStyle.bottomMarginLarge]}
icon={'sync'} icon={'sync'}
text={__('Get new address')} text={'Get new address'}
onPress={getNewAddress} onPress={getNewAddress}
disabled={gettingNewAddress} disabled={gettingNewAddress}
/> />
<Text style={walletStyle.smallText}> <Text style={walletStyle.smallText}>
{__( You can generate a new address at any time, and any previous addresses will continue to work. Using multiple
'You can generate a new address at any time, and any previous addresses will continue to work. Using multiple addresses can be helpful for keeping track of incoming payments from multiple sources.' addresses can be helpful for keeping track of incoming payments from multiple sources.
)}
</Text> </Text>
</View> </View>
); );
+2 -2
View File
@@ -16,8 +16,8 @@ class WalletBalance extends React.PureComponent<Props> {
return ( return (
<View style={walletStyle.balanceCard}> <View style={walletStyle.balanceCard}>
<Image style={walletStyle.balanceBackground} resizeMode={'cover'} source={require('../../assets/stripe.png')} /> <Image style={walletStyle.balanceBackground} resizeMode={'cover'} source={require('../../assets/stripe.png')} />
<Text style={walletStyle.balanceTitle}>{__('Balance')}</Text> <Text style={walletStyle.balanceTitle}>Balance</Text>
<Text style={walletStyle.balanceCaption}>{__('You currently have')}</Text> <Text style={walletStyle.balanceCaption}>You currently have</Text>
<Text style={walletStyle.balance}> <Text style={walletStyle.balance}>
{(balance || balance === 0) && formatCredits(parseFloat(balance), 2) + ' LBC'} {(balance || balance === 0) && formatCredits(parseFloat(balance), 2) + ' LBC'}
</Text> </Text>
+1 -7
View File
@@ -1,10 +1,4 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { selectUnclaimedRewardValue, selectUser } from 'lbryinc';
import WalletRewardsDriver from './view'; import WalletRewardsDriver from './view';
const select = state => ({ export default connect()(WalletRewardsDriver);
unclaimedRewardAmount: selectUnclaimedRewardValue(state),
user: selectUser(state),
});
export default connect(select)(WalletRewardsDriver);
+2 -21
View File
@@ -5,31 +5,12 @@ import walletStyle from 'styles/wallet';
class WalletRewardsDriver extends React.PureComponent<Props> { class WalletRewardsDriver extends React.PureComponent<Props> {
render() { render() {
const { navigation, unclaimedRewardAmount, user } = this.props; const { navigation } = this.props;
const signedIn = user && user.has_verified_email;
return ( return (
<TouchableOpacity style={walletStyle.rewardDriverCard} onPress={() => navigation.navigate('Rewards')}> <TouchableOpacity style={walletStyle.rewardDriverCard} onPress={() => navigation.navigate('Rewards')}>
<Icon name="award" size={16} style={walletStyle.rewardIcon} /> <Icon name="award" size={16} style={walletStyle.rewardIcon} />
{signedIn && ( <Text style={walletStyle.rewardDriverText}>Earn credits while using the LBRY app.</Text>
<Text style={walletStyle.rewardDriverText}>
{unclaimedRewardAmount === 0 && __('Free credits available in rewards.')}
{unclaimedRewardAmount === 1 &&
__('%amount% free credit available in rewards.', { amount: unclaimedRewardAmount })}
{unclaimedRewardAmount > 1 &&
__('%amount% free credits available in rewards.', { amount: unclaimedRewardAmount })}{' '}
{__('Tap to learn more.')}
</Text>
)}
{!signedIn && (
<Text style={walletStyle.rewardDriverText}>
{unclaimedRewardAmount === 1 &&
__('Get %amount% free credit after creating an account.', { amount: unclaimedRewardAmount })}
{unclaimedRewardAmount !== 1 &&
__('Get %amount% free credits after creating an account.', { amount: unclaimedRewardAmount })}
</Text>
)}
</TouchableOpacity> </TouchableOpacity>
); );
} }
+11 -12
View File
@@ -38,24 +38,24 @@ class WalletSend extends React.PureComponent<Props> {
const { address, amount } = this.state; const { address, amount } = this.state;
if (address && !regexAddress.test(address)) { if (address && !regexAddress.test(address)) {
notify({ notify({
message: __('The recipient address is not a valid LBRY address.'), message: 'The recipient address is not a valid LBRY address.',
}); });
return; return;
} }
if (amount > balance) { if (amount > balance) {
notify({ notify({
message: __('Insufficient credits'), message: 'Insufficient credits',
}); });
return; return;
} }
if (amount && address) { if (amount && address) {
// Show confirmation before send // Show confirmation before send
Alert.alert(__('Send LBC'), `Are you sure you want to send ${amount} LBC to ${address}?`, [ Alert.alert('Send LBC', `Are you sure you want to send ${amount} LBC to ${address}?`, [
{ text: __('No') }, { text: 'No' },
{ {
text: __('Yes'), text: 'Yes',
onPress: () => { onPress: () => {
sendToAddress(address, parseFloat(amount)); sendToAddress(address, parseFloat(amount));
this.setState({ address: null, amount: null }); this.setState({ address: null, amount: null });
@@ -69,7 +69,7 @@ class WalletSend extends React.PureComponent<Props> {
if (this.state.addressChanged && !this.state.addressValid) { if (this.state.addressChanged && !this.state.addressValid) {
const { notify } = this.props; const { notify } = this.props;
notify({ notify({
message: __('The recipient address is not a valid LBRY address.'), message: 'The recipient address is not a valid LBRY address.',
}); });
} }
}; };
@@ -82,20 +82,19 @@ class WalletSend extends React.PureComponent<Props> {
render() { render() {
const { balance } = this.props; const { balance } = this.props;
const canSend = const canSend = this.state.address && this.state.amount > 0 && this.state.address.trim().length > 0;
this.state.address && this.state.amount > 0 && this.state.address.trim().length > 0 && this.state.addressValid;
return ( return (
<View style={walletStyle.card}> <View style={walletStyle.card}>
<Text style={walletStyle.title}>{__('Send Credits')}</Text> <Text style={walletStyle.title}>Send Credits</Text>
<Text style={walletStyle.text}>{__('Recipient address')}</Text> <Text style={walletStyle.text}>Recipient address</Text>
<View style={[walletStyle.row, walletStyle.bottomMarginMedium]}> <View style={[walletStyle.row, walletStyle.bottomMarginMedium]}>
<TextInput <TextInput
onChangeText={value => onChangeText={value =>
this.setState({ this.setState({
address: value, address: value,
addressChanged: true, addressChanged: true,
addressValid: value.trim().length === 0 || regexAddress.test(value), addressValid: value.trim().length == 0 || regexAddress.test(value),
}) })
} }
onBlur={this.handleAddressInputBlur} onBlur={this.handleAddressInputBlur}
@@ -112,7 +111,7 @@ class WalletSend extends React.PureComponent<Props> {
onPress={() => Clipboard.getString().then(value => this.setState({ address: value, addressChanged: true }))} onPress={() => Clipboard.getString().then(value => this.setState({ address: value, addressChanged: true }))}
/> />
</View> </View>
<Text style={walletStyle.text}>{__('Amount')}</Text> <Text style={walletStyle.text}>Amount</Text>
<View style={walletStyle.row}> <View style={walletStyle.row}>
<View style={walletStyle.amountRow}> <View style={walletStyle.amountRow}>
<TextInput <TextInput
-19
View File
@@ -1,19 +0,0 @@
import { connect } from 'react-redux';
import { doToast } from 'lbry-redux';
import { doSetClientSetting } from 'redux/actions/settings';
import { selectUser } from 'lbryinc';
import WalletSignIn from './view';
const select = state => ({
user: selectUser(state),
});
const perform = dispatch => ({
notify: data => dispatch(doToast(data)),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
});
export default connect(
select,
perform
)(WalletSignIn);
-59
View File
@@ -1,59 +0,0 @@
import React from 'react';
import { Linking, NativeModules, Text, TouchableOpacity, View } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Button from 'component/button';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import Link from 'component/link';
import Colors from 'styles/colors';
import Icon from 'react-native-vector-icons/FontAwesome5';
import walletStyle from 'styles/wallet';
class WalletSignIn extends React.Component {
onContinuePressed = () => {
const { navigation, setClientSetting } = this.props;
setClientSetting(Constants.SETTING_ALPHA_UNDERSTANDS_RISKS, true);
};
onSignInPressed = () => {
const { navigation } = this.props;
navigation.navigate({
routeName: 'Verification',
key: 'verification',
params: { syncFlow: true, signInFlow: true },
});
};
render() {
const { navigation, user } = this.props;
return (
<View style={walletStyle.signInContainer}>
<View style={walletStyle.signInSummaryRow}>
<Text style={walletStyle.signInTitle}>Account Recommended</Text>
</View>
<View style={walletStyle.onboarding}>
<Text style={walletStyle.onboardingText}>
{__(
'An account with LBRY Inc. allows you to earn rewards, backup your wallet, and keep everything synced.'
)}
{'\n\n'}
{__('Without an account, you assume all responsibility for securing your wallet and LBRY data.')}
</Text>
</View>
<View style={walletStyle.buttonRow}>
<Link style={walletStyle.continueLink} text={__('Skip Account')} onPress={this.onContinuePressed} />
<Button
style={walletStyle.signInButton}
theme={'light'}
text={__('Sign Up')}
onPress={this.onSignInPressed}
/>
</View>
</View>
);
}
}
export default WalletSignIn;
+1 -1
View File
@@ -3,7 +3,7 @@ import { doSetClientSetting } from 'redux/actions/settings';
import { makeSelectClientSetting } from 'redux/selectors/settings'; import { makeSelectClientSetting } from 'redux/selectors/settings';
import { doToast } from 'lbry-redux'; import { doToast } from 'lbry-redux';
import { selectUserEmail } from 'lbryinc'; import { selectUserEmail } from 'lbryinc';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import WalletSyncDriver from './view'; import WalletSyncDriver from './view';
const select = state => ({ const select = state => ({
+15 -15
View File
@@ -1,7 +1,7 @@
import React from 'react'; import React from 'react';
import { Alert, NativeModules, Switch, Text, View } from 'react-native'; import { Alert, NativeModules, Switch, Text, View } from 'react-native';
import Button from 'component/button'; import Button from 'component/button';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import Link from 'component/link'; import Link from 'component/link';
import walletStyle from 'styles/wallet'; import walletStyle from 'styles/wallet';
@@ -15,15 +15,15 @@ class WalletSyncDriver extends React.PureComponent<Props> {
// turning off // turning off
// set deviceWalletSynced to false (if confirmed) // set deviceWalletSynced to false (if confirmed)
Alert.alert( Alert.alert(
__('Disable wallet sync'), 'Disable wallet sync',
__('Are you sure you want to turn off wallet sync?'), 'Are you sure you want to turn off wallet sync?',
[ [
{ text: __('No') }, { text: 'No' },
{ {
text: __('Yes'), text: 'Yes',
onPress: () => { onPress: () => {
setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, false); setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, false);
notify({ message: __('Wallet sync was successfully disabled.') }); notify({ message: 'Wallet sync was successfully disabled.' });
}, },
}, },
], ],
@@ -37,14 +37,14 @@ class WalletSyncDriver extends React.PureComponent<Props> {
return ( return (
<View style={walletStyle.syncDriverCard}> <View style={walletStyle.syncDriverCard}>
<Text style={walletStyle.syncDriverTitle}>{__('Wallet Sync')}</Text> <Text style={walletStyle.syncDriverTitle}>Wallet Sync</Text>
<View style={walletStyle.switchRow}> <View style={walletStyle.switchRow}>
<View style={walletStyle.tableCol}> <View style={walletStyle.tableCol}>
<Text style={walletStyle.labelText}>{__('Sync status')}</Text> <Text style={walletStyle.labelText}>Sync status</Text>
</View> </View>
<View style={walletStyle.tableColRow}> <View style={walletStyle.tableColRow}>
<Text selectable style={walletStyle.valueText}> <Text selectable={true} style={walletStyle.valueText}>
{deviceWalletSynced ? __('On') : __('Off')} {deviceWalletSynced ? 'On' : 'Off'}
</Text> </Text>
<Switch <Switch
style={walletStyle.syncSwitch} style={walletStyle.syncSwitch}
@@ -56,11 +56,11 @@ class WalletSyncDriver extends React.PureComponent<Props> {
{deviceWalletSynced && ( {deviceWalletSynced && (
<View style={walletStyle.tableRow}> <View style={walletStyle.tableRow}>
<View style={walletStyle.tableCol}> <View style={walletStyle.tableCol}>
<Text style={walletStyle.labelText}>{__('Connected email')}</Text> <Text style={walletStyle.labelText}>Connected email</Text>
</View> </View>
<View style={walletStyle.tableCol}> <View style={walletStyle.tableCol}>
<Text selectable style={walletStyle.valueText} numberOfLines={1}> <Text selectable={true} style={walletStyle.valueText}>
{userEmail || __('No connected email')} {userEmail ? userEmail : 'No connected email'}
</Text> </Text>
</View> </View>
</View> </View>
@@ -69,7 +69,7 @@ class WalletSyncDriver extends React.PureComponent<Props> {
<View style={walletStyle.linkRow}> <View style={walletStyle.linkRow}>
<View style={walletStyle.tableCol}> <View style={walletStyle.tableCol}>
<Link <Link
text={__('Manual backup')} text="Manual backup"
href="https://lbry.com/faq/how-to-backup-wallet#android" href="https://lbry.com/faq/how-to-backup-wallet#android"
style={walletStyle.syncDriverLink} style={walletStyle.syncDriverLink}
/> />
@@ -77,7 +77,7 @@ class WalletSyncDriver extends React.PureComponent<Props> {
<View style={walletStyle.rightTableCol}> <View style={walletStyle.rightTableCol}>
{!deviceWalletSynced && ( {!deviceWalletSynced && (
<Link <Link
text={__('Sync FAQ')} text="Sync FAQ"
href="https://lbry.com/faq/how-to-backup-wallet#sync" href="https://lbry.com/faq/how-to-backup-wallet#sync"
style={[walletStyle.syncDriverLink, walletStyle.rightLink]} style={[walletStyle.syncDriverLink, walletStyle.rightLink]}
/> />
+5 -26
View File
@@ -25,14 +25,11 @@ const Constants = {
PHASE_DETAILS: 'details', PHASE_DETAILS: 'details',
PHASE_PUBLISH: 'publish', PHASE_PUBLISH: 'publish',
PHASE_LIST: 'list',
PHASE_NEW: 'create',
CONTENT_TAB: 'content', CONTENT_TAB: 'content',
ABOUT_TAB: 'about', ABOUT_TAB: 'about',
KEY_FIRST_RUN_EMAIL: 'firstRunEmail', KEY_FIRST_RUN_EMAIL: 'firstRunEmail',
KEY_WALLET_PASSWORD: 'firstRunPassword', KEY_FIRST_RUN_PASSWORD: 'firstRunPassword',
KEY_FIRST_USER_AUTH: 'firstUserAuth', KEY_FIRST_USER_AUTH: 'firstUserAuth',
KEY_SHOULD_VERIFY_EMAIL: 'shouldVerifyEmail', KEY_SHOULD_VERIFY_EMAIL: 'shouldVerifyEmail',
KEY_EMAIL_VERIFY_PENDING: 'emailVerifyPending', KEY_EMAIL_VERIFY_PENDING: 'emailVerifyPending',
@@ -56,16 +53,6 @@ const Constants = {
ACTION_REACT_NAVIGATION_NAVIGATE: 'Navigation/NAVIGATE', ACTION_REACT_NAVIGATION_NAVIGATE: 'Navigation/NAVIGATE',
ACTION_REACT_NAVIGATION_REPLACE: 'Navigation/REPLACE', ACTION_REACT_NAVIGATION_REPLACE: 'Navigation/REPLACE',
ACTION_SORT_BY_ITEM_CHANGED: 'SORT_BY_ITEM_CHANGED',
ACTION_TIME_ITEM_CHANGED: 'TIME_ITEM_CHANGED',
ACTION_UPDATE_PUBLISH_FORM_STATE: 'UPDATE_PUBLISH_FORM_STATE',
ACTION_UPDATE_CHANNEL_FORM_STATE: 'UPDATE_CHANNEL_FORM_STATE',
ACTION_CLEAR_PUBLISH_FORM_STATE: 'CLEAR_PUBLISH_FORM_STATE',
ACTION_CLEAR_CHANNEL_FORM_STATE: 'CLEAR_CHANNEL_FORM_STATE',
ACTION_FULLSCREEN_MODE_TOGGLED: 'FULLSCREEN_MODE_TOGGLED',
ORIENTATION_HORIZONTAL: 'horizontal', ORIENTATION_HORIZONTAL: 'horizontal',
ORIENTATION_VERTICAL: 'vertical', ORIENTATION_VERTICAL: 'vertical',
@@ -79,7 +66,6 @@ const Constants = {
DRAWER_ROUTE_SUBSCRIPTIONS: 'Subscriptions', DRAWER_ROUTE_SUBSCRIPTIONS: 'Subscriptions',
DRAWER_ROUTE_MY_LBRY: 'Downloads', DRAWER_ROUTE_MY_LBRY: 'Downloads',
DRAWER_ROUTE_PUBLISH: 'Publish', DRAWER_ROUTE_PUBLISH: 'Publish',
DRAWER_ROUTE_PUBLISH_FORM: 'PublishForm',
DRAWER_ROUTE_PUBLISHES: 'Publishes', DRAWER_ROUTE_PUBLISHES: 'Publishes',
DRAWER_ROUTE_REWARDS: 'Rewards', DRAWER_ROUTE_REWARDS: 'Rewards',
DRAWER_ROUTE_WALLET: 'Wallet', DRAWER_ROUTE_WALLET: 'Wallet',
@@ -88,11 +74,12 @@ const Constants = {
DRAWER_ROUTE_SEARCH: 'Search', DRAWER_ROUTE_SEARCH: 'Search',
DRAWER_ROUTE_TRANSACTION_HISTORY: 'TransactionHistory', DRAWER_ROUTE_TRANSACTION_HISTORY: 'TransactionHistory',
DRAWER_ROUTE_TAG: 'Tag', DRAWER_ROUTE_TAG: 'Tag',
DRAWER_ROUTE_CHANNEL_CREATOR: 'ChannelCreator',
DRAWER_ROUTE_CHANNEL_CREATOR_FORM: 'ChannnelCreatorForm',
FULL_ROUTE_NAME_DISCOVER: 'DiscoverStack', FULL_ROUTE_NAME_DISCOVER: 'DiscoverStack',
FULL_ROUTE_NAME_TRENDING: 'TrendingStack',
FULL_ROUTE_NAME_MY_SUBSCRIPTIONS: 'MySubscriptionsStack',
FULL_ROUTE_NAME_WALLET: 'WalletStack', FULL_ROUTE_NAME_WALLET: 'WalletStack',
FULL_ROUTE_NAME_MY_LBRY: 'MyLBRYStack',
ROUTE_FILE: 'File', ROUTE_FILE: 'File',
@@ -129,7 +116,7 @@ const Constants = {
{ name: TIME_ALL, label: 'All time' }, { name: TIME_ALL, label: 'All time' },
], ],
DEFAULT_ORDER_BY: ['trending_group', 'trending_mixed'], DEFAULT_ORDER_BY: ['trending_global', 'trending_mixed'],
ORDER_BY_EFFECTIVE_AMOUNT: 'effective_amount', ORDER_BY_EFFECTIVE_AMOUNT: 'effective_amount',
@@ -140,10 +127,6 @@ const Constants = {
MORE_PLACEHOLDER: '_more', MORE_PLACEHOLDER: '_more',
TRUE_STRING: 'true', TRUE_STRING: 'true',
MINIMUM_TRANSACTION_BALANCE: 0.1,
SHARE_BASE_URL: 'https://open.lbry.com',
}; };
export default Constants; export default Constants;
@@ -163,8 +146,4 @@ export const DrawerRoutes = [
Constants.DRAWER_ROUTE_ABOUT, Constants.DRAWER_ROUTE_ABOUT,
Constants.DRAWER_ROUTE_SEARCH, Constants.DRAWER_ROUTE_SEARCH,
Constants.DRAWER_ROUTE_TRANSACTION_HISTORY, Constants.DRAWER_ROUTE_TRANSACTION_HISTORY,
Constants.DRAWER_ROUTE_CHANNEL_CREATOR,
]; ];
// sub-pages for main routes
export const InnerDrawerRoutes = [Constants.DRAWER_ROUTE_CHANNEL_CREATOR_FORM, Constants.DRAWER_ROUTE_PUBLISH_FORM];
-79
View File
@@ -1,79 +0,0 @@
import { NativeModules, Platform } from 'react-native';
import { SETTINGS } from 'lbry-redux';
import { doTransifexUpload } from 'lbryinc';
import AsyncStorage from '@react-native-community/async-storage';
import RNFS from 'react-native-fs';
const isProduction = !__DEV__; // eslint-disable-line no-undef
let knownMessages = null;
window.language = NativeModules.UtilityModule.language;
window.i18n_messages = window.i18n_messages || {};
function saveMessage(message) {
// file path that won't get wiped if app storage is cleared or the app is uninstalled
const messagesFilePath = RNFS.ExternalStorageDirectoryPath + '/lbry-app-strings.json';
if (knownMessages === null) {
RNFS.readFile(messagesFilePath, 'utf8')
.then(fileContents => {
knownMessages = JSON.parse(fileContents);
checkMessageAndSave(message, messagesFilePath);
})
.catch(err => {
knownMessages = {}; // no known messages, initialise the object
checkMessageAndSave(message, messagesFilePath);
});
} else {
checkMessageAndSave(message, messagesFilePath);
}
}
function checkMessageAndSave(message, messagesFilePath) {
if (!knownMessages[message]) {
knownMessages[message] = message;
const contents = JSON.stringify(knownMessages, null, 2);
RNFS.writeFile(messagesFilePath, contents, 'utf8')
.then(() => {
// successful write
// send to transifex (should we do this even if the file doesn't get saved?)
// TODO: load token from .env
/* doTransifexUpload(
contents,
'lbry-mobile',
'*token*',
() => {
// successful
},
err => {
// failed
}
); */
})
.catch(err => {
if (err) {
throw err;
}
});
}
}
export function __(message, tokens) {
const w = global.window ? global.window : window;
let language = w.language ? w.language : 'en';
if (!isProduction) {
saveMessage(message);
}
const translatedMessage = w.i18n_messages[language] ? w.i18n_messages[language][message] || message : message;
if (!tokens) {
return translatedMessage;
}
return translatedMessage.replace(/%([^%]+)%/g, function($1, $2) {
return tokens[$2] || $2;
});
}
+32 -67
View File
@@ -4,8 +4,6 @@ import { Provider, connect } from 'react-redux';
import { AppRegistry, Text, View, NativeModules } from 'react-native'; import { AppRegistry, Text, View, NativeModules } from 'react-native';
import { import {
Lbry, Lbry,
buildSharedStateMiddleware,
blockedReducer,
claimsReducer, claimsReducer,
contentReducer, contentReducer,
fileReducer, fileReducer,
@@ -15,24 +13,18 @@ import {
searchReducer, searchReducer,
tagsReducer, tagsReducer,
walletReducer, walletReducer,
ACTIONS as LBRY_REDUX_ACTIONS,
} from 'lbry-redux'; } from 'lbry-redux';
import { import {
Lbryio,
authReducer, authReducer,
blacklistReducer, blacklistReducer,
costInfoReducer, costInfoReducer,
doGetSync,
filteredReducer, filteredReducer,
homepageReducer, homepageReducer,
rewardsReducer, rewardsReducer,
selectUserVerifiedEmail,
subscriptionsReducer, subscriptionsReducer,
syncReducer, syncReducer,
userReducer, userReducer,
LBRYINC_ACTIONS,
} from 'lbryinc'; } from 'lbryinc';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { createStore, applyMiddleware, compose } from 'redux'; import { createStore, applyMiddleware, compose } from 'redux';
import AppWithNavigationState, { import AppWithNavigationState, {
AppNavigator, AppNavigator,
@@ -40,20 +32,15 @@ import AppWithNavigationState, {
reactNavigationMiddleware, reactNavigationMiddleware,
} from 'component/AppNavigator'; } from 'component/AppNavigator';
import { REHYDRATE, PURGE, persistCombineReducers, persistStore } from 'redux-persist'; import { REHYDRATE, PURGE, persistCombineReducers, persistStore } from 'redux-persist';
import { __ } from 'i18n';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import getStoredStateMigrateV4 from 'redux-persist/lib/integration/getStoredStateMigrateV4'; import getStoredStateMigrateV4 from 'redux-persist/lib/integration/getStoredStateMigrateV4';
import FilesystemStorage from 'redux-persist-filesystem-storage'; import FilesystemStorage from 'redux-persist-filesystem-storage';
import createCompressor from 'redux-persist-transform-compress'; import createCompressor from 'redux-persist-transform-compress';
import createFilter from 'redux-persist-transform-filter'; import createFilter from 'redux-persist-transform-filter';
import moment from 'moment'; import moment from 'moment';
import formReducer from 'redux/reducers/form';
import drawerReducer from 'redux/reducers/drawer'; import drawerReducer from 'redux/reducers/drawer';
import settingsReducer from 'redux/reducers/settings'; import settingsReducer from 'redux/reducers/settings';
import thunk from 'redux-thunk'; import thunk from 'redux-thunk';
window.__ = __;
const globalExceptionHandler = (error, isFatal) => { const globalExceptionHandler = (error, isFatal) => {
if (error && NativeModules.Firebase) { if (error && NativeModules.Firebase) {
NativeModules.Firebase.logException(isFatal, error.message ? error.message : 'No message', JSON.stringify(error)); NativeModules.Firebase.logException(isFatal, error.message ? error.message : 'No message', JSON.stringify(error));
@@ -91,27 +78,18 @@ function enableBatching(reducer) {
const compressor = createCompressor(); const compressor = createCompressor();
const authFilter = createFilter('auth', ['authToken']); const authFilter = createFilter('auth', ['authToken']);
const blockedFilter = createFilter('blocked', ['blockedChannels']);
const contentFilter = createFilter('content', ['positions']); const contentFilter = createFilter('content', ['positions']);
const saveClaimsFilter = createFilter('claims', ['claimsByUri']); const saveClaimsFilter = createFilter('claims', ['claimsByUri']);
const subscriptionsFilter = createFilter('subscriptions', ['enabledChannelNotifications', 'subscriptions', 'latest']); const subscriptionsFilter = createFilter('subscriptions', ['enabledChannelNotifications', 'subscriptions']);
const settingsFilter = createFilter('settings', ['clientSettings']); const settingsFilter = createFilter('settings', ['clientSettings']);
const tagsFilter = createFilter('tags', ['followedTags']); const tagsFilter = createFilter('tags', ['followedTags']);
const walletFilter = createFilter('wallet', ['receiveAddress']); const walletFilter = createFilter('wallet', ['receiveAddress']);
const v4PersistOptions = { const v4PersistOptions = {
whitelist: ['auth', 'blocked', 'claims', 'content', 'subscriptions', 'settings', 'tags', 'wallet'], whitelist: ['auth', 'claims', 'content', 'subscriptions', 'settings', 'tags', 'wallet'],
// Order is important. Needs to be compressed last or other transforms can't // Order is important. Needs to be compressed last or other transforms can't
// read the data // read the data
transforms: [ transforms: [authFilter, saveClaimsFilter, subscriptionsFilter, settingsFilter, walletFilter, compressor],
authFilter,
blockedFilter,
saveClaimsFilter,
subscriptionsFilter,
settingsFilter,
walletFilter,
compressor,
],
debounce: 10000, debounce: 10000,
storage: FilesystemStorage, storage: FilesystemStorage,
}; };
@@ -124,7 +102,6 @@ const persistOptions = Object.assign({}, v4PersistOptions, {
const reducers = persistCombineReducers(persistOptions, { const reducers = persistCombineReducers(persistOptions, {
auth: authReducer, auth: authReducer,
blacklist: blacklistReducer, blacklist: blacklistReducer,
blocked: blockedReducer,
claims: claimsReducer, claims: claimsReducer,
content: contentReducer, content: contentReducer,
costInfo: costInfoReducer, costInfo: costInfoReducer,
@@ -132,7 +109,6 @@ const reducers = persistCombineReducers(persistOptions, {
file: fileReducer, file: fileReducer,
fileInfo: fileInfoReducer, fileInfo: fileInfoReducer,
filtered: filteredReducer, filtered: filteredReducer,
form: formReducer,
homepage: homepageReducer, homepage: homepageReducer,
nav: navigatorReducer, nav: navigatorReducer,
notifications: notificationsReducer, notifications: notificationsReducer,
@@ -147,45 +123,8 @@ const reducers = persistCombineReducers(persistOptions, {
wallet: walletReducer, wallet: walletReducer,
}); });
/**
* source: the reducer name
* property: the property in the reducer-specific state
* transform: optional method to modify the value to be stored
*/
const sharedStateActions = [
LBRYINC_ACTIONS.CHANNEL_SUBSCRIBE,
LBRYINC_ACTIONS.CHANNEL_UNSUBSCRIBE,
LBRY_REDUX_ACTIONS.CREATE_CHANNEL_COMPLETED,
LBRY_REDUX_ACTIONS.TOGGLE_TAG_FOLLOW,
LBRY_REDUX_ACTIONS.TOGGLE_BLOCK_CHANNEL,
];
const sharedStateFilters = {
tags: { source: 'tags', property: 'followedTags' },
subscriptions: {
source: 'subscriptions',
property: 'subscriptions',
transform: function(value) {
return value.map(({ uri }) => uri);
},
},
blocked: { source: 'blocked', property: 'blockedChannels' },
};
const sharedStateCallback = ({ dispatch, getState }) => {
const state = getState();
const syncEnabled = makeSelectClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED)(state);
const emailVerified = selectUserVerifiedEmail(state);
if (syncEnabled && emailVerified) {
NativeModules.UtilityModule.getSecureValue(Constants.KEY_WALLET_PASSWORD).then(password =>
dispatch(doGetSync(password))
);
}
};
const sharedStateMiddleware = buildSharedStateMiddleware(sharedStateActions, sharedStateFilters, sharedStateCallback);
const bulkThunk = createBulkThunkMiddleware(); const bulkThunk = createBulkThunkMiddleware();
const middleware = [sharedStateMiddleware, thunk, bulkThunk, reactNavigationMiddleware]; const middleware = [thunk, bulkThunk, reactNavigationMiddleware];
// eslint-disable-next-line no-underscore-dangle // eslint-disable-next-line no-underscore-dangle
const composeEnhancers = compose; const composeEnhancers = compose;
@@ -197,12 +136,38 @@ const store = createStore(
); );
window.store = store; window.store = store;
const persistor = persistStore(store, persistOptions, err => { /* const persistor = persistStore(store, persistOptions, err => {
if (err) { if (err) {
console.log('Unable to load saved SETTINGS'); console.log('Unable to load saved SETTINGS');
} }
}); });
window.persistor = persistor; window.persistor = persistor; */
const persistFilter = {
auth: ['authToken'],
claims: ['byId', 'claimsByUri'],
content: ['positions'],
subscriptions: ['enabledChannelNotifications', 'subscriptions'],
settings: ['clientSettings'],
tags: ['followedTags'],
wallet: ['receiveAddress'],
};
store.subscribe(() => {
const state = (({ auth, claims, content, subscriptions, settings, tags, wallet }) => ({
auth,
claims,
content,
subscriptions,
settings,
tags,
wallet,
}))(store.getState());
NativeModules.StatePersistor.update(state, persistFilter);
});
// TODO: Find i18n module that is compatible with react-native
global.__ = str => str;
class LBRYApp extends React.Component { class LBRYApp extends React.Component {
render() { render() {
+38 -40
View File
@@ -2,7 +2,7 @@ import React from 'react';
import { Lbry } from 'lbry-redux'; import { Lbry } from 'lbry-redux';
import { NativeModules, Text, View, ScrollView } from 'react-native'; import { NativeModules, Text, View, ScrollView } from 'react-native';
import { navigateBack } from 'utils/helper'; import { navigateBack } from 'utils/helper';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import Link from 'component/link'; import Link from 'component/link';
import PageHeader from 'component/pageHeader'; import PageHeader from 'component/pageHeader';
import aboutStyle from 'styles/about'; import aboutStyle from 'styles/about';
@@ -18,7 +18,7 @@ class AboutPage extends React.PureComponent {
componentWillMount() { componentWillMount() {
const { navigation } = this.props; const { navigation } = this.props;
// this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused); this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
} }
componentWillUnmount() { componentWillUnmount() {
@@ -44,21 +44,19 @@ class AboutPage extends React.PureComponent {
pushDrawerStack(); pushDrawerStack();
setPlayerVisible(); setPlayerVisible();
NativeModules.Firebase.setCurrentScreen('About').then(result => { if (NativeModules.VersionInfo) {
if (NativeModules.VersionInfo) { NativeModules.VersionInfo.getAppVersion().then(version => {
NativeModules.VersionInfo.getAppVersion().then(version => { this.setState({ appVersion: version });
this.setState({ appVersion: version });
});
}
Lbry.version().then(info => {
this.setState({
versionInfo: info,
});
}); });
Lbry.status().then(info => { }
this.setState({ Lbry.version().then(info => {
lbryId: info.installation_id, this.setState({
}); versionInfo: info,
});
});
Lbry.status().then(info => {
this.setState({
lbryId: info.installation_id,
}); });
}); });
@@ -67,7 +65,7 @@ class AboutPage extends React.PureComponent {
render() { render() {
const { accessToken, drawerStack, navigation, notify, popDrawerStack, userEmail } = this.props; const { accessToken, drawerStack, navigation, notify, popDrawerStack, userEmail } = this.props;
const loading = __('Loading...'); const loading = 'Loading...';
const ver = this.state.versionInfo ? this.state.versionInfo : null; const ver = this.state.versionInfo ? this.state.versionInfo : null;
return ( return (
@@ -76,20 +74,20 @@ class AboutPage extends React.PureComponent {
<ScrollView style={aboutStyle.scrollContainer}> <ScrollView style={aboutStyle.scrollContainer}>
<Text style={aboutStyle.title}>Content Freedom</Text> <Text style={aboutStyle.title}>Content Freedom</Text>
<Text style={aboutStyle.paragraph}> <Text style={aboutStyle.paragraph}>
{__( LBRY is a free, open, and community-run digital marketplace. It is a decentralized peer-to-peer content
'LBRY is a free, open, and community-run digital marketplace. It is a decentralized peer-to-peer content distribution platform for creators to upload and share content, and earn LBRY credits for their effort. Users will be able to find a wide selection of videos, music, ebooks and other digital content they are interested in.' distribution platform for creators to upload and share content, and earn LBRY credits for their effort.
)} Users will be able to find a wide selection of videos, music, ebooks and other digital content they are
interested in.
</Text> </Text>
<View style={aboutStyle.links}> <View style={aboutStyle.links}>
<Link style={aboutStyle.link} href="https://lbry.com/faq/what-is-lbry" text={__('What is LBRY?')} /> <Link style={aboutStyle.link} href="https://lbry.com/faq/what-is-lbry" text="What is LBRY?" />
<Link style={aboutStyle.link} href="https://lbry.com/faq/android-basics" text={__('Android App Basics')} /> <Link style={aboutStyle.link} href="https://lbry.com/faq/android-basics" text="Android App Basics" />
<Link style={aboutStyle.link} href="https://lbry.com/faq" text={__('Frequently Asked Questions')} /> <Link style={aboutStyle.link} href="https://lbry.com/faq" text="Frequently Asked Questions" />
</View> </View>
<Text style={aboutStyle.socialTitle}>Get Social</Text> <Text style={aboutStyle.socialTitle}>Get Social</Text>
<Text style={aboutStyle.paragraph}> <Text style={aboutStyle.paragraph}>
{__( You can interact with the LBRY team and members of the community on Discord, Facebook, Instagram, Twitter or
'You can interact with the LBRY team and members of the community on Discord, Facebook, Instagram, Twitter or Reddit.' Reddit.
)}
</Text> </Text>
<View style={aboutStyle.links}> <View style={aboutStyle.links}>
<Link style={aboutStyle.link} href="https://discordapp.com/invite/Z3bERWA" text="Discord" /> <Link style={aboutStyle.link} href="https://discordapp.com/invite/Z3bERWA" text="Discord" />
@@ -99,15 +97,15 @@ class AboutPage extends React.PureComponent {
<Link style={aboutStyle.link} href="https://reddit.com/r/lbry" text="Reddit" /> <Link style={aboutStyle.link} href="https://reddit.com/r/lbry" text="Reddit" />
<Link style={aboutStyle.link} href="https://t.me/lbryofficial" text="Telegram" /> <Link style={aboutStyle.link} href="https://t.me/lbryofficial" text="Telegram" />
</View> </View>
<Text style={aboutStyle.releaseInfoTitle}>{__('App info')}</Text> <Text style={aboutStyle.releaseInfoTitle}>App info</Text>
{userEmail && userEmail.trim().length > 0 && ( {userEmail && userEmail.trim().length > 0 && (
<View style={aboutStyle.verticalRow}> <View style={aboutStyle.verticalRow}>
<View style={aboutStyle.innerRow}> <View style={aboutStyle.innerRow}>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text style={aboutStyle.text}>{__('Connected email')}</Text> <Text style={aboutStyle.text}>Connected email</Text>
</View> </View>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text selectable style={aboutStyle.valueText}> <Text selectable={true} style={aboutStyle.valueText}>
{userEmail} {userEmail}
</Text> </Text>
</View> </View>
@@ -116,7 +114,7 @@ class AboutPage extends React.PureComponent {
<Link <Link
style={aboutStyle.listLink} style={aboutStyle.listLink}
href={`http://lbry.com/list/edit/${accessToken}`} href={`http://lbry.com/list/edit/${accessToken}`}
text={__('Update mailing preferences')} text="Update mailing preferences"
/> />
</View> </View>
</View> </View>
@@ -124,10 +122,10 @@ class AboutPage extends React.PureComponent {
<View style={aboutStyle.row}> <View style={aboutStyle.row}>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text style={aboutStyle.text}>{__('App version')}</Text> <Text style={aboutStyle.text}>App version</Text>
</View> </View>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text selectable style={aboutStyle.valueText}> <Text selectable={true} style={aboutStyle.valueText}>
{this.state.appVersion} {this.state.appVersion}
</Text> </Text>
</View> </View>
@@ -135,10 +133,10 @@ class AboutPage extends React.PureComponent {
<View style={aboutStyle.row}> <View style={aboutStyle.row}>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text style={aboutStyle.text}>{__('LBRY SDK')}</Text> <Text style={aboutStyle.text}>Daemon (lbrynet)</Text>
</View> </View>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text selectable style={aboutStyle.valueText}> <Text selectable={true} style={aboutStyle.valueText}>
{ver ? ver.lbrynet_version : loading} {ver ? ver.lbrynet_version : loading}
</Text> </Text>
</View> </View>
@@ -146,10 +144,10 @@ class AboutPage extends React.PureComponent {
<View style={aboutStyle.row}> <View style={aboutStyle.row}>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text style={aboutStyle.text}>{__('Platform')}</Text> <Text style={aboutStyle.text}>Platform</Text>
</View> </View>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text selectable style={aboutStyle.valueText}> <Text selectable={true} style={aboutStyle.valueText}>
{ver ? ver.platform : loading} {ver ? ver.platform : loading}
</Text> </Text>
</View> </View>
@@ -157,8 +155,8 @@ class AboutPage extends React.PureComponent {
<View style={aboutStyle.row}> <View style={aboutStyle.row}>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text style={aboutStyle.text}>{__('Installation ID')}</Text> <Text style={aboutStyle.text}>Installation ID</Text>
<Text selectable style={aboutStyle.lineValueText}> <Text selectable={true} style={aboutStyle.lineValueText}>
{this.state.lbryId ? this.state.lbryId : loading} {this.state.lbryId ? this.state.lbryId : loading}
</Text> </Text>
</View> </View>
@@ -166,12 +164,12 @@ class AboutPage extends React.PureComponent {
<View style={aboutStyle.row}> <View style={aboutStyle.row}>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Text style={aboutStyle.text}>{__('Logs')}</Text> <Text style={aboutStyle.text}>Logs</Text>
</View> </View>
<View style={aboutStyle.col}> <View style={aboutStyle.col}>
<Link <Link
style={aboutStyle.listLink} style={aboutStyle.listLink}
text={__('Send log')} text="Send log"
onPress={() => { onPress={() => {
if (NativeModules.UtilityModule) { if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.shareLogFile(error => { NativeModules.UtilityModule.shareLogFile(error => {
+11 -10
View File
@@ -1,25 +1,26 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { doAbandonClaim, doFetchChannelListMine, makeSelectClaimForUri, selectMyChannelClaims } from 'lbry-redux'; import {
doFetchClaimsByChannel,
makeSelectClaimForUri,
makeSelectClaimsInChannelForCurrentPageState,
makeSelectFetchingChannelClaims,
makeSelectTotalPagesForChannel,
} from 'lbry-redux';
import { doPopDrawerStack } from 'redux/actions/drawer'; import { doPopDrawerStack } from 'redux/actions/drawer';
import { doSetSortByItem, doSetTimeItem } from 'redux/actions/settings';
import { selectDrawerStack } from 'redux/selectors/drawer'; import { selectDrawerStack } from 'redux/selectors/drawer';
import { selectSortByItem, selectTimeItem } from 'redux/selectors/settings';
import ChannelPage from './view'; import ChannelPage from './view';
const select = (state, props) => ({ const select = (state, props) => ({
channels: selectMyChannelClaims(state),
claim: makeSelectClaimForUri(props.uri)(state), claim: makeSelectClaimForUri(props.uri)(state),
claimsInChannel: makeSelectClaimsInChannelForCurrentPageState(props.uri)(state),
drawerStack: selectDrawerStack(state), drawerStack: selectDrawerStack(state),
sortByItem: selectSortByItem(state), fetching: makeSelectFetchingChannelClaims(props.uri)(state),
timeItem: selectTimeItem(state), totalPages: makeSelectTotalPagesForChannel(props.uri, 10)(state), // Update to use a default PAGE_SIZE constant
}); });
const perform = dispatch => ({ const perform = dispatch => ({
abandonClaim: (txid, nout) => dispatch(doAbandonClaim(txid, nout)), fetchClaims: (uri, page) => dispatch(doFetchClaimsByChannel(uri, page)),
fetchChannelListMine: () => dispatch(doFetchChannelListMine()),
popDrawerStack: () => dispatch(doPopDrawerStack()), popDrawerStack: () => dispatch(doPopDrawerStack()),
setSortByItem: item => dispatch(doSetSortByItem(item)),
setTimeItem: item => dispatch(doSetTimeItem(item)),
}); });
export default connect( export default connect(
+104 -215
View File
@@ -1,116 +1,111 @@
// @flow // @flow
import React from 'react'; import React from 'react';
import { import { ActivityIndicator, Dimensions, Image, ScrollView, Text, TouchableOpacity, View } from 'react-native';
ActivityIndicator,
Alert,
Dimensions,
Image,
NativeModules,
ScrollView,
Text,
TouchableOpacity,
View,
} from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view'; import { TabView, SceneMap } from 'react-native-tab-view';
import { normalizeURI } from 'lbry-redux'; import { navigateBack } from 'utils/helper';
import { navigateBack, getOrderBy, formatLbryUrlForWeb } from 'utils/helper';
import ChannelIconItem from 'component/channelIconItem';
import ClaimList from 'component/claimList';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import Button from 'component/button'; import Button from 'component/button';
import EmptyStateView from 'component/emptyStateView';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Link from 'component/link'; import Link from 'component/link';
import ModalPicker from 'component/modalPicker'; import FileList from 'component/fileList';
import PageHeader from 'component/pageHeader'; import PageHeader from 'component/pageHeader';
import SubscribeButton from 'component/subscribeButton'; import SubscribeButton from 'component/subscribeButton';
import SubscribeNotificationButton from 'component/subscribeNotificationButton';
import UriBar from 'component/uriBar'; import UriBar from 'component/uriBar';
import channelIconStyle from 'styles/channelIcon';
import channelPageStyle from 'styles/channelPage'; import channelPageStyle from 'styles/channelPage';
import discoverStyle from 'styles/discover';
class ChannelPage extends React.PureComponent { class ChannelPage extends React.PureComponent {
state = { state = {
autoStyle: null, page: 1,
showSortPicker: false, showPageButtons: false,
showTimePicker: false,
orderBy: ['release_time'], // sort by new by default
activeTab: Constants.CONTENT_TAB, activeTab: Constants.CONTENT_TAB,
}; };
componentWillMount() {
this.setState({
autoStyle:
ChannelIconItem.AUTO_THUMB_STYLES[Math.floor(Math.random() * ChannelIconItem.AUTO_THUMB_STYLES.length)],
});
}
componentDidMount() { componentDidMount() {
const { fetchChannelListMine, setSortByItem } = this.props; const { uri, page, claimsInChannel, fetchClaims, fetchClaimCount } = this.props;
NativeModules.Firebase.setCurrentScreen('Channel');
setSortByItem(Constants.CLAIM_SEARCH_SORT_BY_ITEMS[1]); // sort by newest first if (!claimsInChannel || !claimsInChannel.length) {
fetchChannelListMine(); fetchClaims(uri, page || this.state.page);
}
} }
handleSortByItemSelected = item => { handlePreviousPage = () => {
const { setSortByItem } = this.props; const { uri, fetchClaims } = this.props;
setSortByItem(item); if (this.state.page > 1) {
this.setState({ orderBy: getOrderBy(item), showSortPicker: false }); this.setState({ page: this.state.page - 1, showPageButtons: false }, () => {
fetchClaims(uri, this.state.page);
});
}
}; };
handleTimeItemSelected = item => { handleNextPage = () => {
const { setTimeItem } = this.props; const { uri, fetchClaims, totalPages } = this.props;
setTimeItem(item); if (this.state.page < totalPages) {
this.setState({ showTimePicker: false }); this.setState({ page: this.state.page + 1, showPageButtons: false }, () => {
}; fetchClaims(uri, this.state.page);
});
listHeader = () => { }
const { sortByItem, timeItem } = this.props;
return (
<View style={channelPageStyle.listHeader}>
<View style={discoverStyle.pickerRow}>
<View style={discoverStyle.leftPickerRow}>
<TouchableOpacity style={discoverStyle.tagSortBy} onPress={() => this.setState({ showSortPicker: true })}>
<Text style={discoverStyle.tagSortText}>{__(sortByItem.label.split(' ')[0])}</Text>
<Icon style={discoverStyle.tagSortIcon} name={'sort-down'} size={14} />
</TouchableOpacity>
{Constants.SORT_BY_TOP === sortByItem.name && (
<TouchableOpacity style={discoverStyle.tagTime} onPress={() => this.setState({ showTimePicker: true })}>
<Text style={discoverStyle.tagSortText}>{__(timeItem.label)}</Text>
<Icon style={discoverStyle.tagSortIcon} name={'sort-down'} size={14} />
</TouchableOpacity>
)}
</View>
</View>
</View>
);
}; };
renderContent = () => { renderContent = () => {
const { claim, navigation, timeItem } = this.props; const { fetching, claimsInChannel, totalPages, navigation } = this.props;
let channelId; let contentList;
if (claim) { if (fetching) {
channelId = claim.claim_id; contentList = (
<View style={channelPageStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.NextLbryGreen} />
<Text style={channelPageStyle.infoText}>Fetching content...</Text>
</View>
);
} else {
contentList =
claimsInChannel && claimsInChannel.length ? (
<FileList
sortByHeight
hideFilter
fileInfos={claimsInChannel}
navigation={navigation}
style={channelPageStyle.fileList}
contentContainerStyle={channelPageStyle.fileListContent}
onEndReached={() => this.setState({ showPageButtons: true })}
/>
) : (
<View style={channelPageStyle.busyContainer}>
<Text style={channelPageStyle.infoText}>No content found.</Text>
</View>
);
}
let pageButtons;
if (totalPages > 1 && this.state.showPageButtons) {
pageButtons = (
<View style={channelPageStyle.pageButtons}>
<View>
{this.state.page > 1 && (
<Button
style={channelPageStyle.button}
text={'Previous'}
disabled={!!fetching}
onPress={this.handlePreviousPage}
/>
)}
</View>
{this.state.page < totalPages && (
<Button
style={[channelPageStyle.button, channelPageStyle.nextButton]}
text={'Next'}
disabled={!!fetching}
onPress={this.handleNextPage}
/>
)}
</View>
);
} }
return ( return (
<View style={channelPageStyle.contentTab}> <View style={channelPageStyle.contentTab}>
{channelId && ( {contentList}
<ClaimList {pageButtons}
ListHeaderComponent={this.listHeader}
hideChannel
orderBy={this.state.orderBy}
time={timeItem.name}
navigation={navigation}
orientation={Constants.ORIENTATION_VERTICAL}
channelIds={[channelId]}
style={channelPageStyle.claimList}
/>
)}
</View> </View>
); );
}; };
@@ -122,7 +117,7 @@ class ChannelPage extends React.PureComponent {
return ( return (
<View style={channelPageStyle.aboutTab}> <View style={channelPageStyle.aboutTab}>
<View style={channelPageStyle.busyContainer}> <View style={channelPageStyle.busyContainer}>
<Text style={channelPageStyle.infoText}>{__('No information to display.')}</Text> <Text style={channelPageStyle.infoText}>No information to display.</Text>
</View> </View>
</View> </View>
); );
@@ -132,21 +127,23 @@ class ChannelPage extends React.PureComponent {
return ( return (
<View style={channelPageStyle.aboutTab}> <View style={channelPageStyle.aboutTab}>
{!websiteUrl && !email && !description && ( {!websiteUrl && !email && !description && (
<EmptyStateView message={__("There's nothing here yet.\nPlease check back later.")} /> <View style={channelPageStyle.busyContainer}>
<Text style={channelPageStyle.infoText}>Nothing here yet. Please check back later.</Text>
</View>
)} )}
{(websiteUrl || email || description) && ( {(websiteUrl || email || description) && (
<ScrollView style={channelPageStyle.aboutScroll} contentContainerStyle={channelPageStyle.aboutScrollContent}> <ScrollView style={channelPageStyle.aboutScroll} contentContainerStyle={channelPageStyle.aboutScrollContent}>
{websiteUrl && websiteUrl.trim().length > 0 && ( {websiteUrl && websiteUrl.trim().length > 0 && (
<View style={channelPageStyle.aboutItem}> <View style={channelPageStyle.aboutItem}>
<Text style={channelPageStyle.aboutTitle}>{__('Website')}</Text> <Text style={channelPageStyle.aboutTitle}>Website</Text>
<Link style={channelPageStyle.aboutText} text={websiteUrl} href={websiteUrl} /> <Link style={channelPageStyle.aboutText} text={websiteUrl} href={websiteUrl} />
</View> </View>
)} )}
{email && email.trim().length > 0 && ( {email && email.trim().length > 0 && (
<View style={channelPageStyle.aboutItem}> <View style={channelPageStyle.aboutItem}>
<Text style={channelPageStyle.aboutTitle}>{__('Email')}</Text> <Text style={channelPageStyle.aboutTitle}>Email</Text>
<Link style={channelPageStyle.aboutText} text={email} href={`mailto:${email}`} /> <Link style={channelPageStyle.aboutText} text={email} href={`mailto:${email}`} />
</View> </View>
)} )}
@@ -162,76 +159,19 @@ class ChannelPage extends React.PureComponent {
); );
}; };
onEditPressed = () => {
const { claim, navigation } = this.props;
if (claim) {
const { permanent_url: permanentUrl } = claim;
navigation.navigate({
routeName: Constants.DRAWER_ROUTE_CHANNEL_CREATOR,
params: { editChannelUrl: permanentUrl },
});
}
};
onSharePressed = () => {
const { claim } = this.props;
if (claim) {
const { canonical_url: canonicalUrl, short_url: shortUrl, permanent_url: permanentUrl } = claim;
const url = Constants.SHARE_BASE_URL + formatLbryUrlForWeb(canonicalUrl || shortUrl || permanentUrl);
NativeModules.UtilityModule.shareUrl(url);
}
};
onDeletePressed = () => {
const { abandonClaim, claim, navigation } = this.props;
if (claim) {
const { txid, nout } = claim;
// show confirm alert
Alert.alert(
__('Delete channel'),
__('Are you sure you want to delete this channel?'),
[
{ text: __('No') },
{
text: __('Yes'),
onPress: () => {
abandonClaim(txid, nout);
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_CHANNEL_CREATOR });
},
},
],
{ cancelable: true }
);
}
};
render() { render() {
const { channels, claim, navigation, uri, drawerStack, popDrawerStack, sortByItem, timeItem } = this.props; const { fetching, claimsInChannel, claim, navigation, totalPages, uri, drawerStack, popDrawerStack } = this.props;
const { name, permanent_url: permanentUrl } = claim; const { name, permanent_url: permanentUrl } = claim;
const { autoStyle, showSortPicker, showTimePicker } = this.state;
const ownedChannel = channels ? channels.map(channel => channel.permanent_url).includes(permanentUrl) : false;
let thumbnailUrl, let thumbnailUrl, coverUrl, title;
coverUrl, if (claim && claim.value) {
title, title = claim.value.title;
fullUri, if (claim.value.cover) {
displayName = null, coverUrl = claim.value.cover.url;
substrIndex = 0; }
if (claim) { if (claim.value.thumbnail) {
if (claim.value) { thumbnailUrl = claim.value.thumbnail.url;
title = claim.value.title;
if (claim.value.cover) {
coverUrl = claim.value.cover.url;
}
if (claim.value.thumbnail) {
thumbnailUrl = claim.value.thumbnail.url;
}
} }
displayName = title || claim.name;
substrIndex = displayName.startsWith('@') ? 1 : 0;
fullUri = normalizeURI(`${claim.name}#${claim.claim_id}`);
} }
return ( return (
@@ -254,51 +194,19 @@ class ChannelPage extends React.PureComponent {
<Text style={channelPageStyle.channelName}>{title && title.trim().length > 0 ? title : name}</Text> <Text style={channelPageStyle.channelName}>{title && title.trim().length > 0 ? title : name}</Text>
</View> </View>
<View style={[channelPageStyle.avatarImageContainer, autoStyle]}> <View style={channelPageStyle.avatarImageContainer}>
{thumbnailUrl && ( <Image
<Image style={channelPageStyle.avatarImage} resizeMode={'cover'} source={{ uri: thumbnailUrl }} /> style={channelPageStyle.avatarImage}
)} resizeMode={'cover'}
{(!thumbnailUrl || thumbnailUrl.trim().length === 0) && ( source={
<Text style={channelIconStyle.autothumbCharacter}> thumbnailUrl && thumbnailUrl.trim().length > 0
{displayName.substring(substrIndex, substrIndex + 1).toUpperCase()} ? { uri: thumbnailUrl }
</Text> : require('../../assets/default_avatar.jpg')
)} }
/>
</View> </View>
<View style={channelPageStyle.subscribeButtonContainer}> <SubscribeButton style={channelPageStyle.subscribeButton} uri={uri} name={name} />
{ownedChannel && (
<Button
style={channelPageStyle.actionButton}
theme={'light'}
icon={'edit'}
text={'Edit'}
onPress={this.onEditPressed}
/>
)}
{ownedChannel && (
<Button
style={[channelPageStyle.actionButton, channelPageStyle.deleteButton]}
theme={'light'}
icon={'trash-alt'}
text={'Delete'}
onPress={this.onDeletePressed}
/>
)}
<Button
style={[channelPageStyle.actionButton, channelPageStyle.shareButton]}
theme={'light'}
icon={'share-alt'}
onPress={this.onSharePressed}
/>
{!ownedChannel && <SubscribeButton style={channelPageStyle.subscribeButton} uri={fullUri} name={name} />}
{false && !ownedChannel && (
<SubscribeNotificationButton
style={[channelPageStyle.subscribeButton, channelPageStyle.bellButton]}
uri={fullUri}
name={name}
/>
)}
</View>
</View> </View>
<View style={channelPageStyle.tabBar}> <View style={channelPageStyle.tabBar}>
@@ -321,25 +229,6 @@ class ChannelPage extends React.PureComponent {
{Constants.CONTENT_TAB === this.state.activeTab && this.renderContent()} {Constants.CONTENT_TAB === this.state.activeTab && this.renderContent()}
{Constants.ABOUT_TAB === this.state.activeTab && this.renderAbout()} {Constants.ABOUT_TAB === this.state.activeTab && this.renderAbout()}
</View> </View>
{showSortPicker && (
<ModalPicker
title={__('Sort content by')}
onOverlayPress={() => this.setState({ showSortPicker: false })}
onItemSelected={this.handleSortByItemSelected}
selectedItem={sortByItem}
items={Constants.CLAIM_SEARCH_SORT_BY_ITEMS}
/>
)}
{showTimePicker && (
<ModalPicker
title={__('Content from')}
onOverlayPress={() => this.setState({ showTimePicker: false })}
onItemSelected={this.handleTimeItemSelected}
selectedItem={timeItem}
items={Constants.CLAIM_SEARCH_TIME_ITEMS}
/>
)}
</View> </View>
); );
} }
-52
View File
@@ -1,52 +0,0 @@
import { connect } from 'react-redux';
import {
selectAbandoningIds,
selectBalance,
selectMyChannelClaims,
selectFetchingMyChannels,
selectUpdatingChannel,
selectUpdateChannelError,
doAbandonClaim,
doFetchChannelListMine,
doCreateChannel,
doUpdateChannel,
doToast,
} from 'lbry-redux';
import { doGetSync } from 'lbryinc';
import { doPushDrawerStack, doPopDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { doUpdateChannelFormState, doClearChannelFormState } from 'redux/actions/form';
import { selectDrawerStack } from 'redux/selectors/drawer';
import { selectChannelFormState, selectHasChannelFormState } from 'redux/selectors/form';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import ChannelCreator from './view';
const select = state => ({
abandoningClaimIds: selectAbandoningIds(state),
channels: selectMyChannelClaims(state),
channelFormState: selectChannelFormState(state),
drawerStack: selectDrawerStack(state),
fetchingChannels: selectFetchingMyChannels(state),
balance: selectBalance(state),
hasFormState: selectHasChannelFormState(state),
updatingChannel: selectUpdatingChannel(state),
updateChannelError: selectUpdateChannelError(state),
});
const perform = dispatch => ({
abandonClaim: (txid, nout) => dispatch(doAbandonClaim(txid, nout)),
notify: data => dispatch(doToast(data)),
clearChannelFormState: () => dispatch(doClearChannelFormState()),
createChannel: (name, amount, optionalParams) => dispatch(doCreateChannel(name, amount, optionalParams)),
fetchChannelListMine: () => dispatch(doFetchChannelListMine()),
getSync: (password, callback) => dispatch(doGetSync(password, callback)),
updateChannel: params => dispatch(doUpdateChannel(params)),
updateChannelFormState: data => dispatch(doUpdateChannelFormState(data)),
pushDrawerStack: (routeName, params) => dispatch(doPushDrawerStack(routeName, params)),
popDrawerStack: () => dispatch(doPopDrawerStack()),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false)),
});
export default connect(
select,
perform
)(ChannelCreator);
File diff suppressed because it is too large. Load diff
+12 -9
View File
@@ -1,5 +1,12 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { doClaimSearch, doFileList, selectBalance, selectFileInfosDownloaded, selectFollowedTags } from 'lbry-redux'; import {
doClaimSearch,
doFileList,
selectBalance,
selectFileInfosDownloaded,
selectLastClaimSearchUris,
selectFollowedTags,
} from 'lbry-redux';
import { import {
doFetchFeaturedUris, doFetchFeaturedUris,
doFetchRewardedContent, doFetchRewardedContent,
@@ -11,9 +18,9 @@ import {
selectSubscriptionClaims, selectSubscriptionClaims,
selectUnreadSubscriptions, selectUnreadSubscriptions,
} from 'lbryinc'; } from 'lbryinc';
import { doPushDrawerStack } from 'redux/actions/drawer';
import { doSetClientSetting, doSetSortByItem, doSetTimeItem } from 'redux/actions/settings'; import { doSetClientSetting } from 'redux/actions/settings';
import { makeSelectClientSetting, selectSortByItem, selectTimeItem } from 'redux/selectors/settings'; import { makeSelectClientSetting } from 'redux/selectors/settings';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import DiscoverPage from './view'; import DiscoverPage from './view';
@@ -27,9 +34,8 @@ const select = state => ({
followedTags: selectFollowedTags(state), followedTags: selectFollowedTags(state),
ratingReminderDisabled: makeSelectClientSetting(Constants.SETTING_RATING_REMINDER_DISABLED)(state), ratingReminderDisabled: makeSelectClientSetting(Constants.SETTING_RATING_REMINDER_DISABLED)(state),
ratingReminderLastShown: makeSelectClientSetting(Constants.SETTING_RATING_REMINDER_LAST_SHOWN)(state), ratingReminderLastShown: makeSelectClientSetting(Constants.SETTING_RATING_REMINDER_LAST_SHOWN)(state),
sortByItem: selectSortByItem(state),
timeItem: selectTimeItem(state),
unreadSubscriptions: selectUnreadSubscriptions(state), unreadSubscriptions: selectUnreadSubscriptions(state),
uris: selectLastClaimSearchUris(state),
}); });
const perform = dispatch => ({ const perform = dispatch => ({
@@ -38,11 +44,8 @@ const perform = dispatch => ({
fetchRewardedContent: () => dispatch(doFetchRewardedContent()), fetchRewardedContent: () => dispatch(doFetchRewardedContent()),
fetchSubscriptions: () => dispatch(doFetchMySubscriptions()), fetchSubscriptions: () => dispatch(doFetchMySubscriptions()),
fileList: () => dispatch(doFileList()), fileList: () => dispatch(doFileList()),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_DISCOVER)),
removeUnreadSubscriptions: () => dispatch(doRemoveUnreadSubscriptions()), removeUnreadSubscriptions: () => dispatch(doRemoveUnreadSubscriptions()),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)), setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
setSortByItem: item => dispatch(doSetSortByItem(item)),
setTimeItem: item => dispatch(doSetTimeItem(item)),
}); });
export default connect( export default connect(
+118 -188
View File
@@ -11,9 +11,10 @@ import {
View, View,
} from 'react-native'; } from 'react-native';
import { DEFAULT_FOLLOWED_TAGS, Lbry, normalizeURI, parseURI } from 'lbry-redux'; import { DEFAULT_FOLLOWED_TAGS, Lbry, normalizeURI, parseURI } from 'lbry-redux';
import { formatTagTitle, getOrderBy } from 'utils/helper'; import { __, formatTagTitle } from 'utils/helper';
import AsyncStorage from '@react-native-community/async-storage'; import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment'; import moment from 'moment';
import CategoryList from 'component/categoryList';
import ClaimList from 'component/claimList'; import ClaimList from 'component/claimList';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import Colors from 'styles/colors'; import Colors from 'styles/colors';
@@ -29,11 +30,10 @@ import _ from 'lodash';
class DiscoverPage extends React.PureComponent { class DiscoverPage extends React.PureComponent {
state = { state = {
tagCollection: [], tagCollection: [],
remainingTags: [],
showModalTagSelector: false, showModalTagSelector: false,
showSortPicker: false, showSortPicker: false,
showTimePicker: false,
orderBy: Constants.DEFAULT_ORDER_BY, orderBy: Constants.DEFAULT_ORDER_BY,
currentSortByItem: Constants.CLAIM_SEARCH_SORT_BY_ITEMS[0],
}; };
componentDidMount() { componentDidMount() {
@@ -60,50 +60,33 @@ class DiscoverPage extends React.PureComponent {
} }
}); });
const { sortByItem, fetchRewardedContent, fileList, followedTags } = this.props; const { fetchRewardedContent, fetchSubscriptions, fileList, followedTags } = this.props;
this.buildTagCollection(followedTags); this.buildTagCollection(followedTags);
fetchRewardedContent(); fetchRewardedContent();
fetchSubscriptions();
fileList(); fileList();
this.handleSortByItemSelected(sortByItem);
this.showRatingReminder(); this.showRatingReminder();
this.onComponentFocused();
} }
componentWillReceiveProps(nextProps) {
const { currentRoute: prevRoute, followedTags: prevFollowedTags } = this.props;
const { currentRoute, followedTags } = nextProps;
if (Constants.DRAWER_ROUTE_DISCOVER === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
if (!_.isEqual(followedTags, prevFollowedTags)) {
this.buildTagCollection(followedTags);
}
}
onComponentFocused = () => {
const { fetchSubscriptions, pushDrawerStack } = this.props;
// pushDrawerStack();
NativeModules.Firebase.setCurrentScreen('Your tags').then(result => {
fetchSubscriptions();
});
};
handleSortByItemSelected = item => { handleSortByItemSelected = item => {
const { setSortByItem } = this.props; let orderBy = [];
setSortByItem(item); switch (item.name) {
const orderBy = getOrderBy(item); case Constants.SORT_BY_HOT:
this.setState({ orderBy, showSortPicker: false }); orderBy = Constants.DEFAULT_ORDER_BY;
}; break;
handleTimeItemSelected = item => { case Constants.SORT_BY_NEW:
const { setTimeItem } = this.props; orderBy = ['release_time'];
setTimeItem(item); break;
this.setState({ showTimePicker: false });
case Constants.SORT_BY_TOP:
orderBy = ['effective_amount'];
break;
}
this.setState({ currentSortByItem: item, orderBy, showSortPicker: false });
}; };
subscriptionForUri = (uri, channelName) => { subscriptionForUri = (uri, channelName) => {
@@ -123,43 +106,56 @@ class DiscoverPage extends React.PureComponent {
return null; return null;
}; };
componentWillReceiveProps(nextProps) {
const { followedTags: prevFollowedTags } = this.props;
const { followedTags } = nextProps;
if (!_.isEqual(followedTags, prevFollowedTags)) {
this.buildTagCollection(followedTags);
}
}
componentDidUpdate(prevProps, prevState) { componentDidUpdate(prevProps, prevState) {
const { unreadSubscriptions, enabledChannelNotifications } = this.props; const { unreadSubscriptions, enabledChannelNotifications } = this.props;
const utility = NativeModules.UtilityModule; const utility = NativeModules.UtilityModule;
const hasUnread = if (utility) {
prevProps.unreadSubscriptions && const hasUnread =
prevProps.unreadSubscriptions.length !== unreadSubscriptions.length && prevProps.unreadSubscriptions &&
unreadSubscriptions.length > 0; prevProps.unreadSubscriptions.length !== unreadSubscriptions.length &&
unreadSubscriptions.length > 0;
if (hasUnread) { if (hasUnread) {
unreadSubscriptions.map(({ channel, uris }) => { unreadSubscriptions.map(({ channel, uris }) => {
const { claimName: channelName } = parseURI(channel); const { claimName: channelName } = parseURI(channel);
// check if notifications are enabled for the channel // check if notifications are enabled for the channel
if (enabledChannelNotifications.includes(channelName)) { if (enabledChannelNotifications.indexOf(channelName) > -1) {
uris.forEach(uri => { uris.forEach(uri => {
Lbry.resolve({ urls: uri }).then(result => { Lbry.resolve({ urls: uri }).then(result => {
const sub = result[uri]; const sub = result[uri].claim;
if (sub && sub.value && sub.value.stream) {
if (sub && sub.value) { let isPlayable = false;
const { source, title, thumbnail } = sub.value; const source = sub.value.stream.source;
const isPlayable = const metadata = sub.value.stream.metadata;
source && source.media_type && ['audio', 'video'].includes(source.media_type.substring(0, 5)); if (source) {
if (title) { isPlayable =
utility.showNotificationForContent( source.contentType && ['audio', 'video'].indexOf(source.contentType.substring(0, 5)) > -1;
uri, }
title, if (metadata) {
channelName, utility.showNotificationForContent(
thumbnail ? thumbnail.url : null, uri,
isPlayable metadata.title,
); channelName,
metadata.thumbnail,
isPlayable
);
}
} }
} });
}); });
}); }
} });
}); }
} }
} }
@@ -175,18 +171,16 @@ class DiscoverPage extends React.PureComponent {
if (!isNaN(lastShownTime) && !isNaN(lastShownCount)) { if (!isNaN(lastShownTime) && !isNaN(lastShownCount)) {
if (now > lastShownTime + Constants.RATING_REMINDER_INTERVAL * lastShownCount) { if (now > lastShownTime + Constants.RATING_REMINDER_INTERVAL * lastShownCount) {
Alert.alert( Alert.alert(
__('Enjoying LBRY?'), 'Enjoying LBRY?',
__( 'Are you enjoying your experience with the LBRY app? You can leave a review for us on the Play Store.',
'Are you enjoying your experience with the LBRY app? You can leave a review for us on the Play Store.'
),
[ [
{ {
text: __('Never ask again'), text: 'Never ask again',
onPress: () => setClientSetting(Constants.SETTING_RATING_REMINDER_DISABLED, 'true'), onPress: () => setClientSetting(Constants.SETTING_RATING_REMINDER_DISABLED, 'true'),
}, },
{ text: __('Maybe later'), onPress: () => this.updateRatingReminderShown(lastShownCount) }, { text: 'Maybe later', onPress: () => this.updateRatingReminderShown(lastShownCount) },
{ {
text: __('Rate app'), text: 'Rate app',
onPress: () => { onPress: () => {
setClientSetting(Constants.SETTING_RATING_REMINDER_DISABLED, 'true'); setClientSetting(Constants.SETTING_RATING_REMINDER_DISABLED, 'true');
Linking.openURL(Constants.PLAY_STORE_URL); Linking.openURL(Constants.PLAY_STORE_URL);
@@ -213,7 +207,7 @@ class DiscoverPage extends React.PureComponent {
buildSections = () => { buildSections = () => {
return this.state.tagCollection.map(tags => ({ return this.state.tagCollection.map(tags => ({
title: tags.length === 1 ? tags[0] : __('All tags you follow'), title: tags.length === 1 ? tags[0] : 'All tags you follow',
data: [tags], data: [tags],
})); }));
}; };
@@ -223,136 +217,81 @@ class DiscoverPage extends React.PureComponent {
// each of the followed tags // each of the followed tags
const tagCollection = _.shuffle(tags) const tagCollection = _.shuffle(tags)
.slice(0, 5) .slice(0, 6)
.map(tag => [tag]); .map(tag => [tag]);
const usedTags = tagCollection.map(tagList => tagList[0]);
const remainingTags = tags.filter(tag => !usedTags.includes(tag));
// everything // everything
tagCollection.unshift(tags); tagCollection.unshift(tags);
this.setState({ remainingTags, tagCollection }); this.setState({ tagCollection });
}; };
handleTagPress = name => { handleTagPress = name => {
const { navigation, sortByItem } = this.props; const { navigation } = this.props;
if (name.toLowerCase() !== __('all tags you follow')) { if (name.toLowerCase() !== 'trending') {
navigation.navigate({ navigation.navigate({ routeName: Constants.DRAWER_ROUTE_TAG, key: `tagPage`, params: { tag: name } });
routeName: Constants.DRAWER_ROUTE_TAG,
key: `tagPage`,
params: {
tag: name,
},
});
} else { } else {
// navigate to the trending page // navigate to the trending page
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_TRENDING, params: { filterForTags: true } }); navigation.navigate({ routeName: Constants.FULL_ROUTE_NAME_TRENDING });
} }
}; };
sectionListHeader = () => {
const { sortByItem, timeItem } = this.props;
return (
<View style={discoverStyle.listHeader}>
<View style={discoverStyle.titleRow}>
<Text style={discoverStyle.pageTitle}>{__('Your Tags')}</Text>
</View>
<View style={discoverStyle.pickerRow}>
<View style={discoverStyle.leftPickerRow}>
<TouchableOpacity style={discoverStyle.tagSortBy} onPress={() => this.setState({ showSortPicker: true })}>
<Text style={discoverStyle.tagSortText}>{__(sortByItem.label.split(' ')[0])}</Text>
<Icon style={discoverStyle.tagSortIcon} name={'sort-down'} size={14} />
</TouchableOpacity>
{Constants.SORT_BY_TOP === sortByItem.name && (
<TouchableOpacity style={discoverStyle.tagTime} onPress={() => this.setState({ showTimePicker: true })}>
<Text style={discoverStyle.tagSortText}>{__(timeItem.label)}</Text>
<Icon style={discoverStyle.tagSortIcon} name={'sort-down'} size={14} />
</TouchableOpacity>
)}
</View>
<Link
style={discoverStyle.customizeLink}
text={__('Customize')}
onPress={() => this.setState({ showModalTagSelector: true })}
/>
</View>
</View>
);
};
sectionListFooter = () => {
const { remainingTags } = this.state;
if (remainingTags.length === 0) {
return null;
}
return (
<View style={discoverStyle.footer}>
<Text style={discoverStyle.footerTitle}>{__('More tags you follow')}</Text>
<View style={discoverStyle.footerTags}>
{remainingTags.map(tag => (
<Text
key={tag}
style={[discoverStyle.categoryName, discoverStyle.footerTag]}
onPress={() => this.handleTagPress(tag)}
>
{formatTagTitle(tag)}
</Text>
))}
</View>
</View>
);
};
renderSectionListItem = ({ item, index, section }) => (
<ClaimList
key={item.sort().join(',')}
orderBy={this.state.orderBy}
time={this.props.timeItem.name}
tags={item}
morePlaceholder
navigation={this.props.navigation}
orientation={Constants.ORIENTATION_HORIZONTAL}
/>
);
renderSectionHeader = ({ section: { title } }) => (
<View style={discoverStyle.categoryTitleRow}>
<Text style={discoverStyle.categoryName} onPress={() => this.handleTagPress(title)}>
{formatTagTitle(title)}
</Text>
<TouchableOpacity onPress={() => this.handleTagPress(title)}>
<Icon name={'angle-double-down'} size={16} />
</TouchableOpacity>
</View>
);
render() { render() {
const { navigation, sortByItem, timeItem } = this.props; const { navigation } = this.props;
const { orderBy, showModalTagSelector, showSortPicker, showTimePicker } = this.state; const { currentSortByItem, orderBy, showModalTagSelector, showSortPicker } = this.state;
return ( return (
<View style={discoverStyle.container}> <View style={discoverStyle.container}>
<UriBar navigation={navigation} belowOverlay={showModalTagSelector} /> <UriBar navigation={navigation} belowOverlay={showModalTagSelector} />
<SectionList <SectionList
ListHeaderComponent={this.sectionListHeader} ListHeaderComponent={
ListFooterComponent={this.sectionListFooter} <View style={discoverStyle.titleRow}>
<Text style={discoverStyle.pageTitle}>Explore</Text>
<View style={discoverStyle.rightTitleRow}>
<Link
style={discoverStyle.customizeLink}
text={'Customize'}
onPress={() => this.setState({ showModalTagSelector: true })}
/>
<TouchableOpacity
style={discoverStyle.tagSortBy}
onPress={() => this.setState({ showSortPicker: true })}
>
<Text style={discoverStyle.tagSortText}>{currentSortByItem.label.split(' ')[0]}</Text>
<Icon style={discoverStyle.tagSortIcon} name={'sort-down'} size={14} />
</TouchableOpacity>
</View>
</View>
}
style={discoverStyle.scrollContainer} style={discoverStyle.scrollContainer}
contentContainerStyle={discoverStyle.scrollPadding} contentContainerStyle={discoverStyle.scrollPadding}
initialNumToRender={4} initialNumToRender={4}
maxToRenderPerBatch={4} maxToRenderPerBatch={4}
removeClippedSubviews removeClippedSubviews
renderItem={this.renderSectionListItem} renderItem={({ item, index, section }) => (
renderSectionHeader={this.renderSectionHeader} <ClaimList
key={item.sort().join(',')}
orderBy={orderBy}
time={Constants.TIME_WEEK}
tags={item}
morePlaceholder
navigation={navigation}
orientation={Constants.ORIENTATION_HORIZONTAL}
/>
)}
renderSectionHeader={({ section: { title } }) => (
<View style={discoverStyle.categoryTitleRow}>
<Text style={discoverStyle.categoryName} onPress={() => this.handleTagPress(title)}>
{formatTagTitle(title)}
</Text>
<TouchableOpacity onPress={() => this.handleTagPress(title)}>
<Icon name={'angle-double-down'} size={16} />
</TouchableOpacity>
</View>
)}
sections={this.buildSections()} sections={this.buildSections()}
keyExtractor={(item, index) => item} keyExtractor={(item, index) => item}
/> />
{!showModalTagSelector && !showSortPicker && !showTimePicker && ( {!showModalTagSelector && !showSortPicker && <FloatingWalletBalance navigation={navigation} />}
<FloatingWalletBalance navigation={navigation} />
)}
{showModalTagSelector && ( {showModalTagSelector && (
<ModalTagSelector <ModalTagSelector
onOverlayPress={() => this.setState({ showModalTagSelector: false })} onOverlayPress={() => this.setState({ showModalTagSelector: false })}
@@ -364,19 +303,10 @@ class DiscoverPage extends React.PureComponent {
title={__('Sort content by')} title={__('Sort content by')}
onOverlayPress={() => this.setState({ showSortPicker: false })} onOverlayPress={() => this.setState({ showSortPicker: false })}
onItemSelected={this.handleSortByItemSelected} onItemSelected={this.handleSortByItemSelected}
selectedItem={sortByItem} selectedItem={currentSortByItem}
items={Constants.CLAIM_SEARCH_SORT_BY_ITEMS} items={Constants.CLAIM_SEARCH_SORT_BY_ITEMS}
/> />
)} )}
{showTimePicker && (
<ModalPicker
title={__('Content from')}
onOverlayPress={() => this.setState({ showTimePicker: false })}
onItemSelected={this.handleTimeItemSelected}
selectedItem={timeItem}
items={Constants.CLAIM_SEARCH_TIME_ITEMS}
/>
)}
</View> </View>
); );
} }
+2 -11
View File
@@ -1,32 +1,23 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { import {
doFileList, doFileList,
doFetchClaimListMine,
selectFileInfosDownloaded, selectFileInfosDownloaded,
selectDownloadedUris,
selectMyClaimsWithoutChannels, selectMyClaimsWithoutChannels,
selectIsFetchingClaimListMine,
selectIsFetchingFileList, selectIsFetchingFileList,
} from 'lbry-redux'; } from 'lbry-redux';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer'; import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { doDeleteFile } from 'redux/actions/file';
import { selectCurrentRoute } from 'redux/selectors/drawer'; import { selectCurrentRoute } from 'redux/selectors/drawer';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import DownloadsPage from './view'; import DownloadsPage from './view';
const select = state => ({ const select = state => ({
claims: selectMyClaimsWithoutChannels(state), claims: selectMyClaimsWithoutChannels(state),
currentRoute: selectCurrentRoute(state), currentRoute: selectCurrentRoute(state),
fileInfos: selectFileInfosDownloaded(state), fileInfos: selectFileInfosDownloaded(state),
downloadedUris: selectDownloadedUris(state), fetching: selectIsFetchingFileList(state),
fetching: selectIsFetchingFileList(state) || selectIsFetchingClaimListMine(state),
}); });
const perform = dispatch => ({ const perform = dispatch => ({
deleteFile: (fileInfo, deleteFromDevice, abandonClaim) => {
dispatch(doDeleteFile(fileInfo, deleteFromDevice, abandonClaim));
},
fetchMyClaims: () => dispatch(doFetchClaimListMine()),
fileList: () => dispatch(doFileList()), fileList: () => dispatch(doFileList()),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_MY_LBRY)), pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_MY_LBRY)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false)), setPlayerVisible: () => dispatch(doSetPlayerVisible(false)),
+27 -136
View File
@@ -1,21 +1,10 @@
import React from 'react'; import React from 'react';
import { Lbry, buildURI, normalizeURI } from 'lbry-redux'; import { Lbry, buildURI } from 'lbry-redux';
import { import { ActivityIndicator, Button, FlatList, Text, TextInput, View, ScrollView } from 'react-native';
ActivityIndicator,
Alert,
Button,
FlatList,
NativeModules,
Text,
TextInput,
View,
ScrollView,
} from 'react-native';
import { navigateToUri, uriFromFileInfo } from 'utils/helper'; import { navigateToUri, uriFromFileInfo } from 'utils/helper';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import PageHeader from 'component/pageHeader'; import PageHeader from 'component/pageHeader';
import EmptyStateView from 'component/emptyStateView';
import FileListItem from 'component/fileListItem'; import FileListItem from 'component/fileListItem';
import FloatingWalletBalance from 'component/floatingWalletBalance'; import FloatingWalletBalance from 'component/floatingWalletBalance';
import StorageStatsCard from 'component/storageStatsCard'; import StorageStatsCard from 'component/storageStatsCard';
@@ -28,17 +17,11 @@ class DownloadsPage extends React.PureComponent {
title: 'Downloads', title: 'Downloads',
}; };
state = {
selectionMode: false,
selectedUris: [],
selectedClaimsMap: {},
};
didFocusListener; didFocusListener;
componentWillMount() { componentWillMount() {
const { navigation } = this.props; const { navigation } = this.props;
// this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused); this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
} }
componentWillUnmount() { componentWillUnmount() {
@@ -48,12 +31,9 @@ class DownloadsPage extends React.PureComponent {
} }
onComponentFocused = () => { onComponentFocused = () => {
const { fetchMyClaims, fileList, pushDrawerStack, setPlayerVisible } = this.props; const { fileList, pushDrawerStack, setPlayerVisible } = this.props;
pushDrawerStack(); pushDrawerStack();
setPlayerVisible(); setPlayerVisible();
NativeModules.Firebase.setCurrentScreen('Library');
fetchMyClaims();
fileList(); fileList();
}; };
@@ -64,138 +44,49 @@ class DownloadsPage extends React.PureComponent {
componentWillReceiveProps(nextProps) { componentWillReceiveProps(nextProps) {
const { currentRoute } = nextProps; const { currentRoute } = nextProps;
const { currentRoute: prevRoute } = this.props; const { currentRoute: prevRoute } = this.props;
if (Constants.DRAWER_ROUTE_MY_LBRY === currentRoute && currentRoute !== prevRoute) { if (Constants.FULL_ROUTE_NAME_MY_LBRY === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused(); this.onComponentFocused();
} }
} }
getFilteredUris = () => {
const { claims, downloadedUris } = this.props;
const claimUris = claims.map(claim => normalizeURI(`${claim.name}#${claim.claim_id}`));
return downloadedUris.filter(uri => !claimUris.includes(uri));
};
getFilteredFileInfos = () => {
const { claims, fileInfos } = this.props;
const claimUris = claims.map(claim => normalizeURI(`${claim.name}#${claim.claim_id}`));
return fileInfos.filter(
fileInfo => !claimUris.includes(normalizeURI(`${fileInfo.claim_name}#${fileInfo.claim_id}`))
);
};
addOrRemoveItem = (uri, claim) => {
const { selectedClaimsMap } = this.state;
let selectedUris = [...this.state.selectedUris];
if (selectedUris.includes(uri)) {
delete selectedClaimsMap[uri];
selectedUris.splice(selectedUris.indexOf(uri), 1);
} else {
selectedClaimsMap[uri] = claim;
selectedUris.push(uri);
}
this.setState({ selectionMode: selectedUris.length > 0, selectedUris, selectedClaimsMap });
};
handleSelectItem = (uri, claim) => {
this.addOrRemoveItem(uri, claim);
};
handleItemLongPress = (uri, claim) => {
this.addOrRemoveItem(uri, claim);
};
onExitSelectionMode = () => {
this.setState({ selectionMode: false, selectedUris: [], selectedClaimsMap: {} });
};
onDeleteActionPressed = () => {
const { deleteFile, fileList } = this.props;
const { selectedClaimsMap } = this.state;
// show confirm alert
Alert.alert(
__('Delete files'),
__('Are you sure you want to delete the selected content?'),
[
{ text: __('No') },
{
text: __('Yes'),
onPress: () => {
const uris = Object.keys(selectedClaimsMap);
uris.forEach(uri => {
const { txid, nout } = selectedClaimsMap[uri];
deleteFile(`${txid}:${nout}`, true);
});
this.onExitSelectionMode();
fileList();
},
},
],
{
cancelable: true,
}
);
};
render() { render() {
const { fetching, claims, downloadedUris, fileInfos, navigation } = this.props; const { fetching, fileInfos, navigation } = this.props;
const { selectionMode, selectedUris } = this.state; const hasDownloads = fileInfos && Object.values(fileInfos).length > 0;
const filteredUris = this.getFilteredUris();
const hasDownloads = filteredUris && filteredUris.length > 0;
return ( return (
<View style={downloadsStyle.container}> <View style={downloadsStyle.container}>
<UriBar <UriBar navigation={navigation} />
navigation={navigation}
selectionMode={selectionMode}
selectedItemCount={selectedUris.length}
onExitSelectionMode={this.onExitSelectionMode}
onDeleteActionPressed={this.onDeleteActionPressed}
/>
{!fetching && !hasDownloads && ( {!fetching && !hasDownloads && (
<EmptyStateView message={__('You do not have any\ndownloaded content on this device.')} /> <View style={downloadsStyle.busyContainer}>
<Text style={downloadsStyle.noDownloadsText}>
You have not watched or downloaded any content from LBRY yet.
</Text>
</View>
)} )}
{fetching && !hasDownloads && (
<View style={downloadsStyle.subContainer}> <View style={downloadsStyle.busyContainer}>
{hasDownloads && <StorageStatsCard fileInfos={this.getFilteredFileInfos()} />} <ActivityIndicator size="large" color={Colors.NextLbryGreen} style={downloadsStyle.loading} />
{fetching && ( </View>
<View style={downloadsStyle.busyContainer}> )}
<ActivityIndicator size="large" color={Colors.NextLbryGreen} style={downloadsStyle.loading} /> {hasDownloads && (
</View> <View style={downloadsStyle.subContainer}>
)} <StorageStatsCard fileInfos={fileInfos} />
{!fetching && hasDownloads && (
<FlatList <FlatList
extraData={this.state}
style={downloadsStyle.scrollContainer} style={downloadsStyle.scrollContainer}
contentContainerStyle={downloadsStyle.scrollPadding} contentContainerStyle={downloadsStyle.scrollPadding}
renderItem={({ item }) => ( renderItem={({ item }) => (
<FileListItem <FileListItem
autoplay
key={item}
uri={item}
style={fileListStyle.item} style={fileListStyle.item}
selected={selectedUris.includes(item)} uri={uriFromFileInfo(item)}
onPress={claim => {
if (selectionMode) {
this.handleSelectItem(item, claim);
} else {
// TODO: when shortUrl is available for my claims, navigate to that URL instead
navigateToUri(navigation, item, { autoplay: true });
}
}}
onLongPress={claim => this.handleItemLongPress(item, claim)}
navigation={navigation} navigation={navigation}
onPress={() => navigateToUri(navigation, uriFromFileInfo(item), { autoplay: true })}
/> />
)} )}
data={downloadedUris} data={fileInfos}
keyExtractor={(item, index) => item} keyExtractor={(item, index) => item.outpoint}
/> />
)} </View>
</View> )}
<FloatingWalletBalance navigation={navigation} /> <FloatingWalletBalance navigation={navigation} />
</View> </View>
); );
+16 -36
View File
@@ -1,14 +1,10 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { import {
doAbandonClaim,
doFetchFileInfo, doFetchFileInfo,
doFetchChannelListMine,
doFetchClaimListMine,
doFileGet, doFileGet,
doPurchaseUri, doPurchaseUri,
doDeletePurchasedUri, doDeletePurchasedUri,
doResolveUri, doResolveUri,
doSearch,
doSendTip, doSendTip,
doToast, doToast,
makeSelectIsUriResolving, makeSelectIsUriResolving,
@@ -18,20 +14,15 @@ import {
makeSelectContentPositionForUri, makeSelectContentPositionForUri,
makeSelectContentTypeForUri, makeSelectContentTypeForUri,
makeSelectMetadataForUri, makeSelectMetadataForUri,
makeSelectRecommendedContentForUri,
makeSelectStreamingUrlForUri, makeSelectStreamingUrlForUri,
makeSelectThumbnailForUri, makeSelectThumbnailForUri,
makeSelectTitleForUri, makeSelectTitleForUri,
selectBalance, selectBalance,
selectMyChannelClaims,
selectMyClaimUrisWithoutChannels,
selectPurchasedUris, selectPurchasedUris,
selectFailedPurchaseUris, selectFailedPurchaseUris,
selectPurchaseUriErrorMessage, selectPurchaseUriErrorMessage,
selectIsSearching,
} from 'lbry-redux'; } from 'lbry-redux';
import { import {
doClaimEligiblePurchaseRewards,
doFetchCostInfoForUri, doFetchCostInfoForUri,
makeSelectCostInfoForUri, makeSelectCostInfoForUri,
selectRewardContentClaimIds, selectRewardContentClaimIds,
@@ -45,65 +36,54 @@ import {
doStopDownloadingFile, doStopDownloadingFile,
} from 'redux/actions/file'; } from 'redux/actions/file';
import { doPopDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer'; import { doPopDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { doToggleFullscreenMode } from 'redux/actions/settings';
import { selectDrawerStack } from 'redux/selectors/drawer'; import { selectDrawerStack } from 'redux/selectors/drawer';
import FilePage from './view'; import FilePage from './view';
const select = (state, props) => { const select = (state, props) => {
const { uri, fullUri } = props.navigation.state.params; const selectProps = { uri: props.navigation.state.params.uri };
const contentUri = fullUri || uri;
const selectProps = { uri: contentUri };
return { return {
balance: selectBalance(state), balance: selectBalance(state),
blackListedOutpoints: selectBlackListedOutpoints(state), blackListedOutpoints: selectBlackListedOutpoints(state),
channels: selectMyChannelClaims(state), claim: makeSelectClaimForUri(selectProps.uri)(state),
claim: makeSelectClaimForUri(contentUri)(state),
drawerStack: selectDrawerStack(state), drawerStack: selectDrawerStack(state),
isResolvingUri: makeSelectIsUriResolving(contentUri)(state), isResolvingUri: makeSelectIsUriResolving(selectProps.uri)(state),
contentType: makeSelectContentTypeForUri(contentUri)(state), contentType: makeSelectContentTypeForUri(selectProps.uri)(state),
costInfo: makeSelectCostInfoForUri(contentUri)(state), costInfo: makeSelectCostInfoForUri(selectProps.uri)(state),
metadata: makeSelectMetadataForUri(contentUri)(state), metadata: makeSelectMetadataForUri(selectProps.uri)(state),
fileInfo: makeSelectFileInfoForUri(contentUri)(state), //obscureNsfw: !selectShowNsfw(state),
//tab: makeSelectCurrentParam('tab')(state),
fileInfo: makeSelectFileInfoForUri(selectProps.uri)(state),
rewardedContentClaimIds: selectRewardContentClaimIds(state, selectProps), rewardedContentClaimIds: selectRewardContentClaimIds(state, selectProps),
channelUri: makeSelectChannelForClaimUri(contentUri, true)(state), channelUri: makeSelectChannelForClaimUri(selectProps.uri, true)(state),
position: makeSelectContentPositionForUri(contentUri)(state), position: makeSelectContentPositionForUri(selectProps.uri)(state),
purchasedUris: selectPurchasedUris(state), purchasedUris: selectPurchasedUris(state),
failedPurchaseUris: selectFailedPurchaseUris(state), failedPurchaseUris: selectFailedPurchaseUris(state),
myClaimUris: selectMyClaimUrisWithoutChannels(state),
purchaseUriErrorMessage: selectPurchaseUriErrorMessage(state), purchaseUriErrorMessage: selectPurchaseUriErrorMessage(state),
streamingUrl: makeSelectStreamingUrlForUri(contentUri)(state), streamingUrl: makeSelectStreamingUrlForUri(selectProps.uri)(state),
thumbnail: makeSelectThumbnailForUri(contentUri)(state), thumbnail: makeSelectThumbnailForUri(selectProps.uri)(state),
title: makeSelectTitleForUri(contentUri)(state), title: makeSelectTitleForUri(selectProps.uri)(state),
recommendedContent: makeSelectRecommendedContentForUri(contentUri)(state),
isSearchingRecommendContent: selectIsSearching(state),
}; };
}; };
const perform = dispatch => ({ const perform = dispatch => ({
abandonClaim: (txid, nout) => dispatch(doAbandonClaim(txid, nout)),
claimEligibleRewards: () => dispatch(doClaimEligiblePurchaseRewards()),
deleteFile: (fileInfo, deleteFromDevice, abandonClaim) => { deleteFile: (fileInfo, deleteFromDevice, abandonClaim) => {
dispatch(doDeleteFile(fileInfo, deleteFromDevice, abandonClaim)); dispatch(doDeleteFile(fileInfo, deleteFromDevice, abandonClaim));
}, },
fetchFileInfo: uri => dispatch(doFetchFileInfo(uri)), fetchFileInfo: uri => dispatch(doFetchFileInfo(uri)),
fetchCostInfo: uri => dispatch(doFetchCostInfoForUri(uri)), fetchCostInfo: uri => dispatch(doFetchCostInfoForUri(uri)),
fetchMyClaims: () => dispatch(doFetchClaimListMine()),
fetchChannelListMine: () => dispatch(doFetchChannelListMine()),
fileGet: (uri, saveFile) => dispatch(doFileGet(uri, saveFile)), fileGet: (uri, saveFile) => dispatch(doFileGet(uri, saveFile)),
notify: data => dispatch(doToast(data)), notify: data => dispatch(doToast(data)),
popDrawerStack: () => dispatch(doPopDrawerStack()), popDrawerStack: () => dispatch(doPopDrawerStack()),
purchaseUri: (uri, costInfo, saveFile) => dispatch(doPurchaseUri(uri, costInfo, saveFile)), purchaseUri: (uri, costInfo, saveFile) => dispatch(doPurchaseUri(uri, costInfo, saveFile)),
deletePurchasedUri: uri => dispatch(doDeletePurchasedUri(uri)), deletePurchasedUri: uri => dispatch(doDeletePurchasedUri(uri)),
resolveUri: uri => dispatch(doResolveUri(uri)), resolveUri: uri => dispatch(doResolveUri(uri)),
searchRecommended: query => dispatch(doSearch(query, 20, undefined, true)), sendTip: (amount, claimId, uri, successCallback, errorCallback) =>
sendTip: (amount, claimId, isSupport, successCallback, errorCallback) => dispatch(doSendTip(amount, claimId, uri, successCallback, errorCallback)),
dispatch(doSendTip(amount, claimId, isSupport, successCallback, errorCallback)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(true)), setPlayerVisible: () => dispatch(doSetPlayerVisible(true)),
stopDownload: (uri, fileInfo) => dispatch(doStopDownloadingFile(uri, fileInfo)), stopDownload: (uri, fileInfo) => dispatch(doStopDownloadingFile(uri, fileInfo)),
startDownload: (uri, outpoint, fileInfo) => dispatch(doStartDownload(uri, outpoint, fileInfo)), startDownload: (uri, outpoint, fileInfo) => dispatch(doStartDownload(uri, outpoint, fileInfo)),
updateDownload: (uri, outpoint, fileInfo, progress) => dispatch(doUpdateDownload(uri, outpoint, fileInfo, progress)), updateDownload: (uri, outpoint, fileInfo, progress) => dispatch(doUpdateDownload(uri, outpoint, fileInfo, progress)),
completeDownload: (uri, outpoint, fileInfo) => dispatch(doCompleteDownload(uri, outpoint, fileInfo)), completeDownload: (uri, outpoint, fileInfo) => dispatch(doCompleteDownload(uri, outpoint, fileInfo)),
toggleFullscreenMode: mode => dispatch(doToggleFullscreenMode(mode)),
}); });
export default connect( export default connect(
+68 -259
View File
@@ -1,13 +1,11 @@
import React from 'react'; import React from 'react';
import { Lbry, normalizeURI, parseURI } from 'lbry-redux'; import { Lbry, normalizeURI } from 'lbry-redux';
import { Lbryio } from 'lbryinc'; import { Lbryio } from 'lbryinc';
import { import {
ActivityIndicator, ActivityIndicator,
Alert, Alert,
DeviceEventEmitter, DeviceEventEmitter,
Dimensions, Dimensions,
Image,
Linking,
NativeModules, NativeModules,
ScrollView, ScrollView,
StatusBar, StatusBar,
@@ -20,11 +18,10 @@ import {
WebView, WebView,
} from 'react-native'; } from 'react-native';
import { NavigationEvents } from 'react-navigation'; import { NavigationEvents } from 'react-navigation';
import { navigateBack, navigateToUri, formatLbryUrlForWeb } from 'utils/helper'; import { navigateBack, navigateToUri } from 'utils/helper';
import Icon from 'react-native-vector-icons/FontAwesome5'; import Icon from 'react-native-vector-icons/FontAwesome5';
import ImageViewer from 'react-native-image-zoom-viewer'; import ImageViewer from 'react-native-image-zoom-viewer';
import Button from 'component/button'; import Button from 'component/button';
import EmptyStateView from 'component/emptyStateView';
import Tag from 'component/tag'; import Tag from 'component/tag';
import ChannelPage from 'page/channel'; import ChannelPage from 'page/channel';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
@@ -61,7 +58,6 @@ class FilePage extends React.PureComponent {
constructor(props) { constructor(props) {
super(props); super(props);
this.state = { this.state = {
attemptAutoGet: false,
autoPlayMedia: false, autoPlayMedia: false,
autoDownloadStarted: false, autoDownloadStarted: false,
downloadButtonShown: false, downloadButtonShown: false,
@@ -74,7 +70,6 @@ class FilePage extends React.PureComponent {
mediaLoaded: false, mediaLoaded: false,
pageSuspended: false, pageSuspended: false,
relatedContentY: 0, relatedContentY: 0,
sendTipStarted: false,
showDescription: false, showDescription: false,
showImageViewer: false, showImageViewer: false,
showWebView: false, showWebView: false,
@@ -86,7 +81,6 @@ class FilePage extends React.PureComponent {
uriVars: null, uriVars: null,
stopDownloadConfirmed: false, stopDownloadConfirmed: false,
streamingMode: false, streamingMode: false,
didSearchRecommended: false,
}; };
} }
@@ -94,18 +88,17 @@ class FilePage extends React.PureComponent {
componentWillMount() { componentWillMount() {
const { navigation } = this.props; const { navigation } = this.props;
// this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused); this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
} }
onComponentFocused = () => { onComponentFocused = () => {
StatusBar.setHidden(false); StatusBar.setHidden(false);
NativeModules.Firebase.setCurrentScreen('File');
DeviceEventEmitter.addListener('onDownloadStarted', this.handleDownloadStarted); DeviceEventEmitter.addListener('onDownloadStarted', this.handleDownloadStarted);
DeviceEventEmitter.addListener('onDownloadUpdated', this.handleDownloadUpdated); DeviceEventEmitter.addListener('onDownloadUpdated', this.handleDownloadUpdated);
DeviceEventEmitter.addListener('onDownloadCompleted', this.handleDownloadCompleted); DeviceEventEmitter.addListener('onDownloadCompleted', this.handleDownloadCompleted);
const { fetchMyClaims, fileInfo, isResolvingUri, resolveUri, navigation } = this.props; const { fileInfo, isResolvingUri, resolveUri, navigation } = this.props;
const { uri, uriVars } = navigation.state.params; const { uri, uriVars } = navigation.state.params;
this.setState({ uri, uriVars }); this.setState({ uri, uriVars });
@@ -113,7 +106,6 @@ class FilePage extends React.PureComponent {
this.fetchFileInfo(this.props); this.fetchFileInfo(this.props);
this.fetchCostInfo(this.props); this.fetchCostInfo(this.props);
fetchMyClaims();
if (NativeModules.Firebase) { if (NativeModules.Firebase) {
NativeModules.Firebase.track('open_file_page', { uri: uri }); NativeModules.Firebase.track('open_file_page', { uri: uri });
@@ -187,27 +179,12 @@ class FilePage extends React.PureComponent {
} }
componentDidUpdate(prevProps) { componentDidUpdate(prevProps) {
const { const { claim, contentType, fileInfo, isResolvingUri, resolveUri, navigation } = this.props;
claim,
contentType,
costInfo,
fileInfo,
isResolvingUri,
resolveUri,
navigation,
purchaseUri,
searchRecommended,
title,
} = this.props;
const { uri } = this.state; const { uri } = this.state;
if (!isResolvingUri && claim === undefined && uri) { if (!isResolvingUri && claim === undefined && uri) {
resolveUri(uri); resolveUri(uri);
} }
if (title && !this.state.didSearchRecommended) {
this.setState({ didSearchRecommended: true }, () => searchRecommended(title));
}
// Returned to the page. If mediaLoaded, and currentMediaInfo is different, update // Returned to the page. If mediaLoaded, and currentMediaInfo is different, update
if (this.state.mediaLoaded && window.currentMediaInfo && window.currentMediaInfo.uri !== this.state.uri) { if (this.state.mediaLoaded && window.currentMediaInfo && window.currentMediaInfo.uri !== this.state.uri) {
const { metadata } = this.props; const { metadata } = this.props;
@@ -217,21 +194,6 @@ class FilePage extends React.PureComponent {
uri: this.state.uri, uri: this.state.uri,
}; };
} }
// attempt to retrieve images and html/text automatically once the claim is loaded, and it's free
const mediaType = Lbry.getMediaType(contentType);
const isViewable = mediaType === 'image' || mediaType === 'text';
if (claim && costInfo && costInfo.cost === 0 && !this.state.autoGetAttempted && isViewable) {
this.setState(
{
autoGetAttempted: true,
downloadPressed: true,
autoPlayMedia: true,
stopDownloadConfirmed: false,
},
() => purchaseUri(claim.permanent_url, costInfo, true)
);
}
} }
fetchFileInfo(props) { fetchFileInfo(props) {
@@ -246,35 +208,30 @@ class FilePage extends React.PureComponent {
} }
} }
handleFullscreenToggle = isFullscreen => { handleFullscreenToggle = mode => {
const { toggleFullscreenMode } = this.props; this.setState({ fullscreenMode: mode });
this.setState({ fullscreenMode: isFullscreen }); StatusBar.setHidden(mode);
toggleFullscreenMode(isFullscreen); if (NativeModules.ScreenOrientation) {
if (mode) {
StatusBar.setHidden(isFullscreen); // fullscreen, so change orientation to landscape mode
NativeModules.ScreenOrientation.lockOrientationLandscape();
if (isFullscreen) { if (NativeModules.UtilityModule) {
// fullscreen, so change orientation to landscape mode // hide the navigation bar (on devices that use have soft navigation bar)
NativeModules.ScreenOrientation.lockOrientationLandscape(); NativeModules.UtilityModule.hideNavigationBar();
}
// hide the navigation bar (on devices that have the soft navigation bar) } else {
NativeModules.UtilityModule.hideNavigationBar(); // Switch back to portrait mode when the media is not fullscreen
} else { NativeModules.ScreenOrientation.lockOrientationPortrait();
// Switch back to portrait mode when the media is not fullscreen if (NativeModules.UtilityModule) {
NativeModules.ScreenOrientation.lockOrientationPortrait(); // hide the navigation bar (on devices that use have soft navigation bar)
NativeModules.UtilityModule.showNavigationBar();
// hide the navigation bar (on devices that have the soft navigation bar) }
NativeModules.UtilityModule.showNavigationBar(); }
} }
}; };
onEditPressed = () => {
const { claim, navigation } = this.props;
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_PUBLISH, params: { editMode: true, claimToEdit: claim } });
};
onDeletePressed = () => { onDeletePressed = () => {
const { abandonClaim, claim, deleteFile, deletePurchasedUri, myClaimUris, fileInfo, navigation } = this.props; const { claim, deleteFile, deletePurchasedUri, fileInfo, navigation } = this.props;
Alert.alert( Alert.alert(
'Delete file', 'Delete file',
@@ -285,27 +242,17 @@ class FilePage extends React.PureComponent {
text: 'Yes', text: 'Yes',
onPress: () => { onPress: () => {
const { uri } = navigation.state.params; const { uri } = navigation.state.params;
deleteFile(`${claim.txid}:${claim.nout}`, true); deleteFile(`${claim.txid}:${claim.nout}`, true);
deletePurchasedUri(uri); deletePurchasedUri(uri);
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.deleteDownload(uri); NativeModules.UtilityModule.deleteDownload(uri);
}
this.setState({ this.setState({
downloadPressed: false, downloadPressed: false,
fileViewLogged: false, fileViewLogged: false,
mediaLoaded: false, mediaLoaded: false,
stopDownloadConfirmed: false, stopDownloadConfirmed: false,
}); });
if (claim) {
const fullUri = normalizeURI(`${claim.name}#${claim.claim_id}`);
const ownedClaim = myClaimUris.includes(fullUri);
if (ownedClaim) {
const { txid, nout } = claim;
abandonClaim(txid, nout);
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_PUBLISHES });
}
}
}, },
}, },
], ],
@@ -523,7 +470,6 @@ class FilePage extends React.PureComponent {
return; return;
} }
const { claimEligibleRewards } = this.props;
const { nout, claim_id: claimId, txid } = claim; const { nout, claim_id: claimId, txid } = claim;
const outpoint = `${txid}:${nout}`; const outpoint = `${txid}:${nout}`;
const params = { const params = {
@@ -535,21 +481,10 @@ class FilePage extends React.PureComponent {
params.time_to_start = timeToStart; params.time_to_start = timeToStart;
} }
Lbryio.call('file', 'view', params) Lbryio.call('file', 'view', params).catch(() => {});
.then(() => claimEligibleRewards())
.catch(() => {});
this.setState({ fileViewLogged: true }); this.setState({ fileViewLogged: true });
}; };
handleSharePress = () => {
const { claim, notify } = this.props;
if (claim) {
const { canonical_url: canonicalUrl, short_url: shortUrl, permanent_url: permanentUrl } = claim;
const url = Constants.SHARE_BASE_URL + formatLbryUrlForWeb(canonicalUrl || shortUrl || permanentUrl);
NativeModules.UtilityModule.shareUrl(url);
}
};
handleSendTip = () => { handleSendTip = () => {
const { claim, balance, navigation, notify, sendTip } = this.props; const { claim, balance, navigation, notify, sendTip } = this.props;
const { uri } = navigation.state.params; const { uri } = navigation.state.params;
@@ -562,25 +497,9 @@ class FilePage extends React.PureComponent {
return; return;
} }
const suffix = 'credit' + (parseInt(tipAmount, 10) === 1 ? '' : 's'); sendTip(tipAmount, claim.claim_id, uri, () => {
Alert.alert( this.setState({ tipAmount: 0, showTipView: false });
'Send tip', });
`Are you sure you want to tip ${tipAmount} ${suffix}?`,
[
{ text: 'No' },
{
text: 'Yes',
onPress: () => {
this.setState({ sendTipStarted: true }, () =>
sendTip(tipAmount, claim.claim_id, false, () => {
this.setState({ tipAmount: null, showTipView: false, sendTipStarted: false });
})
);
},
},
],
{ cancelable: true }
);
}; };
renderTags = tags => { renderTags = tags => {
@@ -625,7 +544,6 @@ class FilePage extends React.PureComponent {
const { const {
balance, balance,
claim, claim,
channels,
channelUri, channelUri,
costInfo, costInfo,
fileInfo, fileInfo,
@@ -635,64 +553,36 @@ class FilePage extends React.PureComponent {
rewardedContentClaimIds, rewardedContentClaimIds,
isResolvingUri, isResolvingUri,
blackListedOutpoints, blackListedOutpoints,
myClaimUris,
navigation, navigation,
position, position,
purchaseUri, purchaseUri,
isSearchingRecommendContent,
recommendedContent,
thumbnail, thumbnail,
title, title,
} = this.props; } = this.props;
const { uri, autoplay } = navigation.state.params; const { uri, autoplay } = navigation.state.params;
const { isChannel } = parseURI(uri);
const myChannelUris = channels ? channels.map(channel => channel.permanent_url) : [];
const ownedClaim = myClaimUris.includes(uri) || myChannelUris.includes(uri);
let innerContent = null; let innerContent = null;
if ((isResolvingUri && !claim) || !claim) { if ((isResolvingUri && !claim) || !claim) {
return ( return (
<View style={filePageStyle.container}> <View style={filePageStyle.container}>
<UriBar value={uri} navigation={navigation} />
{isResolvingUri && ( {isResolvingUri && (
<View style={filePageStyle.busyContainer}> <View style={filePageStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.NextLbryGreen} /> <ActivityIndicator size="large" color={Colors.NextLbryGreen} />
<Text style={filePageStyle.infoText}>{__('Loading decentralized data...')}</Text> <Text style={filePageStyle.infoText}>Loading decentralized data...</Text>
</View> </View>
)} )}
{claim === null && !isResolvingUri && ( {claim === null && !isResolvingUri && (
<View style={filePageStyle.container}> <View style={filePageStyle.container}>
{ownedClaim && ( <Text style={filePageStyle.emptyClaimText}>There's nothing at this location.</Text>
<EmptyStateView
message={
isChannel
? __('It looks like you just created this channel. It will appear in a few minutes.')
: __('It looks you just published this content. It will appear in a few minutes.')
}
/>
)}
{!ownedClaim && (
<EmptyStateView
message={__("There's nothing at this location.")}
buttonText={__('Publish something here')}
onButtonPress={() =>
navigation.navigate({
routeName: Constants.DRAWER_ROUTE_PUBLISH,
params: { vanityUrl: uri.trim() },
})
}
/>
)}
</View> </View>
)} )}
<FloatingWalletBalance navigation={navigation} /> <UriBar value={uri} navigation={navigation} />
</View> </View>
); );
} }
if (claim) { if (claim) {
if (isChannel) { if (claim && claim.name.length && claim.name[0] === '@') {
return <ChannelPage uri={uri} navigation={navigation} />; return <ChannelPage uri={uri} navigation={navigation} />;
} }
@@ -713,11 +603,10 @@ class FilePage extends React.PureComponent {
<View style={filePageStyle.pageContainer}> <View style={filePageStyle.pageContainer}>
<View style={filePageStyle.dmcaContainer}> <View style={filePageStyle.dmcaContainer}>
<Text style={filePageStyle.dmcaText}> <Text style={filePageStyle.dmcaText}>
{__( In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked
'In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked access to this content from our applications.' access to this content from our applications.
)}
</Text> </Text>
<Link style={filePageStyle.dmcaLink} href="https://lbry.com/faq/dmca" text={__('Read More')} /> <Link style={filePageStyle.dmcaLink} href="https://lbry.com/faq/dmca" text="Read More" />
</View> </View>
<UriBar value={uri} navigation={navigation} /> <UriBar value={uri} navigation={navigation} />
</View> </View>
@@ -736,25 +625,20 @@ class FilePage extends React.PureComponent {
const isPlayable = mediaType === 'video' || mediaType === 'audio'; const isPlayable = mediaType === 'video' || mediaType === 'audio';
const { height, signing_channel: signingChannel, value } = claim; const { height, signing_channel: signingChannel, value } = claim;
const channelName = signingChannel && signingChannel.name; const channelName = signingChannel && signingChannel.name;
const channelClaimId = claim && claim.signing_channel && claim.signing_channel.claim_id;
const canSendTip = this.state.tipAmount > 0;
const fullUri = `${claim.name}#${claim.claim_id}`;
const canEdit = myClaimUris.includes(normalizeURI(fullUri));
const showActions = const showActions =
(canEdit || (fileInfo && fileInfo.download_path)) && fileInfo &&
fileInfo.download_path &&
!this.state.fullscreenMode && !this.state.fullscreenMode &&
!this.state.showImageViewer && !this.state.showImageViewer &&
!this.state.showWebView; !this.state.showWebView;
const showFileActions = const showFileActions =
canEdit || fileInfo &&
(fileInfo && fileInfo.download_path &&
fileInfo.download_path && (completed || (fileInfo && !fileInfo.stopped && fileInfo.written_bytes < fileInfo.total_bytes));
(completed || (fileInfo && !fileInfo.stopped && fileInfo.written_bytes < fileInfo.total_bytes))); const channelClaimId = claim && claim.signing_channel && claim.signing_channel.claim_id;
const canSendTip = this.state.tipAmount > 0;
const fullChannelUri = const fullChannelUri =
channelClaimId && channelClaimId.trim().length > 0 channelClaimId && channelClaimId.trim().length > 0 ? `${channelName}#${channelClaimId}` : channelName;
? normalizeURI(`${channelName}#${channelClaimId}`)
: normalizeURI(channelName);
const shortChannelUri = signingChannel ? signingChannel.short_url : null;
const playerStyle = [ const playerStyle = [
filePageStyle.player, filePageStyle.player,
@@ -770,12 +654,10 @@ class FilePage extends React.PureComponent {
const canLoadMedia = const canLoadMedia =
this.state.streamingMode || this.state.streamingMode ||
(fileInfo && (fileInfo.written_bytes >= 2097152 || fileInfo.written_bytes === fileInfo.total_bytes)); // 2MB = 1024*1024*2 (fileInfo && (fileInfo.written_bytes >= 2097152 || fileInfo.written_bytes === fileInfo.total_bytes)); // 2MB = 1024*1024*2
const duration = claim && claim.value && claim.value.video ? claim.value.video.duration : null;
const isViewable = mediaType === 'image' || mediaType === 'text'; const isViewable = mediaType === 'image' || mediaType === 'text';
const isWebViewable = mediaType === 'text'; const isWebViewable = mediaType === 'text';
const canOpen = isViewable && completed; const canOpen = isViewable && completed;
const localFileUri = this.localUriForFileInfo(fileInfo); const localFileUri = this.localUriForFileInfo(fileInfo);
const unsupported = !isPlayable && !canOpen;
const openFile = () => { const openFile = () => {
if (mediaType === 'image') { if (mediaType === 'image') {
@@ -839,43 +721,17 @@ class FilePage extends React.PureComponent {
> >
<View style={filePageStyle.mediaContainer}> <View style={filePageStyle.mediaContainer}>
{(canOpen || (!fileInfo || (isPlayable && !canLoadMedia)) || (!canOpen && fileInfo)) && ( {(canOpen || (!fileInfo || (isPlayable && !canLoadMedia)) || (!canOpen && fileInfo)) && (
<FileItemMedia <FileItemMedia style={filePageStyle.thumbnail} title={title} thumbnail={thumbnail} />
duration={duration}
style={filePageStyle.thumbnail}
title={title}
thumbnail={thumbnail}
/>
)} )}
{!unsupported && {(!this.state.downloadButtonShown || this.state.downloadPressed) && !this.state.mediaLoaded && (
(!this.state.downloadButtonShown || this.state.downloadPressed) &&
!this.state.mediaLoaded && (
<ActivityIndicator size="large" color={Colors.NextLbryGreen} style={filePageStyle.loading} /> <ActivityIndicator size="large" color={Colors.NextLbryGreen} style={filePageStyle.loading} />
)} )}
{unsupported && fileInfo && completed && (
<View style={filePageStyle.unsupportedContent}>
<Image
style={filePageStyle.unsupportedContentImage}
resizeMode={'stretch'}
source={require('../../assets/gerbil-happy.png')}
/>
<View style={filePageStyle.unspportedContentTextContainer}>
<Text style={filePageStyle.unsupportedContentTitle}>{__('Unsupported Content')}</Text>
<Text style={filePageStyle.unsupportedContentText}>
Sorry, we are unable to display this content in the app. You can find the file named{' '}
<Text style={filePageStyle.unsupportedContentFilename}>{fileInfo.file_name}</Text> in your
downloads folder.
</Text>
</View>
</View>
)}
{((isPlayable && !completed && !canLoadMedia) || {((isPlayable && !completed && !canLoadMedia) ||
canOpen || canOpen ||
(!completed && !this.state.streamingMode)) && (!completed && !this.state.streamingMode)) &&
!this.state.downloadPressed && ( !this.state.downloadPressed && (
<FileDownloadButton <FileDownloadButton
uri={claim && claim.permanent_url ? claim.permanent_url : uri} uri={uri}
style={filePageStyle.downloadButton} style={filePageStyle.downloadButton}
openFile={openFile} openFile={openFile}
isPlayable={isPlayable} isPlayable={isPlayable}
@@ -942,22 +798,12 @@ class FilePage extends React.PureComponent {
<View style={filePageStyle.actions}> <View style={filePageStyle.actions}>
{showFileActions && ( {showFileActions && (
<View style={filePageStyle.fileActions}> <View style={filePageStyle.fileActions}>
{canEdit && ( {completed && (
<Button
style={[filePageStyle.actionButton, filePageStyle.editButton]}
theme={'light'}
icon={'edit'}
text={__('Edit')}
onPress={this.onEditPressed}
/>
)}
{(completed || canEdit) && (
<Button <Button
style={filePageStyle.actionButton} style={filePageStyle.actionButton}
theme={'light'} theme={'light'}
icon={'trash-alt'} icon={'trash'}
text={__('Delete')} text={'Delete'}
onPress={this.onDeletePressed} onPress={this.onDeletePressed}
/> />
)} )}
@@ -970,7 +816,7 @@ class FilePage extends React.PureComponent {
style={filePageStyle.actionButton} style={filePageStyle.actionButton}
icon={'stop'} icon={'stop'}
theme={'light'} theme={'light'}
text={__('Stop Download')} text={'Stop Download'}
onPress={this.onStopDownloadPressed} onPress={this.onStopDownloadPressed}
/> />
)} )}
@@ -994,36 +840,11 @@ class FilePage extends React.PureComponent {
<Text style={filePageStyle.title} selectable> <Text style={filePageStyle.title} selectable>
{title} {title}
</Text> </Text>
{isRewardContent && <Icon name="award" style={filePageStyle.rewardIcon} size={16} />}
<View style={filePageStyle.descriptionToggle}> <View style={filePageStyle.descriptionToggle}>
<Icon name={this.state.showDescription ? 'caret-up' : 'caret-down'} size={24} /> <Icon name={this.state.showDescription ? 'caret-up' : 'caret-down'} size={24} />
</View> </View>
</View> </View>
</TouchableWithoutFeedback> </TouchableWithoutFeedback>
<View style={filePageStyle.largeButtonsRow}>
<TouchableOpacity style={filePageStyle.largeButton} onPress={this.handleSharePress}>
<Icon name={'share-alt'} size={20} style={filePageStyle.largeButtonIcon} />
<Text style={filePageStyle.largeButtonText}>{__('Share')}</Text>
</TouchableOpacity>
<TouchableOpacity
style={filePageStyle.largeButton}
onPress={() => this.setState({ showTipView: true })}
>
<Icon name={'gift'} size={20} style={filePageStyle.largeButtonIcon} />
<Text style={filePageStyle.largeButtonText}>{__('Tip')}</Text>
</TouchableOpacity>
<TouchableOpacity
style={filePageStyle.largeButton}
onPress={() => Linking.openURL(`https://lbry.com/dmca/${claim.claim_id}`)}
>
<Icon name={'flag'} size={20} style={filePageStyle.largeButtonIcon} />
<Text style={filePageStyle.largeButtonText}>{__('Report')}</Text>
</TouchableOpacity>
</View>
<View style={filePageStyle.channelRow}> <View style={filePageStyle.channelRow}>
<View style={filePageStyle.publishInfo}> <View style={filePageStyle.publishInfo}>
{channelName && ( {channelName && (
@@ -1034,19 +855,13 @@ class FilePage extends React.PureComponent {
numberOfLines={1} numberOfLines={1}
ellipsizeMode={'tail'} ellipsizeMode={'tail'}
onPress={() => { onPress={() => {
navigateToUri( navigateToUri(navigation, normalizeURI(fullChannelUri));
navigation,
normalizeURI(shortChannelUri || fullChannelUri),
null,
false,
fullChannelUri
);
}} }}
/> />
)} )}
{!channelName && ( {!channelName && (
<Text style={filePageStyle.anonChannelName} selectable ellipsizeMode={'tail'}> <Text style={filePageStyle.anonChannelName} selectable ellipsizeMode={'tail'}>
{__('Anonymous')} Anonymous
</Text> </Text>
)} )}
<DateTime <DateTime
@@ -1066,6 +881,12 @@ class FilePage extends React.PureComponent {
onPress={this.onSaveFilePressed} onPress={this.onSaveFilePressed}
/> />
)} )}
<Button
style={[filePageStyle.actionButton, filePageStyle.tipButton]}
theme={'light'}
icon={'gift'}
onPress={() => this.setState({ showTipView: true })}
/>
{channelName && ( {channelName && (
<SubscribeButton <SubscribeButton
style={filePageStyle.actionButton} style={filePageStyle.actionButton}
@@ -1074,7 +895,7 @@ class FilePage extends React.PureComponent {
hideText={false} hideText={false}
/> />
)} )}
{false && channelName && ( {channelName && (
<SubscribeNotificationButton <SubscribeNotificationButton
style={[filePageStyle.actionButton, filePageStyle.bellButton]} style={[filePageStyle.actionButton, filePageStyle.bellButton]}
uri={fullChannelUri} uri={fullChannelUri}
@@ -1090,28 +911,24 @@ class FilePage extends React.PureComponent {
<View style={filePageStyle.row}> <View style={filePageStyle.row}>
<View style={filePageStyle.amountRow}> <View style={filePageStyle.amountRow}>
<TextInput <TextInput
editable={!this.state.sendTipStarted}
ref={ref => (this.tipAmountInput = ref)} ref={ref => (this.tipAmountInput = ref)}
onChangeText={value => this.setState({ tipAmount: value })} onChangeText={value => this.setState({ tipAmount: value })}
underlineColorAndroid={Colors.NextLbryGreen}
keyboardType={'numeric'} keyboardType={'numeric'}
placeholder={'0'} placeholder={'0'}
value={this.state.tipAmount} value={this.state.tipAmount}
selectTextOnFocus
style={[filePageStyle.input, filePageStyle.tipAmountInput]} style={[filePageStyle.input, filePageStyle.tipAmountInput]}
/> />
<Text style={[filePageStyle.text, filePageStyle.currency]}>LBC</Text> <Text style={[filePageStyle.text, filePageStyle.currency]}>LBC</Text>
</View> </View>
{this.state.sendTipStarted && <ActivityIndicator size={'small'} color={Colors.NextLbryGreen} />}
<Link <Link
style={[filePageStyle.link, filePageStyle.cancelTipLink]} style={[filePageStyle.link, filePageStyle.cancelTipLink]}
text={__('Cancel')} text={'Cancel'}
onPress={() => this.setState({ showTipView: false })} onPress={() => this.setState({ showTipView: false })}
/> />
<Button <Button
text={__('Send a tip')} text={'Send a tip'}
style={[filePageStyle.button, filePageStyle.sendButton]} style={[filePageStyle.button, filePageStyle.sendButton]}
disabled={!canSendTip || this.state.sendTipStarted} disabled={!canSendTip}
onPress={this.handleSendTip} onPress={this.handleSendTip}
/> />
</View> </View>
@@ -1135,18 +952,10 @@ class FilePage extends React.PureComponent {
</View> </View>
)} )}
{costInfo && parseFloat(costInfo.cost) > balance && !fileInfo && ( {costInfo && parseFloat(costInfo.cost) > balance && <FileRewardsDriver navigation={navigation} />}
<FileRewardsDriver navigation={navigation} />
)}
<View onLayout={this.setRelatedContentPosition} /> <View onLayout={this.setRelatedContentPosition} />
<RelatedContent navigation={navigation} uri={uri} />
{isSearchingRecommendContent && (
<ActivityIndicator size="small" color={Colors.NextLbryGreen} style={filePageStyle.relatedLoading} />
)}
{!isSearchingRecommendContent && recommendedContent && recommendedContent.length > 0 && (
<RelatedContent navigation={navigation} uri={uri} fullUri={fullUri} />
)}
</ScrollView> </ScrollView>
</View> </View>
)} )}
+5 -7
View File
@@ -1,14 +1,14 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { SETTINGS, doToast } from 'lbry-redux'; import { doToast } from 'lbry-redux';
import { import {
doAuthenticate, doAuthenticate,
doCheckSync, doCheckSync,
doGetSync, doGetSync,
doSetDefaultAccount,
doSyncApply, doSyncApply,
doUserEmailNew, doUserEmailNew,
doUserResendVerificationEmail, doUserResendVerificationEmail,
selectAuthToken, selectAuthToken,
selectEmailAlreadyExists,
selectEmailNewErrorMessage, selectEmailNewErrorMessage,
selectEmailNewIsPending, selectEmailNewIsPending,
selectEmailToVerify, selectEmailToVerify,
@@ -22,19 +22,16 @@ import {
selectUser, selectUser,
} from 'lbryinc'; } from 'lbryinc';
import { doSetClientSetting } from 'redux/actions/settings'; import { doSetClientSetting } from 'redux/actions/settings';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import FirstRun from './view'; import FirstRun from './view';
const select = state => ({ const select = state => ({
authenticating: selectAuthenticationIsPending(state), authenticating: selectAuthenticationIsPending(state),
authToken: selectAuthToken(state), authToken: selectAuthToken(state),
emailToVerify: selectEmailToVerify(state), emailToVerify: selectEmailToVerify(state),
emailAlreadyExists: selectEmailAlreadyExists(state),
emailNewErrorMessage: selectEmailNewErrorMessage(state), emailNewErrorMessage: selectEmailNewErrorMessage(state),
emailNewPending: selectEmailNewIsPending(state), emailNewPending: selectEmailNewIsPending(state),
hasSyncedWallet: selectHasSyncedWallet(state), hasSyncedWallet: selectHasSyncedWallet(state),
getSyncIsPending: selectGetSyncIsPending(state), getSyncIsPending: selectGetSyncIsPending(state),
language: makeSelectClientSetting(SETTINGS.LANGUAGE)(state),
syncApplyErrorMessage: selectSyncApplyErrorMessage(state), syncApplyErrorMessage: selectSyncApplyErrorMessage(state),
syncApplyIsPending: selectSyncApplyIsPending(state), syncApplyIsPending: selectSyncApplyIsPending(state),
syncHash: selectSyncHash(state), syncHash: selectSyncHash(state),
@@ -44,11 +41,12 @@ const select = state => ({
const perform = dispatch => ({ const perform = dispatch => ({
addUserEmail: email => dispatch(doUserEmailNew(email)), addUserEmail: email => dispatch(doUserEmailNew(email)),
authenticate: (appVersion, os, firebaseToken) => dispatch(doAuthenticate(appVersion, os, firebaseToken)), authenticate: (appVersion, os) => dispatch(doAuthenticate(appVersion, os)),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)), setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
syncApply: (hash, data, password) => dispatch(doSyncApply(hash, data, password)), syncApply: (hash, data, password) => dispatch(doSyncApply(hash, data, password)),
getSync: (password, callback) => dispatch(doGetSync(password, callback)), getSync: password => dispatch(doGetSync(password)),
checkSync: () => dispatch(doCheckSync()), checkSync: () => dispatch(doCheckSync()),
setDefaultAccount: () => dispatch(doSetDefaultAccount()),
notify: data => dispatch(doToast(data)), notify: data => dispatch(doToast(data)),
resendVerificationEmail: email => dispatch(doUserResendVerificationEmail(email)), resendVerificationEmail: email => dispatch(doUserResendVerificationEmail(email)),
}); });
@@ -3,7 +3,7 @@ import { Lbry } from 'lbry-redux';
import { NativeModules, Platform, Text, TextInput, View } from 'react-native'; import { NativeModules, Platform, Text, TextInput, View } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage'; import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import firstRunStyle from 'styles/firstRun'; import firstRunStyle from 'styles/firstRun';
class EmailCollectPage extends React.PureComponent { class EmailCollectPage extends React.PureComponent {
@@ -44,7 +44,7 @@ class EmailCollectPage extends React.PureComponent {
const content = ( const content = (
<View onLayout={() => onEmailViewLayout('collect')}> <View onLayout={() => onEmailViewLayout('collect')}>
<Text style={firstRunStyle.title}>{__('Setup account')}</Text> <Text style={firstRunStyle.title}>Setup account</Text>
<TextInput <TextInput
style={firstRunStyle.emailInput} style={firstRunStyle.emailInput}
placeholder={this.state.placeholder} placeholder={this.state.placeholder}
@@ -64,10 +64,10 @@ class EmailCollectPage extends React.PureComponent {
}} }}
/> />
<Text style={firstRunStyle.paragraph}> <Text style={firstRunStyle.paragraph}>
{__('A lbry.tv account allows you to earn rewards, backup your wallet, and keep everything in sync.')} An account will allow you to earn rewards and keep your account and settings synced.
</Text> </Text>
<Text style={firstRunStyle.infoParagraph}> <Text style={firstRunStyle.infoParagraph}>
{__('This information is disclosed only to LBRY, Inc. and not to the LBRY network.')} This information is disclosed only to LBRY, Inc. and not to the LBRY network.
</Text> </Text>
</View> </View>
); );
+10 -12
View File
@@ -4,7 +4,7 @@ import { ActivityIndicator, Linking, NativeModules, Platform, Switch, Text, Text
import AsyncStorage from '@react-native-community/async-storage'; import AsyncStorage from '@react-native-community/async-storage';
import Button from 'component/button'; import Button from 'component/button';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import Icon from 'react-native-vector-icons/FontAwesome5'; import Icon from 'react-native-vector-icons/FontAwesome5';
import firstRunStyle from 'styles/firstRun'; import firstRunStyle from 'styles/firstRun';
@@ -13,30 +13,28 @@ class EmailVerifyPage extends React.PureComponent {
const { email, notify, resendVerificationEmail } = this.props; const { email, notify, resendVerificationEmail } = this.props;
resendVerificationEmail(email); resendVerificationEmail(email);
AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'true'); AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'true');
notify({ message: __('Please follow the instructions in the email sent to your address to continue.') }); notify({ message: 'Please follow the instructions in the email sent to your address to continue.' });
}; };
render() { render() {
const { onEmailViewLayout, email, emailAlreadyExists } = this.props; const { onEmailViewLayout, email } = this.props;
const content = ( const content = (
<View onLayout={() => onEmailViewLayout('verify')}> <View onLayout={() => onEmailViewLayout('verify')}>
<Text style={firstRunStyle.title}>{emailAlreadyExists ? __('Sign In') : __('Verify Email')}</Text> <Text style={firstRunStyle.title}>Verify Email</Text>
<Text style={firstRunStyle.paragraph}> <Text style={firstRunStyle.paragraph}>
{__('An email has been sent to')} An email has been sent to{' '}
{'\n\n'} <Text style={firstRunStyle.nowrap} numberOfLines={1}>
{email} {email}
{'\n\n'} </Text>
{emailAlreadyExists && __('Please click the link in the message to complete signing in')} . Please follow the instructions in the message to verify your email address.
{!emailAlreadyExists && __('Please click the link in the message to verify your email address')}.
</Text> </Text>
<View style={firstRunStyle.buttonContainer}> <View style={firstRunStyle.buttonContainer}>
<Button <Button
style={firstRunStyle.verificationButton} style={firstRunStyle.verificationButton}
theme={'light'} theme={'light'}
text={__('Resend')} text={'Resend'}
onPress={this.onResendPressed} onPress={this.onResendPressed}
/> />
</View> </View>
@@ -12,7 +12,7 @@ import {
View, View,
} from 'react-native'; } from 'react-native';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import Icon from 'react-native-vector-icons/FontAwesome5'; import Icon from 'react-native-vector-icons/FontAwesome5';
import firstRunStyle from 'styles/firstRun'; import firstRunStyle from 'styles/firstRun';
@@ -28,10 +28,10 @@ class SkipAccountPage extends React.PureComponent {
<View onLayout={onSkipAccountViewLayout}> <View onLayout={onSkipAccountViewLayout}>
<View style={firstRunStyle.row}> <View style={firstRunStyle.row}>
<Icon name="exclamation-triangle" style={firstRunStyle.titleIcon} size={32} color={Colors.White} /> <Icon name="exclamation-triangle" style={firstRunStyle.titleIcon} size={32} color={Colors.White} />
<Text style={firstRunStyle.title}>{__('Are you sure?')}</Text> <Text style={firstRunStyle.title}>Are you sure?</Text>
</View> </View>
<Text style={firstRunStyle.paragraph}> <Text style={firstRunStyle.paragraph}>
{__('Without an account, you will not receive rewards, sync and backup services, or security updates.')} Without an account, you will not receive rewards, sync and backup services, or security updates.
</Text> </Text>
<View style={[firstRunStyle.row, firstRunStyle.confirmContainer]}> <View style={[firstRunStyle.row, firstRunStyle.confirmContainer]}>
@@ -45,9 +45,8 @@ class SkipAccountPage extends React.PureComponent {
/> />
</View> </View>
<Text style={firstRunStyle.rowParagraph}> <Text style={firstRunStyle.rowParagraph}>
{__( I understand that by uninstalling LBRY I will lose any balances or published content with no recovery
'I understand that by uninstalling LBRY I will lose any balances or published content with no recovery option if it is not backed up manually (see wallet page)' option.
)}
</Text> </Text>
</View> </View>
</View> </View>
+11 -42
View File
@@ -14,7 +14,7 @@ import {
import { BarPasswordStrengthDisplay } from 'react-native-password-strength-meter'; import { BarPasswordStrengthDisplay } from 'react-native-password-strength-meter';
import AsyncStorage from '@react-native-community/async-storage'; import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import firstRunStyle from 'styles/firstRun'; import firstRunStyle from 'styles/firstRun';
import Icon from 'react-native-vector-icons/FontAwesome5'; import Icon from 'react-native-vector-icons/FontAwesome5';
@@ -28,32 +28,12 @@ class WalletPage extends React.PureComponent {
walletReady: false, walletReady: false,
hasCheckedSync: false, hasCheckedSync: false,
revealPassword: false, revealPassword: false,
autoPassword: false,
autoLoginAttempted: false,
}; };
componentDidMount() { componentDidMount() {
this.checkWalletReady(); this.checkWalletReady();
} }
componentDidUpdate() {
const { hasSyncedWallet, getSyncIsPending, onPasswordChanged, autoLogin } = this.props;
if (this.state.walletReady && this.state.hasCheckedSync && !getSyncIsPending) {
if (!hasSyncedWallet && !this.state.autoPassword) {
// new account, in which case, don't ask for a password, and act as the final first run step
this.setState({ password: '', autoPassword: true });
if (onPasswordChanged) {
onPasswordChanged('', true);
}
}
if (hasSyncedWallet && !this.state.autoLoginAttempted && autoLogin) {
autoLogin();
this.setState({ autoLoginAttempted: true });
}
}
}
checkWalletReady = () => { checkWalletReady = () => {
// make sure the sdk wallet component is ready // make sure the sdk wallet component is ready
Lbry.status() Lbry.status()
@@ -82,42 +62,31 @@ class WalletPage extends React.PureComponent {
}; };
render() { render() {
const { const { onPasswordChanged, onWalletViewLayout, getSyncIsPending, hasSyncedWallet, syncApplyIsPending } = this.props;
onPasswordChanged,
onWalletViewLayout,
getSyncIsPending,
hasSyncedWallet,
syncApplyIsPending,
syncApplyStarted,
syncApplyCompleted,
} = this.props;
let content; let content;
if (!this.state.walletReady || !this.state.hasCheckedSync || getSyncIsPending) { if (!this.state.walletReady || !this.state.hasCheckedSync || getSyncIsPending) {
content = ( content = (
<View style={firstRunStyle.centered}> <View style={firstRunStyle.centered}>
<ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} /> <ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} />
<Text style={firstRunStyle.paragraph}>{__('Retrieving your account information...')}</Text> <Text style={firstRunStyle.paragraph}>Retrieving your account information...</Text>
</View> </View>
); );
} else if (syncApplyStarted || syncApplyIsPending || syncApplyCompleted) { } else if (syncApplyIsPending) {
content = ( content = (
<View style={firstRunStyle.centered}> <View style={firstRunStyle.centered}>
<ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} /> <ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} />
<Text style={firstRunStyle.paragraph}> <Text style={firstRunStyle.paragraph}>Validating password...</Text>
{syncApplyIsPending ? __('Validating password') : __('Synchronizing')}...
</Text>
</View> </View>
); );
} else if (hasSyncedWallet && this.state.autoLoginAttempted) { } else {
// only display this view if it's not a new user (or auto-login has been attempted once)
content = ( content = (
<View onLayout={onWalletViewLayout}> <View onLayout={onWalletViewLayout}>
<Text style={firstRunStyle.title}>Password</Text> <Text style={firstRunStyle.title}>Password</Text>
<Text style={firstRunStyle.paragraph}> <Text style={firstRunStyle.paragraph}>
{hasSyncedWallet {hasSyncedWallet
? __('Please enter the password you used to secure your wallet.') ? 'Please enter the password you used to secure your wallet.'
: __('Please enter a password to secure your account and wallet.')} : 'Please enter a password to secure your account and wallet.'}
</Text> </Text>
<View style={firstRunStyle.passwordInputContainer}> <View style={firstRunStyle.passwordInputContainer}>
<TextInput <TextInput
@@ -150,8 +119,8 @@ class WalletPage extends React.PureComponent {
<View style={firstRunStyle.passwordWarning}> <View style={firstRunStyle.passwordWarning}>
<Text style={firstRunStyle.passwordWarningText}> <Text style={firstRunStyle.passwordWarningText}>
{hasSyncedWallet {hasSyncedWallet
? __('If you did not provide a password, please press Use LBRY to continue.') ? 'If you did not provide a password, please press Use LBRY to continue.'
: __('You can proceed without a password, but this is not recommended.')} : 'You can proceed without a password, but this is not recommended.'}
</Text> </Text>
</View> </View>
)} )}
@@ -166,7 +135,7 @@ class WalletPage extends React.PureComponent {
</View> </View>
)} )}
<Text style={firstRunStyle.infoParagraph}> <Text style={firstRunStyle.infoParagraph}>
{__('Note: for wallet security purposes, LBRY is unable to reset your password.')} Note: for wallet security purposes, LBRY is unable to reset your password.
</Text> </Text>
</View> </View>
); );
+26 -42
View File
@@ -3,8 +3,7 @@ import { Lbry } from 'lbry-redux';
import { ActivityIndicator, NativeModules, Platform, Text, View } from 'react-native'; import { ActivityIndicator, NativeModules, Platform, Text, View } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage'; import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import Link from 'component/link';
import firstRunStyle from 'styles/firstRun'; import firstRunStyle from 'styles/firstRun';
class WelcomePage extends React.PureComponent { class WelcomePage extends React.PureComponent {
@@ -26,7 +25,7 @@ class WelcomePage extends React.PureComponent {
} else { } else {
// first_user_auth because it's the first time // first_user_auth because it's the first time
AsyncStorage.getItem(Constants.KEY_FIRST_USER_AUTH).then(firstUserAuth => { AsyncStorage.getItem(Constants.KEY_FIRST_USER_AUTH).then(firstUserAuth => {
if (firstUserAuth !== 'true') { if ('true' !== firstUserAuth) {
// first_user_auth // first_user_auth
NativeModules.Firebase.track('first_user_auth', null); NativeModules.Firebase.track('first_user_auth', null);
AsyncStorage.setItem(Constants.KEY_FIRST_USER_AUTH, 'true'); AsyncStorage.setItem(Constants.KEY_FIRST_USER_AUTH, 'true');
@@ -45,39 +44,31 @@ class WelcomePage extends React.PureComponent {
} }
startAuthenticating = () => { startAuthenticating = () => {
const { authenticate } = this.props;
this.setState({ authenticationStarted: true, authenticationFailed: false }); this.setState({ authenticationStarted: true, authenticationFailed: false });
NativeModules.VersionInfo.getAppVersion().then(appVersion => { NativeModules.VersionInfo.getAppVersion().then(appVersion => {
NativeModules.Firebase.getMessagingToken() Lbry.status()
.then(firebaseToken => this.performAuthenticate(appVersion, firebaseToken)) .then(info => {
.catch(() => { this.setState({ sdkStarted: true });
this.performAuthenticate(appVersion); /* proceed without firebase */
authenticate(appVersion, Platform.OS);
})
.catch(error => {
if (this.state.statusTries >= WelcomePage.MAX_STATUS_TRIES) {
this.setState({ authenticationFailed: true });
// sdk_start_failed
NativeModules.Firebase.track('sdk_start_failed', null);
} else {
setTimeout(() => {
this.startAuthenticating();
this.setState({ statusTries: this.state.statusTries + 1 });
}, 1000); // Retry every second for a maximum of MAX_STATUS_TRIES tries (60 seconds)
}
}); });
}); });
}; };
performAuthenticate(appVersion, firebaseToken) {
const { authenticate } = this.props;
Lbry.status()
.then(info => {
this.setState({ sdkStarted: true });
authenticate(appVersion, Platform.OS, firebaseToken);
})
.catch(error => {
if (this.state.statusTries >= WelcomePage.MAX_STATUS_TRIES) {
this.setState({ authenticationFailed: true });
// sdk_start_failed
NativeModules.Firebase.track('sdk_start_failed', null);
} else {
setTimeout(() => {
this.startAuthenticating();
this.setState({ statusTries: this.state.statusTries + 1 });
}, 1000); // Retry every second for a maximum of MAX_STATUS_TRIES tries (60 seconds)
}
});
}
render() { render() {
const { authenticating, authToken, onWelcomePageLayout } = this.props; const { authenticating, authToken, onWelcomePageLayout } = this.props;
@@ -87,9 +78,8 @@ class WelcomePage extends React.PureComponent {
content = ( content = (
<View> <View>
<Text style={firstRunStyle.paragraph}> <Text style={firstRunStyle.paragraph}>
{__( The LBRY servers were unreachable at this time. Please check your Internet connection and then restart the
'The LBRY servers were unreachable at this time. Please check your Internet connection and then restart the app to try again.' app to try again.
)}
</Text> </Text>
</View> </View>
); );
@@ -97,7 +87,7 @@ class WelcomePage extends React.PureComponent {
content = ( content = (
<View style={firstRunStyle.centered}> <View style={firstRunStyle.centered}>
<ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} /> <ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} />
<Text style={firstRunStyle.paragraph}>{__('Please wait while we get some things ready...')}</Text> <Text style={firstRunStyle.paragraph}>Please wait while we get some things ready...</Text>
</View> </View>
); );
} else { } else {
@@ -105,14 +95,8 @@ class WelcomePage extends React.PureComponent {
<View onLayout={onWelcomePageLayout}> <View onLayout={onWelcomePageLayout}>
<Text style={firstRunStyle.title}>Welcome to LBRY.</Text> <Text style={firstRunStyle.title}>Welcome to LBRY.</Text>
<Text style={firstRunStyle.paragraph}> <Text style={firstRunStyle.paragraph}>
{__( LBRY is a community-controlled content platform where you can find and publish videos, music, books, and
'LBRY is a community-controlled content platform where you can find and publish videos, music, books, and more.' more.
)}
</Text>
<Text style={[firstRunStyle.infoParagraph, firstRunStyle.tosParagraph]}>
By continuing, I agree to the{' '}
<Link style={firstRunStyle.tosLink} text={'Terms of Service'} href={'https://lbry.com/termsofservice'} />{' '}
and confirm I am over the age of 13.
</Text> </Text>
</View> </View>
); );
+49 -138
View File
@@ -1,17 +1,16 @@
import React from 'react'; import React from 'react';
import { SETTINGS, Lbry } from 'lbry-redux'; import { Lbry } from 'lbry-redux';
import { ActivityIndicator, Linking, NativeModules, Text, TouchableOpacity, View } from 'react-native'; import { ActivityIndicator, Linking, NativeModules, Text, TouchableOpacity, View } from 'react-native';
import { NavigationActions, StackActions } from 'react-navigation'; import { NavigationActions, StackActions } from 'react-navigation';
import AsyncStorage from '@react-native-community/async-storage'; import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import WalletPage from './internal/wallet-page'; import WalletPage from './internal/wallet-page';
import WelcomePage from './internal/welcome-page'; import WelcomePage from './internal/welcome-page';
import EmailCollectPage from './internal/email-collect-page'; import EmailCollectPage from './internal/email-collect-page';
import EmailVerifyPage from './internal/email-verify-page'; import EmailVerifyPage from './internal/email-verify-page';
import SkipAccountPage from './internal/skip-account-page'; import SkipAccountPage from './internal/skip-account-page';
import firstRunStyle from 'styles/firstRun'; import firstRunStyle from 'styles/firstRun';
import RNFS from 'react-native-fs';
class FirstRunScreen extends React.PureComponent { class FirstRunScreen extends React.PureComponent {
static pages = [ static pages = [
@@ -30,15 +29,12 @@ class FirstRunScreen extends React.PureComponent {
enterPasswordTracked: false, enterPasswordTracked: false,
isFirstRun: false, isFirstRun: false,
launchUrl: null, launchUrl: null,
languageLoaded: false,
showSkip: false, showSkip: false,
isEmailVerified: false, isEmailVerified: false,
skipAccountConfirmed: false, skipAccountConfirmed: false,
showBottomContainer: false, showBottomContainer: false,
walletPassword: '', walletPassword: null,
syncApplyStarted: false, syncApplyStarted: false,
syncApplyCompleted: false,
language: null,
}; };
componentDidMount() { componentDidMount() {
@@ -48,70 +44,28 @@ class FirstRunScreen extends React.PureComponent {
} }
}); });
NativeModules.UtilityModule.getNativeStringSetting(SETTINGS.LANGUAGE, 'en').then(language => if (NativeModules.FirstRun) {
this.loadLanguage(language) NativeModules.FirstRun.isFirstRun().then(firstRun => {
); AsyncStorage.removeItem(Constants.KEY_FIRST_RUN_EMAIL);
} AsyncStorage.removeItem(Constants.KEY_EMAIL_VERIFY_PENDING);
this.setState({ isFirstRun: firstRun });
loadLanguage = language => { if (firstRun) {
if (!language || language === 'en') { this.setState({ currentPage: FirstRunScreen.pages[0] });
this.checkFirstRun(); } else {
} else { // Not the first run. Navigate to the splash screen right away
// Load the current language setting before doing anything this.launchSplashScreen();
const languageFile = RNFS.ExternalDirectoryPath + '/' + language + '.json'; }
RNFS.readFile(languageFile, 'utf8')
.then(fileContents => {
const json = JSON.parse(fileContents);
window.language = language;
window.i18n_messages[language] = json;
// language exists, so download an update
this.downloadLanguageUpdate(language);
this.checkFirstRun();
})
.catch(err => {
// language file doesn't exist? maintain the default language
this.checkFirstRun();
});
}
};
downloadLanguageUpdate = language => {
fetch('https://lbry.com/i18n/get/lbry-mobile/app-strings/' + language + '.json')
.then(r => r.json())
.then(j => {
window.i18n_messages[language] = j;
// write the language file to the filesystem
const langFilePath = RNFS.ExternalDirectoryPath + '/' + language + '.json';
RNFS.writeFile(langFilePath, JSON.stringify(j), 'utf8');
// update state and client setting
window.language = language;
})
.catch(() => {
/* pass */
}); });
}; } else {
// The first run module was not detected. Go straight to the splash screen.
checkFirstRun = () => { this.launchSplashScreen();
NativeModules.FirstRun.isFirstRun().then(firstRun => { }
AsyncStorage.removeItem(Constants.KEY_FIRST_RUN_EMAIL); }
AsyncStorage.removeItem(Constants.KEY_EMAIL_VERIFY_PENDING);
this.setState({ isFirstRun: firstRun });
if (firstRun) {
NativeModules.Firebase.setCurrentScreen('First Run');
this.setState({ currentPage: FirstRunScreen.pages[0] });
} else {
// Not the first run. Navigate to the splash screen right away
this.launchSplashScreen();
}
});
};
componentWillReceiveProps(nextProps) { componentWillReceiveProps(nextProps) {
const { emailNewErrorMessage, emailNewPending, syncApplyErrorMessage, syncApplyIsPending, user } = nextProps; const { emailNewErrorMessage, emailNewPending, syncApplyErrorMessage, syncApplyIsPending, user } = nextProps;
const { notify, isApplyingSync, setClientSetting } = this.props; const { notify, isApplyingSync, setClientSetting, setDefaultAccount } = this.props;
if (this.state.emailSubmitted && !emailNewPending) { if (this.state.emailSubmitted && !emailNewPending) {
this.setState({ emailSubmitted: false }); this.setState({ emailSubmitted: false });
@@ -119,41 +73,23 @@ class FirstRunScreen extends React.PureComponent {
notify({ message: String(emailNewErrorMessage), isError: true }); notify({ message: String(emailNewErrorMessage), isError: true });
} else { } else {
// Request successful. Navigate to email verify page. // Request successful. Navigate to email verify page.
NativeModules.Firebase.track('email_added', { email: this.state.email });
this.showPage(Constants.FIRST_RUN_PAGE_EMAIL_VERIFY); this.showPage(Constants.FIRST_RUN_PAGE_EMAIL_VERIFY);
} }
} }
if (this.state.syncApplyStarted && !syncApplyIsPending) { if (this.state.syncApplyStarted && !syncApplyIsPending) {
this.setState({ syncApplyStarted: false });
if (syncApplyErrorMessage && syncApplyErrorMessage.trim().length > 0) { if (syncApplyErrorMessage && syncApplyErrorMessage.trim().length > 0) {
notify({ message: __(syncApplyErrorMessage), isError: true }); notify({ message: syncApplyErrorMessage, isError: true });
this.setState({ showBottomContainer: true, syncApplyStarted: false, syncApplyCompleted: false }); this.setState({ showBottomContainer: true });
} else { } else {
this.setState({ syncApplyCompleted: true });
// password successfully verified // password successfully verified
NativeModules.UtilityModule.setSecureValue( if (NativeModules.UtilityModule) {
Constants.KEY_WALLET_PASSWORD, NativeModules.UtilityModule.setSecureValue(Constants.KEY_FIRST_RUN_PASSWORD, this.state.walletPassword);
this.state.walletPassword ? this.state.walletPassword : '' }
); setDefaultAccount();
setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, true); setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, true);
Lbry.wallet_status().then(status => { this.closeFinalPage();
// unlock the wallet
if (status.is_locked) {
Lbry.wallet_unlock({ password: this.state.walletPassword ? this.state.walletPassword : '' }).then(
unlocked => {
if (unlocked) {
this.closeFinalPage();
} else {
notify({ message: __('The wallet could not be unlocked at this time. Please restart the app.') });
}
}
);
} else {
// wallet not locked. close final page
this.closeFinalPage();
}
});
} }
} }
@@ -179,9 +115,9 @@ class FirstRunScreen extends React.PureComponent {
const { navigation } = this.props; const { navigation } = this.props;
const resetAction = StackActions.reset({ const resetAction = StackActions.reset({
index: 0, index: 0,
actions: [NavigationActions.navigate({ routeName: 'Splash', params: { launchUri: this.state.launchUrl } })], actions: [NavigationActions.navigate({ routeName: 'Splash', params: { launchUri: this.state.launchUri } })],
}); });
setTimeout(() => navigation.dispatch(resetAction), 1000); navigation.dispatch(resetAction);
} }
handleLeftButtonPressed = () => { handleLeftButtonPressed = () => {
@@ -210,13 +146,6 @@ class FirstRunScreen extends React.PureComponent {
}); });
}; };
autoLogin = () => {
const { hasSyncedWallet } = this.props;
if (hasSyncedWallet && !this.state.syncApplyStarted) {
this.checkWalletPassword();
}
};
handleContinuePressed = () => { handleContinuePressed = () => {
const { notify, user, hasSyncedWallet } = this.props; const { notify, user, hasSyncedWallet } = this.props;
const pageIndex = FirstRunScreen.pages.indexOf(this.state.currentPage); const pageIndex = FirstRunScreen.pages.indexOf(this.state.currentPage);
@@ -231,7 +160,7 @@ class FirstRunScreen extends React.PureComponent {
} }
if (Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage && !this.state.skipAccountConfirmed) { if (Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage && !this.state.skipAccountConfirmed) {
notify({ message: __('Please confirm that you want to use LBRY without creating an account.') }); notify({ message: 'Please confirm that you want to use LBRY without creating an account.' });
return; return;
} }
@@ -257,7 +186,7 @@ class FirstRunScreen extends React.PureComponent {
// validate the email // validate the email
if (!email || email.indexOf('@') === -1) { if (!email || email.indexOf('@') === -1) {
return notify({ return notify({
message: __('Please provide a valid email address to continue.'), message: 'Please provide a valid email address to continue.',
}); });
} }
@@ -289,7 +218,6 @@ class FirstRunScreen extends React.PureComponent {
closeFinalPage() { closeFinalPage() {
// Final page. Let the app know that first run experience is completed. // Final page. Let the app know that first run experience is completed.
this.setState({ syncApplyStarted: false });
if (NativeModules.FirstRun) { if (NativeModules.FirstRun) {
NativeModules.FirstRun.firstRunCompleted(); NativeModules.FirstRun.firstRunCompleted();
} }
@@ -300,7 +228,7 @@ class FirstRunScreen extends React.PureComponent {
onEmailChanged = email => { onEmailChanged = email => {
this.setState({ email }); this.setState({ email });
if (Constants.FIRST_RUN_PAGE_EMAIL_COLLECT === this.state.currentPage) { if (Constants.FIRST_RUN_PAGE_EMAIL_COLLECT == this.state.currentPage) {
this.setState({ showSkip: !email || email.trim().length === 0 }); this.setState({ showSkip: !email || email.trim().length === 0 });
} else { } else {
this.setState({ showSkip: false }); this.setState({ showSkip: false });
@@ -308,26 +236,22 @@ class FirstRunScreen extends React.PureComponent {
}; };
onEmailViewLayout = phase => { onEmailViewLayout = phase => {
if (phase === 'collect') { if ('collect' === phase) {
if (!this.state.emailCollectTracked) { if (!this.state.emailCollectTracked) {
// we only want to track this once // we only want to track this once
this.setState({ emailCollectTracked: true }, () => this.setState({ emailCollectTracked: true }, () =>
NativeModules.Firebase.track('first_run_email_collect', null) NativeModules.Firebase.track('first_run_email_collect', null)
); );
} }
} else if (phase === 'verify') { } else if ('verify' === phase) {
NativeModules.Firebase.track('first_run_email_verify', null); NativeModules.Firebase.track('first_run_email_verify', null);
} }
this.setState({ showBottomContainer: true, showSkip: true }); this.setState({ showBottomContainer: true, showSkip: true });
}; };
onWalletPasswordChanged = (password, finalStep) => { onWalletPasswordChanged = password => {
this.setState({ walletPassword: password !== null ? password : '' }); this.setState({ walletPassword: password });
if (finalStep) {
// final step for a new user
this.setFreshPassword();
}
}; };
onWalletViewLayout = () => { onWalletViewLayout = () => {
@@ -356,20 +280,13 @@ class FirstRunScreen extends React.PureComponent {
const { getSync, setClientSetting } = this.props; const { getSync, setClientSetting } = this.props;
if (NativeModules.UtilityModule) { if (NativeModules.UtilityModule) {
const newPassword = this.state.walletPassword ? this.state.walletPassword : ''; const newPassword = this.state.walletPassword ? this.state.walletPassword : '';
NativeModules.UtilityModule.setSecureValue(Constants.KEY_WALLET_PASSWORD, newPassword); NativeModules.UtilityModule.setSecureValue(Constants.KEY_FIRST_RUN_PASSWORD, newPassword);
if (newPassword.trim().length === 0) { Lbry.account_encrypt({ new_password: newPassword }).then(() => {
// blank password. Do not encrypt // fresh account, new password set
getSync(newPassword); getSync(newPassword);
setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, true); setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, true);
this.closeFinalPage(); this.closeFinalPage();
} else { });
Lbry.wallet_encrypt({ new_password: newPassword }).then(() => {
// fresh account, new password set
getSync(newPassword);
setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, true);
this.closeFinalPage();
});
}
} }
}; };
@@ -379,11 +296,9 @@ class FirstRunScreen extends React.PureComponent {
authenticating, authenticating,
authToken, authToken,
checkSync, checkSync,
emailAlreadyExists,
emailNewErrorMessage, emailNewErrorMessage,
emailNewPending, emailNewPending,
emailToVerify, emailToVerify,
language,
notify, notify,
hasSyncedWallet, hasSyncedWallet,
getSyncIsPending, getSyncIsPending,
@@ -421,7 +336,6 @@ class FirstRunScreen extends React.PureComponent {
<EmailVerifyPage <EmailVerifyPage
onEmailViewLayout={this.onEmailViewLayout} onEmailViewLayout={this.onEmailViewLayout}
email={this.state.email} email={this.state.email}
emailAlreadyExists={emailAlreadyExists}
notify={notify} notify={notify}
resendVerificationEmail={resendVerificationEmail} resendVerificationEmail={resendVerificationEmail}
/> />
@@ -435,11 +349,8 @@ class FirstRunScreen extends React.PureComponent {
hasSyncedWallet={hasSyncedWallet} hasSyncedWallet={hasSyncedWallet}
getSyncIsPending={getSyncIsPending} getSyncIsPending={getSyncIsPending}
syncApplyIsPending={syncApplyIsPending} syncApplyIsPending={syncApplyIsPending}
syncApplyStarted={this.state.syncApplyStarted}
syncApplyCompleted={this.state.syncApplyCompleted}
onWalletViewLayout={this.onWalletViewLayout} onWalletViewLayout={this.onWalletViewLayout}
onPasswordChanged={this.onWalletPasswordChanged} onPasswordChanged={this.onWalletPasswordChanged}
autoLogin={this.autoLogin}
/> />
); );
break; break;
@@ -472,29 +383,29 @@ class FirstRunScreen extends React.PureComponent {
<Text style={firstRunStyle.buttonText}> <Text style={firstRunStyle.buttonText}>
«{' '} «{' '}
{Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage {Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage
? __('Setup account') ? 'Setup account'
: __('Change email')} : 'Change email'}
</Text> </Text>
</TouchableOpacity> </TouchableOpacity>
)} )}
{!emailNewPending && Constants.FIRST_RUN_PAGE_EMAIL_COLLECT === this.state.currentPage && ( {!emailNewPending && Constants.FIRST_RUN_PAGE_EMAIL_COLLECT === this.state.currentPage && (
<TouchableOpacity style={firstRunStyle.leftButton} onPress={this.handleLeftButtonPressed}> <TouchableOpacity style={firstRunStyle.leftButton} onPress={this.handleLeftButtonPressed}>
<Text style={firstRunStyle.smallLeftButtonText}>{__('No, thanks')} »</Text> <Text style={firstRunStyle.smallLeftButtonText}>No, thanks »</Text>
</TouchableOpacity> </TouchableOpacity>
)} )}
{!emailNewPending && ( {!emailNewPending && (
<TouchableOpacity style={firstRunStyle.button} onPress={this.handleContinuePressed}> <TouchableOpacity style={firstRunStyle.button} onPress={this.handleContinuePressed}>
{Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage && ( {Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage && (
<Text style={firstRunStyle.smallButtonText}>{__('Use LBRY')} »</Text> <Text style={firstRunStyle.smallButtonText}>Use LBRY »</Text>
)} )}
{Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT !== this.state.currentPage && {Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT !== this.state.currentPage &&
Constants.FIRST_RUN_PAGE_EMAIL_VERIFY !== this.state.currentPage && ( Constants.FIRST_RUN_PAGE_EMAIL_VERIFY !== this.state.currentPage && (
<Text style={firstRunStyle.buttonText}> <Text style={firstRunStyle.buttonText}>
{Constants.FIRST_RUN_PAGE_WALLET === this.state.currentPage ? __('Use LBRY') : __('Continue')} » {Constants.FIRST_RUN_PAGE_WALLET === this.state.currentPage ? 'Use LBRY' : 'Continue'} »
</Text> </Text>
)} )}
</TouchableOpacity> </TouchableOpacity>
)} )}
</View> </View>
+6 -18
View File
@@ -3,37 +3,25 @@ import {
doPublish, doPublish,
doResolveUri, doResolveUri,
doToast, doToast,
doUpdatePublishForm, doUploadThumbnail,
selectBalance, selectBalance,
selectMyClaims,
selectPublishFormValues, selectPublishFormValues,
} from 'lbry-redux'; } from 'lbry-redux';
import { selectDrawerStack } from 'redux/selectors/drawer'; import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { doUpdatePublishFormState, doClearPublishFormState, doPendingPublishSuccess } from 'redux/actions/form'; import Constants from 'constants';
import { doPushDrawerStack, doPopDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectPublishFormState, selectHasPublishFormState } from 'redux/selectors/form';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import PublishPage from './view'; import PublishPage from './view';
const select = state => ({ const select = state => ({
balance: selectBalance(state), balance: selectBalance(state),
drawerStack: selectDrawerStack(state),
hasFormState: selectHasPublishFormState(state),
myClaims: selectMyClaims(state),
publishFormState: selectPublishFormState(state),
publishFormValues: selectPublishFormValues(state), publishFormValues: selectPublishFormValues(state),
}); });
const perform = dispatch => ({ const perform = dispatch => ({
notify: data => dispatch(doToast(data)), notify: data => dispatch(doToast(data)),
clearPublishFormState: () => dispatch(doClearPublishFormState()), uploadThumbnail: (filePath, fsAdapter) => dispatch(doUploadThumbnail(filePath, null, fsAdapter)),
pendingPublishSuccess: pendingClaim => dispatch(doPendingPublishSuccess(pendingClaim)), publish: params => dispatch(doPublish(params)),
updatePublishForm: value => dispatch(doUpdatePublishForm(value)),
updatePublishFormState: data => dispatch(doUpdatePublishFormState(data)),
publish: (success, fail) => dispatch(doPublish(success, fail)),
resolveUri: uri => dispatch(doResolveUri(uri)), resolveUri: uri => dispatch(doResolveUri(uri)),
pushDrawerStack: (routeName, params) => dispatch(doPushDrawerStack(routeName, params)), pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_PUBLISH)),
popDrawerStack: () => dispatch(doPopDrawerStack()),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false)), setPlayerVisible: () => dispatch(doSetPlayerVisible(false)),
}); });
+253 -697
View File
File diff suppressed because it is too large. Load diff
+1 -13
View File
@@ -1,13 +1,5 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { import { doCheckPendingPublishes, selectMyClaimUrisWithoutChannels, selectIsFetchingClaimListMine } from 'lbry-redux';
doAbandonClaim,
doCheckPendingPublishes,
doFetchClaimListMine,
doToast,
selectMyClaimUrisWithoutChannels,
selectPendingClaims,
selectIsFetchingClaimListMine,
} from 'lbry-redux';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer'; import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import PublishesPage from './view'; import PublishesPage from './view';
@@ -15,14 +7,10 @@ import PublishesPage from './view';
const select = state => ({ const select = state => ({
uris: selectMyClaimUrisWithoutChannels(state), uris: selectMyClaimUrisWithoutChannels(state),
fetching: selectIsFetchingClaimListMine(state), fetching: selectIsFetchingClaimListMine(state),
pendingClaims: selectPendingClaims(state),
}); });
const perform = dispatch => ({ const perform = dispatch => ({
abandonClaim: (txid, nout) => dispatch(doAbandonClaim(txid, nout)),
fetchMyClaims: () => dispatch(doFetchClaimListMine()),
checkPendingPublishes: () => dispatch(doCheckPendingPublishes()), checkPendingPublishes: () => dispatch(doCheckPendingPublishes()),
notify: data => dispatch(doToast(data)),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_PUBLISHES)), pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_PUBLISHES)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false)), setPlayerVisible: () => dispatch(doSetPlayerVisible(false)),
}); });
+19 -142
View File
@@ -1,27 +1,20 @@
import React from 'react'; import React from 'react';
import { ActivityIndicator, Alert, FlatList, NativeModules, Text, TouchableOpacity, View } from 'react-native'; import { ActivityIndicator, FlatList, Text, TouchableOpacity, View } from 'react-native';
import Button from 'component/button'; import Button from 'component/button';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
import EmptyStateView from 'component/emptyStateView';
import FileListItem from 'component/fileListItem'; import FileListItem from 'component/fileListItem';
import FloatingWalletBalance from 'component/floatingWalletBalance'; import FloatingWalletBalance from 'component/floatingWalletBalance';
import UriBar from 'component/uriBar'; import UriBar from 'component/uriBar';
import publishStyle from 'styles/publish'; import publishStyle from 'styles/publish';
import { navigateToUri } from 'utils/helper'; import { __ } from 'utils/helper';
class PublishesPage extends React.PureComponent { class PublishesPage extends React.PureComponent {
state = {
selectionMode: false,
selectedUris: [],
selectedClaimsMap: {},
};
didFocusListener; didFocusListener;
componentWillMount() { componentWillMount() {
const { navigation } = this.props; const { navigation } = this.props;
// this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused); this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
} }
componentWillUnmount() { componentWillUnmount() {
@@ -30,164 +23,48 @@ class PublishesPage extends React.PureComponent {
} }
} }
componentDidMount() {
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { currentRoute } = nextProps;
const { currentRoute: prevRoute } = this.props;
if (Constants.DRAWER_ROUTE_PUBLISHES === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
}
onComponentFocused = () => { onComponentFocused = () => {
const { checkPendingPublishes, fetchMyClaims, pushDrawerStack, setPlayerVisible } = this.props; const { checkPendingPublishes, pushDrawerStack, setPlayerVisible } = this.props;
pushDrawerStack(); pushDrawerStack();
setPlayerVisible(); setPlayerVisible();
NativeModules.Firebase.setCurrentScreen('Publishes').then(result => { checkPendingPublishes();
fetchMyClaims();
checkPendingPublishes();
});
};
addOrRemoveItem = (uri, claim) => {
const { pendingClaims } = this.state;
const { selectedClaimsMap } = this.state;
let selectedUris = [...this.state.selectedUris];
if (selectedUris.includes(uri)) {
delete selectedClaimsMap[uri];
selectedUris.splice(selectedUris.indexOf(uri), 1);
} else {
selectedClaimsMap[uri] = claim;
selectedUris.push(uri);
}
this.setState({ selectionMode: selectedUris.length > 0, selectedUris, selectedClaimsMap });
};
handleSelectItem = (uri, claim) => {
this.addOrRemoveItem(uri, claim);
};
handleItemLongPress = (uri, claim) => {
this.addOrRemoveItem(uri, claim);
};
onExitSelectionMode = () => {
this.setState({ selectionMode: false, selectedUris: [], selectedClaimsMap: {} });
};
onEditActionPressed = () => {
const { navigation } = this.props;
const { selectedClaimsMap, selectedUris } = this.state;
// only 1 item can be edited (and edit button should be visible only if there is a single selection)
const claim = selectedClaimsMap[selectedUris[0]];
this.onExitSelectionMode();
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_PUBLISH, params: { editMode: true, claimToEdit: claim } });
};
onDeleteActionPressed = () => {
const { abandonClaim } = this.props;
const { selectedClaimsMap } = this.state;
// show confirm alert
Alert.alert(
__('Unpublish'),
__('Are you sure you want to unpublish the selected content?'),
[
{ text: __('No') },
{
text: __('Yes'),
onPress: () => {
const uris = Object.keys(selectedClaimsMap);
uris.forEach(uri => {
const { txid, nout } = selectedClaimsMap[uri];
abandonClaim(txid, nout);
});
this.onExitSelectionMode();
},
},
],
{ cancelable: true }
);
}; };
render() { render() {
const { fetching, navigation, uris } = this.props; const { fetching, navigation, uris } = this.props;
const { selectionMode, selectedUris } = this.state;
return ( return (
<View style={publishStyle.container}> <View style={publishStyle.container}>
<UriBar <UriBar navigation={navigation} />
allowEdit
navigation={navigation}
selectionMode={selectionMode}
selectedItemCount={selectedUris.length}
onDeleteActionPressed={this.onDeleteActionPressed}
onEditActionPressed={this.onEditActionPressed}
onExitSelectionMode={this.onExitSelectionMode}
/>
{fetching && ( {fetching && (
<View style={publishStyle.centered}> <View style={publishStyle.centered}>
<ActivityIndicator size={'large'} color={Colors.NextLbryGreen} /> <ActivityIndicator size={'small'} color={Colors.LbryGreen} />
</View> </View>
)} )}
{!fetching && (!uris || uris.length === 0) && ( {!fetching && (!uris || uris.length === 0) && (
<EmptyStateView <View style={publishStyle.noPublishes}>
message={__('It looks like you have not\npublished any content to LBRY yet.')} <Text style={publishStyle.noPublishText}>
buttonText={__('Publish something new')} {__('It looks like you have not published anything to LBRY yet.')}
onButtonPress={() => navigation.navigate({ routeName: Constants.DRAWER_ROUTE_PUBLISH })} </Text>
/> <Button
style={publishStyle.publishNowButton}
text={__('Publish something new')}
onPress={() => navigation.navigate({ routeName: Constants.DRAWER_ROUTE_PUBLISH })}
/>
</View>
)} )}
{uris && uris.length > 0 && ( {uris && uris.length > 0 && (
<FlatList <FlatList
style={publishStyle.publishesList} style={publishStyle.publishesList}
contentContainerStyle={publishStyle.publishesScrollPadding} contentContainerStyle={publishStyle.publishesScrollPadding}
extraData={this.state}
initialNumToRender={8} initialNumToRender={8}
maxToRenderPerBatch={24} maxToRenderPerBatch={24}
removeClippedSubviews removeClippedSubviews
ListFooterComponent={
<View style={publishStyle.publishesFooter}>
<Button
style={publishStyle.publishesFooterButton}
text={__('Publish something new')}
onPress={() => navigation.navigate({ routeName: Constants.DRAWER_ROUTE_PUBLISH })}
/>
</View>
}
renderItem={({ item }) => ( renderItem={({ item }) => (
<FileListItem <FileListItem hideChannel key={item} uri={item} style={publishStyle.listItem} navigation={navigation} />
key={item}
uri={item}
style={publishStyle.listItem}
selected={selectedUris.includes(item)}
onPress={claim => {
if (selectionMode) {
this.handleSelectItem(item, claim);
} else {
const { notify, pendingClaims } = this.props;
if (pendingClaims.some(pendingClaim => pendingClaim.claim_id === claim.claim_id)) {
notify({
message: __('This content is currently pending. It will be available in a few minutes.'),
});
} else {
// TODO: when shortUrl is available for my claims, navigate to that URL instead
navigateToUri(navigation, item);
}
}
}}
onLongPress={claim => this.handleItemLongPress(item, claim)}
navigation={navigation}
/>
)} )}
data={uris} data={uris}
keyExtractor={(item, index) => item} keyExtractor={(item, index) => item}
+5 -9
View File
@@ -8,6 +8,7 @@ import CustomRewardCard from 'component/customRewardCard';
import PageHeader from 'component/pageHeader'; import PageHeader from 'component/pageHeader';
import RewardCard from 'component/rewardCard'; import RewardCard from 'component/rewardCard';
import RewardEnrolment from 'component/rewardEnrolment'; import RewardEnrolment from 'component/rewardEnrolment';
import RewardSummary from 'component/rewardSummary';
import UriBar from 'component/uriBar'; import UriBar from 'component/uriBar';
import rewardStyle from 'styles/reward'; import rewardStyle from 'styles/reward';
@@ -27,7 +28,7 @@ class RewardsPage extends React.PureComponent {
componentWillMount() { componentWillMount() {
const { navigation } = this.props; const { navigation } = this.props;
// this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused); this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
} }
componentWillUnmount() { componentWillUnmount() {
@@ -41,8 +42,6 @@ class RewardsPage extends React.PureComponent {
pushDrawerStack(); pushDrawerStack();
setPlayerVisible(); setPlayerVisible();
NativeModules.Firebase.setCurrentScreen('Rewards');
fetchRewards(); fetchRewards();
this.setState({ this.setState({
@@ -106,8 +105,7 @@ class RewardsPage extends React.PureComponent {
<View style={[rewardStyle.card, rewardStyle.verification]}> <View style={[rewardStyle.card, rewardStyle.verification]}>
<Text style={rewardStyle.title}>Manual Reward Verification</Text> <Text style={rewardStyle.title}>Manual Reward Verification</Text>
<Text style={rewardStyle.text}> <Text style={rewardStyle.text}>
__('You need to be manually verified before you can start claiming rewards.') Please request to be verified You need to be manually verified before you can start claiming rewards. Please request to be verified on the{' '}
on the{' '}
<Link <Link
style={rewardStyle.greenLink} style={rewardStyle.greenLink}
href="https://discordapp.com/invite/Z3bERWA" href="https://discordapp.com/invite/Z3bERWA"
@@ -130,15 +128,13 @@ class RewardsPage extends React.PureComponent {
return ( return (
<View style={rewardStyle.busyContainer}> <View style={rewardStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.NextLbryGreen} /> <ActivityIndicator size="large" color={Colors.NextLbryGreen} />
<Text style={rewardStyle.infoText}>{__('Fetching rewards...')}</Text> <Text style={rewardStyle.infoText}>Fetching rewards...</Text>
</View> </View>
); );
} else if (user === null) { } else if (user === null) {
return ( return (
<View style={rewardStyle.busyContainer}> <View style={rewardStyle.busyContainer}>
<Text style={rewardStyle.infoText}> <Text style={rewardStyle.infoText}>This app is unable to earn rewards due to an authentication failure.</Text>
{__('This app is unable to earn rewards due to an authentication failure.')}
</Text>
</View> </View>
); );
} }
+3 -9
View File
@@ -1,10 +1,8 @@
import { connect } from 'react-redux'; import { connect } from 'react-redux';
import { import {
doClaimSearch,
doSearch, doSearch,
doUpdateSearchQuery, doUpdateSearchQuery,
makeSelectSearchUris, makeSelectSearchUris,
selectClaimSearchByQuery,
selectIsSearching, selectIsSearching,
selectSearchValue, selectSearchValue,
makeSelectQueryWithOptions, makeSelectQueryWithOptions,
@@ -12,23 +10,19 @@ import {
} from 'lbry-redux'; } from 'lbry-redux';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer'; import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectCurrentRoute } from 'redux/selectors/drawer'; import { selectCurrentRoute } from 'redux/selectors/drawer';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants';
import SearchPage from './view'; import SearchPage from './view';
const numSearchResults = 25;
const select = state => ({ const select = state => ({
claimSearchByQuery: selectClaimSearchByQuery(state),
currentRoute: selectCurrentRoute(state), currentRoute: selectCurrentRoute(state),
isSearching: selectIsSearching(state), isSearching: selectIsSearching(state),
query: selectSearchValue(state), query: selectSearchValue(state),
uris: makeSelectSearchUris(makeSelectQueryWithOptions(null, numSearchResults)(state))(state), uris: makeSelectSearchUris(makeSelectQueryWithOptions(null, 25)(state))(state),
urisByQuery: selectSearchUrisByQuery(state), urisByQuery: selectSearchUrisByQuery(state),
}); });
const perform = dispatch => ({ const perform = dispatch => ({
search: query => dispatch(doSearch(query, numSearchResults)), search: query => dispatch(doSearch(query, 25)),
claimSearch: options => dispatch(doClaimSearch(options)),
updateSearchQuery: query => dispatch(doUpdateSearchQuery(query)), updateSearchQuery: query => dispatch(doUpdateSearchQuery(query)),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_SEARCH)), pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_SEARCH)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false)), setPlayerVisible: () => dispatch(doSetPlayerVisible(false)),
+50 -102
View File
@@ -1,15 +1,6 @@
import React from 'react'; import React from 'react';
import { Lbry, createNormalizedClaimSearchKey, parseURI, normalizeURI, isURIValid } from 'lbry-redux'; import { Lbry, parseURI, normalizeURI, isURIValid } from 'lbry-redux';
import { import { ActivityIndicator, Button, Text, TextInput, View, ScrollView } from 'react-native';
ActivityIndicator,
Button,
FlatList,
NativeModules,
Text,
TextInput,
TouchableOpacity,
View,
} from 'react-native';
import { navigateToUri } from 'utils/helper'; import { navigateToUri } from 'utils/helper';
import Colors from 'styles/colors'; import Colors from 'styles/colors';
import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api import Constants from 'constants'; // eslint-disable-line node/no-deprecated-api
@@ -23,9 +14,6 @@ class SearchPage extends React.PureComponent {
state = { state = {
currentQuery: null, currentQuery: null,
currentUri: null, currentUri: null,
showTagResult: false,
claimSearchRun: false,
claimSearchOptions: null,
}; };
static navigationOptions = { static navigationOptions = {
@@ -36,7 +24,7 @@ class SearchPage extends React.PureComponent {
componentWillMount() { componentWillMount() {
const { navigation } = this.props; const { navigation } = this.props;
// this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused); this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
} }
componentWillUnmount() { componentWillUnmount() {
@@ -49,19 +37,15 @@ class SearchPage extends React.PureComponent {
const { pushDrawerStack, setPlayerVisible, query, search } = this.props; const { pushDrawerStack, setPlayerVisible, query, search } = this.props;
pushDrawerStack(); pushDrawerStack();
setPlayerVisible(); setPlayerVisible();
NativeModules.Firebase.setCurrentScreen('Search').then(result => {
const searchQuery = query || this.getSearchQuery(); const searchQuery = query || this.getSearchQuery();
if (searchQuery && searchQuery.trim().length > 0) { if (searchQuery && searchQuery.trim().length > 0) {
this.setState({ this.setState({
currentQuery: searchQuery, currentQuery: searchQuery,
currentUri: isURIValid(searchQuery) ? normalizeURI(searchQuery) : null, currentUri: isURIValid(searchQuery) ? normalizeURI(searchQuery) : null,
claimSearchOptions: null, });
claimSearchRun: false, search(searchQuery);
showTagResult: false, }
});
search(searchQuery);
}
});
}; };
componentDidMount() { componentDidMount() {
@@ -95,95 +79,59 @@ class SearchPage extends React.PureComponent {
handleSearchSubmitted = keywords => { handleSearchSubmitted = keywords => {
const { search } = this.props; const { search } = this.props;
this.setState({ this.setState({ currentUri: isURIValid(keywords) ? normalizeURI(keywords) : null });
currentUri: isURIValid(keywords) ? normalizeURI(keywords) : null,
claimSearchOptions: null,
claimSearchRun: false,
showTagResult: false,
});
search(keywords); search(keywords);
}; };
listEmptyComponent = () => {
const { query } = this.props;
return (
<View style={searchStyle.noResults}>
<Text style={searchStyle.noResultsText}>
There are no results to display for <Text style={searchStyle.boldText}>{query}</Text>. Please try a different
search term.
</Text>
</View>
);
};
listHeaderComponent = showTagResult => {
const { navigation, claimSearch, claimSearchByQuery } = this.props;
const { currentUri } = this.state;
const query = this.getSearchQuery();
const canBeTag = query && query.trim().length > 0 && isURIValid(query);
if (canBeTag && !this.state.claimSearchRun) {
const options = {
any_tags: [query],
page: 1,
no_totals: true,
};
this.setState({ claimSearchOptions: options, claimSearchRun: true }, () => claimSearch(options));
}
if (this.state.claimSearchRun && this.state.claimSearchOptions) {
const claimSearchKey = createNormalizedClaimSearchKey(this.state.claimSearchOptions);
const claimSearchUris = claimSearchByQuery[claimSearchKey];
this.setState({ showTagResult: claimSearchUris && claimSearchUris.length > 0 });
}
return (
<View>
<FileListItem uri={currentUri} featuredResult style={searchStyle.featuredResultItem} navigation={navigation} />
{showTagResult && (
<TouchableOpacity style={searchStyle.tagResultItem} onPress={() => this.handleTagResultPressed(query)}>
<Text style={searchStyle.tagResultTitle}>#{query.toLowerCase()}</Text>
<Text style={searchStyle.tagResultDescription}>{__('Explore content for this tag')}</Text>
</TouchableOpacity>
)}
</View>
);
};
handleTagResultPressed = tag => {
const { navigation } = this.props;
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_TAG, key: `tagPage`, params: { tag: tag.toLowerCase() } });
};
render() { render() {
const { isSearching, navigation, query, uris, urisByQuery } = this.props; const { isSearching, navigation, query, uris, urisByQuery } = this.props;
return ( return (
<View style={searchStyle.container}> <View style={searchStyle.container}>
<UriBar value={query} navigation={navigation} onSearchSubmitted={this.handleSearchSubmitted} /> <UriBar value={query} navigation={navigation} onSearchSubmitted={this.handleSearchSubmitted} />
{isSearching && ( {isSearching && (
<View style={searchStyle.busyContainer}> <View style={searchStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.NextLbryGreen} style={searchStyle.loading} /> <ActivityIndicator size="large" color={Colors.NextLbryGreen} style={searchStyle.loading} />
</View> </View>
)} )}
<FlatList {!isSearching && (
extraData={this.state} <ScrollView
style={searchStyle.scrollContainer} style={searchStyle.scrollContainer}
contentContainerStyle={searchStyle.scrollPadding} contentContainerStyle={searchStyle.scrollPadding}
keyboardShouldPersistTaps={'handled'} keyboardShouldPersistTaps={'handled'}
data={uris} >
keyExtractor={(item, index) => item} {this.state.currentUri && (
initialNumToRender={10} <FileListItem
maxToRenderPerBatch={20} key={this.state.currentUri}
removeClippedSubviews uri={this.state.currentUri}
ListEmptyComponent={!isSearching ? this.listEmptyComponent() : null} featuredResult
ListHeaderComponent={this.state.currentUri ? this.listHeaderComponent(this.state.showTagResult) : null} style={searchStyle.featuredResultItem}
renderItem={({ item }) => ( navigation={navigation}
<FileListItem key={item} uri={item} style={searchStyle.resultItem} navigation={navigation} /> onPress={() => navigateToUri(navigation, this.state.currentUri)}
)} />
/> )}
{uris && uris.length
? uris.map(uri => (
<FileListItem
key={uri}
uri={uri}
style={searchStyle.resultItem}
navigation={navigation}
onPress={() => navigateToUri(navigation, uri)}
/>
))
: null}
{(!uris || uris.length === 0) && (
<View style={searchStyle.noResults}>
<Text style={searchStyle.noResultsText}>
There are no results to display for <Text style={searchStyle.boldText}>{query}</Text>. Please try a
different search term.
</Text>
</View>
)}
</ScrollView>
)}
<FloatingWalletBalance navigation={navigation} /> <FloatingWalletBalance navigation={navigation} />
</View> </View>
); );
Loaded 100 of 156 files, more files were not shown because too many files have changed in this diff. Show more