Compare commits

..
77 Commits
Author SHA1 Message Date
Akinwale Ariwodola d45dac4587 bumpversion 0.2.1 --> 0.2.2 2018-09-30 17:00:39 +01:00
Akinwale Ariwodola 38292bcbcc Merge pull request #316 from lbryio/stop-download-tweaks
improve stop download experience
2018-09-28 20:58:22 +01:00
Akinwale Ariwodola 8b8cf9cd7a improve stop download experience 2018-09-26 21:11:55 +01:00
Akinwale Ariwodola 7c969cbe93 fix for red screen during phone number verification 2018-09-26 17:55:03 +01:00
Akinwale Ariwodola 3283cc447e Merge pull request #303 from ykris45/patch-1
add telegram link
2018-09-25 15:00:58 +01:00
Akinwale Ariwodola 810ba74e75 Merge pull request #313 from lbryio/blacklist
show blocked message for blacklisted content
2018-09-25 14:47:17 +01:00
Akinwale Ariwodola 5e1a20c5de Merge pull request #314 from lbryio/dismiss-reward-summary
dismiss button added to reward summary, and some style tweaks.
2018-09-25 14:46:33 +01:00
Akinwale Ariwodola 975c59a114 dismiss button added to reward summary, and some style tweaks. 2018-09-24 14:59:00 +01:00
Akinwale Ariwodola 51fcf04b0b show blocked message for blacklisted content 2018-09-24 14:19:34 +01:00
Akinwale Ariwodola d921347d73 updated readme for beta 2018-09-24 13:30:06 +01:00
YULIUS KURNIAWAN KRISTIANTO 5e25b542fb add telegram link 2018-09-18 00:48:44 +07:00
Akinwale Ariwodola 9b4ef98a3d bumpversion 0.2.0 --> 0.2.1 2018-09-14 14:10:30 -04:00
Akinwale Ariwodola 8a862439cc do not display reward summary if the user is approved for rewards 2018-09-14 13:39:18 -04:00
Akinwale Ariwodola 6719953cf1 fix React Native bundle 2018-09-14 11:52:56 -04:00
Akinwale Ariwodola 2bf73eb961 update state if user data changed 2018-09-14 11:28:34 -04:00
Akinwale Ariwodola fe5d711fea Merge pull request #293 from lbryio/rewards-eligible-check
do not display phone verification action for users who are already reward approved
2018-09-14 08:58:07 -04:00
Akinwale Ariwodola 33c8aaf36f do not display phone verification action for users who are already reward approved 2018-09-14 04:06:23 -04:00
Akinwale Ariwodola d5366b10fa Merge pull request #292 from lbryio/build-doc-fix
update build instructions with missing packages
2018-09-14 03:56:56 -04:00
Akinwale Ariwodola 50d07fd31f update build instructions with missing packages 2018-09-10 15:43:27 -04:00
Akinwale Ariwodola 792d64a33a Merge pull request #285 from lbryio/download-failed-callback
display the play / download button again upon a failure condition
2018-09-08 10:40:54 +01:00
Akinwale Ariwodola adc9550e58 display the play / download button again upon a failure condition 2018-09-08 10:11:52 +01:00
Akinwale Ariwodola 0638b9f133 ongoing pre-beta tasks (#284)
* tapping on the player controls container while it is visible should hide the container
* change 'click' to 'tap'
* add related content component
* file list item resolving display tweaks
* increase number of search results to 25
* fix name display for identity claims in search results
2018-09-05 14:43:39 +01:00
Akinwale Ariwodola 05531e0bc5 change 'alpha' to 'beta' in wallet warning 2018-09-03 20:53:09 +01:00
Akinwale Ariwodola 44ec2270f2 update lbryinc in package.json 2018-09-03 20:47:01 +01:00
Akinwale Ariwodola ffd4f474ed bumpversion 0.1.10 --> 0.2.0 2018-09-03 20:44:12 +01:00
Akinwale Ariwodola 2c22780c91 Merge pull request #281 from lbryio/mobile-platform
send Platform.OS as operating system value for the install/new request
2018-09-03 20:35:32 +01:00
Akinwale Ariwodola 1d03d09119 send Platform.OS as operating system value for the install/new request 2018-09-03 20:19:12 +01:00
Akinwale Ariwodola 404647c4cb add storage stats card to My LBRY downloads page (#278)
* add storage stats card to My LBRY downloads page
* add decimalPoints parameter to formatBytes method
* some more tweaks to notifications and startup
* cancel all notifications if the service is not running when the activity is destroyed
2018-09-03 03:00:54 +01:00
Akinwale Ariwodola c0b464ae36 implement phone verification (#274)
* implement phone verification
* update permissions in buildozer.spec
2018-09-03 02:57:54 +01:00
Akinwale Ariwodola e8185e0f9c cancel specific notifications instead of using cancelAll 2018-09-02 17:54:37 +01:00
Akinwale Ariwodola 0592c42df0 Unify notification channels for background service and background media player 2018-09-02 11:38:15 +01:00
Akinwale Ariwodola 87a50c494f use openDrawer in react-navigation v2. Tweak hardware back button behaviour. 2018-09-02 08:32:09 +01:00
Akinwale Ariwodola 8257d7b41d more navigation tweaks (#277)
* upgrade react-navigation module, implement associated code updates
* call resolveUri for a file list item if the claim is not yet resolved
2018-09-02 08:12:21 +01:00
Akinwale Ariwodola 77e471d671 Merge pull request #276 from lbryio/bg-media-notification-intent
group the background service and background media player notifications
2018-09-02 03:05:11 +01:00
Akinwale Ariwodola 92f5e6e77c group the background service and background media player notifications 2018-09-01 22:45:20 +01:00
Akinwale Ariwodola 4b7be60c27 better performance on lower end devices with react-native-fast-image (#275)
* thumbnail aspect ratio sizing tweaks
* show approximate values for formatted bytes
* truncate titles over 80 characters in the file item list component
2018-09-01 22:04:50 +01:00
Akinwale Ariwodola e9abbf256e implement my LBRY downloads page (#273) 2018-08-31 08:56:41 +01:00
Akinwale Ariwodola 002d8c7430 Merge pull request #272 from lbryio/search-results-tweaks
update thumbnail display in search results and add channel links
2018-08-31 00:51:00 +01:00
Akinwale Ariwodola 346c7a027d update thumbnail display in search results and add channel links 2018-08-31 00:39:25 +01:00
Akinwale Ariwodola 7313e2d1c4 implement touch to seek for media playback using the seek bar (#271) 2018-08-31 00:15:13 +01:00
Akinwale Ariwodola a34a8136c2 add time to start (in seconds) to Play track event for new downloads (#269)
* add time to start (in seconds) to Play track event for new downloads
* send time_to_start parameter with file/view call
2018-08-30 18:11:03 +01:00
Akinwale Ariwodola 3b76dca8f1 Merge pull request #270 from lbryio/ux-tweaks
some file page UX tweaks
2018-08-30 14:39:41 +01:00
Akinwale Ariwodola 30682bf8f5 Merge pull request #267 from lbryio/back-navigation-part-deux
create navigation button component and handle onPress events properly
2018-08-30 14:38:46 +01:00
Akinwale Ariwodola e7b83326d0 some file page UX tweaks 2018-08-30 13:48:29 +01:00
Akinwale Ariwodola ef55bd2719 create navigation button component and handle onPress events properly 2018-08-29 21:19:49 +01:00
Akinwale Ariwodola 0c29785a7e Merge pull request #265 from lbryio/thumbnails
tweak thumbnail aspect ratio and sizing on discover and search pages
2018-08-29 06:19:46 +01:00
Akinwale Ariwodola a5b67d4923 Merge pull request #266 from lbryio/blob-delete-revisited
do not delete the sd hash blob when deleting file blobs
2018-08-29 01:01:00 +01:00
Akinwale Ariwodola 34a4df96fc do not delete the sd hash blob when deleting file blobs 2018-08-28 21:10:11 +01:00
Akinwale Ariwodola eeacbbb979 tweak thumbnail aspect ratio and sizing on discover and search pages 2018-08-28 20:23:48 +01:00
Akinwale Ariwodola 2a010e2643 update package.json 2018-08-28 19:25:18 +01:00
Akinwale Ariwodola c25785ccf4 Mobile rewards (#251) 2018-08-28 11:59:14 +01:00
Akinwale Ariwodola 050fc2b29e tweaks to the download notifications (#260) 2018-08-28 07:29:12 +01:00
Akinwale Ariwodola e1e8fa410a escape special characters for the encoded path (#262) 2018-08-27 18:14:29 +01:00
Akinwale Ariwodola becf21b7ea Merge pull request #263 from lbryio/fix-search
submit search queries from the omnibar on the search page
2018-08-27 16:53:36 +01:00
Akinwale Ariwodola 9c3f2f44da show animated activity indicator after the user presses the Play button (#261) 2018-08-27 16:53:03 +01:00
Akinwale Ariwodola 793541474a submit search queries from the omnibar on the search page 2018-08-27 09:01:05 +01:00
Akinwale Ariwodola 94f9ad6cc4 display floating wallet balance (#252)
* display floating wallet balance
2018-08-24 11:10:30 +01:00
Sean Yesmunt 9a89d4c44c Merge pull request #250 from lbryio/search-selector
use new search suggestion selector
2018-08-22 11:13:41 -04:00
Akinwale Ariwodola b99ffa0395 add stop action button to LBRY service notification (#248) 2018-08-22 13:50:59 +01:00
Akinwale Ariwodola f926dc28be Merge pull request #249 from lbryio/omnibar-text-alignment
URI bar text visible from the left when it's not focused
2018-08-21 06:10:10 +01:00
Sean Yesmunt 5b92d477e2 use new search suggestion selector 2018-08-21 00:30:36 -04:00
Akinwale Ariwodola df561cc582 Background media controls (#242)
* create background control notification when background play is enabled
2018-08-20 16:00:16 +01:00
Akinwale Ariwodola da60aeb71b delete individual blob files for completed file downloads to save space (#234) 2018-08-17 19:11:15 +01:00
Akinwale Ariwodola 684f4867c3 URI bar text visible from the left when it's not focused 2018-08-17 15:08:19 +01:00
Akinwale Ariwodola 82a7846e6d Merge pull request #238 from lbryio/hide-navigation-bar-fix
obtain the proper activity reference in the utility module
2018-08-16 19:27:54 +01:00
Akinwale Ariwodola a9199661a4 obtain the proper activity reference in the utility module 2018-08-16 18:42:07 +01:00
Akinwale Ariwodola d07fc29a96 Merge pull request #237 from lbryio/video-aspect-ratio-tweak
better media aspect ratio handling
2018-08-16 18:04:46 +01:00
Akinwale Ariwodola 066919259c better media aspect ratio handling 2018-08-16 17:50:59 +01:00
Akinwale Ariwodola a094ba7d5c Merge pull request #236 from lbryio/email-verify-tweak
tweaks to the user email verification process
2018-08-16 13:43:02 +01:00
Akinwale Ariwodola 76a9485f0b tweaks to the user email verification process 2018-08-16 13:21:28 +01:00
Akinwale Ariwodola 413ef66701 complete authentication flow and email verification link implementation (#232)
* complete authentication flow and email verification link implementation
* send appVersion and deviceId with authentication request
2018-08-16 10:48:34 +01:00
Akinwale Ariwodola 1e91a53a8a Merge pull request #233 from lbryio/python-requirements-tweak
Update Twisted version. Remove pycrypto recipe.
2018-08-15 17:02:21 +01:00
Akinwale Ariwodola 0db7e51d69 bumpversion 0.1.9 --> 0.1.10 2018-08-14 18:23:59 +01:00
Akinwale Ariwodola cdf7f75058 Merge pull request #231 from lbryio/notification-channel-hotfix
Fix service notification channel for older Android versions (prior to Oreo)
2018-08-14 18:19:32 +01:00
Akinwale Ariwodola 84e4151f42 use new libgmp mirror for builds 2018-08-14 17:45:54 +01:00
Akinwale Ariwodola 3a9729de06 Fix service notification channel for older Android versions (prior to Oreo) 2018-08-14 16:15:04 +01:00
Akinwale Ariwodola a5dfe0c586 Update Twisted version. Remove pycrypto recipe. 2018-06-03 12:20:15 +01:00
350 changed files with 4024 additions and 710 deletions

No files matched your search

+1 -1
View File
@@ -17,7 +17,7 @@ Based on the quickstart instructions at http://buildozer.readthedocs.io/en/lates
```
sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install build-essential 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 openjdk-8-jdk unzip zlib1g-dev zlib1g:i386 m4 libc6-dev-i386
sudo apt-get install autoconf autogen build-essential libtool python python-pip python-openssl 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 openjdk-8-jdk unzip zlib1g-dev zlib1g:i386 m4 libc6-dev-i386
```
Alternatively, the JDK available from http://www.oracle.com/technetwork/java/javase/downloads/index.html can be installed instead of the `openjdk-8-jdk` package.
+1 -1
View File
@@ -8,7 +8,7 @@ An Android browser and wallet for the [LBRY](https://lbry.io) network. This app
## Installation
The minimum supported Android version is 5.0 Lollipop. There are two ways to install:
1. Via the Google Play Store. While in alpha, it will not show in the Play Store unless you sign up [here](https://lbry.io/android-alpha).
1. Via the Google Play Store. Anyone can join the [open beta](https://play.google.com/apps/testing/io.lbry.browser) in order to install the app from the Play Store.
1. Direct APK install available at [http://build.lbry.io/android/latest.apk](http://build.lbry.io/android/latest.apk). You will need to enable installation from third-party sources on your device in order to install from this source.
## Usage
+202 -22
View File
@@ -2440,6 +2440,15 @@
"object-assign": "^4.1.1"
}
},
"create-react-context": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/create-react-context/-/create-react-context-0.2.3.tgz",
"integrity": "sha512-CQBmD0+QGgTaxDL3OX1IDXYqjkp2It4RIbcb99jS6AEg27Ga+a9G3JtK6SIu0HBwPLZlmwt9F7UwWA4Bn92Rag==",
"requires": {
"fbjs": "^0.8.0",
"gud": "^1.0.0"
}
},
"cross-spawn": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-5.1.0.tgz",
@@ -3351,6 +3360,11 @@
}
}
},
"fuse.js": {
"version": "2.6.2",
"resolved": "https://registry.npmjs.org/fuse.js/-/fuse.js-2.6.2.tgz",
"integrity": "sha1-1dmU/alvVDtaUd84tyzsnMYNneo="
},
"gauge": {
"version": "1.2.7",
"resolved": "https://registry.npmjs.org/gauge/-/gauge-1.2.7.tgz",
@@ -3422,6 +3436,11 @@
"resolved": "https://registry.npmjs.org/globals/-/globals-9.18.0.tgz",
"integrity": "sha512-S0nG3CLEQiY/ILxqtztTWH/3iRRdyBLw6KMDxnKMchrtbj2OFmehVh0WUCfW3DUrIgx/qFrJPICrq4Z4sTR9UQ=="
},
"google-libphonenumber": {
"version": "2.0.19",
"resolved": "https://registry.npmjs.org/google-libphonenumber/-/google-libphonenumber-2.0.19.tgz",
"integrity": "sha512-kwtbruT+eyiof081cxT1tltMTxgTOq3CQhUoEYBROC+vNf+COPqzfKJtVnDvgXQe4SzfbnAYkP8KoSpbJBIlSg=="
},
"graceful-fs": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz",
@@ -3432,6 +3451,11 @@
"resolved": "https://registry.npmjs.org/growly/-/growly-1.3.0.tgz",
"integrity": "sha1-8QdIy+dq+WS3yWyTxrzCivEgwIE="
},
"gud": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/gud/-/gud-1.0.0.tgz",
"integrity": "sha512-zGEOVKFM5sVPPrYs7J5/hYEw2Pof8KCyOwyhG8sAF26mCAeUFAcYPu1mwB7hhpIP29zOIBaDqwuHdLp0jvZXjw=="
},
"has-ansi": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/has-ansi/-/has-ansi-2.0.0.tgz",
@@ -3958,13 +3982,21 @@
}
},
"lbry-redux": {
"version": "github:lbryio/lbry-redux#467e48c77b8004cef738e950bdcc67654748ae9f",
"version": "github:lbryio/lbry-redux#31f7afa8a37f5741dac01fc1ecdf153f3bed95dc",
"from": "github:lbryio/lbry-redux",
"requires": {
"proxy-polyfill": "0.1.6",
"reselect": "^3.0.0"
}
},
"lbryinc": {
"version": "github:lbryio/lbryinc#f2fff2a331578aef84eb77c108f976967afc50e0",
"from": "github:lbryio/lbryinc",
"requires": {
"lbry-redux": "github:lbryio/lbry-redux#31f7afa8a37f5741dac01fc1ecdf153f3bed95dc",
"reselect": "^3.0.0"
}
},
"lcid": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/lcid/-/lcid-1.0.0.tgz",
@@ -4066,6 +4098,11 @@
"resolved": "https://registry.npmjs.org/lodash.throttle/-/lodash.throttle-4.1.1.tgz",
"integrity": "sha1-wj6RtxAkKscMN/HhzaknTMOb8vQ="
},
"lodash.toarray": {
"version": "4.4.0",
"resolved": "https://registry.npmjs.org/lodash.toarray/-/lodash.toarray-4.4.0.tgz",
"integrity": "sha1-JMS/zWsvuji/0FlNsRedjptlZWE="
},
"lodash.unset": {
"version": "4.5.2",
"resolved": "https://registry.npmjs.org/lodash.unset/-/lodash.unset-4.5.2.tgz",
@@ -4532,6 +4569,14 @@
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.1.tgz",
"integrity": "sha1-KzJxhOiZIQEXeyhWP7XnECrNDKk="
},
"node-emoji": {
"version": "1.8.1",
"resolved": "https://registry.npmjs.org/node-emoji/-/node-emoji-1.8.1.tgz",
"integrity": "sha512-+ktMAh1Jwas+TnGodfCfjUbJKoANqPaJFN0z0iqh41eqD8dvguNzcitVSBSVK1pidz0AqGbLKcoVuVLRVZ/aVg==",
"requires": {
"lodash.toarray": "^4.4.0"
}
},
"node-fetch": {
"version": "1.7.3",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-1.7.3.tgz",
@@ -5003,6 +5048,15 @@
"resolved": "https://registry.npmjs.org/pseudomap/-/pseudomap-1.0.2.tgz",
"integrity": "sha1-8FKijacOYYkX7wqKw0wa5aaChrM="
},
"query-string": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/query-string/-/query-string-6.1.0.tgz",
"integrity": "sha512-pNB/Gr8SA8ff8KpUFM36o/WFAlthgaThka5bV19AD9PNTH20Pwq5Zxodif2YyHwrctp6SkL4GqlOot0qR/wGaw==",
"requires": {
"decode-uri-component": "^0.2.0",
"strict-uri-encode": "^2.0.0"
}
},
"randomatic": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/randomatic/-/randomatic-3.0.0.tgz",
@@ -5159,6 +5213,44 @@
}
}
},
"react-native-country-picker-modal": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/react-native-country-picker-modal/-/react-native-country-picker-modal-0.6.2.tgz",
"integrity": "sha1-upcRi+Q3O+DBHNUeRF5r1Eji8co=",
"requires": {
"fuse.js": "2.6.2",
"lodash": "4.12.0",
"node-emoji": "1.8.1",
"prop-types": "15.6.0",
"react-native-safe-area-view": "^0.7.0",
"world-countries": "1.8.0"
},
"dependencies": {
"lodash": {
"version": "4.12.0",
"resolved": "http://registry.npmjs.org/lodash/-/lodash-4.12.0.tgz",
"integrity": "sha1-K9bcRqBA9Z5obJcu0h2T3FkFMlg="
},
"prop-types": {
"version": "15.6.0",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.6.0.tgz",
"integrity": "sha1-zq8IMCL8RrSjX2nhPvda7Q1jmFY=",
"requires": {
"fbjs": "^0.8.16",
"loose-envify": "^1.3.1",
"object-assign": "^4.1.1"
}
},
"react-native-safe-area-view": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/react-native-safe-area-view/-/react-native-safe-area-view-0.7.0.tgz",
"integrity": "sha512-SjLdW/Th0WVMhyngH4O6yC21S+O4U4AAG3QxBr7fZ2ftgjXSpKbDHAhEpxBdFwei6HsnsC2h9oYMtPpaW9nfGg==",
"requires": {
"hoist-non-react-statics": "^2.3.1"
}
}
}
},
"react-native-dismiss-keyboard": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/react-native-dismiss-keyboard/-/react-native-dismiss-keyboard-1.0.0.tgz",
@@ -5180,6 +5272,11 @@
"react-native-drawer-layout": "1.3.2"
}
},
"react-native-fast-image": {
"version": "5.0.3",
"resolved": "https://registry.npmjs.org/react-native-fast-image/-/react-native-fast-image-5.0.3.tgz",
"integrity": "sha512-70XlQPt8b7yQSMwUEEIN5jTx7KOx1EBD2XhIRIEHChfNv5Gwn8dh28RSo/Dq9qezf4CWJXO3CAb4lq+Hu9d0vw=="
},
"react-native-fetch-blob": {
"version": "0.10.8",
"resolved": "https://registry.npmjs.org/react-native-fetch-blob/-/react-native-fetch-blob-0.10.8.tgz",
@@ -5217,17 +5314,27 @@
"react-native-image-pan-zoom": "^2.1.2"
}
},
"react-native-phone-input": {
"version": "github:lbryio/react-native-phone-input#60fdef484e8bf27328c7fb6a203baab9eb9cd4a1",
"from": "github:lbryio/react-native-phone-input",
"requires": {
"google-libphonenumber": "^2.0.9",
"lodash": "^4.17.4",
"prop-types": "^15.5.10"
}
},
"react-native-safe-area-view": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/react-native-safe-area-view/-/react-native-safe-area-view-0.7.0.tgz",
"integrity": "sha512-SjLdW/Th0WVMhyngH4O6yC21S+O4U4AAG3QxBr7fZ2ftgjXSpKbDHAhEpxBdFwei6HsnsC2h9oYMtPpaW9nfGg==",
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/react-native-safe-area-view/-/react-native-safe-area-view-0.9.0.tgz",
"integrity": "sha512-y792ScHMzvgwquxL869S9CER4dwiFu/TuCiXdy0xBtygmScMK4eWonnUT65LvOrsSSdr8o6XEK1mbI51h6ozvQ==",
"requires": {
"hoist-non-react-statics": "^2.3.1"
}
},
"react-native-tab-view": {
"version": "github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
"from": "react-native-tab-view@github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb",
"version": "0.0.77",
"resolved": "https://registry.npmjs.org/react-native-tab-view/-/react-native-tab-view-0.0.77.tgz",
"integrity": "sha512-9vjD4Ly1Zlum1Y4g23ODpi/F3gYIUIsKWrsZO/Oh5cuX1eiB1DRVn11nY1z+j/hsQfhfyW6nDlmySyDvYQvYCA==",
"requires": {
"prop-types": "^15.6.0"
}
@@ -5260,6 +5367,13 @@
"which-module": "^2.0.0",
"y18n": "^3.2.1",
"yargs-parser": "^7.0.0"
},
"dependencies": {
"y18n": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz",
"integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE="
}
}
}
}
@@ -5273,28 +5387,82 @@
}
},
"react-navigation": {
"version": "1.5.12",
"resolved": "https://registry.npmjs.org/react-navigation/-/react-navigation-1.5.12.tgz",
"integrity": "sha512-+i0ymFHokQxjv0/0knBUtxC1zuyvLgbDVPFU7ScKxT25SGVh2exuRjYwXImF234/qtYMskfY7bfhEjGLcXPySQ==",
"version": "2.12.1",
"resolved": "https://registry.npmjs.org/react-navigation/-/react-navigation-2.12.1.tgz",
"integrity": "sha512-C+do+STPvvd/5LbaDhrZyf1P8tCeffttdlHyIRe1NgGg8Nj93FZHWOThi2hnmEZ75kXsS/JGxox4DDPqYVAxeQ==",
"requires": {
"clamp": "^1.0.1",
"create-react-context": "^0.2.1",
"hoist-non-react-statics": "^2.2.0",
"path-to-regexp": "^1.7.0",
"prop-types": "^15.5.10",
"react-lifecycles-compat": "^3.0.2",
"react-native-drawer-layout-polyfill": "^1.3.2",
"react-native-safe-area-view": "^0.7.0",
"react-native-tab-view": "github:react-navigation/react-native-tab-view#36ebd834d78b841fc19778c966465d02fd1213bb"
"query-string": "^6.1.0",
"react-lifecycles-compat": "^3",
"react-native-safe-area-view": "^0.9.0",
"react-navigation-deprecated-tab-navigator": "1.3.0",
"react-navigation-drawer": "0.5.0",
"react-navigation-stack": "0.2.3",
"react-navigation-tabs": "0.6.0"
}
},
"react-navigation-deprecated-tab-navigator": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/react-navigation-deprecated-tab-navigator/-/react-navigation-deprecated-tab-navigator-1.3.0.tgz",
"integrity": "sha512-Cm+qYOPFWbvvcuv0YYX0ioYwLGgw7XAqdhAfpo3sIr3trxRW8871ePmfFOPezjQtz4v6ItjZt6LPgtBAVZoroQ==",
"requires": {
"react-native-tab-view": "^0.0.77"
}
},
"react-navigation-drawer": {
"version": "0.5.0",
"resolved": "https://registry.npmjs.org/react-navigation-drawer/-/react-navigation-drawer-0.5.0.tgz",
"integrity": "sha512-F1y593uC6pqBMGH+Omz75oNODEbxB/s0EGO8QtYwu1NmOOEUuuLA+c14zm+pgMsI4HlDabiHxPkWqsgGz25xVQ==",
"requires": {
"react-native-drawer-layout-polyfill": "^1.3.2"
}
},
"react-navigation-redux-helpers": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/react-navigation-redux-helpers/-/react-navigation-redux-helpers-1.0.7.tgz",
"integrity": "sha512-JUD3ycYS0EZLIzuaZVQ4/c3KMrEztPLqXzVV/qifeWQQLq01BmPnIuR7VWluSfZ98cgGlX9hY5r72wwgvvrfjw==",
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/react-navigation-redux-helpers/-/react-navigation-redux-helpers-2.0.5.tgz",
"integrity": "sha512-oxDpPqmXdzUJJ32ef8NY6Cu9XDJNO4DU91p0+ZgleEfaZwec9t2ua6sKwQyOfdWQPDwbJAxiXfZIAe3ao5MG6Q==",
"requires": {
"invariant": "^2.2.2"
}
},
"react-navigation-stack": {
"version": "0.2.3",
"resolved": "https://registry.npmjs.org/react-navigation-stack/-/react-navigation-stack-0.2.3.tgz",
"integrity": "sha512-xjVqiI/ztcQt45jxQ3vfO8Lr+9bVq+0J/lRhMdZCvCDwiyOVuB64wx7qPNJW16pnBBLiI5h6H7uhWE3rAT0r/w=="
},
"react-navigation-tabs": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/react-navigation-tabs/-/react-navigation-tabs-0.6.0.tgz",
"integrity": "sha512-Ax1rujJ51R1Jrz7b5bHUAIgsYC1VrFws+d3hxlPy5dXG84iJdV5dnDFRvdQMDDfDZc+NDx2a223lAYsc3p2+XA==",
"requires": {
"hoist-non-react-statics": "^2.5.0",
"prop-types": "^15.6.1",
"react-lifecycles-compat": "^3.0.4",
"react-native-safe-area-view": "^0.7.0",
"react-native-tab-view": "^1.0.0"
},
"dependencies": {
"react-native-safe-area-view": {
"version": "0.7.0",
"resolved": "https://registry.npmjs.org/react-native-safe-area-view/-/react-native-safe-area-view-0.7.0.tgz",
"integrity": "sha512-SjLdW/Th0WVMhyngH4O6yC21S+O4U4AAG3QxBr7fZ2ftgjXSpKbDHAhEpxBdFwei6HsnsC2h9oYMtPpaW9nfGg==",
"requires": {
"hoist-non-react-statics": "^2.3.1"
}
},
"react-native-tab-view": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/react-native-tab-view/-/react-native-tab-view-1.0.2.tgz",
"integrity": "sha512-x8I43V1X7/AyMnIwnqJGMU54LqQRlV6vJ9irbls9asA/axdHIdxagPIV6Jx1ttFe/bPKhFwXL+lRYdYxGyUlWg==",
"requires": {
"prop-types": "^15.6.1"
}
}
}
},
"react-proxy": {
"version": "1.1.8",
"resolved": "https://registry.npmjs.org/react-proxy/-/react-proxy-1.1.8.tgz",
@@ -6310,6 +6478,11 @@
"resolved": "https://registry.npmjs.org/stream-buffers/-/stream-buffers-2.2.0.tgz",
"integrity": "sha1-kdX1Ew0c75bc+n9yaUUYh0HQnuQ="
},
"strict-uri-encode": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/strict-uri-encode/-/strict-uri-encode-2.0.0.tgz",
"integrity": "sha1-ucczDHBChi9rFC3CdLvMWGbONUY="
},
"string-width": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
@@ -6724,6 +6897,11 @@
"resolved": "https://registry.npmjs.org/wordwrap/-/wordwrap-1.0.0.tgz",
"integrity": "sha1-J1hIEIkUVqQXHI0CJkQa3pDLyus="
},
"world-countries": {
"version": "1.8.0",
"resolved": "https://registry.npmjs.org/world-countries/-/world-countries-1.8.0.tgz",
"integrity": "sha1-F/SOfoRwrFohNq1pON/GVvwry5U="
},
"wrap-ansi": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-2.1.0.tgz",
@@ -6825,11 +7003,6 @@
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.1.tgz",
"integrity": "sha1-pcbVMr5lbiPbgg77lDofBJmNY68="
},
"y18n": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz",
"integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE="
},
"yallist": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-2.1.2.tgz",
@@ -6853,6 +7026,13 @@
"which-module": "^2.0.0",
"y18n": "^3.2.1",
"yargs-parser": "^7.0.0"
},
"dependencies": {
"y18n": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-3.2.1.tgz",
"integrity": "sha1-bRX7qITAhnnA136I53WegR4H+kE="
}
}
},
"yargs-parser": {
+7 -2
View File
@@ -6,16 +6,21 @@
"start": "node node_modules/react-native/local-cli/cli.js start"
},
"dependencies": {
"base-64": "^0.1.0",
"lbry-redux": "lbryio/lbry-redux",
"lbryinc": "lbryio/lbryinc",
"moment": "^2.22.1",
"react": "16.2.0",
"react-native": "0.55.3",
"react-native-country-picker-modal": "^0.6.2",
"react-native-fast-image": "^5.0.3",
"react-native-fetch-blob": "^0.10.8",
"react-native-image-zoom-viewer": "^2.2.5",
"react-native-phone-input": "lbryio/react-native-phone-input",
"react-native-vector-icons": "^5.0.0",
"react-native-video": "lbryio/react-native-video#exoplayer-lbry-android",
"react-navigation": "^1.5.12",
"react-navigation-redux-helpers": "^1.0.1",
"react-navigation": "^2.12.1",
"react-navigation-redux-helpers": "^2.0.5",
"react-redux": "^5.0.3",
"redux": "^3.6.0",
"redux-logger": "3.0.6",
+196 -55
View File
@@ -1,23 +1,28 @@
import React from 'react';
import AboutPage from '../page/about';
import DiscoverPage from '../page/discover';
import DownloadsPage from '../page/downloads';
import FilePage from '../page/file';
import FirstRunScreen from '../page/firstRun';
import SearchPage from '../page/search';
import RewardsPage from '../page/rewards';
import TrendingPage from '../page/trending';
import SearchPage from '../page/search';
import SettingsPage from '../page/settings';
import SplashScreen from '../page/splash';
import TransactionHistoryPage from '../page/transactionHistory';
import WalletPage from '../page/wallet';
import SearchInput from '../component/searchInput';
import {
addNavigationHelpers,
DrawerNavigator,
StackNavigator,
createDrawerNavigator,
createStackNavigator,
NavigationActions
} from 'react-navigation';
import {
addListener,
reduxifyNavigator,
createReactNavigationReduxMiddleware,
} from 'react-navigation-redux-helpers';
import { connect } from 'react-redux';
import { addListener } from '../utils/redux';
import {
AppState,
AsyncStorage,
@@ -27,19 +32,40 @@ import {
TextInput,
ToastAndroid
} from 'react-native';
import { SETTINGS, doHideNotification, selectNotification } from 'lbry-redux';
import { doDeleteCompleteBlobs } from '../redux/actions/file';
import { SETTINGS, doHideNotification, doNotify, selectNotification } from 'lbry-redux';
import {
doUserEmailVerify,
doUserEmailVerifyFailure,
selectEmailToVerify,
selectEmailVerifyIsPending,
selectEmailVerifyErrorMessage,
selectUser
} from 'lbryinc';
import { makeSelectClientSetting } from '../redux/selectors/settings';
import { decode as atob } from 'base-64';
import { dispatchNavigateToUri } from '../utils/helper';
import Colors from '../styles/colors';
import Constants from '../constants';
import Icon from 'react-native-vector-icons/FontAwesome5';
import NavigationButton from '../component/navigationButton';
import discoverStyle from '../styles/discover';
import searchStyle from '../styles/search';
import SearchRightHeaderIcon from "../component/searchRightHeaderIcon";
import SearchRightHeaderIcon from '../component/searchRightHeaderIcon';
const discoverStack = StackNavigator({
const menuNavigationButton = (navigation) => <NavigationButton
name="bars"
size={24}
style={discoverStyle.drawerMenuButton}
iconStyle={discoverStyle.drawerHamburger}
onPress={() => navigation.openDrawer() } />
const discoverStack = createStackNavigator({
Discover: {
screen: DiscoverPage,
navigationOptions: ({ navigation }) => ({
title: 'Discover',
headerLeft: <Icon name="bars" size={24} style={discoverStyle.drawerHamburger} onPress={() => navigation.navigate('DrawerOpen')} />,
headerLeft: menuNavigationButton(navigation),
})
},
File: {
@@ -56,25 +82,45 @@ const discoverStack = StackNavigator({
})
}
}, {
headerMode: 'screen',
headerMode: 'screen'
});
const trendingStack = StackNavigator({
const trendingStack = createStackNavigator({
Trending: {
screen: TrendingPage,
navigationOptions: ({ navigation }) => ({
title: 'Trending',
headerLeft: <Icon name="bars" size={24} style={discoverStyle.drawerHamburger} onPress={() => navigation.navigate('DrawerOpen')} />,
headerLeft: menuNavigationButton(navigation),
})
}
});
const walletStack = StackNavigator({
const myLbryStack = createStackNavigator({
Downloads: {
screen: DownloadsPage,
navigationOptions: ({ navigation }) => ({
title: 'My LBRY',
headerLeft: menuNavigationButton(navigation),
})
}
});
const rewardsStack = createStackNavigator({
Rewards: {
screen: RewardsPage,
navigationOptions: ({ navigation }) => ({
title: 'Rewards',
headerLeft: menuNavigationButton(navigation),
})
}
});
const walletStack = createStackNavigator({
Wallet: {
screen: WalletPage,
navigationOptions: ({ navigation }) => ({
title: 'Wallet',
headerLeft: <Icon name="bars" size={24} style={discoverStyle.drawerHamburger} onPress={() => navigation.navigate('DrawerOpen')} />,
headerLeft: menuNavigationButton(navigation),
})
},
TransactionHistory: {
@@ -88,18 +134,39 @@ const walletStack = StackNavigator({
headerMode: 'screen'
});
const drawer = DrawerNavigator({
DiscoverStack: { screen: discoverStack },
TrendingStack: { screen: trendingStack },
WalletStack: { screen: walletStack },
Settings: { screen: SettingsPage, navigationOptions: { drawerLockMode: 'locked-closed' } },
About: { screen: AboutPage, navigationOptions: { drawerLockMode: 'locked-closed' } }
const drawer = createDrawerNavigator({
DiscoverStack: { screen: discoverStack, navigationOptions: {
title: 'Discover', drawerIcon: ({ tintColor }) => <Icon name="compass" size={20} style={{ color: tintColor }} />
}},
TrendingStack: { screen: trendingStack, navigationOptions: {
title: 'Trending', drawerIcon: ({ tintColor }) => <Icon name="fire" size={20} style={{ color: tintColor }} />
}},
MyLBRYStack: { screen: myLbryStack, navigationOptions: {
title: 'My LBRY', drawerIcon: ({ tintColor }) => <Icon name="folder" size={20} style={{ color: tintColor }} />
}},
Rewards: { screen: rewardsStack, navigationOptions: {
drawerIcon: ({ tintColor }) => <Icon name="trophy" size={20} style={{ color: tintColor }} />
}},
WalletStack: { screen: walletStack, navigationOptions: {
title: 'Wallet', drawerIcon: ({ tintColor }) => <Icon name="wallet" size={20} style={{ color: tintColor }} />
}},
Settings: { screen: SettingsPage, navigationOptions: {
drawerLockMode: 'locked-closed',
drawerIcon: ({ tintColor }) => <Icon name="cog" size={20} style={{ color: tintColor }} />
}},
About: { screen: AboutPage, navigationOptions: {
drawerLockMode: 'locked-closed',
drawerIcon: ({ tintColor }) => <Icon name="info" size={20} style={{ color: tintColor }} />
}}
}, {
drawerWidth: 300,
headerMode: 'none'
headerMode: 'none',
contentOptions: {
activeTintColor: Colors.LbryGreen
}
});
export const AppNavigator = new StackNavigator({
export const AppNavigator = new createStackNavigator({
FirstRun: {
screen: FirstRunScreen,
navigationOptions: {
@@ -119,32 +186,44 @@ export const AppNavigator = new StackNavigator({
headerMode: 'none'
});
export const reactNavigationMiddleware = createReactNavigationReduxMiddleware(
"root",
state => state.nav,
);
const App = reduxifyNavigator(AppNavigator, "root");
const appMapStateToProps = (state) => ({
state: state.nav,
});
const ReduxAppNavigator = connect(appMapStateToProps)(App);
class AppWithNavigationState extends React.Component {
static supportedDisplayTypes = ['toast'];
constructor() {
super();
this.state = {
emailVerifyDone: false
};
}
componentWillMount() {
AppState.addEventListener('change', this._handleAppStateChange);
BackHandler.addEventListener('hardwareBackPress', function() {
const { dispatch, nav } = this.props;
// There should be a better way to check this
if (nav.routes.length > 0) {
if (nav.routes[0].routes && nav.routes[0].routes.length > 0) {
const subRoutes = nav.routes[0].routes[0].routes;
const lastRoute = subRoutes[subRoutes.length - 1];
if (nav.routes[0].routes[0].index > 0 &&
['About', 'Settings'].indexOf(lastRoute.key) > -1) {
dispatch(NavigationActions.back());
return true;
}
}
if (nav.routes[0].routeName === 'Main') {
if (nav.routes[0].routes[0].routes[0].index > 0) {
const mainRoute = nav.routes[0];
if (mainRoute.index > 0 ||
mainRoute.routes[0].index > 0 /* Discover stack index */ ||
mainRoute.routes[4].index > 0 /* Wallet stack index */ ||
mainRoute.index >= 5 /* Settings and About screens */) {
dispatch(NavigationActions.back());
return true;
}
}
}
return false;fo
return false;
}.bind(this));
}
@@ -160,11 +239,18 @@ class AppWithNavigationState extends React.Component {
componentWillUpdate(nextProps) {
const { dispatch } = this.props;
const { notification } = nextProps;
const {
notification,
emailToVerify,
emailVerifyPending,
emailVerifyErrorMessage,
user
} = nextProps;
if (notification) {
const { displayType, message } = notification;
let currentDisplayType;
if (displayType.length) {
if (displayType && displayType.length) {
for (let i = 0; i < displayType.length; i++) {
const type = displayType[i];
if (AppWithNavigationState.supportedDisplayTypes.indexOf(type) > -1) {
@@ -176,15 +262,39 @@ class AppWithNavigationState extends React.Component {
currentDisplayType = displayType;
}
if (!currentDisplayType && message) {
// default to toast if no display type set and there is a message specified
currentDisplayType = 'toast';
}
if ('toast' === currentDisplayType) {
ToastAndroid.show(message, ToastAndroid.SHORT);
ToastAndroid.show(message, ToastAndroid.LONG);
}
dispatch(doHideNotification());
}
if (user &&
!emailVerifyPending &&
!this.state.emailVerifyDone &&
(emailToVerify || emailVerifyErrorMessage)) {
AsyncStorage.getItem(Constants.KEY_SHOULD_VERIFY_EMAIL).then(shouldVerify => {
if ('true' === shouldVerify) {
this.setState({ emailVerifyDone: true });
const message = emailVerifyErrorMessage ?
String(emailVerifyErrorMessage) : 'Your email address was successfully verified.';
if (!emailVerifyErrorMessage) {
AsyncStorage.removeItem(Constants.KEY_FIRST_RUN_EMAIL);
}
AsyncStorage.removeItem(Constants.KEY_SHOULD_VERIFY_EMAIL);
dispatch(doNotify({ message, displayType: ['toast'] }));
}
});
}
}
_handleAppStateChange = (nextAppState) => {
const { backgroundPlayEnabled, dispatch } = this.props;
// Check if the app was suspended
if (AppState.currentState && AppState.currentState.match(/inactive|background/)) {
AsyncStorage.getItem('firstLaunchTime').then(start => {
@@ -193,41 +303,72 @@ class AppWithNavigationState extends React.Component {
// If so, this needs to be included as a property when tracking
AsyncStorage.setItem('firstLaunchSuspended', 'true');
}
// Background media
if (backgroundPlayEnabled && NativeModules.BackgroundMedia && window.currentMediaInfo) {
const { title, channel, uri } = window.currentMediaInfo;
NativeModules.BackgroundMedia.showPlaybackNotification(title, channel, uri, false);
}
});
}
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();
}
}
}
_handleUrl = (evt) => {
const { dispatch } = this.props;
const { dispatch, nav } = this.props;
if (evt.url) {
const navigateAction = NavigationActions.navigate({
routeName: 'File',
key: evt.url,
params: { uri: evt.url }
});
dispatch(navigateAction);
if (evt.url.startsWith('lbry://?verify=')) {
this.setState({ emailVerifyDone: false });
let verification = {};
try {
verification = JSON.parse(atob(evt.url.substring(15)));
} catch (error) {
console.log(error);
}
if (verification.token && verification.recaptcha) {
AsyncStorage.setItem(Constants.KEY_SHOULD_VERIFY_EMAIL, 'true');
try {
dispatch(doUserEmailVerify(verification.token, verification.recaptcha));
} catch (error) {
const message = 'Invalid Verification Token';
dispatch(doUserEmailVerifyFailure(message));
dispatch(doNotify({ message, displayType: ['toast'] }));
}
} else {
dispatch(doNotify({
message: 'Invalid Verification URI',
displayType: ['toast'],
}));
}
} else {
dispatchNavigateToUri(dispatch, nav, evt.url);
}
}
}
render() {
const { dispatch, nav } = this.props;
return (
<AppNavigator
navigation={addNavigationHelpers({
dispatch,
state: nav,
addListener,
})}
/>
);
return <ReduxAppNavigator />;
}
}
const mapStateToProps = state => ({
backgroundPlayEnabled: makeSelectClientSetting(SETTINGS.BACKGROUND_PLAY_ENABLED)(state),
keepDaemonRunning: makeSelectClientSetting(SETTINGS.KEEP_DAEMON_RUNNING)(state),
nav: state.nav,
notification: selectNotification(state),
keepDaemonRunning: makeSelectClientSetting(SETTINGS.KEEP_DAEMON_RUNNING)(state),
showNsfw: makeSelectClientSetting(SETTINGS.SHOW_NSFW)(state)
emailToVerify: selectEmailToVerify(state),
emailVerifyPending: selectEmailVerifyIsPending(state),
emailVerifyErrorMessage: selectEmailVerifyErrorMessage(state),
showNsfw: makeSelectClientSetting(SETTINGS.SHOW_NSFW)(state),
user: selectUser(state)
});
export default connect(mapStateToProps)(AppWithNavigationState);
+3 -2
View File
@@ -12,7 +12,8 @@ export default class Button extends React.PureComponent {
text,
icon,
theme,
onPress
onPress,
onLayout
} = this.props;
let styles = [buttonStyle.button, buttonStyle.row];
@@ -41,7 +42,7 @@ export default class Button extends React.PureComponent {
}
return (
<TouchableOpacity disabled={disabled} style={styles} onPress={onPress}>
<TouchableOpacity disabled={disabled} style={styles} onPress={onPress} onLayout={onLayout}>
{icon && <Icon name={icon} size={18} color={'light' === theme ? Colors.DarkGrey : Colors.White} />}
{text && (text.trim().length > 0) && <Text style={textStyles}>{text}</Text>}
</TouchableOpacity>
@@ -0,0 +1,22 @@
import { connect } from 'react-redux';
import {
doUserEmailNew,
selectEmailNewErrorMessage,
selectEmailNewIsPending,
selectEmailToVerify
} from 'lbryinc';
import { doNotify } 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(doNotify(data))
});
export default connect(select, perform)(EmailRewardSubcard);
@@ -0,0 +1,98 @@
// @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,
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 });
} else {
this.setState({ email: emailToVerify });
}
});
}
componentWillReceiveProps(nextProps) {
const { emailNewErrorMessage, emailNewPending } = nextProps;
const { notify } = this.props;
if (this.state.verifyStarted && !emailNewPending) {
if (emailNewErrorMessage) {
notify({ message: String(emailNewErrorMessage), displayType: ['toast']});
this.setState({ verifyStarted: false });
} else {
notify({
message: 'Please follow the instructions in the email sent to your address to continue.',
displayType: ['toast']
});
}
}
}
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 } = 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.',
displayType: ['toast'],
});
}
this.setState({ verifyStarted: true });
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;
@@ -17,7 +17,7 @@ const select = (state, props) => ({
});
const perform = dispatch => ({
purchaseUri: uri => dispatch(doPurchaseUri(uri)),
purchaseUri: (uri, failureCallback) => dispatch(doPurchaseUri(uri, null, failureCallback)),
restartDownload: (uri, outpoint) => dispatch(doStartDownload(uri, outpoint)),
fetchCostInfo: uri => dispatch(doFetchCostInfoForUri(uri)),
});
+8 -4
View File
@@ -42,10 +42,12 @@ class FileDownloadButton extends React.PureComponent {
loading,
doPause,
style,
openFile
openFile,
onButtonLayout,
onStartDownloadFailed
} = this.props;
if (loading || downloading) {
if ((fileInfo && !fileInfo.stopped) || loading || downloading) {
const progress =
fileInfo && fileInfo.written_bytes ? fileInfo.written_bytes / fileInfo.total_bytes * 100 : 0,
label = fileInfo ? progress.toFixed(0) + '% complete' : 'Connecting...';
@@ -67,11 +69,12 @@ class FileDownloadButton extends React.PureComponent {
return (
<Button icon={isPlayable ? 'play' : null}
text={isPlayable ? 'Play' : 'Download'}
onLayout={onButtonLayout}
style={[style, fileDownloadButtonStyle.container]} onPress={() => {
if (NativeModules.Mixpanel) {
NativeModules.Mixpanel.track('Purchase Uri', { Uri: uri });
}
purchaseUri(uri);
purchaseUri(uri, onStartDownloadFailed);
if (isPlayable && onPlay) {
this.props.onPlay();
}
@@ -79,7 +82,8 @@ class FileDownloadButton extends React.PureComponent {
);
} else if (fileInfo && fileInfo.download_path) {
return (
<TouchableOpacity style={[style, fileDownloadButtonStyle.container]} onPress={openFile}>
<TouchableOpacity onLayout={onButtonLayout}
style={[style, fileDownloadButtonStyle.container]} onPress={openFile}>
<Text style={fileDownloadButtonStyle.text}>Open</Text>
</TouchableOpacity>
);
+1 -1
View File
@@ -5,8 +5,8 @@ import {
makeSelectMetadataForUri,
makeSelectFileInfoForUri,
makeSelectIsUriResolving,
selectRewardContentClaimIds
} from 'lbry-redux';
import { selectRewardContentClaimIds } from 'lbryinc';
import { selectShowNsfw } from '../../redux/selectors/settings';
import FileItem from './view';
+13 -5
View File
@@ -2,8 +2,11 @@ import React from 'react';
import { normalizeURI } from 'lbry-redux';
import { NavigationActions } from 'react-navigation';
import { NativeModules, Text, View, TouchableOpacity } from 'react-native';
import { navigateToUri } from '../../utils/helper';
import Colors from '../../styles/colors';
import FileItemMedia from '../fileItemMedia';
import FilePrice from '../filePrice';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Link from '../link';
import NsfwOverlay from '../nsfwOverlay';
import discoverStyle from '../../styles/discover';
@@ -37,6 +40,7 @@ class FileItem extends React.PureComponent {
isResolvingUri,
rewardedContentClaimIds,
style,
mediaStyle,
navigation
} = this.props;
@@ -53,23 +57,27 @@ class FileItem extends React.PureComponent {
if (NativeModules.Mixpanel) {
NativeModules.Mixpanel.track('Discover Tap', { Uri: uri });
}
navigation.navigate({ routeName: 'File', key: uri, params: { uri } });
navigateToUri(navigation, uri);
}
}>
<FileItemMedia title={title}
thumbnail={thumbnail}
blurRadius={obscureNsfw ? 15 : 0}
resizeMode="cover"
isResolvingUri={isResolvingUri} />
isResolvingUri={isResolvingUri}
style={mediaStyle} />
<FilePrice uri={uri} style={discoverStyle.filePriceContainer} textStyle={discoverStyle.filePriceText} />
<Text style={discoverStyle.fileItemName}>{title}</Text>
<View style={isRewardContent ? discoverStyle.rewardTitleContainer : null}>
<Text style={[discoverStyle.fileItemName, discoverStyle.rewardTitle]}>{title}</Text>
{isRewardContent && <Icon style={discoverStyle.rewardIcon} name="award" size={20} />}
</View>
{channelName &&
<Link style={discoverStyle.channelName} text={channelName} onPress={() => {
const channelUri = normalizeURI(channelName);
navigation.navigate({ routeName: 'File', key: channelUri, params: { uri: channelUri }});
navigateToUri(navigation, channelUri);
}} />}
</TouchableOpacity>
{obscureNsfw && <NsfwOverlay onPress={() => navigation.navigate('Settings')} />}
{obscureNsfw && <NsfwOverlay onPress={() => navigation.navigate({ routeName: 'Settings', key: 'settingsPage' })} />}
</View>
);
}
+36 -6
View File
@@ -1,6 +1,7 @@
import React from 'react';
import { ActivityIndicator, Image, Text, View } from 'react-native';
import Colors from '../../styles/colors';
import FastImage from 'react-native-fast-image'
import fileItemMediaStyle from '../../styles/fileItemMedia';
class FileItemMedia extends React.PureComponent {
@@ -18,6 +19,10 @@ class FileItemMedia extends React.PureComponent {
fileItemMediaStyle.autothumbOrange,
];
state: {
imageLoadFailed: false
};
componentWillMount() {
this.setState({
autoThumbStyle:
@@ -27,21 +32,46 @@ class FileItemMedia extends React.PureComponent {
});
}
getFastImageResizeMode(resizeMode) {
switch (resizeMode) {
case "contain":
return FastImage.resizeMode.contain;
case "stretch":
return FastImage.resizeMode.stretch;
case "center":
return FastImage.resizeMode.center;
default:
return FastImage.resizeMode.cover;
}
}
render() {
let style = this.props.style;
const { blurRadius, isResolvingUri, thumbnail, title, resizeMode } = this.props;
const atStyle = this.state.autoThumbStyle;
if (thumbnail && ((typeof thumbnail) === 'string')) {
if (thumbnail && ((typeof thumbnail) === 'string') && !this.state.imageLoadFailed) {
if (style == null) {
style = fileItemMediaStyle.thumbnail;
}
if (blurRadius > 0) {
// No blur radius support in FastImage yet
return (
<Image
source={{uri: thumbnail}}
blurRadius={blurRadius}
resizeMode={resizeMode ? resizeMode : "cover"}
style={style}
/>);
}
return (
<Image source={{uri: thumbnail}}
blurRadius={blurRadius}
resizeMode={resizeMode ? resizeMode : "cover"}
style={style} />
<FastImage
source={{uri: thumbnail}}
onError={() => this.setState({ imageLoadFailed: true })}
resizeMode={this.getFastImageResizeMode(resizeMode)}
style={style}
/>
);
}
@@ -7,10 +7,11 @@ import {
makeSelectIsUriResolving,
} from 'lbry-redux';
import { selectShowNsfw } from '../../redux/selectors/settings';
import SearchResultItem from './view';
import FileListItem from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
fileInfo: makeSelectFileInfoForUri(props.uri)(state),
isDownloaded: !!makeSelectFileInfoForUri(props.uri)(state),
metadata: makeSelectMetadataForUri(props.uri)(state),
isResolvingUri: makeSelectIsUriResolving(props.uri)(state),
@@ -21,4 +22,4 @@ const perform = dispatch => ({
resolveUri: uri => dispatch(doResolveUri(uri))
});
export default connect(select, perform)(SearchResultItem);
export default connect(select, perform)(FileListItem);
+114
View File
@@ -0,0 +1,114 @@
import React from 'react';
import { normalizeURI, parseURI } from 'lbry-redux';
import {
ActivityIndicator,
Platform,
ProgressBarAndroid,
Text,
TouchableOpacity,
View
} from 'react-native';
import { navigateToUri, formatBytes } from '../../utils/helper';
import Colors from '../../styles/colors';
import FileItemMedia from '../fileItemMedia';
import Link from '../../component/link';
import NsfwOverlay from '../../component/nsfwOverlay';
import fileListStyle from '../../styles/fileList';
class FileListItem extends React.PureComponent {
getStorageForFileInfo = (fileInfo) => {
if (!fileInfo.completed) {
const written = formatBytes(fileInfo.written_bytes);
const total = formatBytes(fileInfo.total_bytes);
return `(${written} / ${total})`;
}
return formatBytes(fileInfo.written_bytes);
}
formatTitle = (title) => {
if (!title) {
return title;
}
return (title.length > 80) ? title.substring(0, 77).trim() + '...' : title;
}
getDownloadProgress = (fileInfo) => {
return Math.ceil((fileInfo.written_bytes / fileInfo.total_bytes) * 100);
}
componentDidMount() {
const { claim, resolveUri, uri } = this.props;
if (!claim) {
resolveUri(uri);
}
}
render() {
const {
claim,
fileInfo,
metadata,
isResolvingUri,
isDownloaded,
style,
onPress,
navigation
} = 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;
let channel;
if (claim) {
name = claim.name;
channel = claim.channel_name;
}
return (
<View style={style}>
<TouchableOpacity style={style} onPress={onPress}>
<FileItemMedia style={fileListStyle.thumbnail}
blurRadius={obscureNsfw ? 15 : 0}
resizeMode="cover"
title={(title || name)}
thumbnail={metadata ? metadata.thumbnail : null} />
<View style={fileListStyle.detailsContainer}>
{!title && !name && !channel && isResolving && (
<View>
{(!title && !name) && <Text style={fileListStyle.uri}>{uri}</Text>}
{(!title && !name) && <View style={fileListStyle.row}>
<ActivityIndicator size={"small"} color={Colors.LbryGreen} />
</View>}
</View>)}
{(title || name) && <Text style={fileListStyle.title}>{this.formatTitle(title) || this.formatTitle(name)}</Text>}
{channel &&
<Link style={fileListStyle.publisher} text={channel} onPress={() => {
const channelUri = normalizeURI(channel);
navigateToUri(navigation, channelUri);
}} />}
{fileInfo &&
<View style={fileListStyle.downloadInfo}>
<Text style={fileListStyle.downloadStorage}>{this.getStorageForFileInfo(fileInfo)}</Text>
{!fileInfo.completed &&
<View style={fileListStyle.progress}>
<View style={[fileListStyle.progressCompleted, { flex: this.getDownloadProgress(fileInfo) } ]} />
<View style={[fileListStyle.progressRemaining, { flex: (100 - this.getDownloadProgress(fileInfo)) } ]} />
</View>}
</View>
}
</View>
</TouchableOpacity>
{obscureNsfw && <NsfwOverlay onPress={() => navigation.navigate({ routeName: 'Settings', key: 'settingsPage' })} />}
</View>
);
}
}
export default FileListItem;
@@ -0,0 +1,9 @@
import { connect } from 'react-redux';
import { selectBalance } from 'lbry-redux';
import FloatingWalletBalance from './view';
const select = state => ({
balance: selectBalance(state),
});
export default connect(select, null)(FloatingWalletBalance);
@@ -0,0 +1,30 @@
// @flow
import React from 'react';
import { ActivityIndicator, Text, TouchableOpacity, View } from 'react-native';
import { formatCredits } from 'lbry-redux'
import Address from '../address';
import Button from '../button';
import Colors from '../../styles/colors';
import floatingButtonStyle from '../../styles/floatingButton';
type Props = {
balance: number,
};
class FloatingWalletBalance extends React.PureComponent<Props> {
render() {
const { balance, navigation } = this.props;
return (
<TouchableOpacity style={[floatingButtonStyle.container, floatingButtonStyle.bottomRight]}
onPress={() => navigation && navigation.navigate({ routeName: 'WalletStack' })}>
{isNaN(balance) && <ActivityIndicator size="small" color={Colors.White} />}
<Text style={floatingButtonStyle.text}>
{(balance || balance === 0) && (formatCredits(balance, 2) + ' LBC')}
</Text>
</TouchableOpacity>
);
}
}
export default FloatingWalletBalance;
+6 -8
View File
@@ -10,10 +10,10 @@ export default class Link extends React.PureComponent {
}
this.addTappedStyle = this.addTappedStyle.bind(this)
}
handlePress = () => {
const { error, href, navigation, notify } = this.props;
if (navigation && href.startsWith('#')) {
navigation.navigate(href.substring(1));
} else {
@@ -32,14 +32,14 @@ export default class Link extends React.PureComponent {
this.setState({ tappedStyle: true });
setTimeout(() => { this.setState({ tappedStyle: false }); }, 2000);
}
render() {
const {
onPress,
style,
text
} = this.props;
let styles = [];
if (style) {
if (style.length) {
@@ -52,11 +52,9 @@ export default class Link extends React.PureComponent {
if (this.props.effectOnTap && this.state.tappedStyle) {
styles.push(this.props.effectOnTap);
}
return (
<Text style={styles} onPress={onPress ? onPress : this.handlePress}>
{text}
</Text>
<Text style={styles} onPress={onPress ? onPress : this.handlePress}>{text}</Text>
);
}
};
+1 -2
View File
@@ -6,6 +6,5 @@ import MediaPlayer from './view';
const select = state => ({
backgroundPlayEnabled: makeSelectClientSetting(SETTINGS.BACKGROUND_PLAY_ENABLED)(state),
});
const perform = dispatch => ({});
export default connect(select, perform)(MediaPlayer);
export default connect(select, null)(MediaPlayer);
+69 -8
View File
@@ -1,6 +1,7 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
DeviceEventEmitter,
NativeModules,
PanResponder,
Text,
@@ -29,10 +30,11 @@ class MediaPlayer extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
encodedFilePath: null,
rate: 1,
volume: 1,
muted: false,
resizeMode: 'stretch',
resizeMode: 'contain',
duration: 0.0,
currentTime: 0.0,
paused: !props.autoPlay,
@@ -91,9 +93,8 @@ class MediaPlayer extends React.PureComponent {
}
if (this.state.firstPlay) {
if (NativeModules.Mixpanel) {
const { uri } = this.props;
NativeModules.Mixpanel.track('Play', { Uri: uri });
if (this.props.onPlaybackStarted) {
this.props.onPlaybackStarted();
}
this.setState({ firstPlay: false });
this.hidePlayerControls();
@@ -114,6 +115,11 @@ class MediaPlayer extends React.PureComponent {
this.hidePlayerControls();
}
manualHidePlayerControls = () => {
this.clearControlsTimeout();
this.setState({ areControlsVisible: false });
}
hidePlayerControls() {
const player = this;
let timeout = setTimeout(() => {
@@ -122,6 +128,14 @@ class MediaPlayer extends React.PureComponent {
player.setState({ controlsTimeout: timeout });
}
togglePlayerControls = () => {
if (this.state.areControlsVisible) {
this.manualHidePlayerControls();
} else {
this.showPlayerControls();
}
}
togglePlay = () => {
this.showPlayerControls();
this.setState({ paused: !this.state.paused });
@@ -131,7 +145,6 @@ class MediaPlayer extends React.PureComponent {
this.showPlayerControls();
const { onFullscreenToggled } = this.props;
this.setState({ fullscreenMode: !this.state.fullscreenMode }, () => {
this.setState({ resizeMode: this.state.fullscreenMode ? 'contain' : 'stretch' });
if (onFullscreenToggled) {
onFullscreenToggled(this.state.fullscreenMode);
}
@@ -225,10 +238,19 @@ class MediaPlayer extends React.PureComponent {
}
componentDidMount() {
const { assignPlayer } = this.props;
if (assignPlayer) {
assignPlayer(this);
}
this.setSeekerPosition(this.calculateSeekerPosition());
DeviceEventEmitter.addListener('onBackgroundPlayPressed', this.play);
DeviceEventEmitter.addListener('onBackgroundPausePressed', this.pause);
}
componentWillUnmount() {
DeviceEventEmitter.removeListener('onBackgroundPlayPressed', this.play);
DeviceEventEmitter.removeListener('onBackgroundPausePressed', this.pause);
this.clearControlsTimeout();
this.setState({ paused: true, fullscreenMode: false });
const { onFullscreenToggled } = this.props;
@@ -237,6 +259,24 @@ class MediaPlayer extends React.PureComponent {
}
}
play = () => {
this.setState({ paused: false }, this.updateBackgroundMediaNotification);
}
pause = () => {
this.setState({ paused: true }, this.updateBackgroundMediaNotification);
}
updateBackgroundMediaNotification = () => {
const { backgroundPlayEnabled } = this.props;
if (backgroundPlayEnabled) {
if (NativeModules.BackgroundMedia && window.currentMediaInfo) {
const { title, channel, uri } = window.currentMediaInfo;
NativeModules.BackgroundMedia.showPlaybackNotification(title, channel, uri, this.state.paused);
}
}
}
renderPlayerControls() {
if (this.state.areControlsVisible) {
return (
@@ -262,9 +302,26 @@ class MediaPlayer extends React.PureComponent {
}
getEncodedDownloadPath = (fileInfo) => {
if (this.state.encodedFilePath) {
return this.state.encodedFilePath;
}
const { file_name: fileName } = fileInfo;
const encodedFileName = encodeURIComponent(fileName).replace(/!/g, '%21');
return fileInfo.download_path.replace(new RegExp(fileName, 'g'), encodedFileName);
const encodedFilePath = fileInfo.download_path.replace(fileName, encodedFileName);
this.setState({ encodedFilePath });
return encodedFilePath;
}
onSeekerTouchAreaPressed = (evt) => {
if (evt && evt.nativeEvent) {
const newSeekerPosition = evt.nativeEvent.locationX;
if (!isNaN(newSeekerPosition)) {
const time = this.state.duration * (newSeekerPosition / this.seekerWidth);
this.setSeekerPosition(newSeekerPosition);
this.seekTo(time);
}
}
}
render() {
@@ -286,7 +343,7 @@ class MediaPlayer extends React.PureComponent {
return (
<View style={styles} onLayout={onLayout}>
<Video source={{ uri: 'file:///' + this.getEncodedDownloadPath(fileInfo) }}
ref={(ref: Video) => { this.video = ref }}
ref={(ref: Video) => { this.video = ref; }}
resizeMode={this.state.resizeMode}
playInBackground={backgroundPlayEnabled}
style={mediaPlayerStyle.player}
@@ -298,7 +355,7 @@ class MediaPlayer extends React.PureComponent {
onEnd={this.onEnd}
/>
<TouchableOpacity style={mediaPlayerStyle.playerControls} onPress={this.showPlayerControls}>
<TouchableOpacity style={mediaPlayerStyle.playerControls} onPress={this.togglePlayerControls}>
{this.renderPlayerControls()}
</TouchableOpacity>
@@ -320,6 +377,10 @@ class MediaPlayer extends React.PureComponent {
{ left: this.state.seekerPosition }]} { ...this.seekResponder.panHandlers }>
<View style={this.state.seeking ? mediaPlayerStyle.bigSeekerCircle : mediaPlayerStyle.seekerCircle} />
</View>
<TouchableOpacity
style={[mediaPlayerStyle.seekerTouchArea,
(this.state.fullscreenMode ? mediaPlayerStyle.seekerTouchAreaFs : mediaPlayerStyle.seekerTouchAreaContained)]}
onPress={this.onSeekerTouchAreaPressed} />
</View>}
</View>
);
@@ -0,0 +1,4 @@
import { connect } from 'react-redux';
import NavigationButton from './view';
export default connect()(NavigationButton);
@@ -0,0 +1,18 @@
import React from 'react';
import Icon from 'react-native-vector-icons/FontAwesome5';
import { TouchableOpacity } from 'react-native';
class NavigationButton extends React.PureComponent {
render() {
const { iconStyle, name, onPress, size, style } = this.props;
return (
<TouchableOpacity onPress={onPress} style={style}>
<Icon name={name} size={size} style={iconStyle} />
</TouchableOpacity>
);
}
};
export default NavigationButton;
+8 -3
View File
@@ -9,6 +9,7 @@ import {
View
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome5';
import NavigationButton from '../navigationButton';
import pageHeaderStyle from '../../styles/pageHeader';
const APPBAR_HEIGHT = Platform.OS === 'ios' ? 44 : 56;
@@ -34,9 +35,13 @@ class PageHeader extends React.PureComponent {
{title}
</AnimatedText>
</View>
<TouchableOpacity style={pageHeaderStyle.left}>
<Icon name="arrow-left" size={24} onPress={onBackPressed} style={pageHeaderStyle.backIcon} />
</TouchableOpacity>
<NavigationButton
name="arrow-left"
style={pageHeaderStyle.left}
size={24}
iconStyle={pageHeaderStyle.backIcon}
onPress={onBackPressed}
/>
</View>
</View>
</View>
@@ -0,0 +1,28 @@
import { connect } from 'react-redux';
import { doNotify } 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(doNotify(data)),
});
export default connect(select, perform)(PhoneNumberRewardSubcard);
@@ -0,0 +1,253 @@
// @flow
import React from 'react';
import {
ActivityIndicator,
AsyncStorage,
DeviceEventEmitter,
NativeModules,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native';
import Button from '../button';
import Colors from '../../styles/colors';
import Constants from '../../constants';
import CountryPicker from 'react-native-country-picker-modal';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Link from '../link';
import PhoneInput from 'react-native-phone-input';
import rewardStyle from '../../styles/reward';
class PhoneNumberRewardSubcard extends React.PureComponent {
phoneInput = null;
picker = null;
constructor(props) {
super(props);
this.state = {
canReceiveSms: false,
cca2: 'US',
codeVerifyStarted: false,
codeVerifySuccessful: false,
countryCode: null,
newPhoneAdded: false,
number: null,
verificationCode: null,
};
}
componentDidMount() {
DeviceEventEmitter.addListener('onReceiveSmsPermissionGranted', this.receiveSmsPermissionGranted);
DeviceEventEmitter.addListener('onVerificationCodeReceived', this.receiveVerificationCode);
const { phone } = this.props;
if (phone && String(phone).trim().length > 0) {
this.setState({ newPhoneAdded: true });
}
if (NativeModules.UtilityModule) {
NativeModules.UtilityModule.canReceiveSms().then(canReceiveSms => this.setState({ canReceiveSms }));
}
}
componentWillUnmount() {
DeviceEventEmitter.removeListener('onReceiveSmsPermissionGranted', this.receiveSmsPermissionGranted);
DeviceEventEmitter.removeListener('onVerificationCodeReceived', this.receiveVerificationCode);
}
componentDidUpdate(prevProps) {
const {
phoneVerifyIsPending,
phoneVerifyErrorMessage,
notify,
phoneNewErrorMessage,
phoneNewIsPending,
onPhoneVerifySuccessful
} = this.props;
if (!phoneNewIsPending && (phoneNewIsPending !== prevProps.phoneNewIsPending)) {
if (phoneNewErrorMessage) {
notify({ message: String(phoneNewErrorMessage), displayType: ['toast'] });
} else {
this.setState({ newPhoneAdded: true });
}
}
if (!phoneVerifyIsPending && (phoneVerifyIsPending !== prevProps.phoneVerifyIsPending)) {
if (phoneVerifyErrorMessage) {
notify({ message: String(phoneVerifyErrorMessage), displayType: ['toast'] });
this.setState({ codeVerifyStarted: false });
} else {
notify({ message: 'Your phone number was successfully verified.', displayType: ['toast'] });
this.setState({ codeVerifySuccessful: true });
if (onPhoneVerifySuccessful) {
onPhoneVerifySuccessful();
}
}
}
}
receiveSmsPermissionGranted = () => {
this.setState({ canReceiveSms: true });
}
receiveVerificationCode = (evt) => {
if (!this.state.newPhoneAdded || this.state.codeVerifySuccessful) {
return;
}
const { verifyPhone } = this.props;
this.setState({ codeVerifyStarted: true });
verifyPhone(evt.code);
}
onAllowAccessPressed = () => {
if (!NativeModules.UtilityModule) {
return notify({
message: 'The required permission could not be obtained due to a missing module.',
displayType: ['toast']
});
}
NativeModules.UtilityModule.requestReceiveSmsPermission();
}
onSendTextPressed = () => {
const { addUserPhone, notify } = this.props;
if (!this.phoneInput.isValidNumber()) {
return notify({
message: 'Please provide a valid telephone number.',
displayType: ['toast']
});
}
const countryCode = this.phoneInput.getCountryCode();
const number = this.phoneInput.getValue().replace('+' + countryCode, '');
this.setState({ countryCode, number });
addUserPhone(number, countryCode);
}
onVerifyPressed = () => {
if (this.state.codeVerifyStarted) {
return;
}
const { verifyPhone } = this.props;
this.setState({ codeVerifyStarted: true });
verifyPhone(this.state.verificationCode);
}
onPressFlag = () => {
if (this.picker) {
this.picker.openModal();
}
}
selectCountry(country) {
this.phoneInput.selectCountry(country.cca2.toLowerCase());
this.setState({ cca2: country.cca2 });
}
handleChangeText = (text) => {
this.setState({ verificationCode: text });
};
render() {
const {
phoneVerifyIsPending,
phoneVerifyErrorMessage,
phone,
phoneErrorMessage,
phoneNewIsPending
} = this.props;
if (this.state.codeVerifySuccessful) {
return null;
}
return (
<View style={rewardStyle.subcard}>
<Text style={rewardStyle.subtitle}>Pending action: Verify Phone Number</Text>
{!this.state.canReceiveSms &&
<View style={rewardStyle.smsPermissionContainer}>
<Text style={[rewardStyle.bottomMarginMedium, rewardStyle.subcardText]}>
You can grant access to the receive SMS permission in order to verify phone number. Alternatively, you can enter the verification code manually.
</Text>
<Button
style={rewardStyle.actionButton}
text={"Allow access"}
onPress={this.onAllowAccessPressed}
/>
</View>}
<View style={rewardStyle.phoneVerificationContainer}>
{!this.state.newPhoneAdded &&
<View>
<Text style={[rewardStyle.bottomMarginMedium, rewardStyle.subcardText]}>Please enter your phone number to continue.</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>}
{this.state.newPhoneAdded &&
<View>
{!phoneVerifyIsPending && !this.codeVerifyStarted &&
<View>
<Text style={[rewardStyle.bottomMarginSmall, rewardStyle.subcardText]}>
Please enter the verification code.
</Text>
<TextInput
style={rewardStyle.verificationCodeInput}
keyboardType="numeric"
placeholder="0000"
underlineColorAndroid="transparent"
value={this.state.verificationCode}
onChangeText={text => this.handleChangeText(text)}
/>
<Button
style={[rewardStyle.actionButton, rewardStyle.topMarginSmall ]}
text={"Verify"}
onPress={this.onVerifyPressed} />
</View>
}
{phoneVerifyIsPending &&
<View>
<Text style={rewardStyle.subcardText}>Verifying your phone number...</Text>
<ActivityIndicator
color={Colors.LbryGreen}
size="small"
style={[rewardStyle.loading, rewardStyle.topMarginMedium]} />
</View>}
</View>
}
</View>
<CountryPicker
ref={(picker) => { this.picker = picker; }}
cca2={this.state.cca2}
filterable={true}
onChange={value => this.selectCountry(value)}
showCallingCode={true}
translation="eng">
<View />
</CountryPicker>
</View>
);
}
};
export default PhoneNumberRewardSubcard;
+23
View File
@@ -0,0 +1,23 @@
import { connect } from 'react-redux';
import {
makeSelectClaimForUri,
doSearch,
makeSelectRecommendedContentForUri,
selectIsSearching,
} from 'lbry-redux';
import RelatedContent from './view';
const select = (state, props) => ({
claim: makeSelectClaimForUri(props.uri)(state),
recommendedContent: makeSelectRecommendedContentForUri(props.uri)(state),
isSearching: selectIsSearching(state),
});
const perform = dispatch => ({
search: query => dispatch(doSearch(query, 10, undefined, true)),
});
export default connect(
select,
perform
)(RelatedContent);
+66
View File
@@ -0,0 +1,66 @@
import React from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';
import { navigateToUri } from '../../utils/helper';
import Colors from '../../styles/colors';
import FileListItem from '../fileListItem';
import fileListStyle from '../../styles/fileList';
import relatedContentStyle from '../../styles/relatedContent';
export default class RelatedContent extends React.PureComponent<Props> {
constructor() {
super();
this.didSearch = undefined;
}
componentDidMount() {
this.getRecommendedContent();
}
componentDidUpdate(prevProps: Props) {
const { claim, uri } = this.props;
if (uri !== prevProps.uri) {
this.didSearch = false;
}
if (claim && !this.didSearch) {
this.getRecommendedContent();
}
}
getRecommendedContent() {
const { claim, search } = this.props;
if (claim && claim.value && claim.value.stream && claim.value.stream.metadata) {
const { title } = claim.value.stream.metadata;
search(title);
this.didSearch = true;
}
}
didSearch: ?boolean;
render() {
const { recommendedContent, isSearching, navigation } = this.props;
if (!isSearching && (!recommendedContent || recommendedContent.length === 0)) {
return null;
}
return (
<View style={relatedContentStyle.container}>
<Text style={relatedContentStyle.title}>Related Content</Text>
{recommendedContent && recommendedContent.map(recommendedUri => (
<FileListItem
style={fileListStyle.item}
key={recommendedUri}
uri={recommendedUri}
navigation={navigation}
onPress={() => navigateToUri(navigation, recommendedUri, { autoplay: true })} />
))}
{isSearching && <ActivityIndicator size="small" color={Colors.LbryGreen} style={relatedContentStyle.loading} />}
</View>
);
}
}
+29
View File
@@ -0,0 +1,29 @@
import { connect } from 'react-redux';
import { doNotify } from 'lbry-redux';
import {
doClaimRewardType,
doClaimRewardClearError,
makeSelectClaimRewardError,
makeSelectIsRewardClaimPending,
} from 'lbryinc';
import RewardCard from './view';
const makeSelect = () => {
const selectIsPending = makeSelectIsRewardClaimPending();
const selectError = makeSelectClaimRewardError();
const select = (state, props) => ({
errorMessage: selectError(state, props),
isPending: selectIsPending(state, props),
});
return select;
};
const perform = dispatch => ({
claimReward: reward => dispatch(doClaimRewardType(reward.reward_type, true)),
clearError: reward => dispatch(doClaimRewardClearError(reward)),
notify: data => dispatch(doNotify(data))
});
export default connect(makeSelect, perform)(RewardCard);
+95
View File
@@ -0,0 +1,95 @@
// @flow
import React from 'react';
import { ActivityIndicator, Text, TouchableOpacity, View } from 'react-native';
import Colors from '../../styles/colors';
import Icon from 'react-native-vector-icons/FontAwesome5';
import Link from '../link';
import rewardStyle from '../../styles/reward';
type Props = {
canClaim: bool,
onClaimPress: object,
reward: {
id: string,
reward_title: string,
reward_amount: number,
transaction_id: string,
created_at: string,
reward_description: string,
reward_type: string,
},
};
class RewardCard extends React.PureComponent<Props> {
state = {
claimStarted: false
};
componentWillReceiveProps(nextProps) {
const { errorMessage, isPending } = nextProps;
const { clearError, notify, reward } = this.props;
if (this.state.claimStarted && !isPending) {
if (errorMessage && errorMessage.trim().length > 0) {
notify({ message: errorMessage, displayType: ['toast'] });
clearError(reward);
} else {
notify({ message: 'Reward successfully claimed!', displayType: ['toast'] });
}
this.setState({ claimStarted: false });
}
}
onClaimPress = () => {
const {
canClaim,
claimReward,
notify,
reward
} = this.props;
if (!canClaim) {
notify({ message: 'Unfortunately, you are not eligible to claim this reward at this time.', displayType: ['toast'] });
return;
}
this.setState({ claimStarted: true }, () => {
claimReward(reward);
});
}
render() {
const { canClaim, isPending, onClaimPress, reward } = this.props;
const claimed = !!reward.transaction_id;
return (
<View style={[rewardStyle.rewardCard, rewardStyle.row]}>
<View style={rewardStyle.leftCol}>
{!isPending && <TouchableOpacity onPress={() => {
if (!claimed) {
this.onClaimPress();
}
}}>
<Icon name={claimed ? "check-circle" : "circle"}
style={claimed ? rewardStyle.claimed : (canClaim ? rewardStyle.unclaimed : rewardStyle.disabled)}
size={20} />
</TouchableOpacity>}
{isPending && <ActivityIndicator size="small" color={Colors.LbryGreen} />}
</View>
<View style={rewardStyle.midCol}>
<Text style={rewardStyle.rewardTitle}>{reward.reward_title}</Text>
<Text style={rewardStyle.rewardDescription}>{reward.reward_description}</Text>
{claimed && <Link style={rewardStyle.link}
href={`https://explorer.lbry.io/tx/${reward.transaction_id}`}
text={reward.transaction_id.substring(0, 7)}
error={'The transaction URL could not be opened'} />}
</View>
<View style={rewardStyle.rightCol}>
<Text style={rewardStyle.rewardAmount}>{reward.reward_amount}</Text>
<Text style={rewardStyle.rewardCurrency}>LBC</Text>
</View>
</View>
);
}
};
export default RewardCard;
+17
View File
@@ -0,0 +1,17 @@
import { connect } from 'react-redux';
import { doNotify } from 'lbry-redux';
import { doRewardList, selectUnclaimedRewardValue, selectFetchingRewards, selectUser } from 'lbryinc';
import RewardSummary from './view';
const select = state => ({
unclaimedRewardAmount: selectUnclaimedRewardValue(state),
fetching: selectFetchingRewards(state),
user: selectUser(state)
});
const perform = dispatch => ({
fetchRewards: () => dispatch(doRewardList()),
notify: data => dispatch(doNotify(data))
});
export default connect(select, perform)(RewardSummary);
+68
View File
@@ -0,0 +1,68 @@
import React from 'react';
import { AsyncStorage, NativeModules, Text, TouchableOpacity } from 'react-native';
import Button from '../../component/button';
import rewardStyle from '../../styles/reward';
class RewardSummary extends React.Component {
static itemKey = 'rewardSummaryDismissed';
state = {
actionsLeft: 0,
dismissed: false
};
componentDidMount() {
this.props.fetchRewards();
AsyncStorage.getItem(RewardSummary.itemKey).then(isDismissed => {
if ('true' === isDismissed) {
this.setState({ dismissed: true });
}
const { user } = this.props;
let actionsLeft = 0;
if (!user || !user.has_verified_email) {
actionsLeft++;
}
if (!user || !user.is_identity_verified) {
actionsLeft++;
}
this.setState({ actionsLeft });
});
}
onDismissPressed = () => {
AsyncStorage.setItem(RewardSummary.itemKey, 'true');
this.setState({ dismissed: true });
this.props.notify({
message: 'You can always claim your rewards from the Rewards page.',
displayType: ['toast']
});
}
render() {
const { fetching, navigation, unclaimedRewardAmount, user } = this.props;
if (this.state.dismissed ||
(user && user.is_reward_approved) ||
this.state.actionsLeft === 0 ||
unclaimedRewardAmount === 0) {
return null;
}
return (
<TouchableOpacity style={rewardStyle.summaryContainer} onPress={() => {
navigation.navigate('Rewards');
}}>
<Text style={rewardStyle.summaryText}>
You have {unclaimedRewardAmount} LBC in unclaimed rewards. You have {this.state.actionsLeft} action{this.state.actionsLeft === 1 ? '' : 's'} left to claim your first reward. Tap here to continue.
</Text>
<Button style={rewardStyle.dismissButton} theme={"light"} text={"Dismiss"} onPress={this.onDismissPressed} />
</TouchableOpacity>
);
}
}
export default RewardSummary;
@@ -1,60 +0,0 @@
import React from 'react';
import { normalizeURI, parseURI } from 'lbry-redux';
import { ActivityIndicator, Text, TouchableOpacity, View } from 'react-native';
import Colors from '../../styles/colors';
import FileItemMedia from '../fileItemMedia';
import NsfwOverlay from '../../component/nsfwOverlay';
import searchStyle from '../../styles/search';
class SearchResultItem extends React.PureComponent {
render() {
const {
claim,
metadata,
isResolvingUri,
showUri,
isDownloaded,
style,
onPress,
navigation
} = this.props;
const uri = normalizeURI(this.props.uri);
const obscureNsfw = this.props.obscureNsfw && metadata && metadata.nsfw;
const title = metadata && metadata.title ? metadata.title : parseURI(uri).contentName;
let name;
let channel;
if (claim) {
name = claim.name;
channel = claim.channel_name;
}
return (
<View style={style}>
<TouchableOpacity style={style} onPress={onPress}>
<View style={searchStyle.thumbnailContainer}>
<FileItemMedia style={searchStyle.thumbnail}
blurRadius={obscureNsfw ? 15 : 0}
title={title}
thumbnail={metadata ? metadata.thumbnail : null} />
</View>
<View style={searchStyle.detailsContainer}>
{isResolvingUri && (
<View>
<Text style={searchStyle.uri}>{uri}</Text>
<View style={searchStyle.row}>
<ActivityIndicator size={"small"} color={Colors.LbryGreen} />
</View>
</View>)}
{!isResolvingUri && <Text style={searchStyle.title}>{title || name}</Text>}
{!isResolvingUri && channel && <Text style={searchStyle.publisher}>{channel}</Text>}
</View>
</TouchableOpacity>
{obscureNsfw && <NsfwOverlay onPress={() => navigation.navigate('Settings')} />}
</View>
);
}
}
export default SearchResultItem;
@@ -0,0 +1,4 @@
import { connect } from 'react-redux';
import StorageStatsCard from './view';
export default connect()(StorageStatsCard);
+128
View File
@@ -0,0 +1,128 @@
import React from 'react';
import { normalizeURI, parseURI } from 'lbry-redux';
import {
ActivityIndicator,
Platform,
Switch,
Text,
TouchableOpacity,
View
} from 'react-native';
import { formatBytes } from '../../utils/helper';
import Colors from '../../styles/colors';
import storageStatsStyle from '../../styles/storageStats';
class StorageStatsCard extends React.PureComponent {
state = {
totalBytes: 0,
totalAudioBytes: 0,
totalAudioPercent: 0,
totalImageBytes: 0,
totalImagePercent: 0,
totalVideoBytes: 0,
totalVideoPercent: 0,
totalOtherBytes: 0,
totalOtherPercent: 0,
showStats: false
};
componentDidMount() {
// calculate total bytes
const { fileInfos } = this.props;
let totalBytes = 0, totalAudioBytes = 0, totalImageBytes = 0, totalVideoBytes = 0;
let totalAudioPercent = 0, totalImagePercent = 0, totalVideoPercent = 0;
fileInfos.forEach(fileInfo => {
if (fileInfo.completed) {
const bytes = fileInfo.written_bytes;
const type = fileInfo.mime_type;
totalBytes += bytes;
if (type) {
if (type.startsWith('audio/')) totalAudioBytes += bytes;
if (type.startsWith('image/')) totalImageBytes += bytes;
if (type.startsWith('video/')) totalVideoBytes += bytes;
}
}
});
totalAudioPercent = ((totalAudioBytes / totalBytes) * 100).toFixed(2);
totalImagePercent = ((totalImageBytes / totalBytes) * 100).toFixed(2);
totalVideoPercent = ((totalVideoBytes / totalBytes) * 100).toFixed(2);
this.setState({
totalBytes,
totalAudioBytes,
totalAudioPercent,
totalImageBytes,
totalImagePercent,
totalVideoBytes,
totalVideoPercent,
totalOtherBytes: totalBytes - (totalAudioBytes + totalImageBytes + totalVideoBytes),
totalOtherPercent: (100 - (parseFloat(totalAudioPercent) +
parseFloat(totalImagePercent) +
parseFloat(totalVideoPercent))).toFixed(2)
});
}
render() {
return (
<View style={storageStatsStyle.card}>
<View style={[storageStatsStyle.row, storageStatsStyle.totalSizeContainer]}>
<View style={storageStatsStyle.summary}>
<Text style={storageStatsStyle.totalSize}>{formatBytes(this.state.totalBytes, 2)}</Text>
<Text style={storageStatsStyle.annotation}>used</Text>
</View>
<View style={[storageStatsStyle.row, storageStatsStyle.toggleStatsContainer]}>
<Text style={storageStatsStyle.statsText}>Stats</Text>
<Switch
style={storageStatsStyle.statsToggle}
value={this.state.showStats}
onValueChange={(value) => this.setState({ showStats: value })} />
</View>
</View>
{this.state.showStats &&
<View>
<View style={storageStatsStyle.distributionBar}>
<View style={[storageStatsStyle.audioDistribution, { flex: parseFloat(this.state.totalAudioPercent) }]} />
<View style={[storageStatsStyle.imageDistribution, { flex: parseFloat(this.state.totalImagePercent) }]} />
<View style={[storageStatsStyle.videoDistribution, { flex: parseFloat(this.state.totalVideoPercent) }]} />
<View style={[storageStatsStyle.otherDistribution, { flex: parseFloat(this.state.totalOtherPercent) }]} />
</View>
<View style={storageStatsStyle.legend}>
{this.state.totalAudioBytes > 0 &&
<View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}>
<View style={[storageStatsStyle.legendBox, storageStatsStyle.audioDistribution]} />
<Text style={storageStatsStyle.legendText}>Audio</Text>
<Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalAudioBytes, 2)}</Text>
</View>
}
{this.state.totalImageBytes > 0 &&
<View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}>
<View style={[storageStatsStyle.legendBox, storageStatsStyle.imageDistribution]} />
<Text style={storageStatsStyle.legendText}>Images</Text>
<Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalImageBytes, 2)}</Text>
</View>
}
{this.state.totalVideoBytes > 0 &&
<View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}>
<View style={[storageStatsStyle.legendBox, storageStatsStyle.videoDistribution]} />
<Text style={storageStatsStyle.legendText}>Videos</Text>
<Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalVideoBytes, 2)}</Text>
</View>
}
{this.state.totalOtherBytes > 0 &&
<View style={[storageStatsStyle.row, storageStatsStyle.legendItem]}>
<View style={[storageStatsStyle.legendBox, storageStatsStyle.otherDistribution]} />
<Text style={storageStatsStyle.legendText}>Other</Text>
<Text style={storageStatsStyle.legendSize}>{formatBytes(this.state.totalOtherBytes, 2)}</Text>
</View>
}
</View>
</View>}
</View>
)
}
}
export default StorageStatsCard;
@@ -2,6 +2,7 @@
import React from 'react';
import { Text, View, Linking } from 'react-native';
import { buildURI, formatCredits } from 'lbry-redux';
import { navigateToUri } from '../../../utils/helper';
import Link from '../../link';
import moment from 'moment';
import transactionListStyle from '../../../styles/transactionList';
@@ -10,11 +11,11 @@ class TransactionListItem extends React.PureComponent {
capitalize(string: string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
render() {
const { transaction, navigation } = this.props;
const { amount, claim_id: claimId, claim_name: name, date, fee, txid, type } = transaction;
return (
<View style={transactionListStyle.listItem}>
<View style={[transactionListStyle.row, transactionListStyle.topRow]}>
@@ -23,13 +24,9 @@ class TransactionListItem extends React.PureComponent {
{name && claimId && (
<Link
style={transactionListStyle.link}
onPress={() => navigation && navigation.navigate({
routeName: 'File',
key: evt.Url,
params: { uri: buildURI({ claimName: name, claimId }) }})
}
onPress={() => navigateToUri(navigation, buildURI({ claimName: name, claimId }))}
text={name} />
)}
)}
</View>
<View style={transactionListStyle.col}>
<Text style={[transactionListStyle.amount, transactionListStyle.text]}>{formatCredits(amount, 8)}</Text>
@@ -47,7 +44,7 @@ class TransactionListItem extends React.PureComponent {
{date ? (
<Text style={transactionListStyle.smallText}>{moment(date).format('MMM D')}</Text>
) : (
<Text style={transactionListStyle.smallText}>Pending</Text>
<Text style={transactionListStyle.smallText}>Pending</Text>
)}
</View>
</View>
+3 -2
View File
@@ -1,12 +1,13 @@
import { connect } from 'react-redux';
import { doUpdateSearchQuery, selectSearchState as selectSearch } from 'lbry-redux';
import { doUpdateSearchQuery, selectSearchState as selectSearch, selectSearchSuggestions } from 'lbry-redux';
import UriBar from './view';
const select = state => {
const { ...searchState } = selectSearch(state);
return {
...searchState
...searchState,
suggestions: selectSearchSuggestions(state)
};
};
+46 -18
View File
@@ -2,26 +2,28 @@
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 UriBarItem from './internal/uri-bar-item';
import uriBarStyle from '../../styles/uriBar';
class UriBar extends React.PureComponent {
static INPUT_TIMEOUT = 500;
textInput = null;
keyboardDidHideListener = null;
componentDidMount () {
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
this.setSelection();
}
componentWillUnmount() {
if (this.keyboardDidHideListener) {
this.keyboardDidHideListener.remove();
}
}
constructor(props) {
super(props);
this.state = {
@@ -31,32 +33,40 @@ class UriBar extends React.PureComponent {
focused: false
};
}
handleChangeText = text => {
const newValue = text ? text : '';
clearTimeout(this.state.changeTextTimeout);
const { updateSearchQuery } = this.props;
let timeout = setTimeout(() => {
updateSearchQuery(text);
}, UriBar.INPUT_TIMEOUT);
this.setState({ inputText: newValue, currentValue: newValue, changeTextTimeout: timeout });
}
handleItemPress = (item) => {
const { navigation, updateSearchQuery } = this.props;
const { navigation, onSearchSubmitted, updateSearchQuery } = this.props;
const { type, value } = item;
Keyboard.dismiss();
if (SEARCH_TYPES.SEARCH === type) {
this.setState({ currentValue: value });
updateSearchQuery(value);
if (onSearchSubmitted) {
onSearchSubmitted(value);
return;
}
navigation.navigate({ routeName: 'Search', key: 'searchPage', params: { searchQuery: value }});
} else {
const uri = normalizeURI(value);
navigation.navigate({ routeName: 'File', key: uri, params: { uri }});
navigateToUri(navigation, uri);
}
}
_keyboardDidHide = () => {
if (this.textInput) {
this.textInput.blur();
@@ -64,17 +74,23 @@ class UriBar extends React.PureComponent {
this.setState({ focused: false });
}
setSelection() {
if (this.textInput) {
this.textInput.setNativeProps({ selection: { start: 0, end: 0 }});
}
}
render() {
const { navigation, suggestions, updateSearchQuery, value } = this.props;
const { navigation, onSearchSubmitted, suggestions, updateSearchQuery, value } = this.props;
if (this.state.currentValue === null) {
this.setState({ currentValue: value });
}
let style = [uriBarStyle.overlay];
if (this.state.focused) {
style.push(uriBarStyle.inFocus);
}
return (
<View style={style}>
{this.state.focused && (
@@ -90,6 +106,7 @@ class UriBar extends React.PureComponent {
<View style={uriBarStyle.uriContainer}>
<TextInput ref={(ref) => { this.textInput = ref }}
style={uriBarStyle.uriText}
onLayout={() => { this.setSelection(); }}
selectTextOnFocus={true}
placeholder={'Search for videos, music, games and more'}
underlineColorAndroid={'transparent'}
@@ -100,15 +117,26 @@ class UriBar extends React.PureComponent {
inlineImageLeft={'baseline_search_black_24'}
inlineImagePadding={16}
onFocus={() => this.setState({ focused: true })}
onBlur={() => this.setState({ focused: false })}
onBlur={() => {
this.setState({ focused: false });
this.setSelection();
}}
onChangeText={this.handleChangeText}
onSubmitEditing={() => {
if (this.state.inputText) {
let inputText = this.state.inputText;
if (isNameValid(inputText) || isURIValid(inputText)) {
if (inputText.startsWith('lbry://') && isURIValid(inputText)) {
// if it's a URI (lbry://...), open the file page
const uri = normalizeURI(inputText);
navigation.navigate({ routeName: 'File', key: uri, params: { uri }});
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 }});
}
+7 -1
View File
@@ -1,5 +1,11 @@
const Constants = {
SETTING_ALPHA_UNDERSTANDS_RISKS: "ALPHA_UNDERSTANDS_RISKS"
KEY_FIRST_RUN_EMAIL: "firstRunEmail",
KEY_SHOULD_VERIFY_EMAIL: "shouldVerifyEmail",
SETTING_ALPHA_UNDERSTANDS_RISKS: "alphaUnderstandRisks",
ACTION_DELETE_COMPLETED_BLOBS: "DELETE_COMPLETED_BLOBS",
ACTION_FIRST_RUN_PAGE_CHANGED: "FIRST_RUN_PAGE_CHANGED",
};
export default Constants;
+18 -9
View File
@@ -10,6 +10,7 @@ import {
} from 'react-native';
import {
Lbry,
blacklistReducer,
claimsReducer,
costInfoReducer,
fileInfoReducer,
@@ -17,13 +18,12 @@ import {
searchReducer,
walletReducer
} from 'lbry-redux';
import { authReducer, rewardsReducer, userReducer } from 'lbryinc';
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';
import { createLogger } from 'redux-logger';
import { StackNavigator, addNavigationHelpers } from 'react-navigation';
import { AppNavigator } from './component/AppNavigator';
import { persistStore, autoRehydrate } from 'redux-persist';
import { reactNavigationMiddleware } from './utils/redux';
import AppWithNavigationState from './component/AppNavigator';
import AppWithNavigationState, { reactNavigationMiddleware } from './component/AppNavigator';
import FilesystemStorage from 'redux-persist-filesystem-storage';
import createCompressor from 'redux-persist-transform-compress';
import createFilter from 'redux-persist-transform-filter';
@@ -68,14 +68,18 @@ const navigatorReducer = (state = initialNavState, action) => {
};
const reducers = combineReducers({
auth: authReducer,
blacklist: blacklistReducer,
claims: claimsReducer,
costInfo: costInfoReducer,
fileInfo: fileInfoReducer,
notifications: notificationsReducer,
search: searchReducer,
wallet: walletReducer,
nav: navigatorReducer,
settings: settingsReducer
notifications: notificationsReducer,
rewards: rewardsReducer,
settings: settingsReducer,
search: searchReducer,
user: userReducer,
wallet: walletReducer
});
const bulkThunk = createBulkThunkMiddleware();
@@ -93,18 +97,20 @@ const store = createStore(
applyMiddleware(...middleware)
)
);
window.store = store;
const compressor = createCompressor();
const authFilter = createFilter('auth', ['authToken']);
const saveClaimsFilter = createFilter('claims', ['byId', 'claimsByUri']);
const subscriptionsFilter = createFilter('subscriptions', ['subscriptions']);
const settingsFilter = createFilter('settings', ['clientSettings']);
const walletFilter = createFilter('wallet', ['receiveAddress']);
const persistOptions = {
whitelist: ['claims', 'subscriptions', 'settings', 'wallet'],
whitelist: ['auth', 'claims', 'subscriptions', 'settings', 'wallet'],
// Order is important. Needs to be compressed last or other transforms can't
// read the data
transforms: [saveClaimsFilter, subscriptionsFilter, settingsFilter, walletFilter, compressor],
transforms: [authFilter, saveClaimsFilter, subscriptionsFilter, settingsFilter, walletFilter, compressor],
debounce: 10000,
storage: FilesystemStorage
};
@@ -115,6 +121,9 @@ persistStore(store, persistOptions, err => {
}
});
// TODO: Find i18n module that is compatible with react-native
global.__ = (str) => str;
class LBRYApp extends React.Component {
render() {
return (
+3 -2
View File
@@ -24,7 +24,6 @@ class AboutPage extends React.PureComponent {
});
});
Lbry.status().then(info => {
console.log(info);
this.setState({
lbryId: info.installation_id,
});
@@ -32,13 +31,14 @@ class AboutPage extends React.PureComponent {
}
render() {
const { navigation } = this.props;
const loading = 'Loading...';
const ver = this.state.versionInfo ? this.state.versionInfo : null;
return (
<View style={aboutStyle.container}>
<PageHeader title={"About LBRY"}
onBackPressed={() => { this.props.navigation.goBack(); }} />
onBackPressed={() => navigation.goBack(navigation.state.key)} />
<ScrollView style={aboutStyle.scrollContainer}>
<Text style={aboutStyle.title}>Content Freedom</Text>
<Text style={aboutStyle.paragraph}>
@@ -61,6 +61,7 @@ class AboutPage extends React.PureComponent {
<Link style={aboutStyle.link} href="https://www.instagram.com/LBRYio/" text="Instagram" />
<Link style={aboutStyle.link} href="https://twitter.com/LBRYio" text="Twitter" />
<Link style={aboutStyle.link} href="https://reddit.com/r/lbry" text="Reddit" />
<Link style={aboutStyle.link} href="https://t.me/lbryofficial" text="Telegram" />
</View>
<Text style={aboutStyle.releaseInfoTitle}>Release information</Text>
<View style={aboutStyle.row}>
+2 -2
View File
@@ -47,12 +47,12 @@ class ChannelPage extends React.PureComponent {
return (
<View style={channelPageStyle.container}>
<PageHeader title={name} onBackPressed={() => { this.props.navigation.goBack(); }} />
<PageHeader title={name} onBackPressed={() => navigation.goBack(navigation.state.key)} />
{contentList}
<UriBar value={uri} navigation={navigation} />
</View>
)
}
}
}
export default ChannelPage;
+9 -1
View File
@@ -1,14 +1,22 @@
import { connect } from 'react-redux';
import { doFetchFeaturedUris, selectFeaturedUris, selectFetchingFeaturedUris } from 'lbry-redux';
import {
doFetchFeaturedUris,
selectBalance,
selectFeaturedUris,
selectFetchingFeaturedUris
} from 'lbry-redux';
import { doFetchRewardedContent } from 'lbryinc';
import DiscoverPage from './view';
const select = state => ({
balance: selectBalance(state),
featuredUris: selectFeaturedUris(state),
fetchingFeaturedUris: selectFetchingFeaturedUris(state),
});
const perform = dispatch => ({
fetchFeaturedUris: () => dispatch(doFetchFeaturedUris()),
fetchRewardedContent: () => dispatch(doFetchRewardedContent()),
});
export default connect(select, perform)(DiscoverPage);
+10 -3
View File
@@ -10,9 +10,11 @@ import {
} from 'react-native';
import { normalizeURI } from 'lbry-redux';
import moment from 'moment';
import FileItem from '../../component/fileItem';
import discoverStyle from '../../styles/discover';
import Colors from '../../styles/colors';
import discoverStyle from '../../styles/discover';
import FloatingWalletBalance from '../../component/floatingWalletBalance';
import FileItem from '../../component/fileItem';
import RewardSummary from '../../component/rewardSummary';
import UriBar from '../../component/uriBar';
class DiscoverPage extends React.PureComponent {
@@ -39,7 +41,9 @@ class DiscoverPage extends React.PureComponent {
}
});
this.props.fetchFeaturedUris();
const { fetchFeaturedUris, fetchRewardedContent } = this.props;
fetchFeaturedUris();
fetchRewardedContent();
}
render() {
@@ -49,6 +53,7 @@ class DiscoverPage extends React.PureComponent {
return (
<View style={discoverStyle.container}>
<RewardSummary navigation={navigation} />
{!hasContent && fetchingFeaturedUris && (
<View style={discoverStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.LbryGreen} />
@@ -60,6 +65,7 @@ class DiscoverPage extends React.PureComponent {
renderItem={ ({item, index, section}) => (
<FileItem
style={discoverStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={item}
uri={normalizeURI(item)}
navigation={navigation} />
@@ -72,6 +78,7 @@ class DiscoverPage extends React.PureComponent {
keyExtractor={(item, index) => item}
/>
}
<FloatingWalletBalance navigation={navigation} />
<UriBar navigation={navigation} />
</View>
);
+20
View File
@@ -0,0 +1,20 @@
import { connect } from 'react-redux';
import {
doFileList,
selectFileInfosDownloaded,
selectMyClaimsWithoutChannels,
selectIsFetchingFileList,
} from 'lbry-redux';
import DownloadsPage from './view';
const select = (state) => ({
fileInfos: selectFileInfosDownloaded(state),
fetching: selectIsFetchingFileList(state),
claims: selectMyClaimsWithoutChannels(state),
});
const perform = dispatch => ({
fileList: () => dispatch(doFileList()),
});
export default connect(select, perform)(DownloadsPage);
+84
View File
@@ -0,0 +1,84 @@
import React from 'react';
import { Lbry, buildURI } from 'lbry-redux';
import {
ActivityIndicator,
Button,
FlatList,
Text,
TextInput,
View,
ScrollView
} from 'react-native';
import { navigateToUri } 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';
class DownloadsPage extends React.PureComponent {
static navigationOptions = {
title: 'My LBRY'
};
componentDidMount() {
this.props.fileList();
}
uriFromFileInfo(fileInfo) {
const { name: claimName, claim_name: claimNameDownloaded, claim_id: claimId } = fileInfo;
const uriParams = {};
uriParams.contentName = claimName || claimNameDownloaded;
uriParams.claimId = claimId;
return buildURI(uriParams);
}
render() {
const { fetching, fileInfos, navigation } = this.props;
const hasDownloads = fileInfos && Object.values(fileInfos).length > 0;
return (
<View style={downloadsStyle.container}>
{!fetching && !hasDownloads &&
<View style={downloadsStyle.busyContainer}>
<Text style={downloadsStyle.noDownloadsText}>You have not downloaded anything from LBRY yet.</Text>
</View>}
{fetching && !hasDownloads &&
<View style={downloadsStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.LbryGreen} style={downloadsStyle.loading} />
</View>}
{hasDownloads &&
<View style={downloadsStyle.subContainer}>
<StorageStatsCard fileInfos={fileInfos} />
<FlatList
style={downloadsStyle.scrollContainer}
contentContainerStyle={downloadsStyle.scrollPadding}
renderItem={ ({item}) => (
<FileListItem
style={fileListStyle.item}
uri={this.uriFromFileInfo(item)}
navigation={navigation}
onPress={() => navigateToUri(navigation, this.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.outpoint}
/>
</View>}
<FloatingWalletBalance navigation={navigation} />
<UriBar navigation={navigation} />
</View>
);
}
}
export default DownloadsPage;
+9 -7
View File
@@ -1,17 +1,18 @@
import { connect } from 'react-redux';
import {
doFetchFileInfo,
doResolveUri,
doFetchCostInfoForUri,
doResolveUri,
doNotify,
makeSelectIsUriResolving,
makeSelectCostInfoForUri,
makeSelectFileInfoForUri,
makeSelectClaimForUri,
makeSelectContentTypeForUri,
makeSelectMetadataForUri,
selectRewardContentClaimIds,
selectBlackListedOutpoints,
selectBlackListedOutpoints,
} from 'lbry-redux';
import { selectRewardContentClaimIds } from 'lbryinc';
import { doDeleteFile, doStopDownloadingFile } from '../../redux/actions/file';
import FilePage from './view';
@@ -32,13 +33,14 @@ const select = (state, props) => {
};
const perform = dispatch => ({
fetchFileInfo: uri => dispatch(doFetchFileInfo(uri)),
fetchCostInfo: uri => dispatch(doFetchCostInfoForUri(uri)),
resolveUri: uri => dispatch(doResolveUri(uri)),
stopDownload: (uri, fileInfo) => dispatch(doStopDownloadingFile(uri, fileInfo)),
deleteFile: (fileInfo, deleteFromDevice, abandonClaim) => {
dispatch(doDeleteFile(fileInfo, deleteFromDevice, abandonClaim));
},
fetchFileInfo: uri => dispatch(doFetchFileInfo(uri)),
fetchCostInfo: uri => dispatch(doFetchCostInfoForUri(uri)),
notify: data => dispatch(doNotify(data)),
resolveUri: uri => dispatch(doResolveUri(uri)),
stopDownload: (uri, fileInfo) => dispatch(doStopDownloadingFile(uri, fileInfo)),
});
export default connect(select, perform)(FilePage);
+278 -127
View File
@@ -1,5 +1,6 @@
import React from 'react';
import { Lbry, normalizeURI } from 'lbry-redux';
import { Lbryio } from 'lbryinc';
import {
ActivityIndicator,
Alert,
@@ -14,6 +15,7 @@ import {
View,
WebView
} from 'react-native';
import { navigateToUri } from '../../utils/helper';
import ImageViewer from 'react-native-image-zoom-viewer';
import Button from '../../component/button';
import Colors from '../../styles/colors';
@@ -21,8 +23,10 @@ import ChannelPage from '../channel';
import FileDownloadButton from '../../component/fileDownloadButton';
import FileItemMedia from '../../component/fileItemMedia';
import FilePrice from '../../component/filePrice';
import FloatingWalletBalance from '../../component/floatingWalletBalance';
import Link from '../../component/link';
import MediaPlayer from '../../component/mediaPlayer';
import RelatedContent from '../../component/relatedContent';
import UriBar from '../../component/uriBar';
import Video from 'react-native-video';
import filePageStyle from '../../styles/filePage';
@@ -35,20 +39,26 @@ class FilePage extends React.PureComponent {
playerBackground = null;
player = null;
startTime = null;
constructor(props) {
super(props);
this.state = {
mediaLoaded: false,
autoplayMedia: false,
autoPlayMedia: false,
downloadButtonShown: false,
downloadPressed: false,
fileViewLogged: false,
fullscreenMode: false,
imageUrls: null,
isLandscape: false,
mediaLoaded: false,
pageSuspended: false,
showImageViewer: false,
showWebView: false,
imageUrls: null,
playerBgHeight: 0,
playerHeight: 0,
isLandscape: false,
uri: null,
stopDownloadConfirmed: false
};
}
@@ -57,6 +67,8 @@ class FilePage extends React.PureComponent {
const { isResolvingUri, resolveUri, navigation } = this.props;
const { uri } = navigation.state.params;
this.setState({ uri });
if (!isResolvingUri) resolveUri(uri);
this.fetchFileInfo(this.props);
@@ -70,14 +82,34 @@ class FilePage extends React.PureComponent {
}
}
componentDidUpdate() {
componentDidUpdate(prevProps) {
this.fetchFileInfo(this.props);
const { isResolvingUri, resolveUri, claim, navigation } = this.props;
const { uri } = navigation.state.params;
const { claim, contentType, fileInfo, isResolvingUri, resolveUri, navigation } = this.props;
const { uri } = this.state;
if (!isResolvingUri && claim === undefined && uri) {
resolveUri(uri);
}
// Returned to the page. If mediaLoaded, and currentMediaInfo is different, update
if (this.state.mediaLoaded && window.currentMediaInfo && window.currentMediaInfo.uri !== this.state.uri) {
const { metadata } = this.props;
window.currentMediaInfo = {
channel: claim ? claim.channel_name : null,
title: metadata ? metadata.title : claim.name,
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) {
@@ -122,21 +154,44 @@ class FilePage extends React.PureComponent {
'Are you sure you want to remove this file from your device?',
[
{ text: 'No' },
{ text: 'Yes', onPress: () => { deleteFile(fileInfo.outpoint, true); } }
{ text: 'Yes', onPress: () => {
deleteFile(fileInfo.outpoint, true);
this.setState({
downloadPressed: false,
fileViewLogged: false,
mediaLoaded: false,
stopDownloadConfirmed: false
});
}}
],
{ cancelable: true }
);
}
onStopDownloadPressed = () => {
const { deleteFile, stopDownload, fileInfo, navigation } = this.props;
const { fileInfo, navigation, notify, stopDownload } = this.props;
Alert.alert(
'Stop download',
'Are you sure you want to stop downloading this file?',
[
{ text: 'No' },
{ text: 'Yes', onPress: () => { stopDownload(navigation.state.params.uri, fileInfo); } }
{ text: 'Yes', onPress: () => {
stopDownload(navigation.state.params.uri, fileInfo);
this.setState({
downloadPressed: false,
fileViewLogged: false,
mediaLoaded: false,
stopDownloadConfirmed: true
});
// there can be a bit of lag between the user pressing Yes and the UI being updated
// after the file_set_status and file_delete operations, so let the user know
notify({
message: 'The download will stop momentarily. You do not need to wait to discover something else.',
displayType: ['toast']
});
}}
],
{ cancelable: true }
);
@@ -152,6 +207,10 @@ class FilePage extends React.PureComponent {
utility.keepAwakeOff();
utility.showNavigationBar();
}
if (window.currentMediaInfo) {
window.currentMediaInfo = null;
}
window.player = null;
}
localUriForFileInfo = (fileInfo) => {
@@ -201,6 +260,10 @@ class FilePage extends React.PureComponent {
const isLandscape = screenWidth > screenHeight;
this.setState({ isLandscape });
if (!this.playerBackground) {
return;
}
if (isLandscape) {
this.playerBackground.setNativeProps({ height: screenHeight - StyleSheet.flatten(uriBarStyle.uriContainer).height });
} else if (this.state.playerBgHeight > 0) {
@@ -208,6 +271,46 @@ class FilePage extends React.PureComponent {
}
}
onMediaLoaded = (channelName, title, uri) => {
this.setState({ mediaLoaded: true });
window.currentMediaInfo = { channel: channelName, title, uri };
}
onPlaybackStarted = () => {
let timeToStartMillis, timeToStart;
if (this.startTime) {
timeToStartMillis = Date.now() - this.startTime;
timeToStart = Math.ceil(timeToStartMillis / 1000);
this.startTime = null;
}
const { fileInfo, navigation } = this.props;
const { uri } = navigation.state.params;
this.logFileView(uri, fileInfo, timeToStartMillis);
let payload = { 'Uri': uri };
if (!isNaN(timeToStart)) {
payload['Time to Start (seconds)'] = timeToStart;
payload['Time to Start (ms)'] = timeToStartMillis;
}
NativeModules.Mixpanel.track('Play', payload);
}
logFileView = (uri, fileInfo, timeToStart) => {
const { outpoint, claim_id: claimId } = fileInfo;
const params = {
uri,
outpoint,
claim_id: claimId
};
if (!isNaN(timeToStart)) {
params.time_to_start = timeToStart;
}
Lbryio.call('file', 'view', params).catch(() => {});
this.setState({ fileViewLogged: true });
}
render() {
const {
claim,
@@ -220,7 +323,7 @@ class FilePage extends React.PureComponent {
blackListedOutpoints,
navigation
} = this.props;
const { uri } = navigation.state.params;
const { uri, autoplay } = navigation.state.params;
let innerContent = null;
if ((isResolvingUri && !claim) || !claim) {
@@ -244,126 +347,174 @@ class FilePage extends React.PureComponent {
<ChannelPage uri={uri} navigation={navigation} />
);
} else if (claim) {
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 &&
(completed || (fileInfo && !fileInfo.stopped && fileInfo.written_bytes < fileInfo.total_bytes));
const channelClaimId =
value && value.publisherSignature && value.publisherSignature.certificateId;
let isClaimBlackListed = false;
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];
// 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 canOpen = (mediaType === 'image' || mediaType === 'text') && completed;
const isWebViewable = mediaType === 'text';
const localFileUri = this.localUriForFileInfo(fileInfo);
const openFile = () => {
if (mediaType === 'image') {
// use image viewer
this.setState({
imageUrls: [{
url: localFileUri
}],
showImageViewer: true
});
}
if (isWebViewable) {
// show webview
this.setState({
showWebView: true
});
if (blackListedOutpoints) {
for (let i = 0; i < blackListedOutpoints.length; i += 1) {
const outpoint = blackListedOutpoints[i];
if (outpoint.txid === claim.txid && outpoint.nout === claim.nout) {
isClaimBlackListed = true;
break;
}
}
}
innerContent = (
<View style={filePageStyle.pageContainer}>
{this.state.showWebView && isWebViewable && <WebView source={{ uri: localFileUri }}
style={filePageStyle.viewer} />}
{this.state.showImageViewer && <ImageViewer style={StyleSheet.flatten(filePageStyle.viewer)}
imageUrls={this.state.imageUrls}
renderIndicator={() => null} />}
{!this.state.showWebView && (
<View style={this.state.fullscreenMode ? filePageStyle.innerPageContainerFsMode : filePageStyle.innerPageContainer}
onLayout={this.checkOrientation}>
<View style={filePageStyle.mediaContainer}>
{(canOpen || (!fileInfo || (isPlayable && !canLoadMedia))) &&
<FileItemMedia style={filePageStyle.thumbnail} title={title} thumbnail={metadata.thumbnail} />}
{(canOpen || (isPlayable && !this.state.mediaLoaded)) && <ActivityIndicator size="large" color={Colors.LbryGreen} style={filePageStyle.loading} />}
{((isPlayable && !completed && !canLoadMedia) || !completed || canOpen) &&
<FileDownloadButton uri={uri}
style={filePageStyle.downloadButton}
openFile={openFile}
isPlayable={isPlayable}
onPlay={() => this.setState({ autoPlayMedia: true })} />}
{!fileInfo && <FilePrice uri={uri} style={filePageStyle.filePriceContainer} textStyle={filePageStyle.filePriceText} />}
</View>
{canLoadMedia && <View style={playerBgStyle} ref={(ref) => { this.playerBackground = ref; }}
onLayout={(evt) => {
if (!this.state.playerBgHeight) {
this.setState({ playerBgHeight: evt.nativeEvent.layout.height });
}
}} />}
{canLoadMedia && <MediaPlayer fileInfo={fileInfo}
ref={(ref) => { this.player = ref; }}
uri={uri}
style={playerStyle}
autoPlay={this.state.autoPlayMedia}
onFullscreenToggled={this.handleFullscreenToggle}
onMediaLoaded={() => { this.setState({ mediaLoaded: true }); }}
onLayout={(evt) => {
if (!this.state.playerHeight) {
this.setState({ playerHeight: evt.nativeEvent.layout.height });
}
}}
/>}
{ showActions &&
<View style={filePageStyle.actions}>
{completed && <Button style={filePageStyle.actionButton}
theme={"light"}
icon={"trash"}
text={"Delete"}
onPress={this.onDeletePressed} />}
{!completed && fileInfo && !fileInfo.stopped && fileInfo.written_bytes < fileInfo.total_bytes &&
<Button style={filePageStyle.actionButton}
theme={"light"}
text={"Stop Download"}
onPress={this.onStopDownloadPressed} />
}
</View>}
<ScrollView style={showActions ? filePageStyle.scrollContainerActions : filePageStyle.scrollContainer}>
<Text style={filePageStyle.title} selectable={true}>{title}</Text>
{channelName && <Link style={filePageStyle.channelName}
selectable={true}
text={channelName}
onPress={() => {
const channelUri = normalizeURI(channelName);
navigation.navigate({ routeName: 'File', key: channelUri, params: { uri: channelUri }});
}} />}
{description && description.length > 0 && <View style={filePageStyle.divider} />}
{description && <Text style={filePageStyle.description} selectable={true}>{this.linkify(description)}</Text>}
</ScrollView>
if (isClaimBlackListed) {
innerContent = (
<View style={filePageStyle.pageContainer}>
<View style={filePageStyle.dmcaContainer}>
<Text style={filePageStyle.dmcaText}>
In response to a complaint we received under the US Digital Millennium Copyright Act, we have blocked access to this content from our applications.
</Text>
<Link style={filePageStyle.dmcaLink} href="https://lbry.io/faq/dmca" text="Read More" />
</View>
)}
<UriBar value={uri} navigation={navigation} />
</View>
);
} else {
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 &&
(completed || (fileInfo && !fileInfo.stopped && fileInfo.written_bytes < fileInfo.total_bytes));
const channelClaimId =
value && value.publisherSignature && value.publisherSignature.certificateId;
{!this.state.fullscreenMode && <UriBar value={uri} navigation={navigation} />}
</View>
);
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];
// 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 canOpen = (mediaType === 'image' || mediaType === 'text') && completed;
const isWebViewable = mediaType === 'text';
const localFileUri = this.localUriForFileInfo(fileInfo);
const openFile = () => {
if (mediaType === 'image') {
// use image viewer
this.setState({
imageUrls: [{
url: localFileUri
}],
showImageViewer: true
});
}
if (isWebViewable) {
// show webview
this.setState({
showWebView: true
});
}
}
innerContent = (
<View style={filePageStyle.pageContainer}>
{this.state.showWebView && isWebViewable && <WebView source={{ uri: localFileUri }}
style={filePageStyle.viewer} />}
{this.state.showImageViewer && <ImageViewer style={StyleSheet.flatten(filePageStyle.viewer)}
imageUrls={this.state.imageUrls}
renderIndicator={() => null} />}
{!this.state.showWebView && (
<View style={this.state.fullscreenMode ? filePageStyle.innerPageContainerFsMode : filePageStyle.innerPageContainer}
onLayout={this.checkOrientation}>
<View style={filePageStyle.mediaContainer}>
{((canOpen || (!fileInfo || (isPlayable && !canLoadMedia))) || (!canOpen && fileInfo)) &&
<FileItemMedia style={filePageStyle.thumbnail} title={title} thumbnail={metadata.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) &&
<FileDownloadButton uri={uri}
style={filePageStyle.downloadButton}
openFile={openFile}
isPlayable={isPlayable}
onPlay={() => {
this.startTime = Date.now();
this.setState({ downloadPressed: true, autoPlayMedia: true, stopDownloadConfirmed: false });
}}
onButtonLayout={() => this.setState({ downloadButtonShown: true })}
onStartDownloadFailed={() => {
this.startTime = null;
setTimeout(() => {
this.setState({ downloadPressed: false, fileViewLogged: false, mediaLoaded: false });
}, 500);
}} />}
{!fileInfo && <FilePrice uri={uri} style={filePageStyle.filePriceContainer} textStyle={filePageStyle.filePriceText} />}
</View>
{canLoadMedia && fileInfo && <View style={playerBgStyle}
ref={(ref) => { this.playerBackground = ref; }}
onLayout={(evt) => {
if (!this.state.playerBgHeight) {
this.setState({ playerBgHeight: evt.nativeEvent.layout.height });
}
}} />}
{canLoadMedia && fileInfo && <MediaPlayer
fileInfo={fileInfo}
assignPlayer={(ref) => { this.player = ref; }}
uri={uri}
style={playerStyle}
autoPlay={autoplay || this.state.autoPlayMedia}
onFullscreenToggled={this.handleFullscreenToggle}
onLayout={(evt) => {
if (!this.state.playerHeight) {
this.setState({ playerHeight: evt.nativeEvent.layout.height });
}
}}
onMediaLoaded={() => this.onMediaLoaded(channelName, title, uri)}
onPlaybackStarted={this.onPlaybackStarted}
/>}
{fileInfo && showActions &&
<View style={filePageStyle.actions}>
{completed && <Button style={filePageStyle.actionButton}
theme={"light"}
icon={"trash"}
text={"Delete"}
onPress={this.onDeletePressed} />}
{!completed && fileInfo && !fileInfo.stopped &&
fileInfo.written_bytes < fileInfo.total_bytes &&
!this.state.stopDownloadConfirmed &&
<Button style={filePageStyle.actionButton}
theme={"light"}
text={"Stop Download"}
onPress={this.onStopDownloadPressed} />
}
</View>}
<ScrollView
style={showActions ? filePageStyle.scrollContainerActions : filePageStyle.scrollContainer}
contentContainerstyle={showActions ? null : filePageStyle.scrollContent}>
<Text style={filePageStyle.title} selectable={true}>{title}</Text>
{channelName && <Link style={filePageStyle.channelName}
selectable={true}
text={channelName}
onPress={() => {
const channelUri = normalizeURI(channelName);
navigateToUri(navigation, channelUri);
}} />}
{description && description.length > 0 && <View style={filePageStyle.divider} />}
{description && <Text style={filePageStyle.description} selectable={true}>{this.linkify(description)}</Text>}
<RelatedContent navigation={navigation} uri={uri} />
</ScrollView>
</View>
)}
{!this.state.fullscreenMode && <FloatingWalletBalance navigation={navigation} />}
{!this.state.fullscreenMode && <UriBar value={uri} navigation={navigation} />}
</View>
);
}
}
return innerContent;
+24 -2
View File
@@ -1,6 +1,28 @@
import { connect } from 'react-redux';
import { doNotify } from 'lbry-redux';
import {
doGenerateAuthToken,
doUserEmailNew,
selectAuthToken,
selectEmailNewErrorMessage,
selectEmailNewIsPending,
selectEmailToVerify,
selectIsAuthenticating
} from 'lbryinc';
import FirstRun from './view';
const perform = dispatch => ({});
const select = (state) => ({
authenticating: selectIsAuthenticating(state),
authToken: selectAuthToken(state),
emailToVerify: selectEmailToVerify(state),
emailNewErrorMessage: selectEmailNewErrorMessage(state),
emailNewPending: selectEmailNewIsPending(state),
});
export default connect(null, perform)(FirstRun);
const perform = dispatch => ({
addUserEmail: email => dispatch(doUserEmailNew(email)),
generateAuthToken: installationId => dispatch(doGenerateAuthToken(installationId)),
notify: data => dispatch(doNotify(data))
});
export default connect(select, perform)(FirstRun);
@@ -0,0 +1,128 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
AsyncStorage,
Linking,
Text,
TextInput,
View
} from 'react-native';
import Colors from '../../../styles/colors';
import Constants from '../../../constants';
import firstRunStyle from '../../../styles/firstRun';
class EmailCollectPage extends React.PureComponent {
static MAX_STATUS_TRIES = 15;
state = {
email: null,
authenticationStarted: false,
authenticationFailed: false,
placeholder: 'you@example.com',
statusTries: 0
};
componentWillReceiveProps(nextProps) {
const { authenticating, authToken } = this.props;
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 { generateAuthToken } = this.props;
this.setState({ authenticationStarted: true, authenticationFailed: false });
Lbry.status().then(info => {
generateAuthToken(info.installation_id)
}).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 (15 seconds)
}
});
}
handleChangeText = (text) => {
// save the value to the state email
const { onEmailChanged } = this.props;
this.setState({ email: text });
if (onEmailChanged) {
onEmailChanged(text);
}
AsyncStorage.setItem(Constants.KEY_FIRST_RUN_EMAIL, text);
}
render() {
const { authenticating, authToken, onEmailChanged, onEmailViewLayout, emailToVerify } = 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>
);
}
return (
<View style={firstRunStyle.container}>
{content}
</View>
);
}
}
export default EmailCollectPage;
+123 -24
View File
@@ -1,28 +1,35 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
AsyncStorage,
Linking,
NativeModules,
Text,
TouchableOpacity,
View
} from 'react-native';
import { NavigationActions } from 'react-navigation';
import { NavigationActions, StackActions } from 'react-navigation';
import Colors from '../../styles/colors';
import Constants from '../../constants';
import WelcomePage from './internal/welcome-page';
import EmailCollectPage from './internal/email-collect-page';
import firstRunStyle from '../../styles/firstRun';
class FirstRunScreen extends React.PureComponent {
static pages = ['welcome'];
static pages = [
'welcome',
'email-collect'
];
constructor() {
super();
this.state = {
currentPage: null,
launchUrl: null,
isFirstRun: false
}
}
state = {
currentPage: null,
emailSubmitted: false,
isFirstRun: false,
launchUrl: null,
showSkip: false,
showBottomContainer: true
};
componentDidMount() {
Linking.getInitialURL().then((url) => {
@@ -47,9 +54,24 @@ class FirstRunScreen extends React.PureComponent {
}
}
componentWillReceiveProps(nextProps) {
const { emailNewErrorMessage, emailNewPending } = nextProps;
const { notify } = this.props;
if (this.state.emailSubmitted && !emailNewPending) {
this.setState({ emailSubmitted: false });
if (emailNewErrorMessage) {
notify ({ message: String(emailNewErrorMessage), displayType: ['toast']});
} else {
// Request successful. Navigate to discover.
this.closeFinalPage();
}
}
}
launchSplashScreen() {
const { navigation } = this.props;
const resetAction = NavigationActions.reset({
const resetAction = StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Splash', params: { launchUri: this.state.launchUri } })
@@ -60,36 +82,113 @@ class FirstRunScreen extends React.PureComponent {
handleContinuePressed = () => {
const pageIndex = FirstRunScreen.pages.indexOf(this.state.currentPage);
if (pageIndex === (FirstRunScreen.pages.length - 1)) {
// Final page. Let the app know that first run experience is completed.
if (NativeModules.FirstRun) {
NativeModules.FirstRun.firstRunCompleted();
if (this.state.currentPage !== 'email-collect' &&
pageIndex === (FirstRunScreen.pages.length - 1)) {
this.closeFinalPage();
} else {
// TODO: Actions and page verification for specific pages
if (this.state.currentPage === 'email-collect') {
// handle email collect
this.handleEmailCollectPageContinue();
} else {
this.showNextPage();
}
}
}
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;
}
// Navigate to the splash screen
this.launchSplashScreen();
// validate the email
if (email.indexOf('@') === -1) {
return notify({
message: 'Please provide a valid email address to continue.',
displayType: ['toast'],
});
}
addUserEmail(email);
this.setState({ emailSubmitted: true });
});
}
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 });
}
}
closeFinalPage() {
// Final page. Let the app know that first run experience is completed.
if (NativeModules.FirstRun) {
NativeModules.FirstRun.firstRunCompleted();
}
// Navigate to the splash screen
this.launchSplashScreen();
}
onEmailChanged = (email) => {
if ('email-collect' == this.state.currentPage) {
this.setState({ showSkip: (!email || email.trim().length === 0) });
} else {
// TODO: Page transition animation?
this.state.currentPage = FirstRunScreen.pages[pageIndex + 1];
this.setState({ showSkip: false });
}
}
render() {
const {
authenticating,
authToken,
generateAuthToken,
emailNewErrorMessage,
emailNewPending,
emailToVerify
} = 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}
generateAuthToken={generateAuthToken}
onEmailChanged={this.onEmailChanged}
onEmailViewLayout={() => this.setState({ showBottomContainer: true, showSkip: true })} />);
}
return (
<View style={firstRunStyle.screenContainer}>
{page}
{this.state.currentPage &&
<TouchableOpacity style={firstRunStyle.button} onPress={this.handleContinuePressed}>
<Text style={firstRunStyle.buttonText}>Continue</Text>
</TouchableOpacity>}
{this.state.currentPage && this.state.showBottomContainer &&
<View style={firstRunStyle.bottomContainer}>
{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>}
</View>
)
);
}
}
+28
View File
@@ -0,0 +1,28 @@
import { connect } from 'react-redux';
import {
doRewardList,
selectEmailVerifyErrorMessage,
selectEmailVerifyIsPending,
selectFetchingRewards,
selectUnclaimedRewards,
selectClaimedRewards,
selectUser,
} from 'lbryinc';
import { doNotify } from 'lbry-redux';
import RewardsPage from './view';
const select = state => ({
emailVerifyErrorMessage: selectEmailVerifyErrorMessage(state),
emailVerifyPending: selectEmailVerifyIsPending(state),
fetching: selectFetchingRewards(state),
rewards: selectUnclaimedRewards(state),
claimed: selectClaimedRewards(state),
user: selectUser(state),
});
const perform = dispatch => ({
fetchRewards: () => dispatch(doRewardList()),
notify: data => dispatch(doNotify(data)),
});
export default connect(select, perform)(RewardsPage);
+155
View File
@@ -0,0 +1,155 @@
import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
NativeModules,
ScrollView,
Text,
View
} from 'react-native';
import Colors from '../../styles/colors';
import Link from '../../component/link';
import PhoneNumberRewardSubcard from '../../component/phoneNumberRewardSubcard';
import EmailRewardSubcard from '../../component/emailRewardSubcard';
import PageHeader from '../../component/pageHeader';
import RewardCard from '../../component/rewardCard';
import rewardStyle from '../../styles/reward';
class RewardsPage extends React.PureComponent {
state = {
isEmailVerified: false,
isIdentityVerified: false,
isRewardApproved: false,
verifyRequestStarted: false,
};
componentDidMount() {
this.props.fetchRewards();
const { user } = this.props;
this.setState({
isEmailVerified: (user && user.primary_email && user.has_verified_email),
isIdentityVerified: (user && user.is_identity_verified),
isRewardApproved: (user && user.is_reward_approved)
});
}
componentWillReceiveProps(nextProps) {
const { emailVerifyErrorMessage, emailVerifyPending, user } = nextProps;
if (emailVerifyPending) {
this.setState({ verifyRequestStarted: true });
}
if (this.state.verifyRequestStarted && !emailVerifyPending) {
this.setState({ verifyRequestStarted: false });
if (!emailVerifyErrorMessage) {
this.setState({ isEmailVerified: true });
}
}
if (user) {
// update other checks (if new user data has been retrieved)
this.setState({
isEmailVerified: (user && user.primary_email && user.has_verified_email),
isIdentityVerified: (user && user.is_identity_verified),
isRewardApproved: (user && user.is_reward_approved)
});
}
}
renderVerification() {
if (this.state.isRewardApproved) {
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" />.
</Text>
</View>
);
}
return null;
}
renderUnclaimedRewards() {
const { claimed, fetching, rewards, user } = this.props;
if (fetching) {
return (
<View style={rewardStyle.busyContainer}>
<ActivityIndicator size="large" color={Colors.LbryGreen} />
<Text style={rewardStyle.infoText}>Fetching rewards...</Text>
</View>
);
} else if (user === null) {
return (
<View style={rewardStyle.busyContainer}>
<Text style={rewardStyle.infoText}>This app is unable to earn rewards due to an authentication failure.</Text>
</View>
);
} else if (!rewards || rewards.length <= 0) {
return (
<View style={rewardStyle.busyContainer}>
<Text style={rewardStyle.infoText}>
{(claimed && claimed.length) ?
"You have claimed all available rewards! We're regularly adding more so be sure to check back later." :
"There are no rewards available at this time, please check back later."}
</Text>
</View>
);
}
const isNotEligible = !user || !user.primary_email || !user.has_verified_email || !user.is_reward_approved;
return (
<View>
{rewards.map(reward => <RewardCard key={reward.reward_type}
canClaim={!isNotEligible}
reward={reward}
reward_type={reward.reward_type} />)}
</View>
);
}
renderClaimedRewards() {
const { claimed } = this.props;
if (claimed && claimed.length) {
return (
<View>
{claimed.map(reward => <RewardCard key={reward.reward_type} reward={reward} />)}
</View>
);
}
}
render() {
const { user } = this.props;
return (
<View style={rewardStyle.container}>
<ScrollView style={rewardStyle.scrollContainer} contentContainerStyle={rewardStyle.scrollContentContainer}>
{this.renderVerification()}
{this.renderUnclaimedRewards()}
{this.renderClaimedRewards()}
</ScrollView>
</View>
);
}
}
export default RewardsPage;
+1 -1
View File
@@ -14,7 +14,7 @@ const select = (state) => ({
});
const perform = dispatch => ({
search: (query) => dispatch(doSearch(query))
search: (query) => dispatch(doSearch(query, 25))
});
export default connect(select, perform)(SearchPage);
+16 -15
View File
@@ -8,9 +8,11 @@ import {
View,
ScrollView
} from 'react-native';
import { navigateToUri } from '../../utils/helper';
import Colors from '../../styles/colors';
import PageHeader from '../../component/pageHeader';
import SearchResultItem from '../../component/searchResultItem';
import FileListItem from '../../component/fileListItem';
import FloatingWalletBalance from '../../component/floatingWalletBalance';
import UriBar from '../../component/uriBar';
import searchStyle from '../../styles/search';
@@ -18,7 +20,7 @@ class SearchPage extends React.PureComponent {
static navigationOptions = {
title: 'Search Results'
};
componentDidMount() {
const { navigation, search } = this.props;
const { searchQuery } = navigation.state.params;
@@ -26,30 +28,29 @@ class SearchPage extends React.PureComponent {
search(searchQuery);
}
}
render() {
const { isSearching, navigation, uris, query } = this.props;
const { isSearching, navigation, query, search, uris } = this.props;
const { searchQuery } = navigation.state.params;
return (
<View style={searchStyle.container}>
{!isSearching && (!uris || uris.length === 0) &&
<Text style={searchStyle.noResultsText}>No results to display.</Text>}
<ScrollView style={searchStyle.scrollContainer} contentContainerStyle={searchStyle.scrollPadding}>
{!isSearching && uris && uris.length ? (
uris.map(uri => <SearchResultItem key={uri}
uri={uri}
style={searchStyle.resultItem}
navigation={navigation}
onPress={() => navigation.navigate({
routeName: 'File',
key: 'filePage',
params: { uri }})
}/>)
uris.map(uri => <FileListItem key={uri}
uri={uri}
style={searchStyle.resultItem}
navigation={navigation}
onPress={() => navigateToUri(navigation, uri)}/>)
) : null }
</ScrollView>
{isSearching && <ActivityIndicator size="large" color={Colors.LbryGreen} style={searchStyle.loading} /> }
<UriBar value={searchQuery} navigation={navigation} />
<FloatingWalletBalance navigation={navigation} />
<UriBar value={searchQuery}
navigation={navigation}
onSearchSubmitted={(keywords) => search(keywords)} />
</View>
);
}
+3 -2
View File
@@ -13,6 +13,7 @@ class SettingsPage extends React.PureComponent {
const {
backgroundPlayEnabled,
keepDaemonRunning,
navigation,
showNsfw,
setClientSetting
} = this.props;
@@ -23,7 +24,7 @@ class SettingsPage extends React.PureComponent {
return (
<View>
<PageHeader title={"Settings"}
onBackPressed={() => { this.props.navigation.goBack(); }} />
onBackPressed={() => navigation.goBack(navigation.state.key)} />
<ScrollView style={settingsStyle.scrollContainer}>
<View style={settingsStyle.row}>
<View style={settingsStyle.switchText}>
@@ -46,7 +47,7 @@ class SettingsPage extends React.PureComponent {
<View style={settingsStyle.row}>
<View style={settingsStyle.switchText}>
<Text style={settingsStyle.label}>Keep the daemon background service running when the app is suspended.</Text>
<Text style={settingsStyle.label}>Keep the daemon background service running after closing the app</Text>
<Text style={settingsStyle.description}>Enable this option for quicker app launch and to keep the synchronisation with the blockchain up to date.</Text>
</View>
<View style={settingsStyle.switchContainer}>
+27 -4
View File
@@ -1,9 +1,32 @@
import { connect } from 'react-redux';
import { doBalanceSubscribe } from 'lbry-redux';
import { doBalanceSubscribe, doBlackListedOutpointsSubscribe, doNotify } from 'lbry-redux';
import {
doAuthenticate,
doFetchRewardedContent,
doUserEmailToVerify,
doUserEmailVerify,
doUserEmailVerifyFailure,
selectUser,
selectEmailToVerify
} from 'lbryinc';
import { doDeleteCompleteBlobs } from '../../redux/actions/file';
import SplashScreen from './view';
const perform = dispatch => ({
balanceSubscribe: () => dispatch(doBalanceSubscribe())
const select = state => ({
user: selectUser(state),
emailToVerify: selectEmailToVerify(state)
});
export default connect(null, perform)(SplashScreen);
const perform = dispatch => ({
authenticate: (appVersion, os) => dispatch(doAuthenticate(appVersion, os)),
balanceSubscribe: () => dispatch(doBalanceSubscribe()),
blacklistedOutpointsSubscribe: () => dispatch(doBlackListedOutpointsSubscribe()),
deleteCompleteBlobs: () => dispatch(doDeleteCompleteBlobs()),
fetchRewardedContent: () => dispatch(doFetchRewardedContent()),
notify: data => dispatch(doNotify(data)),
setEmailToVerify: email => dispatch(doUserEmailToVerify(email)),
verifyUserEmail: (token, recaptcha) => dispatch(doUserEmailVerify(token, recaptcha)),
verifyUserEmailFailure: error => dispatch(doUserEmailVerifyFailure(error)),
});
export default connect(select, perform)(SplashScreen);
+88 -16
View File
@@ -2,6 +2,7 @@ import React from 'react';
import { Lbry } from 'lbry-redux';
import {
ActivityIndicator,
AsyncStorage,
Linking,
NativeModules,
Platform,
@@ -9,9 +10,12 @@ import {
Text,
View
} from 'react-native';
import { NavigationActions } from 'react-navigation';
import { NavigationActions, StackActions } from 'react-navigation';
import { decode as atob } from 'base-64';
import { navigateToUri } from '../../utils/helper';
import PropTypes from 'prop-types';
import Colors from '../../styles/colors';
import Constants from '../../constants';
import splashStyle from '../../styles/splash';
class SplashScreen extends React.PureComponent {
@@ -21,13 +25,15 @@ class SplashScreen extends React.PureComponent {
componentWillMount() {
this.setState({
daemonReady: false,
details: 'Starting daemon',
message: 'Connecting',
isRunning: false,
isLagging: false,
launchUrl: null,
isDownloadingHeaders: false,
headersDownloadProgress: 0
headersDownloadProgress: 0,
shouldAuthenticate: false
});
if (NativeModules.DaemonServiceControl) {
@@ -44,6 +50,8 @@ class SplashScreen extends React.PureComponent {
AsyncStorage.setItem('firstLaunchTime', String(moment().unix()));
}
});
this.props.fetchRewardedContent();
}
updateStatus() {
@@ -52,16 +60,79 @@ class SplashScreen extends React.PureComponent {
});
}
componentWillReceiveProps(nextProps) {
const {
emailToVerify,
navigation,
setEmailToVerify,
verifyUserEmail,
verifyUserEmailFailure
} = this.props;
const { user } = nextProps;
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
const resetAction = StackActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Main'})
]
});
navigation.dispatch(resetAction);
const launchUrl = navigation.state.params.launchUrl || this.state.launchUrl;
if (launchUrl) {
if (launchUrl.startsWith('lbry://?verify=')) {
let verification = {};
try {
verification = JSON.parse(atob(launchUrl.substring(15)));
} catch (error) {
console.log(error);
}
if (verification.token && verification.recaptcha) {
AsyncStorage.setItem(Constants.KEY_SHOULD_VERIFY_EMAIL, 'true');
try {
verifyUserEmail(verification.token, verification.recaptcha);
} catch (error) {
const message = 'Invalid Verification Token';
verifyUserEmailFailure(message);
notify({ message, displayType: ['toast'] });
}
} else {
notify({
message: 'Invalid Verification URI',
displayType: ['toast'],
});
}
} else {
navigateToUri(navigation, launchUrl);
}
}
});
});
}
}
_updateStatusCallback(status) {
const { deleteCompleteBlobs } = 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.wallet && status.wallet.blocks_behind <= 0;
const hasStarted = startupStatus.file_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
// to give us a better sense of when we are actually started
this.setState({
daemonReady: true,
message: 'Testing Network',
details: 'Waiting for name resolution',
isLagging: false,
@@ -70,22 +141,22 @@ class SplashScreen extends React.PureComponent {
Lbry.resolve({ uri: 'lbry://one' }).then(() => {
// Leave the splash screen
const { balanceSubscribe, navigation } = this.props;
const {
authenticate,
balanceSubscribe,
blacklistedOutpointsSubscribe,
navigation,
notify
} = this.props;
balanceSubscribe();
const resetAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'Main'})
]
blacklistedOutpointsSubscribe();
NativeModules.VersionInfo.getAppVersion().then(appVersion => {
this.setState({ shouldAuthenticate: true });
authenticate(appVersion, Platform.OS);
});
navigation.dispatch(resetAction);
const launchUrl = navigation.state.params.launchUrl || this.state.launchUrl;
if (launchUrl) {
navigation.navigate({ routeName: 'File', key: launchUrl, params: { uri: launchUrl } });
}
});
return;
}
@@ -123,6 +194,7 @@ class SplashScreen extends React.PureComponent {
details: 'Initializing LBRY service...'
});
}
setTimeout(() => {
this.updateStatus();
}, 500);
+3
View File
@@ -13,6 +13,7 @@ import moment from 'moment';
import FileItem from '../../component/fileItem';
import discoverStyle from '../../styles/discover';
import Colors from '../../styles/colors';
import FloatingWalletBalance from '../../component/floatingWalletBalance';
import UriBar from '../../component/uriBar';
class TrendingPage extends React.PureComponent {
@@ -38,6 +39,7 @@ class TrendingPage extends React.PureComponent {
renderItem={ ({item}) => (
<FileItem
style={discoverStyle.fileItem}
mediaStyle={discoverStyle.fileItemMedia}
key={item}
uri={normalizeURI(item)}
navigation={navigation} />
@@ -47,6 +49,7 @@ class TrendingPage extends React.PureComponent {
keyExtractor={(item, index) => item}
/>
}
<FloatingWalletBalance navigation={navigation} />
<UriBar navigation={navigation} />
</View>
);
+2 -2
View File
@@ -11,13 +11,13 @@ import walletStyle from '../../styles/wallet';
class WalletPage extends React.PureComponent {
render() {
const { understandsRisks, setClientSetting } = this.props;
if (!understandsRisks) {
return (
<View>
<View style={walletStyle.warning}>
<Text style={walletStyle.warningText}>
This is alpha 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 click the button below.
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.
</Text>
</View>
<Button text={'I understand the risks'} style={[walletStyle.button, walletStyle.understand]}
+71 -26
View File
@@ -9,10 +9,20 @@ import {
makeSelectMetadataForUri,
selectDownloadingByOutpoint,
} 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) => {
Lbry.file_list({
@@ -40,14 +50,18 @@ export function doUpdateLoadStatus(uri, outpoint) {
if (NativeModules.LbryDownloadManager) {
NativeModules.LbryDownloadManager.updateDownload(uri, fileInfo.file_name, 100, writtenBytes, totalBytes);
}
// 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,
});
notif.onclick = () => {
ipcRenderer.send('focusWindow', 'main');
};*/
});*/
} else {
// ready to play
const { total_bytes: totalBytes, written_bytes: writtenBytes } = fileInfo;
@@ -66,7 +80,7 @@ export function doUpdateLoadStatus(uri, outpoint) {
if (NativeModules.LbryDownloadManager) {
NativeModules.LbryDownloadManager.updateDownload(uri, fileInfo.file_name, progress, writtenBytes, totalBytes);
}
setTimeout(() => {
dispatch(doUpdateLoadStatus(uri, outpoint));
}, DOWNLOAD_POLL_INTERVAL);
@@ -96,7 +110,7 @@ export function doStartDownload(uri, outpoint) {
fileInfo,
},
});
if (NativeModules.LbryDownloadManager) {
NativeModules.LbryDownloadManager.startDownload(uri, fileInfo.file_name);
}
@@ -110,7 +124,7 @@ export function doStopDownloadingFile(uri, fileInfo) {
return dispatch => {
let params = { status: 'stop' };
if (fileInfo.sd_hash) {
params.sd_hash = fileInfo.sd_hash;
params.sd_hash = fileInfo.sd_hash;
}
if (fileInfo.stream_hash) {
params.stream_hash = fileInfo.stream_hash;
@@ -121,24 +135,22 @@ export function doStopDownloadingFile(uri, fileInfo) {
type: ACTIONS.DOWNLOADING_CANCELED,
data: {}
});
// 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);
}
});
if (NativeModules.LbryDownloadManager) {
NativeModules.LbryDownloadManager.stopDownload(uri, fileInfo.file_name);
}
// Should also delete the file after the user stops downloading
dispatch(doDeleteFile(fileInfo.outpoint, uri));
};
}
export function doDownloadFile(uri, streamInfo) {
return dispatch => {
dispatch(doStartDownload(uri, streamInfo.outpoint));
//analytics.apiLog(uri, streamInfo.output, streamInfo.claim_id);
//dispatch(doClaimEligiblePurchaseRewards());
const { outpoint } = streamInfo;
dispatch(doStartDownload(uri, outpoint));
dispatch(doClaimEligiblePurchaseRewards());
};
}
@@ -151,7 +163,7 @@ export function doSetPlayingUri(uri) {
};
}
export function doLoadVideo(uri) {
export function doLoadVideo(uri, failureCallback) {
return dispatch => {
dispatch({
type: ACTIONS.LOADING_VIDEO_STARTED,
@@ -159,7 +171,7 @@ export function doLoadVideo(uri) {
uri,
},
});
Lbry.get({ uri })
.then(streamInfo => {
const timeout =
@@ -176,6 +188,10 @@ export function doLoadVideo(uri) {
message: `File timeout for uri ${uri}`,
displayType: ['toast']
}));
if (failureCallback) {
failureCallback();
}
} else {
dispatch(doDownloadFile(uri, streamInfo));
}
@@ -186,16 +202,20 @@ export function doLoadVideo(uri) {
type: ACTIONS.LOADING_VIDEO_FAILED,
data: { uri },
});
dispatch(doNotify({
message: `Failed to download ${uri}, please try again. If this problem persists, visit https://lbry.io/faq/support for support.`,
displayType: ['toast']
}));
if (failureCallback) {
failureCallback();
}
});
};
}
export function doPurchaseUri(uri, specificCostInfo) {
export function doPurchaseUri(uri, specificCostInfo, failureCallback) {
return (dispatch, getState) => {
const state = getState();
const balance = selectBalance(state);
@@ -214,11 +234,11 @@ export function doPurchaseUri(uri, specificCostInfo) {
`This will purchase "${title}" for ${formattedCost} ${unit}`,
[
{ text: 'OK', onPress: () => dispatch(doLoadVideo(uri)) },
{ text: 'Cancel', style: 'cancel' }
{ text: 'Cancel', style: 'cancel', onPress: () => failureCallback && failureCallback() }
],
{ cancelable: true });
} else {
dispatch(doLoadVideo(uri));
dispatch(doLoadVideo(uri, failureCallback));
}
}
@@ -248,6 +268,10 @@ export function doPurchaseUri(uri, specificCostInfo) {
message: 'Insufficient credits',
displayType: ['toast']
}));
if (failureCallback) {
failureCallback();
}
Promise.resolve();
return;
}
@@ -301,3 +325,24 @@ export function doDeleteFile(outpoint, deleteFromComputer, abandonClaim) {
//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);
});
}
});
});
};
}
+1
View File
@@ -9,3 +9,4 @@ export function doSetClientSetting(key, value) {
},
};
}
-2
View File
@@ -1,7 +1,5 @@
import { AsyncStorage } from 'react-native';
import { ACTIONS } from 'lbry-redux';
const reducers = {};
const defaultState = {
clientSettings: {}
+6 -1
View File
@@ -4,12 +4,17 @@ const Colors = {
DarkGrey: '#555555',
DescriptionGrey: '#999999',
LbryGreen: '#40b89a',
BrighterLbryGreen: '#40b887',
LightGrey: '#cccccc',
LighterGrey: '#e5e5e5',
Orange: '#ffbb00',
Red: '#ff0000',
VeryLightGrey: '#f1f1f1',
White: '#ffffff'
White: '#ffffff',
StatsAudio: '#f6a637',
StatsImage: '#ff4a7d',
StatsOther: '#26bcf7'
};
export default Colors;
+39 -3
View File
@@ -1,6 +1,17 @@
import { StyleSheet } from 'react-native';
import { Dimensions, PixelRatio, StyleSheet } from 'react-native';
import Colors from './colors';
const screenDimension = Dimensions.get('window');
const screenWidth = screenDimension.width;
const screenHeight = screenDimension.height;
const screenWidthPixels = PixelRatio.getPixelSizeForLayoutSize(screenWidth);
const screenHeightPixels = PixelRatio.getPixelSizeForLayoutSize(screenHeight);
// calculate thumbnail width and height based on device's aspect ratio
const horizontalMargin = 48; // left and right margins (24 + 24)
const verticalMargin = (screenWidthPixels > 720 && screenHeightPixels > 1920) ? 0 : ((screenWidthPixels <= 720) ? 20 : 16);
const mediaWidth = screenWidth - horizontalMargin;
const mediaHeight = ((screenWidth / screenHeight) * ((screenWidthPixels <= 720) ? screenWidth : mediaWidth)) - verticalMargin;
const discoverStyle = StyleSheet.create({
container: {
flex: 1
@@ -40,6 +51,12 @@ const discoverStyle = StyleSheet.create({
marginRight: 24,
marginBottom: 48
},
fileItemMedia: {
width: mediaWidth,
height: mediaHeight,
alignItems: 'center',
justifyContent: 'center'
},
fileItemName: {
fontFamily: 'Metropolis-Bold',
marginTop: 8,
@@ -67,8 +84,13 @@ const discoverStyle = StyleSheet.create({
textAlign: 'center',
color: '#0c604b'
},
drawerMenuButton: {
height: '100%',
justifyContent: 'center'
},
drawerHamburger: {
marginLeft: 16
marginLeft: 16,
marginRight: 16
},
rightHeaderIcon: {
marginRight: 16
@@ -87,10 +109,24 @@ const discoverStyle = StyleSheet.create({
height: '100%'
},
overlayText: {
color: '#ffffff',
color: Colors.White,
fontSize: 14,
textAlign: 'center',
fontFamily: 'Metropolis-Regular'
},
rewardTitleContainer: {
alignItems: 'center',
flexDirection: 'row',
justifyContent: 'space-between'
},
rewardIcon: {
color: Colors.LbryGreen,
flex: 0.1,
textAlign: 'right',
marginTop: 6
},
rewardTitle: {
flex: 0.9
}
});
+41
View File
@@ -0,0 +1,41 @@
import { StyleSheet } from 'react-native';
const downloadsStyle = StyleSheet.create({
container: {
flex: 1
},
busyContainer: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
flexDirection: 'row'
},
subContainer: {
flex: 1
},
itemList: {
flex: 1,
},
scrollContainer: {
flex: 1,
paddingLeft: 16,
paddingRight: 16,
marginTop: 16,
marginBottom: 60
},
scrollPadding: {
marginTop: -16,
paddingBottom: 16
},
noDownloadsText: {
textAlign: 'center',
fontFamily: 'Metropolis-Regular',
fontSize: 14,
position: 'absolute'
},
loading: {
position: 'absolute'
}
});
export default downloadsStyle;
+2 -1
View File
@@ -2,7 +2,8 @@ import { StyleSheet } from 'react-native';
const fileDownloadButtonStyle = StyleSheet.create({
container: {
width: 160,
paddingLeft: 32,
paddingRight: 32,
height: 36,
borderRadius: 18,
justifyContent: 'center',
+5 -6
View File
@@ -1,19 +1,18 @@
import { StyleSheet, Dimensions } from 'react-native';
const screenDimension = Dimensions.get('window');
const width = screenDimension.width - 48; // screen width minus combined left and right margins
import { StyleSheet } from 'react-native';
import Colors from './colors';
const fileItemMediaStyle = StyleSheet.create({
autothumb: {
flex: 1,
width: '100%',
height: 200,
justifyContent: 'center'
justifyContent: 'center',
alignItems: 'center'
},
autothumbText: {
fontFamily: 'Metropolis-SemiBold',
textAlign: 'center',
color: '#ffffff',
color: Colors.White,
fontSize: 40
},
autothumbPurple: {
+71
View File
@@ -0,0 +1,71 @@
import { Dimensions, PixelRatio, StyleSheet } from 'react-native';
import Colors from './colors';
const screenDimension = Dimensions.get('window');
const screenWidth = screenDimension.width;
const screenHeight = screenDimension.height;
const screenWidthPixels = PixelRatio.getPixelSizeForLayoutSize(screenWidth);
const screenHeightPixels = PixelRatio.getPixelSizeForLayoutSize(screenHeight);
const verticalAdjust = (screenHeightPixels > 1280 && screenHeightPixels <= 1920) ? 6 : 0;
const thumbnailWidth = (screenWidthPixels <= 720) ? 144 : 156;
const thumbnailHeight = ((screenWidth / screenHeight) * thumbnailWidth) - verticalAdjust;
const fileListStyle = StyleSheet.create({
item: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 8
},
detailsContainer: {
flex: 1
},
thumbnail: {
width: thumbnailWidth,
height: thumbnailHeight,
marginRight: (screenWidthPixels <= 720) ? 10 : 12,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontFamily: 'Metropolis-SemiBold',
fontSize: (screenWidthPixels <= 720) ? 12 : 16
},
uri: {
fontFamily: 'Metropolis-SemiBold',
fontSize: (screenWidthPixels <= 720) ? 12 : 14,
marginBottom: 8
},
publisher: {
fontFamily: 'Metropolis-SemiBold',
fontSize: (screenWidthPixels <= 720) ? 12 : 14,
marginTop: (screenWidthPixels <= 720) ? 1 : 3,
color: Colors.LbryGreen
},
loading: {
position: 'absolute'
},
downloadInfo: {
marginTop: (screenWidthPixels <= 720) ? 4 : 8
},
downloadStorage: {
fontFamily: 'Metropolis-Regular',
fontSize: (screenWidthPixels <= 720) ? 12 : 14,
color: Colors.ChannelGrey
},
progress: {
marginTop: (screenWidthPixels <= 720) ? 2 : 4,
height: 3,
flex: 1,
flexDirection: 'row'
},
progressCompleted: {
backgroundColor: Colors.LbryGreen
},
progressRemaining: {
backgroundColor: Colors.LbryGreen,
opacity: 0.2
}
});
export default fileListStyle;
+33 -9
View File
@@ -3,6 +3,8 @@ import Colors from './colors';
const screenDimension = Dimensions.get('window');
const screenWidth = screenDimension.width;
const containedMediaHeight = ((screenWidth * 9) / 16); // 16:9 display ratio
const containedMediaHeightWithControls = containedMediaHeight + 17;
const filePageStyle = StyleSheet.create({
container: {
@@ -30,7 +32,7 @@ const filePageStyle = StyleSheet.create({
mediaContainer: {
alignItems: 'center',
width: screenWidth,
height: 240
height: containedMediaHeightWithControls
},
emptyClaimText: {
fontFamily: 'Metropolis-Regular',
@@ -41,8 +43,9 @@ const filePageStyle = StyleSheet.create({
},
scrollContainer: {
flex: 1,
marginTop: -16,
marginBottom: -4,
marginTop: -16
},
scrollContent: {
paddingTop: 10
},
scrollContainerActions: {
@@ -71,11 +74,11 @@ const filePageStyle = StyleSheet.create({
lineHeight: 20,
marginLeft: 20,
marginRight: 20,
marginBottom: 40
marginBottom: 16
},
thumbnail: {
width: screenWidth,
height: 224,
height: containedMediaHeight,
justifyContent: 'center',
alignItems: 'center'
},
@@ -92,7 +95,7 @@ const filePageStyle = StyleSheet.create({
},
containedPlayer: {
width: '100%',
height: 240,
height: containedMediaHeightWithControls,
},
containedPlayerLandscape: {
width: '100%',
@@ -114,7 +117,7 @@ const filePageStyle = StyleSheet.create({
},
containedPlayerBackground: {
width: '100%',
height: 206,
height: containedMediaHeight,
},
fullscreenPlayerBackground: {
width: '100%',
@@ -144,11 +147,13 @@ const filePageStyle = StyleSheet.create({
paddingTop: 16,
paddingBottom: 8,
marginTop: -14,
width: '50%',
width: '100%',
},
actionButton: {
alignSelf: 'flex-start',
backgroundColor: Colors.White,
width: 160
paddingLeft: 24,
paddingRight: 24
},
loading: {
position: 'absolute',
@@ -160,6 +165,25 @@ const filePageStyle = StyleSheet.create({
alignItems: 'center',
flexDirection: 'row'
},
dmcaContainer: {
flex: 1,
alignItems: 'flex-start',
justifyContent: 'center',
paddingLeft: 24,
paddingRight: 24
},
dmcaText: {
fontFamily: 'Metropolis-Regular',
fontSize: 18,
lineHeight: 24
},
dmcaLink: {
color: Colors.LbryGreen,
fontFamily: 'Metropolis-Regular',
fontSize: 18,
lineHeight: 24,
marginTop: 24
},
infoText: {
fontFamily: 'Metropolis-Regular',
fontSize: 20,
+42 -2
View File
@@ -28,16 +28,56 @@ const firstRunStyle = StyleSheet.create({
marginBottom: 20,
color: Colors.White
},
button: {
infoParagraph: {
fontFamily: 'Metropolis-Regular',
fontSize: 14,
lineHeight: 20,
marginLeft: 32,
marginRight: 32,
marginBottom: 20,
color: Colors.White
},
emailInput: {
fontFamily: 'Metropolis-Regular',
fontSize: 24,
lineHeight: 24,
marginLeft: 32,
marginRight: 32,
marginBottom: 20,
textAlign: 'center'
},
leftButton: {
flex: 1,
alignSelf: 'flex-start',
marginLeft: 32,
marginRight: 32
},
bottomContainer: {
flex: 1
},
actionButton: {
backgroundColor: Colors.White,
alignSelf: 'center',
fontFamily: 'Metropolis-Regular',
fontSize: 12,
paddingLeft: 16,
paddingRight: 16
},
button: {
alignSelf: 'flex-end',
marginLeft: 32,
marginRight: 32
},
buttonText: {
fontFamily: 'Metropolis-Regular',
fontSize: 28,
fontSize: 24,
color: Colors.White
},
waiting: {
marginBottom: 24
},
pageWaiting: {
alignSelf: 'center'
}
});
+34
View File
@@ -0,0 +1,34 @@
import { StyleSheet } from 'react-native';
import Colors from './colors';
const floatingButtonStyle = StyleSheet.create({
container: {
position: 'absolute',
zIndex: 100,
borderRadius: 24,
padding: 14,
paddingLeft: 20,
paddingRight: 20,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: Colors.BrighterLbryGreen,
shadowColor: 'black',
shadowOpacity: 0.1,
shadowRadius: StyleSheet.hairlineWidth,
shadowOffset: {
height: StyleSheet.hairlineWidth,
},
elevation: 4
},
text: {
color: Colors.White,
fontFamily: 'Metropolis-Bold',
fontSize: 18,
},
bottomRight: {
right: 10,
bottom: 70
}
});
export default floatingButtonStyle;
+18 -5
View File
@@ -39,7 +39,7 @@ const mediaPlayerStyle = StyleSheet.create({
},
fullscreenTrackingControls: {
alignSelf: 'center',
width: '70%'
width: '60%'
},
playerControls: {
position: 'absolute',
@@ -49,7 +49,7 @@ const mediaPlayerStyle = StyleSheet.create({
height: '100%',
},
playerControlsContainer: {
backgroundColor: 'transparent',
backgroundColor: '#00000020',
flex: 1,
alignItems: 'center',
justifyContent: 'center'
@@ -75,7 +75,7 @@ const mediaPlayerStyle = StyleSheet.create({
position: 'absolute',
left: 8,
bottom: 24,
fontSize: 12,
fontSize: 14,
color: '#ffffff'
},
totalDuration: {
@@ -83,7 +83,7 @@ const mediaPlayerStyle = StyleSheet.create({
position: 'absolute',
right: 40,
bottom: 24,
fontSize: 12,
fontSize: 14,
color: '#ffffff'
},
seekerCircle: {
@@ -100,7 +100,8 @@ const mediaPlayerStyle = StyleSheet.create({
position: 'absolute',
height: 36,
width: 48,
marginLeft: -18
marginLeft: -18,
zIndex: 20
},
seekerHandleContained: {
bottom: -17
@@ -108,6 +109,18 @@ const mediaPlayerStyle = StyleSheet.create({
seekerHandleFs: {
bottom: 0
},
seekerTouchArea: {
position: 'absolute',
height: 30,
width: '100%',
zIndex: 10,
},
seekerTouchAreaContained: {
bottom: -15,
},
seekerTouchAreaFs: {
bottom: 0
},
bigSeekerCircle: {
borderRadius: 24,
position: 'relative',
+3 -1
View File
@@ -34,7 +34,8 @@ const pageHeaderStyle = StyleSheet.create({
...platformContainerStyles,
},
backIcon: {
marginLeft: 16
marginLeft: 16,
marginRight: 16
},
header: {
...StyleSheet.absoluteFillObject,
@@ -61,6 +62,7 @@ const pageHeaderStyle = StyleSheet.create({
left: 0,
bottom: 0,
top: 0,
height: '100%',
position: 'absolute',
alignItems: 'center',
flexDirection: 'row',
+37
View File
@@ -0,0 +1,37 @@
import { StyleSheet } from 'react-native';
import Colors from './colors';
const relatedContentStyle = StyleSheet.create({
container: {
flex: 1,
paddingTop: 16,
paddingBottom: 16,
paddingLeft: 24,
paddingRight: 24,
borderTopColor: Colors.LighterGrey,
borderTopWidth: 1
},
title: {
fontFamily: 'Metropolis-Regular',
fontSize: 18,
},
itemList: {
flex: 1,
},
scrollContainer: {
flex: 1,
paddingLeft: 16,
paddingRight: 16,
marginTop: 16,
marginBottom: 60
},
scrollPadding: {
marginTop: -16,
paddingBottom: 16
},
loading: {
marginTop: 16
}
});
export default relatedContentStyle;
+208
View File
@@ -0,0 +1,208 @@
import { StyleSheet } from 'react-native';
import Colors from './colors';
const rewardStyle = StyleSheet.create({
container: {
flex: 1
},
row: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
},
actionButton: {
backgroundColor: Colors.LbryGreen,
alignSelf: 'flex-start',
paddingTop: 9,
paddingBottom: 9,
paddingLeft: 24,
paddingRight: 24
},
busyContainer: {
flex: 1,
marginTop: 32,
marginBottom: 16,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row'
},
rewardsContainer: {
flex: 1
},
scrollContentContainer: {
paddingBottom: 16
},
card: {
backgroundColor: Colors.White,
marginTop: 16,
marginLeft: 16,
marginRight: 16,
padding: 16
},
rewardCard: {
backgroundColor: Colors.White,
marginTop: 16,
marginLeft: 16,
marginRight: 16,
paddingTop: 16,
paddingBottom: 16
},
text: {
fontFamily: 'Metropolis-Regular',
fontSize: 16,
lineHeight: 24
},
infoText: {
fontFamily: 'Metropolis-Regular',
fontSize: 18,
marginLeft: 12
},
title: {
fontFamily: 'Metropolis-Regular',
fontSize: 22,
marginBottom: 6,
color: Colors.LbryGreen
},
subtitle: {
fontFamily: 'Metropolis-Regular',
fontSize: 18,
marginBottom: 6,
color: Colors.LbryGreen
},
subcardText: {
fontFamily: 'Metropolis-Regular',
fontSize: 15,
lineHeight: 20,
marginLeft: 2,
marginRight: 2
},
subcardTextInput: {
fontFamily: 'Metropolis-Regular',
fontSize: 16,
marginTop: 2,
marginBottom: 2
},
topMarginSmall: {
marginTop: 8
},
topMarginMedium: {
marginTop: 16
},
bottomMarginSmall: {
marginBottom: 8
},
bottomMarginMedium: {
marginBottom: 16
},
bottomMarginLarge: {
marginBottom: 24
},
link: {
color: Colors.LbryGreen,
fontFamily: 'Metropolis-Regular',
fontSize: 14,
},
textLink: {
color: Colors.LbryGreen
},
leftCol: {
width: '15%',
alignItems: 'center',
paddingLeft: 6
},
midCol: {
width: '65%'
},
rightCol: {
width: '18%',
alignItems: 'center'
},
rewardAmount: {
fontFamily: 'Metropolis-Regular',
fontSize: 26,
textAlign: 'center'
},
rewardCurrency: {
fontFamily: 'Metropolis-Regular'
},
rewardTitle: {
fontFamily: 'Metropolis-Regular',
fontSize: 16,
color: Colors.LbryGreen,
marginBottom: 4,
},
rewardDescription: {
fontFamily: 'Metropolis-Regular',
fontSize: 14,
lineHeight: 18,
marginBottom: 4
},
claimed: {
color: Colors.LbryGreen,
},
disabled: {
color: Colors.LightGrey
},
subcard: {
borderTopColor: Colors.VeryLightGrey,
borderTopWidth: 1,
paddingTop: 16,
paddingLeft: 8,
paddingRight: 8,
marginTop: 16,
marginLeft: -8,
marginRight: -8
},
summaryContainer: {
backgroundColor: Colors.LbryGreen,
padding: 12,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
},
summaryText: {
color: Colors.White,
fontFamily: 'Metropolis-Regular',
fontSize: 14,
lineHeight: 20,
flex: 0.7
},
phoneVerificationContainer: {
paddingLeft: 4,
paddingRight: 4
},
phoneInput: {
marginLeft: 8
},
phoneInputText: {
fontFamily: 'Metropolis-Regular',
fontSize: 16,
letterSpacing: 1.3
},
verifyingText: {
fontFamily: 'Metropolis-Regular',
fontSize: 14,
marginLeft: 12,
alignSelf: 'flex-start'
},
verificationCodeInput: {
fontFamily: 'Metropolis-Regular',
fontSize: 24,
letterSpacing: 12
},
loading: {
alignSelf: 'flex-start'
},
smsPermissionContainer: {
marginBottom: 32
},
dismissButton: {
alignSelf: 'center',
backgroundColor: Colors.White,
paddingLeft: 4,
paddingRight: 4,
flex: 0.2
}
});
export default rewardStyle;
+1 -26
View File
@@ -21,17 +21,7 @@ const searchStyle = StyleSheet.create({
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 16
},
thumbnail: {
width: '100%',
height: 80
},
thumbnailContainer: {
width: '25%'
},
detailsContainer: {
width: '70%'
marginTop: 8
},
searchInput: {
width: '100%',
@@ -39,21 +29,6 @@ const searchStyle = StyleSheet.create({
fontFamily: 'Metropolis-Regular',
fontSize: 16
},
title: {
fontFamily: 'Metropolis-SemiBold',
fontSize: 16
},
uri: {
fontFamily: 'Metropolis-SemiBold',
fontSize: 14,
marginBottom: 8
},
publisher: {
fontFamily: 'Metropolis-SemiBold',
fontSize: 12,
marginTop: 4,
color: '#c0c0c0'
},
noResultsText: {
textAlign: 'center',
fontFamily: 'Metropolis-Regular',
+4 -2
View File
@@ -25,12 +25,14 @@ const settingsStyle = StyleSheet.create({
},
label: {
fontSize: 14,
fontFamily: 'Metropolis-Regular'
fontFamily: 'Metropolis-Regular',
lineHeight: 18
},
description: {
color: '#aaaaaa',
fontSize: 12,
fontFamily: 'Metropolis-Regular',
color: '#aaaaaa'
lineHeight: 18
}
});
+84
View File
@@ -0,0 +1,84 @@
import { StyleSheet } from 'react-native';
import Colors from './colors';
const storageStatsStyle = StyleSheet.create({
container: {
flex: 1
},
row: {
flexDirection: 'row'
},
card: {
backgroundColor: Colors.White,
marginTop: 16,
marginLeft: 16,
marginRight: 16,
padding: 16
},
totalSize: {
fontFamily: 'Metropolis-Regular',
fontSize: 36
},
annotation: {
fontFamily: 'Metropolis-Regular',
fontSize: 14,
marginTop: -4
},
statsText: {
fontFamily: 'Metropolis-Regular',
fontSize: 14
},
distributionBar: {
flexDirection: 'row',
width: '100%',
height: 8,
marginTop: 16,
marginBottom: 16
},
audioDistribution: {
backgroundColor: Colors.StatsAudio
},
imageDistribution: {
backgroundColor: Colors.StatsImage
},
videoDistribution: {
backgroundColor: Colors.LbryGreen
},
otherDistribution: {
backgroundColor: Colors.StatsOther
},
legendItem: {
alignItems: 'center',
marginBottom: 8,
justifyContent: 'space-between'
},
legendBox: {
width: 16,
height: 16,
},
legendText: {
fontFamily: 'Metropolis-Regular',
fontSize: 14,
flex: 0.3
},
legendSize: {
fontFamily: 'Metropolis-Regular',
fontSize: 14,
flex: 0.6,
textAlign: 'right'
},
statsToggle: {
marginLeft: 8,
},
summary: {
flex: 0.5,
alignSelf: 'flex-start'
},
toggleStatsContainer: {
flex: 0.5,
alignItems: 'center',
justifyContent: 'flex-end'
}
});
export default storageStatsStyle;
+6 -3
View File
@@ -128,13 +128,16 @@ const walletStyle = StyleSheet.create({
margin: 16
},
warningText: {
color: '#ffffff',
color: Colors.White,
fontFamily: 'Metropolis-Regular',
fontSize: 16,
lineHeight: 30
lineHeight: 24
},
understand: {
marginLeft: 16
marginLeft: 16,
padding: 12,
paddingLeft: 18,
paddingRight: 18
},
currency: {
alignSelf: 'flex-start',
+59
View File
@@ -0,0 +1,59 @@
import { NavigationActions, StackActions } from 'react-navigation';
export function dispatchNavigateToUri(dispatch, nav, uri) {
const params = { uri };
if (nav && nav.routes && nav.routes.length > 0 && 'Main' === nav.routes[0].routeName) {
const mainRoute = nav.routes[0];
const discoverRoute = mainRoute.routes[0];
if (discoverRoute.index > 0 && 'File' === discoverRoute.routes[discoverRoute.index].routeName) {
const fileRoute = discoverRoute.routes[discoverRoute.index];
// Currently on a file page, so we can ignore (if the URI is the same) or replace (different URIs)
if (uri !== fileRoute.params.uri) {
const stackAction = StackActions.replace({ routeName: 'File', newKey: uri, params });
dispatch(stackAction);
return;
}
}
}
const navigateAction = NavigationActions.navigate({ routeName: 'File', key: uri, params });
dispatch(navigateAction);
}
export function formatBytes(bytes, decimalPoints = 0) {
if (!bytes) {
return '0 KB';
}
if (bytes < 1048576) { // < 1MB
const value = (bytes / 1024.0).toFixed(decimalPoints);
return `${value} KB`;
}
if (bytes < 1073741824) { // < 1GB
const value = (bytes / (1024.0 * 1024.0)).toFixed(decimalPoints);
return `${value} MB`;
}
const value = (bytes / (1024.0 * 1024.0 * 1024.0)).toFixed(decimalPoints);
return `${value} GB`;
}
export function navigateToUri(navigation, uri, additionalParams) {
if (!navigation) {
return;
}
if (uri === navigation.state.key) {
return;
}
const params = Object.assign({ uri }, additionalParams);
if ('File' === navigation.state.routeName) {
const stackAction = StackActions.replace({ routeName: 'File', newKey: uri, params });
navigation.dispatch(stackAction);
return;
}
navigation.navigate({ routeName: 'File', key: uri, params });
}
-15
View File
@@ -1,15 +0,0 @@
import {
createReactNavigationReduxMiddleware,
createReduxBoundAddListener,
} from 'react-navigation-redux-helpers';
const reactNavigationMiddleware = createReactNavigationReduxMiddleware(
"root",
state => state.nav,
);
const addListener = createReduxBoundAddListener("root");
export {
reactNavigationMiddleware,
addListener,
};
+3 -3
View File
@@ -36,7 +36,7 @@ version.filename = %(source.dir)s/main.py
# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = openssl, sqlite3, hostpython2, android, distro, pyjnius, certifi==2018.4.16, constantly, incremental, functools32, miniupnpc==1.9, gmpy==1.17, twisted==16.6.0, appdirs==1.4.3, argparse==1.2.1, docopt==0.6.2, base58==0.2.2, colorama==0.3.7, dnspython==1.12.0, ecdsa==0.13, envparse==0.2.0, jsonrpc==1.2, jsonrpclib==0.1.7, jsonschema==2.5.1, pbkdf2==1.3, pyyaml==3.12, qrcode==5.2.2, requests==2.9.1, seccure==0.3.1.3, attrs==18.1.0, pyasn1, pyasn1-modules, service_identity==16.0.0, six==1.9.0, slowaes==0.1a1, txJSON-RPC==0.5, wsgiref==0.1.2, zope.interface==4.3.3, protobuf==3.2.0, keyring==10.4.0, netifaces, txupnp==0.0.1a10, git+https://github.com/lbryio/lbryschema.git@v0.0.16#egg=lbryschema, git+https://github.com/lbryio/lbryum.git#egg=lbryum, git+https://github.com/lbryio/lbry.git#egg=lbrynet, asn1crypto, cryptography==2.2.2, pyopenssl==17.4.0, treq==17.8.0, funcsigs, mock, pbr, unqlite
requirements = openssl, sqlite3, hostpython2, android, distro, pyjnius, certifi==2018.4.16, constantly, incremental, functools32, miniupnpc==1.9, gmpy==1.17, twisted==16.6.0, appdirs==1.4.3, argparse==1.2.1, docopt==0.6.2, base58==0.2.2, colorama==0.3.7, dnspython==1.12.0, ecdsa==0.13, envparse==0.2.0, jsonrpc==1.2, jsonrpclib==0.1.7, jsonschema==2.5.1, pbkdf2==1.3, pyyaml==3.12, qrcode==5.2.2, requests==2.9.1, seccure==0.3.1.3, attrs==18.1.0, pyasn1, pyasn1-modules, service_identity==16.0.0, six==1.9.0, slowaes==0.1a1, txJSON-RPC==0.5, wsgiref==0.1.2, zope.interface==4.3.3, protobuf==3.2.0, keyring==10.4.0, netifaces, txupnp==0.0.1a10, git+https://github.com/lbryio/lbryschema.git@v0.0.16#egg=lbryschema, git+https://github.com/lbryio/lbryum.git#egg=lbryum, git+https://github.com/lbryio/lbry.git@v0.21.2#egg=lbrynet, asn1crypto, cryptography==2.2.2, pyopenssl==17.4.0, treq==17.8.0, funcsigs, mock, pbr, unqlite
# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
@@ -86,7 +86,7 @@ fullscreen = 0
#android.presplash_color = #FFFFFF
# (list) Permissions
android.permissions = ACCESS_NETWORK_STATE,BLUETOOTH,INTERNET,READ_EXTERNAL_STORAGE,READ_PHONE_STATE,WRITE_EXTERNAL_STORAGE
android.permissions = ACCESS_NETWORK_STATE,BLUETOOTH,INTERNET,READ_EXTERNAL_STORAGE,RECEIVE_SMS,WRITE_EXTERNAL_STORAGE
# (int) Android API to use
android.api = 27
@@ -148,7 +148,7 @@ android.react_src = ./app
# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
android.gradle_dependencies = com.android.support:appcompat-v7:27.1.1, com.facebook.react:react-native:0.55.3, com.mixpanel.android:mixpanel-android:5+, com.google.android.gms:play-services-gcm:11.0.4+, com.facebook.fresco:fresco:1.9.0, com.facebook.fresco:animated-gif:1.9.0
android.gradle_dependencies = com.android.support:support-v4:27.1.1, com.android.support:support-media-compat:27.1.1, com.android.support:appcompat-v7:27.1.1, com.facebook.react:react-native:0.55.3, com.mixpanel.android:mixpanel-android:5+, com.google.android.gms:play-services-gcm:11.0.4+, com.facebook.fresco:fresco:1.9.0, com.facebook.fresco:animated-gif:1.9.0
# (str) python-for-android branch to use, defaults to master
#p4a.branch = stable
+3 -3
View File
@@ -36,7 +36,7 @@ version.filename = %(source.dir)s/main.py
# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = openssl, sqlite3, hostpython2, android, distro, pyjnius, certifi==2018.4.16, constantly, incremental, functools32, miniupnpc==1.9, gmpy==1.17, twisted==16.6.0, appdirs==1.4.3, argparse==1.2.1, docopt==0.6.2, base58==0.2.2, colorama==0.3.7, dnspython==1.12.0, ecdsa==0.13, envparse==0.2.0, jsonrpc==1.2, jsonrpclib==0.1.7, jsonschema==2.5.1, pbkdf2==1.3, pyyaml==3.12, qrcode==5.2.2, requests==2.9.1, seccure==0.3.1.3, attrs==18.1.0, pyasn1, pyasn1-modules, service_identity==16.0.0, six==1.9.0, slowaes==0.1a1, txJSON-RPC==0.5, wsgiref==0.1.2, zope.interface==4.3.3, protobuf==3.2.0, keyring==10.4.0, netifaces, txupnp==0.0.1a10, git+https://github.com/lbryio/lbryschema.git@v0.0.16#egg=lbryschema, git+https://github.com/lbryio/lbryum.git#egg=lbryum, git+https://github.com/lbryio/lbry.git#egg=lbrynet, asn1crypto, cryptography==2.2.2, pyopenssl==17.4.0, treq==17.8.0, funcsigs, mock, pbr, unqlite
requirements = openssl, sqlite3, hostpython2, android, distro, pyjnius, certifi==2018.4.16, constantly, incremental, functools32, miniupnpc==1.9, gmpy==1.17, twisted==16.6.0, appdirs==1.4.3, argparse==1.2.1, docopt==0.6.2, base58==0.2.2, colorama==0.3.7, dnspython==1.12.0, ecdsa==0.13, envparse==0.2.0, jsonrpc==1.2, jsonrpclib==0.1.7, jsonschema==2.5.1, pbkdf2==1.3, pyyaml==3.12, qrcode==5.2.2, requests==2.9.1, seccure==0.3.1.3, attrs==18.1.0, pyasn1, pyasn1-modules, service_identity==16.0.0, six==1.9.0, slowaes==0.1a1, txJSON-RPC==0.5, wsgiref==0.1.2, zope.interface==4.3.3, protobuf==3.2.0, keyring==10.4.0, netifaces, txupnp==0.0.1a10, git+https://github.com/lbryio/lbryschema.git@v0.0.16#egg=lbryschema, git+https://github.com/lbryio/lbryum.git#egg=lbryum, git+https://github.com/lbryio/lbry.git@v0.21.2#egg=lbrynet, asn1crypto, cryptography==2.2.2, pyopenssl==17.4.0, treq==17.8.0, funcsigs, mock, pbr, unqlite
# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
@@ -86,7 +86,7 @@ fullscreen = 0
#android.presplash_color = #FFFFFF
# (list) Permissions
android.permissions = ACCESS_NETWORK_STATE,BLUETOOTH,INTERNET,READ_EXTERNAL_STORAGE,READ_PHONE_STATE,WRITE_EXTERNAL_STORAGE
android.permissions = ACCESS_NETWORK_STATE,BLUETOOTH,INTERNET,READ_EXTERNAL_STORAGE,RECEIVE_SMS,WRITE_EXTERNAL_STORAGE
# (int) Android API to use
android.api = 27
@@ -148,7 +148,7 @@ android.react_src = ./app
# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
android.gradle_dependencies = com.android.support:appcompat-v7:27.1.1, com.facebook.react:react-native:0.55.3, com.mixpanel.android:mixpanel-android:5+, com.google.android.gms:play-services-gcm:11.0.4+, com.facebook.fresco:fresco:1.9.0, com.facebook.fresco:animated-gif:1.9.0
android.gradle_dependencies = com.android.support:support-v4:27.1.1, com.android.support:support-media-compat:27.1.1, com.android.support:appcompat-v7:27.1.1, com.facebook.react:react-native:0.55.3, com.mixpanel.android:mixpanel-android:5+, com.google.android.gms:play-services-gcm:11.0.4+, com.facebook.fresco:fresco:1.9.0, com.facebook.fresco:animated-gif:1.9.0
# (str) python-for-android branch to use, defaults to master
#p4a.branch = stable
+3 -5
View File
@@ -36,7 +36,7 @@ version.filename = %(source.dir)s/main.py
# (list) Application requirements
# comma seperated e.g. requirements = sqlite3,kivy
requirements = openssl, sqlite3, hostpython2, android, distro, pyjnius, certifi==2018.4.16, constantly, incremental, functools32, miniupnpc==1.9, gmpy==1.17, twisted==16.6.0, appdirs==1.4.3, argparse==1.2.1, docopt==0.6.2, base58==0.2.2, colorama==0.3.7, dnspython==1.12.0, ecdsa==0.13, envparse==0.2.0, jsonrpc==1.2, jsonrpclib==0.1.7, jsonschema==2.5.1, pbkdf2==1.3, pyyaml==3.12, qrcode==5.2.2, requests==2.9.1, seccure==0.3.1.3, attrs==18.1.0, pyasn1, pyasn1-modules, service_identity==16.0.0, six==1.9.0, slowaes==0.1a1, txJSON-RPC==0.5, wsgiref==0.1.2, zope.interface==4.3.3, protobuf==3.2.0, keyring==10.4.0, netifaces, txupnp==0.0.1a10, git+https://github.com/lbryio/lbryschema.git@v0.0.16#egg=lbryschema, git+https://github.com/lbryio/lbryum.git#egg=lbryum, git+https://github.com/lbryio/lbry.git#egg=lbrynet, asn1crypto, cryptography==2.2.2, pyopenssl==17.4.0, treq==17.8.0, funcsigs, mock, pbr, unqlite
requirements = openssl, sqlite3, hostpython2, android, distro, pyjnius, certifi==2018.4.16, constantly, incremental, functools32, miniupnpc==1.9, gmpy==1.17, twisted==16.6.0, appdirs==1.4.3, argparse==1.2.1, docopt==0.6.2, base58==0.2.2, colorama==0.3.7, dnspython==1.12.0, ecdsa==0.13, envparse==0.2.0, jsonrpc==1.2, jsonrpclib==0.1.7, jsonschema==2.5.1, pbkdf2==1.3, pyyaml==3.12, qrcode==5.2.2, requests==2.9.1, seccure==0.3.1.3, attrs==18.1.0, pyasn1, pyasn1-modules, service_identity==16.0.0, six==1.9.0, slowaes==0.1a1, txJSON-RPC==0.5, wsgiref==0.1.2, zope.interface==4.3.3, protobuf==3.2.0, keyring==10.4.0, netifaces, txupnp==0.0.1a10, git+https://github.com/lbryio/lbryschema.git@v0.0.16#egg=lbryschema, git+https://github.com/lbryio/lbryum.git#egg=lbryum, git+https://github.com/lbryio/lbry.git@v0.21.2#egg=lbrynet, asn1crypto, cryptography==2.2.2, pyopenssl==17.4.0, treq==17.8.0, funcsigs, mock, pbr, unqlite
# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
@@ -86,7 +86,7 @@ fullscreen = 0
#android.presplash_color = #FFFFFF
# (list) Permissions
android.permissions = ACCESS_NETWORK_STATE,BLUETOOTH,INTERNET,READ_EXTERNAL_STORAGE,READ_PHONE_STATE,WRITE_EXTERNAL_STORAGE
android.permissions = ACCESS_NETWORK_STATE,BLUETOOTH,INTERNET,READ_EXTERNAL_STORAGE,RECEIVE_SMS,WRITE_EXTERNAL_STORAGE
# (int) Android API to use
android.api = 27
@@ -148,7 +148,7 @@ android.react_src = ./app
# (list) Gradle dependencies to add (currently works only with sdl2_gradle
# bootstrap)
android.gradle_dependencies = com.android.support:appcompat-v7:27.1.1, com.facebook.react:react-native:0.55.3, com.mixpanel.android:mixpanel-android:5+, com.google.android.gms:play-services-gcm:11.0.4+, com.facebook.fresco:fresco:1.9.0, com.facebook.fresco:animated-gif:1.9.0
android.gradle_dependencies = com.android.support:support-v4:27.1.1, com.android.support:support-media-compat:27.1.1, com.android.support:appcompat-v7:27.1.1, com.facebook.react:react-native:0.55.3, com.mixpanel.android:mixpanel-android:5+, com.google.android.gms:play-services-gcm:11.0.4+, com.facebook.fresco:fresco:1.9.0, com.facebook.fresco:animated-gif:1.9.0
# (str) python-for-android branch to use, defaults to master
#p4a.branch = stable
@@ -272,5 +272,3 @@ warn_on_root = 1
# Then, invoke the command line with the "demo" profile:
#
#buildozer --profile demo android debug
builddir = /home/vagrant
@@ -40,6 +40,10 @@ android {
}
}
dexOptions {
jumboMode true
}
{% if args.sign -%}
signingConfigs {
release {
@@ -80,9 +84,10 @@ subprojects {
}
dependencies {
compile project(':react-native-video')
compile project(':react-native-fast-image')
compile project(':react-native-fetch-blob')
{%- for aar in aars %}
compile project(':react-native-video')
{%- for aar in aars %}
compile(name: '{{ aar }}', ext: 'aar')
{%- endfor -%}
{%- if args.depends -%}
@@ -1,5 +1,7 @@
rootProject.name = 'browser'
include ':react-native-video'
project(':react-native-video').projectDir = new File(rootProject.projectDir, './react/node_modules/react-native-video/android-exoplayer')
include ':react-native-fast-image'
project(':react-native-fast-image').projectDir = new File(rootProject.projectDir, './react/node_modules/react-native-fast-image/android')
include ':react-native-fetch-blob'
project(':react-native-fetch-blob').projectDir = new File(rootProject.projectDir, './react/node_modules/react-native-fetch-blob/android')
include ':react-native-video'
project(':react-native-video').projectDir = new File(rootProject.projectDir, './react/node_modules/react-native-video/android-exoplayer')
+1 -1
View File
@@ -7,7 +7,7 @@ import sh
class LibGMPRecipe(Recipe):
version = '6.1.2'
url = 'https://ftp.gnu.org/pub/gnu/gmp/gmp-{version}.tar.bz2'
url = 'http://www.mirrorservice.org/pub/gnu/gmp/gmp-{version}.tar.bz2'
#url = 'https://gmplib.org/download/gmp/gmp-{version}.tar.bz2'
def should_build(self, arch):
-59
View File
@@ -1,59 +0,0 @@
from pythonforandroid.toolchain import (
CompiledComponentsPythonRecipe,
Recipe,
current_directory,
info,
shprint,
)
from os.path import join
import sh
class PyCryptoRecipe(CompiledComponentsPythonRecipe):
version = '2.6.1'
url = 'https://pypi.python.org/packages/source/p/pycrypto/pycrypto-{version}.tar.gz'
depends = ['libgmp', 'openssl', 'python2']
site_packages_name = 'Crypto'
call_hostpython_via_targetpython = False
patches = ['add_length.patch', 'fix-fastmath-include-dirs.patch']
def get_recipe_env(self, arch=None):
env = super(PyCryptoRecipe, self).get_recipe_env(arch)
openssl_build_dir = Recipe.get_recipe('openssl', self.ctx).get_build_dir(arch.arch)
target_python = Recipe.get_recipe('python2', self.ctx).get_build_dir(arch.arch)
# include libgmp build dir for gmp.h
libgmp_build_dir = Recipe.get_recipe('libgmp', self.ctx).get_build_dir(arch.arch)
# set to prevent including hostpython headers to avoid
# LONG_BIT definition appears wrong for platform error when compiling for Androidd
env['PYTHONXCPREFIX'] = target_python
env['LDSHARED'] = env['CC'] + ' -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions'
env['PYTHON_ROOT'] = join(target_python, 'python-install')
env['CFLAGS'] += ' -I' + env['PYTHON_ROOT'] + '/include/python2.7'
env['LDFLAGS'] += ' -L' + env['PYTHON_ROOT'] + '/lib' + ' -lpython2.7'
env['CFLAGS'] += ' -I%s' % (join(libgmp_build_dir, 'include'))
env['CC'] = '%s -I%s' % (env['CC'], join(openssl_build_dir, 'include'))
env['LDFLAGS'] = env['LDFLAGS'] + ' -L{}'.format(
self.ctx.get_libs_dir(arch.arch) +
'-L{}'.format(self.ctx.libs_dir)) + ' -L{}'.format(
openssl_build_dir)
env['EXTRA_CFLAGS'] = '--host linux-armv'
env['ac_cv_func_malloc_0_nonnull'] = 'yes'
return env
def build_compiled_components(self, arch):
info('Configuring compiled components in {}'.format(self.name))
env = self.get_recipe_env(arch)
with current_directory(self.get_build_dir(arch.arch)):
configure = sh.Command('./configure')
shprint(configure, '--host=arm-eabi',
'--prefix={}'.format(self.ctx.get_python_install_dir()),
'--enable-shared', _env=env)
super(PyCryptoRecipe, self).build_compiled_components(arch)
recipe = PyCryptoRecipe()
-11
View File
@@ -1,11 +0,0 @@
--- pycrypto-2.6.1/src/hash_SHA2_template.c.orig 2013-10-14 14:38:10.000000000 -0700
+++ pycrypto-2.6.1/src/hash_SHA2_template.c 2014-05-19 10:15:51.000000000 -0700
@@ -87,7 +87,7 @@
* return 1 on success
* return 0 if the length overflows
*/
-int add_length(hash_state *hs, sha2_word_t inc) {
+static int add_length(hash_state *hs, sha2_word_t inc) {
sha2_word_t overflow_detector;
overflow_detector = hs->length_lower;
hs->length_lower += inc;
@@ -1,11 +0,0 @@
--- a/setup.py 2013-10-14 22:38:10.000000000 +0100
+++ b/setup.py 2017-12-20 16:05:16.726389781 +0100
@@ -370,7 +370,7 @@
'ext_modules': plat_ext + [
# _fastmath (uses GNU mp library)
Extension("Crypto.PublicKey._fastmath",
- include_dirs=['src/','/usr/include/'],
+ include_dirs=['src/'],
libraries=['gmp'],
sources=["src/_fastmath.c"]),
+1 -1
View File
@@ -12,7 +12,7 @@ import sh
class TwistedRecipe(CythonRecipe):
version = '16.0.0'
version = '16.6.0'
url = 'https://github.com/twisted/twisted/archive/twisted-{version}.tar.gz'
depends = ['setuptools', 'zope_interface']
+2 -2
View File
@@ -8,10 +8,10 @@ jarsigner -verbose -sigalg SHA1withRSA \
-digestalg SHA1 \
-keystore lbry-android.keystore \
-storepass $KEYSTORE_PASSWORD \
bin/browser-$version-release-unsigned.apk lbry-android \
bin/browser-$version-release-unsigned.apk lbry-android > /dev/null \
&& mv bin/browser-$version-release-unsigned.apk bin/browser-$version-release-signed.apk
~/.buildozer/android/platform/android-sdk-23/build-tools/26.0.1/zipalign -v 4 \
bin/browser-$version-release-signed.apk bin/browser-$version-release.apk \
bin/browser-$version-release-signed.apk bin/browser-$version-release.apk > /dev/null \
&& rm bin/browser-$version-release-signed.apk
@@ -5,12 +5,16 @@ import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Binder;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.io.File;
@@ -33,41 +37,83 @@ import org.renpy.android.ResourceManager;
*/
public class LbrynetService extends PythonService {
private static final String NOTIFICATION_CHANNEL_ID = "io.lbry.browser.DAEMON_NOTIFICATION_CHANNEL";
public static final int SERVICE_NOTIFICATION_GROUP_ID = 5;
public static final String ACTION_STOP_SERVICE = "io.lbry.browser.ACTION_STOP_SERVICE";
public static final String GROUP_SERVICE = "io.lbry.browser.GROUP_SERVICE";
public static final String NOTIFICATION_CHANNEL_ID = "io.lbry.browser.DAEMON_NOTIFICATION_CHANNEL";
public static String TAG = "LbrynetService";
public static LbrynetService serviceInstance;
private BroadcastReceiver stopServiceReceiver;
@Override
public boolean canDisplayNotification() {
return true;
}
@Override
public void onCreate() {
super.onCreate();
// Register the stop service receiver
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ACTION_STOP_SERVICE);
stopServiceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
LbrynetService.this.stopSelf();
}
};
registerReceiver(stopServiceReceiver, intentFilter);
}
@Override
protected void doStartForeground(Bundle extras) {
String serviceTitle = extras.getString("serviceTitle");
String serviceDescription = "The LBRY service is running in the background.";
Context context = getApplicationContext();
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "LBRY Browser", NotificationManager.IMPORTANCE_LOW);
channel.setDescription("LBRY service notification channel");
channel.setShowBadge(false);
notificationManager.createNotificationChannel(channel);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "LBRY Browser", NotificationManager.IMPORTANCE_LOW);
channel.setDescription("LBRY service notification channel");
channel.setShowBadge(false);
notificationManager.createNotificationChannel(channel);
}
Intent contextIntent = new Intent(context, MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, contextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, contextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent stopIntent = new Intent(ACTION_STOP_SERVICE);
PendingIntent stopPendingIntent = PendingIntent.getBroadcast(context, 0, stopIntent, 0);
// Create the notification group
NotificationCompat.Builder groupBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
groupBuilder.setContentTitle("LBRY Browser")
.setColor(ContextCompat.getColor(context, R.color.lbrygreen))
.setSmallIcon(R.drawable.ic_lbry)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setGroup(GROUP_SERVICE)
.setGroupSummary(true);
notificationManager.notify(SERVICE_NOTIFICATION_GROUP_ID, groupBuilder.build());
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
Notification notification = builder.setContentTitle(serviceTitle)
Notification notification = builder.setColor(ContextCompat.getColor(context, R.color.lbrygreen))
.setContentIntent(pendingIntent)
.setContentTitle(serviceTitle)
.setContentText(serviceDescription)
.setContentIntent(pIntent)
.setGroup(GROUP_SERVICE)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.drawable.ic_lbry)
.setOngoing(true)
.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Stop", stopPendingIntent)
.build();
startForeground(1, notification);
}
@@ -91,11 +137,23 @@ public class LbrynetService extends PythonService {
getApplicationContext(), "", LbrynetService.class, "lbrynetservice");
}
// Register broadcast receiver
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
if (stopServiceReceiver != null) {
unregisterReceiver(stopServiceReceiver);
stopServiceReceiver = null;
}
Context context = getApplicationContext();
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancelAll();
super.onDestroy();
serviceInstance = null;
}
+200 -23
View File
@@ -4,6 +4,7 @@ import android.os.Build;
import android.os.Bundle;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
@@ -13,35 +14,55 @@ import android.Manifest;
import android.net.Uri;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.widget.Toast;
import com.brentvatne.react.ReactVideoPackage;
import com.dylanvann.fastimage.FastImageViewPackage;
import com.facebook.react.common.LifecycleState;
import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler;
import com.facebook.react.ReactRootView;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.shell.MainReactPackage;
import com.RNFetchBlob.RNFetchBlobPackage;
import io.lbry.browser.reactpackages.LbryReactPackage;
import io.lbry.browser.reactmodules.BackgroundMediaModule;
import io.lbry.browser.reactmodules.DownloadManagerModule;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity implements DefaultHardwareBackBtnHandler {
private static Activity currentActivity = null;
private static final int OVERLAY_PERMISSION_REQ_CODE = 101;
private static final int STORAGE_PERMISSION_REQ_CODE = 201;
private static final int PHONE_STATE_PERMISSION_REQ_CODE = 202;
private static final int RECEIVE_SMS_PERMISSION_REQ_CODE = 203;
private BroadcastReceiver backgroundMediaReceiver;
private BroadcastReceiver smsReceiver;
private BroadcastReceiver stopServiceReceiver;
private ReactRootView mReactRootView;
private ReactInstanceManager mReactInstanceManager;
@@ -54,12 +75,16 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
public static final String SETTING_KEEP_DAEMON_RUNNING = "keepDaemonRunning";
public static List<Integer> downloadNotificationIds = new ArrayList<Integer>();
/**
* Flag which indicates whether or not the service is running. Will be updated in the
* onResume method.
*/
private boolean serviceRunning;
private boolean receivedStopService;
protected String getMainComponentName() {
return "LBRYApp";
}
@@ -75,6 +100,13 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
}
super.onCreate(savedInstanceState);
currentActivity = this;
// Register the stop service receiver (so that we close the activity if the user requests the service to stop)
registerStopReceiver();
// Register SMS receiver for handling verification texts
registerSmsReceiver();
// Start the daemon service if it is not started
serviceRunning = isServiceRunning(LbrynetService.class);
@@ -88,6 +120,7 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
.setBundleAssetName("index.android.bundle")
.setJSMainModulePath("index")
.addPackage(new MainReactPackage())
.addPackage(new FastImageViewPackage())
.addPackage(new ReactVideoPackage())
.addPackage(new RNFetchBlobPackage())
.addPackage(new LbryReactPackage())
@@ -96,9 +129,91 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
.build();
mReactRootView.startReactApplication(mReactInstanceManager, "LBRYApp", null);
registerBackgroundMediaReceiver();
setContentView(mReactRootView);
}
private void registerStopReceiver() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(LbrynetService.ACTION_STOP_SERVICE);
stopServiceReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity.this.receivedStopService = true;
MainActivity.this.finish();
}
};
registerReceiver(stopServiceReceiver, intentFilter);
}
private void registerBackgroundMediaReceiver() {
// Background media receiver
IntentFilter backgroundMediaFilter = new IntentFilter();
backgroundMediaFilter.addAction(BackgroundMediaModule.ACTION_PLAY);
backgroundMediaFilter.addAction(BackgroundMediaModule.ACTION_PAUSE);
backgroundMediaReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
if (reactContext != null) {
if (BackgroundMediaModule.ACTION_PLAY.equals(action)) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("onBackgroundPlayPressed", null);
}
if (BackgroundMediaModule.ACTION_PAUSE.equals(action)) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("onBackgroundPausePressed", null);
}
}
}
};
registerReceiver(backgroundMediaReceiver, backgroundMediaFilter);
}
public void registerSmsReceiver() {
if (!hasPermission(Manifest.permission.RECEIVE_SMS, this)) {
// don't create the receiver if we don't have the read sms permission
return;
}
IntentFilter smsFilter = new IntentFilter();
smsFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
smsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get the message
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
if (pdus != null && pdus.length > 0) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[0]);
String text = sms.getMessageBody();
if (text == null || text.trim().length() == 0) {
return;
}
// Retrieve verification code from the text message if it contains
// the strings "lbry", "verification code" and the colon (following the expected format)
text = text.toLowerCase();
if (text.indexOf("lbry") > -1 && text.indexOf("verification code") > -1 && text.indexOf(":") > -1) {
String code = text.substring(text.lastIndexOf(":") + 1).trim();
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
if (reactContext != null) {
WritableMap params = Arguments.createMap();
params.putString("code", code);
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("onVerificationCodeReceived", params);
}
}
}
}
}
};
registerReceiver(smsReceiver, smsFilter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
@@ -110,14 +225,17 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
}
}
public static Activity getActivity() {
Activity activity = new Activity();
activity = currentActivity;
return activity;
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case STORAGE_PERMISSION_REQ_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Request for the READ_PHONE_STATE permission
checkPhoneStatePermission(this);
if (BuildConfig.DEBUG && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
@@ -137,14 +255,39 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
case PHONE_STATE_PERMISSION_REQ_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted
acquireDeviceId(this);
// Permission granted. Emit an onPhoneStatePermissionGranted event
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
if (reactContext != null) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("onPhoneStatePermissionGranted", null);
}
} else {
// Permission not granted. Simply show a message.
Toast.makeText(this,
"No permission granted to read your device state. Rewards cannot be claimed.", Toast.LENGTH_LONG).show();
}
break;
case RECEIVE_SMS_PERMISSION_REQ_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted. Emit an onPhoneStatePermissionGranted event
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
if (reactContext != null) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("onReceiveSmsPermissionGranted", null);
}
// register the receiver
if (smsReceiver == null) {
registerSmsReceiver();
}
} else {
// Permission not granted. Simply show a message.
Toast.makeText(this,
"No permission granted to receive your SMS messages. You may have to enter the verification code manually.",
Toast.LENGTH_LONG).show();
}
break;
}
}
@@ -160,7 +303,6 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
} else {
id = telephonyManager.getDeviceId();
}
} catch (SecurityException ex) {
// Maybe the permission was not granted? Try to acquire permission
checkPhoneStatePermission(context);
@@ -172,19 +314,10 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
Toast.makeText(context, "Rewards cannot be claimed because we could not identify your device.", Toast.LENGTH_LONG).show();
}
try {
MessageDigest md = MessageDigest.getInstance("SHA-384");
md.update(id.getBytes("UTF-8"));
String hash = new BigInteger(1, md.digest()).toString(16);
SharedPreferences sp = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(DEVICE_ID_KEY, hash);
editor.commit();
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
// SHA-384 not found, UTF-8 encoding not supported
Toast.makeText(context, "Rewards cannot be claimed because we could not identify your device.", Toast.LENGTH_LONG).show();
}
SharedPreferences sp = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString(DEVICE_ID_KEY, id);
editor.commit();
return id;
}
@@ -230,6 +363,32 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
}
}
if (backgroundMediaReceiver != null) {
unregisterReceiver(backgroundMediaReceiver);
backgroundMediaReceiver = null;
}
if (smsReceiver != null) {
unregisterReceiver(smsReceiver);
smsReceiver = null;
}
if (stopServiceReceiver != null) {
unregisterReceiver(stopServiceReceiver);
stopServiceReceiver = null;
}
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.cancel(BackgroundMediaModule.NOTIFICATION_ID);
notificationManager.cancel(DownloadManagerModule.GROUP_ID);
if (downloadNotificationIds != null) {
for (int i = 0; i < downloadNotificationIds.size(); i++) {
notificationManager.cancel(downloadNotificationIds.get(i));
}
}
if (receivedStopService || !isServiceRunning(LbrynetService.class)) {
notificationManager.cancelAll();
}
super.onDestroy();
if (mReactInstanceManager != null) {
@@ -254,10 +413,10 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
super.onNewIntent(intent);
}
private static void checkPermission(String permission, int requestCode, String rationale, Context context) {
private static void checkPermission(String permission, int requestCode, String rationale, Context context, boolean forceRequest) {
if (ContextCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permission)) {
if (!forceRequest && ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, permission)) {
Toast.makeText(context, rationale, Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions((Activity) context, new String[] { permission }, requestCode);
@@ -265,13 +424,31 @@ public class MainActivity extends Activity implements DefaultHardwareBackBtnHand
}
}
private static void checkPhoneStatePermission(Context context) {
private static void checkPermission(String permission, int requestCode, String rationale, Context context) {
checkPermission(permission, requestCode, rationale, context, false);
}
public static boolean hasPermission(String permission, Context context) {
return (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED);
}
public static void checkPhoneStatePermission(Context context) {
// Request read phone state permission
checkPermission(Manifest.permission.READ_PHONE_STATE,
PHONE_STATE_PERMISSION_REQ_CODE,
"LBRY requires optional access to be able to identify your device for rewards. " +
"You cannot claim rewards without this permission.",
context);
context,
true);
}
public static void checkReceiveSmsPermission(Context context) {
// Request read phone state permission
checkPermission(Manifest.permission.RECEIVE_SMS,
RECEIVE_SMS_PERMISSION_REQ_CODE,
"LBRY requires access to be able to read a verification text message for rewards.",
context,
true);
}
private boolean isServiceRunning(Class<?> serviceClass) {
@@ -0,0 +1,84 @@
package io.lbry.browser.reactmodules;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import io.lbry.browser.LbrynetService;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
public class BackgroundMediaModule extends ReactContextBaseJavaModule {
public static final int NOTIFICATION_ID = 30;
public static final String ACTION_PLAY = "io.lbry.browser.ACTION_MEDIA_PLAY";
public static final String ACTION_PAUSE = "io.lbry.browser.ACTION_MEDIA_PAUSE";
public static final String ACTION_STOP = "io.lbry.browser.ACTION_MEDIA_STOP";
private Context context;
public BackgroundMediaModule(ReactApplicationContext reactContext) {
super(reactContext);
this.context = reactContext;
}
@Override
public String getName() {
return "BackgroundMedia";
}
@ReactMethod
public void showPlaybackNotification(String title, String publisher, String uri, boolean paused) {
Intent contextIntent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, contextIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Intent playIntent = new Intent();
playIntent.setAction(ACTION_PLAY);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(context, 0, playIntent, 0);
Intent pauseIntent = new Intent();
pauseIntent.setAction(ACTION_PAUSE);
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(context, 0, pauseIntent, 0);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, LbrynetService.NOTIFICATION_CHANNEL_ID);
builder.setColor(ContextCompat.getColor(context, R.color.lbrygreen))
.setContentIntent(pendingIntent)
.setContentTitle(title)
.setContentText(publisher)
.setGroup(LbrynetService.GROUP_SERVICE)
.setOngoing(!paused)
.setSmallIcon(paused ? android.R.drawable.ic_media_pause : android.R.drawable.ic_media_play)
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0))
.addAction(paused ? android.R.drawable.ic_media_play : android.R.drawable.ic_media_pause,
paused ? "Play" : "Pause",
paused ? playPendingIntent : pausePendingIntent)
.build();
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
@ReactMethod
public void hidePlaybackNotification() {
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.cancel(NOTIFICATION_ID);
}
}
@@ -1,6 +1,7 @@
package io.lbry.browser.reactmodules;
import android.app.Activity;
import android.app.NotificationChannel;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.SharedPreferences;
@@ -14,6 +15,7 @@ import io.lbry.browser.MainActivity;
import io.lbry.browser.ServiceHelper;
public class DaemonServiceControlModule extends ReactContextBaseJavaModule {
private Context context;
public DaemonServiceControlModule(ReactApplicationContext reactContext) {
@@ -6,6 +6,7 @@ import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
@@ -33,6 +34,8 @@ public class DownloadManagerModule extends ReactContextBaseJavaModule {
private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#");
private static final int MAX_FILENAME_LENGTH = 20;
private static final int MAX_PROGRESS = 100;
private static final String GROUP_DOWNLOADS = "io.lbry.browser.GROUP_DOWNLOADS";
@@ -43,7 +46,9 @@ public class DownloadManagerModule extends ReactContextBaseJavaModule {
public static final String NOTIFICATION_ID_KEY = "io.lbry.browser.notificationId";
public static final int GROUP_ID = 0;
public static final int GROUP_ID = 20;
private static NotificationCompat.Builder groupBuilder = null;
public static boolean groupCreated = false;
@@ -53,7 +58,13 @@ public class DownloadManagerModule extends ReactContextBaseJavaModule {
}
private int generateNotificationId() {
return new Random().nextInt();
int id = 0;
Random random = new Random();
do {
id = random.nextInt();
} while (id < 100);
return id;
}
@Override
@@ -80,15 +91,16 @@ public class DownloadManagerModule extends ReactContextBaseJavaModule {
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, GROUP_ID, intent, 0);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
builder.setContentTitle("Active downloads")
.setContentText("Active downloads")
.setSmallIcon(android.R.drawable.stat_sys_download)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setGroup(GROUP_DOWNLOADS)
.setGroupSummary(true)
.setDeleteIntent(pendingIntent);
notificationManager.notify(GROUP_ID, builder.build());
groupBuilder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
groupBuilder.setContentTitle("Active LBRY downloads")
// contentText will be displayed if there are no notifications in the group
.setContentText("There are no active LBRY downloads.")
.setSmallIcon(android.R.drawable.stat_sys_download)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setGroup(GROUP_DOWNLOADS)
.setGroupSummary(true)
.setDeleteIntent(pendingIntent);
notificationManager.notify(GROUP_ID, groupBuilder.build());
groupCreated = true;
}
@@ -102,7 +114,7 @@ public class DownloadManagerModule extends ReactContextBaseJavaModule {
}
@ReactMethod
public void startDownload(String id, String fileName) {
public void startDownload(String id, String filename) {
createNotificationChannel();
createNotificationGroup();
@@ -110,48 +122,77 @@ public class DownloadManagerModule extends ReactContextBaseJavaModule {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
// The file URI is used as the unique ID
builder.setContentIntent(getLaunchPendingIntent(id))
.setContentTitle(String.format("Downloading %s...", fileName))
.setContentTitle(String.format("Downloading %s", truncateFilename(filename)))
.setGroup(GROUP_DOWNLOADS)
.setPriority(NotificationCompat.PRIORITY_LOW)
.setProgress(MAX_PROGRESS, 0, false)
.setSmallIcon(android.R.drawable.stat_sys_download);
int notificationId = generateNotificationId();
downloadIdNotificationIdMap.put(id, notificationId);
int notificationId = getNotificationId(id);
builders.put(notificationId, builder);
notificationManager.notify(notificationId, builder.build());
if (groupCreated && groupBuilder != null) {
groupBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
notificationManager.notify(GROUP_ID, groupBuilder.build());
}
}
@ReactMethod
public void updateDownload(String id, String fileName, double progress, double writtenBytes, double totalBytes) {
if (!downloadIdNotificationIdMap.containsKey(id)) {
return;
}
int notificationId = downloadIdNotificationIdMap.get(id);
if (!builders.containsKey(notificationId)) {
public void updateDownload(String id, String filename, double progress, double writtenBytes, double totalBytes) {
int notificationId = getNotificationId(id);
if (notificationId == -1) {
return;
}
createNotificationChannel();
createNotificationGroup();
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
NotificationCompat.Builder builder = builders.get(notificationId);
NotificationCompat.Builder builder = null;
if (builders.containsKey(notificationId)) {
builder = builders.get(notificationId);
} else {
builder = new NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID);
builder.setContentTitle(String.format("Downloading %s", truncateFilename(filename)))
.setPriority(NotificationCompat.PRIORITY_LOW);
builders.put(notificationId, builder);
}
builder.setContentIntent(getLaunchPendingIntent(id))
.setContentText(String.format("%.0f%% (%s / %s)", progress, formatBytes(writtenBytes), formatBytes(totalBytes)))
.setGroup(GROUP_DOWNLOADS)
.setProgress(MAX_PROGRESS, new Double(progress).intValue(), false);
.setProgress(MAX_PROGRESS, new Double(progress).intValue(), false)
.setSmallIcon(android.R.drawable.stat_sys_download);
notificationManager.notify(notificationId, builder.build());
if (progress == MAX_PROGRESS) {
builder.setContentTitle(String.format("Downloaded %s", fileName))
builder.setContentTitle(String.format("Downloaded %s", truncateFilename(filename, 30)))
.setContentText(String.format("%s", formatBytes(totalBytes)))
.setProgress(0, 0, false);
.setGroup(GROUP_DOWNLOADS)
.setProgress(0, 0, false)
.setSmallIcon(android.R.drawable.stat_sys_download_done);
notificationManager.notify(notificationId, builder.build());
downloadIdNotificationIdMap.remove(id);
builders.remove(notificationId);
if (downloadIdNotificationIdMap.containsKey(id)) {
downloadIdNotificationIdMap.remove(id);
}
if (builders.containsKey(notificationId)) {
builders.remove(notificationId);
}
// If there are no more downloads and the group exists, set the icon to stop animating
if (groupCreated && groupBuilder != null && downloadIdNotificationIdMap.size() == 0) {
groupBuilder.setSmallIcon(android.R.drawable.stat_sys_download_done);
notificationManager.notify(GROUP_ID, groupBuilder.build());
}
String spKey = String.format("dl__%s", id);
SharedPreferences sp = context.getSharedPreferences(MainActivity.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(spKey);
editor.apply();
}
}
@@ -179,7 +220,26 @@ public class DownloadManagerModule extends ReactContextBaseJavaModule {
}
}
private String formatBytes(double bytes)
private int getNotificationId(String id) {
String spKey = String.format("dl__%s", id);
SharedPreferences sp = context.getSharedPreferences(MainActivity.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
int notificationId = sp.getInt(spKey, -1);
if (notificationId == -1) {
notificationId = generateNotificationId();
SharedPreferences.Editor editor = sp.edit();
editor.putInt(spKey, notificationId);
editor.apply();
}
if (MainActivity.downloadNotificationIds != null &&
!MainActivity.downloadNotificationIds.contains(notificationId)) {
MainActivity.downloadNotificationIds.add(notificationId);
}
downloadIdNotificationIdMap.put(id, notificationId);
return notificationId;
}
private static String formatBytes(double bytes)
{
if (bytes < 1048576) { // < 1MB
return String.format("%s KB", DECIMAL_FORMAT.format(bytes / 1024.0));
@@ -191,4 +251,24 @@ public class DownloadManagerModule extends ReactContextBaseJavaModule {
return String.format("%s GB", DECIMAL_FORMAT.format(bytes / (1024.0 * 1024.0 * 1024.0)));
}
private static String truncateFilename(String filename, int alternateMaxLength) {
int maxLength = alternateMaxLength > 0 ? alternateMaxLength : MAX_FILENAME_LENGTH;
if (filename.length() < maxLength) {
return filename;
}
// Get the extension
int dotIndex = filename.lastIndexOf(".");
if (dotIndex > -1) {
String extension = filename.substring(dotIndex);
return String.format("%s...%s", filename.substring(0, maxLength - extension.length() - 4), extension);
}
return String.format("%s...", filename.substring(0, maxLength - 3));
}
private static String truncateFilename(String filename) {
return truncateFilename(filename, 0);
}
}
@@ -2,13 +2,20 @@ package io.lbry.browser.reactmodules;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.Manifest;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.view.View;
import android.view.WindowManager;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import io.lbry.browser.MainActivity;
public class UtilityModule extends ReactContextBaseJavaModule {
private Context context;
@@ -52,23 +59,115 @@ public class UtilityModule extends ReactContextBaseJavaModule {
@ReactMethod
public void hideNavigationBar() {
if (context != null && context instanceof Activity) {
Activity activity = (Activity) context;
View decorView = activity.getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_IMMERSIVE |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
final Activity activity = MainActivity.getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
public void run() {
View decorView = activity.getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
}
});
}
}
@ReactMethod
public void showNavigationBar() {
if (context != null && context instanceof Activity) {
Activity activity = (Activity) context;
View decorView = activity.getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_VISIBLE);
final Activity activity = MainActivity.getActivity();
if (activity != null) {
activity.runOnUiThread(new Runnable() {
public void run() {
View decorView = activity.getWindow().getDecorView();
decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_VISIBLE);
}
});
}
}
@ReactMethod
public void getDeviceId(boolean requestPermission, final Promise promise) {
if (isEmulator()) {
promise.reject("Rewards cannot be claimed from an emulator nor virtual device.");
return;
}
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String id = null;
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
id = telephonyManager.getImei(); // GSM
if (id == null) {
id = telephonyManager.getMeid(); // CDMA
}
} else {
id = telephonyManager.getDeviceId();
}
} catch (SecurityException ex) {
// Maybe the permission was not granted? Try to acquire permission
/*if (requestPermission) {
requestPhoneStatePermission();
}*/
} catch (Exception ex) {
// id could not be obtained. Display a warning that rewards cannot be claimed.
promise.reject(ex.getMessage());
}
if (id == null || id.trim().length() == 0) {
promise.reject("Rewards cannot be claimed because your device could not be identified.");
return;
}
promise.resolve(id);
}
@ReactMethod
public void canReceiveSms(final Promise promise) {
promise.resolve(MainActivity.hasPermission(Manifest.permission.RECEIVE_SMS, MainActivity.getActivity()));
}
@ReactMethod
public void requestReceiveSmsPermission() {
MainActivity activity = (MainActivity) MainActivity.getActivity();
if (activity != null) {
// Request for the RECEIVE_SMS permission
MainActivity.checkReceiveSmsPermission(activity);
}
}
private static boolean isEmulator() {
String buildModel = Build.MODEL.toLowerCase();
return (// Check FINGERPRINT
Build.FINGERPRINT.startsWith("generic") ||
Build.FINGERPRINT.startsWith("unknown") ||
Build.FINGERPRINT.contains("test-keys") ||
// Check MODEL
buildModel.contains("google_sdk") ||
buildModel.contains("emulator") ||
buildModel.contains("android sdk built for x86") ||
// Check MANUFACTURER
Build.MANUFACTURER.contains("Genymotion") ||
"unknown".equals(Build.MANUFACTURER) ||
// Check HARDWARE
Build.HARDWARE.contains("goldfish") ||
Build.HARDWARE.contains("vbox86") ||
// Check PRODUCT
"google_sdk".equals(Build.PRODUCT) ||
"sdk_google_phone_x86".equals(Build.PRODUCT) ||
"sdk".equals(Build.PRODUCT) ||
"sdk_x86".equals(Build.PRODUCT) ||
"vbox86p".equals(Build.PRODUCT) ||
// Check BRAND and DEVICE
(Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
);
}
}
@@ -5,6 +5,7 @@ import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import io.lbry.browser.reactmodules.BackgroundMediaModule;
import io.lbry.browser.reactmodules.DaemonServiceControlModule;
import io.lbry.browser.reactmodules.DownloadManagerModule;
import io.lbry.browser.reactmodules.FirstRunModule;
@@ -27,6 +28,7 @@ public class LbryReactPackage implements ReactPackage {
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new BackgroundMediaModule(reactContext));
modules.add(new DaemonServiceControlModule(reactContext));
modules.add(new DownloadManagerModule(reactContext));
modules.add(new FirstRunModule(reactContext));
@@ -14,4 +14,4 @@ public class NotificationDeletedReceiver extends BroadcastReceiver {
DownloadManagerModule.groupCreated = false;
}
}
}
}
Loaded 100 of 350 files, more files were not shown because too many files have changed in this diff. Show more