Compare commits

..
41 Commits
Author SHA1 Message Date
Akinwale Ariwodola a2c0851ac7 bumpversion 0.7.2 --> 0.7.3 2019-06-04 05:57:36 +01:00
Akinwale Ariwodola 7e136faea5 perform user authentication on first page of first run (#572)
* perform user authentication on first page of first run
* additional firebase events for first run
2019-06-04 05:56:45 +01:00
Akinwale Ariwodola 309b1e70e6 bumpversion 0.7.1 --> 0.7.2 2019-06-03 09:02:00 +01:00
Akinwale Ariwodola e2399c257d Merge pull request #566 from lbryio/custom-drawer-content
add custom drawer content to navigate to the topmost item in nested stacks
2019-06-03 08:14:21 +01:00
Akinwale Ariwodola c892b51ff8 add custom drawer content to navigate to the topmost item in nested stacks 2019-05-31 05:41:44 +01:00
Akinwale Ariwodola 8b3a0d22be bumpversion 0.7.0 --> 0.7.1 2019-05-29 18:04:42 +01:00
Akinwale Ariwodola f4fe9294f0 fix backspace in search uri bar 2019-05-29 17:45:14 +01:00
Akinwale Ariwodola 67a2b76e41 create progress bar component (#560) 2019-05-29 16:40:59 +01:00
Akinwale Ariwodola 499e406c5d Merge pull request #563 from lbryio/search-uri-bar-fix
fix typing in uri bar on search page
2019-05-29 16:40:22 +01:00
Akinwale Ariwodola 90ccf18fbf fix typing in uri bar on search page 2019-05-29 16:39:34 +01:00
Akinwale Ariwodola 7f57447e57 change the appearance of the uri bar input (#561)
* change the appearance of the uri bar input
* improve no search results display
2019-05-29 11:53:27 +01:00
Akinwale Ariwodola 10beb9935f change manual reward verification message 2019-05-28 20:41:57 +01:00
Akinwale Ariwodola 5fc2e1247b Set default account upon wallet sync restore (#556) 2019-05-28 19:26:53 +01:00
Akinwale Ariwodola 67d4e97582 add reveal password icon and more UI tweaks (#554)
* add reveal password icon and more UI tweaks
* navigation workaround. more UI updates and tweaks.
* update control colours. fix search.
* optimise launcher icon. file page style tweak.
* optimise media player buffer values
2019-05-28 16:00:15 +01:00
Akinwale Ariwodola abeadd858e sdk 0.37.2 update for release (#547) 2019-05-27 10:30:33 +01:00
Akinwale Ariwodola 5a737ce38d wait for user to complete email verification (#548)
* wait for user to complete email verification on first run
* add password strength meter. fix auth bugs in first run.
2019-05-23 22:11:52 +01:00
Akinwale Ariwodola 97f1b530b2 additional rewards page changes and new verification flow (#542) 2019-05-15 11:00:15 +01:00
Akinwale Ariwodola f1393ae707 Merge branch 'master' of https://github.com/lbryio/lbry-android 2019-05-03 19:32:39 +01:00
Akinwale Ariwodola 0c274617cb fix settings page background 2019-05-03 19:31:13 +01:00
Akinwale Ariwodola f33a8c3829 Merge pull request #538 from lbryio/rewards-rework
optimise display of rewards verification requirements
2019-05-03 12:27:00 +01:00
Akinwale Ariwodola c243645124 optimise display of rewards verification requirements 2019-05-03 12:21:56 +01:00
Akinwale Ariwodola 4655678481 Merge branch 'master' of https://github.com/lbryio/lbry-android 2019-05-03 11:58:08 +01:00
Akinwale Ariwodola cec8ddeeee change launcher icon. remove unused images. 2019-05-03 11:57:21 +01:00
Akinwale Ariwodola 8d987a02aa Merge pull request #537 from lbryio/quickstart
add quick start build instructions
2019-05-02 23:46:00 +01:00
Akinwale Ariwodola a6d87d570f add quick start build instructions 2019-05-02 23:41:22 +01:00
Akinwale Ariwodola f3b07be01f bumpversion 0.6.2 --> 0.7.0 2019-05-02 07:10:23 +01:00
Akinwale Ariwodola 07f23ba927 Channel page redesign (#528)
* channel page redesign changes
* add constants. change publisher thumbnail resize mode.
2019-05-02 07:07:26 +01:00
Akinwale Ariwodola 7a7e96388b Replace Mixpanel with Firebase (Google) analytics (#535)
* replace mixpanel with firebase analytics
* add encrypted google-services.json file
2019-05-02 07:06:42 +01:00
Akinwale Ariwodola 73d91f7268 Merge pull request #536 from lbryio/player-fullscreen-overlay-fix
fix transparent player background covering touchable items
2019-05-01 16:36:58 +01:00
Akinwale Ariwodola 6371296b28 fix transparent player background covering touchable items 2019-05-01 12:45:04 +01:00
Akinwale Ariwodola cdeadf9d6d update .gitignore 2019-05-01 12:29:32 +01:00
Akinwale Ariwodola c332acb2c1 Merge pull request #529 from lbryio/media-player-update
update react native video version
2019-04-29 21:10:08 +01:00
Akinwale Ariwodola 0d68f1a24b update react native video version 2019-04-29 21:07:58 +01:00
Akinwale Ariwodola 1666ea88fc File view tags (#527)
* display claim tags below description
2019-04-29 11:26:30 +01:00
Akinwale Ariwodola ff163a31bf sdk 0.36 updates (#526)
* add requirements to support sdk 0.36
* updates for sdk 0.36
2019-04-29 10:38:17 +01:00
Akinwale Ariwodola 73d469dc8d Explore page redesign (#518) 2019-04-24 15:31:44 +01:00
Akinwale Ariwodola d0226ab4cc Cross-device sync implementation (#505)
* first run updates for sync
* finish sync implementation and fix build for openssl 1.1.1b required for sdk
* fix openssl recipe and tweak build
* fix NativeModules import on wallet page
* display total wallet balance. fix dispatch prop.
* add pipeline status to README.md
* remove unused build recipes
* hide 'No, thanks' button during email new request
* bumpversion 0.6.0 --> 0.6.1
* move unclaimed reward amount to the left of floating wallet balance
* Upgrade to React Native 0.59.3 (#513)
* upgrade to react native 0.59.3
* add FOREGROUND_SERVICE permission for Android 9 Pie (target sdk 28)
* put android.permission.FOREGROUND_SERVICE permission directly in AndroidManifest
* allow cleartext traffic
* minor copy changes
* enable secure password input and auto account_unlock on startup
2019-04-22 13:42:47 +01:00
Akinwale Ariwodola 3d1b07f11c Merge pull request #517 from lbryio/rewards-rework
streamline reward summary
2019-04-19 05:41:55 +01:00
Akinwale Ariwodola f98d7c26dc streamline reward summary 2019-04-17 16:37:55 +01:00
YULIUS KURNIAWAN KRISTIANTO c5fca74e39 change io to com (#504)
* Update README.md
* Update issue_template.md
2019-04-05 15:54:56 +01:00
Akinwale Ariwodola f79ad3dabc Upgrade to React Native 0.59.3 (#513)
* upgrade to react native 0.59.3
* add FOREGROUND_SERVICE permission for Android 9 Pie (target sdk 28)
* put android.permission.FOREGROUND_SERVICE permission directly in AndroidManifest
* allow cleartext traffic
2019-04-05 09:13:35 +01:00
174 changed files with 7319 additions and 3163 deletions

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@ To make it possible for us to help you, please fill out below information carefu
Before reporting any issues, please make sure that you're using the latest version.
We are also available on live chat at https://chat.lbry.io
We are also available on live chat at https://chat.lbry.com
-->
+2
View File
@@ -10,4 +10,6 @@ src/main/assets/index.android.bundle.meta
.vagrant
lbry-android.keystore
p4a/pythonforandroid/bootstraps/lbry/build/templates/google-services.json
.gitsecret/keys/random_seed
+1
View File
@@ -1 +1,2 @@
lbry-android.keystore:
p4a/pythonforandroid/bootstraps/lbry/build/templates/google-services.json
+110
View File
@@ -0,0 +1,110 @@
### Introduction
If you would like to contribute to the Android app, but find the build documentation a little daunting, this guide lets you copy-paste your way to a successful APK build.
#### Estimated build time
25 - 40 minutes (depending on Internet connection speeds)
#### What do you need?
* A computer running Ubuntu 18.04
* Internet access to download modules and packages.
* At least 15GB of free disk space.
* Alternatively, Docker. You can skip steps 1 through 5 if you make use of the `lbry/android-base` Docker base image. Scroll down to Fast track if you would prefer to use Docker.
### Step 1 of 10
Install all the apt packages required by running the following commands. You can copy-paste directly to your terminal.
```
sudo dpkg --add-architecture i386
sudo apt-get -y update
sudo apt-get install -y curl ca-certificates software-properties-common gpg-agent wget
sudo add-apt-repository ppa:deadsnakes/ppa -y && \
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get -y update && apt-get -y install autoconf autogen automake libtool libffi-dev \
build-essential python3.7 python3.7-dev python3.7-venv python3-pip ccache git libncurses5:i386 libstdc++6:i386 \
libgtk2.0-0:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 libidn11:i386 python2.7 python2.7-dev \
python-pip openjdk-8-jdk unzip zlib1g-dev zlib1g:i386 m4 libc6-dev-i386 yarn gawk nodejs npm
```
### Step 2 of 10
Install a couple of packages using the Python package installer
```
sudo -H pip install --upgrade cython==0.28.1 setuptools
```
### Step 3 of 10
Install buildozer, a tool for creating the apk package using the python for android toolcahin.
```
git clone https://github.com/lbryio/buildozer.git
cd buildozer && python2.7 setup.py install && cd ..
```
### Step 4 of 10
The Android SDK needs to be setup for buildozer. This requires creating a few directories and downloading a number of files. Run the following commands to create the buildozer directory, download the required archives and extract them into their proper destination folders.
```
mkdir -p ~/.buildozer/android/platform
wget 'https://dl.google.com/android/android-sdk_r23-linux.tgz' -P ~/.buildozer/android/platform/ && \
wget 'https://dl.google.com/android/repository/platform-28_r06.zip' -P ~/.buildozer/android/platform/ && \
wget 'https://dl.google.com/android/repository/build-tools_r26.0.2-linux.zip' -P ~/.buildozer/android/platform/
tar -xvf ~/.buildozer/android/platform/android-sdk_r23-linux.tgz -C ~/.buildozer/android/platform/ && \
mv ~/.buildozer/android/platform/android-sdk-linux ~/.buildozer/android/platform/android-sdk-23 && \
unzip ~/.buildozer/android/platform/platform-28_r06.zip -d ~/.buildozer/android/platform/android-sdk-23/platforms && \
mv ~/.buildozer/android/platform/android-sdk-23/platforms/android-9 ~/.buildozer/android/platform/android-sdk-23/platforms/android-28 && \
mkdir -p ~/.buildozer/android/platform/android-sdk-23/build-tools && \
unzip ~/.buildozer/android/platform/build-tools_r26.0.2-linux.zip -d ~/.buildozer/android/platform/android-sdk-23/build-tools && \
mkdir -p ~/.buildozer/android/platform/android-sdk-23/licenses && \
echo $'\nd56f5187479451eabf01fb78af6dfcb131a6481e' > ~/.buildozer/android/platform/android-sdk-23/licenses/android-sdk-license
```
### Step 5 of 10
Install the react-native-cli npm package.
```
sudo npm install -g react-native-cli
```
### Step 6 of 10
Install the Crystax NDK which is required for building Python 3.7 for the mobile app, and a number of native C / C++ modules and packages used by the app. Run the following commands to download and extract the NDK.
```
wget 'https://www.crystax.net/download/crystax-ndk-10.3.2-linux-x86_64.tar.xz' -P ~/.buildozer/android/ && \
tar -xvf ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz -C ~/.buildozer/android/ && \
rm -rf ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9 && \
ln -s ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21 ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
```
### Step 7 of 10
Clone the lbryio/lbry-android git repository and create your buildozer.spec file. The provide buildozer.spec.sample contains defaults provided you followed steps 1 through 5 exactly as described. You can also customise the spec file if you want to.
```
git clone https://github.com/lbryio/lbry-android
cd lbry-android
cp buildozer.spec.sample buildozer.spec
```
### Step 8 of 10
Install the npm packages required for the app's React Native code.
```
cd app
npm install
cd ..
```
### Step 9 of 10
Copy a couple of required files from the repository for the build to be successful.
```
cp scripts/build-target-python.sh ~/.buildozer/android/crystax-ndk-10.3.2/build/tools/build-target-python.sh
cp scripts/mangled-glibc-syscalls.h ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21/arch-arm/usr/include/crystax/bionic/libc/include/sys/mangled-glibc-syscalls.h
```
### Step 10 of 10
If you made it this far, you're finally ready to build the package! You just have to run a single command to generate the APK.
```
buildozer android debug
```
### Fast Track
Install Docker and start a container using the `lbry/android-base` image, which is about 1.72GB in size. Run the following commands for Ubuntu and then follow steps 6 through 10 in the container's bash prompt.
```
sudo apt-get install docker-ce
docker run -it lbry/android-base:latest /bin/bash
```
**Protip:** You can also make use of Docker to run your builds on macOS or Windows.
+3 -3
View File
@@ -1,7 +1,7 @@
# LBRY Android
[![pipeline status](https://ci.lbry.tech/lbry/lbry-android/badges/master/pipeline.svg)](https://ci.lbry.tech/lbry/lbry-android/commits/master)
An Android browser and wallet for the [LBRY](https://lbry.io) network. This app bundles [lbrynet-daemon](https://github.com/lbryio/lbry) as a background service with a UI layer built with React Native. The APK is built using buildozer and the Gradle build tool.
An Android browser and wallet for the [LBRY](https://lbry.com) network. This app bundles [lbrynet-daemon](https://github.com/lbryio/lbry) as a background service with a UI layer built with React Native. The APK is built using buildozer and the Gradle build tool.
<img src="https://spee.ch/8/lbry-android.png" alt="LBRY Android Screenshot" width="384px" />
@@ -24,7 +24,7 @@ Contributions to this project are welcome, encouraged, and compensated. For more
This project is MIT licensed. For the full license, see [LICENSE](LICENSE).
## Security
We take security seriously. Please contact security@lbry.io regarding any security issues. Our PGP key is [here](https://keybase.io/lbry/key.asc) if you need it.
We take security seriously. Please contact security@lbry.com regarding any security issues. Our PGP key is [here](https://keybase.io/lbry/key.asc) if you need it.
## Contact
The primary contact for this project is [@akinwale](https://github.com/akinwale) (akinwale@lbry.io)
The primary contact for this project is [@akinwale](https://github.com/akinwale) (akinwale@lbry.com)
+2 -1
View File
@@ -1,6 +1,7 @@
{
"presets": ["react-native"],
"presets": ["module:metro-react-native-babel-preset"],
"plugins": [
"@babel/plugin-proposal-nullish-coalescing-operator",
["module-resolver", {
root: ["./src"],
}],
+2471 -1462
View File
File diff suppressed because it is too large. Load diff
+14 -10
View File
@@ -13,29 +13,33 @@
"lodash": ">=4.17.11",
"merge": ">=1.2.1",
"moment": "^2.22.1",
"react": "16.2.0",
"react-native": "0.55.3",
"react": "16.8.6",
"react-native": "0.59.3",
"@react-native-community/async-storage": "^1.2.2",
"react-native-country-picker-modal": "^0.6.2",
"react-native-exception-handler": "2.9.0",
"react-native-fast-image": "^5.0.3",
"rn-fetch-blob": "^0.10.15",
"react-native-gesture-handler": "^1.1.0",
"react-native-image-zoom-viewer": "^2.2.5",
"react-native-password-strength-meter": "^0.0.2",
"react-native-phone-input": "lbryio/react-native-phone-input",
"react-native-vector-icons": "^5.0.0",
"react-native-vector-icons": "^6.4.2",
"react-native-video": "lbryio/react-native-video#exoplayer-lbry-android",
"react-navigation": "^2.18.3",
"react-navigation-redux-helpers": "^2.0.9",
"react-navigation": "^3.11.0",
"react-navigation-redux-helpers": "^3.0.2",
"react-redux": "^5.0.3",
"redux": "^3.6.0",
"redux-logger": "3.0.6",
"redux-persist": "^4.8.0",
"redux-persist": "^4.10.2",
"redux-persist-filesystem-storage": "^1.3.2",
"redux-persist-transform-compress": "^4.2.0",
"redux-persist-transform-filter": "0.0.10",
"redux-thunk": "^2.2.0"
"redux-persist-transform-filter": "0.0.18",
"redux-thunk": "^2.3.0",
"rn-fetch-blob": "^0.10.15"
},
"devDependencies": {
"@babel/core": "^7.4.3",
"babel-preset-env": "^1.6.1",
"babel-preset-react-native": "5.0.2",
"babel-preset-stage-2": "^6.18.0",
"babel-plugin-module-resolver": "^3.1.1",
"flow-babel-webpack-plugin": "^1.1.1"
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 354 KiB

+33 -56
View File
@@ -2,6 +2,7 @@ import React from 'react';
import AboutPage from 'page/about';
import DiscoverPage from 'page/discover';
import DownloadsPage from 'page/downloads';
import DrawerContent from 'component/drawerContent';
import FilePage from 'page/file';
import FirstRunScreen from 'page/firstRun';
import RewardsPage from 'page/rewards';
@@ -11,32 +12,31 @@ import SettingsPage from 'page/settings';
import SplashScreen from 'page/splash';
import SubscriptionsPage from 'page/subscriptions';
import TransactionHistoryPage from 'page/transactionHistory';
import VerificationScreen from 'page/verification';
import WalletPage from 'page/wallet';
import SearchInput from 'component/searchInput';
import {
createDrawerNavigator,
createStackNavigator,
NavigationActions
} from 'react-navigation';
import {
addListener,
reduxifyNavigator,
createReduxContainer,
createReactNavigationReduxMiddleware,
createNavigationReducer
} from 'react-navigation-redux-helpers';
import { connect } from 'react-redux';
import {
AppState,
AsyncStorage,
BackHandler,
Linking,
NativeModules,
TextInput,
ToastAndroid
} from 'react-native';
import { doDeleteCompleteBlobs } from 'redux/actions/file';
import { selectDrawerStack } from 'redux/selectors/drawer';
import { SETTINGS, doDismissToast, doToast, selectToast } from 'lbry-redux';
import {
doGetSync,
doUserCheckEmailVerified,
doUserEmailVerify,
doUserEmailVerifyFailure,
@@ -48,6 +48,7 @@ import {
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { decode as atob } from 'base-64';
import { dispatchNavigateBack, dispatchNavigateToUri } from 'utils/helper';
import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors';
import Constants from 'constants';
import Icon from 'react-native-vector-icons/FontAwesome5';
@@ -99,46 +100,6 @@ discoverStack.navigationOptions = ({ navigation }) => {
};
};
const trendingStack = createStackNavigator({
Trending: {
screen: TrendingPage,
navigationOptions: ({ navigation }) => ({
title: 'Trending',
header: null
})
}
});
const myLbryStack = createStackNavigator({
Downloads: {
screen: DownloadsPage,
navigationOptions: ({ navigation }) => ({
title: 'Downloads',
header: null
})
}
});
const mySubscriptionsStack = createStackNavigator({
Subscriptions: {
screen: SubscriptionsPage,
navigationOptions: ({ navigation }) => ({
title: 'Subscriptions',
header: null
})
}
});
const rewardsStack = createStackNavigator({
Rewards: {
screen: RewardsPage,
navigationOptions: ({ navigation }) => ({
title: 'Rewards',
header: null
})
}
});
const walletStack = createStackNavigator({
Wallet: {
screen: WalletPage,
@@ -163,20 +124,20 @@ const drawer = createDrawerNavigator({
DiscoverStack: { screen: discoverStack, navigationOptions: {
title: 'Explore', drawerIcon: ({ tintColor }) => <Icon name="home" size={20} style={{ color: tintColor }} />
}},
TrendingStack: { screen: trendingStack, navigationOptions: {
TrendingStack: { screen: TrendingPage, navigationOptions: {
title: 'Trending', drawerIcon: ({ tintColor }) => <Icon name="fire" size={20} style={{ color: tintColor }} />
}},
MySubscriptionsStack: { screen: mySubscriptionsStack, navigationOptions: {
MySubscriptionsStack: { screen: SubscriptionsPage, navigationOptions: {
title: 'Subscriptions', drawerIcon: ({ tintColor }) => <Icon name="heart" solid={true} size={20} style={{ color: tintColor }} />
}},
WalletStack: { screen: walletStack, navigationOptions: {
title: 'Wallet', drawerIcon: ({ tintColor }) => <Icon name="wallet" size={20} style={{ color: tintColor }} />
}},
Rewards: { screen: rewardsStack, navigationOptions: {
Rewards: { screen: RewardsPage, navigationOptions: {
drawerIcon: ({ tintColor }) => <Icon name="award" size={20} style={{ color: tintColor }} />
}},
MyLBRYStack: { screen: myLbryStack, navigationOptions: {
title: 'Downloads', drawerIcon: ({ tintColor }) => <Icon name="folder" size={20} style={{ color: tintColor }} />
MyLBRYStack: { screen: DownloadsPage, navigationOptions: {
title: 'Library', drawerIcon: ({ tintColor }) => <Icon name="download" size={20} style={{ color: tintColor }} />
}},
Settings: { screen: SettingsPage, navigationOptions: {
drawerLockMode: 'locked-closed',
@@ -189,13 +150,14 @@ const drawer = createDrawerNavigator({
}, {
drawerWidth: 300,
headerMode: 'none',
contentComponent: DrawerContent,
contentOptions: {
activeTintColor: Colors.LbryGreen,
labelStyle: discoverStyle.menuText
}
});
export const AppNavigator = new createStackNavigator({
const mainStackNavigator = new createStackNavigator({
FirstRun: {
screen: FirstRunScreen,
navigationOptions: {
@@ -210,16 +172,25 @@ export const AppNavigator = new createStackNavigator({
},
Main: {
screen: drawer
},
Verification: {
screen: VerificationScreen,
navigationOptions: {
drawerLockMode: 'locked-closed'
}
}
}, {
headerMode: 'none'
});
export const AppNavigator = mainStackNavigator;
export const navigatorReducer = createNavigationReducer(AppNavigator);
export const reactNavigationMiddleware = createReactNavigationReduxMiddleware(
"root",
state => state.nav,
);
const App = reduxifyNavigator(AppNavigator, "root");
const App = createReduxContainer(mainStackNavigator);
const appMapStateToProps = (state) => ({
state: state.nav,
});
@@ -280,13 +251,20 @@ class AppWithNavigationState extends React.Component {
}
componentDidUpdate() {
const { user } = this.props;
const { dispatch, user } = this.props;
if (this.state.verifyPending && this.emailVerifyCheckInterval > 0 && user && user.has_verified_email) {
clearInterval(this.emailVerifyCheckInterval);
AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'false');
this.setState({ verifyPending: false });
ToastAndroid.show('Your email address was successfully verified.', ToastAndroid.LONG);
// upon successful email verification, do wallet sync (if password has been set)
NativeModules.UtilityModule.getSecureValue(Constants.KEY_FIRST_RUN_PASSWORD).then(walletPassword => {
if (walletPassword && walletPassword.trim().length > 0) {
dispatch(doGetSync(walletPassword));
}
});
}
}
@@ -327,6 +305,7 @@ class AppWithNavigationState extends React.Component {
if (!emailVerifyErrorMessage) {
AsyncStorage.removeItem(Constants.KEY_FIRST_RUN_EMAIL);
}
AsyncStorage.removeItem(Constants.KEY_SHOULD_VERIFY_EMAIL);
dispatch(doToast({ message }));
}
@@ -354,8 +333,6 @@ class AppWithNavigationState extends React.Component {
}
if (AppState.currentState && AppState.currentState.match(/active/)) {
// Cleanup blobs for completed files upon app resume to save space
dispatch(doDeleteCompleteBlobs());
if (backgroundPlayEnabled || NativeModules.BackgroundMedia) {
NativeModules.BackgroundMedia.hidePlaybackNotification();
}
+4
View File
@@ -0,0 +1,4 @@
import { connect } from 'react-redux';
import CategoryList from './view';
export default connect(null, null)(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;
+4 -1
View File
@@ -28,12 +28,15 @@ class CustomRewardCard extends React.PureComponent<Props> {
}
onClaimPress = () => {
const { canClaim, notify, submitRewardCode } = this.props;
const { canClaim, notify, showVerification, submitRewardCode } = this.props;
const { rewardCode } = this.state;
Keyboard.dismiss();
if (!canClaim) {
if (showVerification) {
showVerification();
}
notify({ message: 'Unfortunately, you are not eligible to claim this reward at this time.' });
return;
}
+2 -2
View File
@@ -1,9 +1,9 @@
import { connect } from 'react-redux';
import { doFetchBlock, makeSelectBlockDate } from 'lbry-redux';
import { makeSelectDateForUri } from 'lbry-redux';
import DateTime from './view';
const select = (state, props) => ({
date: !props.date && props.block ? makeSelectBlockDate(props.block)(state) : props.date,
date: props.date || makeSelectDateForUri(props.uri)(state),
});
const perform = dispatch => ({
+4
View File
@@ -0,0 +1,4 @@
import { connect } from 'react-redux';
import DrawerContent from './view';
export default connect()(DrawerContent);
+38
View File
@@ -0,0 +1,38 @@
import React from 'react';
import { DrawerItems, SafeAreaView } from 'react-navigation';
import { ScrollView } from 'react-native';
import Constants from 'constants';
import discoverStyle from 'styles/discover';
class DrawerContent extends React.PureComponent {
render() {
const props = this.props;
const { navigation, onItemPress } = props;
return (
<ScrollView>
<SafeAreaView style={discoverStyle.drawerContentContainer} forceInset={{ top: 'always', horizontal: 'never' }}>
<DrawerItems
{...props}
onItemPress={(route) => {
const { routeName } = route.route;
if (Constants.FULL_ROUTE_NAME_DISCOVER === routeName) {
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_DISCOVER });
return;
}
if (Constants.FULL_ROUTE_NAME_WALLET === routeName) {
navigation.navigate({ routeName: Constants.DRAWER_ROUTE_WALLET });
return;
}
onItemPress(route);
}}
/>
</SafeAreaView>
</ScrollView>
);
}
}
export default DrawerContent;
@@ -1,24 +0,0 @@
import { connect } from 'react-redux';
import {
doUserEmailNew,
doUserResendVerificationEmail,
selectEmailNewErrorMessage,
selectEmailNewIsPending,
selectEmailToVerify,
} from 'lbryinc';
import { doToast } from 'lbry-redux';
import EmailRewardSubcard from './view';
const select = state => ({
emailToVerify: selectEmailToVerify(state),
emailNewErrorMessage: selectEmailNewErrorMessage(state),
emailNewPending: selectEmailNewIsPending(state)
});
const perform = dispatch => ({
addUserEmail: email => dispatch(doUserEmailNew(email)),
notify: data => dispatch(doToast(data)),
resendVerificationEmail: email => dispatch(doUserResendVerificationEmail(email))
});
export default connect(select, perform)(EmailRewardSubcard);
@@ -1,105 +0,0 @@
// @flow
import React from 'react';
import {
ActivityIndicator,
AsyncStorage,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Button from '../button';
import Colors from '../../styles/colors';
import Constants from '../../constants';
import Link from '../link';
import rewardStyle from '../../styles/reward';
class EmailRewardSubcard extends React.PureComponent {
state = {
email: null,
emailAlreadySet: false,
previousEmail: null,
verfiyStarted: false
};
componentDidMount() {
const { emailToVerify } = this.props;
AsyncStorage.getItem(Constants.KEY_FIRST_RUN_EMAIL).then(email => {
if (email && email.trim().length > 0) {
this.setState({ email, emailAlreadySet: true, previousEmail: email });
} else {
this.setState({ email: emailToVerify, previousEmail: emailToVerify });
}
});
}
componentWillReceiveProps(nextProps) {
const { emailNewErrorMessage, emailNewPending } = nextProps;
const { notify } = this.props;
if (this.state.verifyStarted && !emailNewPending) {
if (emailNewErrorMessage) {
notify({ message: String(emailNewErrorMessage), isError: true });
this.setState({ verifyStarted: false });
} else {
notify({ message: 'Please follow the instructions in the email sent to your address to continue.' });
AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'true');
}
}
}
handleChangeText = (text) => {
// save the value to the state email
this.setState({ email: text });
AsyncStorage.setItem(Constants.KEY_FIRST_RUN_EMAIL, text);
}
onSendVerificationPressed = () => {
if (this.state.verifyStarted) {
return;
}
const { addUserEmail, notify, resendVerificationEmail } = this.props;
const { email } = this.state;
if (!email || email.trim().length === 0 || email.indexOf('@') === -1) {
return notify({
message: 'Please provide a valid email address to continue.',
});
}
this.setState({ verifyStarted: true });
if (this.state.emailAlreadySet && this.state.previousEmail === email) {
// resend verification email if there was one previously set (and it wasn't changed)
resendVerificationEmail(email);
AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'true');
notify({ message: 'Please follow the instructions in the email sent to your address to continue.' });
return;
}
addUserEmail(email);
}
render() {
const { emailNewPending } = this.props;
return (
<View style={rewardStyle.subcard}>
<Text style={rewardStyle.subtitle}>Pending action: Verify Email</Text>
<Text style={rewardStyle.subcardText}>Please provide an email address to verify. If you received a link previously, please follow the instructions in the email to complete verification.</Text>
<TextInput style={rewardStyle.subcardTextInput}
placeholder="you@example.com"
underlineColorAndroid="transparent"
value={this.state.email}
onChangeText={text => this.handleChangeText(text)} />
{!this.state.verifyStarted && <Button style={rewardStyle.actionButton}
text={"Send verification email"}
onPress={this.onSendVerificationPressed} />}
{this.state.verifyStarted && emailNewPending &&
<ActivityIndicator size={"small"} color={Colors.LbryGreen} style={rewardStyle.loading} />}
</View>
);
}
};
export default EmailRewardSubcard;
@@ -1,11 +1,12 @@
import { connect } from 'react-redux';
import {
doPurchaseUri,
makeSelectFileInfoForUri,
makeSelectDownloadingForUri,
makeSelectLoadingForUri,
} from 'lbry-redux';
import { doFetchCostInfoForUri, makeSelectCostInfoForUri } from 'lbryinc';
import { doPurchaseUri, doStartDownload } from 'redux/actions/file';
import { doStartDownload } from 'redux/actions/file';
import FileDownloadButton from './view';
const select = (state, props) => ({
@@ -16,7 +17,7 @@ const select = (state, props) => ({
});
const perform = dispatch => ({
purchaseUri: (uri, failureCallback) => dispatch(doPurchaseUri(uri, null, failureCallback)),
purchaseUri: (uri, costInfo, saveFile) => dispatch(doPurchaseUri(uri, costInfo, saveFile)),
restartDownload: (uri, outpoint) => dispatch(doStartDownload(uri, outpoint)),
fetchCostInfo: uri => dispatch(doFetchCostInfoForUri(uri)),
});
+9 -7
View File
@@ -1,7 +1,7 @@
import React from 'react';
import { NativeModules, Text, View, TouchableOpacity } from 'react-native';
import Button from '../button';
import fileDownloadButtonStyle from '../../styles/fileDownloadButton';
import fileDownloadButtonStyle from 'styles/fileDownloadButton';
class FileDownloadButton extends React.PureComponent {
componentDidMount() {
@@ -13,7 +13,7 @@ class FileDownloadButton extends React.PureComponent {
componentWillReceiveProps(nextProps) {
//this.checkAvailability(nextProps.uri);
this.restartDownload(nextProps);
//this.restartDownload(nextProps);
}
restartDownload(props) {
@@ -46,7 +46,6 @@ class FileDownloadButton extends React.PureComponent {
style,
openFile,
onButtonLayout,
onStartDownloadFailed
} = this.props;
if ((fileInfo && !fileInfo.stopped) || loading || downloading) {
@@ -60,7 +59,7 @@ class FileDownloadButton extends React.PureComponent {
<Text style={fileDownloadButtonStyle.text}>{label}</Text>
</View>
);
} else if (fileInfo === null && !downloading) {
} else if (!fileInfo && !downloading) {
if (!costInfo) {
return (
<View style={[style, fileDownloadButtonStyle.container]}>
@@ -73,10 +72,13 @@ class FileDownloadButton extends React.PureComponent {
text={(isPlayable ? 'Play' : (isViewable ? 'View' : 'Download'))}
onLayout={onButtonLayout}
style={[style, fileDownloadButtonStyle.container]} onPress={() => {
if (NativeModules.Mixpanel) {
NativeModules.Mixpanel.track('Purchase Uri', { Uri: uri });
if (NativeModules.Firebase) {
NativeModules.Firebase.track('purchase_uri', { uri: uri });
}
purchaseUri(uri, costInfo, !isPlayable);
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.checkDownloads();
}
purchaseUri(uri, onStartDownloadFailed);
if (isPlayable && onPlay) {
this.props.onPlay();
}
+8 -2
View File
@@ -4,10 +4,13 @@ import {
makeSelectClaimForUri,
makeSelectMetadataForUri,
makeSelectFileInfoForUri,
makeSelectThumbnailForUri,
makeSelectTitleForUri,
makeSelectIsUriResolving,
makeSelectClaimIsNsfw
} from 'lbry-redux';
import { selectRewardContentClaimIds } from 'lbryinc';
import { selectShowNsfw } from '../../redux/selectors/settings';
import { selectShowNsfw } from 'redux/selectors/settings';
import FileItem from './view';
const select = (state, props) => ({
@@ -16,7 +19,10 @@ const select = (state, props) => ({
metadata: makeSelectMetadataForUri(props.uri)(state),
rewardedContentClaimIds: selectRewardContentClaimIds(state, props),
isResolvingUri: makeSelectIsUriResolving(props.uri)(state),
obscureNsfw: !selectShowNsfw(state)
obscureNsfw: !selectShowNsfw(state),
thumbnail: makeSelectThumbnailForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
nsfw: makeSelectClaimIsNsfw(props.uri)(state),
});
const perform = dispatch => ({
+12 -9
View File
@@ -36,8 +36,8 @@ class FileItem extends React.PureComponent {
navigateToFileUri = () => {
const { navigation, uri } = this.props;
const normalizedUri = normalizeURI(uri);
if (NativeModules.Mixpanel) {
NativeModules.Mixpanel.track('Discover Tap', { Uri: normalizeURI });
if (NativeModules.Firebase) {
NativeModules.Firebase.track('explore_click', { uri: normalizedUri });
}
navigateToUri(navigation, normalizedUri);
}
@@ -45,6 +45,8 @@ class FileItem extends React.PureComponent {
render() {
const {
claim,
title,
thumbnail,
fileInfo,
metadata,
isResolvingUri,
@@ -58,8 +60,6 @@ class FileItem extends React.PureComponent {
} = this.props;
const uri = normalizeURI(this.props.uri);
const title = metadata && metadata.title ? metadata.title : uri;
const thumbnail = metadata && metadata.thumbnail ? metadata.thumbnail : null;
const obscureNsfw = this.props.obscureNsfw && metadata && metadata.nsfw;
const isRewardContent = claim && rewardedContentClaimIds.includes(claim.claim_id);
const channelName = claim ? claim.channel_name : null;
@@ -70,7 +70,7 @@ class FileItem extends React.PureComponent {
return (
<View style={style}>
<TouchableOpacity style={discoverStyle.container} onPress={this.navigateToFileUri}>
{!compactView && titleBeforeThumbnail && <Text style={[discoverStyle.fileItemName, discoverStyle.rewardTitle]}>{title}</Text>}
{!compactView && titleBeforeThumbnail && <Text numberOfLines={1} style={[discoverStyle.fileItemName, discoverStyle.rewardTitle]}>{title}</Text>}
<FileItemMedia title={title}
thumbnail={thumbnail}
blurRadius={obscureNsfw ? 15 : 0}
@@ -78,10 +78,13 @@ class FileItem extends React.PureComponent {
isResolvingUri={isResolvingUri}
style={mediaStyle} />
{!compactView && <FilePrice uri={uri} style={discoverStyle.filePriceContainer} textStyle={discoverStyle.filePriceText} />}
{(!compactView && fileInfo && fileInfo.completed && fileInfo.download_path) &&
<Icon style={discoverStyle.downloadedIcon} solid={true} color={Colors.NextLbryGreen} name={"folder"} size={16} />}
{(!compactView && (!fileInfo || !fileInfo.completed || !fileInfo.download_path)) &&
<FilePrice uri={uri} style={discoverStyle.filePriceContainer} textStyle={discoverStyle.filePriceText} />}
{!compactView && <View style={isRewardContent ? discoverStyle.rewardTitleContainer : null}>
<Text style={[discoverStyle.fileItemName, discoverStyle.rewardTitle]}>{title}</Text>
{isRewardContent && <Icon style={discoverStyle.rewardIcon} name="award" size={20} />}
<Text numberOfLines={1} style={[discoverStyle.fileItemName, discoverStyle.rewardTitle]}>{title}</Text>
{isRewardContent && <Icon style={discoverStyle.rewardIcon} name="award" size={14} />}
</View>}
{(!compactView && showDetails) &&
<View style={discoverStyle.detailsRow}>
@@ -89,7 +92,7 @@ class FileItem extends React.PureComponent {
<Link style={discoverStyle.channelName} text={channelName} onPress={() => {
navigateToUri(navigation, normalizeURI(fullChannelUri));
}} />}
<DateTime style={discoverStyle.dateTime} textStyle={discoverStyle.dateTimeText} timeAgo block={height} />
<DateTime style={discoverStyle.dateTime} textStyle={discoverStyle.dateTimeText} timeAgo uri={uri} />
</View>}
</TouchableOpacity>
{obscureNsfw && <NsfwOverlay onPress={() => navigation.navigate({ routeName: 'Settings', key: 'settingsPage' })} />}
+13 -1
View File
@@ -45,11 +45,23 @@ class FileItemMedia extends React.PureComponent {
}
}
isThumbnailValid = (thumbnail) => {
if (!thumbnail || ((typeof thumbnail) !== 'string')) {
return false;
}
if (thumbnail.substring(0, 7) != 'http://' && thumbnail.substring(0, 8) != 'https://') {
return false;
}
return true;
}
render() {
let style = this.props.style;
const { blurRadius, isResolvingUri, thumbnail, title, resizeMode } = this.props;
const atStyle = this.state.autoThumbStyle;
if (thumbnail && ((typeof thumbnail) === 'string') && !this.state.imageLoadFailed) {
if (this.isThumbnailValid(thumbnail) && !this.state.imageLoadFailed) {
if (style == null) {
style = fileItemMediaStyle.thumbnail;
}
+2 -2
View File
@@ -3,7 +3,7 @@ import * as React from 'react';
import { buildURI } from 'lbry-redux';
import { FlatList } from 'react-native';
import FileItem from 'component/fileItem';
import discoverStyle from 'styles/discover';
import fileListStyle from 'styles/fileList';
// In the future, all Flow types need to be specified in a common source (lbry-redux, perhaps?)
type FileInfo = {
@@ -183,7 +183,7 @@ class FileList extends React.PureComponent<Props, State> {
onEndReached={onEndReached}
keyExtractor={(item, index) => item}
renderItem={({item}) => (
<FileItem style={discoverStyle.fileItem}
<FileItem style={fileListStyle.fileItem}
uri={item}
navigation={navigation}
showDetails={true}
+5 -1
View File
@@ -5,6 +5,8 @@ import {
makeSelectMetadataForUri,
makeSelectFileInfoForUri,
makeSelectIsUriResolving,
makeSelectTitleForUri,
makeSelectThumbnailForUri,
} from 'lbry-redux';
import { selectShowNsfw } from 'redux/selectors/settings';
import FileListItem from './view';
@@ -15,7 +17,9 @@ const select = (state, props) => ({
isDownloaded: !!makeSelectFileInfoForUri(props.uri)(state),
metadata: makeSelectMetadataForUri(props.uri)(state),
isResolvingUri: makeSelectIsUriResolving(props.uri)(state),
obscureNsfw: !selectShowNsfw(state)
obscureNsfw: !selectShowNsfw(state),
title: makeSelectTitleForUri(props.uri)(state),
thumbnail: makeSelectThumbnailForUri(props.uri)(state),
});
const perform = dispatch => ({
+18 -11
View File
@@ -3,7 +3,6 @@ import { normalizeURI, parseURI } from 'lbry-redux';
import {
ActivityIndicator,
Platform,
ProgressBarAndroid,
Text,
TouchableOpacity,
View
@@ -12,8 +11,10 @@ import { navigateToUri, formatBytes } from 'utils/helper';
import Colors from 'styles/colors';
import DateTime from 'component/dateTime';
import FileItemMedia from 'component/fileItemMedia';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Link from 'component/link';
import NsfwOverlay from 'component/nsfwOverlay';
import ProgressBar from 'component/progressBar';
import fileListStyle from 'styles/fileList';
class FileListItem extends React.PureComponent {
@@ -56,13 +57,14 @@ class FileListItem extends React.PureComponent {
isDownloaded,
style,
onPress,
navigation
navigation,
thumbnail,
title
} = this.props;
const uri = normalizeURI(this.props.uri);
const obscureNsfw = this.props.obscureNsfw && metadata && metadata.nsfw;
const isResolving = !fileInfo && isResolvingUri;
const title = fileInfo ? fileInfo.metadata.title : metadata && metadata.title ? metadata.title : parseURI(uri).contentName;
let name, channel, height, channelClaimId, fullChannelUri;
if (claim) {
@@ -84,7 +86,9 @@ class FileListItem extends React.PureComponent {
blurRadius={obscureNsfw ? 15 : 0}
resizeMode="cover"
title={(title || name)}
thumbnail={metadata ? metadata.thumbnail : null} />
thumbnail={thumbnail} />
{(fileInfo && fileInfo.completed && fileInfo.download_path) &&
<Icon style={fileListStyle.downloadedIcon} solid={true} color={Colors.NextLbryGreen} name={"folder"} size={16} />}
<View style={fileListStyle.detailsContainer}>
{featuredResult && <Text style={fileListStyle.featuredUri} numberOfLines={1}>{uri}</Text>}
@@ -103,17 +107,20 @@ class FileListItem extends React.PureComponent {
}} />}
<View style={fileListStyle.info}>
{fileInfo && <Text style={fileListStyle.infoText}>{this.getStorageForFileInfo(fileInfo)}</Text>}
<DateTime style={fileListStyle.publishInfo} textStyle={fileListStyle.infoText} timeAgo block={height} />
{(fileInfo && !isNaN(fileInfo.written_bytes) && fileInfo.written_bytes > 0) &&
<Text style={fileListStyle.infoText}>{this.getStorageForFileInfo(fileInfo)}</Text>}
<DateTime style={fileListStyle.publishInfo} textStyle={fileListStyle.infoText} timeAgo uri={uri} />
</View>
{fileInfo &&
{(fileInfo && fileInfo.download_path) &&
<View style={fileListStyle.downloadInfo}>
{!fileInfo.completed &&
<View style={fileListStyle.progress}>
<View style={[fileListStyle.progressCompleted, { flex: this.getDownloadProgress(fileInfo) } ]} />
<View style={[fileListStyle.progressRemaining, { flex: (100 - this.getDownloadProgress(fileInfo)) } ]} />
</View>}
<ProgressBar
borderRadius={3}
color={Colors.NextLbryGreen}
height={3}
style={fileListStyle.progress}
progress={this.getDownloadProgress(fileInfo)} />}
</View>
}
</View>
+1 -1
View File
@@ -108,7 +108,7 @@ class FilePrice extends React.PureComponent {
<CreditAmount
style={textStyle}
label={false}
amount={costInfo.cost}
amount={parseFloat(costInfo.cost)}
isEstimate={isEstimate}
showFree
showFullPrice={showFullPrice}>???</CreditAmount>
@@ -0,0 +1,4 @@
import { connect } from 'react-redux';
import FileRewardsDriver from './view';
export default connect()(FileRewardsDriver);
@@ -0,0 +1,20 @@
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import Colors from 'styles/colors';
import Icon from 'react-native-vector-icons/FontAwesome5';
import filePageStyle from 'styles/filePage';
class FileRewardsDriver extends React.PureComponent<Props> {
render() {
const { navigation } = this.props;
return (
<TouchableOpacity style={filePageStyle.rewardDriverCard} onPress={() => navigation.navigate('Rewards')}>
<Icon name="award" size={16} style={filePageStyle.rewardIcon} />
<Text style={filePageStyle.rewardDriverText}>Earn some credits to access this content.</Text>
</TouchableOpacity>
);
}
}
export default FileRewardsDriver;
@@ -1,11 +1,14 @@
import { connect } from 'react-redux';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { selectBalance } from 'lbry-redux';
import { selectUnclaimedRewardValue } from 'lbryinc';
import Constants from 'constants';
import FloatingWalletBalance from './view';
import { doRewardList, selectUnclaimedRewardValue, selectFetchingRewards, selectUser } from 'lbryinc';
const select = state => ({
balance: selectBalance(state),
unclaimedRewardAmount: selectUnclaimedRewardValue(state),
rewardsNotInterested: makeSelectClientSetting(Constants.SETTING_REWARDS_NOT_INTERESTED)(state),
});
export default connect(select, null)(FloatingWalletBalance);
@@ -14,11 +14,11 @@ type Props = {
class FloatingWalletBalance extends React.PureComponent<Props> {
render() {
const { balance, navigation, unclaimedRewardAmount } = this.props;
const { balance, navigation, rewardsNotInterested, unclaimedRewardAmount } = this.props;
return (
<View style={[floatingButtonStyle.view, floatingButtonStyle.bottomRight]}>
{unclaimedRewardAmount > 0 &&
{(!rewardsNotInterested && unclaimedRewardAmount > 0) &&
<TouchableOpacity style={floatingButtonStyle.pendingContainer}
onPress={() => navigation && navigation.navigate({ routeName: 'Rewards' })} >
<Icon name="award" size={18} style={floatingButtonStyle.rewardIcon} />
@@ -27,9 +27,8 @@ class FloatingWalletBalance extends React.PureComponent<Props> {
<TouchableOpacity style={floatingButtonStyle.container}
onPress={() => navigation && navigation.navigate({ routeName: 'WalletStack' })}>
{isNaN(balance) && <ActivityIndicator size="small" color={Colors.White} />}
<Text style={floatingButtonStyle.text}>
{(balance || balance === 0) && (formatCredits(parseFloat(balance), 2) + ' LBC')}
</Text>
{(!isNaN(balance) || balance === 0) && (
<Text style={floatingButtonStyle.text}>{(formatCredits(parseFloat(balance), 2) + ' LBC')}</Text>)}
</TouchableOpacity>
</View>
);
+5 -1
View File
@@ -1,14 +1,18 @@
import { connect } from 'react-redux';
import { SETTINGS, savePosition } from 'lbry-redux';
import { makeSelectClientSetting } from '../../redux/selectors/settings';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { doSetPlayerVisible } from 'redux/actions/drawer';
import { selectIsPlayerVisible } from 'redux/selectors/drawer';
import MediaPlayer from './view';
const select = state => ({
backgroundPlayEnabled: makeSelectClientSetting(SETTINGS.BACKGROUND_PLAY_ENABLED)(state),
isPlayerVisible: selectIsPlayerVisible(state),
});
const perform = dispatch => ({
savePosition: (claimId, outpoint, position) => dispatch(savePosition(claimId, outpoint, position)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(true)),
});
export default connect(select, perform)(MediaPlayer);
+90 -29
View File
@@ -1,6 +1,8 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
AppState,
ActivityIndicator,
DeviceEventEmitter,
NativeModules,
PanResponder,
@@ -9,12 +11,15 @@ import {
ScrollView,
TouchableOpacity
} from 'react-native';
import Colors from 'styles/colors';
import FastImage from 'react-native-fast-image'
import Video from 'react-native-video';
import Icon from 'react-native-vector-icons/FontAwesome5';
import FileItemMedia from 'component/fileItemMedia';
import mediaPlayerStyle from 'styles/mediaPlayer';
const positionSaveInterval = 10
class MediaPlayer extends React.PureComponent {
static ControlsTimeout = 3000;
@@ -31,7 +36,9 @@ class MediaPlayer extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
encodedFilePath: null,
buffering: false,
backgroundPlayEnabled: false,
autoPaused: false,
rate: 1,
volume: 1,
muted: false,
@@ -85,6 +92,7 @@ class MediaPlayer extends React.PureComponent {
const { position } = this.props;
if (!isNaN(parseFloat(position)) && position > 0) {
this.video.seek(position);
this.setState({ currentTime: position }, () => this.setSeekerPosition(this.calculateSeekerPosition()));
}
if (this.props.onMediaLoaded) {
@@ -93,10 +101,13 @@ class MediaPlayer extends React.PureComponent {
}
onProgress = (data) => {
const { savePosition, fileInfo } = this.props;
const { savePosition, claim } = this.props;
this.setState({ currentTime: data.currentTime }, () => savePosition(fileInfo.claim_id, fileInfo.outpoint, data.currentTime));
this.setState({ buffering: false, currentTime: data.currentTime });
if (data.currentTime > 0 && Math.floor(data.currentTime) % positionSaveInterval === 0) {
const { claim_id: claimId, txid, nout } = claim;
savePosition(claimId, `${txid}:${nout}`, data.currentTime);
}
if (!this.state.seeking) {
this.setSeekerPosition(this.calculateSeekerPosition());
@@ -140,6 +151,11 @@ class MediaPlayer extends React.PureComponent {
}
togglePlayerControls = () => {
const { setPlayerVisible, isPlayerVisible } = this.props;
if (!isPlayerVisible) {
setPlayerVisible();
}
if (this.state.areControlsVisible) {
this.manualHidePlayerControls();
} else {
@@ -149,7 +165,14 @@ class MediaPlayer extends React.PureComponent {
togglePlay = () => {
this.showPlayerControls();
this.setState({ paused: !this.state.paused });
this.setState({ paused: !this.state.paused }, this.handlePausedState);
}
handlePausedState = () => {
if (!this.state.paused) {
// onProgress will automatically clear this, so it's fine
this.setState({ buffering: true });
}
}
toggleFullscreenMode = () => {
@@ -217,7 +240,7 @@ class MediaPlayer extends React.PureComponent {
onPanResponderRelease: (evt, gestureState) => {
const time = this.getCurrentTimeForSeekerPosition();
if (time >= this.state.duration) {
this.setState({ paused: true });
this.setState({ paused: true }, this.handlePausedState);
this.onEnd();
} else {
this.seekTo(time);
@@ -251,18 +274,29 @@ class MediaPlayer extends React.PureComponent {
this.initSeeker();
}
componentWillReceiveProps(nextProps) {
const { isPlayerVisible } = nextProps;
if (!isPlayerVisible && !this.state.backgroundPlayEnabled) {
// force pause if the player is not visible and background play is not enabled
this.setState({ paused: true });
}
}
componentDidMount() {
const { assignPlayer } = this.props;
const { assignPlayer, backgroundPlayEnabled } = this.props;
if (assignPlayer) {
assignPlayer(this);
}
this.setState({ backgroundPlayEnabled: !!backgroundPlayEnabled });
this.setSeekerPosition(this.calculateSeekerPosition());
AppState.addEventListener('change', this.handleAppStateChange);
DeviceEventEmitter.addListener('onBackgroundPlayPressed', this.play);
DeviceEventEmitter.addListener('onBackgroundPausePressed', this.pause);
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
DeviceEventEmitter.removeListener('onBackgroundPlayPressed', this.play);
DeviceEventEmitter.removeListener('onBackgroundPausePressed', this.pause);
this.clearControlsTimeout();
@@ -273,6 +307,26 @@ class MediaPlayer extends React.PureComponent {
}
}
handleAppStateChange = () => {
if (AppState.currentState && AppState.currentState.match(/inactive|background/)) {
if (!this.state.backgroundPlayEnabled && !this.state.paused) {
this.setState({ paused: true, autoPaused: true });
}
}
if (AppState.currentState && AppState.currentState.match(/active/)) {
if (!this.state.backgroundPlayEnabled && this.state.autoPaused) {
this.setState({ paused: false, autoPaused: false });
}
}
}
onBuffer = () => {
if (!this.state.paused) {
this.setState({ buffering: true }, () => this.manualHidePlayerControls());
}
}
play = () => {
this.setState({ paused: false }, this.updateBackgroundMediaNotification);
}
@@ -282,6 +336,7 @@ class MediaPlayer extends React.PureComponent {
}
updateBackgroundMediaNotification = () => {
this.handlePausedState();
const { backgroundPlayEnabled } = this.props;
if (backgroundPlayEnabled) {
if (NativeModules.BackgroundMedia && window.currentMediaInfo) {
@@ -292,13 +347,19 @@ class MediaPlayer extends React.PureComponent {
}
renderPlayerControls() {
const { onBackButtonPressed } = this.props;
if (this.state.areControlsVisible) {
return (
<View style={mediaPlayerStyle.playerControlsContainer}>
<TouchableOpacity style={mediaPlayerStyle.backButton} onPress={onBackButtonPressed}>
<Icon name={"arrow-left"} size={18} style={mediaPlayerStyle.backButtonIcon} />
</TouchableOpacity>
<TouchableOpacity style={mediaPlayerStyle.playPauseButton}
onPress={this.togglePlay}>
{this.state.paused && <Icon name="play" size={32} color="#ffffff" />}
{!this.state.paused && <Icon name="pause" size={32} color="#ffffff" />}
{this.state.paused && <Icon name="play" size={40} color="#ffffff" />}
{!this.state.paused && <Icon name="pause" size={40} color="#ffffff" />}
</TouchableOpacity>
<TouchableOpacity style={mediaPlayerStyle.toggleFullscreenButton} onPress={this.toggleFullscreenMode}>
@@ -315,18 +376,6 @@ class MediaPlayer extends React.PureComponent {
return null;
}
getEncodedDownloadPath = (fileInfo) => {
if (this.state.encodedFilePath) {
return this.state.encodedFilePath;
}
const { file_name: fileName } = fileInfo;
const encodedFileName = encodeURIComponent(fileName).replace(/!/g, '%21');
const encodedFilePath = fileInfo.download_path.replace(fileName, encodedFileName);
this.setState({ encodedFilePath });
return encodedFilePath;
}
onSeekerTouchAreaPressed = (evt) => {
if (evt && evt.nativeEvent) {
const newSeekerPosition = evt.nativeEvent.locationX;
@@ -338,8 +387,14 @@ class MediaPlayer extends React.PureComponent {
}
}
onTrackingLayout = (evt) => {
this.trackingOffset = evt.nativeEvent.layout.x;
this.seekerWidth = evt.nativeEvent.layout.width;
this.setSeekerPosition(this.calculateSeekerPosition());
}
render() {
const { backgroundPlayEnabled, fileInfo, thumbnail, onLayout, style } = this.props;
const { onLayout, source, style, thumbnail } = this.props;
const completedWidth = this.getCurrentTimePercentage() * this.seekerWidth;
const remainingWidth = this.seekerWidth - completedWidth;
let styles = [this.state.fullscreenMode ? mediaPlayerStyle.fullscreenContainer : mediaPlayerStyle.container];
@@ -356,20 +411,24 @@ class MediaPlayer extends React.PureComponent {
return (
<View style={styles} onLayout={onLayout}>
<Video source={{ uri: 'file:///' + this.getEncodedDownloadPath(fileInfo) }}
<Video source={{ uri: source }}
bufferConfig={{ minBufferMs: 15000, maxBufferMs: 60000, bufferForPlaybackMs: 5000, bufferForPlaybackAfterRebufferMs: 5000 }}
ref={(ref: Video) => { this.video = ref; }}
resizeMode={this.state.resizeMode}
playInBackground={backgroundPlayEnabled}
playInBackground={this.state.backgroundPlayEnabled}
style={mediaPlayerStyle.player}
rate={this.state.rate}
volume={this.state.volume}
paused={this.state.paused}
onLoad={this.onLoad}
onBuffer={this.onBuffer}
onProgress={this.onProgress}
onEnd={this.onEnd}
onError={this.onError}
minLoadRetryCount={999}
/>
{this.state.firstPlay && thumbnail &&
{this.state.firstPlay && thumbnail && thumbnail.trim().length > 0 &&
<FastImage
source={{uri: thumbnail}}
resizeMode={FastImage.resizeMode.cover}
@@ -381,16 +440,18 @@ class MediaPlayer extends React.PureComponent {
</TouchableOpacity>
{(!this.state.fullscreenMode || (this.state.fullscreenMode && this.state.areControlsVisible)) &&
<View style={trackingStyle} onLayout={(evt) => {
this.trackingOffset = evt.nativeEvent.layout.x;
this.seekerWidth = evt.nativeEvent.layout.width;
}}>
<View style={trackingStyle} onLayout={this.onTrackingLayout}>
<View style={mediaPlayerStyle.progress}>
<View style={[mediaPlayerStyle.innerProgressCompleted, { width: completedWidth }]} />
<View style={[mediaPlayerStyle.innerProgressRemaining, { width: remainingWidth }]} />
</View>
</View>}
{this.state.buffering &&
<View style={mediaPlayerStyle.loadingContainer}>
<ActivityIndicator color={Colors.LbryGreen} size="large" />
</View>}
{this.state.areControlsVisible &&
<View style={{ left: this.getTrackingOffset(), width: this.seekerWidth }}>
<View style={[mediaPlayerStyle.seekerHandle,
+2 -2
View File
@@ -9,8 +9,8 @@ import {
View
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome5';
import NavigationButton from '../navigationButton';
import pageHeaderStyle from '../../styles/pageHeader';
import NavigationButton from 'component/navigationButton';
import pageHeaderStyle from 'styles/pageHeader';
const APPBAR_HEIGHT = Platform.OS === 'ios' ? 44 : 56;
const AnimatedText = Animated.Text;
@@ -1,28 +0,0 @@
import { connect } from 'react-redux';
import { doToast } from 'lbry-redux';
import {
doUserPhoneNew,
doUserPhoneVerify,
selectPhoneNewErrorMessage,
selectPhoneNewIsPending,
selectPhoneToVerify,
selectPhoneVerifyIsPending,
selectPhoneVerifyErrorMessage
} from 'lbryinc';
import PhoneNumberRewardSubcard from './view';
const select = state => ({
phoneVerifyErrorMessage: selectPhoneVerifyErrorMessage(state),
phoneVerifyIsPending: selectPhoneVerifyIsPending(state),
phone: selectPhoneToVerify(state),
phoneNewErrorMessage: selectPhoneNewErrorMessage(state),
phoneNewIsPending: selectPhoneNewIsPending(state),
});
const perform = dispatch => ({
addUserPhone: (phone, country_code) => dispatch(doUserPhoneNew(phone, country_code)),
verifyPhone: (verificationCode) => dispatch(doUserPhoneVerify(verificationCode)),
notify: data => dispatch(doToast(data)),
});
export default connect(select, perform)(PhoneNumberRewardSubcard);
+4
View File
@@ -0,0 +1,4 @@
import { connect } from 'react-redux';
import ProgressBar from './view';
export default connect()(ProgressBar);
+54
View File
@@ -0,0 +1,54 @@
// @flow
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
const defaultHeight = 5;
const defaultBorderRadius = 5;
const minProgress = 0;
const maxProgress = 100;
class ProgressBar extends React.PureComponent {
static propTypes = {
borderRadius: PropTypes.number,
color: PropTypes.string.isRequired,
height: PropTypes.number,
progress: function(props, propName, componentName) {
const value = parseInt(props[propName], 10);
if (isNaN(value) || props[propName] < minProgress || props[propName] > maxProgress) {
return new Error('progress should be between 0 and 100');
}
},
style: PropTypes.any
};
render() {
const { borderRadius, color, height, progress, style } = this.props;
const currentProgress = Math.ceil(progress);
let styles = [];
if (style) {
if (style.length) {
styles = styles.concat(style);
} else {
styles.push(style);
}
}
styles.push({
borderRadius: borderRadius || defaultBorderRadius,
flexDirection: 'row',
height: height || defaultHeight,
overflow: 'hidden'
});
return (
<View style={styles}>
<View style={{ backgroundColor: color, borderRadius: borderRadius || defaultBorderRadius, flex: currentProgress }} />
<View style={{ backgroundColor: color, opacity: 0.2, flex: (100 - currentProgress) }} />
</View>
);
}
}
export default ProgressBar;
@@ -3,6 +3,7 @@ import {
makeSelectClaimForUri,
doSearch,
makeSelectRecommendedContentForUri,
makeSelectTitleForUri,
selectIsSearching,
} from 'lbry-redux';
import RelatedContent from './view';
@@ -10,6 +11,7 @@ import RelatedContent from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
recommendedContent: makeSelectRecommendedContentForUri(props.uri)(state),
title: makeSelectTitleForUri(props.uri)(state),
isSearching: selectIsSearching(state),
});
+2 -3
View File
@@ -30,10 +30,9 @@ export default class RelatedContent extends React.PureComponent<Props> {
}
getRecommendedContent() {
const { claim, search } = this.props;
const { search, title } = this.props;
if (claim && claim.value && claim.value.stream && claim.value.stream.metadata) {
const { title } = claim.value.stream.metadata;
if (title) {
search(title);
this.didSearch = true;
}
+7 -3
View File
@@ -44,10 +44,14 @@ class RewardCard extends React.PureComponent<Props> {
canClaim,
claimReward,
notify,
reward
reward,
showVerification
} = this.props;
if (!canClaim) {
if (showVerification) {
showVerification();
}
notify({ message: 'Unfortunately, you are not eligible to claim this reward at this time.' });
return;
}
@@ -73,9 +77,9 @@ class RewardCard extends React.PureComponent<Props> {
this.onClaimPress();
}
}}>
<Icon name={claimed ? "check-circle" : "circle"}
{claimed && <Icon name={claimed ? "check-circle" : "circle"}
style={claimed ? rewardStyle.claimed : (canClaim ? rewardStyle.unclaimed : rewardStyle.disabled)}
size={20} />
size={20} />}
</TouchableOpacity>}
{isPending && <ActivityIndicator size="small" color={Colors.LbryGreen} />}
</View>
@@ -0,0 +1,19 @@
import { connect } from 'react-redux';
import { doToast } from 'lbry-redux';
import { doSetClientSetting } from 'redux/actions/settings';
import { doRewardList, selectUnclaimedRewardValue, selectFetchingRewards, selectUser } from 'lbryinc';
import RewardEnrolment 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)),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
});
export default connect(select, perform)(RewardEnrolment);
+53
View File
@@ -0,0 +1,53 @@
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 Constants from 'constants';
import Link from 'component/link';
import Colors from 'styles/colors';
import Icon from 'react-native-vector-icons/FontAwesome5';
import rewardStyle from 'styles/reward';
class RewardEnrolment extends React.Component {
componentDidMount() {
this.props.fetchRewards();
}
onNotInterestedPressed = () => {
const { navigation, setClientSetting } = this.props;
setClientSetting(Constants.SETTING_REWARDS_NOT_INTERESTED, true);
navigation.navigate({ routeName: 'DiscoverStack' });
}
onEnrollPressed = () => {
const { navigation } = this.props;
navigation.navigate({ routeName: 'Verification', key: 'verification', params: { syncFlow: false }});
}
render() {
const { fetching, navigation, unclaimedRewardAmount, user } = this.props;
return (
<View style={rewardStyle.enrollContainer} onPress>
<View style={rewardStyle.summaryRow}>
<Icon name="award" size={36} color={Colors.White} />
<Text style={rewardStyle.summaryText}>
{unclaimedRewardAmount} unclaimed credits
</Text>
</View>
<View style={rewardStyle.onboarding}>
<Text style={rewardStyle.enrollDescText}>LBRY credits allow you to purchase content, publish content, and influence the network. You can start earning credits by watching videos on LBRY.</Text>
</View>
<View style={rewardStyle.buttonRow}>
<Link style={rewardStyle.notInterestedLink} text={"Not interested"} onPress={this.onNotInterestedPressed} />
<Button style={rewardStyle.enrollButton} theme={"light"} text={"Enroll"} onPress={this.onEnrollPressed} />
</View>
</View>
);
}
}
export default RewardEnrolment;
+21 -8
View File
@@ -1,7 +1,10 @@
import React from 'react';
import { AsyncStorage, NativeModules, Text, TouchableOpacity, View } from 'react-native';
import Button from '../../component/button';
import rewardStyle from '../../styles/reward';
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';
@@ -41,6 +44,13 @@ class RewardSummary extends React.Component {
});
}
handleSummaryPressed = () => {
const { showVerification } = this.props;
if (showVerification) {
showVerification();
}
}
render() {
const { fetching, navigation, unclaimedRewardAmount, user } = this.props;
@@ -56,12 +66,15 @@ class RewardSummary extends React.Component {
}
return (
<View style={rewardStyle.summaryContainer}>
<Text style={rewardStyle.summaryText}>
You have {unclaimedRewardAmount} LBC in unclaimed rewards. LBC stands for LBRY Credits which are tokens that you can use in the digital marketplace. You have {this.state.actionsLeft} action{this.state.actionsLeft === 1 ? '' : 's'} left to claim your first reward.
</Text>
<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} />
</View>
</TouchableOpacity>
);
}
}
+2 -2
View File
@@ -5,8 +5,8 @@ import SearchInput from './view';
const perform = dispatch => ({
search: search => {
if (NativeModules.Mixpanel) {
NativeModules.Mixpanel.track('Search', { Query: search });
if (NativeModules.Firebase) {
NativeModules.Firebase.track('search', { query: search });
}
return dispatch(doSearch(search));
},
@@ -66,6 +66,10 @@ class StorageStatsCard extends React.PureComponent {
}
render() {
if (this.state.totalBytes == 0) {
return null;
}
return (
<View style={storageStatsStyle.card}>
<View style={[storageStatsStyle.row, storageStatsStyle.totalSizeContainer]}>
+2 -2
View File
@@ -25,14 +25,14 @@ class SubscribeButton extends React.PureComponent {
const iconColor = isSubscribed ? null : Colors.Red;
const subscriptionHandler = isSubscribed ? doChannelUnsubscribe : doChannelSubscribe;
const subscriptionLabel = isSubscribed ? __('Unsubscribe') : __('Subscribe');
const subscriptionLabel = isSubscribed ? null : __('Subscribe');
const { claimName } = parseURI(uri);
return (
<Button
style={styles}
theme={"light"}
icon={"heart"}
icon={isSubscribed ? "heart-broken" : "heart"}
iconColor={iconColor}
solid={isSubscribed ? false : true}
text={subscriptionLabel}
+10 -2
View File
@@ -1,12 +1,20 @@
import { connect } from 'react-redux';
import { doUpdateSearchQuery, selectSearchState as selectSearch, selectSearchSuggestions } from 'lbry-redux';
import {
doUpdateSearchQuery,
selectSearchState as selectSearch,
selectSearchValue,
selectSearchSuggestions
} from 'lbry-redux';
import { selectCurrentRoute } from 'redux/selectors/drawer';
import UriBar from './view';
const select = state => {
const { ...searchState } = selectSearch(state);
return {
...searchState,
query: selectSearchValue(state),
currentRoute: selectCurrentRoute(state),
suggestions: selectSearchSuggestions(state)
};
};
+60 -38
View File
@@ -3,13 +3,14 @@ import React from 'react';
import { SEARCH_TYPES, isNameValid, isURIValid, normalizeURI } from 'lbry-redux';
import { FlatList, Keyboard, TextInput, View } from 'react-native';
import { navigateToUri } from 'utils/helper';
import Constants from 'constants';
import UriBarItem from './internal/uri-bar-item';
import NavigationButton from 'component/navigationButton';
import discoverStyle from 'styles/discover';
import uriBarStyle from 'styles/uriBar';
class UriBar extends React.PureComponent {
static INPUT_TIMEOUT = 1000; // 1 second
static INPUT_TIMEOUT = 2500; // 2.5 seconds
textInput = null;
@@ -26,6 +27,15 @@ class UriBar extends React.PureComponent {
}
}
componentWillReceiveProps(nextProps) {
const { currentRoute, query } = nextProps;
const { currentRoute: prevRoute } = this.props;
if (Constants.DRAWER_ROUTE_SEARCH === currentRoute && currentRoute !== prevRoute) {
this.setState({ currentValue: query, inputText: query });
}
}
constructor(props) {
super(props);
this.state = {
@@ -44,6 +54,11 @@ class UriBar extends React.PureComponent {
const { updateSearchQuery, onSearchSubmitted, navigation } = this.props;
let timeout = setTimeout(() => {
if (text.trim().length === 0) {
// don't do anything if the text is empty
return;
}
updateSearchQuery(text);
if (!text.startsWith('lbry://')) {
@@ -94,30 +109,43 @@ class UriBar extends React.PureComponent {
}
}
handleSubmitEditing = () => {
const { navigation, onSearchSubmitted, updateSearchQuery } = this.props;
if (this.state.inputText) {
let inputText = this.state.inputText;
if (inputText.startsWith('lbry://') && isURIValid(inputText)) {
// if it's a URI (lbry://...), open the file page
const uri = normalizeURI(inputText);
navigateToUri(navigation, uri);
} else {
updateSearchQuery(inputText);
// Not a URI, default to a search request
if (onSearchSubmitted) {
// Only the search page sets the onSearchSubmitted prop, so call this prop if set
onSearchSubmitted(inputText);
return;
}
// Open the search page with the query populated
navigation.navigate({ routeName: 'Search', key: 'searchPage', params: { searchQuery: inputText }});
}
}
}
onSearchPageBlurred() {
this.setState({ currenValueSet: false });
}
render() {
const { navigation, onSearchSubmitted, suggestions, updateSearchQuery, value } = this.props;
const { navigation, suggestions, query, value } = this.props;
if (this.state.currentValue === null) {
this.setState({ currentValue: value });
}
let style = [uriBarStyle.overlay];
/*if (this.state.focused) {
style.push(uriBarStyle.inFocus);
}
{(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)}
/>)} />
</View>)}*/
// TODO: Add optional setting to enable URI / search bar suggestions
/*if (this.state.focused) { style.push(uriBarStyle.inFocus); }*/
return (
<View style={style}>
@@ -146,26 +174,20 @@ class UriBar extends React.PureComponent {
this.setSelection();
}}
onChangeText={this.handleChangeText}
onSubmitEditing={() => {
if (this.state.inputText) {
let inputText = this.state.inputText;
if (inputText.startsWith('lbry://') && isURIValid(inputText)) {
// if it's a URI (lbry://...), open the file page
const uri = normalizeURI(inputText);
navigateToUri(navigation, uri);
} else {
// Not a URI, default to a search request
if (onSearchSubmitted) {
// Only the search page sets the onSearchSubmitted prop, so call this prop if set
onSearchSubmitted(inputText);
return;
}
// Open the search page with the query populated
navigation.navigate({ routeName: 'Search', key: 'searchPage', params: { searchQuery: inputText }});
}
}
}}/>
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)}
/>)} />
</View>)}
</View>
</View>
);
+1 -1
View File
@@ -32,7 +32,7 @@ class WalletAddress extends React.PureComponent<Props> {
<Address address={receiveAddress} style={walletStyle.bottomMarginSmall} />
<Button style={[walletStyle.button, walletStyle.bottomMarginLarge]}
icon={'sync'}
text={'Get New Address'}
text={'Get new address'}
onPress={getNewAddress}
disabled={gettingNewAddress}
/>
+4 -4
View File
@@ -1,10 +1,10 @@
// @flow
import React from 'react';
import { Image, Text, View } from 'react-native';
import { formatCredits } from 'lbry-redux'
import Address from '../address';
import Button from '../button';
import walletStyle from '../../styles/wallet';
import { Lbry, formatCredits } from 'lbry-redux'
import Address from 'component/address';
import Button from 'component/button';
import walletStyle from 'styles/wallet';
type Props = {
balance: number,
@@ -0,0 +1,4 @@
import { connect } from 'react-redux';
import WalletRewardsDriver from './view';
export default connect()(WalletRewardsDriver);
@@ -0,0 +1,17 @@
import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import walletStyle from 'styles/wallet';
class WalletRewardsDriver extends React.PureComponent<Props> {
render() {
const { navigation } = this.props;
return (
<TouchableOpacity style={walletStyle.rewardDriverCard} onPress={() => navigation.navigate('Rewards')}>
<Text style={walletStyle.rewardDriverText}>Earn credits while using the LBRY app. Tap to get started.</Text>
</TouchableOpacity>
);
}
}
export default WalletRewardsDriver;
+1
View File
@@ -108,6 +108,7 @@ class WalletSend extends React.PureComponent<Props> {
<TextInput ref={ref => this.amountInput = ref}
onChangeText={value => this.setState({amount: value})}
keyboardType={'numeric'}
placeholder={'0'}
value={this.state.amount}
style={[walletStyle.input, walletStyle.amountInput]} />
<Text style={[walletStyle.text, walletStyle.currency]}>LBC</Text>
@@ -0,0 +1,10 @@
import { connect } from 'react-redux';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import Constants from 'constants';
import WalletSyncDriver from './view';
const select = state => ({
deviceWalletSynced: makeSelectClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED)(state),
});
export default connect(select, null)(WalletSyncDriver);
@@ -0,0 +1,33 @@
import React from 'react';
import { Text, View } from 'react-native';
import Button from 'component/button';
import Link from 'component/link';
import walletStyle from 'styles/wallet';
class WalletSyncDriver extends React.PureComponent<Props> {
onEnableSyncPressed = () => {
const { navigation } = this.props;
navigation.navigate({ routeName: 'Verification', key: 'verification', params: { syncFlow: true } });
}
render() {
const { deviceWalletSynced } = this.props;
return (
<View style={walletStyle.syncDriverCard}>
<View style={walletStyle.syncDriverRow}>
<Text style={walletStyle.syncDriverTitle}>Wallet sync is {deviceWalletSynced ? 'on' : 'off'}.</Text>
{!deviceWalletSynced &&
<Link text="Sync FAQ" href="https://lbry.com/faq/how-to-backup-wallet#sync" style={walletStyle.syncDriverText} />}
</View>
{!deviceWalletSynced &&
<View style={walletStyle.actionRow}>
<Button style={walletStyle.enrollButton} theme={"light"} text={"Enable"} onPress={this.onEnableSyncPressed} />
<Link text="Manual backup" href="https://lbry.com/faq/how-to-backup-wallet#android" style={walletStyle.syncDriverText} />
</View>}
</View>
);
}
}
export default WalletSyncDriver;
+36 -3
View File
@@ -1,5 +1,22 @@
const Constants = {
FIRST_RUN_PAGE_WELCOME: "welcome",
FIRST_RUN_PAGE_EMAIL_COLLECT: "email-collect",
FIRST_RUN_PAGE_EMAIL_VERIFY:"email-verify",
FIRST_RUN_PAGE_WALLET: "wallet",
FIRST_RUN_PAGE_SKIP_ACCOUNT: "skip-account",
VERIFY_PAGE_EMAIL: "email-verify",
VERIFY_PAGE_PHONE_NUMBER: "phone-number-verify",
PHASE_COLLECTION: "collection",
PHASE_VERIFICATION: "verification",
CONTENT_TAB: "content",
ABOUT_TAB: "about",
KEY_FIRST_RUN_EMAIL: "firstRunEmail",
KEY_FIRST_RUN_PASSWORD: "firstRunPassword",
KEY_FIRST_USER_AUTH: "firstUserAuth",
KEY_SHOULD_VERIFY_EMAIL: "shouldVerifyEmail",
KEY_EMAIL_VERIFY_PENDING: "emailVerifyPending",
@@ -7,12 +24,20 @@ const Constants = {
SETTING_SUBSCRIPTIONS_VIEW_MODE: "subscriptionsViewMode",
SETTING_RATING_REMINDER_LAST_SHOWN: "ratingReminderLastShown",
SETTING_RATING_REMINDER_DISABLED: "ratingReminderDisabled",
SETTING_BACKUP_DISMISSED: "backupDismissed",
SETTING_REWARDS_NOT_INTERESTED: "rewardsNotInterested",
SETTING_DEVICE_WALLET_SYNCED: "deviceWalletSynced",
ACTION_DELETE_COMPLETED_BLOBS: "DELETE_COMPLETED_BLOBS",
ACTION_FIRST_RUN_PAGE_CHANGED: "FIRST_RUN_PAGE_CHANGED",
ACTION_PUSH_DRAWER_STACK: "PUSH_DRAWER_STACK",
ACTION_POP_DRAWER_STACK: "POP_DRAWER_STACK",
ACTION_SET_PLAYER_VISIBLE: "SET_PLAYER_VISIBLE",
ACTION_REACT_NAVIGATION_RESET: "Navigation/RESET",
ACTION_REACT_NAVIGATION_NAVIGATE: "Navigation/NAVIGATE",
ACTION_REACT_NAVIGATION_REPLACE: "Navigation/REPLACE",
PAGE_REWARDS: "rewards",
PAGE_SETTINGS: "settings",
@@ -30,10 +55,18 @@ const Constants = {
DRAWER_ROUTE_SEARCH: "Search",
DRAWER_ROUTE_TRANSACTION_HISTORY: "TransactionHistory",
SUBSCRIPTIONS_VIEW_ALL: 'view_all',
SUBSCRIPTIONS_VIEW_LATEST_FIRST: 'view_latest_first',
FULL_ROUTE_NAME_DISCOVER: "DiscoverStack",
FULL_ROUTE_NAME_TRENDING: "TrendingStack",
FULL_ROUTE_NAME_MY_SUBSCRIPTIONS: "MySubscriptionsStack",
FULL_ROUTE_NAME_WALLET: "WalletStack",
FULL_ROUTE_NAME_MY_LBRY: "MyLBRYStack",
PLAY_STORE_URL: 'https://play.google.com/store/apps/details?id=io.lbry.browser',
ROUTE_FILE: "File",
SUBSCRIPTIONS_VIEW_ALL: "view_all",
SUBSCRIPTIONS_VIEW_LATEST_FIRST: "view_latest_first",
PLAY_STORE_URL: "https://play.google.com/store/apps/details?id=io.lbry.browser",
RATING_REMINDER_INTERVAL: 604800, // 7 days (7 * 24 * 3600s)
};
+11 -15
View File
@@ -3,8 +3,6 @@ import { setJSExceptionHandler } from 'react-native-exception-handler';
import { Provider, connect } from 'react-redux';
import {
AppRegistry,
AppState,
AsyncStorage,
Text,
View,
NativeModules
@@ -13,6 +11,7 @@ import {
Lbry,
claimsReducer,
contentReducer,
fileReducer,
fileInfoReducer,
notificationsReducer,
searchReducer,
@@ -25,13 +24,13 @@ import {
homepageReducer,
rewardsReducer,
subscriptionsReducer,
syncReducer,
userReducer
} from 'lbryinc';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { createLogger } from 'redux-logger';
import { AppNavigator } from 'component/AppNavigator';
import AppWithNavigationState, { AppNavigator, navigatorReducer, reactNavigationMiddleware } from 'component/AppNavigator';
import { persistStore, autoRehydrate } from 'redux-persist';
import AppWithNavigationState, { reactNavigationMiddleware } from './component/AppNavigator';
import AsyncStorage from '@react-native-community/async-storage';
import FilesystemStorage from 'redux-persist-filesystem-storage';
import createCompressor from 'redux-persist-transform-compress';
import createFilter from 'redux-persist-transform-filter';
@@ -40,14 +39,14 @@ import drawerReducer from 'redux/reducers/drawer';
import settingsReducer from 'redux/reducers/settings';
import thunk from 'redux-thunk';
const globalExceptionHandler = (error, isFatal) => {
if (error && NativeModules.Mixpanel) {
NativeModules.Mixpanel.logException(isFatal, error.message ? error.message : "No message", error);
if (error && NativeModules.Firebase) {
NativeModules.Firebase.logException(isFatal, error.message ? error.message : "No message", JSON.stringify(error));
}
};
setJSExceptionHandler(globalExceptionHandler, true);
function isFunction(object) {
return typeof object === 'function';
}
@@ -76,13 +75,9 @@ function enableBatching(reducer) {
};
}
const router = AppNavigator.router;
/*const router = AppNavigator.router;
const navAction = router.getActionForPathAndParams('FirstRun');
const initialNavState = router.getStateForAction(navAction);
const navigatorReducer = (state = initialNavState, action) => {
const nextState = AppNavigator.router.getStateForAction(action, state);
return nextState || state;
};
const initialNavState = router.getStateForAction(navAction);*/
const reducers = combineReducers({
auth: authReducer,
@@ -91,6 +86,7 @@ const reducers = combineReducers({
content: contentReducer,
costInfo: costInfoReducer,
drawer: drawerReducer,
file: fileReducer,
fileInfo: fileInfoReducer,
homepage: homepageReducer,
nav: navigatorReducer,
@@ -99,12 +95,12 @@ const reducers = combineReducers({
settings: settingsReducer,
search: searchReducer,
subscriptions: subscriptionsReducer,
sync: syncReducer,
user: userReducer,
wallet: walletReducer
});
const bulkThunk = createBulkThunkMiddleware();
const logger = createLogger({ collapsed: true });
const middleware = [thunk, bulkThunk, reactNavigationMiddleware];
// eslint-disable-next-line no-underscore-dangle
+5 -3
View File
@@ -1,15 +1,16 @@
import { connect } from 'react-redux';
import { doToast } from 'lbry-redux';
import { doFetchAccessToken, selectAccessToken, selectUserEmail } from 'lbryinc';
import { doPushDrawerStack, doPopDrawerStack } from 'redux/actions/drawer';
import { selectDrawerStack } from 'redux/selectors/drawer';
import { doPushDrawerStack, doPopDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectCurrentRoute, selectDrawerStack } from 'redux/selectors/drawer';
import AboutPage from './view';
import Constants from 'constants';
const select = state => ({
accessToken: selectAccessToken(state),
userEmail: selectUserEmail(state),
currentRoute: selectCurrentRoute(state),
drawerStack: selectDrawerStack(state),
userEmail: selectUserEmail(state),
});
const perform = dispatch => ({
@@ -17,6 +18,7 @@ const perform = dispatch => ({
notify: data => dispatch(doToast(data)),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_ABOUT)),
popDrawerStack: () => dispatch(doPopDrawerStack()),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false)),
});
export default connect(select, perform)(AboutPage);
+30 -1
View File
@@ -2,6 +2,7 @@ import React from 'react';
import { Lbry } from 'lbry-redux';
import { NativeModules, Text, View, ScrollView } from 'react-native';
import { navigateBack } from 'utils/helper';
import Constants from 'constants';
import Link from 'component/link';
import PageHeader from 'component/pageHeader';
import aboutStyle from 'styles/about';
@@ -13,8 +14,36 @@ class AboutPage extends React.PureComponent {
versionInfo: null
};
didFocusListener;
componentWillMount() {
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
componentWillUnmount() {
if (this.didFocusListener) {
this.didFocusListener.remove();
}
}
componentDidMount() {
this.props.pushDrawerStack();
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { currentRoute } = nextProps;
const { currentRoute: prevRoute } = this.props;
if (Constants.DRAWER_ROUTE_ABOUT === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
}
onComponentFocused = () => {
const { pushDrawerStack, setPlayerVisible } = this.props;
pushDrawerStack();
setPlayerVisible();
if (NativeModules.VersionInfo) {
NativeModules.VersionInfo.getAppVersion().then(version => {
this.setState({appVersion: version});
-2
View File
@@ -1,7 +1,6 @@
import { connect } from 'react-redux';
import {
doFetchClaimsByChannel,
doFetchClaimCountByChannel,
makeSelectClaimForUri,
makeSelectClaimsInChannelForCurrentPageState,
makeSelectFetchingChannelClaims,
@@ -21,7 +20,6 @@ const select = (state, props) => ({
const perform = dispatch => ({
fetchClaims: (uri, page) => dispatch(doFetchClaimsByChannel(uri, page)),
fetchClaimCount: uri => dispatch(doFetchClaimCountByChannel(uri)),
popDrawerStack: () => dispatch(doPopDrawerStack())
});
+138 -25
View File
@@ -1,9 +1,20 @@
// @flow
import React from 'react';
import { ActivityIndicator, Text, View } from 'react-native';
import {
ActivityIndicator,
Dimensions,
Image,
ScrollView,
Text,
TouchableOpacity,
View
} from 'react-native';
import { TabView, SceneMap } from 'react-native-tab-view';
import { navigateBack } from 'utils/helper';
import Colors from 'styles/colors';
import Constants from 'constants';
import Button from 'component/button';
import Link from 'component/link';
import FileList from 'component/fileList';
import PageHeader from 'component/pageHeader';
import SubscribeButton from 'component/subscribeButton';
@@ -13,7 +24,8 @@ import channelPageStyle from 'styles/channelPage';
class ChannelPage extends React.PureComponent {
state = {
page: 1,
showPageButtons: false
showPageButtons: false,
activeTab: Constants.CONTENT_TAB
};
componentDidMount() {
@@ -21,7 +33,6 @@ class ChannelPage extends React.PureComponent {
if (!claimsInChannel || !claimsInChannel.length) {
fetchClaims(uri, page || this.state.page);
fetchClaimCount(uri);
}
}
@@ -43,18 +54,8 @@ class ChannelPage extends React.PureComponent {
}
}
render() {
const {
fetching,
claimsInChannel,
claim,
navigation,
totalPages,
uri,
drawerStack,
popDrawerStack
} = this.props;
const { name, permanent_url: permanentUrl } = claim;
renderContent = () => {
const { fetching, claimsInChannel, totalPages, navigation } = this.props;
let contentList;
if (fetching) {
@@ -81,15 +82,9 @@ class ChannelPage extends React.PureComponent {
);
}
return (
<View style={channelPageStyle.container}>
<UriBar value={uri} navigation={navigation} />
<View style={channelPageStyle.channelHeader}>
<Text style={channelPageStyle.channelName}>{name}</Text>
<SubscribeButton style={channelPageStyle.subscribeButton} uri={uri} name={name} />
</View>
{contentList}
{(totalPages > 1) && this.state.showPageButtons &&
let pageButtons;
if (totalPages > 1 && this.state.showPageButtons) {
pageButtons = (
<View style={channelPageStyle.pageButtons}>
<View>
{(this.state.page > 1) && <Button
@@ -103,7 +98,125 @@ class ChannelPage extends React.PureComponent {
text={"Next"}
disabled={!!fetching}
onPress={this.handleNextPage} />}
</View>}
</View>
);
}
return (
<View style={channelPageStyle.contentTab}>
{contentList}
{pageButtons}
</View>
);
}
renderAbout = () => {
const { claim } = this.props;
if (!claim) {
return (
<View style={channelPageStyle.aboutTab}>
<View style={channelPageStyle.busyContainer}>
<Text style={channelPageStyle.infoText}>No information to display.</Text>
</View>
</View>
);
}
const { cover, description, thumbnail, email, website_url, title } = claim.value;
return (
<View style={channelPageStyle.aboutTab}>
{(!website_url && !email && !description) &&
<View style={channelPageStyle.busyContainer}>
<Text style={channelPageStyle.infoText}>Nothing here yet. Please check back later.</Text>
</View>}
{(website_url || email || description) &&
<ScrollView style={channelPageStyle.aboutScroll} contentContainerStyle={channelPageStyle.aboutScrollContent}>
{(website_url && website_url.trim().length > 0) &&
<View style={channelPageStyle.aboutItem}>
<Text style={channelPageStyle.aboutTitle}>Website</Text>
<Link style={channelPageStyle.aboutText} text={website_url} href={website_url} />
</View>}
{(email && email.trim().length > 0) &&
<View style={channelPageStyle.aboutItem}>
<Text style={channelPageStyle.aboutTitle}>Email</Text>
<Link style={channelPageStyle.aboutText} text={email} href={`mailto:${email}`} />
</View>}
{(description && description.trim().length > 0) &&
<View style={channelPageStyle.aboutItem}>
<Text style={channelPageStyle.aboutText}>{description}</Text>
</View>}
</ScrollView>}
</View>
);
}
render() {
const {
fetching,
claimsInChannel,
claim,
navigation,
totalPages,
uri,
drawerStack,
popDrawerStack
} = this.props;
const { name, permanent_url: permanentUrl } = claim;
let thumbnailUrl, coverUrl, title;
if (claim && claim.value) {
title = claim.value.title;
if (claim.value.cover) {
coverUrl = claim.value.cover.url;
}
if (claim.value.thumbnail) {
thumbnailUrl = claim.value.thumbnail.url;
}
}
return (
<View style={channelPageStyle.container}>
<UriBar value={uri} navigation={navigation} />
<View style={channelPageStyle.viewContainer}>
<View style={channelPageStyle.cover}>
<Image
style={channelPageStyle.coverImage}
resizeMode={'cover'}
source={(coverUrl && coverUrl.trim().length > 0) ? { uri: coverUrl } : require('../../assets/default_channel_cover.png')} />
<View style={channelPageStyle.channelHeader}>
<Text style={channelPageStyle.channelName}>{(title && title.trim().length > 0) ? title : name}</Text>
</View>
<View style={channelPageStyle.avatarImageContainer}>
<Image
style={channelPageStyle.avatarImage}
resizeMode={'cover'}
source={(thumbnailUrl && thumbnailUrl.trim().length > 0) ? { uri: thumbnailUrl } : require('../../assets/default_avatar.jpg')} />
</View>
<SubscribeButton style={channelPageStyle.subscribeButton} uri={uri} name={name} />
</View>
<View style={channelPageStyle.tabBar}>
<TouchableOpacity style={channelPageStyle.tab} onPress={() => this.setState({ activeTab: Constants.CONTENT_TAB })}>
<Text style={channelPageStyle.tabTitle}>CONTENT</Text>
{Constants.CONTENT_TAB === this.state.activeTab && <View style={channelPageStyle.activeTabHint} />}
</TouchableOpacity>
<TouchableOpacity style={channelPageStyle.tab} onPress={() => this.setState({ activeTab: Constants.ABOUT_TAB })}>
<Text style={channelPageStyle.tabTitle}>ABOUT</Text>
{Constants.ABOUT_TAB === this.state.activeTab && <View style={channelPageStyle.activeTabHint} />}
</TouchableOpacity>
</View>
{Constants.CONTENT_TAB === this.state.activeTab && this.renderContent()}
{Constants.ABOUT_TAB === this.state.activeTab && this.renderAbout()}
</View>
</View>
)
}
+4
View File
@@ -1,6 +1,8 @@
import { connect } from 'react-redux';
import {
doFileList,
selectBalance,
selectFileInfosDownloaded,
} from 'lbry-redux';
import {
doFetchFeaturedUris,
@@ -24,6 +26,7 @@ const select = state => ({
enabledChannelNotifications: selectEnabledChannelNotifications(state),
featuredUris: selectFeaturedUris(state),
fetchingFeaturedUris: selectFetchingFeaturedUris(state),
fileInfos: selectFileInfosDownloaded(state),
ratingReminderDisabled: makeSelectClientSetting(Constants.SETTING_RATING_REMINDER_DISABLED)(state),
ratingReminderLastShown: makeSelectClientSetting(Constants.SETTING_RATING_REMINDER_LAST_SHOWN)(state),
unreadSubscriptions: selectUnreadSubscriptions(state),
@@ -33,6 +36,7 @@ const perform = dispatch => ({
fetchFeaturedUris: () => dispatch(doFetchFeaturedUris()),
fetchRewardedContent: () => dispatch(doFetchRewardedContent()),
fetchSubscriptions: () => dispatch(doFetchMySubscriptions()),
fileList: () => dispatch(doFileList()),
removeUnreadSubscriptions: () => dispatch(doRemoveUnreadSubscriptions()),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value))
});
+25 -18
View File
@@ -3,7 +3,6 @@ import NavigationActions from 'react-navigation';
import {
Alert,
ActivityIndicator,
AsyncStorage,
Linking,
NativeModules,
SectionList,
@@ -11,12 +10,13 @@ import {
View
} from 'react-native';
import { Lbry, normalizeURI, parseURI } from 'lbry-redux';
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
import CategoryList from 'component/categoryList';
import Constants from 'constants';
import Colors from 'styles/colors';
import discoverStyle from 'styles/discover';
import FloatingWalletBalance from 'component/floatingWalletBalance';
import FileItem from 'component/fileItem';
import UriBar from 'component/uriBar';
class DiscoverPage extends React.PureComponent {
@@ -34,9 +34,9 @@ class DiscoverPage extends React.PureComponent {
AsyncStorage.getItem('firstLaunchSuspended').then(suspended => {
AsyncStorage.removeItem('firstLaunchSuspended');
const appSuspended = (suspended === 'true');
if (NativeModules.Mixpanel) {
NativeModules.Mixpanel.track('First Run Time', {
'Total Seconds': delta, 'App Suspended': appSuspended
if (NativeModules.Firebase) {
NativeModules.Firebase.track('first_run_time', {
'total_seconds': delta, 'app_suspended': appSuspended
});
}
});
@@ -46,12 +46,14 @@ class DiscoverPage extends React.PureComponent {
const {
fetchFeaturedUris,
fetchRewardedContent,
fetchSubscriptions
fetchSubscriptions,
fileList
} = this.props;
fetchFeaturedUris();
fetchRewardedContent();
fetchSubscriptions();
fileList();
this.showRatingReminder();
}
@@ -150,6 +152,10 @@ class DiscoverPage extends React.PureComponent {
setClientSetting(Constants.SETTING_RATING_REMINDER_LAST_SHOWN, settingString);
}
trimClaimIdFromCategory(category) {
return category.split('#')[0];
}
render() {
const { featuredUris, fetchingFeaturedUris, navigation } = this.props;
const hasContent = typeof featuredUris === 'object' && Object.keys(featuredUris).length,
@@ -165,22 +171,23 @@ class DiscoverPage extends React.PureComponent {
</View>
)}
{(!!hasContent) &&
(<SectionList style={discoverStyle.scrollContainer}
(<SectionList
style={discoverStyle.scrollContainer}
contentContainerStyle={discoverStyle.scrollPadding}
initialNumToRender={4}
maxToRenderPerBatch={4}
removeClippedSubviews={true}
renderItem={ ({item, index, section}) => (
<FileItem
style={discoverStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={item}
uri={normalizeURI(item)}
navigation={navigation}
compactView={false}
showDetails={true} />
)
}
<CategoryList
key={item}
category={item}
categoryMap={featuredUris}
navigation={navigation} />
)}
renderSectionHeader={
({section: {title}}) => (<Text style={discoverStyle.categoryName}>{title}</Text>)
}
sections={Object.keys(featuredUris).map(category => ({ title: category, data: featuredUris[category] }))}
sections={Object.keys(featuredUris).map(category => ({ title: this.trimClaimIdFromCategory(category), data: [category] }))}
keyExtractor={(item, index) => item}
/>)
}
+6 -3
View File
@@ -5,19 +5,22 @@ import {
selectMyClaimsWithoutChannels,
selectIsFetchingFileList,
} from 'lbry-redux';
import { doPushDrawerStack } from 'redux/actions/drawer';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectCurrentRoute } from 'redux/selectors/drawer';
import Constants from 'constants';
import DownloadsPage from './view';
const select = (state) => ({
claims: selectMyClaimsWithoutChannels(state),
currentRoute: selectCurrentRoute(state),
fileInfos: selectFileInfosDownloaded(state),
fetching: selectIsFetchingFileList(state),
claims: selectMyClaimsWithoutChannels(state),
});
const perform = dispatch => ({
fileList: () => dispatch(doFileList()),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_MY_LBRY))
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_MY_LBRY)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false))
});
export default connect(select, perform)(DownloadsPage);
+41 -20
View File
@@ -9,27 +9,54 @@ import {
View,
ScrollView
} from 'react-native';
import { navigateToUri, uriFromFileInfo } from '../../utils/helper';
import Colors from '../../styles/colors';
import PageHeader from '../../component/pageHeader';
import FileListItem from '../../component/fileListItem';
import FloatingWalletBalance from '../../component/floatingWalletBalance';
import StorageStatsCard from '../../component/storageStatsCard';
import UriBar from '../../component/uriBar';
import downloadsStyle from '../../styles/downloads';
import fileListStyle from '../../styles/fileList';
import { navigateToUri, uriFromFileInfo } from 'utils/helper';
import Colors from 'styles/colors';
import Constants from 'constants';
import PageHeader from 'component/pageHeader';
import FileListItem from 'component/fileListItem';
import FloatingWalletBalance from 'component/floatingWalletBalance';
import StorageStatsCard from 'component/storageStatsCard';
import UriBar from 'component/uriBar';
import downloadsStyle from 'styles/downloads';
import fileListStyle from 'styles/fileList';
class DownloadsPage extends React.PureComponent {
static navigationOptions = {
title: 'Downloads'
};
componentDidMount() {
const { fileList, pushDrawerStack } = this.props;
didFocusListener;
componentWillMount() {
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
componentWillUnmount() {
if (this.didFocusListener) {
this.didFocusListener.remove();
}
}
onComponentFocused = () => {
const { fileList, pushDrawerStack, setPlayerVisible } = this.props;
pushDrawerStack();
setPlayerVisible();
fileList();
}
componentDidMount() {
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { currentRoute } = nextProps;
const { currentRoute: prevRoute } = this.props;
if (Constants.FULL_ROUTE_NAME_MY_LBRY === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
}
render() {
const { fetching, fileInfos, navigation } = this.props;
const hasDownloads = fileInfos && Object.values(fileInfos).length > 0;
@@ -39,7 +66,7 @@ class DownloadsPage extends React.PureComponent {
<UriBar navigation={navigation} />
{!fetching && !hasDownloads &&
<View style={downloadsStyle.busyContainer}>
<Text style={downloadsStyle.noDownloadsText}>You have not downloaded anything from LBRY yet.</Text>
<Text style={downloadsStyle.noDownloadsText}>You have not watched or downloaded any content from LBRY yet.</Text>
</View>}
{fetching && !hasDownloads &&
<View style={downloadsStyle.busyContainer}>
@@ -59,14 +86,8 @@ class DownloadsPage extends React.PureComponent {
onPress={() => navigateToUri(navigation, uriFromFileInfo(item), { autoplay: true })} />
)
}
data={fileInfos.sort((a, b) => {
// TODO: Implement sort based on user selection
if (!a.completed && b.completed) return -1;
if (a.completed && !b.completed) return 1;
if (a.metadata.title === b.metadata.title) return 0;
return (a.metadata.title < b.metadata.title) ? -1 : 1;
})}
keyExtractor={(item, index) => item.download_path}
data={fileInfos}
keyExtractor={(item, index) => item.outpoint}
/>
</View>}
<FloatingWalletBalance navigation={navigation} />
+32 -3
View File
@@ -1,6 +1,8 @@
import { connect } from 'react-redux';
import {
doFetchFileInfo,
doPurchaseUri,
doDeletePurchasedUri,
doResolveUri,
doSendTip,
doToast,
@@ -11,7 +13,13 @@ import {
makeSelectContentPositionForUri,
makeSelectContentTypeForUri,
makeSelectMetadataForUri,
makeSelectStreamingUrlForUri,
makeSelectThumbnailForUri,
makeSelectTitleForUri,
selectBalance,
selectPurchasedUris,
selectFailedPurchaseUris,
selectPurchaseUriErrorMessage,
} from 'lbry-redux';
import {
doFetchCostInfoForUri,
@@ -19,7 +27,15 @@ import {
selectRewardContentClaimIds,
selectBlackListedOutpoints
} from 'lbryinc';
import { doDeleteFile, doPurchaseUri, doStopDownloadingFile } from 'redux/actions/file';
import {
doStartDownload,
doUpdateDownload,
doCompleteDownload,
doDeleteFile,
doStopDownloadingFile
} from 'redux/actions/file';
import { doPopDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectDrawerStack } from 'redux/selectors/drawer';
import FilePage from './view';
const select = (state, props) => {
@@ -28,6 +44,7 @@ const select = (state, props) => {
balance: selectBalance(state),
blackListedOutpoints: selectBlackListedOutpoints(state),
claim: makeSelectClaimForUri(selectProps.uri)(state),
drawerStack: selectDrawerStack(state),
isResolvingUri: makeSelectIsUriResolving(selectProps.uri)(state),
contentType: makeSelectContentTypeForUri(selectProps.uri)(state),
costInfo: makeSelectCostInfoForUri(selectProps.uri)(state),
@@ -37,7 +54,13 @@ const select = (state, props) => {
fileInfo: makeSelectFileInfoForUri(selectProps.uri)(state),
rewardedContentClaimIds: selectRewardContentClaimIds(state, selectProps),
channelUri: makeSelectChannelForClaimUri(selectProps.uri, true)(state),
position: makeSelectContentPositionForUri(selectProps.uri)(state)
position: makeSelectContentPositionForUri(selectProps.uri)(state),
purchasedUris: selectPurchasedUris(state),
failedPurchaseUris: selectFailedPurchaseUris(state),
purchaseUriErrorMessage: selectPurchaseUriErrorMessage(state),
streamingUrl: makeSelectStreamingUrlForUri(selectProps.uri)(state),
thumbnail: makeSelectThumbnailForUri(selectProps.uri)(state),
title: makeSelectTitleForUri(selectProps.uri)(state),
};
};
@@ -48,10 +71,16 @@ const perform = dispatch => ({
fetchFileInfo: uri => dispatch(doFetchFileInfo(uri)),
fetchCostInfo: uri => dispatch(doFetchCostInfoForUri(uri)),
notify: data => dispatch(doToast(data)),
purchaseUri: (uri, failureCallback) => dispatch(doPurchaseUri(uri, null, failureCallback)),
popDrawerStack: () => dispatch(doPopDrawerStack()),
purchaseUri: (uri, costInfo, saveFile) => dispatch(doPurchaseUri(uri, costInfo, saveFile)),
deletePurchasedUri: uri => dispatch(doDeletePurchasedUri(uri)),
resolveUri: uri => dispatch(doResolveUri(uri)),
sendTip: (amount, claimId, uri, successCallback, errorCallback) => dispatch(doSendTip(amount, claimId, uri, successCallback, errorCallback)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(true)),
stopDownload: (uri, fileInfo) => dispatch(doStopDownloadingFile(uri, fileInfo)),
startDownload: (uri, outpoint, fileInfo) => dispatch(doStartDownload(uri, outpoint, fileInfo)),
updateDownload: (uri, outpoint, fileInfo, progress) => dispatch(doUpdateDownload(uri, outpoint, fileInfo, progress)),
completeDownload: (uri, outpoint, fileInfo) => dispatch(doCompleteDownload(uri, outpoint, fileInfo)),
});
export default connect(select, perform)(FilePage);
+244 -69
View File
@@ -4,6 +4,7 @@ import { Lbryio } from 'lbryinc';
import {
ActivityIndicator,
Alert,
DeviceEventEmitter,
Dimensions,
NativeModules,
ScrollView,
@@ -12,15 +13,18 @@ import {
Text,
TextInput,
TouchableOpacity,
TouchableWithoutFeedback,
View,
WebView
} from 'react-native';
import { navigateToUri } from 'utils/helper';
import { NavigationEvents } from 'react-navigation';
import { navigateBack, navigateToUri } from 'utils/helper';
import Icon from 'react-native-vector-icons/FontAwesome5';
import ImageViewer from 'react-native-image-zoom-viewer';
import Button from 'component/button';
import Colors from 'styles/colors';
import ChannelPage from 'page/channel';
import Colors from 'styles/colors';
import Constants from 'constants';
import DateTime from 'component/dateTime';
import FileDownloadButton from 'component/fileDownloadButton';
import FileItemMedia from 'component/fileItemMedia';
@@ -33,6 +37,7 @@ import SubscribeButton from 'component/subscribeButton';
import SubscribeNotificationButton from 'component/subscribeNotificationButton';
import UriBar from 'component/uriBar';
import Video from 'react-native-video';
import FileRewardsDriver from 'component/fileRewardsDriver';
import filePageStyle from 'styles/filePage';
import uriBarStyle from 'styles/uriBar';
@@ -72,14 +77,26 @@ class FilePage extends React.PureComponent {
tipAmount: null,
uri: null,
uriVars: null,
stopDownloadConfirmed: false
stopDownloadConfirmed: false,
streamingMode: false
};
}
componentDidMount() {
didFocusListener;
componentWillMount() {
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
onComponentFocused = () => {
StatusBar.setHidden(false);
const { isResolvingUri, resolveUri, navigation } = this.props;
DeviceEventEmitter.addListener('onDownloadStarted', this.handleDownloadStarted);
DeviceEventEmitter.addListener('onDownloadUpdated', this.handleDownloadUpdated);
DeviceEventEmitter.addListener('onDownloadCompleted', this.handleDownloadCompleted);
const { fileInfo, isResolvingUri, resolveUri, navigation } = this.props;
const { uri, uriVars } = navigation.state.params;
this.setState({ uri, uriVars });
@@ -88,16 +105,74 @@ class FilePage extends React.PureComponent {
this.fetchFileInfo(this.props);
this.fetchCostInfo(this.props);
if (NativeModules.Mixpanel) {
NativeModules.Mixpanel.track('Open File Page', { Uri: uri });
if (NativeModules.Firebase) {
NativeModules.Firebase.track('open_file_page', { uri: uri });
}
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.keepAwakeOn();
}
}
componentDidMount() {
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const {
claim,
currentRoute,
failedPurchaseUris: prevFailedPurchaseUris,
purchasedUris: prevPurchasedUris,
navigation,
contentType,
notify
} = this.props;
const { uri } = navigation.state.params;
const {
currentRoute: prevRoute,
failedPurchaseUris,
fileInfo,
purchasedUris,
purchaseUriErrorMessage,
streamingUrl
} = nextProps;
if (Constants.ROUTE_FILE === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
if (failedPurchaseUris.includes(uri) && !purchasedUris.includes(uri)) {
if (purchaseUriErrorMessage && purchaseUriErrorMessage.trim().length > 0) {
notify({ message: purchaseUriErrorMessage, isError: true });
}
this.setState({ downloadPressed: false, fileViewLogged: false, mediaLoaded: false });
}
const mediaType = Lbry.getMediaType(contentType);
const isPlayable = mediaType === 'video' || mediaType === 'audio';
if (prevPurchasedUris.length != purchasedUris.length && NativeModules.UtilityModule) {
if (purchasedUris.includes(uri)) {
const { nout, txid } = claim;
const outpoint = `${txid}:${nout}`;
NativeModules.UtilityModule.queueDownload(outpoint);
// If the media is playable, file/view will be done in onPlaybackStarted
if (!isPlayable && !this.state.fileViewLogged) {
this.logFileView(uri, claim);
}
}
NativeModules.UtilityModule.checkDownloads();
}
if (!this.state.streamingMode && isPlayable) {
if (streamingUrl) {
this.setState({ streamingMode: true, currentStreamUrl: streamingUrl });
} else if (fileInfo && fileInfo.streaming_url) {
this.setState({ streamingMode: true, currentStreamUrl: fileInfo.streaming_url });
}
}
}
componentDidUpdate(prevProps) {
this.fetchFileInfo(this.props);
const { claim, contentType, fileInfo, isResolvingUri, resolveUri, navigation } = this.props;
const { uri } = this.state;
if (!isResolvingUri && claim === undefined && uri) {
@@ -113,17 +188,6 @@ class FilePage extends React.PureComponent {
uri: this.state.uri
};
}
const prevFileInfo = prevProps.fileInfo;
if (!prevFileInfo && fileInfo) {
// started downloading
const mediaType = Lbry.getMediaType(contentType);
const isPlayable = mediaType === 'video' || mediaType === 'audio';
// If the media is playable, file/view will be done in onPlaybackStarted
if (!isPlayable && !this.state.fileViewLogged) {
this.logFileView(uri, fileInfo);
}
}
}
fetchFileInfo(props) {
@@ -161,7 +225,7 @@ class FilePage extends React.PureComponent {
}
onDeletePressed = () => {
const { deleteFile, fileInfo } = this.props;
const { claim, deleteFile, deletePurchasedUri, fileInfo, navigation } = this.props;
Alert.alert(
'Delete file',
@@ -169,7 +233,12 @@ class FilePage extends React.PureComponent {
[
{ text: 'No' },
{ text: 'Yes', onPress: () => {
deleteFile(fileInfo.outpoint, true);
const { uri } = navigation.state.params;
deleteFile(`${claim.txid}:${claim.nout}`, true);
deletePurchasedUri(uri);
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.deleteDownload(uri);
}
this.setState({
downloadPressed: false,
fileViewLogged: false,
@@ -183,7 +252,7 @@ class FilePage extends React.PureComponent {
}
onStopDownloadPressed = () => {
const { fileInfo, navigation, notify, stopDownload } = this.props;
const { deletePurchasedUri, fileInfo, navigation, notify, stopDownload } = this.props;
Alert.alert(
'Stop download',
@@ -191,7 +260,12 @@ class FilePage extends React.PureComponent {
[
{ text: 'No' },
{ text: 'Yes', onPress: () => {
stopDownload(navigation.state.params.uri, fileInfo);
const { uri } = navigation.state.params;
stopDownload(uri, fileInfo);
deletePurchasedUri(uri);
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.deleteDownload(uri);
}
this.setState({
downloadPressed: false,
fileViewLogged: false,
@@ -220,10 +294,35 @@ class FilePage extends React.PureComponent {
utility.keepAwakeOff();
utility.showNavigationBar();
}
if (this.didFocusListener) {
this.didFocusListener.remove();
}
if (window.currentMediaInfo) {
window.currentMediaInfo = null;
}
window.player = null;
DeviceEventEmitter.removeListener('onDownloadStarted', this.handleDownloadStarted);
DeviceEventEmitter.removeListener('onDownloadUpdated', this.handleDownloadUpdated);
DeviceEventEmitter.removeListener('onDownloadCompleted', this.handleDownloadCompleted);
}
handleDownloadStarted = (evt) => {
const { startDownload } = this.props;
const { uri, outpoint, fileInfo } = evt;
startDownload(uri, outpoint, fileInfo);
}
handleDownloadUpdated = (evt) => {
const { updateDownload } = this.props;
const { uri, outpoint, fileInfo, progress } = evt;
updateDownload(uri, outpoint, fileInfo, progress);
}
handleDownloadCompleted = (evt) => {
const { completeDownload } = this.props;
const { uri, outpoint, fileInfo } = evt;
completeDownload(uri, outpoint, fileInfo);
}
localUriForFileInfo = (fileInfo) => {
@@ -233,6 +332,32 @@ class FilePage extends React.PureComponent {
return 'file:///' + fileInfo.download_path;
}
playerUriForFileInfo = (fileInfo) => {
const { streamingUrl } = this.props;
if (fileInfo && fileInfo.download_path) {
return this.getEncodedDownloadPath(fileInfo);
}
if (streamingUrl) {
return streamingUrl;
}
if (this.state.currentStreamUrl) {
return this.state.currentStreamUrl;
}
return null;
}
getEncodedDownloadPath = (fileInfo) => {
if (this.state.encodedFilePath) {
return this.state.encodedFilePath;
}
const { file_name: fileName } = fileInfo;
const encodedFileName = encodeURIComponent(fileName).replace(/!/g, '%21');
const encodedFilePath = fileInfo.download_path.replace(fileName, encodedFileName);
return encodedFilePath;
}
linkify = (text) => {
let linkifiedContent = [];
let lines = text.split(/\n/g);
@@ -297,16 +422,16 @@ class FilePage extends React.PureComponent {
this.startTime = null;
}
const { fileInfo, navigation } = this.props;
const { claim, navigation } = this.props;
const { uri } = navigation.state.params;
this.logFileView(uri, fileInfo, timeToStartMillis);
this.logFileView(uri, claim, timeToStartMillis);
let payload = { 'Uri': uri };
let payload = { 'uri': uri };
if (!isNaN(timeToStart)) {
payload['Time to Start (seconds)'] = timeToStart;
payload['Time to Start (ms)'] = timeToStartMillis;
payload['time_to_start_seconds'] = timeToStart;
payload['time_to_start_ms'] = timeToStartMillis;
}
NativeModules.Mixpanel.track('Play', payload);
NativeModules.Firebase.track('play', payload);
}
onPlaybackFinished = () => {
@@ -321,8 +446,13 @@ class FilePage extends React.PureComponent {
}
}
logFileView = (uri, fileInfo, timeToStart) => {
const { outpoint, claim_id: claimId } = fileInfo;
logFileView = (uri, claim, timeToStart) => {
if (!claim) {
return;
}
const { nout, claim_id: claimId, txid } = claim;
const outpoint = `${txid}:${nout}`;
const params = {
uri,
outpoint,
@@ -351,17 +481,30 @@ class FilePage extends React.PureComponent {
sendTip(tipAmount, claim.claim_id, uri, () => { this.setState({ tipAmount: 0, showTipView: false }) });
}
startDownloadFailed = () => {
this.startTime = null;
setTimeout(() => {
this.setState({ downloadPressed: false, fileViewLogged: false, mediaLoaded: false });
}, 500);
renderTags = (tags) => {
return tags.map((tag, i) => (
<Text style={filePageStyle.tagItem} key={`${tag}-${i}`}>{tag}</Text>
));
}
onFileDownloadButtonPlayed = () => {
const { setPlayerVisible } = this.props;
this.startTime = Date.now();
this.setState({ downloadPressed: true, autoPlayMedia: true, stopDownloadConfirmed: false });
setPlayerVisible();
}
onBackButtonPressed = () => {
const { navigation, drawerStack, popDrawerStack } = this.props;
navigateBack(navigation, drawerStack, popDrawerStack);
}
render() {
const {
balance,
claim,
channelUri,
costInfo,
fileInfo,
metadata,
contentType,
@@ -371,7 +514,9 @@ class FilePage extends React.PureComponent {
blackListedOutpoints,
navigation,
position,
purchaseUri
purchaseUri,
thumbnail,
title
} = this.props;
const { uri, autoplay } = navigation.state.params;
@@ -422,27 +567,33 @@ class FilePage extends React.PureComponent {
</View>
);
} else {
let tags = [];
if (claim && claim.value && claim.value.tags) {
tags = claim.value.tags;
}
const completed = fileInfo && fileInfo.completed;
const title = metadata.title;
const isRewardContent = rewardedContentClaimIds.includes(claim.claim_id);
const description = metadata.description ? metadata.description : null;
const mediaType = Lbry.getMediaType(contentType);
const isPlayable = mediaType === 'video' || mediaType === 'audio';
const { height, channel_name: channelName, value } = claim;
const showActions = !this.state.fullscreenMode && !this.state.showImageViewer && !this.state.showWebView;
const showFileActions = (completed || (fileInfo && !fileInfo.stopped && fileInfo.written_bytes < fileInfo.total_bytes));
const channelClaimId = value && value.publisherSignature && value.publisherSignature.certificateId;
const showActions = !this.state.streamingMode && !this.state.fullscreenMode && !this.state.showImageViewer && !this.state.showWebView;
const showFileActions = (fileInfo && fileInfo.download_path) &&
(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 = channelClaimId && channelClaimId.trim().length > 0 ? `${channelName}#${channelClaimId}` : channelName;
const playerStyle = [filePageStyle.player,
this.state.isLandscape ? filePageStyle.containedPlayerLandscape :
(this.state.fullscreenMode ? filePageStyle.fullscreenPlayer : filePageStyle.containedPlayer)];
const playerBgStyle = [filePageStyle.playerBackground, this.state.fullscreenMode ?
filePageStyle.fullscreenPlayerBackground : filePageStyle.containedPlayerBackground];
const playerBgStyle = [filePageStyle.playerBackground, filePageStyle.containedPlayerBackground];
const fsPlayerBgStyle = [filePageStyle.playerBackground, filePageStyle.fullscreenPlayerBackground];
// at least 2MB (or the full download) before media can be loaded
const canLoadMedia = fileInfo &&
(fileInfo.written_bytes >= 2097152 || fileInfo.written_bytes == fileInfo.total_bytes); // 2MB = 1024*1024*2
const canLoadMedia = (this.state.streamingMode) || (fileInfo &&
(fileInfo.written_bytes >= 2097152 || fileInfo.written_bytes == fileInfo.total_bytes)); // 2MB = 1024*1024*2
const isViewable = (mediaType === 'image' || mediaType === 'text');
const isWebViewable = mediaType === 'text';
const canOpen = isViewable && completed;
@@ -472,7 +623,10 @@ class FilePage extends React.PureComponent {
if (fileInfo && !this.state.autoDownloadStarted && this.state.uriVars && 'true' === this.state.uriVars.download) {
this.setState({ autoDownloadStarted: true }, () => {
purchaseUri(uri, this.startDownloadFailed);
purchaseUri(uri, costInfo, !isPlayable);
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.checkDownloads();
}
});
}
@@ -496,25 +650,26 @@ class FilePage extends React.PureComponent {
onLayout={this.checkOrientation}>
<View style={filePageStyle.mediaContainer}>
{((canOpen || (!fileInfo || (isPlayable && !canLoadMedia))) || (!canOpen && fileInfo)) &&
<FileItemMedia style={filePageStyle.thumbnail} title={title} thumbnail={metadata.thumbnail} />}
<FileItemMedia style={filePageStyle.thumbnail} title={title} thumbnail={thumbnail} />}
{((!this.state.downloadButtonShown || this.state.downloadPressed) && !this.state.mediaLoaded) &&
<ActivityIndicator size="large" color={Colors.LbryGreen} style={filePageStyle.loading} />}
{((isPlayable && !completed && !canLoadMedia) || !completed || canOpen) && (!this.state.downloadPressed) &&
{((isPlayable && !completed && !canLoadMedia) || canOpen || (!completed && !this.state.streamingMode)) &&
(!this.state.downloadPressed) &&
<FileDownloadButton uri={uri}
style={filePageStyle.downloadButton}
openFile={openFile}
isPlayable={isPlayable}
isViewable={isViewable}
onPlay={() => {
this.startTime = Date.now();
this.setState({ downloadPressed: true, autoPlayMedia: true, stopDownloadConfirmed: false });
}}
onPlay={this.onFileDownloadButtonPlayed}
onView={() => this.setState({ downloadPressed: true })}
onButtonLayout={() => this.setState({ downloadButtonShown: true })}
onStartDownloadFailed={this.startDownloadFailed} />}
onButtonLayout={() => this.setState({ downloadButtonShown: true })} />}
{!fileInfo && <FilePrice uri={uri} style={filePageStyle.filePriceContainer} textStyle={filePageStyle.filePriceText} />}
<TouchableOpacity style={filePageStyle.backButton} onPress={this.onBackButtonPressed}>
<Icon name={"arrow-left"} size={18} style={filePageStyle.backButtonIcon} />
</TouchableOpacity>
</View>
{(canLoadMedia && fileInfo && isPlayable) &&
{(this.state.streamingMode || (canLoadMedia && fileInfo && isPlayable)) &&
<View style={playerBgStyle}
ref={(ref) => { this.playerBackground = ref; }}
onLayout={(evt) => {
@@ -522,11 +677,14 @@ class FilePage extends React.PureComponent {
this.setState({ playerBgHeight: evt.nativeEvent.layout.height });
}
}} />}
{(canLoadMedia && fileInfo && isPlayable) &&
{((this.state.streamingMode || (canLoadMedia && fileInfo && isPlayable)) && this.state.fullscreenMode) &&
<View style={fsPlayerBgStyle} />}
{(this.state.streamingMode || (canLoadMedia && fileInfo && isPlayable)) &&
<MediaPlayer
fileInfo={fileInfo}
claim={claim}
assignPlayer={(ref) => { this.player = ref; }}
uri={uri}
source={this.playerUriForFileInfo(fileInfo)}
style={playerStyle}
autoPlay={autoplay || this.state.autoPlayMedia}
onFullscreenToggled={this.handleFullscreenToggle}
@@ -536,9 +694,10 @@ class FilePage extends React.PureComponent {
}
}}
onMediaLoaded={() => this.onMediaLoaded(channelName, title, uri)}
onBackButtonPressed={this.onBackButtonPressed}
onPlaybackStarted={this.onPlaybackStarted}
onPlaybackFinished={this.onPlaybackFinished}
thumbnail={metadata.thumbnail}
thumbnail={thumbnail}
position={position}
/>}
@@ -555,6 +714,7 @@ class FilePage extends React.PureComponent {
fileInfo.written_bytes < fileInfo.total_bytes &&
!this.state.stopDownloadConfirmed &&
<Button style={filePageStyle.actionButton}
icon={"stop"}
theme={"light"}
text={"Stop Download"}
onPress={this.onStopDownloadPressed} />
@@ -564,14 +724,17 @@ class FilePage extends React.PureComponent {
<ScrollView
style={showActions ? filePageStyle.scrollContainerActions : filePageStyle.scrollContainer}
contentContainerstyle={showActions ? null : filePageStyle.scrollContent}
keyboardShouldPersistTaps={'handled'}
ref={(ref) => { this.scrollView = ref; }}>
<View style={filePageStyle.titleRow}>
<Text style={filePageStyle.title} selectable={true}>{title}</Text>
<TouchableOpacity style={filePageStyle.descriptionToggle}
onPress={() => this.setState({ showDescription: !this.state.showDescription })}>
<Icon name={this.state.showDescription ? "caret-up" : "caret-down"} size={24} />
</TouchableOpacity>
</View>
<TouchableWithoutFeedback style={filePageStyle.titleTouch}
onPress={() => this.setState({ showDescription: !this.state.showDescription })}>
<View style={filePageStyle.titleRow}>
<Text style={filePageStyle.title} selectable={true}>{title}</Text>
<View style={filePageStyle.descriptionToggle}>
<Icon name={this.state.showDescription ? "caret-up" : "caret-down"} size={24} />
</View>
</View>
</TouchableWithoutFeedback>
{channelName &&
<View style={filePageStyle.channelRow}>
<View style={filePageStyle.publishInfo}>
@@ -586,7 +749,7 @@ class FilePage extends React.PureComponent {
<DateTime
style={filePageStyle.publishDate}
textStyle={filePageStyle.publishDateText}
block={height}
uri={uri}
formatOptions={{ day: 'numeric', month: 'long', year: 'numeric' }}
show={DateTime.SHOW_DATE} />
</View>
@@ -615,6 +778,7 @@ class FilePage extends React.PureComponent {
<TextInput ref={ref => this.tipAmountInput = ref}
onChangeText={value => this.setState({tipAmount: value})}
keyboardType={'numeric'}
placeholder={'0'}
value={this.state.tipAmount}
style={[filePageStyle.input, filePageStyle.tipAmountInput]} />
<Text style={[filePageStyle.text, filePageStyle.currency]}>LBC</Text>
@@ -628,15 +792,26 @@ class FilePage extends React.PureComponent {
</View>}
{(this.state.showDescription && description && description.length > 0) && <View style={filePageStyle.divider} />}
{(this.state.showDescription && description) &&
<Text style={filePageStyle.description} selectable={true}>{this.linkify(description)}</Text>}
{(this.state.showDescription && description) && (
<View>
<Text style={filePageStyle.description} selectable={true}>{this.linkify(description)}</Text>
{tags && tags.length > 0 && (
<View style={filePageStyle.tagContainer}>
<Text style={filePageStyle.tagTitle}>Tags</Text>
<View style={filePageStyle.tagList}>{this.renderTags(tags)}</View>
</View>
)}
</View>)}
{(costInfo && parseFloat(costInfo.cost) > balance) && <FileRewardsDriver navigation={navigation} />}
<View onLayout={this.setRelatedContentPosition} />
<RelatedContent navigation={navigation} uri={uri} />
</ScrollView>
</View>
)}
{!this.state.fullscreenMode && <FloatingWalletBalance navigation={navigation} />}
{(!this.state.fullscreenMode && !this.state.showImageViewer && !this.state.showWebView) &&
<FloatingWalletBalance navigation={navigation} />}
</View>
);
}
+28 -2
View File
@@ -2,13 +2,26 @@ import { connect } from 'react-redux';
import { doToast } from 'lbry-redux';
import {
doAuthenticate,
doCheckSync,
doGetSync,
doSetDefaultAccount,
doSyncApply,
doUserEmailNew,
doUserResendVerificationEmail,
selectAuthToken,
selectEmailNewErrorMessage,
selectEmailNewIsPending,
selectEmailToVerify,
selectAuthenticationIsPending
selectAuthenticationIsPending,
selectHasSyncedWallet,
selectGetSyncIsPending,
selectSyncApplyIsPending,
selectSyncApplyErrorMessage,
selectSyncData,
selectSyncHash,
selectUser,
} from 'lbryinc';
import { doSetClientSetting } from 'redux/actions/settings';
import FirstRun from './view';
const select = (state) => ({
@@ -17,12 +30,25 @@ const select = (state) => ({
emailToVerify: selectEmailToVerify(state),
emailNewErrorMessage: selectEmailNewErrorMessage(state),
emailNewPending: selectEmailNewIsPending(state),
hasSyncedWallet: selectHasSyncedWallet(state),
getSyncIsPending: selectGetSyncIsPending(state),
syncApplyErrorMessage: selectSyncApplyErrorMessage(state),
syncApplyIsPending: selectSyncApplyIsPending(state),
syncHash: selectSyncHash(state),
syncData: selectSyncData(state),
user: selectUser(state),
});
const perform = dispatch => ({
addUserEmail: email => dispatch(doUserEmailNew(email)),
authenticate: (appVersion, os) => dispatch(doAuthenticate(appVersion, os)),
notify: data => dispatch(doToast(data))
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
syncApply: (hash, data, password) => dispatch(doSyncApply(hash, data, password)),
getSync: password => dispatch(doGetSync(password)),
checkSync: () => dispatch(doCheckSync()),
setDefaultAccount: () => dispatch(doSetDefaultAccount()),
notify: data => dispatch(doToast(data)),
resendVerificationEmail: email => dispatch(doUserResendVerificationEmail(email))
});
export default connect(select, perform)(FirstRun);
@@ -1,69 +1,37 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
AsyncStorage,
Linking,
NativeModules,
Platform,
Text,
TextInput,
View
} from 'react-native';
import Colors from '../../../styles/colors';
import Constants from '../../../constants';
import firstRunStyle from '../../../styles/firstRun';
import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors';
import Constants from 'constants';
import firstRunStyle from 'styles/firstRun';
class EmailCollectPage extends React.PureComponent {
static MAX_STATUS_TRIES = 30;
state = {
email: null,
authenticationStarted: false,
authenticationFailed: false,
placeholder: 'you@example.com',
statusTries: 0
verifying: true
};
componentWillReceiveProps(nextProps) {
const { authenticating, authToken } = this.props;
const { showNextPage } = this.props;
const { user } = nextProps;
if (this.state.authenticationStarted && !authenticating && authToken === null) {
this.setState({ authenticationFailed: true, authenticationStarted: false });
}
}
componentDidMount() {
// call user/new
const { generateAuthToken, authenticating, authToken } = this.props;
if (!authToken && !authenticating) {
this.startAuthenticating();
}
AsyncStorage.getItem('firstRunEmail').then(email => {
if (email) {
this.setState({ email });
}
});
}
startAuthenticating = () => {
const { authenticate } = this.props;
this.setState({ authenticationStarted: true, authenticationFailed: false });
NativeModules.VersionInfo.getAppVersion().then(appVersion => {
Lbry.status().then(info => {
authenticate(appVersion, Platform.OS)
}).catch(error => {
if (this.state.statusTries >= EmailCollectPage.MAX_STATUS_TRIES) {
this.setState({ authenticationFailed: true });
} else {
setTimeout(() => {
this.startAuthenticating();
this.setState({ statusTries: this.state.statusTries + 1 });
}, 1000); // Retry every second for a maximum of MAX_STATUS_TRIES tries (30 seconds)
if (this.state.verifying) {
if (user && user.primary_email && user.has_verified_email) {
if (showNextPage) {
showNextPage();
}
});
});
} else {
this.setState({ verifying: false });
}
}
}
handleChangeText = (text) => {
@@ -78,49 +46,32 @@ class EmailCollectPage extends React.PureComponent {
}
render() {
const { authenticating, authToken, onEmailChanged, onEmailViewLayout, emailToVerify } = this.props;
const { onEmailViewLayout } = this.props;
let content;
if (this.state.authenticationFailed) {
// Ask the user to try again
content = (
<View>
<Text style={firstRunStyle.paragraph}>The LBRY servers were unreachable at this time. Please check your Internet connection and then restart the app to try again.</Text>
</View>
);
} else if (!authToken || authenticating) {
content = (
<View>
<ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} />
<Text style={firstRunStyle.paragraph}>Please wait while we get some things ready...</Text>
</View>
);
} else {
content = (
<View onLayout={onEmailViewLayout}>
<Text style={firstRunStyle.title}>Rewards.</Text>
<Text style={firstRunStyle.paragraph}>You can earn LBRY Credits (LBC) rewards by completing various tasks in the app.</Text>
<Text style={firstRunStyle.paragraph}>Please provide a valid email address below to be able to claim your rewards.</Text>
<TextInput style={firstRunStyle.emailInput}
placeholder={this.state.placeholder}
underlineColorAndroid="transparent"
value={this.state.email}
onChangeText={text => this.handleChangeText(text)}
onFocus={() => {
if (!this.state.email || this.state.email.length === 0) {
this.setState({ placeholder: '' });
}
}}
onBlur={() => {
if (!this.state.email || this.state.email.length === 0) {
this.setState({ placeholder: 'you@example.com' });
}
}}
/>
<Text style={firstRunStyle.infoParagraph}>This information is disclosed only to LBRY, Inc. and not to the LBRY network. It is only required to earn LBRY rewards and may be used to sync usage data across devices.</Text>
</View>
);
}
const content = (
<View onLayout={onEmailViewLayout}>
<Text style={firstRunStyle.title}>Setup account</Text>
<TextInput style={firstRunStyle.emailInput}
placeholder={this.state.placeholder}
underlineColorAndroid="transparent"
selectionColor={Colors.NextLbryGreen}
value={this.state.email}
onChangeText={text => this.handleChangeText(text)}
onFocus={() => {
if (!this.state.email || this.state.email.length === 0) {
this.setState({ placeholder: '' });
}
}}
onBlur={() => {
if (!this.state.email || this.state.email.length === 0) {
this.setState({ placeholder: 'you@example.com' });
}
}}
/>
<Text style={firstRunStyle.paragraph}>An account will allow you to earn rewards and keep your account and settings synced.</Text>
<Text style={firstRunStyle.infoParagraph}>This information is disclosed only to LBRY, Inc. and not to the LBRY network.</Text>
</View>
);
return (
<View style={firstRunStyle.container}>
@@ -0,0 +1,50 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
Linking,
NativeModules,
Platform,
Switch,
Text,
TextInput,
View
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Button from 'component/button';
import Colors from 'styles/colors';
import Constants from 'constants';
import Icon from 'react-native-vector-icons/FontAwesome5';
import firstRunStyle from 'styles/firstRun';
class EmailVerifyPage extends React.PureComponent {
onResendPressed = () => {
const { email, notify, resendVerificationEmail } = this.props;
resendVerificationEmail(email);
AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'true');
notify({ message: 'Please follow the instructions in the email sent to your address to continue.' });
}
render() {
const { onEmailViewLayout, email } = this.props;
const content = (
<View onLayout={onEmailViewLayout}>
<Text style={firstRunStyle.title}>Verify Email</Text>
<Text style={firstRunStyle.paragraph}>An email has been sent to <Text style={firstRunStyle.nowrap} numberOfLines={1}>{email}</Text>. Please follow the instructions in the message to verify your email address.</Text>
<View style={firstRunStyle.buttonContainer}>
<Button style={firstRunStyle.verificationButton} theme={"light"} text={"Resend"} onPress={this.onResendPressed} />
</View>
</View>
);
return (
<View style={firstRunStyle.container}>
{content}
</View>
);
}
}
export default EmailVerifyPage;
@@ -0,0 +1,52 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
AsyncStorage,
Linking,
NativeModules,
Platform,
Switch,
Text,
TextInput,
View
} from 'react-native';
import Colors from 'styles/colors';
import Constants from 'constants';
import Icon from 'react-native-vector-icons/FontAwesome5';
import firstRunStyle from 'styles/firstRun';
class SkipAccountPage extends React.PureComponent {
state = {
confirmed: false
};
render() {
const { onSkipAccountViewLayout, onSkipSwitchChanged } = this.props;
const content = (
<View onLayout={onSkipAccountViewLayout}>
<View style={firstRunStyle.row}>
<Icon name="exclamation-triangle" style={firstRunStyle.titleIcon} size={32} color={Colors.White} />
<Text style={firstRunStyle.title}>Are you sure?</Text>
</View>
<Text style={firstRunStyle.paragraph}>Without an account, you will not receive rewards, sync and backup services, or security updates.</Text>
<View style={[firstRunStyle.row, firstRunStyle.confirmContainer]}>
<View style={firstRunStyle.rowSwitch}>
<Switch value={this.state.confirmed} onValueChange={value => { this.setState({ confirmed: value }); onSkipSwitchChanged(value); }} />
</View>
<Text style={firstRunStyle.rowParagraph}>I understand that by uninstalling LBRY I will lose any balances or published content with no recovery option.</Text>
</View>
</View>
);
return (
<View style={firstRunStyle.container}>
{content}
</View>
);
}
}
export default SkipAccountPage;
@@ -0,0 +1,134 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
Dimensions,
Linking,
NativeModules,
Platform,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native';
import { BarPasswordStrengthDisplay } from 'react-native-password-strength-meter';
import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors';
import Constants from 'constants';
import firstRunStyle from 'styles/firstRun';
import Icon from 'react-native-vector-icons/FontAwesome5';
const firstRunMargins = 80;
class WalletPage extends React.PureComponent {
state = {
password: null,
placeholder: 'password',
statusTries: 0,
walletReady: false,
hasCheckedSync: false,
revealPassword: false
};
componentDidMount() {
this.checkWalletReady();
}
checkWalletReady = () => {
// make sure the sdk wallet component is ready
Lbry.status().then(status => {
if (status.startup_status && status.startup_status.wallet) {
this.setState({ walletReady: true }, () => {
this.props.checkSync();
setTimeout(() => this.setState({ hasCheckedSync: true}), 1000);
});
return;
}
setTimeout(this.checkWalletReady, 1000);
}).catch((e) => {
setTimeout(this.checkWalletReady, 1000);
});
}
handleChangeText = (text) => {
// save the value to the state email
const { onPasswordChanged } = this.props;
this.setState({ password: text });
if (onPasswordChanged) {
onPasswordChanged(text);
}
}
render() {
const { onPasswordChanged, onWalletViewLayout, getSyncIsPending, hasSyncedWallet, syncApplyIsPending } = this.props;
let content;
if (!this.state.walletReady || !this.state.hasCheckedSync || getSyncIsPending) {
content = (
<View style={firstRunStyle.centered}>
<ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} />
<Text style={firstRunStyle.paragraph}>Retrieving your account information...</Text>
</View>
);
} else if (syncApplyIsPending) {
content = (
<View style={firstRunStyle.centered}>
<ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} />
<Text style={firstRunStyle.paragraph}>Validating password...</Text>
</View>
);
} else {
content = (
<View onLayout={onWalletViewLayout}>
<Text style={firstRunStyle.title}>Password</Text>
<Text style={firstRunStyle.paragraph}>
{hasSyncedWallet ? "Please enter the password you used to secure your wallet." :
"Please enter a password to secure your account and wallet."}
</Text>
<View style={firstRunStyle.passwordInputContainer}>
<TextInput style={firstRunStyle.passwordInput}
placeholder={this.state.placeholder}
underlineColorAndroid="transparent"
selectionColor={Colors.NextLbryGreen}
secureTextEntry={!this.state.revealPassword}
value={this.state.password}
onChangeText={text => this.handleChangeText(text)}
onFocus={() => {
if (!this.state.password || this.state.password.length === 0) {
this.setState({ placeholder: '' });
}
}}
onBlur={() => {
if (!this.state.password || this.state.password.length === 0) {
this.setState({ placeholder: 'password' });
}
}}
/>
<TouchableOpacity
style={firstRunStyle.revealPasswordIcon}
onPress={() => this.setState({ revealPassword: !this.state.revealPassword })}>
<Icon name={this.state.revealPassword ? "eye-slash" : "eye"} size={16} style={firstRunStyle.revealIcon} />
</TouchableOpacity>
</View>
{(!hasSyncedWallet && this.state.password && this.state.password.trim().length) > 0 &&
<View style={firstRunStyle.passwordStrength}>
<BarPasswordStrengthDisplay
width={Dimensions.get('window').width - firstRunMargins}
minLength={1}
password={this.state.password} />
</View>}
<Text style={firstRunStyle.infoParagraph}>Note: for wallet security purposes, LBRY is unable to reset your password.</Text>
</View>
);
}
return (
<View style={firstRunStyle.container}>
{content}
</View>
);
}
}
export default WalletPage;
+98 -8
View File
@@ -1,18 +1,108 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import { View, Text, Linking } from 'react-native';
import Colors from '../../../styles/colors';
import firstRunStyle from '../../../styles/firstRun';
import {
ActivityIndicator,
NativeModules,
Platform,
Text,
View
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors';
import Constants from 'constants';
import firstRunStyle from 'styles/firstRun';
class WelcomePage extends React.PureComponent {
static MAX_STATUS_TRIES = 60;
state = {
authenticationStarted: false,
authenticationFailed: false,
sdkStarted: false,
statusTries: 0,
};
componentWillReceiveProps(nextProps) {
const { authenticating, authToken } = this.props;
if (this.state.authenticationStarted && !authenticating) {
if (authToken === null) {
this.setState({ authenticationFailed: true, authenticationStarted: false });
} else {
// first_user_auth because it's the first time
AsyncStorage.getItem(Constants.KEY_FIRST_USER_AUTH).then(firstUserAuth => {
if ('true' !== firstUserAuth) {
// first_user_auth
NativeModules.Firebase.track('first_user_auth', null);
AsyncStorage.setItem(Constants.KEY_FIRST_USER_AUTH, 'true');
}
});
}
}
}
componentDidMount() {
// call user/new
const { generateAuthToken, authenticating, authToken } = this.props;
if (!authenticating) {
this.startAuthenticating();
}
}
startAuthenticating = () => {
const { authenticate } = this.props;
this.setState({ authenticationStarted: true, authenticationFailed: false });
NativeModules.VersionInfo.getAppVersion().then(appVersion => {
Lbry.status().then(info => {
this.setState({ sdkStarted: true });
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)
}
});
});
}
render() {
const { authenticating, authToken, onWelcomePageLayout } = this.props;
let content;
if (this.state.authenticationFailed) {
// Ask the user to try again
content = (
<View>
<Text style={firstRunStyle.paragraph}>The LBRY servers were unreachable at this time. Please check your Internet connection and then restart the app to try again.</Text>
</View>
);
} else if (!authToken || authenticating) {
content = (
<View style={firstRunStyle.centered}>
<ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} />
<Text style={firstRunStyle.paragraph}>Please wait while we get some things ready...</Text>
</View>
);
} else {
content = (
<View onLayout={onWelcomePageLayout}>
<Text style={firstRunStyle.title}>Welcome to LBRY.</Text>
<Text style={firstRunStyle.paragraph}>LBRY is a community-controlled content platform where you can find and publish videos, music, books, and more.</Text>
</View>
);
}
return (
<View style={firstRunStyle.container}>
<Text style={firstRunStyle.title}>Welcome to LBRY.</Text>
<Text style={firstRunStyle.paragraph}>LBRY is a decentralized peer-to-peer content sharing platform where
you can upload and download videos, music, ebooks and other forms of digital content.</Text>
<Text style={firstRunStyle.paragraph}>We make use of a blockchain which needs to be synchronized before
you can use the app. Synchronization may take a while because this is the first app launch.</Text>
{content}
</View>
);
}
+219 -45
View File
@@ -2,7 +2,6 @@ import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
AsyncStorage,
Linking,
NativeModules,
Text,
@@ -10,25 +9,37 @@ import {
View
} from 'react-native';
import { NavigationActions, StackActions } from 'react-navigation';
import Colors from '../../styles/colors';
import Constants from '../../constants';
import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors';
import Constants from 'constants';
import WalletPage from './internal/wallet-page';
import WelcomePage from './internal/welcome-page';
import EmailCollectPage from './internal/email-collect-page';
import firstRunStyle from '../../styles/firstRun';
import EmailVerifyPage from './internal/email-verify-page';
import SkipAccountPage from './internal/skip-account-page';
import firstRunStyle from 'styles/firstRun';
class FirstRunScreen extends React.PureComponent {
static pages = [
'welcome',
'email-collect'
Constants.FIRST_RUN_PAGE_WELCOME,
Constants.FIRST_RUN_PAGE_EMAIL_COLLECT,
Constants.FIRST_RUN_PAGE_EMAIL_VERIFY,
Constants.FIRST_RUN_PAGE_WALLET,
Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT,
];
state = {
currentPage: null,
email: null,
emailSubmitted: false,
isFirstRun: false,
launchUrl: null,
showSkip: false,
showBottomContainer: true
isEmailVerified: false,
skipAccountConfirmed: false,
showBottomContainer: false,
walletPassword: null,
syncApplyStarted: false
};
componentDidMount() {
@@ -55,18 +66,48 @@ class FirstRunScreen extends React.PureComponent {
}
componentWillReceiveProps(nextProps) {
const { emailNewErrorMessage, emailNewPending } = nextProps;
const { notify } = this.props;
const { emailNewErrorMessage, emailNewPending, syncApplyErrorMessage, syncApplyIsPending, user } = nextProps;
const { notify, isApplyingSync, setClientSetting, setDefaultAccount } = this.props;
if (this.state.emailSubmitted && !emailNewPending) {
this.setState({ emailSubmitted: false });
if (emailNewErrorMessage) {
if (emailNewErrorMessage && emailNewErrorMessage.trim().length > 0) {
notify ({ message: String(emailNewErrorMessage), isError: true });
} else {
// Request successful. Navigate to discover.
// Request successful. Navigate to email verify page.
this.showPage(Constants.FIRST_RUN_PAGE_EMAIL_VERIFY)
}
}
if (this.state.syncApplyStarted && !syncApplyIsPending) {
this.setState({ syncApplyStarted: false });
if (syncApplyErrorMessage && syncApplyErrorMessage.trim().length > 0) {
notify({ message: syncApplyErrorMessage, isError: true });
this.setState({ showBottomContainer: true });
} else {
// password successfully verified
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.setSecureValue(Constants.KEY_FIRST_RUN_PASSWORD, this.state.walletPassword);
}
setDefaultAccount();
setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, true);
this.closeFinalPage();
}
}
this.checkVerificationStatus(user);
}
checkVerificationStatus = (user) => {
const { navigation } = this.props;
this.setState({
isEmailVerified: (user && user.primary_email && user.has_verified_email),
}, () => {
if (this.state.isEmailVerified) {
this.showPage(Constants.FIRST_RUN_PAGE_WALLET);
}
});
}
launchSplashScreen() {
@@ -80,14 +121,57 @@ class FirstRunScreen extends React.PureComponent {
navigation.dispatch(resetAction);
}
handleLeftButtonPressed = () => {
// Go to setup account page when "Setup account" is pressed
if (Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage) {
return this.showPage(Constants.FIRST_RUN_PAGE_EMAIL_COLLECT);
}
// Go to skip account page when "No, thanks" is pressed
if (Constants.FIRST_RUN_PAGE_EMAIL_COLLECT === this.state.currentPage) {
this.showPage(Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT);
}
// Go to email collection page if user cancels from email verification
if (Constants.FIRST_RUN_PAGE_EMAIL_VERIFY === this.state.currentPage) {
this.showPage(Constants.FIRST_RUN_PAGE_EMAIL_COLLECT);
}
}
checkWalletPassword = () => {
const { syncApply, syncHash, syncData } = this.props;
this.setState({ syncApplyStarted: true, showBottomContainer: false }, () => {
syncApply(syncHash, syncData, this.state.walletPassword);
});
}
handleContinuePressed = () => {
const { notify, user, hasSyncedWallet } = this.props;
const pageIndex = FirstRunScreen.pages.indexOf(this.state.currentPage);
if (this.state.currentPage !== 'email-collect' &&
pageIndex === (FirstRunScreen.pages.length - 1)) {
if (Constants.FIRST_RUN_PAGE_WALLET === this.state.currentPage) {
if (!this.state.walletPassword || this.state.walletPassword.trim().length === 0) {
return notify({ message: 'Please enter a wallet password' });
}
// do apply sync to check if the password is valid
if (hasSyncedWallet) {
this.checkWalletPassword();
} else {
this.setFreshPassword();
}
return;
}
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.' });
return;
}
if (Constants.FIRST_RUN_PAGE_EMAIL_COLLECT !== this.state.currentPage && pageIndex === (FirstRunScreen.pages.length - 1)) {
this.closeFinalPage();
} else {
// TODO: Actions and page verification for specific pages
if (this.state.currentPage === 'email-collect') {
if (Constants.FIRST_RUN_PAGE_EMAIL_COLLECT === this.state.currentPage) {
// handle email collect
this.handleEmailCollectPageContinue();
} else {
@@ -98,21 +182,10 @@ class FirstRunScreen extends React.PureComponent {
handleEmailCollectPageContinue() {
const { notify, addUserEmail } = this.props;
const pageIndex = FirstRunScreen.pages.indexOf(this.state.currentPage);
AsyncStorage.getItem(Constants.KEY_FIRST_RUN_EMAIL).then(email => {
if (!email || email.trim().length === 0) {
// no email provided. Skip.
if (this.state.currentPage === 'email-collect' && pageIndex === (FirstRunScreen.pages.length - 1)) {
this.closeFinalPage();
} else {
this.showNextPage();
}
return;
}
// validate the email
if (email.indexOf('@') === -1) {
if (!email || email.indexOf('@') === -1) {
return notify({
message: 'Please provide a valid email address to continue.',
});
@@ -123,13 +196,25 @@ class FirstRunScreen extends React.PureComponent {
});
}
showNextPage() {
checkBottomContainer = (pageName) => {
if (Constants.FIRST_RUN_PAGE_EMAIL_COLLECT === pageName || Constants.FIRST_RUN_PAGE_WALLET === pageName) {
// do not show the buttons (because we're waiting to get things ready)
this.setState({ showBottomContainer: false });
}
}
showNextPage = () => {
const pageIndex = FirstRunScreen.pages.indexOf(this.state.currentPage);
const nextPage = FirstRunScreen.pages[pageIndex + 1];
this.setState({ currentPage: nextPage });
if (nextPage === 'email-collect') {
// do not show the buttons (because we're waiting to get things ready)
this.setState({ showBottomContainer: false });
this.checkBottomContainer(nextPage);
}
showPage(pageName) {
const pageIndex = FirstRunScreen.pages.indexOf(pageName);
if (pageIndex > -1) {
this.setState({ currentPage: pageName });
this.checkBottomContainer(pageName);
}
}
@@ -144,7 +229,8 @@ class FirstRunScreen extends React.PureComponent {
}
onEmailChanged = (email) => {
if ('email-collect' == this.state.currentPage) {
this.setState({ email });
if (Constants.FIRST_RUN_PAGE_EMAIL_COLLECT == this.state.currentPage) {
this.setState({ showSkip: (!email || email.trim().length === 0) });
} else {
this.setState({ showSkip: false });
@@ -158,26 +244,95 @@ class FirstRunScreen extends React.PureComponent {
});
}
onWalletPasswordChanged = (password) => {
this.setState({ walletPassword: password });
}
onWalletViewLayout = () => {
this.setState({ showBottomContainer: true });
}
onWelcomePageLayout = () => {
this.setState({ showBottomContainer: true });
}
onSkipSwitchChanged = (checked) => {
this.setState({ skipAccountConfirmed: checked });
}
setFreshPassword = () => {
const { getSync, setClientSetting } = this.props;
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.setSecureValue(Constants.KEY_FIRST_RUN_PASSWORD, this.state.walletPassword);
Lbry.account_encrypt({ new_password: this.state.walletPassword }).then(() => {
Lbry.account_unlock({ password: this.state.walletPassword }).then(() => {
// fresh account, new password set
getSync(this.state.walletPassword);
setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, true);
this.closeFinalPage();
});
});
}
}
render() {
const {
authenticate,
authenticating,
authToken,
checkSync,
emailNewErrorMessage,
emailNewPending,
emailToVerify
emailToVerify,
notify,
hasSyncedWallet,
getSyncIsPending,
syncApplyIsPending,
resendVerificationEmail,
user
} = this.props;
let page = null;
if (this.state.currentPage === 'welcome') {
// show welcome page
page = (<WelcomePage />);
} else if (this.state.currentPage === 'email-collect') {
page = (<EmailCollectPage authenticating={authenticating}
authToken={authToken}
authenticate={authenticate}
onEmailChanged={this.onEmailChanged}
onEmailViewLayout={this.onEmailViewLayout} />);
switch (this.state.currentPage) {
case Constants.FIRST_RUN_PAGE_WELCOME:
page = (<WelcomePage
authenticating={authenticating}
authToken={authToken}
authenticate={authenticate}
onWelcomePageLayout={this.onWelcomePageLayout} />);
break;
case Constants.FIRST_RUN_PAGE_EMAIL_COLLECT:
page = (<EmailCollectPage
user={user}
showNextPage={this.showNextPage}
onEmailChanged={this.onEmailChanged}
onEmailViewLayout={this.onEmailViewLayout} />);
break;
case Constants.FIRST_RUN_PAGE_EMAIL_VERIFY:
page = (<EmailVerifyPage
onEmailViewLayout={this.onEmailViewLayout}
email={this.state.email}
notify={notify}
resendVerificationEmail={resendVerificationEmail} />);
break;
case Constants.FIRST_RUN_PAGE_WALLET:
page = (<WalletPage
checkSync={checkSync}
hasSyncedWallet={hasSyncedWallet}
getSyncIsPending={getSyncIsPending}
syncApplyIsPending={syncApplyIsPending}
onWalletViewLayout={this.onWalletViewLayout}
onPasswordChanged={this.onWalletPasswordChanged} />);
break;
case Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT:
page = (<SkipAccountPage
onSkipAccountViewLayout={this.onSkipAccountViewLayout}
onSkipSwitchChanged={this.onSkipSwitchChanged} />);
break;
}
return (
@@ -188,10 +343,29 @@ class FirstRunScreen extends React.PureComponent {
{emailNewPending &&
<ActivityIndicator size="small" color={Colors.White} style={firstRunStyle.pageWaiting} />}
{!emailNewPending &&
<TouchableOpacity style={firstRunStyle.button} onPress={this.handleContinuePressed}>
<Text style={firstRunStyle.buttonText}>{this.state.showSkip ? 'Skip': 'Continue'}</Text>
</TouchableOpacity>}
<View style={firstRunStyle.buttonRow}>
{([Constants.FIRST_RUN_PAGE_WELCOME, Constants.FIRST_RUN_PAGE_WALLET].indexOf(this.state.currentPage) > -1) && <View />}
{(Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage ||
Constants.FIRST_RUN_PAGE_EMAIL_VERIFY === this.state.currentPage) &&
<TouchableOpacity style={firstRunStyle.leftButton} onPress={this.handleLeftButtonPressed}>
<Text style={firstRunStyle.buttonText}>
« {Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage ? 'Setup account' : 'Change email'}</Text>
</TouchableOpacity>}
{!emailNewPending && (Constants.FIRST_RUN_PAGE_EMAIL_COLLECT === this.state.currentPage) &&
<TouchableOpacity style={firstRunStyle.leftButton} onPress={this.handleLeftButtonPressed}>
<Text style={firstRunStyle.smallLeftButtonText}>No, thanks »</Text>
</TouchableOpacity>}
{!emailNewPending &&
<TouchableOpacity style={firstRunStyle.button} onPress={this.handleContinuePressed}>
{Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT === this.state.currentPage &&
<Text style={firstRunStyle.smallButtonText}>Use LBRY »</Text>}
{Constants.FIRST_RUN_PAGE_SKIP_ACCOUNT !== this.state.currentPage &&
Constants.FIRST_RUN_PAGE_EMAIL_VERIFY !== this.state.currentPage &&
<Text style={firstRunStyle.buttonText}>{Constants.FIRST_RUN_PAGE_WALLET === this.state.currentPage ? 'Use LBRY' : 'Continue'} »</Text>}
</TouchableOpacity>}
</View>
</View>}
</View>
);
+8 -3
View File
@@ -1,5 +1,6 @@
import { connect } from 'react-redux';
import {
doClaimRewardType,
doRewardList,
selectEmailVerifyErrorMessage,
selectEmailVerifyIsPending,
@@ -9,23 +10,27 @@ import {
selectUser,
} from 'lbryinc';
import { doToast } from 'lbry-redux';
import { doPushDrawerStack } from 'redux/actions/drawer';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectCurrentRoute } from 'redux/selectors/drawer';
import Constants from 'constants';
import RewardsPage from './view';
const select = state => ({
claimed: selectClaimedRewards(state),
currentRoute: selectCurrentRoute(state),
emailVerifyErrorMessage: selectEmailVerifyErrorMessage(state),
emailVerifyPending: selectEmailVerifyIsPending(state),
fetching: selectFetchingRewards(state),
rewards: selectUnclaimedRewards(state),
claimed: selectClaimedRewards(state),
user: selectUser(state),
});
const perform = dispatch => ({
claimReward: reward => dispatch(doClaimRewardType(reward.reward_type, true)),
fetchRewards: () => dispatch(doRewardList()),
notify: data => dispatch(doToast(data)),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_REWARDS))
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_REWARDS)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false))
});
export default connect(select, perform)(RewardsPage);
+67 -27
View File
@@ -8,12 +8,12 @@ import {
View
} from 'react-native';
import Colors from 'styles/colors';
import Constants from 'constants';
import Link from 'component/link';
import CustomRewardCard from 'component/customRewardCard';
import PhoneNumberRewardSubcard from 'component/phoneNumberRewardSubcard';
import EmailRewardSubcard from 'component/emailRewardSubcard';
import PageHeader from 'component/pageHeader';
import RewardCard from 'component/rewardCard';
import RewardEnrolment from 'component/rewardEnrolment';
import RewardSummary from 'component/rewardSummary';
import UriBar from 'component/uriBar';
import rewardStyle from 'styles/reward';
@@ -24,12 +24,30 @@ class RewardsPage extends React.PureComponent {
isIdentityVerified: false,
isRewardApproved: false,
verifyRequestStarted: false,
revealVerification: true,
firstRewardClaimed: false
};
componentDidMount() {
const { fetchRewards, pushDrawerStack, navigation, user } = this.props;
scrollView = null;
didFocusListener;
componentWillMount() {
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
componentWillUnmount() {
if (this.didFocusListener) {
this.didFocusListener.remove();
}
}
onComponentFocused = () => {
const { fetchRewards, pushDrawerStack, navigation, setPlayerVisible, user } = this.props;
pushDrawerStack();
setPlayerVisible();
fetchRewards();
this.setState({
@@ -39,8 +57,18 @@ class RewardsPage extends React.PureComponent {
});
}
componentDidMount() {
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { emailVerifyErrorMessage, emailVerifyPending, user } = nextProps;
const { currentRoute, emailVerifyErrorMessage, emailVerifyPending, rewards, user } = nextProps;
const { claimReward, currentRoute: prevRoute } = this.props;
if (Constants.DRAWER_ROUTE_REWARDS === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
if (emailVerifyPending) {
this.setState({ verifyRequestStarted: true });
}
@@ -60,6 +88,17 @@ class RewardsPage extends React.PureComponent {
isRewardApproved: (user && user.is_reward_approved)
});
}
if (rewards && rewards.length && this.state.isRewardApproved && !this.state.firstRewardClaimed) {
// claim new_user and new_mobile rewards
for (let i = 0; i < rewards.length; i++) {
const { reward_type: type } = rewards[i];
if ('new_user' === type || 'new_mobile' === type) {
claimReward(rewards[i]);
}
}
this.setState({ firstRewardClaimed: true });
}
}
renderVerification() {
@@ -67,23 +106,12 @@ class RewardsPage extends React.PureComponent {
return null;
}
if (!this.state.isEmailVerified || !this.state.isIdentityVerified) {
return (
<View style={[rewardStyle.card, rewardStyle.verification]}>
<Text style={rewardStyle.title}>Humans Only</Text>
<Text style={rewardStyle.text}>Rewards are for human beings only. You'll have to prove you're one of us before you can claim any rewards.</Text>
{!this.state.isEmailVerified && <EmailRewardSubcard />}
{!this.state.isIdentityVerified && <PhoneNumberRewardSubcard />}
</View>
);
}
if (this.state.isEmailVerified && this.state.isIdentityVerified && !this.state.isRewardApproved) {
return (
<View style={[rewardStyle.card, rewardStyle.verification]}>
<Text style={rewardStyle.title}>Manual Reward Verification</Text>
<Text style={rewardStyle.text}>
You need to be manually verified before you can start claiming rewards. Please request to be verified on the <Link style={rewardStyle.textLink} href="https://discordapp.com/invite/Z3bERWA" text="LBRY Discord server" />.
You need to be manually verified before you can start claiming rewards. Please request to be verified on the <Link style={rewardStyle.greenLink} href="https://discordapp.com/invite/Z3bERWA" text="LBRY Discord server" />.
</Text>
</View>
);
@@ -115,10 +143,11 @@ class RewardsPage extends React.PureComponent {
return (
<View>
{unclaimedRewards.map(reward => <RewardCard key={reward.reward_type}
showVerification={this.showVerification}
canClaim={!isNotEligible}
reward={reward}
reward_type={reward.reward_type} />)}
<CustomRewardCard canClaim={!isNotEligible} />
<CustomRewardCard canClaim={!isNotEligible} showVerification={this.showVerification} />
</View>
);
}
@@ -135,21 +164,32 @@ class RewardsPage extends React.PureComponent {
}
}
showVerification = () => {
this.setState({ revealVerification: true }, () => {
if (this.scrollView) {
this.scrollView.scrollTo({ x: 0, y: 0, animated: true });
}
});
}
render() {
const { user, navigation } = this.props;
return (
<View style={rewardStyle.container}>
<UriBar navigation={navigation} />
<ScrollView
keyboardShouldPersistTaps={'handled'}
style={rewardStyle.scrollContainer}
contentContainerStyle={rewardStyle.scrollContentContainer}>
<RewardSummary navigation={navigation} />
{this.renderVerification()}
{this.renderUnclaimedRewards()}
{this.renderClaimedRewards()}
</ScrollView>
{(!this.state.isEmailVerified || !this.state.isRewardApproved) &&
<RewardEnrolment navigation={navigation} />}
{(this.state.isEmailVerified && this.state.isRewardApproved) &&
<ScrollView
ref={ref => this.scrollView = ref}
keyboardShouldPersistTaps={'handled'}
style={rewardStyle.scrollContainer}
contentContainerStyle={rewardStyle.scrollContentContainer}>
{this.renderUnclaimedRewards()}
{this.renderClaimedRewards()}
</ScrollView>}
</View>
);
}
+4 -1
View File
@@ -8,11 +8,13 @@ import {
makeSelectQueryWithOptions,
selectSearchUrisByQuery
} from 'lbry-redux';
import { doPushDrawerStack } from 'redux/actions/drawer';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectCurrentRoute } from 'redux/selectors/drawer';
import Constants from 'constants';
import SearchPage from './view';
const select = (state) => ({
currentRoute: selectCurrentRoute(state),
isSearching: selectIsSearching(state),
query: selectSearchValue(state),
uris: makeSelectSearchUris(makeSelectQueryWithOptions(null, 25)(state))(state),
@@ -23,6 +25,7 @@ const perform = dispatch => ({
search: (query) => dispatch(doSearch(query, 25)),
updateSearchQuery: query => dispatch(doUpdateSearchQuery(query)),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_SEARCH)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false))
});
export default connect(select, perform)(SearchPage);
+61 -12
View File
@@ -10,6 +10,7 @@ import {
} from 'react-native';
import { navigateToUri } from 'utils/helper';
import Colors from 'styles/colors';
import Constants from 'constants';
import PageHeader from 'component/pageHeader';
import FileListItem from 'component/fileListItem';
import FloatingWalletBalance from 'component/floatingWalletBalance';
@@ -18,24 +19,69 @@ import searchStyle from 'styles/search';
class SearchPage extends React.PureComponent {
state = {
currentUri: null
currentQuery: null,
currentUri: null,
}
static navigationOptions = {
title: 'Search Results'
};
didFocusListener;
componentWillMount() {
this.props.pushDrawerStack();
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
componentWillUnmount() {
if (this.didFocusListener) {
this.didFocusListener.remove();
}
}
onComponentFocused = () => {
const { pushDrawerStack, setPlayerVisible, query, search } = this.props;
pushDrawerStack();
setPlayerVisible();
const searchQuery = query || this.getSearchQuery();
if (searchQuery && searchQuery.trim().length > 0) {
this.setState({
currentQuery: searchQuery,
currentUri: (isURIValid(searchQuery)) ? normalizeURI(searchQuery) : null
});
search(searchQuery);
}
}
componentDidMount() {
const { navigation, search } = this.props;
const { searchQuery } = navigation.state.params;
if (searchQuery && searchQuery.trim().length > 0) {
this.setState({ currentUri: (isURIValid(searchQuery)) ? normalizeURI(searchQuery) : null })
search(searchQuery);
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { currentRoute, query } = nextProps;
const { currentRoute: prevRoute, search } = this.props;
if (Constants.DRAWER_ROUTE_SEARCH === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
if (query && query.trim().length > 0 && query !== this.state.currentQuery) {
this.setState({
currentQuery: query,
currentUri: (isURIValid(query)) ? normalizeURI(query) : null
});
search(query);
}
}
getSearchQuery() {
const { navigation } = this.props;
if (navigation && navigation.state && navigation.state.params) {
return navigation.state.params.searchQuery;
}
return null;
}
handleSearchSubmitted = (keywords) => {
@@ -46,19 +92,18 @@ class SearchPage extends React.PureComponent {
render() {
const { isSearching, navigation, query, uris, urisByQuery } = this.props;
const { searchQuery } = navigation.state.params;
return (
<View style={searchStyle.container}>
<UriBar value={searchQuery}
<UriBar value={query}
navigation={navigation}
onSearchSubmitted={this.handleSearchSubmitted} />
{!isSearching && (!uris || uris.length === 0) &&
<Text style={searchStyle.noResultsText}>No results to display.</Text>}
{isSearching &&
<View style={searchStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.LbryGreen} style={searchStyle.loading} />
</View>}
{!isSearching &&
<ScrollView
style={searchStyle.scrollContainer}
@@ -73,13 +118,17 @@ class SearchPage extends React.PureComponent {
navigation={navigation}
onPress={() => navigateToUri(navigation, this.state.currentUri)}
/>}
{!isSearching && uris && uris.length ? (
{(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} />
</View>
+4 -2
View File
@@ -1,14 +1,15 @@
import { connect } from 'react-redux';
import { SETTINGS } from 'lbry-redux';
import { doPushDrawerStack, doPopDrawerStack } from 'redux/actions/drawer';
import { doPushDrawerStack, doPopDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { doSetClientSetting } from 'redux/actions/settings';
import { selectDrawerStack } from 'redux/selectors/drawer';
import { selectCurrentRoute, selectDrawerStack } from 'redux/selectors/drawer';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import Constants from 'constants';
import SettingsPage from './view';
const select = state => ({
backgroundPlayEnabled: makeSelectClientSetting(SETTINGS.BACKGROUND_PLAY_ENABLED)(state),
currentRoute: selectCurrentRoute(state),
drawerStack: selectDrawerStack(state),
keepDaemonRunning: makeSelectClientSetting(SETTINGS.KEEP_DAEMON_RUNNING)(state),
showNsfw: makeSelectClientSetting(SETTINGS.SHOW_NSFW)(state),
@@ -18,6 +19,7 @@ const perform = dispatch => ({
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_SETTINGS)),
popDrawerStack: () => dispatch(doPopDrawerStack()),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false)),
});
export default connect(select, perform)(SettingsPage);
+30 -2
View File
@@ -2,6 +2,7 @@ import React from 'react';
import { SETTINGS } from 'lbry-redux';
import { Text, View, ScrollView, Switch, NativeModules } from 'react-native';
import { navigateBack } from 'utils/helper';
import Constants from 'constants';
import PageHeader from 'component/pageHeader';
import settingsStyle from 'styles/settings';
@@ -10,8 +11,35 @@ class SettingsPage extends React.PureComponent {
title: 'Settings'
}
didFocusListener;
componentWillMount() {
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
componentWillUnmount() {
if (this.didFocusListener) {
this.didFocusListener.remove();
}
}
onComponentFocused = () => {
const { pushDrawerStack, setPlayerVisible } = this.props;
pushDrawerStack();
setPlayerVisible();
}
componentDidMount() {
this.props.pushDrawerStack();
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { currentRoute } = nextProps;
const { currentRoute: prevRoute } = this.props;
if (Constants.DRAWER_ROUTE_SETTINGS === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
}
render() {
@@ -29,7 +57,7 @@ class SettingsPage extends React.PureComponent {
const actualKeepDaemonRunning = (keepDaemonRunning === null || keepDaemonRunning === undefined) ? true : keepDaemonRunning;
return (
<View>
<View style={settingsStyle.container}>
<PageHeader title={"Settings"}
onBackPressed={() => navigateBack(navigation, drawerStack, popDrawerStack)} />
<ScrollView style={settingsStyle.scrollContainer}>
+4 -2
View File
@@ -6,13 +6,14 @@ import {
doCheckSubscriptionsInit,
doFetchMySubscriptions,
doFetchRewardedContent,
doGetSync,
doUserEmailToVerify,
doUserEmailVerify,
doUserEmailVerifyFailure,
selectUser,
selectEmailToVerify
} from 'lbryinc';
import { doDeleteCompleteBlobs } from 'redux/actions/file';
import { doSetClientSetting } from 'redux/actions/settings';
import SplashScreen from './view';
const select = state => ({
@@ -25,10 +26,11 @@ const perform = dispatch => ({
balanceSubscribe: () => dispatch(doBalanceSubscribe()),
blacklistedOutpointsSubscribe: () => dispatch(doBlackListedOutpointsSubscribe()),
checkSubscriptionsInit: () => dispatch(doCheckSubscriptionsInit()),
deleteCompleteBlobs: () => dispatch(doDeleteCompleteBlobs()),
fetchRewardedContent: () => dispatch(doFetchRewardedContent()),
fetchSubscriptions: (callback) => dispatch(doFetchMySubscriptions(callback)),
getSync: password => dispatch(doGetSync(password)),
notify: data => dispatch(doToast(data)),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
setEmailToVerify: email => dispatch(doUserEmailToVerify(email)),
updateBlockHeight: () => dispatch(doUpdateBlockHeight()),
verifyUserEmail: (token, recaptcha) => dispatch(doUserEmailVerify(token, recaptcha)),
+84 -66
View File
@@ -2,21 +2,22 @@ import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
AsyncStorage,
Linking,
NativeModules,
Platform,
ProgressBarAndroid,
Text,
View
} from 'react-native';
import { NavigationActions, StackActions } from 'react-navigation';
import { decode as atob } from 'base-64';
import { navigateToUri } from '../../utils/helper';
import { navigateToUri } from 'utils/helper';
import moment from 'moment';
import AsyncStorage from '@react-native-community/async-storage';
import ProgressBar from 'component/progressBar';
import PropTypes from 'prop-types';
import Colors from '../../styles/colors';
import Constants from '../../constants';
import splashStyle from '../../styles/splash';
import Colors from 'styles/colors';
import Constants from 'constants';
import splashStyle from 'styles/splash';
const BLOCK_HEIGHT_INTERVAL = 1000 * 60 * 2.5; // every 2.5 minutes
@@ -28,7 +29,7 @@ class SplashScreen extends React.PureComponent {
componentWillMount() {
this.setState({
daemonReady: false,
details: 'Starting daemon',
details: 'Starting up...',
message: 'Connecting',
isRunning: false,
isLagging: false,
@@ -44,19 +45,6 @@ class SplashScreen extends React.PureComponent {
}
}
componentDidMount() {
// Start measuring the first launch time from the splash screen (time from daemon start to user interaction)
AsyncStorage.getItem('hasLaunched').then(value => {
if (value == null || value !== 'true') {
AsyncStorage.setItem('hasLaunched', 'true');
// only set firstLaunchTime since we've determined that this is the first app launch ever
AsyncStorage.setItem('firstLaunchTime', String(moment().unix()));
}
});
this.props.fetchRewardedContent();
}
updateStatus() {
Lbry.status().then(status => {
this._updateStatusCallback(status);
@@ -114,34 +102,66 @@ class SplashScreen extends React.PureComponent {
if (this.state.daemonReady && this.state.shouldAuthenticate && user && user.id) {
this.setState({ shouldAuthenticate: false }, () => {
AsyncStorage.getItem(Constants.KEY_FIRST_RUN_EMAIL).then(email => {
if (email) {
setEmailToVerify(email);
}
// user is authenticated, navigate to the main view
/*if (user.has_verified_email) {
NativeModules.UtilityModule.getSecureValue(Constants.KEY_FIRST_RUN_PASSWORD).then(walletPassword => {
// user is authenticated, navigate to the main view
if (user.has_verified_email) {
NativeModules.UtilityModule.getSecureValue(Constants.KEY_FIRST_RUN_PASSWORD).then(walletPassword => {
if (walletPassword && walletPassword.trim().length > 0) {
getSync(walletPassword);
this.navigateToMain();
});
return;
}*/
}
this.navigateToMain();
});
return;
}
this.navigateToMain();
});
this.navigateToMain();
});
}
}
finishSplashScreen = () => {
const {
authenticate,
balanceSubscribe,
blacklistedOutpointsSubscribe,
checkSubscriptionsInit,
getSync,
navigation,
notify,
updateBlockHeight,
user
} = this.props;
Lbry.resolve({ urls: 'lbry://one' }).then(() => {
// Leave the splash screen
balanceSubscribe();
blacklistedOutpointsSubscribe();
checkSubscriptionsInit();
updateBlockHeight();
setInterval(() => { updateBlockHeight(); }, BLOCK_HEIGHT_INTERVAL);
if (user && user.id && user.has_verified_email) {
// user already authenticated
NativeModules.UtilityModule.getSecureValue(Constants.KEY_FIRST_RUN_PASSWORD).then(walletPassword => {
if (walletPassword && walletPassword.trim().length > 0) {
getSync(walletPassword);
}
this.navigateToMain();
});
} else {
NativeModules.VersionInfo.getAppVersion().then(appVersion => {
this.setState({ shouldAuthenticate: true });
authenticate(appVersion, Platform.OS);
});
}
});
}
_updateStatusCallback(status) {
const { deleteCompleteBlobs, fetchSubscriptions } = this.props;
const { fetchSubscriptions, getSync, setClientSetting } = this.props;
const startupStatus = status.startup_status;
// At the minimum, wallet should be started and blocks_behind equal to 0 before calling resolve
const hasStarted = startupStatus.stream_manager && startupStatus.wallet && status.wallet.blocks_behind <= 0;
if (hasStarted) {
deleteCompleteBlobs();
// Wait until we are able to resolve a name before declaring
// that we are done.
// TODO: This is a hack, and the logic should live in the daemon
@@ -154,28 +174,16 @@ class SplashScreen extends React.PureComponent {
isRunning: true,
});
// fetch subscriptions, so that we can check for new content after resolve
Lbry.resolve({ urls: 'lbry://one' }).then(() => {
// Leave the splash screen
const {
authenticate,
balanceSubscribe,
blacklistedOutpointsSubscribe,
checkSubscriptionsInit,
updateBlockHeight,
navigation,
notify
} = this.props;
balanceSubscribe();
blacklistedOutpointsSubscribe();
checkSubscriptionsInit();
updateBlockHeight();
setInterval(() => { updateBlockHeight(); }, BLOCK_HEIGHT_INTERVAL);
NativeModules.VersionInfo.getAppVersion().then(appVersion => {
this.setState({ shouldAuthenticate: true });
authenticate(appVersion, Platform.OS);
});
// For now, automatically unlock the wallet if a password is set so that downloads work
NativeModules.UtilityModule.getSecureValue(Constants.KEY_FIRST_RUN_PASSWORD).then(password => {
if (password && password.trim().length > 0) {
// unlock the wallet and then finish the splash screen
Lbry.account_unlock({ password }).then(() => this.finishSplashScreen()).catch(() => this.finishSplashScreen());
return;
}
this.finishSplashScreen();
});
return;
@@ -222,16 +230,27 @@ class SplashScreen extends React.PureComponent {
}
componentDidMount() {
if (NativeModules.Mixpanel) {
NativeModules.Mixpanel.track('App Launch', null);
if (NativeModules.Firebase) {
NativeModules.Firebase.track('app_launch', null);
}
this.props.fetchRewardedContent();
Linking.getInitialURL().then((url) => {
if (url) {
this.setState({ launchUrl: url });
}
});
// Start measuring the first launch time from the splash screen
// (time to first user interaction - after first run completed)
AsyncStorage.getItem('hasLaunched').then(value => {
if ('true' !== value) {
AsyncStorage.setItem('hasLaunched', 'true');
// only set firstLaunchTime since we've determined that this is the first app launch ever
AsyncStorage.setItem('firstLaunchTime', String(moment().unix()));
}
});
Lbry
.connect()
.then(() => {
@@ -253,12 +272,11 @@ class SplashScreen extends React.PureComponent {
return (
<View style={splashStyle.container}>
<Text style={splashStyle.title}>LBRY</Text>
{'android' === Platform.OS && this.state.isDownloadingHeaders &&
<ProgressBarAndroid color={Colors.White}
indeterminate={false}
styleAttr={"Horizontal"}
style={splashStyle.progress}
progress={this.state.headersDownloadProgress/100.0} />}
{this.state.isDownloadingHeaders &&
<ProgressBar
color={Colors.White}
style={splashStyle.progress}
progress={this.state.headersDownloadProgress} />}
{!this.state.isDownloadingHeaders && <ActivityIndicator color={Colors.White} style={splashStyle.loading} size={"small"} />}
<Text style={splashStyle.message}>{message}</Text>
<Text style={splashStyle.details}>{details}</Text>
+4 -1
View File
@@ -12,13 +12,15 @@ import {
selectFirstRunCompleted,
selectShowSuggestedSubs
} from 'lbryinc';
import { doPushDrawerStack } from 'redux/actions/drawer';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { doSetClientSetting } from 'redux/actions/settings';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { selectCurrentRoute } from 'redux/selectors/drawer';
import Constants from 'constants';
import SubscriptionsPage from './view';
const select = state => ({
currentRoute: selectCurrentRoute(state),
loading:
selectIsFetchingSubscriptions(state) ||
Boolean(Object.keys(selectSubscriptionsBeingFetched(state)).length),
@@ -37,6 +39,7 @@ const perform = dispatch => ({
doSetViewMode: (viewMode) => dispatch(doSetViewMode(viewMode)),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_SUBSCRIPTIONS)),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false))
});
export default connect(select, perform)(SubscriptionsPage);
+31 -6
View File
@@ -2,7 +2,6 @@ import React from 'react';
import NavigationActions from 'react-navigation';
import {
ActivityIndicator,
AsyncStorage,
FlatList,
NativeModules,
SectionList,
@@ -12,11 +11,12 @@ import {
} from 'react-native';
import { buildURI, parseURI } from 'lbry-redux';
import { uriFromFileInfo } from 'utils/helper';
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
import Button from 'component/button';
import Colors from 'styles/colors';
import Constants from 'constants';
import discoverStyle from 'styles/discover';
import fileListStyle from 'styles/fileList';
import subscriptionsStyle from 'styles/subscriptions';
import FloatingWalletBalance from 'component/floatingWalletBalance';
import FileItem from 'component/fileItem';
@@ -29,21 +29,46 @@ class SubscriptionsPage extends React.PureComponent {
showingSuggestedSubs: false
};
didFocusListener;
componentWillMount() {
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
componentWillUnmount() {
if (this.didFocusListener) {
this.didFocusListener.remove();
}
}
onComponentFocused = () => {
const {
doFetchMySubscriptions,
doFetchRecommendedSubscriptions,
doSetViewMode,
pushDrawerStack,
setPlayerVisible,
subscriptionsViewMode
} = this.props;
pushDrawerStack();
setPlayerVisible();
doFetchMySubscriptions();
doFetchRecommendedSubscriptions();
doSetViewMode(subscriptionsViewMode ? subscriptionsViewMode : Constants.SUBSCRIPTIONS_VIEW_ALL);
}
componentDidMount() {
const { doSetViewMode, subscriptionsViewMode } = this.props;
doSetViewMode(subscriptionsViewMode ? subscriptionsViewMode : Constants.SUBSCRIPTIONS_VIEW_ALL);
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { currentRoute } = nextProps;
const { currentRoute: prevRoute } = this.props;
if (Constants.FULL_ROUTE_NAME_MY_SUBSCRIPTIONS === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
}
changeViewMode = (viewMode) => {
@@ -104,7 +129,7 @@ class SubscriptionsPage extends React.PureComponent {
renderItem={ ({item}) => (
<FileItem
style={subscriptionsStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
mediaStyle={fileListStyle.fileItemMedia}
key={item}
uri={uriFromFileInfo(item)}
navigation={navigation}
@@ -128,7 +153,7 @@ class SubscriptionsPage extends React.PureComponent {
return uris.map(uri => (
<FileItem
style={subscriptionsStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
mediaStyle={fileListStyle.fileItemMedia}
key={uri}
uri={uri}
navigation={navigation}
+4 -1
View File
@@ -4,11 +4,13 @@ import {
selectTransactionItems,
selectIsFetchingTransactions,
} from 'lbry-redux';
import { doPushDrawerStack } from 'redux/actions/drawer';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectCurrentRoute } from 'redux/selectors/drawer';
import Constants from 'constants';
import TransactionHistoryPage from './view';
const select = state => ({
currentRoute: selectCurrentRoute(state),
fetchingTransactions: selectIsFetchingTransactions(state),
transactions: selectTransactionItems(state),
});
@@ -16,6 +18,7 @@ const select = state => ({
const perform = dispatch => ({
fetchTransactions: () => dispatch(doFetchTransactions()),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_TRANSACTION_HISTORY)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false))
});
export default connect(select, perform)(TransactionHistoryPage);
+27 -2
View File
@@ -1,16 +1,41 @@
import React from 'react';
import { View, ScrollView, Text } from 'react-native';
import Constants from 'constants';
import TransactionList from 'component/transactionList';
import UriBar from 'component/uriBar';
import walletStyle from 'styles/wallet';
class TransactionHistoryPage extends React.PureComponent {
didFocusListener;
componentWillMount() {
this.props.pushDrawerStack();
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
componentWillUnmount() {
if (this.didFocusListener) {
this.didFocusListener.remove();
}
}
onComponentFocused = () => {
const { fetchTransactions, pushDrawerStack, setPlayerVisible } = this.props;
pushDrawerStack();
setPlayerVisible();
fetchTransactions();
}
componentDidMount() {
this.props.fetchTransactions();
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { currentRoute } = nextProps;
const { currentRoute: prevRoute } = this.props;
if (Constants.DRAWER_ROUTE_TRANSACTION_HISTORY === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
}
render() {
+5 -2
View File
@@ -1,17 +1,20 @@
import { connect } from 'react-redux';
import { doFetchTrendingUris, selectTrendingUris, selectFetchingTrendingUris } from 'lbryinc';
import { doPushDrawerStack } from 'redux/actions/drawer';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectCurrentRoute } from 'redux/selectors/drawer';
import Constants from 'constants';
import TrendingPage from './view';
const select = state => ({
currentRoute: selectCurrentRoute(state),
trendingUris: selectTrendingUris(state),
fetchingTrendingUris: selectFetchingTrendingUris(state),
});
const perform = dispatch => ({
fetchTrendingUris: () => dispatch(doFetchTrendingUris()),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_TRENDING))
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_TRENDING)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false))
});
export default connect(select, perform)(TrendingPage);
+34 -7
View File
@@ -1,28 +1,55 @@
import React from 'react';
import NavigationActions from 'react-navigation';
import {
ActivityIndicator,
AsyncStorage,
NativeModules,
FlatList,
Text,
View
} from 'react-native';
import { normalizeURI } from 'lbry-redux';
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
import FileItem from '/component/fileItem';
import FileItem from 'component/fileItem';
import discoverStyle from 'styles/discover';
import fileListStyle from 'styles/fileList';
import Colors from 'styles/colors';
import Constants from 'constants';
import FloatingWalletBalance from 'component/floatingWalletBalance';
import UriBar from 'component/uriBar';
class TrendingPage extends React.PureComponent {
componentDidMount() {
const { fetchTrendingUris, pushDrawerStack } = this.props;
didFocusListener;
componentWillMount() {
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
componentWillUnmount() {
if (this.didFocusListener) {
this.didFocusListener.remove();
}
}
onComponentFocused = () => {
const { fetchTrendingUris, pushDrawerStack, setPlayerVisible } = this.props;
pushDrawerStack();
setPlayerVisible();
fetchTrendingUris();
}
componentDidMount() {
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { currentRoute } = nextProps;
const { currentRoute: prevRoute } = this.props;
if (Constants.FULL_ROUTE_NAME_TRENDING === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
}
render() {
const { trendingUris, fetchingTrendingUris, navigation } = this.props;
const hasContent = typeof trendingUris === 'object' && trendingUris.length,
@@ -41,8 +68,8 @@ class TrendingPage extends React.PureComponent {
<FlatList style={discoverStyle.trendingContainer}
renderItem={ ({item}) => (
<FileItem
style={discoverStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
style={fileListStyle.fileItem}
mediaStyle={fileListStyle.fileItemMedia}
key={item}
uri={normalizeURI(item)}
navigation={navigation}
+69
View File
@@ -0,0 +1,69 @@
import { connect } from 'react-redux';
import { doToast } from 'lbry-redux';
import {
doCheckSync,
doGetSync,
doSetDefaultAccount,
doSyncApply,
doUserEmailNew,
doUserEmailToVerify,
doUserResendVerificationEmail,
doUserPhoneNew,
doUserPhoneVerify,
selectPhoneNewErrorMessage,
selectPhoneNewIsPending,
selectPhoneToVerify,
selectPhoneVerifyIsPending,
selectPhoneVerifyErrorMessage,
selectEmailNewErrorMessage,
selectEmailNewIsPending,
selectEmailToVerify,
selectHasSyncedWallet,
selectGetSyncIsPending,
selectSetSyncIsPending,
selectSyncApplyIsPending,
selectSyncApplyErrorMessage,
selectSyncData,
selectSyncHash,
selectUser,
} from 'lbryinc';
import { doSetClientSetting } from 'redux/actions/settings';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import Constants from 'constants';
import Verification from './view';
const select = (state) => ({
emailToVerify: selectEmailToVerify(state),
emailNewErrorMessage: selectEmailNewErrorMessage(state),
emailNewPending: selectEmailNewIsPending(state),
user: selectUser(state),
phoneVerifyErrorMessage: selectPhoneVerifyErrorMessage(state),
phoneVerifyIsPending: selectPhoneVerifyIsPending(state),
phone: selectPhoneToVerify(state),
phoneNewErrorMessage: selectPhoneNewErrorMessage(state),
phoneNewIsPending: selectPhoneNewIsPending(state),
deviceWalletSynced: makeSelectClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED)(state),
hasSyncedWallet: selectHasSyncedWallet(state),
getSyncIsPending: selectGetSyncIsPending(state),
setSyncIsPending: selectSetSyncIsPending(state),
syncApplyIsPending: selectSyncApplyIsPending(state),
syncApplyErrorMessage: selectSyncApplyErrorMessage(state),
syncData: selectSyncData(state),
syncHash: selectSyncHash(state),
});
const perform = dispatch => ({
addUserEmail: email => dispatch(doUserEmailNew(email)),
addUserPhone: (phone, country_code) => dispatch(doUserPhoneNew(phone, country_code)),
getSync: password => dispatch(doGetSync(password)),
checkSync: () => dispatch(doCheckSync()),
verifyPhone: (verificationCode) => dispatch(doUserPhoneVerify(verificationCode)),
notify: data => dispatch(doToast(data)),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
setDefaultAccount: () => dispatch(doSetDefaultAccount()),
setEmailToVerify: email => dispatch(doUserEmailToVerify(email)),
syncApply: (hash, data, password) => dispatch(doSyncApply(hash, data, password)),
resendVerificationEmail: email => dispatch(doUserResendVerificationEmail(email)),
});
export default connect(select, perform)(Verification);
@@ -0,0 +1,167 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import { ActivityIndicator, View, Text, TextInput } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Button from 'component/button';
import Link from 'component/link';
import Colors from 'styles/colors';
import Constants from 'constants';
import firstRunStyle from 'styles/firstRun';
import rewardStyle from 'styles/reward';
class EmailVerifyPage extends React.PureComponent {
state = {
email: null,
phase: Constants.PHASE_COLLECTION,
placeholder: 'you@example.com',
verifyStarted: false,
previousEmail: null
}
componentDidMount() {
const { setEmailVerificationPhase } = this.props;
if (setEmailVerificationPhase) {
setEmailVerificationPhase(false);
}
}
componentWillUmount() {
AsyncStorage.removeItem(Constants.KEY_EMAIL_VERIFY_PENDING);
AsyncStorage.removeItem(Constants.KEY_FIRST_RUN_EMAIL);
}
handleChangeText = (text) => {
this.setState({ email: text });
AsyncStorage.setItem(Constants.KEY_FIRST_RUN_EMAIL, text);
}
componentWillReceiveProps(nextProps) {
const { emailNewErrorMessage, emailNewPending, emailToVerify } = nextProps;
const { notify, setEmailVerificationPhase } = this.props;
if (this.state.verifyStarted && !emailNewPending) {
if (emailNewErrorMessage) {
notify({ message: String(emailNewErrorMessage), isError: true });
this.setState({ verifyStarted: false });
} else {
this.setState({ phase: Constants.PHASE_VERIFICATION });
if (setEmailVerificationPhase) {
setEmailVerificationPhase(true);
}
//notify({ message: 'Please follow the instructions in the email sent to your address to continue.' });
AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'true');
}
}
}
onSendVerificationPressed = () => {
const {
addUserEmail,
emailNewPending,
notify,
resendVerificationEmail,
setEmailVerificationPhase
} = this.props;
if (emailNewPending) {
return;
}
const { email } = this.state;
if (!email || email.trim().length === 0 || email.indexOf('@') === -1) {
return notify({
message: 'Please provide a valid email address to continue.',
});
}
if (this.state.previousEmail === this.state.email) {
// resend
resendVerificationEmail(this.state.email);
AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'true');
this.setState({ verifyStarted: true, phase: Constants.PHASE_VERIFICATION });
if (setEmailVerificationPhase) {
setEmailVerificationPhase(true);
}
return;
}
this.setState({ verifyStarted: true });
addUserEmail(email);
}
onResendPressed = () => {
const { resendVerificationEmail, notify } = this.props;
// resend verification email if there was one previously set (and it wasn't changed)
resendVerificationEmail(this.state.email);
AsyncStorage.setItem(Constants.KEY_EMAIL_VERIFY_PENDING, 'true');
notify({ message: 'Please follow the instructions in the email sent to your address to continue.' });
}
onEditPressed = () => {
const { setEmailVerificationPhase } = this.props;
this.setState({ verifyStarted: false, phase: Constants.PHASE_COLLECTION, previousEmail: this.state.email }, () => {
if (setEmailVerificationPhase) {
setEmailVerificationPhase(false);
}
// clear the previous email
AsyncStorage.removeItem(Constants.KEY_EMAIL_VERIFY_PENDING);
AsyncStorage.removeItem(Constants.KEY_FIRST_RUN_EMAIL);
});
}
render() {
const { emailNewPending } = this.props;
return (
<View style={firstRunStyle.container}>
<Text style={rewardStyle.verificationTitle}>{(Constants.PHASE_COLLECTION === this.state.phase) ? 'Email' : 'Verify Email'}</Text>
{(Constants.PHASE_COLLECTION === this.state.phase) &&
<View>
<Text style={firstRunStyle.paragraph}>Please provide an email address.</Text>
<TextInput style={firstRunStyle.emailInput}
placeholder={this.state.placeholder}
underlineColorAndroid="transparent"
selectionColor={Colors.NextLbryGreen}
value={this.state.email}
onChangeText={text => this.handleChangeText(text)}
onFocus={() => {
if (!this.state.email || this.state.email.length === 0) {
this.setState({ placeholder: '' });
}
}}
onBlur={() => {
if (!this.state.email || this.state.email.length === 0) {
this.setState({ placeholder: 'you@example.com' });
}
}}
/>
<View style={rewardStyle.buttonContainer}>
{!this.state.verifyStarted &&
<Button
style={rewardStyle.verificationButton}
theme={"light"}
text={"Send verification email"}
onPress={this.onSendVerificationPressed} />}
{this.state.verifyStarted && emailNewPending &&
<View style={firstRunStyle.centerInside}>
<ActivityIndicator size={"small"} color={Colors.White} />
</View>}
</View>
</View>}
{(Constants.PHASE_VERIFICATION === this.state.phase) &&
<View>
<Text style={firstRunStyle.paragraph}>An email has been sent to <Text style={firstRunStyle.nowrap}>{this.state.email}</Text>. Please follow the instructions in the message to verify your email address.</Text>
<View style={rewardStyle.buttonContainer}>
<Button style={rewardStyle.verificationButton} theme={"light"} text={"Resend"} onPress={this.onResendPressed} />
<Link style={rewardStyle.verificationLink} text={"Edit"} onPress={this.onEditPressed} />
</View>
</View>
}
</View>
);
}
}
export default EmailVerifyPage;
@@ -0,0 +1,38 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import { ActivityIndicator, View, Text, TextInput } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Button from 'component/button';
import Link from 'component/link';
import Colors from 'styles/colors';
import Constants from 'constants';
import firstRunStyle from 'styles/firstRun';
import rewardStyle from 'styles/reward';
class ManualVerifyPage extends React.PureComponent {
componentDidMount() {
const { setEmailVerificationPhase } = this.props;
if (setEmailVerificationPhase) {
setEmailVerificationPhase(false);
}
}
render() {
return (
<View style={firstRunStyle.container}>
<Text style={rewardStyle.verificationTitle}>Manual Reward Verification</Text>
<Text style={firstRunStyle.spacedParagraph}>
This account must undergo review before you can participate in the rewards program. This can take anywhere from several minutes to several days.
</Text>
<Text style={firstRunStyle.spacedParagraph}>
If you continue to see this message, please request to be verified on the <Link style={rewardStyle.underlinedTextLink} href="https://discordapp.com/invite/Z3bERWA" text="LBRY Discord server" />.
</Text>
<Text style={firstRunStyle.spacedParagraph}>
Please enjoy free content in the meantime!
</Text>
</View>
);
}
}
export default ManualVerifyPage;
@@ -2,7 +2,6 @@
import React from 'react';
import {
ActivityIndicator,
AsyncStorage,
DeviceEventEmitter,
NativeModules,
StyleSheet,
@@ -11,6 +10,7 @@ import {
TouchableOpacity,
View
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Button from 'component/button';
import Colors from 'styles/colors';
import Constants from 'constants';
@@ -18,9 +18,10 @@ import CountryPicker from 'react-native-country-picker-modal';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Link from 'component/link';
import PhoneInput from 'react-native-phone-input';
import firstRunStyle from 'styles/firstRun';
import rewardStyle from 'styles/reward';
class PhoneNumberRewardSubcard extends React.PureComponent {
class PhoneVerifyPage extends React.PureComponent {
phoneInput = null;
picker = null;
@@ -37,26 +38,18 @@ class PhoneNumberRewardSubcard extends React.PureComponent {
number: null,
phoneVerifyFailed: false,
verificationCode: null,
phase: Constants.PHASE_COLLECTION
};
}
componentDidMount() {
//DeviceEventEmitter.addListener('onReceiveSmsPermissionGranted', this.receiveSmsPermissionGranted);
DeviceEventEmitter.addListener('onVerificationCodeReceived', this.receiveVerificationCode);
const { phone } = this.props;
const { phone, setEmailVerificationPhase } = this.props;
if (phone && String(phone).trim().length > 0) {
this.setState({ newPhoneAdded: true });
this.setState({ newPhoneAdded: true, phase: Constants.PHASE_VERIFICATION });
}
if (setEmailVerificationPhase) {
setEmailVerificationPhase(false);
}
/*if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.canReceiveSms().then(canReceiveSms => this.setState({ canReceiveSms }));
}*/
}
componentWillUnmount() {
//DeviceEventEmitter.removeListener('onReceiveSmsPermissionGranted', this.receiveSmsPermissionGranted);
DeviceEventEmitter.removeListener('onVerificationCodeReceived', this.receiveVerificationCode);
}
componentDidUpdate(prevProps) {
@@ -74,7 +67,7 @@ class PhoneNumberRewardSubcard extends React.PureComponent {
notify({ message: String(phoneNewErrorMessage) });
this.setState({ phoneVerifyFailed: true });
} else {
this.setState({ newPhoneAdded: true, phoneVerifyFailed: false });
this.setState({ newPhoneAdded: true, phase: Constants.PHASE_VERIFICATION, phoneVerifyFailed: false });
}
}
if (!phoneVerifyIsPending && (phoneVerifyIsPending !== prevProps.phoneVerifyIsPending)) {
@@ -91,6 +84,10 @@ class PhoneNumberRewardSubcard extends React.PureComponent {
}
}
onEditPressed = () => {
this.setState({ newPhoneAdded: false, phase: Constants.PHASE_COLLECTION, phoneVerifyFailed: false });
}
receiveVerificationCode = (evt) => {
if (!this.state.newPhoneAdded || this.state.codeVerifySuccessful) {
return;
@@ -151,68 +148,77 @@ class PhoneNumberRewardSubcard extends React.PureComponent {
phoneNewIsPending
} = this.props;
if (this.state.codeVerifySuccessful) {
return null;
}
return (
<View style={rewardStyle.subcard}>
<Text style={rewardStyle.subtitle}>Pending action: Verify Phone Number</Text>
<View style={firstRunStyle.container}>
<Text style={rewardStyle.verificationTitle}>{this.state.phase === Constants.PHASE_VERIFICATION ? 'Verify ' : '' }Phone Number</Text>
<View style={rewardStyle.phoneVerificationContainer}>
{!this.state.newPhoneAdded &&
{this.state.phase == Constants.PHASE_COLLECTION &&
<View>
<Text style={[rewardStyle.bottomMarginMedium, rewardStyle.subcardText]}>Please enter your phone number to continue.</Text>
<Text style={[rewardStyle.bottomMarginMedium, firstRunStyle.paragraph]}>Please provide a phone number to prevent fraud.</Text>
<PhoneInput
ref={(ref) => { this.phoneInput = ref; }}
style={StyleSheet.flatten(rewardStyle.phoneInput)}
textProps={{ placeholder: '(phone number)' }}
textStyle={StyleSheet.flatten(rewardStyle.phoneInputText)}
onPressFlag={this.onPressFlag} />
{!phoneNewIsPending &&
<Button
style={[rewardStyle.actionButton, rewardStyle.topMarginMedium]}
text={"Send verification text"}
onPress={this.onSendTextPressed} />}
{phoneNewIsPending &&
<ActivityIndicator
style={[rewardStyle.loading, rewardStyle.topMarginMedium]}
size="small"
color={Colors.LbryGreen} />}
<View style={rewardStyle.buttonContainer}>
{!phoneNewIsPending &&
<Button
style={[rewardStyle.verificationButton, rewardStyle.topMarginMedium]}
theme={"light"}
text={"Send verification text"}
onPress={this.onSendTextPressed} />}
{phoneNewIsPending &&
<View style={firstRunStyle.centerInside}>
<ActivityIndicator
style={rewardStyle.topMarginMedium}
size="small"
color={Colors.White} />
</View>}
</View>
</View>}
{this.state.newPhoneAdded &&
{this.state.phase === Constants.PHASE_VERIFICATION &&
<View>
{!phoneVerifyIsPending && !this.codeVerifyStarted &&
<View>
<Text style={[rewardStyle.bottomMarginSmall, rewardStyle.subcardText]}>
Please enter the verification code.
<Text style={[rewardStyle.bottomMarginSmall, firstRunStyle.paragraph]}>
Please enter the verification code sent to {phone}.
</Text>
<TextInput
style={rewardStyle.verificationCodeInput}
keyboardType="numeric"
placeholder="0000"
underlineColorAndroid="transparent"
selectionColor={Colors.NextLbryGreen}
value={this.state.verificationCode}
onChangeText={text => this.handleChangeText(text)}
/>
<Button
style={[rewardStyle.actionButton, rewardStyle.topMarginSmall ]}
text={"Verify"}
onPress={this.onVerifyPressed} />
<View style={rewardStyle.buttonContainer}>
<Button
style={[rewardStyle.verificationButton, rewardStyle.topMarginSmall]}
theme={"light"}
text={"Verify"}
onPress={this.onVerifyPressed} />
<Link style={rewardStyle.verificationLink} text={"Edit"} onPress={this.onEditPressed} />
</View>
</View>
}
{phoneVerifyIsPending &&
<View>
<Text style={rewardStyle.subcardText}>Verifying your phone number...</Text>
<View style={firstRunStyle.centered}>
<Text style={firstRunStyle.paragraph}>Verifying your phone number...</Text>
<ActivityIndicator
color={Colors.LbryGreen}
color={Colors.White}
size="small"
style={[rewardStyle.loading, rewardStyle.topMarginMedium]} />
style={[rewardStyle.topMarginMedium, rewardStyle.leftRightMargin]} />
</View>}
</View>
}
{this.state.phoneVerifyFailed &&
<View style={rewardStyle.failureFootnote}>
<Text style={rewardStyle.subcardText}>
<Text style={rewardStyle.paragraphText}>
Sorry, we were unable to verify your phone number. Please go to <Link style={rewardStyle.textLink} href="http://chat.lbry.com" text="chat.lbry.com" /> for manual verification if this keeps happening.
</Text>
</View>}
@@ -232,4 +238,4 @@ class PhoneNumberRewardSubcard extends React.PureComponent {
}
};
export default PhoneNumberRewardSubcard;
export default PhoneVerifyPage;
@@ -0,0 +1,182 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
Dimensions,
NativeModules,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native';
import { BarPasswordStrengthDisplay } from 'react-native-password-strength-meter';
import Button from 'component/button';
import Link from 'component/link';
import Colors from 'styles/colors';
import Constants from 'constants';
import firstRunStyle from 'styles/firstRun';
import Icon from 'react-native-vector-icons/FontAwesome5';
import rewardStyle from 'styles/reward';
class SyncVerifyPage extends React.PureComponent {
state = {
checkSyncStarted: false,
password: null,
placeholder: 'password',
syncApplyStarted: false,
syncChecked: false,
revealPassword: false
}
componentDidMount() {
const { checkSync, setEmailVerificationPhase } = this.props;
this.setState({ checkSyncStarted: true }, () => checkSync());
if (setEmailVerificationPhase) {
setEmailVerificationPhase(false);
}
}
onEnableSyncPressed = () => {
const {
getSync,
hasSyncedWallet,
navigation,
setClientSetting,
syncApply,
syncData,
syncHash
} = this.props;
this.setState({ syncApplyStarted: true }, () => {
if (!hasSyncedWallet) {
// fresh account with no sync
Lbry.account_encrypt({ new_password: this.state.password }).then(() => {
Lbry.account_unlock({ password: this.state.password }).then(() => {
getSync(this.state.password);
setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, true);
navigation.goBack();
});
});
} else {
syncApply(syncHash, syncData, this.state.password);
}
});
}
componentWillReceiveProps(nextProps) {
const { getSyncIsPending, syncApplyIsPending, syncApplyErrorMessage } = nextProps;
const { getSync, hasSyncedWallet, navigation, notify, setClientSetting, setDefaultAccount } = this.props;
if (this.state.checkSyncStarted && !getSyncIsPending) {
this.setState({ syncChecked: true });
}
if (this.state.syncApplyStarted && !syncApplyIsPending) {
if (syncApplyErrorMessage && syncApplyErrorMessage.trim().length > 0) {
notify({ message: syncApplyErrorMessage, isError: true });
this.setState({ syncApplyStarted: false });
} else {
// password successfully verified
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.setSecureValue(Constants.KEY_FIRST_RUN_PASSWORD, this.state.password);
}
setDefaultAccount();
setClientSetting(Constants.SETTING_DEVICE_WALLET_SYNCED, true);
navigation.goBack();
}
}
}
handleChangeText = (text) => {
// save the value to the state email
const { onPasswordChanged } = this.props;
this.setState({ password: text });
if (onPasswordChanged) {
onPasswordChanged(text);
}
}
render() {
const { hasSyncedWallet, syncApplyIsPending } = this.props;
let paragraph;
if (!hasSyncedWallet) {
paragraph = (<Text style={firstRunStyle.paragraph}>Please enter a password to secure your account and wallet.</Text>);
} else {
paragraph = (<Text style={firstRunStyle.paragraph}>Please enter the password you used to secure your wallet.</Text>);
}
let content;
if (!this.state.syncChecked) {
content = (
<View style={firstRunStyle.centered}>
<ActivityIndicator size="large" color={Colors.White} style={firstRunStyle.waiting} />
<Text style={firstRunStyle.paragraph}>Retrieving your account information...</Text>
</View>
);
} else {
content = (
<View>
<Text style={rewardStyle.verificationTitle}>Wallet Sync</Text>
{paragraph}
<View style={firstRunStyle.passwordInputContainer}>
<TextInput style={firstRunStyle.passwordInput}
placeholder={this.state.placeholder}
underlineColorAndroid="transparent"
selectionColor={Colors.NextLbryGreen}
secureTextEntry={!this.state.revealPassword}
value={this.state.password}
onChangeText={text => this.handleChangeText(text)}
onFocus={() => {
if (!this.state.password || this.state.password.length === 0) {
this.setState({ placeholder: '' });
}
}}
onBlur={() => {
if (!this.state.password || this.state.password.length === 0) {
this.setState({ placeholder: 'password' });
}
}}
/>
<TouchableOpacity
style={firstRunStyle.revealPasswordIcon}
onPress={() => this.setState({ revealPassword: !this.state.revealPassword })}>
<Icon name={this.state.revealPassword ? "eye-slash" : "eye"} size={16} style={firstRunStyle.revealIcon} />
</TouchableOpacity>
</View>
{(!hasSyncedWallet && this.state.password && this.state.password.trim().length) > 0 &&
<View style={firstRunStyle.passwordStrength}>
<BarPasswordStrengthDisplay
width={Dimensions.get('window').width - 80}
minLength={1}
password={this.state.password} />
</View>}
<Text style={firstRunStyle.infoParagraph}>Note: for wallet security purposes, LBRY is unable to reset your password.</Text>
<View style={rewardStyle.buttonContainer}>
{!this.state.syncApplyStarted &&
<Button
style={rewardStyle.verificationButton}
theme={"light"}
text={"Enable sync"}
onPress={this.onEnableSyncPressed} />}
{syncApplyIsPending &&
<View style={firstRunStyle.centerInside}>
<ActivityIndicator size={"small"} color={Colors.White} />
</View>}
</View>
</View>
);
}
return (
<View style={firstRunStyle.container}>
{content}
</View>
);
}
}
export default SyncVerifyPage;
+196
View File
@@ -0,0 +1,196 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
Linking,
NativeModules,
Text,
TouchableOpacity,
View
} from 'react-native';
import { NavigationActions, StackActions } from 'react-navigation';
import AsyncStorage from '@react-native-community/async-storage';
import Colors from 'styles/colors';
import Constants from 'constants';
import EmailVerifyPage from './internal/email-verify-page';
import ManualVerifyPage from './internal/manual-verify-page';
import PhoneVerifyPage from './internal/phone-verify-page';
import SyncVerifyPage from './internal/sync-verify-page';
import firstRunStyle from 'styles/firstRun';
class VerificationScreen extends React.PureComponent {
state = {
currentPage: null,
emailSubmitted: false,
launchUrl: null,
showSkip: false,
skipAccountConfirmed: false,
showBottomContainer: true,
walletPassword: null,
isEmailVerificationPhase: false,
isEmailVerified: false,
isIdentityVerified: false,
isRewardApproved: false
};
componentDidMount() {
const { user } = this.props;
this.checkVerificationStatus(user);
}
setEmailVerificationPhase = (value) => {
this.setState({ isEmailVerificationPhase: value });
}
checkVerificationStatus = (user) => {
const { deviceWalletSynced, navigation } = this.props;
const { syncFlow } = navigation.state.params;
this.setState({
isEmailVerified: (user && user.primary_email && user.has_verified_email),
isIdentityVerified: (user && user.is_identity_verified),
isRewardApproved: (user && user.is_reward_approved)
}, () => {
if (!this.state.isEmailVerified) {
this.setState({ currentPage: 'emailVerify' });
}
if (syncFlow) {
if (this.state.isEmailVerified && !deviceWalletSynced) {
this.setState({ currentPage: 'syncVerify' });
}
if (this.state.isEmailVerified && syncFlow && deviceWalletSynced) {
navigation.goBack();
}
} else {
if (this.state.isEmailVerified && !this.state.isIdentityVerified && !this.state.isRewardApproved) {
this.setState({ currentPage: 'phoneVerify' });
}
if (this.state.isEmailVerified && this.state.isIdentityVerified && !this.state.isRewardApproved) {
this.setState({ currentPage: 'manualVerify' });
}
if (this.state.isEmailVerified && this.state.isRewardApproved) {
// verification steps already completed
// simply navigate back to the rewards page
navigation.goBack();
}
}
});
}
componentWillReceiveProps(nextProps) {
const { user } = nextProps;
this.checkVerificationStatus(user);
}
onCloseButtonPressed = () => {
const { navigation } = this.props;
navigation.goBack();
}
render() {
const {
addUserEmail,
checkSync,
emailNewErrorMessage,
emailNewPending,
emailToVerify,
getSync,
navigation,
notify,
addUserPhone,
getSyncIsPending,
setDefaultAccount,
hasSyncedWallet,
setSyncIsPending,
syncApplyIsPending,
syncApplyErrorMessage,
syncApply,
syncData,
syncHash,
phone,
phoneVerifyIsPending,
phoneVerifyErrorMessage,
phoneNewIsPending,
phoneNewErrorMessage,
resendVerificationEmail,
setClientSetting,
verifyPhone
} = this.props;
let page = null;
switch (this.state.currentPage) {
case 'emailVerify':
page = (
<EmailVerifyPage
addUserEmail={addUserEmail}
emailNewErrorMessage={emailNewErrorMessage}
emailNewPending={emailNewPending}
emailToVerify={emailToVerify}
notify={notify}
setEmailVerificationPhase={this.setEmailVerificationPhase}
resendVerificationEmail={resendVerificationEmail}
/>
);
break;
case 'phoneVerify':
page = (
<PhoneVerifyPage
addUserPhone={addUserPhone}
phone={phone}
phoneVerifyIsPending={phoneVerifyIsPending}
phoneVerifyErrorMessage={phoneVerifyErrorMessage}
phoneNewIsPending={phoneNewIsPending}
phoneNewErrorMessage={phoneNewErrorMessage}
setEmailVerificationPhase={this.setEmailVerificationPhase}
notify={notify}
verifyPhone={verifyPhone}
/>
);
break;
case 'syncVerify':
page = (
<SyncVerifyPage
checkSync={checkSync}
getSync={getSync}
getSyncIsPending={getSyncIsPending}
hasSyncedWallet={hasSyncedWallet}
navigation={navigation}
notify={notify}
setEmailVerificationPhase={this.setEmailVerificationPhase}
setClientSetting={setClientSetting}
setDefaultAccount={setDefaultAccount}
setSyncIsPending={setSyncIsPending}
syncApplyIsPending={syncApplyIsPending}
syncApplyErrorMessage={syncApplyErrorMessage}
syncApply={syncApply}
syncData={syncData}
syncHash={syncHash}
/>
);
break;
case 'manualVerify':
page = (
<ManualVerifyPage setEmailVerificationPhase={this.setEmailVerificationPhase} />
);
break;
}
return (
<View style={firstRunStyle.screenContainer}>
{page}
{!this.state.isEmailVerificationPhase &&
(<TouchableOpacity style={firstRunStyle.closeButton} onPress={this.onCloseButtonPressed}>
<Text style={firstRunStyle.closeButtonText}>x</Text>
</TouchableOpacity>)}
</View>
);
}
}
export default VerificationScreen;
+15 -2
View File
@@ -1,17 +1,30 @@
import { connect } from 'react-redux';
import { doSetClientSetting } from 'redux/actions/settings';
import { makeSelectClientSetting } from 'redux/selectors/settings';
import { doPushDrawerStack } from 'redux/actions/drawer';
import { doPushDrawerStack, doSetPlayerVisible } from 'redux/actions/drawer';
import { selectCurrentRoute } from 'redux/selectors/drawer';
import { selectBalance } from 'lbry-redux';
import { doCheckSync, doGetSync, selectUser, selectHasSyncedWallet } from 'lbryinc';
import Constants from 'constants';
import WalletPage from './view';
const select = state => ({
currentRoute: selectCurrentRoute(state),
backupDismissed: makeSelectClientSetting(Constants.SETTING_BACKUP_DISMISSED)(state),
balance: selectBalance(state),
hasSyncedWallet: selectHasSyncedWallet(state),
rewardsNotInterested: makeSelectClientSetting(Constants.SETTING_REWARDS_NOT_INTERESTED)(state),
understandsRisks: makeSelectClientSetting(Constants.SETTING_ALPHA_UNDERSTANDS_RISKS)(state),
user: selectUser(state),
});
const perform = dispatch => ({
checkSync: () => dispatch(doCheckSync()),
getSync: password => dispatch(doGetSync(password)),
setClientSetting: (key, value) => dispatch(doSetClientSetting(key, value)),
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_WALLET))
pushDrawerStack: () => dispatch(doPushDrawerStack(Constants.DRAWER_ROUTE_WALLET)),
setPlayerVisible: () => dispatch(doSetPlayerVisible(false))
});
export default connect(select, perform)(WalletPage);
+67 -13
View File
@@ -1,9 +1,11 @@
import React from 'react';
import { ScrollView, Text, View } from 'react-native';
import { NativeModules, ScrollView, Text, View } from 'react-native';
import TransactionListRecent from 'component/transactionListRecent';
import WalletAddress from 'component/walletAddress';
import WalletBalance from 'component/walletBalance';
import WalletSend from 'component/walletSend';
import WalletRewardsDriver from 'component/walletRewardsDriver';
import WalletSyncDriver from 'component/walletSyncDriver';
import Button from 'component/button';
import Link from 'component/link';
import UriBar from 'component/uriBar';
@@ -11,20 +13,76 @@ import Constants from 'constants';
import walletStyle from 'styles/wallet';
class WalletPage extends React.PureComponent {
didFocusListener;
componentWillMount() {
const { navigation } = this.props;
this.didFocusListener = navigation.addListener('didFocus', this.onComponentFocused);
}
componentWillUnmount() {
if (this.didFocusListener) {
this.didFocusListener.remove();
}
}
componentDidMount() {
this.props.pushDrawerStack();
this.onComponentFocused();
}
componentWillReceiveProps(nextProps) {
const { currentRoute } = nextProps;
const { currentRoute: prevRoute } = this.props;
if (Constants.FULL_ROUTE_NAME_WALLET === currentRoute && currentRoute !== prevRoute) {
this.onComponentFocused();
}
}
onComponentFocused = () => {
const { pushDrawerStack, setPlayerVisible } = this.props;
pushDrawerStack();
setPlayerVisible();
const { getSync, user } = this.props;
if (user && user.has_verified_email) {
NativeModules.UtilityModule.getSecureValue(Constants.KEY_FIRST_RUN_PASSWORD).then(walletPassword => {
if (walletPassword && walletPassword.trim().length > 0) {
getSync(walletPassword);
}
});
}
}
onDismissBackupPressed = () => {
const { setClientSetting } = this.props;
setClientSetting(Constants.SETTING_BACKUP_DISMISSED, true);
}
render() {
const { understandsRisks, setClientSetting, navigation } = this.props;
const {
balance,
backupDismissed,
hasSyncedWallet,
rewardsNotInterested,
understandsRisks,
setClientSetting,
navigation
} = this.props;
if (!understandsRisks) {
return (
<View>
<UriBar navigation={navigation} />
<View style={walletStyle.warning}>
<Text style={walletStyle.warningParagraph}>
This is beta software. You may lose any credits that you send to your wallet due to software bugs, deleted files, or malicious third-party software. You should not use this wallet as your primary wallet.
</Text>
{!hasSyncedWallet &&
<Text style={walletStyle.warningParagraph}>
Since you are not using the LBRY sync service, you will lose all of your credits if you uninstall this application. Instructions on how to enroll as well as how to backup your wallet manually are available on the next page.
</Text>}
<Text style={walletStyle.warningText}>
This is beta software. You may lose any LBC that you send to your wallet due to uninstallation, software bugs, deleted files, or malicious third-party software. You should not use this wallet as your primary wallet. If you understand the risks and you wish to continue, please tap the button below.
If you understand the risks and you wish to continue, please tap the button below.
</Text>
</View>
<Button text={'I understand the risks'} style={[walletStyle.button, walletStyle.understand]}
@@ -34,19 +92,15 @@ class WalletPage extends React.PureComponent {
}
return (
<View>
<View style={walletStyle.container}>
<UriBar navigation={navigation} />
<ScrollView keyboardShouldPersistTaps={'handled'}>
<View style={walletStyle.warningCard}>
<Text style={walletStyle.warningText}>
Please backup your wallet file using the instructions at <Link style={walletStyle.warningText} text="https://lbry.com/faq/how-to-backup-wallet#android" href="https://lbry.com/faq/how-to-backup-wallet#android" />.
</Text>
</View>
<ScrollView style={walletStyle.scrollContainer} keyboardShouldPersistTaps={'handled'}>
<WalletSyncDriver navigation={navigation} />
{(!rewardsNotInterested) && (!balance || balance === 0) && <WalletRewardsDriver navigation={navigation} />}
<WalletBalance />
<WalletAddress />
<WalletSend />
<TransactionListRecent navigation={this.props.navigation} />
<TransactionListRecent navigation={navigation} />
</ScrollView>
</View>
);
+5
View File
@@ -8,3 +8,8 @@ export const doPushDrawerStack = (routeName) => (dispatch) => dispatch({
export const doPopDrawerStack = () => (dispatch) => dispatch({
type: Constants.ACTION_POP_DRAWER_STACK
});
export const doSetPlayerVisible = (visible) => (dispatch) => dispatch({
type: Constants.ACTION_SET_PLAYER_VISIBLE,
data: { visible }
});
+35 -279
View File
@@ -1,112 +1,8 @@
import {
ACTIONS,
Lbry,
doToast,
formatCredits,
selectBalance,
makeSelectFileInfoForUri,
makeSelectMetadataForUri,
selectDownloadingByOutpoint,
} from 'lbry-redux';
import { doClaimEligiblePurchaseRewards, makeSelectCostInfoForUri } from 'lbryinc';
import { ACTIONS, Lbry } from 'lbry-redux';
import { doClaimEligiblePurchaseRewards } from 'lbryinc';
import { Alert, NativeModules } from 'react-native';
import Constants from 'constants';
const DOWNLOAD_POLL_INTERVAL = 250;
const deleteBlobsForSdHash = (sdHash) => {
Lbry.blob_list({ sd_hash: sdHash }).then(hashes => {
hashes.filter(hash => hash != sdHash).forEach(hash => {
Lbry.blob_delete({ blob_hash: hash });
});
});
};
export function doUpdateLoadStatus(uri, outpoint) {
return (dispatch, getState) => {
const state = getState();
Lbry.file_list({
outpoint,
full_status: true,
}).then(([fileInfo]) => {
if (!fileInfo || fileInfo.written_bytes === 0) {
// if the outpoint isn't in the state, then it was probably canceled, so stop checking the load status
const { downloadingByOutpoint = {} } = state.fileInfo;
if (!downloadingByOutpoint[outpoint]) return;
// download hasn't started yet
setTimeout(() => {
dispatch(doUpdateLoadStatus(uri, outpoint));
}, DOWNLOAD_POLL_INTERVAL);
} else if (fileInfo.completed) {
// TODO this isn't going to get called if they reload the client before
// the download finished
const { total_bytes: totalBytes, written_bytes: writtenBytes } = fileInfo;
dispatch({
type: ACTIONS.DOWNLOADING_COMPLETED,
data: {
uri,
outpoint,
fileInfo,
},
});
if (NativeModules.LbryDownloadManager) {
NativeModules.LbryDownloadManager.updateDownload(
uri,
fileInfo.file_name ? fileInfo.file_name : '',
100,
writtenBytes ? writtenBytes : 0,
totalBytes ? totalBytes : 0
);
}
// Once a download has been completed, delete the individual blob files to save space
Lbry.file_set_status({ status: 'stop', sd_hash: fileInfo.sd_hash }).then(() => {
deleteBlobsForSdHash(fileInfo.sd_hash);
}).catch(() => {
deleteBlobsForSdHash(fileInfo.sd_hash);
});
/*const notif = new window.Notification('LBRY Download Complete', {
body: fileInfo.metadata.stream.metadata.title,
silent: false,
});*/
} else {
// ready to play
const { total_bytes: totalBytes, written_bytes: writtenBytes } = fileInfo;
const progress = writtenBytes / totalBytes * 100;
dispatch({
type: ACTIONS.DOWNLOADING_PROGRESSED,
data: {
uri,
outpoint,
fileInfo,
progress,
},
});
if (NativeModules.LbryDownloadManager) {
NativeModules.LbryDownloadManager.updateDownload(
uri,
fileInfo.file_name ? fileInfo.file_name : '',
progress ? progress : 0,
writtenBytes ? writtenBytes : 0,
totalBytes ? totalBytes: 0
);
}
setTimeout(() => {
dispatch(doUpdateLoadStatus(uri, outpoint));
}, DOWNLOAD_POLL_INTERVAL);
}
});
};
}
export function doStartDownload(uri, outpoint) {
export function doStartDownload(uri, outpoint, fileInfo) {
return (dispatch, getState) => {
const state = getState();
@@ -118,22 +14,45 @@ export function doStartDownload(uri, outpoint) {
if (downloadingByOutpoint[outpoint]) return;
Lbry.file_list({ outpoint, full_status: true }).then(([fileInfo]) => {
dispatch({
type: ACTIONS.DOWNLOADING_STARTED,
data: {
uri,
outpoint,
fileInfo,
},
});
dispatch(doClaimEligiblePurchaseRewards());
};
}
export function doUpdateDownload(uri, outpoint, fileInfo, progress) {
return (dispatch) => {
dispatch({
type: ACTIONS.DOWNLOADING_PROGRESSED,
data: {
uri,
outpoint,
fileInfo,
progress,
},
});
};
}
export function doCompleteDownload(uri, outpoint, fileInfo) {
return (dispatch) => {
if (fileInfo.completed) {
dispatch({
type: ACTIONS.DOWNLOADING_STARTED,
type: ACTIONS.DOWNLOADING_COMPLETED,
data: {
uri,
outpoint,
fileInfo,
},
});
if (NativeModules.LbryDownloadManager) {
NativeModules.LbryDownloadManager.startDownload(uri, fileInfo.file_name ? fileInfo.file_name : '');
}
dispatch(doUpdateLoadStatus(uri, outpoint));
});
}
};
}
@@ -155,22 +74,10 @@ export function doStopDownloadingFile(uri, fileInfo) {
// Should also delete the file after the user stops downloading
dispatch(doDeleteFile(fileInfo.outpoint, uri));
if (NativeModules.LbryDownloadManager) {
NativeModules.LbryDownloadManager.stopDownload(uri, fileInfo.file_name ? fileInfo.file_name : '');
}
});
};
}
export function doDownloadFile(uri, streamInfo) {
return dispatch => {
const { outpoint } = streamInfo;
dispatch(doStartDownload(uri, outpoint));
dispatch(doClaimEligiblePurchaseRewards());
};
}
export function doSetPlayingUri(uri) {
return dispatch => {
dispatch({
@@ -180,133 +87,6 @@ export function doSetPlayingUri(uri) {
};
}
export function doLoadVideo(uri, failureCallback) {
return dispatch => {
dispatch({
type: ACTIONS.LOADING_VIDEO_STARTED,
data: {
uri,
},
});
Lbry.get({ uri })
.then(streamInfo => {
const timeout =
streamInfo === null || typeof streamInfo !== 'object' || streamInfo.error === 'Timeout';
if (timeout) {
dispatch(doSetPlayingUri(null));
dispatch({
type: ACTIONS.LOADING_VIDEO_FAILED,
data: { uri },
});
dispatch(doToast({
message: `File timeout for uri ${uri}`,
}));
if (failureCallback) {
failureCallback();
}
} else {
dispatch(doDownloadFile(uri, streamInfo));
}
})
.catch(() => {
dispatch(doSetPlayingUri(null));
dispatch({
type: ACTIONS.LOADING_VIDEO_FAILED,
data: { uri },
});
dispatch(doToast({
message: `Failed to download ${uri}, please try again. If this problem persists, visit https://lbry.com/faq/support for support.`,
}));
if (failureCallback) {
failureCallback();
}
});
};
}
export function doPurchaseUri(uri, specificCostInfo, failureCallback) {
return (dispatch, getState) => {
const state = getState();
const balance = selectBalance(state);
const fileInfo = makeSelectFileInfoForUri(uri)(state);
const metadata = makeSelectMetadataForUri(uri)(state);
const title = metadata ? metadata.title : uri;
const downloadingByOutpoint = selectDownloadingByOutpoint(state);
const alreadyDownloading = fileInfo && !!downloadingByOutpoint[fileInfo.outpoint];
function attemptPlay(cost, instantPurchaseMax = null) {
if (cost > 0 && (!instantPurchaseMax || cost > instantPurchaseMax)) {
// display alert
const formattedCost = formatCredits(cost, 2);
const unit = cost === 1 ? 'credit' : 'credits';
Alert.alert('Confirm purchase',
`This will purchase "${title}" for ${formattedCost} ${unit}`,
[
{ text: 'OK', onPress: () => dispatch(doLoadVideo(uri)) },
{ text: 'Cancel', style: 'cancel', onPress: () => failureCallback && failureCallback() }
],
{ cancelable: true });
} else {
dispatch(doLoadVideo(uri, failureCallback));
}
}
// we already fully downloaded the file.
if (fileInfo && fileInfo.completed) {
// If written_bytes is false that means the user has deleted/moved the
// file manually on their file system, so we need to dispatch a
// doLoadVideo action to reconstruct the file from the blobs
if (!fileInfo.written_bytes) dispatch(doLoadVideo(uri));
Promise.resolve();
return;
}
// we are already downloading the file
if (alreadyDownloading) {
Promise.resolve();
return;
}
const costInfo = makeSelectCostInfoForUri(uri)(state) || specificCostInfo;
const { cost } = costInfo;
if (cost > balance) {
dispatch(doSetPlayingUri(null));
dispatch(doToast({
message: 'Insufficient credits',
}));
if (failureCallback) {
failureCallback();
}
Promise.resolve();
return;
}
attemptPlay(cost);
/*if (cost === 0 || !makeSelectClientSetting(SETTINGS.INSTANT_PURCHASE_ENABLED)(state)) {
attemptPlay(cost);
} else {
const instantPurchaseMax = makeSelectClientSetting(SETTINGS.INSTANT_PURCHASE_MAX)(state);
if (instantPurchaseMax.currency === 'LBC') {
attemptPlay(cost, instantPurchaseMax.amount);
} else {
// Need to convert currency of instant purchase maximum before trying to play
Lbryio.getExchangeRates().then(({ LBC_USD }) => {
attemptPlay(cost, instantPurchaseMax.amount / LBC_USD);
});
}
}*/
};
}
export function doDeleteFile(outpoint, deleteFromComputer, abandonClaim) {
return (dispatch, getState) => {
Lbry.file_delete({
@@ -334,29 +114,5 @@ export function doDeleteFile(outpoint, deleteFromComputer, abandonClaim) {
outpoint,
},
});
//const totalProgress = selectTotalDownloadProgress(getState());
//setProgressBar(totalProgress);
};
}
export function doDeleteCompleteBlobs() {
return dispatch => {
dispatch({
type: Constants.ACTION_DELETE_COMPLETED_BLOBS,
data: {},
});
Lbry.file_list().then(files => {
files.forEach(fileInfo => {
if (fileInfo.completed) {
Lbry.file_set_status({ status: 'stop', sd_hash: fileInfo.sd_hash }).then(() => {
deleteBlobsForSdHash(fileInfo.sd_hash);
}).catch(() => {
deleteBlobsForSdHash(fileInfo.sd_hash);
});
}
});
});
};
}
+32 -1
View File
@@ -2,9 +2,16 @@ import Constants from 'constants';
const reducers = {};
const defaultState = {
stack: [ Constants.DRAWER_ROUTE_DISCOVER ] // Discover is always the first drawer route
stack: [ Constants.DRAWER_ROUTE_DISCOVER ], // Discover is always the first drawer route
playerVisible: false,
currentRoute: null
};
reducers[Constants.ACTION_SET_PLAYER_VISIBLE] = (state, action) =>
Object.assign({}, state, {
playerVisible: action.data.visible
});
reducers[Constants.ACTION_PUSH_DRAWER_STACK] = (state, action) => {
const routeName = action.data;
const newStack = state.stack.slice();
@@ -29,6 +36,30 @@ reducers[Constants.ACTION_POP_DRAWER_STACK] = (state, action) => {
}
};
// TODO: The ACTION_REACT_NAVIGATION_*** reducers are a workaround for the react
// navigation event listeners (willFocus, didFocus, etc) not working with the
// react-navigation-redux-helpers package.
reducers[Constants.ACTION_REACT_NAVGIATION_RESET] = (state, action) => {
return {
...state,
currentRoute: Constants.DRAWER_ROUTE_DISCOVER // default to Discover upon reset
}
}
reducers[Constants.ACTION_REACT_NAVIGATION_NAVIGATE] = (state, action) => {
return {
...state,
currentRoute: action.routeName
}
}
reducers[Constants.ACTION_REACT_NAVIGATION_REPLACE] = (state, action) => {
return {
...state,
currentRoute: action.routeName
}
}
export default function reducer(state = defaultState, action) {
const handler = reducers[action.type];
if (handler) return handler(state, action);
Loaded 100 of 174 files, more files were not shown because too many files have changed in this diff. Show more