Compare commits

...
Author SHA1 Message Date
Akinwale Ariwodola 7dbb60db65 display debug info for received notifications 2020-08-25 14:25:24 +01:00
Akinwale Ariwodola 593b34079c load notifications after app startup 2020-08-20 20:47:14 +01:00
Akinwale Ariwodola becb533624 fix notification relative time display 2020-08-20 20:32:22 +01:00
Akinwale Ariwodola 8efc0522f2 load unread count after fetching remote notifications 2020-08-20 20:03:30 +01:00
Akinwale Ariwodola cead924ca5 Notification timestamp timezone fix. Tweak loading unread notification count. 2020-08-20 19:56:35 +01:00
Akinwale Ariwodola f83a043664 fix notification sorting 2020-08-20 19:00:21 +01:00
Akinwale Ariwodola e8a0bca5ea tweak equality check for LbryNotification 2020-08-20 18:45:02 +01:00
Akinwale Ariwodola 1198c2298a add and update translations 2020-08-20 18:28:32 +01:00
Akinwale Ariwodola 7205acb9d6 Sort newly added notifications. Add remote loading TTL. 2020-08-20 18:06:35 +01:00
Akinwale Ariwodola d21cfd55ab Handle special URLs from notifications. Disable auto load/play for comment notifications. 2020-08-20 16:39:45 +01:00
Akinwale Ariwodola 47cbc3624c Merge pull request #980 from lbryio/channel-comment-hash
properly handle channel comment notifications
2020-08-20 16:26:08 +01:00
Akinwale Ariwodola 1f9a0886a0 properly handle channel comment notifications 2020-08-20 16:20:46 +01:00
Akinwale Ariwodola dd5ea68915 new YRBL 2020-08-20 14:52:41 +01:00
Akinwale Ariwodola b3bba4d273 Merge pull request #979 from lbryio/is-seen
check is_seen flag. display comment author thumbnails if present.
2020-08-20 13:30:28 +01:00
Akinwale Ariwodola 10c123ba6a check is_seen flag. display comment author thumbnails if present. 2020-08-20 13:26:41 +01:00
Akinwale Ariwodola a8ba45b941 bumpversion 0.15.17 --> 0.16.0 2020-08-19 18:18:37 +01:00
Akinwale Ariwodola 3652cdf6bc CI apt-transport-https 2020-08-19 18:14:13 +01:00
Akinwale Ariwodola f2a7a8c439 cleanup: yarn.lock 2020-08-19 18:10:57 +01:00
Akinwale Ariwodola 78d5a99441 Gradle fix (#978) 2020-08-19 18:09:37 +01:00
Akinwale Ariwodola 6931dbe79c Instant verification (#974)
* add instant verification options and Google Play Billing
bumpversion 0.15.16 --> 0.15.17
restore account_undergo_review default string
twitter sign-in flow
fix build error
final changes
update api key and secret
* tweak build script
2020-08-19 17:23:35 +01:00
Akinwale Ariwodola 4d024c06cc In-app notifications (#969)
* display notification bell icon beside URL bar
* notification model
* persist received notifications
* Refresh notification list. Add  is_read flag and display unread count.
* Hide notifications when opening the navigatinon drawer. Open selected notification item before hiding the list.
* update local store with remote notifications
* use card view for notification items
* make notification cards clickable
* handle comment hash
* fix remote notifications not loading. fix comment scroll.
* Improve in-app comment notification linking. Add icons.
2020-08-18 14:19:35 +01:00
Akinwale Ariwodola ddcb190457 do not display global background servce initializing indicator 2020-08-07 10:11:57 +01:00
Akinwale Ariwodola dd14b90d7e Merge pull request #967 from kekkyojin/sendto-feat
Allow to publish files via Send To feature
2020-07-29 15:20:59 +01:00
Akinwale Ariwodola 4b86444478 bumpversion 0.15.15 --> 0.15.16 2020-07-27 11:11:10 +01:00
Javi Rueda feb7f260dc Allow to publish files via Send To feature 2020-07-24 01:59:59 +02:00
Akinwale Ariwodola 74c7a1de4d sdk 0.79.1. Clear resolved sub cache after sync. 2020-07-23 20:04:48 +01:00
Akinwale Ariwodola 88a43dc679 set sync interval back to 5 minutes 2020-07-22 05:52:44 +01:00
Akinwale Ariwodola 1bb5ce72fa Proper fix for subscription sync retention. Eliminate double sync attempt on startup. 2020-07-22 05:49:48 +01:00
Akinwale Ariwodola b4ce544965 bumpversion 0.15.14 --> 0.15.15 2020-07-21 21:25:26 +01:00
Akinwale Ariwodola 1ec6f6173a sdk 0.79.0 2020-07-21 21:13:05 +01:00
Akinwale Ariwodola 8ee19b3f5c Sub sync fix (#965)
* improve sub sync merge handling logic
* do not try to re-subscribe local syncs remotely whhen merging
2020-07-21 19:49:22 +01:00
Akinwale Ariwodola 1055392b7f temporarily omit duration 2020-07-21 19:39:47 +01:00
Akinwale Ariwodola c772cf2ead check buffering events (#952)
* check buffering events
* use the claim permanent url for buffer events
* update request parameters
* hash user ids for buffer events
* update buffer event endpoint
2020-07-21 19:30:45 +01:00
Akinwale Ariwodola 481c50f465 fix open.lbry.com regex 2020-07-17 11:39:59 +01:00
Akinwale Ariwodola 71bc969f2a Merge pull request #962 from kekkyojin/deeplink
Add open.lbry.com deep-links
2020-07-17 11:29:16 +01:00
Akinwale Ariwodola e4edebfed7 fix for follow / unfollow confusion 2020-07-16 13:51:08 +01:00
Javi Rueda e8a5ab8307 Add open.lbry.com deep-links 2020-07-13 19:00:12 +02:00
Akinwale Ariwodola 3738f3af21 Merge pull request #954 from lbryio/invalidated-auth
gracefully handle invalidated auth tokens
2020-07-05 19:07:21 +01:00
Akinwale Ariwodola 74d10e4199 gracefully handle invalidated auth tokens 2020-07-05 18:40:31 +01:00
Akinwale Ariwodola 080e00becf Merge pull request #949 from kekkyojin/patch-1
Bintray repository is no longer needed
2020-06-30 15:30:18 +01:00
Javi Rueda 049d905d7d Bintray repository is no longer needed
LBRY SDK is now hosted on JCenter, which is already available out-of-the-box on Android Studio. The Bintray url is no longer reguired. When building LBRY on F-Droid, I have to remove this line on the build YAML script and it is building correctly.

On my local machine, it builds after commenting it.
2020-06-26 21:06:12 +02:00
Akinwale Ariwodola 33094f8c88 fix empty bindArgs crash error for sql query to clear subscriptions 2020-06-25 23:33:04 +01:00
Akinwale Ariwodola 6c44e503db fix subscriptions sync (#947) 2020-06-25 21:16:41 +01:00
Akinwale Ariwodola fa78c80592 fix ClaimListAdapter and strings.xml 2020-06-25 20:42:55 +01:00
Akinwale Ariwodola 07630ca97b fix: crash bugs 2020-06-25 20:23:24 +01:00
Akinwale Ariwodola a2b6d4e570 bumpversion 0.15.13 --> 0.15.14 2020-06-25 20:16:38 +01:00
Akinwale Ariwodola 9d6b3ddf81 combined tip / support dialog and signed supports (#944)
* combined tip / support dialog and signed supports
* update button label when amount is updated
2020-06-25 20:15:58 +01:00
Akinwale Ariwodola 0a2769859a fix issue with featured search result crash 2020-06-24 10:45:29 +01:00
Akinwale Ariwodola c4a1ed801a make FontAwesome strings non-translatable 2020-06-19 07:18:19 +01:00
Akinwale Ariwodola 453394bf1b update README 2020-06-19 06:57:48 +01:00
Akinwale Ariwodola 4b7dfba5a1 sdk 0.76.0 2020-06-15 19:43:41 +01:00
Akinwale Ariwodola e699fcf0b3 remove broken Bengali strings.xml 2020-06-15 19:29:26 +01:00
Akinwale Ariwodola 7e80f707e0 bumpversion 0.15.12 --> 0.15.13 2020-06-15 19:17:18 +01:00
Akinwale Ariwodola 467f037170 sFix default sort on channel page. Add Bengali and Javanese translations. 2020-06-15 19:11:20 +01:00
Akinwale Ariwodola 89d5b40e5f only allow sending to addresses that begin with b 2020-06-15 15:18:42 +01:00
Akinwale Ariwodola 34fba010e1 use lbryplayer.xyz streaming URLs for signed in users 2020-06-15 15:07:17 +01:00
Akinwale Ariwodola d7396bb044 add MoonPay 'Buy LBC' button (#937)
* add MoonPay 'Buy LBC' button
* tweak button style
* tweak MoonPay parameters
2020-06-13 16:14:06 +01:00
joaquimbrugues fda0817ad1 Add Catalan language (#928)
* Add Catalan language
* Add 'catalan' string to strings.xml
* Attempt to fix conflicting changes
2020-06-11 19:41:53 +01:00
Akinwale Ariwodola 895ca75506 Merge pull request #935 from lbryio/edit-publish-channel
auto select corresponding channel when editing a publish
2020-06-11 19:38:24 +01:00
Akinwale Ariwodola a04448ebe8 auto select corresponding channel when editing a publish 2020-06-11 19:31:06 +01:00
Akinwale Ariwodola 26ccbf2709 reduce comment cost from 2 to 1 2020-06-10 09:54:07 +01:00
Akinwale Ariwodola 7d6c11a88c Remove lbrysdk AARs. Add bintray dependencies. 2020-06-09 22:27:42 +01:00
Akinwale Ariwodola 8742913c33 SDK 0.75.0. Update translations. 2020-06-05 15:31:13 +01:00
Akinwale Ariwodola 8e6e0f0099 fix player notification pending intent 2020-06-05 09:42:45 +01:00
Akinwale Ariwodola a4585de807 reset playback notification large icon when content changes 2020-06-05 09:40:22 +01:00
Akinwale Ariwodola 6c24749ad5 tweak player view resume 2020-06-05 09:34:45 +01:00
Akinwale Ariwodola c73509a4ca set large icon for playback notification 2020-06-05 09:30:54 +01:00
Akinwale Ariwodola 673b85b2aa bumpversion 0.15.11 --> 0.15.12 2020-06-05 09:07:35 +01:00
Akinwale Ariwodola fe6e60cd67 implement background playback with control notification 2020-06-05 09:04:24 +01:00
Akinwale Ariwodola 8bcee90d68 Add background playback setting. Fix crash bugs. 2020-06-05 08:25:08 +01:00
Akinwale Ariwodola 084407e129 Update translations. Add Catalan and Serbian strings. 2020-06-05 07:50:52 +01:00
Akinwale Ariwodola 4a3db5ae20 enforce minimum spend / deposits 2020-06-05 07:40:44 +01:00
Akinwale Ariwodola b36813ebe6 fix nsfw search flag 2020-06-05 07:23:56 +01:00
Akinwale Ariwodola cc1ddfa16e use only txids for unlocking tips 2020-06-05 07:17:56 +01:00
Akinwale Ariwodola 5f1775d478 fix possible null item in channel id list 2020-06-05 07:04:54 +01:00
Akinwale Ariwodola 288e35dd64 fix margins 2020-06-02 09:40:17 +01:00
Akinwale Ariwodola d4af28d1c5 display publisher title and thumbnail on file page 2020-06-02 09:34:59 +01:00
Akinwale Ariwodola 37cf85a5f6 bumpversion 0.15.10 --> 0.15.11 2020-06-02 09:05:04 +01:00
Akinwale Ariwodola c2cbd76f49 change comment confirmation title 2020-06-02 09:03:56 +01:00
Akinwale Ariwodola 3d874435c3 change BigDecimal initialisation for comment cost 2020-06-02 08:57:12 +01:00
Akinwale Ariwodola 9ed8864f23 More crash fixes. Change comment cost to 2 LBC. 2020-06-02 08:55:34 +01:00
Akinwale Ariwodola 61263dd59d bumpversion 0.15.9 --> 0.15.10 2020-06-01 08:56:38 +01:00
Akinwale Ariwodola 2707e135c6 comment creation event 2020-06-01 08:53:58 +01:00
Akinwale Ariwodola f9de0d7937 do not prompt again for content that is already purchased 2020-06-01 08:48:17 +01:00
Akinwale Ariwodola f03d58d648 tweak PIP player for certain aspect ratios 2020-06-01 08:33:07 +01:00
Akinwale Ariwodola f49a3570e9 fix file view display for cached reposts 2020-05-31 21:22:37 +01:00
Akinwale Ariwodola 1d97f9008d implement commenting with tips (#922)
* implement commenting with tips
* add comments to channel page
2020-05-31 21:06:03 +01:00
140 changed files with 12766 additions and 2016 deletions

No files matched your search

+1
View File
@@ -60,6 +60,7 @@ buck-out/
# Other Files # Other Files
app/google-services.json app/google-services.json
app/twitter.properties
*.log *.log
.vagrant .vagrant
*.hprof *.hprof
+21 -13
View File
@@ -8,10 +8,13 @@ build apk:
stage: build stage: build
image: lbry/android-base:platform-28 image: lbry/android-base:platform-28
before_script: before_script:
- apt-get -y update && apt-get -y install build-essential ca-certificates curl git gpg-agent openjdk-8-jdk software-properties-common wget zipalign - echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install build-essential ca-certificates curl git gpg-agent openjdk-8-jdk software-properties-common wget zipalign git-secret
- git secret reveal
- chmod u+x $CI_PROJECT_DIR/gradlew - chmod u+x $CI_PROJECT_DIR/gradlew
- export ANDROID_SDK_ROOT=~/.buildozer/android/platform/android-sdk-23 - export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -p $CI_PROJECT_DIR -q printVersionName --console=plain | tail -1)
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
artifacts: artifacts:
paths: paths:
- bin/browser-*-release__arm.apk - bin/browser-*-release__arm.apk
@@ -19,12 +22,7 @@ build apk:
expire_in: 1 week expire_in: 1 week
script: script:
- export PATH=/usr/bin:$PATH - export PATH=/usr/bin:$PATH
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import - export ANDROID_SDK_ROOT=~/.buildozer/android/platform/android-sdk-23
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install git-secret
- git secret reveal
- yarn
- chmod u+x ./release.sh - chmod u+x ./release.sh
- ./release.sh - ./release.sh
- cp bin/browser-$BUILD_VERSION-release__arm.apk /dev/null - cp bin/browser-$BUILD_VERSION-release__arm.apk /dev/null
@@ -36,10 +34,15 @@ deploy build.lbry.io:
dependencies: dependencies:
- build apk - build apk
before_script: before_script:
- apt-get -y update && apt-get -y install openjdk-8-jdk - apt-get -y update && apt-get -y install apt-transport-https
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install openjdk-8-jdk git git-secret
- pip install awscli - pip install awscli
- chmod u+x $CI_PROJECT_DIR/gradlew - chmod u+x $CI_PROJECT_DIR/gradlew
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1) - git secret reveal
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -p $CI_PROJECT_DIR -q printVersionName --console=plain | tail -1)
- export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk - export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk
- export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk - export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk
script: script:
@@ -55,10 +58,15 @@ release apk:
dependencies: dependencies:
- build apk - build apk
before_script: before_script:
- apt-get -y update && apt-get -y install openjdk-8-jdk - apt-get -y update && apt-get -y install apt-transport-https
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install openjdk-8-jdk git git-secret
- pip install awscli githubrelease - pip install awscli githubrelease
- git secret reveal
- chmod u+x $CI_PROJECT_DIR/gradlew - chmod u+x $CI_PROJECT_DIR/gradlew
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1) - export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -p $CI_PROJECT_DIR -q printVersionName --console=plain | tail -1)
- export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk - export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk
- export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk - export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk
script: script:
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -1,2 +1,3 @@
lbry-android.keystore:0d958c531870694624cc877ea98ca1c583485f8ebbb3a5acca58b1930c190d65 lbry-android.keystore:0d958c531870694624cc877ea98ca1c583485f8ebbb3a5acca58b1930c190d65
app/google-services.json:896a0bee8294a36d061f10fa926129d8a780528b34d0a2f03113400c4246d67c app/google-services.json:896a0bee8294a36d061f10fa926129d8a780528b34d0a2f03113400c4246d67c
app/twitter.properties:01212d70712f2041efb5c814bf30ecbf6f72e1ca5179c7647c4f8cbd995dd033
+2 -2
View File
@@ -2,7 +2,7 @@
[![pipeline status](https://ci.lbry.tech/lbry/lbry-android/badges/master/pipeline.svg)](https://ci.lbry.tech/lbry/lbry-android/commits/master) [![pipeline status](https://ci.lbry.tech/lbry/lbry-android/badges/master/pipeline.svg)](https://ci.lbry.tech/lbry/lbry-android/commits/master)
[![GitHub license](https://img.shields.io/github/license/lbryio/lbry-android)](https://github.com/lbryio/lbry-android/blob/master/LICENSE) [![GitHub license](https://img.shields.io/github/license/lbryio/lbry-android)](https://github.com/lbryio/lbry-android/blob/master/LICENSE)
An Android browser and wallet for the [LBRY](https://lbry.com) network. This app bundles [LBRY SDK](https://github.com/lbryio/lbry) as a background service with a UI layer built with React Native. An Android browser and wallet for the [LBRY](https://lbry.com) network.
<img src="https://spee.ch/@lbry:3f/android-08-homepage.gif" alt="LBRY Android GIF" width="384px" /> <img src="https://spee.ch/@lbry:3f/android-08-homepage.gif" alt="LBRY Android GIF" width="384px" />
@@ -18,7 +18,7 @@ The minimum supported Android version is 5.0 Lollipop. There are two ways to ins
The app can be launched by opening **LBRY** from the device's app drawer or via the shortcut on the home screen if that was created upon installation. The app can be launched by opening **LBRY** from the device's app drawer or via the shortcut on the home screen if that was created upon installation.
## Running from Source ## Running from Source
Please refer to https://github.com/lbryio/lbry-react-native/blob/master/README.md Clone the repository and open the project in Android Studio. Android Studio will automatically run the initial build process. Click the Run button to launch the app on your simulator or connected debugging device after the build process is complete.
## Contributing ## Contributing
Contributions to this project are welcome, encouraged, and compensated. For more details, see https://lbry.io/faq/contributing Contributions to this project are welcome, encouraged, and compensated. For more details, see https://lbry.io/faq/contributing
+34 -9
View File
@@ -16,12 +16,16 @@ android {
applicationId "io.lbry.browser" applicationId "io.lbry.browser"
minSdkVersion 21 minSdkVersion 21
targetSdkVersion 29 targetSdkVersion 29
versionCode 1509 versionCode 1600
versionName "0.15.9" versionName "0.16.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
} }
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
}
productFlavors { productFlavors {
__32bit { __32bit {
versionCode android.defaultConfig.versionCode * 10 + 1 versionCode android.defaultConfig.versionCode * 10 + 1
@@ -38,7 +42,17 @@ android {
} }
buildTypes { buildTypes {
debug {
Properties twitterProps = new Properties()
twitterProps.load(project.file('twitter.properties').newDataInputStream())
resValue "string", "TWITTER_CONSUMER_KEY", "\"${twitterProps.getProperty("twitterConsumerKey")}\""
resValue "string", "TWITTER_CONSUMER_SECRET", "\"${twitterProps.getProperty("twitterConsumerSecret")}\""
}
release { release {
Properties twitterProps = new Properties()
twitterProps.load(project.file('twitter.properties').newDataInputStream())
resValue "string", "TWITTER_CONSUMER_KEY", "\"${twitterProps.getProperty("twitterConsumerKey")}\""
resValue "string", "TWITTER_CONSUMER_SECRET", "\"${twitterProps.getProperty("twitterConsumerSecret")}\""
minifyEnabled false minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
} }
@@ -51,12 +65,19 @@ task printVersionName {
} }
} }
configurations {
all {
exclude module: 'httpclient'
exclude module: 'commons-logging'
}
}
dependencies { dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar']) implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.2.0-rc01' implementation 'androidx.appcompat:appcompat:1.3.0-alpha01'
implementation 'androidx.legacy:legacy-support-v4:1.0.0' implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.2.0-alpha06' implementation 'com.google.android.material:material:1.3.0-alpha01'
implementation "androidx.cardview:cardview:1.0.0" implementation "androidx.cardview:cardview:1.0.0"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment:2.2.2' implementation 'androidx.navigation:navigation-fragment:2.2.2'
@@ -64,17 +85,21 @@ dependencies {
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0' implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0' implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
implementation 'androidx.preference:preference:1.1.1' implementation 'androidx.preference:preference:1.1.1'
implementation 'androidx.webkit:webkit:1.3.0-alpha02' implementation 'androidx.webkit:webkit:1.3.0-alpha03'
implementation 'androidx.camera:camera-core:1.0.0-beta03' implementation 'androidx.camera:camera-core:1.0.0-beta03'
implementation 'androidx.camera:camera-camera2:1.0.0-beta03' implementation 'androidx.camera:camera-camera2:1.0.0-beta03'
implementation 'androidx.camera:camera-lifecycle:1.0.0-beta03' implementation 'androidx.camera:camera-lifecycle:1.0.0-beta03'
implementation 'androidx.camera:camera-view:1.0.0-alpha10' implementation 'androidx.camera:camera-view:1.0.0-alpha10'
implementation 'androidx.browser:browser:1.2.0'
implementation 'com.github.bumptech.glide:glide:4.11.0' implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.squareup.okhttp3:okhttp:4.4.1' implementation 'com.squareup.okhttp3:okhttp:4.4.1'
implementation 'com.google.firebase:firebase-analytics:17.4.1' implementation 'com.google.firebase:firebase-analytics:17.4.2'
implementation 'com.google.android.gms:play-services-base:17.2.1' implementation 'com.google.android.gms:play-services-base:17.2.1'
implementation 'com.google.firebase:firebase-messaging:20.1.7' implementation 'com.google.firebase:firebase-messaging:20.2.0'
implementation 'com.google.oauth-client:google-oauth-client:1.30.4'
implementation 'com.android.billingclient:billing:3.0.0'
implementation 'com.google.code.gson:gson:2.8.6' implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.google.android.exoplayer:exoplayer-core:2.11.4' implementation 'com.google.android.exoplayer:exoplayer-core:2.11.4'
@@ -100,8 +125,8 @@ dependencies {
androidTestImplementation 'androidx.test.ext:junit:1.1.1' androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0' androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
__32bitImplementation files('libs/lbrysdk-0.74.0-release__arm.aar') __32bitImplementation 'io.lbry:lbrysdk32:0.80.0'
__64bitImplementation files('libs/lbrysdk-0.74.0-release__arm64.aar') __64bitImplementation 'io.lbry:lbrysdk64:0.80.0'
} }
apply plugin: 'com.google.gms.google-services' apply plugin: 'com.google.gms.google-services'
Binary file not shown.
Binary file not shown.
Binary file not shown.
+15
View File
@@ -10,6 +10,7 @@
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.android.vending.BILLING" />
<application <application
android:allowBackup="true" android:allowBackup="true"
@@ -50,12 +51,26 @@
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="video/*" />
<data android:mimeType="image/*" />
<data android:mimeType="text/*" />
</intent-filter>
<intent-filter> <intent-filter>
<action android:name="android.intent.action.VIEW" /> <action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" /> <category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="lbry" /> <data android:scheme="lbry" />
</intent-filter> </intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" android:host="open.lbry.com"/>
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity> </activity>
<activity <activity
Binary file not shown.
@@ -15,6 +15,7 @@ import androidx.appcompat.app.AppCompatActivity;
import androidx.core.text.HtmlCompat; import androidx.core.text.HtmlCompat;
import androidx.preference.PreferenceManager; import androidx.preference.PreferenceManager;
import io.lbry.browser.exceptions.AuthTokenInvalidatedException;
import io.lbry.browser.utils.Helper; import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry; import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics; import io.lbry.browser.utils.LbryAnalytics;
@@ -139,7 +140,11 @@ public class FirstRunActivity extends AppCompatActivity {
this.context = context; this.context = context;
} }
protected Void doInBackground(Void... params) { protected Void doInBackground(Void... params) {
Lbryio.authenticate(context); try {
Lbryio.authenticate(context);
} catch (AuthTokenInvalidatedException ex) {
// pass
}
return null; return null;
} }
} }
@@ -6,6 +6,7 @@ import android.app.PendingIntent;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager; import android.media.RingtoneManager;
import android.net.Uri; import android.net.Uri;
import android.os.Build; import android.os.Build;
@@ -20,19 +21,22 @@ import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage; import com.google.firebase.messaging.RemoteMessage;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryAnalytics; import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.lbrysdk.LbrynetService;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class LbrynetMessagingService extends FirebaseMessagingService { public class LbrynetMessagingService extends FirebaseMessagingService {
public static final String ACTION_NOTIFICATION_RECEIVED = "io.lbry.browser.Broadcast.NotificationReceived";
private static final String TAG = "LbrynetMessagingService"; private static final String TAG = "LbrynetMessagingService";
private static final String NOTIFICATION_CHANNEL_ID = "io.lbry.browser.LBRY_ENGAGEMENT_CHANNEL"; private static final String NOTIFICATION_CHANNEL_ID = "io.lbry.browser.LBRY_ENGAGEMENT_CHANNEL";
private static final String TYPE_COMMENT = "comment";
private static final String TYPE_SUBSCRIPTION = "subscription"; private static final String TYPE_SUBSCRIPTION = "subscription";
private static final String TYPE_REWARD = "reward"; private static final String TYPE_REWARD = "reward";
private static final String TYPE_INTERESTS = "interests"; private static final String TYPE_INTERESTS = "interests";
@@ -52,10 +56,12 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
String title = payload.get("title"); String title = payload.get("title");
String body = payload.get("body"); String body = payload.get("body");
String name = payload.get("name"); // notification name String name = payload.get("name"); // notification name
String contentTitle = payload.get("content_title"); String hash = payload.get("hash"); // comment hash
String channelUrl = payload.get("channel_url");
//String publishTime = payload.get("publish_time"); Log.d(TAG, "Received notification message with payload");
String publishTime = null; for (Map.Entry<String, String> entry : payload.entrySet()) {
Log.d(TAG, String.format("%s = %s", entry.getKey(), entry.getValue()));
}
if (type != null && getEnabledTypes().indexOf(type) > -1 && body != null && body.trim().length() > 0) { if (type != null && getEnabledTypes().indexOf(type) > -1 && body != null && body.trim().length() > 0) {
// only log the receive event for valid notifications received // only log the receive event for valid notifications received
@@ -65,7 +71,34 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
firebaseAnalytics.logEvent(LbryAnalytics.EVENT_LBRY_NOTIFICATION_RECEIVE, bundle); firebaseAnalytics.logEvent(LbryAnalytics.EVENT_LBRY_NOTIFICATION_RECEIVE, bundle);
} }
sendNotification(title, body, type, url, name, contentTitle, channelUrl, publishTime); if (!Helper.isNullOrEmpty(hash)) {
url = String.format("%s?comment_hash=%s", url, hash);
}
sendNotification(title, body, type, url, name);
}
// persist the notification data
try {
DatabaseHelper helper = DatabaseHelper.getInstance();
SQLiteDatabase db = helper.getWritableDatabase();
LbryNotification lnotification = new LbryNotification();
lnotification.setTitle(title);
lnotification.setDescription(body);
lnotification.setTargetUrl(url);
lnotification.setTimestamp(new Date());
DatabaseHelper.createOrUpdateNotification(lnotification, db);
// send a broadcast
Intent intent = new Intent(ACTION_NOTIFICATION_RECEIVED);
intent.putExtra("title", title);
intent.putExtra("body", body);
intent.putExtra("url", url);
intent.putExtra("timestamp", lnotification.getTimestamp().getTime());
sendBroadcast(intent);
} catch (Exception ex) {
// don't fail if any error occurs while saving a notification
Log.e(TAG, "could not save notification", ex);
} }
} }
} }
@@ -97,8 +130,7 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
* *
* @param messageBody FCM message body received. * @param messageBody FCM message body received.
*/ */
private void sendNotification(String title, String messageBody, String type, String url, String name, private void sendNotification(String title, String messageBody, String type, String url, String name) {
String contentTitle, String channelUrl, String publishTime) {
//Intent intent = new Intent(this, MainActivity.class); //Intent intent = new Intent(this, MainActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (url == null) { if (url == null) {
@@ -143,6 +175,9 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
List<String> enabledTypes = new ArrayList<String>(); List<String> enabledTypes = new ArrayList<String>();
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_COMMENTS, true)) {
enabledTypes.add(TYPE_COMMENT);
}
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_SUBSCRIPTIONS, true)) { if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_SUBSCRIPTIONS, true)) {
enabledTypes.add(TYPE_SUBSCRIPTION); enabledTypes.add(TYPE_SUBSCRIPTION);
} }
@@ -1,5 +1,6 @@
package io.lbry.browser; package io.lbry.browser;
import android.annotation.SuppressLint;
import android.app.Activity; import android.app.Activity;
import android.app.ActivityManager; import android.app.ActivityManager;
import android.app.Notification; import android.app.Notification;
@@ -7,6 +8,7 @@ import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.app.PictureInPictureParams; import android.app.PictureInPictureParams;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
@@ -16,6 +18,7 @@ import android.content.pm.PackageManager;
import android.content.res.Configuration; import android.content.res.Configuration;
import android.content.res.TypedArray; import android.content.res.TypedArray;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Color; import android.graphics.Color;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.net.Uri; import android.net.Uri;
@@ -44,9 +47,21 @@ import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.ConsumeParams;
import com.android.billingclient.api.ConsumeResponseListener;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer; import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ext.cast.CastPlayer; import com.google.android.exoplayer2.ext.cast.CastPlayer;
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector; import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector;
import com.google.android.exoplayer2.ui.PlayerNotificationManager;
import com.google.android.exoplayer2.ui.PlayerView; import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.cache.Cache; import com.google.android.exoplayer2.upstream.cache.Cache;
import com.google.android.gms.cast.framework.CastContext; import com.google.android.gms.cast.framework.CastContext;
@@ -56,6 +71,7 @@ import com.google.android.material.snackbar.Snackbar;
import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult; import com.google.firebase.iid.InstanceIdResult;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.ActionBarDrawerToggle;
@@ -106,9 +122,11 @@ import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
import io.lbry.browser.adapter.NavigationMenuAdapter; import io.lbry.browser.adapter.NavigationMenuAdapter;
import io.lbry.browser.adapter.NotificationListAdapter;
import io.lbry.browser.adapter.UrlSuggestionListAdapter; import io.lbry.browser.adapter.UrlSuggestionListAdapter;
import io.lbry.browser.data.DatabaseHelper; import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.dialog.ContentScopeDialogFragment; import io.lbry.browser.dialog.ContentScopeDialogFragment;
import io.lbry.browser.exceptions.AuthTokenInvalidatedException;
import io.lbry.browser.exceptions.LbryUriException; import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.listener.CameraPermissionListener; import io.lbry.browser.listener.CameraPermissionListener;
import io.lbry.browser.listener.DownloadActionListener; import io.lbry.browser.listener.DownloadActionListener;
@@ -127,16 +145,22 @@ import io.lbry.browser.model.Tag;
import io.lbry.browser.model.UrlSuggestion; import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.model.WalletBalance; import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.model.WalletSync; import io.lbry.browser.model.WalletSync;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.model.lbryinc.Reward; import io.lbry.browser.model.lbryinc.Reward;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.model.lbryinc.Subscription; import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.tasks.GenericTaskHandler; import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.tasks.claim.ClaimListResultHandler; import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask; import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.tasks.lbryinc.AndroidPurchaseTask;
import io.lbry.browser.tasks.lbryinc.ClaimRewardTask; import io.lbry.browser.tasks.lbryinc.ClaimRewardTask;
import io.lbry.browser.tasks.lbryinc.FetchRewardsTask; import io.lbry.browser.tasks.lbryinc.FetchRewardsTask;
import io.lbry.browser.tasks.LighthouseAutoCompleteTask; import io.lbry.browser.tasks.LighthouseAutoCompleteTask;
import io.lbry.browser.tasks.MergeSubscriptionsTask; import io.lbry.browser.tasks.MergeSubscriptionsTask;
import io.lbry.browser.tasks.claim.ResolveTask; import io.lbry.browser.tasks.claim.ResolveTask;
import io.lbry.browser.tasks.lbryinc.NotificationListTask;
import io.lbry.browser.tasks.lbryinc.NotificationUpdateTask;
import io.lbry.browser.tasks.localdata.FetchRecentUrlHistoryTask; import io.lbry.browser.tasks.localdata.FetchRecentUrlHistoryTask;
import io.lbry.browser.tasks.wallet.DefaultSyncTaskHandler; import io.lbry.browser.tasks.wallet.DefaultSyncTaskHandler;
import io.lbry.browser.tasks.wallet.LoadSharedUserStateTask; import io.lbry.browser.tasks.wallet.LoadSharedUserStateTask;
@@ -178,7 +202,13 @@ import lombok.Setter;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
public class MainActivity extends AppCompatActivity implements SdkStatusListener { public class MainActivity extends AppCompatActivity implements SdkStatusListener {
private static final String CHANNEL_ID_PLAYBACK = "io.lbry.browser.LBRY_PLAYBACK_CHANNEL";
private static final int PLAYBACK_NOTIFICATION_ID = 3;
private static final String SPECIAL_URL_PREFIX = "lbry://?";
private static final int REMOTE_NOTIFICATION_REFRESH_TTL = 300000; // 5 minutes
public static final String SKU_SKIP = "lbryskip";
private Date remoteNotifcationsLastLoaded;
private Map<String, Class> specialRouteFragmentClassMap; private Map<String, Class> specialRouteFragmentClassMap;
@Getter @Getter
private boolean inPictureInPictureMode; private boolean inPictureInPictureMode;
@@ -199,11 +229,14 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
public static boolean startingShareActivity = false; public static boolean startingShareActivity = false;
public static boolean startingPermissionRequest = false; public static boolean startingPermissionRequest = false;
public static boolean startingSignInFlowActivity = false; public static boolean startingSignInFlowActivity = false;
private BillingClient billingClient;
@Getter @Getter
private boolean enteringPIPMode = false; private boolean enteringPIPMode = false;
private boolean fullSyncInProgress = false; private boolean fullSyncInProgress = false;
private int queuedSyncCount = 0; private int queuedSyncCount = 0;
private String cameraOutputFilename; private String cameraOutputFilename;
private Bitmap nowPlayingClaimBitmap;
@Setter @Setter
private BackPressInterceptor backPressInterceptor; private BackPressInterceptor backPressInterceptor;
@@ -211,6 +244,8 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
@Getter @Getter
private String firebaseMessagingToken; private String firebaseMessagingToken;
private NotificationListAdapter notificationListAdapter;
private Map<String, Fragment> openNavFragments; private Map<String, Fragment> openNavFragments;
private static final Map<Class, Integer> fragmentClassNavIdMap = new HashMap<>(); private static final Map<Class, Integer> fragmentClassNavIdMap = new HashMap<>();
static { static {
@@ -265,9 +300,11 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
public static final String ACTION_SAVE_SHARED_USER_STATE = "io.lbry.browser.Broadcast.SaveSharedUserState"; public static final String ACTION_SAVE_SHARED_USER_STATE = "io.lbry.browser.Broadcast.SaveSharedUserState";
// preference keys // preference keys
public static final String PREFERENCE_KEY_BACKGROUND_PLAYBACK = "io.lbry.browser.preference.userinterface.BackgroundPlayback";
public static final String PREFERENCE_KEY_DARK_MODE = "io.lbry.browser.preference.userinterface.DarkMode"; public static final String PREFERENCE_KEY_DARK_MODE = "io.lbry.browser.preference.userinterface.DarkMode";
public static final String PREFERENCE_KEY_SHOW_MATURE_CONTENT = "io.lbry.browser.preference.userinterface.ShowMatureContent"; public static final String PREFERENCE_KEY_SHOW_MATURE_CONTENT = "io.lbry.browser.preference.userinterface.ShowMatureContent";
public static final String PREFERENCE_KEY_SHOW_URL_SUGGESTIONS = "io.lbry.browser.preference.userinterface.UrlSuggestions"; public static final String PREFERENCE_KEY_SHOW_URL_SUGGESTIONS = "io.lbry.browser.preference.userinterface.UrlSuggestions";
public static final String PREFERENCE_KEY_NOTIFICATION_COMMENTS = "io.lbry.browser.preference.notifications.Comments";
public static final String PREFERENCE_KEY_NOTIFICATION_SUBSCRIPTIONS = "io.lbry.browser.preference.notifications.Subscriptions"; public static final String PREFERENCE_KEY_NOTIFICATION_SUBSCRIPTIONS = "io.lbry.browser.preference.notifications.Subscriptions";
public static final String PREFERENCE_KEY_NOTIFICATION_REWARDS = "io.lbry.browser.preference.notifications.Rewards"; public static final String PREFERENCE_KEY_NOTIFICATION_REWARDS = "io.lbry.browser.preference.notifications.Rewards";
public static final String PREFERENCE_KEY_NOTIFICATION_CONTENT_INTERESTS = "io.lbry.browser.preference.notifications.ContentInterests"; public static final String PREFERENCE_KEY_NOTIFICATION_CONTENT_INTERESTS = "io.lbry.browser.preference.notifications.ContentInterests";
@@ -281,6 +318,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
public static final String PREFERENCE_KEY_INTERNAL_WALLET_RECEIVE_ADDRESS = "io.lbry.browser.preference.internal.WalletReceiveAddress"; public static final String PREFERENCE_KEY_INTERNAL_WALLET_RECEIVE_ADDRESS = "io.lbry.browser.preference.internal.WalletReceiveAddress";
public static final String PREFERENCE_KEY_INTERNAL_REWARDS_NOT_INTERESTED = "io.lbry.browser.preference.internal.RewardsNotInterested"; public static final String PREFERENCE_KEY_INTERNAL_REWARDS_NOT_INTERESTED = "io.lbry.browser.preference.internal.RewardsNotInterested";
public static final String PREFERENCE_KEY_INTERNAL_NEW_ANDROID_REWARD_CLAIMED = "io.lbry.browser.preference.internal.NewAndroidRewardClaimed"; public static final String PREFERENCE_KEY_INTERNAL_NEW_ANDROID_REWARD_CLAIMED = "io.lbry.browser.preference.internal.NewAndroidRewardClaimed";
public static final String PREFERENCE_KEY_INTERNAL_INITIAL_SUBSCRIPTION_MERGE_DONE = "io.lbry.browser.preference.internal.InitialSubscriptionMergeDone";
public static final String PREFERENCE_KEY_INTERNAL_FIRST_RUN_COMPLETED = "io.lbry.browser.preference.internal.FirstRunCompleted"; public static final String PREFERENCE_KEY_INTERNAL_FIRST_RUN_COMPLETED = "io.lbry.browser.preference.internal.FirstRunCompleted";
public static final String PREFERENCE_KEY_INTERNAL_FIRST_AUTH_COMPLETED = "io.lbry.browser.preference.internal.FirstAuthCompleted"; public static final String PREFERENCE_KEY_INTERNAL_FIRST_AUTH_COMPLETED = "io.lbry.browser.preference.internal.FirstAuthCompleted";
@@ -292,7 +330,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
public static final String SECURE_VALUE_KEY_SAVED_PASSWORD = "io.lbry.browser.PX"; public static final String SECURE_VALUE_KEY_SAVED_PASSWORD = "io.lbry.browser.PX";
public static final String SECURE_VALUE_FIRST_RUN_PASSWORD = "firstRunPassword"; public static final String SECURE_VALUE_FIRST_RUN_PASSWORD = "firstRunPassword";
private static final String TAG = "io.lbry.browser.Main"; private static final String TAG = "LbryMain";
private NavigationMenuAdapter navMenuAdapter; private NavigationMenuAdapter navMenuAdapter;
private UrlSuggestionListAdapter urlSuggestionListAdapter; private UrlSuggestionListAdapter urlSuggestionListAdapter;
@@ -306,6 +344,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
private static boolean appStarted; private static boolean appStarted;
private boolean serviceRunning; private boolean serviceRunning;
private CheckSdkReadyTask checkSdkReadyTask; private CheckSdkReadyTask checkSdkReadyTask;
private PlayerNotificationManager playerNotificationManager;
private MediaSessionCompat mediaSession; private MediaSessionCompat mediaSession;
private boolean receivedStopService; private boolean receivedStopService;
private ActionBarDrawerToggle toggle; private ActionBarDrawerToggle toggle;
@@ -345,11 +384,6 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
private static final int STARTUP_STAGE_SUBSCRIPTIONS_LOADED = 6; private static final int STARTUP_STAGE_SUBSCRIPTIONS_LOADED = 6;
private static final int STARTUP_STAGE_SUBSCRIPTIONS_RESOLVED = 7; private static final int STARTUP_STAGE_SUBSCRIPTIONS_RESOLVED = 7;
public boolean isDarkMode() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
return sp.getBoolean(PREFERENCE_KEY_DARK_MODE, false);
}
@Override @Override
protected void onCreate(Bundle savedInstanceState) { protected void onCreate(Bundle savedInstanceState) {
// workaround to fix dark theme because https://issuetracker.google.com/issues/37124582 // workaround to fix dark theme because https://issuetracker.google.com/issues/37124582
@@ -391,6 +425,27 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
Toolbar toolbar = findViewById(R.id.toolbar); Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
// setup the billing client in main activity (to handle cases where the verification purchase flow may have been interrupted)
billingClient = BillingClient.newBuilder(this)
.setListener(new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> purchases) {
int responseCode = billingResult.getResponseCode();
if (responseCode == BillingClient.BillingResponseCode.OK && purchases != null)
{
for (Purchase purchase : purchases) {
handlePurchase(purchase);
}
}
}
})
.enablePendingPurchases()
.build();
establishBillingClientConnection();
playerNotificationManager = new PlayerNotificationManager(
this, LbrynetService.NOTIFICATION_CHANNEL_ID, PLAYBACK_NOTIFICATION_ID, new PlayerNotificationDescriptionAdapter());
// TODO: Check Google Play Services availability // TODO: Check Google Play Services availability
// castContext = CastContext.getSharedInstance(this); // castContext = CastContext.getSharedInstance(this);
@@ -425,6 +480,8 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
// setup uri bar // setup uri bar
setupUriBar(); setupUriBar();
initNotificationsPage();
loadUnreadNotificationsCount();
// other // other
pendingSyncSetQueue = new ArrayList<>(); pendingSyncSetQueue = new ArrayList<>();
@@ -461,6 +518,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
public void onDrawerSlide(View drawerView, float slideOffset) { public void onDrawerSlide(View drawerView, float slideOffset) {
if (slideOffset != 0) { if (slideOffset != 0) {
clearWunderbarFocus(findViewById(R.id.wunderbar)); clearWunderbarFocus(findViewById(R.id.wunderbar));
hideNotifications();
} }
super.onDrawerSlide(drawerView, slideOffset); super.onDrawerSlide(drawerView, slideOffset);
} }
@@ -483,14 +541,29 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
stopExoplayer(); stopExoplayer();
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
nowPlayingClaim = null; nowPlayingClaim = null;
nowPlayingClaimUrl = null;
nowPlayingClaimBitmap = null;
findViewById(R.id.global_now_playing_card).setVisibility(View.GONE); findViewById(R.id.global_now_playing_card).setVisibility(View.GONE);
} }
}); });
findViewById(R.id.wunderbar_notifications).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
View container = findViewById(R.id.notifications_container);
if (container.getVisibility() != View.VISIBLE) {
showNotifications();
} else {
hideNotifications();
}
}
});
findViewById(R.id.global_now_playing_card).setOnClickListener(new View.OnClickListener() { findViewById(R.id.global_now_playing_card).setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
if (nowPlayingClaim != null && !Helper.isNullOrEmpty(nowPlayingClaimUrl)) { if (nowPlayingClaim != null && !Helper.isNullOrEmpty(nowPlayingClaimUrl)) {
hideNotifications();
openFileUrl(nowPlayingClaimUrl); openFileUrl(nowPlayingClaimUrl);
} }
} }
@@ -528,6 +601,21 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
}); });
} }
public boolean isDarkMode() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
return sp.getBoolean(PREFERENCE_KEY_DARK_MODE, false);
}
public boolean isBackgroundPlaybackEnabled() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
return sp.getBoolean(PREFERENCE_KEY_BACKGROUND_PLAYBACK, true);
}
public boolean initialSubscriptionMergeDone() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
return sp.getBoolean(PREFERENCE_KEY_INTERNAL_INITIAL_SUBSCRIPTION_MERGE_DONE, false);
}
private void initSpecialRouteMap() { private void initSpecialRouteMap() {
specialRouteFragmentClassMap = new HashMap<>(); specialRouteFragmentClassMap = new HashMap<>();
specialRouteFragmentClassMap.put("about", AboutFragment.class); specialRouteFragmentClassMap.put("about", AboutFragment.class);
@@ -549,6 +637,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
protected void onNewIntent(Intent intent) { protected void onNewIntent(Intent intent) {
super.onNewIntent(intent); super.onNewIntent(intent);
checkSendToIntent(intent);
checkUrlIntent(intent); checkUrlIntent(intent);
checkNotificationOpenIntent(intent); checkNotificationOpenIntent(intent);
} }
@@ -685,8 +774,9 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
} }
private void openSelectedMenuItem() { private void openSelectedMenuItem() {
hideNotifications();
switch (selectedMenuItemId) { switch (selectedMenuItemId) {
// TODO: reverse map lookup for class?
case NavMenuItem.ID_ITEM_FOLLOWING: case NavMenuItem.ID_ITEM_FOLLOWING:
openFragment(FollowingFragment.class, true, NavMenuItem.ID_ITEM_FOLLOWING); openFragment(FollowingFragment.class, true, NavMenuItem.ID_ITEM_FOLLOWING);
break; break;
@@ -746,13 +836,22 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
public void openPublishesOnSuccessfulPublish() { public void openPublishesOnSuccessfulPublish() {
// close publish form // close publish form
try { runOnUiThread(new Runnable() {
getSupportFragmentManager().popBackStack(); @Override
openFragment(PublishesFragment.class, true, NavMenuItem.ID_ITEM_PUBLISHES); public void run() {
} catch (IllegalStateException ex) { try {
// pass getSupportFragmentManager().popBackStack();
onBackPressed(); openFragment(PublishesFragment.class, true, NavMenuItem.ID_ITEM_PUBLISHES);
} } catch (IllegalStateException ex) {
// pass
try {
onBackPressed();
} catch (IllegalStateException iex) {
// if this fails on some devices. what's the solution?
}
}
}
});
} }
public void openPublishForm(Claim claim) { public void openPublishForm(Claim claim) {
@@ -794,6 +893,27 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
openFragment(FileViewFragment.class, true, NavMenuItem.ID_ITEM_FOLLOWING, params); openFragment(FileViewFragment.class, true, NavMenuItem.ID_ITEM_FOLLOWING, params);
} }
private void openSpecialUrl(String url) {
String specialPath = url.substring(8).toLowerCase();
if (specialRouteFragmentClassMap.containsKey(specialPath)) {
Class fragmentClass = specialRouteFragmentClassMap.get(specialPath);
if (fragmentClassNavIdMap.containsKey(fragmentClass)) {
openFragment(
specialRouteFragmentClassMap.get(specialPath),
true,
fragmentClassNavIdMap.get(fragmentClass),
null
);
}
}
}
public void openSendTo(String path) {
Map<String, Object> params = new HashMap<>();
params.put("directFilePath", path);
openFragment(PublishFormFragment.class, true, NavMenuItem.ID_ITEM_NEW_PUBLISH, params);
}
public void openFileClaim(Claim claim) { public void openFileClaim(Claim claim) {
Map<String, Object> params = new HashMap<>(); Map<String, Object> params = new HashMap<>();
params.put("claimId", claim.getClaimId()); params.put("claimId", claim.getClaimId());
@@ -829,7 +949,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
findViewById(R.id.content_main).setVisibility(View.GONE); findViewById(R.id.content_main).setVisibility(View.GONE);
findViewById(R.id.floating_balance_main_container).setVisibility(View.GONE); findViewById(R.id.floating_balance_main_container).setVisibility(View.GONE);
findViewById(R.id.global_now_playing_card).setVisibility(View.GONE); findViewById(R.id.global_now_playing_card).setVisibility(View.GONE);
findViewById(R.id.global_sdk_initializing_status).setVisibility(View.GONE); //findViewById(R.id.global_sdk_initializing_status).setVisibility(View.GONE);
findViewById(R.id.app_bar_main_container).setFitsSystemWindows(true); findViewById(R.id.app_bar_main_container).setFitsSystemWindows(true);
hideActionBar(); hideActionBar();
@@ -837,10 +957,11 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
listener.onEnterPIPMode(); listener.onEnterPIPMode();
} }
View pipPlayerContainer = findViewById(R.id.pip_player_container);
PlayerView pipPlayer = findViewById(R.id.pip_player); PlayerView pipPlayer = findViewById(R.id.pip_player);
pipPlayer.setVisibility(View.VISIBLE);
pipPlayer.setPlayer(appPlayer); pipPlayer.setPlayer(appPlayer);
pipPlayer.setUseController(false); pipPlayer.setUseController(false);
pipPlayerContainer.setVisibility(View.VISIBLE);
playerReassigned = true; playerReassigned = true;
} }
private void renderFullMode() { private void renderFullMode() {
@@ -864,16 +985,17 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
if (!(fragment instanceof FileViewFragment) && !inFullscreenMode) { if (!(fragment instanceof FileViewFragment) && !inFullscreenMode) {
findViewById(R.id.global_now_playing_card).setVisibility(View.VISIBLE); findViewById(R.id.global_now_playing_card).setVisibility(View.VISIBLE);
} }
if (!Lbry.SDK_READY && !inFullscreenMode) { /*if (!Lbry.SDK_READY && !inFullscreenMode) {
findViewById(R.id.global_sdk_initializing_status).setVisibility(View.VISIBLE); findViewById(R.id.global_sdk_initializing_status).setVisibility(View.VISIBLE);
} }*/
for (PIPModeListener listener : pipModeListeners) { for (PIPModeListener listener : pipModeListeners) {
listener.onExitPIPMode(); listener.onExitPIPMode();
} }
View pipPlayerContainer = findViewById(R.id.pip_player_container);
PlayerView pipPlayer = findViewById(R.id.pip_player); PlayerView pipPlayer = findViewById(R.id.pip_player);
pipPlayer.setVisibility(View.INVISIBLE);
pipPlayer.setPlayer(null); pipPlayer.setPlayer(null);
pipPlayerContainer.setVisibility(View.INVISIBLE);
playerReassigned = true; playerReassigned = true;
} }
@@ -887,12 +1009,16 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
if (dbHelper != null) { if (dbHelper != null) {
dbHelper.close(); dbHelper.close();
} }
if (mediaSession != null) { if (mediaSession != null && !isBackgroundPlaybackEnabled()) {
mediaSession.release(); mediaSession.release();
} }
stopExoplayer(); if (!isBackgroundPlaybackEnabled()) {
nowPlayingClaim = null; playerNotificationManager.setPlayer(null);
nowPlayingClaimUrl = null; stopExoplayer();
nowPlayingClaim = null;
nowPlayingClaimUrl = null;
nowPlayingClaimBitmap = null;
}
appStarted = false; appStarted = false;
if (!keepSdkBackground()) { if (!keepSdkBackground()) {
@@ -948,6 +1074,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
@Override @Override
protected void onResume() { protected void onResume() {
super.onResume(); super.onResume();
checkPurchases();
enteringPIPMode = false; enteringPIPMode = false;
applyNavbarSigninPadding(); applyNavbarSigninPadding();
@@ -958,18 +1085,45 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
serviceRunning = isServiceRunning(this, LbrynetService.class); serviceRunning = isServiceRunning(this, LbrynetService.class);
if (!serviceRunning) { if (!serviceRunning) {
Lbry.SDK_READY = false; Lbry.SDK_READY = false;
findViewById(R.id.global_sdk_initializing_status).setVisibility(View.VISIBLE); //findViewById(R.id.global_sdk_initializing_status).setVisibility(View.VISIBLE);
ServiceHelper.start(this, "", LbrynetService.class, "lbrynetservice"); ServiceHelper.start(this, "", LbrynetService.class, "lbrynetservice");
} }
checkSdkReady(); checkSdkReady();
showSignedInUser(); showSignedInUser();
checkPendingOpens(); checkPendingOpens();
if (Lbry.SDK_READY) { /*if (Lbry.SDK_READY) {
findViewById(R.id.global_sdk_initializing_status).setVisibility(View.GONE); findViewById(R.id.global_sdk_initializing_status).setVisibility(View.GONE);
}*/
}
private void checkPurchases() {
if (billingClient != null) {
Purchase.PurchasesResult result = billingClient.queryPurchases(BillingClient.SkuType.INAPP);
if (result.getPurchasesList() != null) {
for (Purchase purchase : result.getPurchasesList()) {
handlePurchase(purchase);
}
}
} }
} }
private void handlePurchase(Purchase purchase) {
handleBillingPurchase(purchase, billingClient, MainActivity.this, null, new RewardVerifiedHandler() {
@Override
public void onSuccess(RewardVerified rewardVerified) {
if (Lbryio.currentUser != null) {
Lbryio.currentUser.setRewardApproved(rewardVerified.isRewardApproved());
}
}
@Override
public void onError(Exception error) {
// pass
}
});
}
private void checkPendingOpens() { private void checkPendingOpens() {
if (pendingFollowingReload) { if (pendingFollowingReload) {
loadFollowingContent(); loadFollowingContent();
@@ -990,7 +1144,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
@Override @Override
protected void onPause() { protected void onPause() {
if (!enteringPIPMode && !inPictureInPictureMode && appPlayer != null) { if (!enteringPIPMode && !inPictureInPictureMode && appPlayer != null && !isBackgroundPlaybackEnabled()) {
appPlayer.setPlayWhenReady(false); appPlayer.setPlayWhenReady(false);
} }
super.onPause(); super.onPause();
@@ -1014,7 +1168,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
View container = findViewById(R.id.url_suggestions_container); View container = findViewById(R.id.url_suggestions_container);
View closeIcon = findViewById(R.id.wunderbar_close); View closeIcon = findViewById(R.id.wunderbar_close);
EditText wunderbar = findViewById(R.id.wunderbar); EditText wunderbar = findViewById(R.id.wunderbar);
wunderbar.setPadding(0, 0, visible ? getScaledValue(36) : 0, 0); //wunderbar.setPadding(0, 0, visible ? getScaledValue(36) : 0, 0);
container.setVisibility(visible ? View.VISIBLE : View.GONE); container.setVisibility(visible ? View.VISIBLE : View.GONE);
closeIcon.setVisibility(visible ? View.VISIBLE : View.GONE); closeIcon.setVisibility(visible ? View.VISIBLE : View.GONE);
@@ -1049,8 +1203,13 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
@Override @Override
public void onFocusChange(View view, boolean hasFocus) { public void onFocusChange(View view, boolean hasFocus) {
if (hasFocus) { if (hasFocus) {
hideNotifications();
findViewById(R.id.wunderbar_notifications).setVisibility(View.INVISIBLE);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, 0); imm.showSoftInput(view, 0);
} else {
findViewById(R.id.wunderbar_notifications).setVisibility(View.VISIBLE);
} }
if (canShowUrlSuggestions()) { if (canShowUrlSuggestions()) {
@@ -1398,7 +1557,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
if (actionBar != null) { if (actionBar != null) {
actionBar.hide(); actionBar.hide();
} }
findViewById(R.id.global_sdk_initializing_status).setVisibility(View.GONE); //findViewById(R.id.global_sdk_initializing_status).setVisibility(View.GONE);
findViewById(R.id.app_bar_main_container).setFitsSystemWindows(false); findViewById(R.id.app_bar_main_container).setFitsSystemWindows(false);
lockDrawer(); lockDrawer();
@@ -1429,9 +1588,9 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
appBarMainContainer.setFitsSystemWindows(true); appBarMainContainer.setFitsSystemWindows(true);
decorView.setSystemUiVisibility(flags); decorView.setSystemUiVisibility(flags);
if (!Lbry.SDK_READY) { /*if (!Lbry.SDK_READY) {
findViewById(R.id.global_sdk_initializing_status).setVisibility(View.VISIBLE); findViewById(R.id.global_sdk_initializing_status).setVisibility(View.VISIBLE);
} }*/
showFloatingWalletBalance(); showFloatingWalletBalance();
ActionBar actionBar = getSupportActionBar(); ActionBar actionBar = getSupportActionBar();
if (actionBar != null) { if (actionBar != null) {
@@ -1520,9 +1679,8 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
checkSyncedWallet(); checkSyncedWallet();
} }
findViewById(R.id.global_sdk_initializing_status).setVisibility(View.GONE); //findViewById(R.id.global_sdk_initializing_status).setVisibility(View.GONE);
syncWalletAndLoadPreferences();
scheduleWalletBalanceUpdate(); scheduleWalletBalanceUpdate();
scheduleWalletSyncTask(); scheduleWalletSyncTask();
fetchOwnChannels(); fetchOwnChannels();
@@ -1581,6 +1739,71 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
mediaSession.setActive(true); mediaSession.setActive(true);
} }
public void initNotificationsPage() {
findViewById(R.id.notification_list_empty_container).setVisibility(View.VISIBLE);
RecyclerView notificationsList = findViewById(R.id.notifications_list);
LinearLayoutManager llm = new LinearLayoutManager(this);
notificationsList.setLayoutManager(llm);
}
public void initPlaybackNotification() {
if (isBackgroundPlaybackEnabled()) {
playerNotificationManager.setPlayer(MainActivity.appPlayer);
if (mediaSession != null) {
playerNotificationManager.setMediaSessionToken(mediaSession.getSessionToken());
}
}
}
private class PlayerNotificationDescriptionAdapter implements PlayerNotificationManager.MediaDescriptionAdapter {
@Override
public CharSequence getCurrentContentTitle(Player player) {
return nowPlayingClaim != null ? nowPlayingClaim.getTitle() : "";
}
@Nullable
@Override
public PendingIntent createCurrentContentIntent(Player player) {
if (nowPlayingClaimUrl != null) {
Intent launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(nowPlayingClaimUrl));
launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(MainActivity.this, 0, launchIntent, 0);
return intent;
}
return null;
}
@Nullable
@Override
public CharSequence getCurrentContentText(Player player) {
return nowPlayingClaim != null && nowPlayingClaim.getSigningChannel() != null ? nowPlayingClaim.getSigningChannel().getTitleOrName() : null;
}
@Nullable
@Override
public Bitmap getCurrentLargeIcon(Player player, PlayerNotificationManager.BitmapCallback callback) {
if (nowPlayingClaimBitmap == null &&
nowPlayingClaim != null &&
!Helper.isNullOrEmpty(nowPlayingClaim.getThumbnailUrl())) {
Glide.with(getApplicationContext()).asBitmap().load(nowPlayingClaim.getThumbnailUrl()).into(new CustomTarget<Bitmap>() {
@Override
public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
nowPlayingClaimBitmap = resource;
callback.onBitmap(resource);
}
@Override
public void onLoadCleared(@Nullable Drawable placeholder) {
}
});
}
return nowPlayingClaimBitmap;
}
}
public void showFloatingWalletBalance() { public void showFloatingWalletBalance() {
findViewById(R.id.floating_balance_main_container).setVisibility(View.VISIBLE); findViewById(R.id.floating_balance_main_container).setVisibility(View.VISIBLE);
} }
@@ -1679,17 +1902,25 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
// reload subscriptions if wallet fragment is FollowingFragment // reload subscriptions if wallet fragment is FollowingFragment
//openNavFragments.get //openNavFragments.get
MergeSubscriptionsTask mergeTask = new MergeSubscriptionsTask( MergeSubscriptionsTask mergeTask = new MergeSubscriptionsTask(
subscriptions, MainActivity.this, new MergeSubscriptionsTask.MergeSubscriptionsHandler() { subscriptions,
initialSubscriptionMergeDone(),
MainActivity.this, new MergeSubscriptionsTask.MergeSubscriptionsHandler() {
@Override @Override
public void onSuccess(List<Subscription> subscriptions, List<Subscription> diff) { public void onSuccess(List<Subscription> subscriptions, List<Subscription> diff) {
Lbryio.subscriptions = new ArrayList<>(subscriptions); Lbryio.subscriptions = new ArrayList<>(subscriptions);
if (diff != null && diff.size() > 0) { if (diff != null && diff.size() > 0) {
saveSharedUserState(); saveSharedUserState();
} }
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
sp.edit().putBoolean(PREFERENCE_KEY_INTERNAL_INITIAL_SUBSCRIPTION_MERGE_DONE, true).apply();
Lbryio.cacheResolvedSubscriptions.clear();
for (Fragment fragment : openNavFragments.values()) { for (Fragment fragment : openNavFragments.values()) {
if (fragment instanceof FollowingFragment) { if (fragment instanceof FollowingFragment) {
// reload local subscriptions // reload local subscriptions
((FollowingFragment) fragment).fetchLoadedSubscriptions(true); FollowingFragment followingFragment = (FollowingFragment) fragment;
followingFragment.fetchLoadedSubscriptions(true);
} }
} }
} }
@@ -1827,7 +2058,6 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
public void onSyncGetSuccess(WalletSync walletSync) { public void onSyncGetSuccess(WalletSync walletSync) {
Lbryio.lastWalletSync = walletSync; Lbryio.lastWalletSync = walletSync;
Lbryio.lastRemoteHash = walletSync.getHash(); Lbryio.lastRemoteHash = walletSync.getHash();
loadSharedUserState();
} }
@Override @Override
@@ -1887,6 +2117,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
intentFilter.addAction(ACTION_OPEN_REWARDS_PAGE); intentFilter.addAction(ACTION_OPEN_REWARDS_PAGE);
intentFilter.addAction(ACTION_PUBLISH_SUCCESSFUL); intentFilter.addAction(ACTION_PUBLISH_SUCCESSFUL);
intentFilter.addAction(ACTION_SAVE_SHARED_USER_STATE); intentFilter.addAction(ACTION_SAVE_SHARED_USER_STATE);
intentFilter.addAction(LbrynetMessagingService.ACTION_NOTIFICATION_RECEIVED);
requestsReceiver = new BroadcastReceiver() { requestsReceiver = new BroadcastReceiver() {
@Override @Override
public void onReceive(Context context, Intent intent) { public void onReceive(Context context, Intent intent) {
@@ -1907,9 +2138,15 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
saveSharedUserState(); saveSharedUserState();
} else if (ACTION_PUBLISH_SUCCESSFUL.equalsIgnoreCase(action)) { } else if (ACTION_PUBLISH_SUCCESSFUL.equalsIgnoreCase(action)) {
openPublishesOnSuccessfulPublish(); openPublishesOnSuccessfulPublish();
} else if (LbrynetMessagingService.ACTION_NOTIFICATION_RECEIVED.equalsIgnoreCase(action)) {
handleNotificationReceived(intent);
} }
} }
private void handleNotificationReceived(Intent intent) {
loadRemoteNotifications(false);
}
private void handleAuthTokenGenerated(Intent intent) { private void handleAuthTokenGenerated(Intent intent) {
// store the value // store the value
String encryptedAuthToken = intent.getStringExtra("authToken"); String encryptedAuthToken = intent.getStringExtra("authToken");
@@ -1952,13 +2189,67 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show(); setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
} }
public void showNotifications() {
clearWunderbarFocus(findViewById(R.id.wunderbar));
findViewById(R.id.notifications_container).setVisibility(View.VISIBLE);
((ImageView) findViewById(R.id.notifications_toggle_icon)).setColorFilter(ContextCompat.getColor(this, R.color.lbryGreen));
if (remoteNotifcationsLastLoaded == null ||
(System.currentTimeMillis() - remoteNotifcationsLastLoaded.getTime() > REMOTE_NOTIFICATION_REFRESH_TTL)) {
loadRemoteNotifications(true);
}
if (notificationListAdapter != null) {
markNotificationsRead();
}
}
public void hideNotifications() {
((ImageView) findViewById(R.id.notifications_toggle_icon)).setColorFilter(ContextCompat.getColor(this, R.color.actionBarForeground));
findViewById(R.id.notifications_container).setVisibility(View.GONE);
}
private void markNotificationsRead() {
List<LbryNotification> all = notificationListAdapter != null ? notificationListAdapter.getItems() : null;
if (all != null) {
List<Long> unreadIds = new ArrayList<>();
for (LbryNotification notification : all) {
if (!notification.isRead() && notification.getRemoteId() > 0) {
unreadIds.add(notification.getRemoteId());
}
}
if (unreadIds.size() > 0) {
NotificationUpdateTask task = new NotificationUpdateTask(unreadIds, true);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
(new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
DatabaseHelper.markNotificationsRead(db);
} catch (Exception ex) {
// pass
}
return null;
}
protected void onPostExecute(Void result) {
loadUnreadNotificationsCount();
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@Override @Override
public void onBackPressed() { public void onBackPressed() {
if (findViewById(R.id.url_suggestions_container).getVisibility() == View.VISIBLE) { if (findViewById(R.id.url_suggestions_container).getVisibility() == View.VISIBLE) {
clearWunderbarFocus(findViewById(R.id.wunderbar)); clearWunderbarFocus(findViewById(R.id.wunderbar));
return; return;
} }
if (findViewById(R.id.notifications_container).getVisibility() == View.VISIBLE) {
hideNotifications();
return;
}
if (backPressInterceptor != null && backPressInterceptor.onBackPressed()) { if (backPressInterceptor != null && backPressInterceptor.onBackPressed()) {
return; return;
} }
@@ -2217,6 +2508,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
findViewById(R.id.splash_view_error_container).setVisibility(View.VISIBLE); findViewById(R.id.splash_view_error_container).setVisibility(View.VISIBLE);
} }
@SuppressLint("StaticFieldLeak")
private void startup() { private void startup() {
final Context context = this; final Context context = this;
Lbry.startupInit(); Lbry.startupInit();
@@ -2273,7 +2565,13 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
} }
startupStages.put(STARTUP_STAGE_EXCHANGE_RATE_LOADED, true); startupStages.put(STARTUP_STAGE_EXCHANGE_RATE_LOADED, true);
Lbryio.authenticate(context); try {
Lbryio.authenticate(context);
} catch (AuthTokenInvalidatedException ex) {
// if this happens, attempt to authenticate again, so that we can obtain a new auth token
// this will also result in the user having to sign in again
Lbryio.authenticate(context);
}
if (Lbryio.currentUser == null) { if (Lbryio.currentUser == null) {
throw new Exception("Did not retrieve authenticated user."); throw new Exception("Did not retrieve authenticated user.");
} }
@@ -2319,8 +2617,8 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
startupStages.put(STARTUP_STAGE_SUBSCRIPTIONS_RESOLVED, true); startupStages.put(STARTUP_STAGE_SUBSCRIPTIONS_RESOLVED, true);
} }
} catch (Exception ex) { } catch (Exception ex) {
// nope // nopecd
android.util.Log.e(TAG, String.format("App startup failed: %s", ex.getMessage()), ex); Log.e(TAG, String.format("App startup failed: %s", ex.getMessage()), ex);
return false; return false;
} finally { } finally {
Helper.closeCloseable(reader); Helper.closeCloseable(reader);
@@ -2347,6 +2645,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
loadLastFragment(); loadLastFragment();
showSignedInUser(); showSignedInUser();
fetchRewards(); fetchRewards();
loadRemoteNotifications(false);
checkUrlIntent(getIntent()); checkUrlIntent(getIntent());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_APP_LAUNCH); LbryAnalytics.logEvent(LbryAnalytics.EVENT_APP_LAUNCH);
@@ -2408,7 +2707,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
if (data != null) { if (data != null) {
String url = data.toString(); String url = data.toString();
// check special urls // check special urls
if (url.startsWith("lbry://?")) { if (url.startsWith(SPECIAL_URL_PREFIX)) {
String specialPath = url.substring(8).toLowerCase(); String specialPath = url.substring(8).toLowerCase();
if (specialRouteFragmentClassMap.containsKey(specialPath)) { if (specialRouteFragmentClassMap.containsKey(specialPath)) {
Class fragmentClass = specialRouteFragmentClassMap.get(specialPath); Class fragmentClass = specialRouteFragmentClassMap.get(specialPath);
@@ -2526,6 +2825,18 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
LbryAnalytics.logEvent(LbryAnalytics.EVENT_LBRY_NOTIFICATION_OPEN, bundle); LbryAnalytics.logEvent(LbryAnalytics.EVENT_LBRY_NOTIFICATION_OPEN, bundle);
} }
private void checkSendToIntent(Intent intent) {
String intentAction = intent.getAction();
if (intentAction != null && intentAction.equals("android.intent.action.SEND")) {
ClipData clipData = intent.getClipData();
if (clipData != null) {
Uri uri = clipData.getItemAt(0).getUri();
String path = Helper.getRealPathFromURI_API19(this, uri);
openSendTo(path);
}
}
}
private void registerServiceActionsReceiver() { private void registerServiceActionsReceiver() {
IntentFilter intentFilter = new IntentFilter(); IntentFilter intentFilter = new IntentFilter();
@@ -2655,6 +2966,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
public void clearNowPlayingClaim() { public void clearNowPlayingClaim() {
nowPlayingClaim = null; nowPlayingClaim = null;
nowPlayingClaimUrl = null; nowPlayingClaimUrl = null;
nowPlayingClaimBitmap = null;
findViewById(R.id.global_now_playing_card).setVisibility(View.GONE); findViewById(R.id.global_now_playing_card).setVisibility(View.GONE);
((TextView) findViewById(R.id.global_now_playing_title)).setText(null); ((TextView) findViewById(R.id.global_now_playing_title)).setText(null);
((TextView) findViewById(R.id.global_now_playing_channel_title)).setText(null); ((TextView) findViewById(R.id.global_now_playing_channel_title)).setText(null);
@@ -2687,9 +2999,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
JSONObject startupStatus = status.getJSONObject("startup_status"); JSONObject startupStatus = status.getJSONObject("startup_status");
sdkReady = startupStatus.getBoolean("file_manager") && startupStatus.getBoolean("wallet"); sdkReady = startupStatus.getBoolean("file_manager") && startupStatus.getBoolean("wallet");
} }
} catch (ConnectException ex) { } catch (ConnectException | JSONException ex) {
// pass
} catch (JSONException ex) {
// pass // pass
} }
@@ -2781,7 +3091,7 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
} }
protected void onStop() { protected void onStop() {
if (appPlayer != null && inPictureInPictureMode) { if (appPlayer != null && inPictureInPictureMode && !isBackgroundPlaybackEnabled()) {
appPlayer.setPlayWhenReady(false); appPlayer.setPlayWhenReady(false);
} }
super.onStop(); super.onStop();
@@ -2914,6 +3224,155 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} }
private void displayUnreadNotificationCount(int count) {
String text = count > 99 ? "99+" : String.valueOf(count);
TextView badge = findViewById(R.id.notifications_badge_count);
badge.setVisibility(count > 0 ? View.VISIBLE : View.INVISIBLE);
badge.setText(text);
}
private void loadUnreadNotificationsCount() {
(new AsyncTask<Void, Void, Integer>() {
@Override
protected Integer doInBackground(Void... params) {
try {
SQLiteDatabase db = dbHelper.getReadableDatabase();
return DatabaseHelper.getUnreadNotificationsCount(db);
} catch (Exception ex) {
return 0;
}
}
protected void onPostExecute(Integer count) {
displayUnreadNotificationCount(count);
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void loadRemoteNotifications(boolean markRead) {
findViewById(R.id.notification_list_empty_container).setVisibility(View.GONE);
NotificationListTask task = new NotificationListTask(this, findViewById(R.id.notifications_progress), new NotificationListTask.ListNotificationsHandler() {
@Override
public void onSuccess(List<LbryNotification> notifications) {
remoteNotifcationsLastLoaded = new Date();
loadUnreadNotificationsCount();
loadLocalNotifications();
if (markRead && findViewById(R.id.notifications_container).getVisibility() == View.VISIBLE) {
markNotificationsRead();
}
}
@Override
public void onError(Exception exception) {
// pass
Log.e(TAG, "error loading remote notifications", exception);
loadLocalNotifications();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void loadLocalNotifications() {
(new AsyncTask<Void, Void, List<LbryNotification>>() {
protected void onPreExecute() {
findViewById(R.id.notification_list_empty_container).setVisibility(View.GONE);
findViewById(R.id.notifications_progress).setVisibility(View.VISIBLE);
}
@Override
protected List<LbryNotification> doInBackground(Void... params) {
List<LbryNotification> notifications = new ArrayList<>();
try {
SQLiteDatabase db = dbHelper.getReadableDatabase();
notifications = DatabaseHelper.getNotifications(db);
} catch (Exception ex) {
// pass
}
return notifications;
}
protected void onPostExecute(List<LbryNotification> notifications) {
findViewById(R.id.notification_list_empty_container).setVisibility(notifications.size() == 0 ? View.VISIBLE : View.GONE);
findViewById(R.id.notifications_progress).setVisibility(View.GONE);
loadUnreadNotificationsCount();
if (notificationListAdapter == null) {
notificationListAdapter = new NotificationListAdapter(notifications, MainActivity.this);
((RecyclerView) findViewById(R.id.notifications_list)).setAdapter(notificationListAdapter);
} else {
notificationListAdapter.addNotifications(notifications);
}
resolveCommentAuthors(notificationListAdapter.getAuthorUrls());
notificationListAdapter.setClickListener(new NotificationListAdapter.NotificationClickListener() {
@Override
public void onNotificationClicked(LbryNotification notification) {
// set as seen and read
NotificationUpdateTask task = new NotificationUpdateTask(Arrays.asList(notification.getRemoteId()), true, true, true);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
markNotificationReadAndSeen(notification.getId());
notification.setSeen(true);
if (notificationListAdapter != null) {
notificationListAdapter.notifyDataSetChanged();
}
String targetUrl = notification.getTargetUrl();
if (targetUrl.startsWith(SPECIAL_URL_PREFIX)) {
openSpecialUrl(targetUrl);
} else {
LbryUri target = LbryUri.tryParse(notification.getTargetUrl());
if (target != null) {
if (target.isChannel()) {
openChannelUrl(notification.getTargetUrl());
} else {
openFileUrl(notification.getTargetUrl());
}
}
}
hideNotifications();
}
});
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void markNotificationReadAndSeen(long notificationId) {
(new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
if (dbHelper != null) {
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
DatabaseHelper.markNotificationReadAndSeen(notificationId, db);
} catch (Exception ex) {
// pass
}
}
return null;
}
protected void onPostExecute() {
loadUnreadNotificationsCount();
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void resolveCommentAuthors(List<String> urls) {
if (urls != null && urls.size() > 0) {
ResolveTask task = new ResolveTask(urls, Lbry.LBRY_TV_CONNECTION_STRING, null, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
if (notificationListAdapter != null) {
notificationListAdapter.updateAuthorClaims(claims);
}
}
@Override
public void onError(Exception error) {
// pass
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private void checkSyncedWallet() { private void checkSyncedWallet() {
String password = Utils.getSecureValue(SECURE_VALUE_KEY_SAVED_PASSWORD, this, Lbry.KEYSTORE); String password = Utils.getSecureValue(SECURE_VALUE_KEY_SAVED_PASSWORD, this, Lbry.KEYSTORE);
// Just check if the current user has a synced wallet, no need to do anything else here // Just check if the current user has a synced wallet, no need to do anything else here
@@ -2957,6 +3416,53 @@ public class MainActivity extends AppCompatActivity implements SdkStatusListener
return (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED); return (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED);
} }
private void establishBillingClientConnection() {
if (billingClient != null) {
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// no need to do anything here. purchases are always checked server-side
checkPurchases();
}
}
@Override
public void onBillingServiceDisconnected() {
establishBillingClientConnection();
}
});
}
}
public static void handleBillingPurchase(
Purchase purchase,
BillingClient billingClient,
Context context,
View progressView,
RewardVerifiedHandler handler) {
String sku = purchase.getSku();
if (SKU_SKIP.equalsIgnoreCase(sku)) {
// send purchase token for verification
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED
/*&& isSignatureValid(purchase)*/) {
// consume the purchase
String purchaseToken = purchase.getPurchaseToken();
ConsumeParams consumeParams = ConsumeParams.newBuilder().setPurchaseToken(purchaseToken).build();
billingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
@Override
public void onConsumeResponse(@NonNull BillingResult billingResult, @NonNull String s) {
}
});
// send the purchase token to the backend to complete verification
AndroidPurchaseTask task = new AndroidPurchaseTask(purchaseToken, progressView, context, handler);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
}
public interface BackPressInterceptor { public interface BackPressInterceptor {
boolean onBackPressed(); boolean onBackPressed();
} }
@@ -7,19 +7,35 @@ import android.content.IntentFilter;
import android.graphics.Color; import android.graphics.Color;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.view.View; import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2; import androidx.viewpager2.widget.ViewPager2;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.google.android.material.snackbar.Snackbar; import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
import io.lbry.browser.adapter.VerificationPagerAdapter; import io.lbry.browser.adapter.VerificationPagerAdapter;
import io.lbry.browser.listener.SignInListener; import io.lbry.browser.listener.SignInListener;
import io.lbry.browser.listener.WalletSyncListener; import io.lbry.browser.listener.WalletSyncListener;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.model.lbryinc.User; import io.lbry.browser.model.lbryinc.User;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.tasks.lbryinc.FetchCurrentUserTask; import io.lbry.browser.tasks.lbryinc.FetchCurrentUserTask;
import io.lbry.browser.utils.Helper; import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryAnalytics; import io.lbry.browser.utils.LbryAnalytics;
@@ -32,11 +48,59 @@ public class VerificationActivity extends FragmentActivity implements SignInList
public static final int VERIFICATION_FLOW_REWARDS = 2; public static final int VERIFICATION_FLOW_REWARDS = 2;
public static final int VERIFICATION_FLOW_WALLET = 3; public static final int VERIFICATION_FLOW_WALLET = 3;
private BillingClient billingClient;
private BroadcastReceiver sdkReceiver; private BroadcastReceiver sdkReceiver;
private String email; private String email;
private boolean signedIn; private boolean signedIn;
private int flow; private int flow;
private PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> purchases) {
int responseCode = billingResult.getResponseCode();
if (responseCode == BillingClient.BillingResponseCode.OK && purchases != null)
{
for (Purchase purchase : purchases) {
if (MainActivity.SKU_SKIP.equalsIgnoreCase(purchase.getSku())) {
showLoading();
MainActivity.handleBillingPurchase(
purchase,
billingClient,
VerificationActivity.this, null, new RewardVerifiedHandler() {
@Override
public void onSuccess(RewardVerified rewardVerified) {
if (Lbryio.currentUser != null) {
Lbryio.currentUser.setRewardApproved(rewardVerified.isRewardApproved());
}
if (!rewardVerified.isRewardApproved()) {
// show pending purchase message (possible slow card tx)
Snackbar.make(findViewById(R.id.verification_pager), R.string.purchase_request_pending, Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(findViewById(R.id.verification_pager), R.string.reward_verification_successful, Snackbar.LENGTH_LONG).show();
}
setResult(RESULT_OK);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 3000);
}
@Override
public void onError(Exception error) {
showFetchUserError(getString(R.string.purchase_request_failed_error));
hideLoading();
}
});
}
}
}
}
};
@Override @Override
public void onCreate(Bundle savedInstanceState) { public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); super.onCreate(savedInstanceState);
@@ -73,6 +137,12 @@ public class VerificationActivity extends FragmentActivity implements SignInList
}; };
registerReceiver(sdkReceiver, filter); registerReceiver(sdkReceiver, filter);
billingClient = BillingClient.newBuilder(this)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases()
.build();
establishBillingClientConnection();
setContentView(R.layout.activity_verification); setContentView(R.layout.activity_verification);
ViewPager2 viewPager = findViewById(R.id.verification_pager); ViewPager2 viewPager = findViewById(R.id.verification_pager);
viewPager.setUserInputEnabled(false); viewPager.setUserInputEnabled(false);
@@ -89,6 +159,24 @@ public class VerificationActivity extends FragmentActivity implements SignInList
}); });
} }
private void establishBillingClientConnection() {
if (billingClient != null) {
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// no need to do anything here. purchases are always checked server-side
}
}
@Override
public void onBillingServiceDisconnected() {
establishBillingClientConnection();
}
});
}
}
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
LbryAnalytics.setCurrentScreen(this, "Verification", "Verification"); LbryAnalytics.setCurrentScreen(this, "Verification", "Verification");
@@ -104,11 +192,13 @@ public class VerificationActivity extends FragmentActivity implements SignInList
flowHandled = true; flowHandled = true;
} else if (flow == VERIFICATION_FLOW_REWARDS) { } else if (flow == VERIFICATION_FLOW_REWARDS) {
User user = Lbryio.currentUser; User user = Lbryio.currentUser;
if (!user.isIdentityVerified()) { // disable phone verification for now
/*if (!user.isIdentityVerified()) {
// phone number verification required // phone number verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false); viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false);
flowHandled = true; flowHandled = true;
} else if (!user.isRewardApproved()) { } else */
if (!user.isRewardApproved()) {
// manual verification required // manual verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false); viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false);
flowHandled = true; flowHandled = true;
@@ -167,7 +257,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
// only sign in required, don't do anything else // only sign in required, don't do anything else
showLoading(); showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() { FetchCurrentUserTask task = new FetchCurrentUserTask(this, new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override @Override
public void onSuccess(User user) { public void onSuccess(User user) {
Lbryio.currentUser = user; Lbryio.currentUser = user;
@@ -185,7 +275,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
} else { } else {
// change pager view depending on flow // change pager view depending on flow
showLoading(); showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() { FetchCurrentUserTask task = new FetchCurrentUserTask(this, new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override @Override
public void onSuccess(User user) { public void onSuccess(User user) {
hideLoading(); hideLoading();
@@ -195,10 +285,14 @@ public class VerificationActivity extends FragmentActivity implements SignInList
ViewPager2 viewPager = findViewById(R.id.verification_pager); ViewPager2 viewPager = findViewById(R.id.verification_pager);
// for rewards, (show phone verification if not done, or manual verification if required) // for rewards, (show phone verification if not done, or manual verification if required)
if (flow == VERIFICATION_FLOW_REWARDS) { if (flow == VERIFICATION_FLOW_REWARDS) {
if (!user.isIdentityVerified()) { // skipping phone verification
/*if (!user.isIdentityVerified()) {
// phone number verification required // phone number verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false); viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false);
} else if (!user.isRewardApproved()) { } else
*/
if (!user.isRewardApproved()) {
// manual verification required // manual verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false); viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false);
} else { } else {
@@ -229,7 +323,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
@Override @Override
public void onPhoneVerified() { public void onPhoneVerified() {
showLoading(); showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() { FetchCurrentUserTask task = new FetchCurrentUserTask(this, new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override @Override
public void onSuccess(User user) { public void onSuccess(User user) {
Lbryio.currentUser = user; Lbryio.currentUser = user;
@@ -289,6 +383,54 @@ public class VerificationActivity extends FragmentActivity implements SignInList
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE); findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
} }
@Override
public void onSkipQueueAction() {
if (billingClient != null) {
List<String> skuList = new ArrayList<>();
skuList.add(MainActivity.SKU_SKIP);
SkuDetailsParams detailsParams = SkuDetailsParams.newBuilder().
setType(BillingClient.SkuType.INAPP).
setSkusList(skuList).build();
billingClient.querySkuDetailsAsync(detailsParams, new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(@NonNull BillingResult billingResult, @Nullable List<SkuDetails> list) {
if (list != null && list.size() > 0) {
// we only queried one product, so it should be the first item in the list
SkuDetails skuDetails = list.get(0);
// launch the billing flow for skip queue
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder().
setSkuDetails(skuDetails).build();
billingClient.launchBillingFlow(VerificationActivity.this, billingFlowParams);
}
}
});
}
}
@Override
public void onTwitterVerified() {
Snackbar.make(findViewById(R.id.verification_pager), R.string.reward_verification_successful, Snackbar.LENGTH_LONG).show();
setResult(RESULT_OK);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 3000);
}
@Override
public void onManualProgress(boolean progress) {
if (progress) {
findViewById(R.id.verification_close_button).setVisibility(View.GONE);
} else {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
}
}
@Override @Override
public void onDestroy() { public void onDestroy() {
Helper.unregisterReceiver(sdkReceiver, this); Helper.unregisterReceiver(sdkReceiver, this);
@@ -97,7 +97,7 @@ public class ChannelFilterListAdapter extends RecyclerView.Adapter<ChannelFilter
vh.titleView.setText(Helper.isNullOrEmpty(claim.getTitle()) ? claim.getName() : claim.getTitle()); vh.titleView.setText(Helper.isNullOrEmpty(claim.getTitle()) ? claim.getName() : claim.getTitle());
String thumbnailUrl = claim.getThumbnailUrl(); String thumbnailUrl = claim.getThumbnailUrl();
if (!Helper.isNullOrEmpty(thumbnailUrl) && context != null) { if (!Helper.isNullOrEmpty(thumbnailUrl) && context != null) {
Glide.with(context.getApplicationContext()).asBitmap().load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(vh.thumbnailView); Glide.with(context.getApplicationContext()).load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(vh.thumbnailView);
} }
vh.alphaContainer.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE); vh.alphaContainer.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE);
vh.thumbnailView.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.GONE : View.VISIBLE); vh.thumbnailView.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.GONE : View.VISIBLE);
@@ -60,7 +60,13 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
public ClaimListAdapter(List<Claim> items, Context context) { public ClaimListAdapter(List<Claim> items, Context context) {
this.context = context; this.context = context;
this.items = new ArrayList<>(items); this.items = new ArrayList<>();
for (Claim item : items) {
if (item != null) {
this.items.add(item);
}
}
this.selectedItems = new ArrayList<>(); this.selectedItems = new ArrayList<>();
quickClaimIdMap = new HashMap<>(); quickClaimIdMap = new HashMap<>();
quickClaimUrlMap = new HashMap<>(); quickClaimUrlMap = new HashMap<>();
@@ -139,7 +145,7 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
public void addItems(List<Claim> claims) { public void addItems(List<Claim> claims) {
for (Claim claim : claims) { for (Claim claim : claims) {
if (!items.contains(claim)) { if (claim != null && !items.contains(claim)) {
items.add(claim); items.add(claim);
} }
} }
@@ -149,7 +155,12 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
notifyDataSetChanged(); notifyDataSetChanged();
} }
public void setItems(List<Claim> claims) { public void setItems(List<Claim> claims) {
items = new ArrayList<>(claims); items = new ArrayList<>();
for (Claim claim : claims) {
if (claim != null) {
items.add(claim);
}
}
notifyDataSetChanged(); notifyDataSetChanged();
} }
@@ -182,6 +193,10 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
protected TextView fileSizeView; protected TextView fileSizeView;
protected ProgressBar downloadProgressView; protected ProgressBar downloadProgressView;
protected TextView deviceView; protected TextView deviceView;
protected View loadingImagePlaceholder;
protected View loadingTextPlaceholder1;
protected View loadingTextPlaceholder2;
public ViewHolder(View v) { public ViewHolder(View v) {
super(v); super(v);
feeContainer = v.findViewById(R.id.claim_fee_container); feeContainer = v.findViewById(R.id.claim_fee_container);
@@ -201,6 +216,10 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
fileSizeView = v.findViewById(R.id.claim_file_size); fileSizeView = v.findViewById(R.id.claim_file_size);
downloadProgressView = v.findViewById(R.id.claim_download_progress); downloadProgressView = v.findViewById(R.id.claim_download_progress);
deviceView = v.findViewById(R.id.claim_view_device); deviceView = v.findViewById(R.id.claim_view_device);
loadingImagePlaceholder = v.findViewById(R.id.claim_thumbnail_placeholder);
loadingTextPlaceholder1 = v.findViewById(R.id.claim_text_loading_placeholder_1);
loadingTextPlaceholder2 = v.findViewById(R.id.claim_text_loading_placeholder_2);
} }
} }
@@ -297,22 +316,19 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
return new ClaimListAdapter.ViewHolder(v); return new ClaimListAdapter.ViewHolder(v);
} }
public int getScaledValue(int value) {
return (int) (value * scale + 0.5f);
}
@Override @Override
public void onBindViewHolder(ClaimListAdapter.ViewHolder vh, int position) { public void onBindViewHolder(ClaimListAdapter.ViewHolder vh, int position) {
int type = getItemViewType(position); int type = getItemViewType(position);
int paddingTop = position == 0 ? 16 : 8; int paddingTop = position == 0 ? 16 : 8;
int paddingBottom = position == getItemCount() - 1 ? 16 : 8; int paddingBottom = position == getItemCount() - 1 ? 16 : 8;
int paddingTopScaled = getScaledValue(paddingTop); int paddingTopScaled = Helper.getScaledValue(paddingTop, scale);
int paddingBottomScaled = getScaledValue(paddingBottom); int paddingBottomScaled = Helper.getScaledValue(paddingBottom, scale);
vh.itemView.setPadding(vh.itemView.getPaddingLeft(), paddingTopScaled, vh.itemView.getPaddingRight(), paddingBottomScaled); vh.itemView.setPadding(vh.itemView.getPaddingLeft(), paddingTopScaled, vh.itemView.getPaddingRight(), paddingBottomScaled);
Claim original = items.get(position); Claim original = items.get(position);
boolean isRepost = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType()); boolean isRepost = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType());
final Claim item = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType()) ? original.getRepostedClaim() : original; final Claim item = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType()) ?
(original.getRepostedClaim() != null ? original.getRepostedClaim() : original): original;
Claim.GenericMetadata metadata = item.getValue(); Claim.GenericMetadata metadata = item.getValue();
Claim signingChannel = item.getSigningChannel(); Claim signingChannel = item.getSigningChannel();
Claim.StreamMetadata streamMetadata = null; Claim.StreamMetadata streamMetadata = null;
@@ -386,8 +402,8 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
}); });
vh.publishTimeView.setVisibility(!isPending ? View.VISIBLE : View.GONE); vh.publishTimeView.setVisibility(!isPending ? View.VISIBLE : View.GONE);
vh.pendingTextView.setVisibility(isPending ? View.VISIBLE : View.GONE); vh.pendingTextView.setVisibility(isPending && !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
vh.repostInfoView.setVisibility(isRepost ? View.VISIBLE : View.GONE); vh.repostInfoView.setVisibility(isRepost && type != VIEW_TYPE_FEATURED ? View.VISIBLE : View.GONE);
vh.repostChannelView.setText(isRepost ? original.getSigningChannel().getName() : null); vh.repostChannelView.setText(isRepost ? original.getSigningChannel().getName() : null);
vh.repostChannelView.setOnClickListener(new View.OnClickListener() { vh.repostChannelView.setOnClickListener(new View.OnClickListener() {
@Override @Override
@@ -409,6 +425,13 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
vh.noThumbnailView.setVisibility(Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE); vh.noThumbnailView.setVisibility(Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE);
Helper.setIconViewBackgroundColor(vh.noThumbnailView, bgColor, false, context); Helper.setIconViewBackgroundColor(vh.noThumbnailView, bgColor, false, context);
Helper.setViewVisibility(vh.loadingImagePlaceholder, item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.loadingTextPlaceholder1, item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.loadingTextPlaceholder2, item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.titleView, !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.publisherView, !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.publishTimeView, !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
if (type == VIEW_TYPE_FEATURED && item.isUnresolved()) { if (type == VIEW_TYPE_FEATURED && item.isUnresolved()) {
vh.durationView.setVisibility(View.GONE); vh.durationView.setVisibility(View.GONE);
vh.titleView.setText("Nothing here. Publish something!"); vh.titleView.setText("Nothing here. Publish something!");
@@ -1,24 +1,74 @@
package io.lbry.browser.adapter; package io.lbry.browser.adapter;
import android.content.Context; import android.content.Context;
import android.text.format.DateUtils;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import io.lbry.browser.R; import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.ClaimCacheKey;
import io.lbry.browser.model.Comment; import io.lbry.browser.model.Comment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
public class CommentListAdapter extends RecyclerView.Adapter<CommentListAdapter.ViewHolder> { public class CommentListAdapter extends RecyclerView.Adapter<CommentListAdapter.ViewHolder> {
private List<Comment> items; private List<Comment> items;
private Context context; private Context context;
private boolean nested;
private float scale;
@Setter
private ClaimListAdapter.ClaimListItemListener listener;
@Setter
private ReplyClickListener replyListener;
public CommentListAdapter(List<Comment> items, Context context) { public CommentListAdapter(List<Comment> items, Context context) {
this.items = items; this(items, context, false);
}
public CommentListAdapter(List<Comment> items, Context context, boolean nested) {
this.items = new ArrayList<>(items);
this.context = context; this.context = context;
this.nested = nested;
if (context != null) {
scale = context.getResources().getDisplayMetrics().density;
}
for (Comment item : this.items) {
ClaimCacheKey key = new ClaimCacheKey();
key.setClaimId(item.getChannelId());
if (Lbry.claimCache.containsKey(key)) {
item.setPoster(Lbry.claimCache.get(key));
}
}
}
public void clearItems() {
items.clear();
notifyDataSetChanged();
}
public int getPositionForComment(String commentHash) {
for (int i = 0; i < items.size(); i++) {
if (commentHash.equalsIgnoreCase(items.get(i).getId())) {
return i;
}
}
return -1;
} }
@Override @Override
@@ -26,14 +76,90 @@ public class CommentListAdapter extends RecyclerView.Adapter<CommentListAdapter.
return items != null ? items.size() : 0; return items != null ? items.size() : 0;
} }
public List<String> getClaimUrlsToResolve() {
List<String> urls = new ArrayList<>();
for (int i = 0; i < items.size(); i++) {
Comment item = items.get(i);
if (item.getPoster() == null) {
LbryUri url = LbryUri.tryParse(String.format("%s#%s", item.getChannelName(), item.getChannelId()));
if (url != null && !urls.contains(url.toString())) {
urls.add(url.toString());
}
}
if (item.getReplies().size() > 0) {
for (int j = 0; j < item.getReplies().size(); j++) {
Comment reply = item.getReplies().get(j);
if (reply.getPoster() == null) {
LbryUri url = LbryUri.tryParse(String.format("%s#%s", reply.getChannelName(), reply.getChannelId()));
if (url != null && !urls.contains(url.toString())) {
urls.add(url.toString());
}
}
}
}
}
return urls;
}
public static class ViewHolder extends RecyclerView.ViewHolder { public static class ViewHolder extends RecyclerView.ViewHolder {
protected TextView channelName; protected TextView channelName;
protected TextView commentText; protected TextView commentText;
protected ImageView thumbnailView;
protected View noThumbnailView;
protected TextView alphaView;
protected TextView commentTimeView;
protected View replyLink;
protected RecyclerView repliesList;
public ViewHolder (View v) { public ViewHolder (View v) {
super(v); super(v);
channelName = v.findViewById(R.id.comment_channel_name); channelName = v.findViewById(R.id.comment_channel_name);
commentTimeView = v.findViewById(R.id.comment_time);
commentText = v.findViewById(R.id.comment_text); commentText = v.findViewById(R.id.comment_text);
replyLink = v.findViewById(R.id.comment_reply_link);
thumbnailView = v.findViewById(R.id.comment_thumbnail);
noThumbnailView = v.findViewById(R.id.comment_no_thumbnail);
alphaView = v.findViewById(R.id.comment_thumbnail_alpha);
repliesList = v.findViewById(R.id.comment_replies);
}
}
public void insert(int index, Comment comment) {
if (!items.contains(comment)) {
items.add(index, comment);
notifyDataSetChanged();
}
}
public void addReply(Comment comment) {
for (int i = 0; i < items.size(); i++) {
Comment parent = items.get(i);
if (parent.getId().equalsIgnoreCase(comment.getParentId())) {
parent.addReply(comment);
notifyDataSetChanged();
break;
}
}
}
public void updatePosterForComment(String channelId, Claim channel) {
for (int i = 0 ; i < items.size(); i++) {
Comment item = items.get(i);
List<Comment> replies = item.getReplies();
if (replies != null && replies.size() > 0) {
for (int j = 0; j < replies.size(); j++) {
Comment reply = item.getReplies().get(j);
if (channelId.equalsIgnoreCase(reply.getChannelId())) {
reply.setPoster(channel);
break;
}
}
}
if (channelId.equalsIgnoreCase(item.getChannelId())) {
item.setPoster(channel);
break;
}
} }
} }
@@ -46,7 +172,57 @@ public class CommentListAdapter extends RecyclerView.Adapter<CommentListAdapter.
@Override @Override
public void onBindViewHolder(ViewHolder holder, int position) { public void onBindViewHolder(ViewHolder holder, int position) {
Comment comment = items.get(position); Comment comment = items.get(position);
holder.itemView.setPadding(
nested ? Helper.getScaledValue(56, scale) : holder.itemView.getPaddingLeft(),
holder.itemView.getPaddingTop(),
nested ? 0 : holder.itemView.getPaddingRight(),
holder.itemView.getPaddingBottom());
holder.channelName.setText(comment.getChannelName()); holder.channelName.setText(comment.getChannelName());
holder.commentTimeView.setText(DateUtils.getRelativeTimeSpanString(
(comment.getTimestamp() * 1000), System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
holder.commentText.setText(comment.getText()); holder.commentText.setText(comment.getText());
holder.replyLink.setVisibility(!nested ? View.VISIBLE : View.GONE);
boolean hasThumbnail = comment.getPoster() != null && !Helper.isNullOrEmpty(comment.getPoster().getThumbnailUrl());
holder.thumbnailView.setVisibility(hasThumbnail ? View.VISIBLE : View.INVISIBLE);
holder.noThumbnailView.setVisibility(!hasThumbnail ? View.VISIBLE : View.INVISIBLE);
int bgColor = Helper.generateRandomColorForValue(comment.getChannelId());
Helper.setIconViewBackgroundColor(holder.noThumbnailView, bgColor, false, context);
if (hasThumbnail) {
Glide.with(context.getApplicationContext()).asBitmap().load(comment.getPoster().getThumbnailUrl()).
apply(RequestOptions.circleCropTransform()).into(holder.thumbnailView);
}
holder.alphaView.setText(comment.getChannelName() != null ? comment.getChannelName().substring(1, 2).toUpperCase() : null);
List<Comment> replies = comment.getReplies();
boolean hasReplies = replies != null && replies.size() > 0;
if (hasReplies) {
holder.repliesList.setLayoutManager(new LinearLayoutManager(context));
holder.repliesList.setAdapter(new CommentListAdapter(replies, context, true));
} else {
holder.repliesList.setAdapter(null);
}
holder.channelName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null && comment.getPoster() != null) {
listener.onClaimClicked(comment.getPoster());
}
}
});
holder.replyLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (replyListener != null) {
replyListener.onReplyClicked(comment);
}
}
});
}
public interface ReplyClickListener {
void onReplyClicked(Comment comment);
} }
} }
@@ -10,6 +10,7 @@ import android.widget.SpinnerAdapter;
import android.widget.TextView; import android.widget.TextView;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection;
import java.util.List; import java.util.List;
import io.lbry.browser.R; import io.lbry.browser.R;
@@ -40,6 +41,25 @@ public class InlineChannelSpinnerAdapter extends ArrayAdapter<Claim> {
channels.add(1, anonymous); channels.add(1, anonymous);
} }
} }
public void addAnonymousPlaceholder() {
Claim anonymous = new Claim();
anonymous.setPlaceholderAnonymous(true);
insert(anonymous, 0);
channels.add(0, anonymous);
}
public void addAll(Collection<? extends Claim> collection) {
for (Claim claim : collection) {
if (!channels.contains(claim)) {
channels.add(claim);
}
}
super.addAll(collection);
}
public void clear() {
channels.clear();
super.clear();
}
public int getItemPosition(Claim item) { public int getItemPosition(Claim item) {
for (int i = 0; i < channels.size(); i++) { for (int i = 0; i < channels.size(); i++) {
@@ -0,0 +1,204 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.graphics.Color;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;
import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.ui.controls.SolidIconView;
import io.lbry.browser.utils.Helper;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Data
@EqualsAndHashCode(callSuper = false)
public class NotificationListAdapter extends RecyclerView.Adapter<NotificationListAdapter.ViewHolder> {
private static final String RULE_CREATOR_SUBSCRIBER = "creator_subscriber";
private static final String RULE_COMMENT = "comment";
private Context context;
private List<LbryNotification> items;
@Setter
private NotificationClickListener clickListener;
@Getter
@Setter
private int customizeMode;
public NotificationListAdapter(List<LbryNotification> notifications, Context context) {
this.context = context;
this.items = new ArrayList<>(notifications);
Collections.sort(items, Collections.reverseOrder(new LbryNotification()));
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected View layoutView;
protected TextView titleView;
protected TextView bodyView;
protected TextView timeView;
protected SolidIconView iconView;
protected ImageView thumbnailView;
public ViewHolder(View v) {
super(v);
layoutView = v.findViewById(R.id.notification_layout);
titleView = v.findViewById(R.id.notification_title);
bodyView = v.findViewById(R.id.notification_body);
timeView = v.findViewById(R.id.notification_time);
iconView = v.findViewById(R.id.notification_icon);
thumbnailView = v.findViewById(R.id.notification_author_thumbnail);
}
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
public void insertNotification(LbryNotification notification, int index) {
if (!items.contains(notification)) {
items.add(index, notification);
}
notifyDataSetChanged();
}
public void addNotification(LbryNotification notification) {
if (!items.contains(notification)) {
items.add(notification);
}
notifyDataSetChanged();
}
public List<String> getAuthorUrls() {
List<String> urls = new ArrayList<>();
for (LbryNotification item : items) {
if (!Helper.isNullOrEmpty(item.getAuthorUrl())) {
urls.add(item.getAuthorUrl());
}
}
return urls;
}
public void updateAuthorClaims(List<Claim> claims) {
for (Claim claim : claims) {
if (claim != null && claim.getThumbnailUrl() != null) {
updateClaimForAuthorUrl(claim);
}
}
notifyDataSetChanged();
}
private void updateClaimForAuthorUrl(Claim claim) {
for (LbryNotification item : items) {
if (claim.getPermanentUrl().equalsIgnoreCase(item.getAuthorUrl())) {
item.setCommentAuthor(claim);
}
}
}
public void addNotifications(List<LbryNotification> notifications) {
for (LbryNotification notification : notifications) {
if (!items.contains(notification)) {
items.add(notification);
}
}
Collections.sort(items, Collections.reverseOrder(new LbryNotification()));
notifyDataSetChanged();
}
@Override
public NotificationListAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_notification, root, false);
return new NotificationListAdapter.ViewHolder(v);
}
private int getStringIdForRule(String rule) {
if (RULE_CREATOR_SUBSCRIBER.equalsIgnoreCase(rule)) {
return R.string.fa_heart;
}
if (RULE_COMMENT.equalsIgnoreCase(rule)) {
return R.string.fa_comment_alt;
}
return R.string.fa_asterisk;
}
private int getColorForRule(String rule) {
if (RULE_CREATOR_SUBSCRIBER.equalsIgnoreCase(rule)) {
return Color.RED;
}
if (RULE_COMMENT.equalsIgnoreCase(rule)) {
return ContextCompat.getColor(context, R.color.nextLbryGreen);
}
return ContextCompat.getColor(context, R.color.lbryGreen);
}
@Override
public void onBindViewHolder(NotificationListAdapter.ViewHolder vh, int position) {
LbryNotification notification = items.get(position);
vh.layoutView.setBackgroundColor(ContextCompat.getColor(context, notification.isSeen() ? R.color.white : R.color.nextLbryGreenSemiTransparent));
vh.titleView.setVisibility(!Helper.isNullOrEmpty(notification.getTitle()) ? View.VISIBLE : View.GONE);
vh.titleView.setText(notification.getTitle());
vh.bodyView.setText(notification.getDescription());
vh.timeView.setText(DateUtils.getRelativeTimeSpanString(
getLocalNotificationTime(notification), System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
vh.thumbnailView.setVisibility(notification.getCommentAuthor() == null ? View.INVISIBLE : View.VISIBLE);
if (notification.getCommentAuthor() != null) {
Glide.with(context.getApplicationContext()).load(
notification.getCommentAuthor().getThumbnailUrl()).apply(RequestOptions.circleCropTransform()).into(vh.thumbnailView);
}
vh.iconView.setVisibility(notification.getCommentAuthor() != null ? View.INVISIBLE : View.VISIBLE);
vh.iconView.setText(getStringIdForRule(notification.getRule()));
vh.iconView.setTextColor(getColorForRule(notification.getRule()));
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onNotificationClicked(notification);
}
}
});
}
private long getLocalNotificationTime(LbryNotification notification) {
TimeZone utcTZ = TimeZone.getTimeZone("UTC");
TimeZone targetTZ = TimeZone.getDefault();
Calendar cal = new GregorianCalendar(utcTZ);
cal.setTimeInMillis(notification.getTimestamp().getTime());
cal.add(Calendar.MILLISECOND, utcTZ.getRawOffset() * -1);
cal.add(Calendar.MILLISECOND, targetTZ.getRawOffset());
return cal.getTimeInMillis();
}
public interface NotificationClickListener {
void onNotificationClicked(LbryNotification notification);
}
}
@@ -97,7 +97,7 @@ public class SuggestedChannelGridAdapter extends RecyclerView.Adapter<SuggestedC
vh.alphaView.setText(claim.getName().substring(1, 2)); vh.alphaView.setText(claim.getName().substring(1, 2));
if (!Helper.isNullOrEmpty(thumbnailUrl)) { if (!Helper.isNullOrEmpty(thumbnailUrl)) {
vh.thumbnailView.setVisibility(View.VISIBLE); vh.thumbnailView.setVisibility(View.VISIBLE);
Glide.with(context.getApplicationContext()).asBitmap().load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(vh.thumbnailView); Glide.with(context.getApplicationContext()).load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(vh.thumbnailView);
} else { } else {
vh.thumbnailView.setVisibility(View.GONE); vh.thumbnailView.setVisibility(View.GONE);
} }
@@ -4,7 +4,6 @@ import android.content.Context;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteOpenHelper;
import android.opengl.Visibility;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.text.ParseException; import java.text.ParseException;
@@ -13,16 +12,16 @@ import java.util.ArrayList;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.model.Tag; import io.lbry.browser.model.Tag;
import io.lbry.browser.model.UrlSuggestion; import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.model.ViewHistory; import io.lbry.browser.model.ViewHistory;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.model.lbryinc.Subscription; import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.utils.Helper; import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri; import io.lbry.browser.utils.LbryUri;
public class DatabaseHelper extends SQLiteOpenHelper { public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 2; public static final int DATABASE_VERSION = 6;
public static final String DATABASE_NAME = "LbryApp.db"; public static final String DATABASE_NAME = "LbryApp.db";
private static DatabaseHelper instance; private static DatabaseHelper instance;
@@ -48,7 +47,19 @@ public class DatabaseHelper extends SQLiteOpenHelper {
", thumbnail_url TEXT" + ", thumbnail_url TEXT" +
", release_time INTEGER " + ", release_time INTEGER " +
", device TEXT" + ", device TEXT" +
", timestamp TEXT NOT NULL)" ", timestamp TEXT NOT NULL)",
"CREATE TABLE notifications (" +
" id INTEGER PRIMARY KEY NOT NULL" +
", remote_id INTEGER NOT NULL" +
", author_url TEXT" +
", title TEXT" +
", description TEXT" +
", thumbnail_url TEXT" +
", target_url TEXT" +
", rule TEXT" +
", is_read INTEGER DEFAULT 0 NOT NULL" +
", is_seen INTEGER DEFAULT 0 NOT NULL " +
", timestamp TEXT NOT NULL)",
}; };
private static final String[] SQL_CREATE_INDEXES = { private static final String[] SQL_CREATE_INDEXES = {
"CREATE UNIQUE INDEX idx_subscription_url ON subscriptions (url)", "CREATE UNIQUE INDEX idx_subscription_url ON subscriptions (url)",
@@ -56,14 +67,41 @@ public class DatabaseHelper extends SQLiteOpenHelper {
"CREATE UNIQUE INDEX idx_url_history_url ON url_history (url)", "CREATE UNIQUE INDEX idx_url_history_url ON url_history (url)",
"CREATE UNIQUE INDEX idx_tag_name ON tags (name)", "CREATE UNIQUE INDEX idx_tag_name ON tags (name)",
"CREATE UNIQUE INDEX idx_view_history_url_device ON view_history (url, device)", "CREATE UNIQUE INDEX idx_view_history_url_device ON view_history (url, device)",
"CREATE INDEX idx_view_history_device ON view_history (device)" "CREATE INDEX idx_view_history_device ON view_history (device)",
"CREATE UNIQUE INDEX idx_notification_remote_id ON notifications (remote_id)",
"CREATE INDEX idx_notification_timestamp ON notifications (timestamp)"
}; };
private static final String[] SQL_V1_V2_UPGRADE = { private static final String[] SQL_V1_V2_UPGRADE = {
"ALTER TABLE view_history ADD COLUMN currency TEXT" "ALTER TABLE view_history ADD COLUMN currency TEXT"
}; };
private static final String[] SQL_V2_V3_UPGRADE = {
"CREATE TABLE notifications (" +
" id INTEGER PRIMARY KEY NOT NULL" +
", title TEXT" +
", description TEXT" +
", thumbnail_url TEXT" +
", target_url TEXT" +
", is_read INTEGER DEFAULT 0 NOT NULL" +
", timestamp TEXT NOT NULL)",
"CREATE INDEX idx_notification_timestamp ON notifications (timestamp)"
};
private static final String[] SQL_V3_V4_UPGRADE = {
"ALTER TABLE notifications ADD COLUMN remote_id INTEGER",
"CREATE UNIQUE INDEX idx_notification_remote_id ON notifications (remote_id)"
};
private static final String[] SQL_V4_V5_UPGRADE = {
"ALTER TABLE notifications ADD COLUMN rule TEXT",
"ALTER TABLE notifications ADD COLUMN is_seen TEXT"
};
private static final String[] SQL_V5_V6_UPGRADE = {
"ALTER TABLE notifications ADD COLUMN author_url TEXT"
};
private static final String SQL_INSERT_SUBSCRIPTION = "REPLACE INTO subscriptions (channel_name, url) VALUES (?, ?)"; private static final String SQL_INSERT_SUBSCRIPTION = "REPLACE INTO subscriptions (channel_name, url) VALUES (?, ?)";
private static final String SQL_CLEAR_SUBSCRIPTIONS = "DELETE FROM subscriptions";
private static final String SQL_DELETE_SUBSCRIPTION = "DELETE FROM subscriptions WHERE url = ?"; private static final String SQL_DELETE_SUBSCRIPTION = "DELETE FROM subscriptions WHERE url = ?";
private static final String SQL_GET_SUBSCRIPTIONS = "SELECT channel_name, url FROM subscriptions"; private static final String SQL_GET_SUBSCRIPTIONS = "SELECT channel_name, url FROM subscriptions";
@@ -72,6 +110,12 @@ public class DatabaseHelper extends SQLiteOpenHelper {
private static final String SQL_CLEAR_URL_HISTORY_BEFORE_TIME = "DELETE FROM url_history WHERE timestamp < ?"; private static final String SQL_CLEAR_URL_HISTORY_BEFORE_TIME = "DELETE FROM url_history WHERE timestamp < ?";
private static final String SQL_GET_RECENT_URL_HISTORY = "SELECT value, url, type FROM url_history ORDER BY timestamp DESC LIMIT 10"; private static final String SQL_GET_RECENT_URL_HISTORY = "SELECT value, url, type FROM url_history ORDER BY timestamp DESC LIMIT 10";
private static final String SQL_INSERT_NOTIFICATION = "REPLACE INTO notifications (remote_id, author_url, title, description, rule, target_url, is_read, is_seen, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_GET_NOTIFICATIONS = "SELECT id, remote_id, author_url, title, description, rule, target_url, is_read, is_seen, timestamp FROM notifications ORDER BY timestamp DESC LIMIT 500";
private static final String SQL_GET_UNREAD_NOTIFICATIONS_COUNT = "SELECT COUNT(id) FROM notifications WHERE is_read <> 1";
private static final String SQL_MARK_NOTIFICATIONS_READ = "UPDATE notifications SET is_read = 1 WHERE is_read = 0";
private static final String SQL_MARK_NOTIFICATION_READ_AND_SEEN = "UPDATE notifications SET is_read = 1, is_seen = 1 WHERE id = ?";
private static final String SQL_INSERT_VIEW_HISTORY = private static final String SQL_INSERT_VIEW_HISTORY =
"REPLACE INTO view_history (url, claim_id, claim_name, cost, currency, title, publisher_claim_id, publisher_name, publisher_title, thumbnail_url, device, release_time, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; "REPLACE INTO view_history (url, claim_id, claim_name, cost, currency, title, publisher_claim_id, publisher_name, publisher_title, thumbnail_url, device, release_time, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_GET_VIEW_HISTORY = private static final String SQL_GET_VIEW_HISTORY =
@@ -110,6 +154,26 @@ public class DatabaseHelper extends SQLiteOpenHelper {
db.execSQL(sql); db.execSQL(sql);
} }
} }
if (oldVersion < 3) {
for (String sql : SQL_V2_V3_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 4) {
for (String sql : SQL_V3_V4_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 5) {
for (String sql : SQL_V4_V5_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 6) {
for (String sql : SQL_V5_V6_UPGRADE) {
db.execSQL(sql);
}
}
} }
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
@@ -230,6 +294,9 @@ public class DatabaseHelper extends SQLiteOpenHelper {
public static void deleteSubscription(Subscription subscription, SQLiteDatabase db) { public static void deleteSubscription(Subscription subscription, SQLiteDatabase db) {
db.execSQL(SQL_DELETE_SUBSCRIPTION, new Object[] { subscription.getUrl() }); db.execSQL(SQL_DELETE_SUBSCRIPTION, new Object[] { subscription.getUrl() });
} }
public static void clearSubscriptions(SQLiteDatabase db) {
db.execSQL(SQL_CLEAR_SUBSCRIPTIONS);
}
public static List<Subscription> getSubscriptions(SQLiteDatabase db) { public static List<Subscription> getSubscriptions(SQLiteDatabase db) {
List<Subscription> subscriptions = new ArrayList<>(); List<Subscription> subscriptions = new ArrayList<>();
Cursor cursor = null; Cursor cursor = null;
@@ -247,4 +314,66 @@ public class DatabaseHelper extends SQLiteOpenHelper {
return subscriptions; return subscriptions;
} }
public static void createOrUpdateNotification(LbryNotification notification, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_NOTIFICATION, new Object[] {
notification.getRemoteId(),
notification.getAuthorUrl(),
notification.getTitle(),
notification.getDescription(),
notification.getRule(),
notification.getTargetUrl(),
notification.isRead() ? 1 : 0,
notification.isSeen() ? 1 : 0,
new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).format(notification.getTimestamp() != null ? notification.getTimestamp() : new Date())
});
}
public static List<LbryNotification> getNotifications(SQLiteDatabase db) {
List<LbryNotification> notifications = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_NOTIFICATIONS, null);
while (cursor.moveToNext()) {
LbryNotification notification = new LbryNotification();
int columnIndex = 0;
notification.setId(cursor.getLong(columnIndex++));
notification.setRemoteId(cursor.getLong(columnIndex++));
notification.setAuthorUrl(cursor.getString(columnIndex++));
notification.setTitle(cursor.getString(columnIndex++));
notification.setDescription(cursor.getString(columnIndex++));
notification.setRule(cursor.getString(columnIndex++));
notification.setTargetUrl(cursor.getString(columnIndex++));
notification.setRead(cursor.getInt(columnIndex++) == 1);
notification.setSeen(cursor.getInt(columnIndex++) == 1);
try {
notification.setTimestamp(new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).parse(cursor.getString(columnIndex++)));
} catch (ParseException ex) {
// invalid timestamp (which shouldn't happen). Skip this item
continue;
}
notifications.add(notification);
}
} finally {
Helper.closeCursor(cursor);
}
return notifications;
}
public static int getUnreadNotificationsCount(SQLiteDatabase db) {
int count = 0;
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_UNREAD_NOTIFICATIONS_COUNT, null);
if (cursor.moveToNext()) {
count = cursor.getInt(0);
}
} finally {
Helper.closeCursor(cursor);
}
return count;
}
public static void markNotificationsRead(SQLiteDatabase db) {
db.execSQL(SQL_MARK_NOTIFICATIONS_READ);
}
public static void markNotificationReadAndSeen(long notificationId, SQLiteDatabase db) {
db.execSQL(SQL_MARK_NOTIFICATION_READ_AND_SEEN, new Object[] { notificationId });
}
} }
@@ -0,0 +1,346 @@
package io.lbry.browser.dialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.text.HtmlCompat;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.tasks.wallet.SupportCreateTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import lombok.Setter;
public class CreateSupportDialogFragment extends BottomSheetDialogFragment implements WalletBalanceListener {
public static final String TAG = "CreateSupportDialog";
private MaterialButton sendButton;
private View cancelLink;
private TextInputEditText inputAmount;
private View inlineBalanceContainer;
private TextView inlineBalanceValue;
private ProgressBar sendProgress;
private InlineChannelSpinnerAdapter channelSpinnerAdapter;
private AppCompatSpinner channelSpinner;
private SwitchMaterial switchTip;
private boolean fetchingChannels;
private ProgressBar progressLoadingChannels;
@Setter
private CreateSupportListener listener;
@Setter
private Claim claim;
public static CreateSupportDialogFragment newInstance() {
return new CreateSupportDialogFragment();
}
private void disableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(false);
}
channelSpinner.setEnabled(false);
switchTip.setEnabled(false);
sendButton.setEnabled(false);
cancelLink.setEnabled(false);
}
private void enableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(true);
}
channelSpinner.setEnabled(true);
switchTip.setEnabled(true);
sendButton.setEnabled(true);
cancelLink.setEnabled(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_create_support, container, false);
inputAmount = view.findViewById(R.id.create_support_input_amount);
inlineBalanceContainer = view.findViewById(R.id.create_support_inline_balance_container);
inlineBalanceValue = view.findViewById(R.id.create_support_inline_balance_value);
sendProgress = view.findViewById(R.id.create_support_progress);
cancelLink = view.findViewById(R.id.create_support_cancel_link);
sendButton = view.findViewById(R.id.create_support_send);
channelSpinner = view.findViewById(R.id.create_support_channel_spinner);
switchTip = view.findViewById(R.id.create_support_make_tip_switch);
progressLoadingChannels = view.findViewById(R.id.create_support_channel_progress);
inputAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
inputAmount.setHint(hasFocus ? getString(R.string.zero) : "");
inlineBalanceContainer.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
inputAmount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
updateSendButtonText();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
updateInfoText();
updateSendButtonText();
String channel = null;
if (Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType())) {
channel = claim.getTitleOrName();
} else if (claim.getSigningChannel() != null) {
channel = claim.getPublisherTitle();
}
TextView titleView = view.findViewById(R.id.create_support_title);
String tipTitleText = Helper.isNullOrEmpty(channel) ? getString(R.string.send_a_tip) : getString(R.string.send_a_tip_to, channel);
titleView.setText(tipTitleText);
switchTip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
// show tip info
titleView.setText(tipTitleText);
updateSendButtonText();
} else {
// show support info
titleView.setText(R.string.support_this_content);
sendButton.setText(R.string.send_revocable_support);
}
updateInfoText();
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String amountString = Helper.getValue(inputAmount.getText());
if (Helper.isNullOrEmpty(amountString)) {
showError(getString(R.string.invalid_amount));
return;
}
BigDecimal amount = new BigDecimal(amountString);
if (amount.doubleValue() > Lbry.walletBalance.getAvailable().doubleValue()) {
showError(getString(R.string.insufficient_balance));
return;
}
if (amount.doubleValue() < Helper.MIN_SPEND) {
showError(getString(R.string.min_spend_required));
return;
}
Claim selectedChannel = (Claim) channelSpinner.getSelectedItem();
String channelId = !fetchingChannels && selectedChannel != null ? selectedChannel.getClaimId() : null;
boolean isTip = switchTip.isChecked();
SupportCreateTask task = new SupportCreateTask(
claim.getClaimId(), channelId, amount, isTip, sendProgress, new GenericTaskHandler() {
@Override
public void beforeStart() {
disableControls();
}
@Override
public void onSuccess() {
enableControls();
if (listener != null) {
listener.onSupportCreated(amount, isTip);
}
dismiss();
}
@Override
public void onError(Exception error) {
showError(error.getMessage());
enableControls();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
cancelLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
onWalletBalanceUpdated(Lbry.walletBalance);
updateInfoText();
return view;
}
private void updateSendButtonText() {
boolean isTip = switchTip.isChecked();
if (!isTip) {
sendButton.setText(R.string.send_revocable_support);
} else {
String amountString = Helper.getValue(inputAmount.getText());
double parsedAmount = Helper.parseDouble(amountString, 0);
sendButton.setText(parsedAmount == 0 ? getString(R.string.send_a_tip) : getString(R.string.send_lbc_tip, amountString));
}
}
private void updateInfoText() {
View view = getView();
if (view != null && switchTip != null) {
TextView infoText = view.findViewById(R.id.create_support_info);
boolean isTip = switchTip.isChecked();
infoText.setMovementMethod(LinkMovementMethod.getInstance());
if (!isTip) {
infoText.setText(HtmlCompat.fromHtml(getString(R.string.support_info), HtmlCompat.FROM_HTML_MODE_LEGACY));
} else if (claim != null) {
infoText.setText(HtmlCompat.fromHtml(
Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType()) ?
getString(R.string.send_tip_info_channel, claim.getTitleOrName()) :
getString(R.string.send_tip_info_content, claim.getTitleOrName()),
HtmlCompat.FROM_HTML_MODE_LEGACY));
}
}
}
private void fetchChannels() {
if (Lbry.ownChannels != null && Lbry.ownChannels.size() > 0) {
updateChannelList(Lbry.ownChannels);
return;
}
fetchingChannels = true;
disableChannelSpinner();
ClaimListTask task = new ClaimListTask(Claim.TYPE_CHANNEL, progressLoadingChannels, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = new ArrayList<>(claims);
updateChannelList(Lbry.ownChannels);
enableChannelSpinner();
fetchingChannels = false;
}
@Override
public void onError(Exception error) {
enableChannelSpinner();
fetchingChannels = false;
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void disableChannelSpinner() {
Helper.setViewEnabled(channelSpinner, false);
}
private void enableChannelSpinner() {
Helper.setViewEnabled(channelSpinner, true);
}
private void updateChannelList(List<Claim> channels) {
if (channelSpinnerAdapter == null) {
Context context = getContext();
if (context != null) {
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, new ArrayList<>(channels));
channelSpinnerAdapter.addAnonymousPlaceholder();
channelSpinnerAdapter.notifyDataSetChanged();
}
} else {
channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.addAnonymousPlaceholder();
channelSpinnerAdapter.notifyDataSetChanged();
}
if (channelSpinner != null) {
channelSpinner.setAdapter(channelSpinnerAdapter);
}
if (channelSpinnerAdapter != null && channelSpinner != null) {
if (channelSpinnerAdapter.getCount() > 1) {
channelSpinner.setSelection(1);
}
}
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
updateInfoText();
fetchChannels();
}
public void onPause() {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).removeWalletBalanceListener(this);
}
super.onPause();
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
public interface CreateSupportListener {
void onSupportCreated(BigDecimal amount, boolean isTip);
}
}
@@ -192,14 +192,16 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
private void loadChannels(List<Claim> channels) { private void loadChannels(List<Claim> channels) {
if (channelSpinnerAdapter == null) { if (channelSpinnerAdapter == null) {
Context context = getContext(); Context context = getContext();
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, channels); if (context != null) {
channelSpinnerAdapter.notifyDataSetChanged(); channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, channels);
channelSpinnerAdapter.notifyDataSetChanged();
}
} else { } else {
channelSpinnerAdapter.clear(); channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels); channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.notifyDataSetChanged(); channelSpinnerAdapter.notifyDataSetChanged();
} }
if (channelSpinner != null) { if (channelSpinner != null && channelSpinnerAdapter != null) {
channelSpinner.setAdapter(channelSpinnerAdapter); channelSpinner.setAdapter(channelSpinnerAdapter);
} }
} }
@@ -229,6 +231,11 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
showError(getString(R.string.insufficient_balance)); showError(getString(R.string.insufficient_balance));
return; return;
} }
if (bid.doubleValue() < Helper.MIN_DEPOSIT) {
String message = getResources().getQuantityString(R.plurals.min_deposit_required, 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(message);
return;
}
Claim channel = (Claim) channelSpinner.getSelectedItem(); Claim channel = (Claim) channelSpinner.getSelectedItem();
if (channel == null) { if (channel == null) {
@@ -1,198 +0,0 @@
package io.lbry.browser.dialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.core.text.HtmlCompat;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.tasks.wallet.SupportCreateTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import lombok.Setter;
public class SendTipDialogFragment extends BottomSheetDialogFragment implements WalletBalanceListener {
public static final String TAG = "SendTipDialog";
private MaterialButton sendButton;
private View cancelLink;
private TextInputEditText inputAmount;
private View inlineBalanceContainer;
private TextView inlineBalanceValue;
private ProgressBar sendProgress;
@Setter
private SendTipListener listener;
@Setter
private Claim claim;
public static SendTipDialogFragment newInstance() {
return new SendTipDialogFragment();
}
private void disableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(false);
}
sendButton.setEnabled(false);
cancelLink.setEnabled(false);
}
private void enableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(true);
}
sendButton.setEnabled(true);
cancelLink.setEnabled(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_send_tip, container, false);
inputAmount = view.findViewById(R.id.tip_input_amount);
inlineBalanceContainer = view.findViewById(R.id.tip_inline_balance_container);
inlineBalanceValue = view.findViewById(R.id.tip_inline_balance_value);
sendProgress = view.findViewById(R.id.tip_send_progress);
cancelLink = view.findViewById(R.id.tip_cancel_link);
sendButton = view.findViewById(R.id.tip_send);
inputAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
inputAmount.setHint(hasFocus ? getString(R.string.zero) : "");
inlineBalanceContainer.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
TextView infoText = view.findViewById(R.id.tip_info);
infoText.setMovementMethod(LinkMovementMethod.getInstance());
if (claim != null) {
infoText.setText(HtmlCompat.fromHtml(
Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType()) ?
getString(R.string.send_tip_info_channel, claim.getTitleOrName()) :
getString(R.string.send_tip_info_content, claim.getTitleOrName()),
HtmlCompat.FROM_HTML_MODE_LEGACY));
}
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String amountString = Helper.getValue(inputAmount.getText());
if (Helper.isNullOrEmpty(amountString)) {
showError(getString(R.string.invalid_amount));
return;
}
BigDecimal amount = new BigDecimal(amountString);
if (amount.doubleValue() > Lbry.walletBalance.getAvailable().doubleValue()) {
showError(getString(R.string.insufficient_balance));
return;
}
SupportCreateTask task = new SupportCreateTask(claim.getClaimId(), amount, true, sendProgress, new GenericTaskHandler() {
@Override
public void beforeStart() {
disableControls();
}
@Override
public void onSuccess() {
enableControls();
if (listener != null) {
listener.onTipSent(amount);
}
dismiss();
}
@Override
public void onError(Exception error) {
showError(error.getMessage());
enableControls();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
cancelLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
String channel = null;
if (Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType())) {
channel = claim.getTitleOrName();
} else if (claim.getSigningChannel() != null) {
channel = claim.getPublisherTitle();
}
((TextView) view.findViewById(R.id.tip_send_title)).setText(
Helper.isNullOrEmpty(channel) ? getString(R.string.send_a_tip) : getString(R.string.send_a_tip_to, channel)
);
onWalletBalanceUpdated(Lbry.walletBalance);
return view;
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
}
public void onPause() {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).removeWalletBalanceListener(this);
}
super.onPause();
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
public interface SendTipListener {
void onTipSent(BigDecimal amount);
}
}
@@ -0,0 +1,4 @@
package io.lbry.browser.exceptions;
public class AuthTokenInvalidatedException extends Exception {
}
@@ -7,4 +7,7 @@ public interface SignInListener {
void onPhoneAdded(String countryCode, String phoneNumber); void onPhoneAdded(String countryCode, String phoneNumber);
void onPhoneVerified(); void onPhoneVerified();
void onManualVerifyContinue(); void onManualVerifyContinue();
void onSkipQueueAction();
void onTwitterVerified();
void onManualProgress(boolean progress);
} }
@@ -54,6 +54,7 @@ public class Claim {
@EqualsAndHashCode.Include @EqualsAndHashCode.Include
private boolean placeholder; private boolean placeholder;
private boolean placeholderAnonymous; private boolean placeholderAnonymous;
private boolean loadingPlaceholder;
private boolean featured; private boolean featured;
private boolean unresolved; // used for featured private boolean unresolved; // used for featured
private String address; private String address;
@@ -1,21 +1,48 @@
package io.lbry.browser.model; package io.lbry.browser.model;
import android.util.Log;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.utils.Helper;
import lombok.Data; import lombok.Data;
@Data @Data
public class Comment { public class Comment {
private final String channelName, text, id, parentId; public static final double LBC_COST = 1;
public static final int MAX_LENGTH = 2000;
public Comment(String channelName, String text, String id, String parentId) { private Claim poster;
private String claimId;
private List<Comment> replies;
private long timestamp;
private String channelId;
private String channelName, text, id, parentId;
public Comment(String channelId, String channelName, String text, String id, String parentId) {
this.channelId = channelId;
this.channelName = channelName; this.channelName = channelName;
this.text = text; this.text = text;
this.id = id; this.id = id;
this.parentId = parentId; this.parentId = parentId;
this.replies = new ArrayList<>();
}
public Comment() {
replies = new ArrayList<>();
}
public void addReply(Comment reply) {
if (replies == null) {
replies = new ArrayList<>();
}
if (!replies.contains(reply)) {
replies.add(reply);
}
} }
public static Comment fromJSONObject(JSONObject jsonObject) { public static Comment fromJSONObject(JSONObject jsonObject) {
@@ -25,15 +52,17 @@ public class Comment {
parentId = jsonObject.getString("parent_id"); parentId = jsonObject.getString("parent_id");
} }
return new Comment( Comment comment = new Comment(
Helper.getJSONString("channel_id", null, jsonObject),
jsonObject.getString("channel_name"), jsonObject.getString("channel_name"),
jsonObject.getString("comment"), jsonObject.getString("comment"),
jsonObject.getString("comment_id"), jsonObject.getString("comment_id"),
parentId parentId
); );
comment.setClaimId(Helper.getJSONString("claim_id", null, jsonObject));
comment.setTimestamp(Helper.getJSONLong("timestamp", 0, jsonObject));
return comment;
} catch (JSONException ex) { } catch (JSONException ex) {
// TODO: Throw exception
Log.e("Comments", ex.toString());
return null; return null;
} }
} }
@@ -0,0 +1,9 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class TwitterOauth {
private String oauthToken;
private String oauthTokenSecret;
}
@@ -0,0 +1,40 @@
package io.lbry.browser.model.lbryinc;
import java.util.Comparator;
import java.util.Date;
import io.lbry.browser.model.Claim;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
public class LbryNotification implements Comparator<LbryNotification> {
private long id;
@EqualsAndHashCode.Include
private long remoteId;
private String title;
private String description;
private String thumbnailUrl;
private String rule;
private String targetUrl;
private boolean read;
private boolean seen;
private Date timestamp;
// only for comment notifications
private String authorUrl;
private Claim commentAuthor;
public int compare(LbryNotification a, LbryNotification b) {
long t1 = a.getTimestamp() != null ? a.getTimestamp().getTime() : 0;
long t2 = b.getTimestamp() != null ? b.getTimestamp().getTime() : 0;
if (t1 < t2) {
return -1;
}
if (t1 > t2) {
return 1;
}
return 0;
}
}
@@ -0,0 +1,9 @@
package io.lbry.browser.model.lbryinc;
import lombok.Data;
@Data
public class RewardVerified {
private long userId;
private boolean isRewardApproved;
}
@@ -0,0 +1,65 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;
import io.lbry.browser.utils.Helper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class BufferEventTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = "LbryBufferEvent";
private static final String ENDPOINT = "https://collector-service.api.lbry.tv/api/v1/events/video";
private String streamUrl;
private String userIdHash;
private long streamDuration;
private long streamPosition;
private long bufferDuration;
public BufferEventTask(String streamUrl, long streamDuration, long streamPosition, long bufferDuration, String userIdHash) {
this.streamUrl = streamUrl;
this.bufferDuration = bufferDuration;
this.streamDuration = streamDuration;
this.streamPosition = streamPosition;
this.userIdHash = userIdHash;
}
protected Void doInBackground(Void... params) {
JSONObject requestBody = new JSONObject();
JSONObject data = new JSONObject();
try {
data.put("url", streamUrl);
data.put("position", streamPosition);
data.put("stream_duration", streamDuration);
//data.put("duration", bufferDuration);
requestBody.put("device", "android");
requestBody.put("type", "buffering");
requestBody.put("client", userIdHash);
requestBody.put("data", data);
RequestBody body = RequestBody.create(requestBody.toString(), Helper.JSON_MEDIA_TYPE);
Request request = new Request.Builder().url(ENDPOINT).post(body).build();
OkHttpClient client = new OkHttpClient.Builder().
writeTimeout(60, TimeUnit.SECONDS).
readTimeout(60, TimeUnit.SECONDS).
build();
Response response = client.newCall(request).execute();
String responseString = response.body().string();
Log.d(TAG, String.format("buffer event sent: %s", responseString));
} catch (Exception ex) {
// we don't want to fail if a buffer event fails to register
Log.d(TAG, String.format("buffer event log failed: %s", ex.getMessage()), ex);
}
return null;
}
}
@@ -0,0 +1,103 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.Comment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.Lbryio;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class CommentCreateWithTipTask extends AsyncTask<Void, Void, Comment> {
private static final String STATUS_ENDPOINT = "https://comments.lbry.com";
private Comment comment;
private BigDecimal amount;
private View progressView;
private CommentCreateWithTipHandler handler;
private Exception error;
public CommentCreateWithTipTask(Comment comment, BigDecimal amount, View progressView, CommentCreateWithTipHandler handler) {
this.comment = comment;
this.amount = amount;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
public Comment doInBackground(Void... params) {
Comment createdComment = null;
try {
// check comments status endpoint
Request request = new Request.Builder().url(STATUS_ENDPOINT).build();
OkHttpClient client = new OkHttpClient.Builder().
writeTimeout(30, TimeUnit.SECONDS).
readTimeout(30, TimeUnit.SECONDS).
build();
Response response = client.newCall(request).execute();
JSONObject status = new JSONObject(response.body().string());
String statusText = Helper.getJSONString("text", null, status);
boolean isRunning = Helper.getJSONBoolean("is_running", false, status);
if (!"ok".equalsIgnoreCase(statusText) || !isRunning) {
throw new ApiCallException("The comment server is not available at this time. Please try again later.");
}
Map<String, Object> options = new HashMap<>();
options.put("blocking", true);
options.put("claim_id", comment.getClaimId());
options.put("amount", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(amount.doubleValue()));
options.put("tip", true);
Lbry.genericApiCall(Lbry.METHOD_SUPPORT_CREATE, options);
options = new HashMap<>();
options.put("comment", comment.getText());
options.put("claim_id", comment.getClaimId());
options.put("channel_id", comment.getChannelId());
options.put("channel_name", comment.getChannelName());
if (!Helper.isNullOrEmpty(comment.getParentId())) {
options.put("parent_id", comment.getParentId());
}
JSONObject jsonObject = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_COMMENT_CREATE, options);
createdComment = Comment.fromJSONObject(jsonObject);
} catch (ApiCallException | ClassCastException | IOException | JSONException ex) {
error = ex;
}
return createdComment;
}
protected void onPostExecute(Comment createdComment) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (createdComment != null) {
handler.onSuccess(createdComment);
} else {
handler.onError(error);
}
}
}
public interface CommentCreateWithTipHandler {
void onSuccess(Comment createdComment);
void onError(Exception error);
}
}
@@ -5,6 +5,6 @@ import java.util.List;
import io.lbry.browser.model.Comment; import io.lbry.browser.model.Comment;
public interface CommentListHandler { public interface CommentListHandler {
void onSuccess(List<Comment> comments); void onSuccess(List<Comment> comments, boolean hasReachedEnd);
void onError(Exception error); void onError(Exception error);
} }
@@ -45,16 +45,36 @@ public class CommentListTask extends AsyncTask<Void, Void, List<Comment>> {
options.put("claim_id", claim); options.put("claim_id", claim);
options.put("page", page); options.put("page", page);
options.put("page_size", pageSize); options.put("page_size", pageSize);
options.put("hidden", false);
options.put("include_replies", false); options.put("include_replies", false);
options.put("is_channel_signature_valid", true); options.put("is_channel_signature_valid", true);
options.put("skip_validation", true);
options.put("visible", true); options.put("visible", true);
options.put("hidden", false);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_COMMENT_LIST, options); JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_COMMENT_LIST, options);
JSONArray items = result.getJSONArray("items"); JSONArray items = result.getJSONArray("items");
List<Comment> children = new ArrayList<>();
comments = new ArrayList<>(); comments = new ArrayList<>();
for (int i = 0; i < items.length(); i++) { for (int i = 0; i < items.length(); i++) {
comments.add(Comment.fromJSONObject(items.getJSONObject(i))); Comment comment = Comment.fromJSONObject(items.getJSONObject(i));
if (comment != null) {
if (!Helper.isNullOrEmpty(comment.getParentId())) {
children.add(comment);
} else {
comments.add(comment);
}
}
}
for (Comment child : children) {
for (Comment parent : comments) {
if (parent.getId().equalsIgnoreCase(child.getParentId())) {
parent.addReply(child);
break;
}
}
} }
} catch (Exception ex) { } catch (Exception ex) {
error = ex; error = ex;
@@ -65,12 +85,10 @@ public class CommentListTask extends AsyncTask<Void, Void, List<Comment>> {
protected void onPostExecute(List<Comment> comments) { protected void onPostExecute(List<Comment> comments) {
Helper.setViewVisibility(progressBar, View.GONE); Helper.setViewVisibility(progressBar, View.GONE);
if (handler != null) { if (handler != null) {
if (comments != null && error == null) { if (comments != null) {
handler.onSuccess(comments); handler.onSuccess(comments, comments.size() < pageSize);
} else { } else {
handler.onError(error); handler.onError(error);
if (error != null) {
}
} }
} }
} }
@@ -34,9 +34,11 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
private List<Subscription> diff; private List<Subscription> diff;
private MergeSubscriptionsHandler handler; private MergeSubscriptionsHandler handler;
private Exception error; private Exception error;
private boolean replaceLocal;
public MergeSubscriptionsTask(List<Subscription> base, Context context, MergeSubscriptionsHandler handler) { public MergeSubscriptionsTask(List<Subscription> base, boolean replaceLocal, Context context, MergeSubscriptionsHandler handler) {
this.base = base; this.base = base;
this.replaceLocal = replaceLocal;
this.context = context; this.context = context;
this.handler = handler; this.handler = handler;
} }
@@ -53,10 +55,17 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
db = ((MainActivity) context).getDbHelper().getWritableDatabase(); db = ((MainActivity) context).getDbHelper().getWritableDatabase();
} }
if (db != null) { if (db != null) {
localSubs = DatabaseHelper.getSubscriptions(db); if (replaceLocal) {
for (Subscription sub : localSubs) { DatabaseHelper.clearSubscriptions(db);
if (!combined.contains(sub)) { for (Subscription sub : base) {
combined.add(sub); DatabaseHelper.createOrUpdateSubscription(sub, db);
}
} else {
localSubs = DatabaseHelper.getSubscriptions(db);
for (Subscription sub : localSubs) {
if (!combined.contains(sub)) {
combined.add(sub);
}
} }
} }
} }
@@ -64,6 +73,7 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
// fetch remote subscriptions // fetch remote subscriptions
JSONArray array = (JSONArray) Lbryio.parseResponse(Lbryio.call("subscription", "list", context)); JSONArray array = (JSONArray) Lbryio.parseResponse(Lbryio.call("subscription", "list", context));
if (array != null) { if (array != null) {
// check for any remote subs that may have been removed, and unsubscribe from them
for (int i = 0; i < array.length(); i++) { for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i); JSONObject item = array.getJSONObject(i);
String claimId = item.getString("claim_id"); String claimId = item.getString("claim_id");
@@ -77,39 +87,39 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
} }
} }
for (int i = 0; i < combined.size(); i++) { List<Subscription> remoteUnsubs = new ArrayList<>();
Subscription local = combined.get(i); List<Subscription> finalRemoteSubs = new ArrayList<>();
if (!remoteSubs.contains(local)) { if (remoteSubs.size() > 0) {
// add to remote subscriptions for (int i = 0; i < remoteSubs.size(); i++) {
try { Subscription sub = remoteSubs.get(i);
LbryUri uri = LbryUri.parse(local.getUrl()); if (!combined.contains(sub)) {
Map<String, String> options = new HashMap<>(); Map<String, String> options = new HashMap<>();
String channelClaimId = uri.getChannelClaimId(); LbryUri uri = LbryUri.tryParse(sub.getUrl());
String channelName = Helper.normalizeChannelName(local.getChannelName()); if (uri != null) {
if (!Helper.isNullOrEmpty(channelClaimId) && !Helper.isNullOrEmpty(channelName)) { options.put("claim_id", uri.getChannelClaimId());
options.put("claim_id", channelClaimId); Lbryio.parseResponse(Lbryio.call("subscription", "delete", options, context));
options.put("channel_name", channelName); remoteUnsubs.add(sub);
Lbryio.parseResponse(Lbryio.call("subscription", "new", options, context)); } else {
finalRemoteSubs.add(sub);
} }
} catch (LbryUriException | LbryioRequestException | LbryioResponseException ex) {
// pass
Log.e(TAG, String.format("subscription/new failed: %s", ex.getMessage()), ex);
} }
} }
} }
for (int i = 0; i < localSubs.size(); i++) { if (!replaceLocal) {
Subscription local = localSubs.get(i); for (int i = 0; i < localSubs.size(); i++) {
if (!base.contains(local) && !diff.contains(local)) { Subscription local = localSubs.get(i);
diff.add(local); if (!base.contains(local) && !diff.contains(local)) {
diff.add(local);
}
} }
} for (int i = 0; i < finalRemoteSubs.size(); i++) {
for (int i = 0; i < remoteSubs.size(); i++) { Subscription remote = finalRemoteSubs.get(i);
Subscription remote = remoteSubs.get(i); if (!combined.contains(remote)) {
if (!combined.contains(remote)) { combined.add(remote);
combined.add(remote); if (!diff.contains(remote)) {
if (!diff.contains(remote)) { diff.add(remote);
diff.add(remote); }
} }
} }
} }
@@ -0,0 +1,8 @@
package io.lbry.browser.tasks;
import io.lbry.browser.model.lbryinc.RewardVerified;
public interface RewardVerifiedHandler {
void onSuccess(RewardVerified rewardVerified);
void onError(Exception error);
}
@@ -0,0 +1,8 @@
package io.lbry.browser.tasks;
import io.lbry.browser.model.TwitterOauth;
public interface TwitterOauthHandler {
void onSuccess(TwitterOauth twitterOauth);
void onError(Exception error);
}
@@ -66,10 +66,15 @@ public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
if (excludeMature && knownTag.isMature()) { if (excludeMature && knownTag.isMature()) {
continue; continue;
} }
if ((knownTag.getLowercaseName().startsWith(filter) || knownTag.getLowercaseName().matches(filter)) && try {
(!tags.contains(knownTag) && if ((knownTag.getLowercaseName().startsWith(filter) ||
!Lbry.followedTags.contains(knownTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(knownTag)))) { knownTag.getLowercaseName().matches(filter)) &&
tags.add(knownTag); (!tags.contains(knownTag) && !Lbry.followedTags.contains(knownTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(knownTag)))
) {
tags.add(knownTag);
}
} catch (Exception ex) {
// continue
} }
} }
} }
@@ -18,12 +18,19 @@ import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry; import io.lbry.browser.utils.Lbry;
public class PurchaseListTask extends AsyncTask<Void, Void, List<Claim>> { public class PurchaseListTask extends AsyncTask<Void, Void, List<Claim>> {
private String claimId;
private int page; private int page;
private int pageSize; private int pageSize;
private ClaimSearchResultHandler handler; private ClaimSearchResultHandler handler;
private View progressView; private View progressView;
private Exception error; private Exception error;
public PurchaseListTask(String claimId, View progressView, ClaimSearchResultHandler handler) {
this.claimId = claimId;
this.progressView = progressView;
this.handler = handler;
}
public PurchaseListTask(int page, int pageSize, View progressView, ClaimSearchResultHandler handler) { public PurchaseListTask(int page, int pageSize, View progressView, ClaimSearchResultHandler handler) {
this.page = page; this.page = page;
this.pageSize = pageSize; this.pageSize = pageSize;
@@ -38,8 +45,15 @@ public class PurchaseListTask extends AsyncTask<Void, Void, List<Claim>> {
List<Claim> claims = null; List<Claim> claims = null;
try { try {
Map<String, Object> options = new HashMap<>(); Map<String, Object> options = new HashMap<>();
options.put("page", page); if (!Helper.isNullOrEmpty(claimId)) {
options.put("page_size", pageSize); options.put("claim_id", claimId);
}
if (page > 0) {
options.put("page", page);
}
if (pageSize > 0) {
options.put("page_size", pageSize);
}
options.put("resolve", true); options.put("resolve", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PURCHASE_LIST, options); JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PURCHASE_LIST, options);
@@ -47,9 +61,10 @@ public class PurchaseListTask extends AsyncTask<Void, Void, List<Claim>> {
claims = new ArrayList<>(); claims = new ArrayList<>();
for (int i = 0; i < items.length(); i++) { for (int i = 0; i < items.length(); i++) {
Claim claim = Claim.fromJSONObject(items.getJSONObject(i).getJSONObject("claim")); Claim claim = Claim.fromJSONObject(items.getJSONObject(i).getJSONObject("claim"));
claims.add(claim); if (!Helper.isNullOrEmpty(claim.getClaimId())) {
claims.add(claim);
Lbry.addClaimToCache(claim); Lbry.addClaimToCache(claim);
}
} }
} catch (ApiCallException | JSONException | ClassCastException ex) { } catch (ApiCallException | JSONException | ClassCastException ex) {
error = ex; error = ex;
@@ -0,0 +1,68 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import io.lbry.browser.MainActivity;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
import okhttp3.Response;
public class AndroidPurchaseTask extends AsyncTask<Void, Void, RewardVerified> {
private Context context;
private View progressView;
private String purchaseToken;
private RewardVerifiedHandler handler;
private Exception error;
public AndroidPurchaseTask(String purchaseToken, View progressView, Context context, RewardVerifiedHandler handler) {
this.purchaseToken = purchaseToken;
this.progressView = progressView;
this.context = context;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected RewardVerified doInBackground(Void... params) {
try {
Map<String, String> options = new HashMap<>();
options.put("purchase_token", purchaseToken);
JSONObject object = (JSONObject) Lbryio.parseResponse(Lbryio.call("verification", "android_purchase", options, context));
Type type = new TypeToken<RewardVerified>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
return gson.fromJson(object.toString(), type);
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(RewardVerified result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (result != null) {
handler.onSuccess(result);
} else {
handler.onError(error);
}
}
}
}
@@ -1,20 +1,23 @@
package io.lbry.browser.tasks.lbryinc; package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import io.lbry.browser.model.lbryinc.User; import io.lbry.browser.model.lbryinc.User;
import io.lbry.browser.utils.Lbryio; import io.lbry.browser.utils.Lbryio;
public class FetchCurrentUserTask extends AsyncTask<Void, Void, User> { public class FetchCurrentUserTask extends AsyncTask<Void, Void, User> {
private Context context;
private Exception error; private Exception error;
private FetchUserTaskHandler handler; private FetchUserTaskHandler handler;
public FetchCurrentUserTask(FetchUserTaskHandler handler) { public FetchCurrentUserTask(Context context, FetchUserTaskHandler handler) {
this.context = context;
this.handler = handler; this.handler = handler;
} }
protected User doInBackground(Void... params) { protected User doInBackground(Void... params) {
try { try {
return Lbryio.fetchCurrentUser(null); return Lbryio.fetchCurrentUser(context);
} catch (Exception ex) { } catch (Exception ex) {
error = ex; error = ex;
return null; return null;
@@ -0,0 +1,128 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import io.lbry.browser.MainActivity;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class NotificationListTask extends AsyncTask<Void, Void, List<LbryNotification>> {
private static final String TAG = "Notifications";
private Context context;
private ListNotificationsHandler handler;
private ProgressBar progressBar;
private Exception error;
public NotificationListTask(Context context, ProgressBar progressBar, ListNotificationsHandler handler) {
this.context = context;
this.progressBar = progressBar;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressBar, View.VISIBLE);
}
protected List<LbryNotification> doInBackground(Void... params) {
List<LbryNotification> notifications = new ArrayList<>();
SQLiteDatabase db = null;
try {
JSONArray array = (JSONArray) Lbryio.parseResponse(Lbryio.call("notification", "list", context));
if (array != null) {
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
if (item.has("notification_parameters")) {
LbryNotification notification = new LbryNotification();
JSONObject notificationParams = item.getJSONObject("notification_parameters");
if (notificationParams.has("device")) {
JSONObject device = notificationParams.getJSONObject("device");
notification.setTitle(Helper.getJSONString("title", null, device));
notification.setDescription(Helper.getJSONString("text", null, device));
notification.setTargetUrl(Helper.getJSONString("target", null, device));
}
if (notificationParams.has("dynamic") && !notificationParams.isNull("dynamic")) {
JSONObject dynamic = notificationParams.getJSONObject("dynamic");
if (dynamic.has("comment_author")) {
notification.setAuthorUrl(Helper.getJSONString("comment_author", null, dynamic));
}
if (dynamic.has("channelURI")) {
String channelUrl = Helper.getJSONString("channelURI", null, dynamic);
if (!Helper.isNullOrEmpty(channelUrl)) {
notification.setTargetUrl(channelUrl);
}
}
if (dynamic.has("hash") && "comment".equalsIgnoreCase(Helper.getJSONString("notification_rule", null, item))) {
notification.setTargetUrl(String.format("%s?comment_hash=%s", notification.getTargetUrl(), dynamic.getString("hash")));
}
}
notification.setRule(Helper.getJSONString("notification_rule", null, item));
notification.setRemoteId(Helper.getJSONLong("id", 0, item));
notification.setRead(Helper.getJSONBoolean("is_read", false, item));
notification.setSeen(Helper.getJSONBoolean("is_seen", false, item));
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(Helper.ISO_DATE_FORMAT_JSON, Locale.US);
notification.setTimestamp(dateFormat.parse(Helper.getJSONString("created_at", dateFormat.format(new Date()), item)));
} catch (ParseException ex) {
notification.setTimestamp(new Date());
}
if (notification.getRemoteId() > 0 && !Helper.isNullOrEmpty(notification.getDescription())) {
notifications.add(notification);
}
}
}
if (context instanceof MainActivity) {
db = ((MainActivity) context).getDbHelper().getWritableDatabase();
for (LbryNotification notification : notifications) {
DatabaseHelper.createOrUpdateNotification(notification, db);
}
}
}
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | SQLiteException | IllegalStateException ex) {
Log.e(TAG, ex.getMessage(), ex);
error = ex;
return null;
}
return notifications;
}
protected void onPostExecute(List<LbryNotification> notifications) {
Helper.setViewVisibility(progressBar, View.GONE);
if (handler != null) {
if (notifications != null) {
handler.onSuccess(notifications);
} else {
handler.onError(error);
}
}
}
public interface ListNotificationsHandler {
void onSuccess(List<LbryNotification> notifications);
void onError(Exception exception);
}
}
@@ -0,0 +1,47 @@
package io.lbry.browser.tasks.lbryinc;
import android.os.AsyncTask;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class NotificationUpdateTask extends AsyncTask<Void, Void, Boolean> {
private List<Long> ids;
private boolean seen;
private boolean read;
private boolean updateSeen;
public NotificationUpdateTask(List<Long> ids, boolean read) {
this(ids, read, false, false);
}
public NotificationUpdateTask(List<Long> ids, boolean read, boolean seen, boolean updateSeen) {
this.ids = ids;
this.read = read;
this.seen = seen;
this.updateSeen = updateSeen;
}
protected Boolean doInBackground(Void... params) {
Map<String, String> options = new HashMap<>();
options.put("notification_ids", Helper.joinL(ids, ","));
options.put("is_read", String.valueOf(read));
if (updateSeen) {
options.put("is_seen", String.valueOf(seen));
}
try {
Object result = Lbryio.parseResponse(Lbryio.call("notification", "edit", options, null));
return "ok".equalsIgnoreCase(result.toString());
} catch (LbryioResponseException | LbryioRequestException ex) {
}
return false;
}
}
@@ -0,0 +1,68 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import io.lbry.browser.model.TwitterOauth;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class TwitterVerifyTask extends AsyncTask<Void, Void, RewardVerified> {
private Context context;
private View progressView;
private TwitterOauth twitterOauth;
private RewardVerifiedHandler handler;
private Exception error;
public TwitterVerifyTask(TwitterOauth twitterOauth, View progressView, Context context, RewardVerifiedHandler handler) {
this.twitterOauth = twitterOauth;
this.progressView = progressView;
this.context = context;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected RewardVerified doInBackground(Void... params) {
try {
Map<String, String> options = new HashMap<>();
options.put("oauth_token", twitterOauth.getOauthToken());
options.put("oauth_token_secret", twitterOauth.getOauthTokenSecret());
JSONObject object = (JSONObject) Lbryio.parseResponse(Lbryio.call("verification", "twitter_verify", options, context));
Type type = new TypeToken<RewardVerified>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
return gson.fromJson(object.toString(), type);
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(RewardVerified result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (result != null) {
handler.onSuccess(result);
} else {
handler.onError(error);
}
}
}
}
@@ -1,20 +1,28 @@
package io.lbry.browser.tasks.verification; package io.lbry.browser.tasks.verification;
import android.content.Context;
import android.os.AsyncTask; import android.os.AsyncTask;
import io.lbry.browser.exceptions.AuthTokenInvalidatedException;
import io.lbry.browser.model.lbryinc.User; import io.lbry.browser.model.lbryinc.User;
import io.lbry.browser.utils.Lbryio; import io.lbry.browser.utils.Lbryio;
public class CheckUserEmailVerifiedTask extends AsyncTask<Void, Void, Boolean> { public class CheckUserEmailVerifiedTask extends AsyncTask<Void, Void, Boolean> {
private Context context;
private CheckUserEmailVerifiedHandler handler; private CheckUserEmailVerifiedHandler handler;
public CheckUserEmailVerifiedTask(CheckUserEmailVerifiedHandler handler) { public CheckUserEmailVerifiedTask(Context context, CheckUserEmailVerifiedHandler handler) {
this.context = context;
this.handler = handler; this.handler = handler;
} }
protected Boolean doInBackground(Void... params) { protected Boolean doInBackground(Void... params) {
User user = Lbryio.fetchCurrentUser(null); try {
return user != null && user.isHasVerifiedEmail(); User user = Lbryio.fetchCurrentUser(context);
return user != null && user.isHasVerifiedEmail();
} catch (AuthTokenInvalidatedException ex) {
return false;
}
} }
protected void onPostExecute(Boolean result) { protected void onPostExecute(Boolean result) {
@@ -0,0 +1,68 @@
package io.lbry.browser.tasks.verification;
import android.os.AsyncTask;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.http.GenericUrl;
import io.lbry.browser.VerificationActivity;
import io.lbry.browser.model.TwitterOauth;
import io.lbry.browser.tasks.TwitterOauthHandler;
import io.lbry.browser.utils.Helper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TwitterAccessTokenTask extends AsyncTask<Void, Void, String> {
private static final String ENDPOINT = "https://api.twitter.com/oauth/access_token";
private Exception error;
private String oauthParams;
private TwitterOauthHandler handler;
public TwitterAccessTokenTask(String oauthParams, TwitterOauthHandler handler) {
this.oauthParams = oauthParams;
this.handler = handler;
}
public String doInBackground(Void... params) {
try {
String url = String.format("%s?%s", ENDPOINT, oauthParams);
RequestBody body = RequestBody.create(new byte[0]);
Request request = new Request.Builder().url(url).post(body).build();
OkHttpClient client = new OkHttpClient.Builder().build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(String response) {
if (!Helper.isNullOrEmpty(response)) {
String[] pairs = response.split("&");
TwitterOauth twitterOauth = new TwitterOauth();
for (String pair : pairs) {
String[] parts = pair.split("=");
if (parts.length != 2) {
continue;
}
String key = parts[0];
String value = parts[1];
if ("oauth_token".equalsIgnoreCase(key)) {
twitterOauth.setOauthToken(value);
} else if ("oauth_token_secret".equalsIgnoreCase(key)) {
twitterOauth.setOauthTokenSecret(value);
}
}
handler.onSuccess(twitterOauth);
} else {
handler.onError(error);
}
}
}
@@ -0,0 +1,88 @@
package io.lbry.browser.tasks.verification;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Base64;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.http.GenericUrl;
import java.nio.charset.StandardCharsets;
import io.lbry.browser.VerificationActivity;
import io.lbry.browser.model.TwitterOauth;
import io.lbry.browser.tasks.TwitterOauthHandler;
import io.lbry.browser.utils.Helper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TwitterRequestTokenTask extends AsyncTask<Void, Void, String> {
private static final String ENDPOINT = "https://api.twitter.com/oauth/request_token";
private String consumerKey;
private String consumerSecret;
private Exception error;
private TwitterOauthHandler handler;
public TwitterRequestTokenTask(String consumerKey, String consumerSecret, TwitterOauthHandler handler) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.handler = handler;
}
public String doInBackground(Void... params) {
try {
OAuthHmacSigner signer = new OAuthHmacSigner();
signer.clientSharedSecret = new String(
Base64.decode(consumerSecret, Base64.NO_WRAP), StandardCharsets.UTF_8.name());
OAuthParameters oauthParams = new OAuthParameters();
oauthParams.callback = "https://lbry.tv";
oauthParams.consumerKey = new String(
Base64.decode(consumerKey, Base64.NO_WRAP), StandardCharsets.UTF_8.name());;
oauthParams.signatureMethod = "HMAC-SHA-1";
oauthParams.signer = signer;
oauthParams.computeNonce();
oauthParams.computeTimestamp();
oauthParams.computeSignature("POST", new GenericUrl(ENDPOINT));
RequestBody body = RequestBody.create(new byte[0]);
Request request = new Request.Builder().url(ENDPOINT).addHeader(
"Authorization", oauthParams.getAuthorizationHeader()).post(body).build();
OkHttpClient client = new OkHttpClient.Builder().build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(String response) {
if (!Helper.isNullOrEmpty(response)) {
String[] pairs = response.split("&");
TwitterOauth twitterOauth = new TwitterOauth();
for (String pair : pairs) {
String[] parts = pair.split("=");
if (parts.length != 2) {
continue;
}
String key = parts[0];
String value = parts[1];
if ("oauth_token".equalsIgnoreCase(key)) {
twitterOauth.setOauthToken(value);
} else if ("oauth_token_secret".equalsIgnoreCase(key)) {
twitterOauth.setOauthTokenSecret(value);
}
}
handler.onSuccess(twitterOauth);
} else {
handler.onError(error);
}
}
}
@@ -17,14 +17,16 @@ import io.lbry.browser.utils.Lbry;
public class SupportCreateTask extends AsyncTask<Void, Void, Boolean> { public class SupportCreateTask extends AsyncTask<Void, Void, Boolean> {
private String claimId; private String claimId;
private String channelId;
private BigDecimal amount; private BigDecimal amount;
private boolean tip; private boolean tip;
private View progressView; private View progressView;
private GenericTaskHandler handler; private GenericTaskHandler handler;
private Exception error; private Exception error;
public SupportCreateTask(String claimId, BigDecimal amount, boolean tip, View progressView, GenericTaskHandler handler) { public SupportCreateTask(String claimId, String channelId, BigDecimal amount, boolean tip, View progressView, GenericTaskHandler handler) {
this.claimId = claimId; this.claimId = claimId;
this.channelId = channelId;
this.amount = amount; this.amount = amount;
this.tip = tip; this.tip = tip;
this.progressView = progressView; this.progressView = progressView;
@@ -40,9 +42,13 @@ public class SupportCreateTask extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) { protected Boolean doInBackground(Void... params) {
try { try {
Map<String, Object> options = new HashMap<>(); Map<String, Object> options = new HashMap<>();
options.put("blocking", true);
options.put("claim_id", claimId); options.put("claim_id", claimId);
options.put("amount", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(amount.doubleValue())); options.put("amount", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(amount.doubleValue()));
options.put("tip", tip); options.put("tip", tip);
if (!Helper.isNullOrEmpty(channelId)) {
options.put("channel_id", channelId);
}
Lbry.genericApiCall(Lbry.METHOD_SUPPORT_CREATE, options); Lbry.genericApiCall(Lbry.METHOD_SUPPORT_CREATE, options);
} catch (ApiCallException ex) { } catch (ApiCallException ex) {
error = ex; error = ex;
@@ -107,7 +107,7 @@ public class SyncGetTask extends AsyncTask<Void, Void, WalletSync> {
if (applySyncChanges) { if (applySyncChanges) {
if (applySyncSuccessful) { if (applySyncSuccessful) {
handler.onSyncApplySuccess(syncHash, syncData); handler.onSyncApplySuccess(syncHash, syncData);
} else { } else if (syncApplyError != null) {
handler.onSyncApplyError(syncApplyError); handler.onSyncApplyError(syncApplyError);
} }
} }
@@ -29,7 +29,6 @@ public class UnlockTipsTask extends AsyncTask<Void, Void, Boolean> {
public Boolean doInBackground(Void... params) { public Boolean doInBackground(Void... params) {
List<String> txids = new ArrayList<>(); List<String> txids = new ArrayList<>();
List<String> claimIds = new ArrayList<>();
try { try {
Map<String, Object> options = new HashMap<>(); Map<String, Object> options = new HashMap<>();
@@ -42,18 +41,15 @@ public class UnlockTipsTask extends AsyncTask<Void, Void, Boolean> {
for (int i = 0; i < items.length(); i++) { for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i); JSONObject item = items.getJSONObject(i);
String txid = Helper.getJSONString("txid", null, item); String txid = Helper.getJSONString("txid", null, item);
String claimId = Helper.getJSONString("claim_id", null, item); if (!Helper.isNullOrEmpty(txid)) {
if (!Helper.isNullOrEmpty(txid) && !Helper.isNullOrEmpty(claimId)) {
txids.add(txid); txids.add(txid);
claimIds.add(claimId);
} }
} }
} }
if (txids.size() > 0 && txids.size() == claimIds.size()) { if (txids.size() > 0) {
options = new HashMap<>(); options = new HashMap<>();
options.put("txid", txids); options.put("txid", txids);
options.put("claim_id", claimIds);
options.put("blocking", true); options.put("blocking", true);
Lbry.genericApiCall(Lbry.METHOD_TXO_SPEND, options); Lbry.genericApiCall(Lbry.METHOD_TXO_SPEND, options);
} }
@@ -1,19 +1,36 @@
package io.lbry.browser.ui; package io.lbry.browser.ui;
import android.content.Context; import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View; import android.view.View;
import android.widget.TextView; import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.util.Map; import java.util.Map;
import io.lbry.browser.BuildConfig;
import io.lbry.browser.MainActivity; import io.lbry.browser.MainActivity;
import io.lbry.browser.R; import io.lbry.browser.R;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.WalletBalance; import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.claim.ChannelCreateUpdateTask;
import io.lbry.browser.tasks.claim.ClaimResultHandler;
import io.lbry.browser.tasks.lbryinc.LogPublishTask;
import io.lbry.browser.ui.wallet.RewardsFragment; import io.lbry.browser.ui.wallet.RewardsFragment;
import io.lbry.browser.utils.Helper; import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry; import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.LbryUri;
import lombok.Getter; import lombok.Getter;
import lombok.Setter; import lombok.Setter;
@@ -94,4 +111,132 @@ public class BaseFragment extends Fragment {
} }
} }
} }
public void showError(String message) {
Context context = getContext();
if (context != null) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
}
public void setupInlineChannelCreator(
View container,
TextInputEditText inputChannelName,
TextInputEditText inputDeposit,
View inlineBalanceView,
TextView inlineBalanceValue,
View linkCancel,
MaterialButton buttonCreate,
View progressView,
AppCompatSpinner channelSpinner,
InlineChannelSpinnerAdapter channelSpinnerAdapter) {
inputDeposit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
Helper.setViewVisibility(inlineBalanceView, hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
linkCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Helper.setViewText(inputChannelName, null);
Helper.setViewText(inputDeposit, null);
Helper.setViewVisibility(container, View.GONE);
}
});
buttonCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// validate deposit and channel name
String channelNameString = Helper.normalizeChannelName(Helper.getValue(inputChannelName.getText()));
Claim claimToSave = new Claim();
claimToSave.setName(channelNameString);
String channelName = claimToSave.getName().startsWith("@") ? claimToSave.getName().substring(1) : claimToSave.getName();
String depositString = Helper.getValue(inputDeposit.getText());
if ("@".equals(channelName) || Helper.isNullOrEmpty(channelName)) {
showError(getString(R.string.please_enter_channel_name));
return;
}
if (!LbryUri.isNameValid(channelName)) {
showError(getString(R.string.channel_name_invalid_characters));
return;
}
if (Helper.channelExists(channelName)) {
showError(getString(R.string.channel_name_already_created));
return;
}
double depositAmount = 0;
try {
depositAmount = Double.valueOf(depositString);
} catch (NumberFormatException ex) {
// pass
showError(getString(R.string.please_enter_valid_deposit));
return;
}
if (depositAmount == 0) {
String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(error);
return;
}
if (Lbry.walletBalance == null || Lbry.walletBalance.getAvailable().doubleValue() < depositAmount) {
showError(getString(R.string.deposit_more_than_balance));
return;
}
ChannelCreateUpdateTask task = new ChannelCreateUpdateTask(
claimToSave, new BigDecimal(depositString), false, progressView, new ClaimResultHandler() {
@Override
public void beforeStart() {
Helper.setViewEnabled(inputChannelName, false);
Helper.setViewEnabled(inputDeposit, false);
Helper.setViewEnabled(buttonCreate, false);
Helper.setViewEnabled(linkCancel, false);
}
@Override
public void onSuccess(Claim claimResult) {
if (!BuildConfig.DEBUG) {
LogPublishTask logPublishTask = new LogPublishTask(claimResult);
logPublishTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
// channel created
Bundle bundle = new Bundle();
bundle.putString("claim_id", claimResult.getClaimId());
bundle.putString("claim_name", claimResult.getName());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_CHANNEL_CREATE, bundle);
// add the claim to the channel list and set it as the selected item
if (channelSpinnerAdapter != null) {
channelSpinnerAdapter.add(claimResult);
}
if (channelSpinner != null && channelSpinnerAdapter != null) {
channelSpinner.setSelection(channelSpinnerAdapter.getCount() - 1);
}
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
}
@Override
public void onError(Exception error) {
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
showError(error.getMessage());
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
Helper.setViewText(inlineBalanceValue, Helper.shortCurrencyFormat(Lbry.walletBalance.getAvailable().doubleValue()));
}
} }
@@ -0,0 +1,734 @@
package io.lbry.browser.ui.channel;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.BuildConfig;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.ClaimListAdapter;
import io.lbry.browser.adapter.CommentListAdapter;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
import io.lbry.browser.listener.SdkStatusListener;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.Comment;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.CommentCreateWithTipTask;
import io.lbry.browser.tasks.CommentListHandler;
import io.lbry.browser.tasks.CommentListTask;
import io.lbry.browser.tasks.claim.ChannelCreateUpdateTask;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.tasks.claim.ClaimResultHandler;
import io.lbry.browser.tasks.claim.ResolveTask;
import io.lbry.browser.tasks.lbryinc.LogPublishTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Lbryio;
import lombok.Setter;
public class ChannelCommentsFragment extends Fragment implements SdkStatusListener, WalletBalanceListener {
@Setter
private Claim claim;
@Setter
private String commentHash;
private CommentListAdapter commentListAdapter;
private Comment replyToComment;
private View containerReplyToComment;
private TextView textReplyingTo;
private TextView textReplyToBody;
private View buttonClearReplyToComment;
private boolean postingComment;
private boolean fetchingChannels;
private View progressLoadingChannels;
private View progressPostComment;
private InlineChannelSpinnerAdapter commentChannelSpinnerAdapter;
private AppCompatSpinner commentChannelSpinner;
private TextInputEditText inputComment;
private TextView textCommentLimit;
private MaterialButton buttonPostComment;
private ImageView commentPostAsThumbnail;
private View commentPostAsNoThumbnail;
private TextView commentPostAsAlpha;
private View inlineChannelCreator;
private TextInputEditText inlineChannelCreatorInputName;
private TextInputEditText inlineChannelCreatorInputDeposit;
private View inlineChannelCreatorInlineBalance;
private TextView inlineChannelCreatorInlineBalanceValue;
private View inlineChannelCreatorCancelLink;
private View inlineChannelCreatorProgress;
private MaterialButton inlineChannelCreatorCreateButton;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_channel_comments, container, false);
containerReplyToComment = root.findViewById(R.id.comment_form_reply_to_container);
textReplyingTo = root.findViewById(R.id.comment_form_replying_to_text);
textReplyToBody = root.findViewById(R.id.comment_form_reply_to_body);
buttonClearReplyToComment = root.findViewById(R.id.comment_form_clear_reply_to);
commentChannelSpinner = root.findViewById(R.id.comment_form_channel_spinner);
progressLoadingChannels = root.findViewById(R.id.comment_form_channels_loading);
progressPostComment = root.findViewById(R.id.comment_form_post_progress);
inputComment = root.findViewById(R.id.comment_form_body);
textCommentLimit = root.findViewById(R.id.comment_form_text_limit);
buttonPostComment = root.findViewById(R.id.comment_form_post);
commentPostAsThumbnail = root.findViewById(R.id.comment_form_thumbnail);
commentPostAsNoThumbnail = root.findViewById(R.id.comment_form_no_thumbnail);
commentPostAsAlpha = root.findViewById(R.id.comment_form_thumbnail_alpha);
inlineChannelCreator = root.findViewById(R.id.container_inline_channel_form_create);
inlineChannelCreatorInputName = root.findViewById(R.id.inline_channel_form_input_name);
inlineChannelCreatorInputDeposit = root.findViewById(R.id.inline_channel_form_input_deposit);
inlineChannelCreatorInlineBalance = root.findViewById(R.id.inline_channel_form_inline_balance_container);
inlineChannelCreatorInlineBalanceValue = root.findViewById(R.id.inline_channel_form_inline_balance_value);
inlineChannelCreatorProgress = root.findViewById(R.id.inline_channel_form_create_progress);
inlineChannelCreatorCancelLink = root.findViewById(R.id.inline_channel_form_cancel_link);
inlineChannelCreatorCreateButton = root.findViewById(R.id.inline_channel_form_create_button);
RecyclerView commentList = root.findViewById(R.id.channel_comments_list);
commentList.setLayoutManager(new LinearLayoutManager(getContext()));
initCommentForm(root);
setupInlineChannelCreator(
inlineChannelCreator,
inlineChannelCreatorInputName,
inlineChannelCreatorInputDeposit,
inlineChannelCreatorInlineBalance,
inlineChannelCreatorInlineBalanceValue,
inlineChannelCreatorCancelLink,
inlineChannelCreatorCreateButton,
inlineChannelCreatorProgress,
commentChannelSpinner,
commentChannelSpinnerAdapter
);
return root;
}
public void onResume() {
super.onResume();
Context context = getContext();
if (!Lbry.SDK_READY) {
if (context instanceof MainActivity) {
((MainActivity) context).addSdkStatusListener(this);
}
} else {
onSdkReady();
}
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
checkAndLoadComments();
}
public void onStop() {
super.onStop();
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.removeSdkStatusListener(this);
activity.removeWalletBalanceListener(this);
}
}
private void checkCommentSdkInitializing() {
View root = getView();
if (root != null) {
TextView commentsSDKInitializing = root.findViewById(R.id.channel_comments_sdk_initializing);
Helper.setViewVisibility(commentsSDKInitializing, Lbry.SDK_READY ? View.GONE : View.VISIBLE);
}
}
@Override
public void onSdkReady() {
fetchChannels();
}
private void checkAndLoadComments() {
View root = getView();
if (root != null) {
RecyclerView commentsList = root.findViewById(R.id.channel_comments_list);
if (commentsList == null || commentsList.getAdapter() == null || commentsList.getAdapter().getItemCount() == 0) {
loadComments();
}
}
}
private void loadComments() {
View root = getView();
ProgressBar relatedLoading = root.findViewById(R.id.channel_comments_progress);
if (claim != null && root != null) {
CommentListTask task = new CommentListTask(1, 200, claim.getClaimId(), relatedLoading, new CommentListHandler() {
@Override
public void onSuccess(List<Comment> comments, boolean hasReachedEnd) {
Context ctx = getContext();
View root = getView();
if (ctx != null && root != null) {
commentListAdapter = new CommentListAdapter(comments, ctx);
commentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
if (!Helper.isNullOrEmpty(claim.getName()) &&
claim.getName().startsWith("@") &&
ctx instanceof MainActivity) {
((MainActivity) ctx).openChannelClaim(claim);
}
}
});
commentListAdapter.setReplyListener(new CommentListAdapter.ReplyClickListener() {
@Override
public void onReplyClicked(Comment comment) {
setReplyToComment(comment);
}
});
RecyclerView relatedContentList = root.findViewById(R.id.channel_comments_list);
relatedContentList.setAdapter(commentListAdapter);
commentListAdapter.notifyDataSetChanged();
checkNoComments();
resolveCommentPosters();
scrollToCommentHash();
}
}
@Override
public void onError(Exception error) {
// pass
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private void scrollToCommentHash() {
View root = getView();
// check for the position of commentHash if set
if (root != null && !Helper.isNullOrEmpty(commentHash) && commentListAdapter != null && commentListAdapter.getItemCount() > 0) {
RecyclerView commentList = root.findViewById(R.id.channel_comments_list);
int position = commentListAdapter.getPositionForComment(commentHash);
if (position > -1 && commentList.getLayoutManager() != null) {
NestedScrollView scrollView = root.findViewById(R.id.channel_comments_area);
scrollView.requestChildFocus(commentList, commentList);
commentList.getLayoutManager().scrollToPosition(position);
}
}
}
private void resolveCommentPosters() {
if (commentListAdapter != null) {
List<String> urlsToResolve = new ArrayList<>(commentListAdapter.getClaimUrlsToResolve());
if (urlsToResolve.size() > 0) {
ResolveTask task = new ResolveTask(urlsToResolve, Lbry.SDK_CONNECTION_STRING, null, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
if (commentListAdapter != null) {
for (Claim claim : claims) {
if (claim.getClaimId() != null) {
commentListAdapter.updatePosterForComment(claim.getClaimId(), claim);
}
}
commentListAdapter.notifyDataSetChanged();
}
}
@Override
public void onError(Exception error) {
// pass
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineChannelCreatorInlineBalanceValue != null) {
inlineChannelCreatorInlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void fetchChannels() {
if (Lbry.ownChannels != null && Lbry.ownChannels.size() > 0) {
updateChannelList(Lbry.ownChannels);
return;
}
fetchingChannels = true;
disableChannelSpinner();
ClaimListTask task = new ClaimListTask(Claim.TYPE_CHANNEL, progressLoadingChannels, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = new ArrayList<>(claims);
updateChannelList(Lbry.ownChannels);
enableChannelSpinner();
fetchingChannels = false;
}
@Override
public void onError(Exception error) {
enableChannelSpinner();
fetchingChannels = false;
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void disableChannelSpinner() {
Helper.setViewEnabled(commentChannelSpinner, false);
hideInlineChannelCreator();
}
private void enableChannelSpinner() {
Helper.setViewEnabled(commentChannelSpinner, true);
if (commentChannelSpinner != null) {
Claim selectedClaim = (Claim) commentChannelSpinner.getSelectedItem();
if (selectedClaim != null) {
if (selectedClaim.isPlaceholder()) {
showInlineChannelCreator();
} else {
hideInlineChannelCreator();
}
}
}
}
private void showInlineChannelCreator() {
Helper.setViewVisibility(inlineChannelCreator, View.VISIBLE);
}
private void hideInlineChannelCreator() {
Helper.setViewVisibility(inlineChannelCreator, View.GONE);
}
private void updateChannelList(List<Claim> channels) {
if (commentChannelSpinnerAdapter == null) {
Context context = getContext();
if (context != null) {
commentChannelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, new ArrayList<>(channels));
commentChannelSpinnerAdapter.addPlaceholder(false);
commentChannelSpinnerAdapter.notifyDataSetChanged();
}
} else {
commentChannelSpinnerAdapter.clear();
commentChannelSpinnerAdapter.addAll(channels);
commentChannelSpinnerAdapter.addPlaceholder(false);
commentChannelSpinnerAdapter.notifyDataSetChanged();
}
if (commentChannelSpinner != null) {
commentChannelSpinner.setAdapter(commentChannelSpinnerAdapter);
}
if (commentChannelSpinnerAdapter != null && commentChannelSpinner != null) {
if (commentChannelSpinnerAdapter.getCount() > 1) {
commentChannelSpinner.setSelection(1);
}
}
}
private void initCommentForm(View root) {
double amount = Comment.LBC_COST;
String buttonText = getResources().getQuantityString(R.plurals.post_for_credits, amount == 1 ? 1 : 2, Helper.LBC_CURRENCY_FORMAT.format(amount));
buttonPostComment.setText(buttonText);
textCommentLimit.setText(String.format("%d / %d", Helper.getValue(inputComment.getText()).length(), Comment.MAX_LENGTH));
buttonClearReplyToComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clearReplyToComment();
}
});
buttonPostComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!Lbry.SDK_READY) {
Snackbar.make(root.findViewById(R.id.channel_comments_area), R.string.sdk_initializing_functionality, Snackbar.LENGTH_LONG).show();
return;
}
validateAndCheckPostComment(amount);
}
});
inputComment.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
int len = charSequence.length();
textCommentLimit.setText(String.format("%d / %d", len, Comment.MAX_LENGTH));
}
@Override
public void afterTextChanged(Editable editable) {
}
});
commentChannelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
Object item = adapterView.getItemAtPosition(position);
if (item instanceof Claim) {
Claim claim = (Claim) item;
if (claim.isPlaceholder()) {
if (!fetchingChannels) {
showInlineChannelCreator();
}
} else {
hideInlineChannelCreator();
updatePostAsChannel(claim);
}
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void validateAndCheckPostComment(double amount) {
String comment = Helper.getValue(inputComment.getText());
Claim channel = (Claim) commentChannelSpinner.getSelectedItem();
if (Helper.isNullOrEmpty(comment)) {
showError(getString(R.string.please_enter_comment));
return;
}
if (channel == null || Helper.isNullOrEmpty(channel.getClaimId())) {
showError(getString(R.string.please_select_channel));
return;
}
if (Lbry.walletBalance == null || amount > Lbry.walletBalance.getAvailable().doubleValue()) {
showError(getString(R.string.insufficient_balance));
return;
}
Context context = getContext();
if (context != null) {
String titleText = getResources().getQuantityString(
R.plurals.post_and_tip,
amount == 1 ? 1 : 2,
Helper.LBC_CURRENCY_FORMAT.format(amount));
String confirmText = getResources().getQuantityString(
R.plurals.confirm_post_comment,
amount == 1 ? 1 : 2,
Helper.LBC_CURRENCY_FORMAT.format(amount),
claim.getTitleOrName());
AlertDialog.Builder builder = new AlertDialog.Builder(context).
setTitle(titleText).
setMessage(confirmText)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
postComment(amount);
}
}).setNegativeButton(R.string.no, null);
builder.show();
}
}
private void updatePostAsChannel(Claim channel) {
boolean hasThumbnail = !Helper.isNullOrEmpty(channel.getThumbnailUrl());
Helper.setViewVisibility(commentPostAsThumbnail, hasThumbnail ? View.VISIBLE : View.INVISIBLE);
Helper.setViewVisibility(commentPostAsNoThumbnail, !hasThumbnail ? View.VISIBLE : View.INVISIBLE);
Helper.setViewText(commentPostAsAlpha, channel.getName() != null ? channel.getName().substring(1, 2).toUpperCase() : null);
Context context = getContext();
int bgColor = Helper.generateRandomColorForValue(channel.getClaimId());
Helper.setIconViewBackgroundColor(commentPostAsNoThumbnail, bgColor, false, context);
if (hasThumbnail && context != null) {
Glide.with(context.getApplicationContext()).
asBitmap().
load(channel.getThumbnailUrl()).
apply(RequestOptions.circleCropTransform()).
into(commentPostAsThumbnail);
}
}
private void beforePostComment() {
postingComment = true;
Helper.setViewEnabled(commentChannelSpinner, false);
Helper.setViewEnabled(inputComment, false);
Helper.setViewEnabled(buttonClearReplyToComment, false);
Helper.setViewEnabled(buttonPostComment, false);
}
private void afterPostComment() {
Helper.setViewEnabled(commentChannelSpinner, true);
Helper.setViewEnabled(inputComment, true);
Helper.setViewEnabled(buttonClearReplyToComment, true);
Helper.setViewEnabled(buttonPostComment, true);
postingComment = false;
}
private Comment buildPostComment() {
Comment comment = new Comment();
Claim channel = (Claim) commentChannelSpinner.getSelectedItem();
comment.setClaimId(claim.getClaimId());
comment.setChannelId(channel.getClaimId());
comment.setChannelName(channel.getName());
comment.setText(Helper.getValue(inputComment.getText()));
comment.setPoster(channel);
if (replyToComment != null) {
comment.setParentId(replyToComment.getId());
}
return comment;
}
private void setReplyToComment(Comment comment) {
replyToComment = comment;
Helper.setViewText(textReplyingTo, getString(R.string.replying_to, comment.getChannelName()));
Helper.setViewText(textReplyToBody, comment.getText());
Helper.setViewVisibility(containerReplyToComment, View.VISIBLE);
inputComment.requestFocus();
Context context = getContext();
if (context != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(inputComment, InputMethodManager.SHOW_FORCED);
}
}
private void clearReplyToComment() {
Helper.setViewText(textReplyingTo, null);
Helper.setViewText(textReplyToBody, null);
Helper.setViewVisibility(containerReplyToComment, View.GONE);
replyToComment = null;
}
private void postComment(double tipAmount) {
if (postingComment) {
return;
}
Comment comment = buildPostComment();
// only use 2 decimal places
BigDecimal amount = new BigDecimal(String.valueOf(tipAmount));
beforePostComment();
CommentCreateWithTipTask task = new CommentCreateWithTipTask(comment, amount, progressPostComment, new CommentCreateWithTipTask.CommentCreateWithTipHandler() {
@Override
public void onSuccess(Comment createdComment) {
inputComment.setText(null);
clearReplyToComment();
if (commentListAdapter != null) {
createdComment.setPoster(comment.getPoster());
if (!Helper.isNullOrEmpty(createdComment.getParentId())) {
commentListAdapter.addReply(createdComment);
} else {
commentListAdapter.insert(0, createdComment);
}
}
afterPostComment();
checkNoComments();
Bundle bundle = new Bundle();
bundle.putDouble("amount", amount.doubleValue());
bundle.putString("claim_id", claim != null ? claim.getClaimId() : null);
bundle.putString("claim_name", claim != null ? claim.getName() : null);
LbryAnalytics.logEvent(LbryAnalytics.EVENT_COMMENT_CREATE, bundle);
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).showMessage(R.string.comment_posted);
}
}
@Override
public void onError(Exception error) {
try {
showError(error != null ? error.getMessage() : getString(R.string.comment_error));
} catch (IllegalStateException ex) {
// pass
}
afterPostComment();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void showError(String message) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).showError(message);
}
}
private void checkNoComments() {
View root = getView();
if (root != null) {
Helper.setViewVisibility(root.findViewById(R.id.channel_no_comments),
commentListAdapter == null || commentListAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
}
private void setupInlineChannelCreator(
View container,
TextInputEditText inputChannelName,
TextInputEditText inputDeposit,
View inlineBalanceView,
TextView inlineBalanceValue,
View linkCancel,
MaterialButton buttonCreate,
View progressView,
AppCompatSpinner channelSpinner,
InlineChannelSpinnerAdapter channelSpinnerAdapter) {
inputDeposit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
Helper.setViewVisibility(inlineBalanceView, hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
linkCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Helper.setViewText(inputChannelName, null);
Helper.setViewText(inputDeposit, null);
Helper.setViewVisibility(container, View.GONE);
}
});
buttonCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// validate deposit and channel name
String channelNameString = Helper.normalizeChannelName(Helper.getValue(inputChannelName.getText()));
Claim claimToSave = new Claim();
claimToSave.setName(channelNameString);
String channelName = claimToSave.getName().startsWith("@") ? claimToSave.getName().substring(1) : claimToSave.getName();
String depositString = Helper.getValue(inputDeposit.getText());
if ("@".equals(channelName) || Helper.isNullOrEmpty(channelName)) {
showError(getString(R.string.please_enter_channel_name));
return;
}
if (!LbryUri.isNameValid(channelName)) {
showError(getString(R.string.channel_name_invalid_characters));
return;
}
if (Helper.channelExists(channelName)) {
showError(getString(R.string.channel_name_already_created));
return;
}
double depositAmount = 0;
try {
depositAmount = Double.valueOf(depositString);
} catch (NumberFormatException ex) {
// pass
showError(getString(R.string.please_enter_valid_deposit));
return;
}
if (depositAmount == 0) {
String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(error);
return;
}
if (Lbry.walletBalance == null || Lbry.walletBalance.getAvailable().doubleValue() < depositAmount) {
showError(getString(R.string.deposit_more_than_balance));
return;
}
ChannelCreateUpdateTask task = new ChannelCreateUpdateTask(
claimToSave, new BigDecimal(depositString), false, progressView, new ClaimResultHandler() {
@Override
public void beforeStart() {
Helper.setViewEnabled(inputChannelName, false);
Helper.setViewEnabled(inputDeposit, false);
Helper.setViewEnabled(buttonCreate, false);
Helper.setViewEnabled(linkCancel, false);
}
@Override
public void onSuccess(Claim claimResult) {
if (!BuildConfig.DEBUG) {
LogPublishTask logPublishTask = new LogPublishTask(claimResult);
logPublishTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
// channel created
Bundle bundle = new Bundle();
bundle.putString("claim_id", claimResult.getClaimId());
bundle.putString("claim_name", claimResult.getName());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_CHANNEL_CREATE, bundle);
// add the claim to the channel list and set it as the selected item
if (channelSpinnerAdapter != null) {
channelSpinnerAdapter.add(claimResult);
}
if (channelSpinner != null && channelSpinnerAdapter != null) {
channelSpinner.setSelection(channelSpinnerAdapter.getCount() - 1);
}
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
}
@Override
public void onError(Exception error) {
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
showError(error.getMessage());
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
Helper.setViewText(inlineBalanceValue, Helper.shortCurrencyFormat(Lbry.walletBalance.getAvailable().doubleValue()));
}
}
@@ -65,7 +65,7 @@ public class ChannelContentFragment extends Fragment implements DownloadActionLi
ViewGroup container, Bundle savedInstanceState) { ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_channel_content, container, false); View root = inflater.inflate(R.layout.fragment_channel_content, container, false);
currentSortBy = ContentSortDialogFragment.ITEM_SORT_BY_TRENDING; currentSortBy = ContentSortDialogFragment.ITEM_SORT_BY_NEW;
currentContentFrom = ContentFromDialogFragment.ITEM_FROM_PAST_WEEK; currentContentFrom = ContentFromDialogFragment.ITEM_FROM_PAST_WEEK;
sortLink = root.findViewById(R.id.channel_content_sort_link); sortLink = root.findViewById(R.id.channel_content_sort_link);
@@ -223,7 +223,7 @@ public class ChannelContentFragment extends Fragment implements DownloadActionLi
(List) null, (List) null,
null, null,
canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS), canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),
Arrays.asList(channelId), !Helper.isNullOrEmpty(channelId) ? Arrays.asList(channelId) : null,
null, null,
getContentSortOrder(), getContentSortOrder(),
contentReleaseTime, contentReleaseTime,
@@ -259,22 +259,25 @@ public class ChannelContentFragment extends Fragment implements DownloadActionLi
@Override @Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) { public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (contentListAdapter == null) { if (contentListAdapter == null) {
contentListAdapter = new ClaimListAdapter(claims, getContext()); Context context = getContext();
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() { if (context != null) {
@Override contentListAdapter = new ClaimListAdapter(claims, context);
public void onClaimClicked(Claim claim) { contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
Context context = getContext(); @Override
if (context instanceof MainActivity) { public void onClaimClicked(Claim claim) {
MainActivity activity = (MainActivity) context; Context context = getContext();
if (claim.getName().startsWith("@")) { if (context instanceof MainActivity) {
// channel claim MainActivity activity = (MainActivity) context;
activity.openChannelClaim(claim); if (claim.getName().startsWith("@")) {
} else { // channel claim
activity.openFileClaim(claim); activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
} }
} }
} });
}); }
} else { } else {
contentListAdapter.addItems(claims); contentListAdapter.addItems(claims);
} }
@@ -140,7 +140,6 @@ public class ChannelFormFragment extends BaseFragment implements
Context context = getContext(); Context context = getContext();
FlexboxLayoutManager flm1 = new FlexboxLayoutManager(context); FlexboxLayoutManager flm1 = new FlexboxLayoutManager(context);
FlexboxLayoutManager flm2 = new FlexboxLayoutManager(context); FlexboxLayoutManager flm2 = new FlexboxLayoutManager(context);
FlexboxLayoutManager flm3 = new FlexboxLayoutManager(context);
addedTagsList = root.findViewById(R.id.form_added_tags); addedTagsList = root.findViewById(R.id.form_added_tags);
addedTagsList.setLayoutManager(flm1); addedTagsList.setLayoutManager(flm1);
suggestedTagsList = root.findViewById(R.id.form_suggested_tags); suggestedTagsList = root.findViewById(R.id.form_suggested_tags);
@@ -326,7 +325,7 @@ public class ChannelFormFragment extends BaseFragment implements
showError(getString(R.string.please_enter_valid_deposit)); showError(getString(R.string.please_enter_valid_deposit));
return; return;
} }
if (depositAmount == 0) { if (depositAmount < Helper.MIN_DEPOSIT) {
String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT)); String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(error); showError(error);
return; return;
@@ -377,13 +376,6 @@ public class ChannelFormFragment extends BaseFragment implements
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} }
private void showError(String message) {
Context context = getContext();
if (context != null) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
}
public void checkPermissionsAndLaunchFilePicker(boolean isCover) { public void checkPermissionsAndLaunchFilePicker(boolean isCover) {
Context context = getContext(); Context context = getContext();
if (MainActivity.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, context)) { if (MainActivity.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, context)) {
@@ -6,16 +6,15 @@ import android.content.Intent;
import android.graphics.Color; import android.graphics.Color;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity; import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter; import androidx.viewpager2.adapter.FragmentStateAdapter;
@@ -36,7 +35,7 @@ import java.util.Map;
import io.lbry.browser.MainActivity; import io.lbry.browser.MainActivity;
import io.lbry.browser.R; import io.lbry.browser.R;
import io.lbry.browser.dialog.SendTipDialogFragment; import io.lbry.browser.dialog.CreateSupportDialogFragment;
import io.lbry.browser.exceptions.LbryUriException; import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.listener.FetchChannelsListener; import io.lbry.browser.listener.FetchChannelsListener;
import io.lbry.browser.model.Claim; import io.lbry.browser.model.Claim;
@@ -50,6 +49,7 @@ import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ResolveTask; import io.lbry.browser.tasks.claim.ResolveTask;
import io.lbry.browser.tasks.lbryinc.FetchStatCountTask; import io.lbry.browser.tasks.lbryinc.FetchStatCountTask;
import io.lbry.browser.ui.BaseFragment; import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.ui.controls.OutlineIconView;
import io.lbry.browser.ui.controls.SolidIconView; import io.lbry.browser.ui.controls.SolidIconView;
import io.lbry.browser.ui.findcontent.FollowingFragment; import io.lbry.browser.ui.findcontent.FollowingFragment;
import io.lbry.browser.utils.Helper; import io.lbry.browser.utils.Helper;
@@ -62,7 +62,7 @@ import lombok.SneakyThrows;
public class ChannelFragment extends BaseFragment implements FetchChannelsListener { public class ChannelFragment extends BaseFragment implements FetchChannelsListener {
private Claim claim; private Claim claim;
private boolean subscribing; private boolean subscribing;
private String url; private String currentUrl;
private View layoutResolving; private View layoutResolving;
private View layoutDisplayArea; private View layoutDisplayArea;
@@ -81,10 +81,14 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private View buttonTip; private View buttonTip;
private View buttonFollowUnfollow; private View buttonFollowUnfollow;
private int subCount; private int subCount;
private SolidIconView iconFollowUnfollow; private OutlineIconView iconFollow;
private SolidIconView iconUnfollow;
private View layoutNothingAtLocation; private View layoutNothingAtLocation;
private View layoutLoadingState; private View layoutLoadingState;
// if this is set, scroll to the specific comment on load
private String commentHash;
public View onCreateView(@NonNull LayoutInflater inflater, public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) { ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_channel, container, false); View root = inflater.inflate(R.layout.fragment_channel, container, false);
@@ -106,7 +110,8 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
buttonShare = root.findViewById(R.id.channel_view_share); buttonShare = root.findViewById(R.id.channel_view_share);
buttonTip = root.findViewById(R.id.channel_view_tip); buttonTip = root.findViewById(R.id.channel_view_tip);
buttonFollowUnfollow = root.findViewById(R.id.channel_view_follow_unfollow); buttonFollowUnfollow = root.findViewById(R.id.channel_view_follow_unfollow);
iconFollowUnfollow = root.findViewById(R.id.channel_view_icon_follow_unfollow); iconFollow = root.findViewById(R.id.channel_view_icon_follow);
iconUnfollow = root.findViewById(R.id.channel_view_icon_unfollow);
tabPager = root.findViewById(R.id.channel_view_pager); tabPager = root.findViewById(R.id.channel_view_pager);
tabLayout = root.findViewById(R.id.channel_view_tabs); tabLayout = root.findViewById(R.id.channel_view_tabs);
@@ -174,21 +179,24 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
} }
if (claim != null) { if (claim != null) {
SendTipDialogFragment dialog = SendTipDialogFragment.newInstance(); CreateSupportDialogFragment dialog = CreateSupportDialogFragment.newInstance();
dialog.setClaim(claim); dialog.setClaim(claim);
dialog.setListener(new SendTipDialogFragment.SendTipListener() { dialog.setListener(new CreateSupportDialogFragment.CreateSupportListener() {
@Override @Override
public void onTipSent(BigDecimal amount) { public void onSupportCreated(BigDecimal amount, boolean isTip) {
double sentAmount = amount.doubleValue(); double sentAmount = amount.doubleValue();
String message = getResources().getQuantityString( View view = getView();
R.plurals.you_sent_a_tip, sentAmount == 1.0 ? 1 : 2, if (view != null) {
new DecimalFormat("#,###.##").format(sentAmount)); String message = getResources().getQuantityString(
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).show(); isTip ? R.plurals.you_sent_a_tip : R.plurals.you_sent_a_support, sentAmount == 1.0 ? 1 : 2,
new DecimalFormat("#,###.##").format(sentAmount));
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
}
} }
}); });
Context context = getContext(); Context context = getContext();
if (context instanceof MainActivity) { if (context instanceof MainActivity) {
dialog.show(((MainActivity) context).getSupportFragmentManager(), SendTipDialogFragment.TAG); dialog.show(((MainActivity) context).getSupportFragmentManager(), CreateSupportDialogFragment.TAG);
} }
} }
} }
@@ -272,13 +280,8 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private void checkIsFollowing() { private void checkIsFollowing() {
if (claim != null) { if (claim != null) {
boolean isFollowing = Lbryio.isFollowing(claim); boolean isFollowing = Lbryio.isFollowing(claim);
if (iconFollowUnfollow != null) { Helper.setViewVisibility(iconFollow, !isFollowing ? View.VISIBLE : View.GONE);
iconFollowUnfollow.setText(isFollowing ? R.string.fa_heart_broken : R.string.fa_heart); Helper.setViewVisibility(iconUnfollow, isFollowing ? View.VISIBLE : View.GONE);
Context context = getContext();
if (context != null) {
iconFollowUnfollow.setTextColor(ContextCompat.getColor(context, isFollowing ? R.color.foreground : R.color.red));
}
}
} }
} }
@@ -321,7 +324,7 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private void checkParams() { private void checkParams() {
boolean updateRequired = false; boolean updateRequired = false;
Map<String, Object> params = getParams(); Map<String, Object> params = getParams();
String newUrl = null;
if (params != null) { if (params != null) {
if (params.containsKey("claim")) { if (params.containsKey("claim")) {
Claim claim = (Claim) params.get("claim"); Claim claim = (Claim) params.get("claim");
@@ -331,21 +334,39 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
} }
} }
if (params.containsKey("url")) { if (params.containsKey("url")) {
String newUrl = params.get("url").toString(); LbryUri newLbryUri = LbryUri.tryParse(params.get("url").toString());
if (claim == null || !newUrl.equalsIgnoreCase(url)) { if (newLbryUri != null) {
this.claim = null; newUrl = newLbryUri.toString();
this.url = newUrl; String qs = newLbryUri.getQueryString();
updateRequired = true; if (!Helper.isNullOrEmpty(qs)) {
String[] qsPairs = qs.split("&");
for (String pair : qsPairs) {
String[] parts = pair.split("=");
if (parts.length < 2) {
continue;
}
if ("comment_hash".equalsIgnoreCase(parts[0])) {
commentHash = parts[1];
break;
}
}
}
if (claim == null || !newUrl.equalsIgnoreCase(currentUrl)) {
this.claim = null;
this.currentUrl = newUrl;
updateRequired = true;
}
} }
} }
} }
if (updateRequired) { if (updateRequired) {
resetSubCount(); resetSubCount();
if (!Helper.isNullOrEmpty(url)) { if (!Helper.isNullOrEmpty(currentUrl)) {
// check if the claim is already cached // check if the claim is already cached
ClaimCacheKey key = new ClaimCacheKey(); ClaimCacheKey key = new ClaimCacheKey();
key.setUrl(url); key.setUrl(currentUrl);
if (Lbry.claimCache.containsKey(key)) { if (Lbry.claimCache.containsKey(key)) {
claim = Lbry.claimCache.get(key); claim = Lbry.claimCache.get(key);
} else { } else {
@@ -357,8 +378,8 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
} }
} }
if (!Helper.isNullOrEmpty(url)) { if (!Helper.isNullOrEmpty(currentUrl)) {
Helper.saveUrlHistory(url, claim != null ? claim.getTitle() : null, UrlSuggestion.TYPE_CHANNEL); Helper.saveUrlHistory(currentUrl, claim != null ? claim.getTitle() : null, UrlSuggestion.TYPE_CHANNEL);
} }
if (claim != null) { if (claim != null) {
@@ -369,13 +390,13 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private void resolveUrl() { private void resolveUrl() {
Helper.setViewVisibility(layoutDisplayArea, View.INVISIBLE); Helper.setViewVisibility(layoutDisplayArea, View.INVISIBLE);
Helper.setViewVisibility(layoutLoadingState, View.VISIBLE); Helper.setViewVisibility(layoutLoadingState, View.VISIBLE);
ResolveTask task = new ResolveTask(url, Lbry.LBRY_TV_CONNECTION_STRING, layoutResolving, new ClaimListResultHandler() { ResolveTask task = new ResolveTask(currentUrl, Lbry.LBRY_TV_CONNECTION_STRING, layoutResolving, new ClaimListResultHandler() {
@Override @Override
public void onSuccess(List<Claim> claims) { public void onSuccess(List<Claim> claims) {
if (claims.size() > 0 && !Helper.isNullOrEmpty(claims.get(0).getClaimId())) { if (claims.size() > 0 && !Helper.isNullOrEmpty(claims.get(0).getClaimId())) {
claim = claims.get(0); claim = claims.get(0);
if (!Helper.isNullOrEmpty(url)) { if (!Helper.isNullOrEmpty(currentUrl)) {
Helper.saveUrlHistory(url, claim.getTitle(), UrlSuggestion.TYPE_CHANNEL); Helper.saveUrlHistory(currentUrl, claim.getTitle(), UrlSuggestion.TYPE_CHANNEL);
} }
renderClaim(); renderClaim();
@@ -426,7 +447,7 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
Glide.with(context.getApplicationContext()).load(coverUrl).centerCrop().into(imageCover); Glide.with(context.getApplicationContext()).load(coverUrl).centerCrop().into(imageCover);
} }
if (context != null && !Helper.isNullOrEmpty(thumbnailUrl)) { if (context != null && !Helper.isNullOrEmpty(thumbnailUrl)) {
Glide.with(context.getApplicationContext()).asBitmap().load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(imageThumbnail); Glide.with(context.getApplicationContext()).load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(imageThumbnail);
noThumbnailView.setVisibility(View.GONE); noThumbnailView.setVisibility(View.GONE);
} else { } else {
imageThumbnail.setVisibility(View.GONE); imageThumbnail.setVisibility(View.GONE);
@@ -441,12 +462,25 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
try { try {
if (tabPager.getAdapter() == null && context instanceof MainActivity) { if (tabPager.getAdapter() == null && context instanceof MainActivity) {
tabPager.setAdapter(new ChannelPagerAdapter(claim, (MainActivity) context)); tabPager.setAdapter(new ChannelPagerAdapter(claim, commentHash, (MainActivity) context));
if (!Helper.isNullOrEmpty(commentHash)) {
// set the Comments tab active if a comment hash is set
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
tabPager.setCurrentItem(2);
}
}, 500);
}
} }
new TabLayoutMediator(tabLayout, tabPager, new TabLayoutMediator.TabConfigurationStrategy() { new TabLayoutMediator(tabLayout, tabPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override @Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) { public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
tab.setText(position == 0 ? R.string.content : R.string.about); switch (position) {
case 0: tab.setText(R.string.content); break;
case 1: tab.setText(R.string.about); break;
case 2: tab.setText(R.string.comments); break;
}
} }
}).attach(); }).attach();
} catch (IllegalStateException ex) { } catch (IllegalStateException ex) {
@@ -487,9 +521,11 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private static class ChannelPagerAdapter extends FragmentStateAdapter { private static class ChannelPagerAdapter extends FragmentStateAdapter {
private Claim channelClaim; private Claim channelClaim;
public ChannelPagerAdapter(Claim channelClaim, FragmentActivity activity) { private String commentHash;
public ChannelPagerAdapter(Claim channelClaim, String commentHash, FragmentActivity activity) {
super(activity); super(activity);
this.channelClaim = channelClaim; this.channelClaim = channelClaim;
this.commentHash = commentHash;
} }
@SneakyThrows @SneakyThrows
@@ -516,6 +552,16 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
// pass // pass
} }
return aboutFragment; return aboutFragment;
case 2:
ChannelCommentsFragment commentsFragment = ChannelCommentsFragment.class.newInstance();
if (channelClaim != null) {
commentsFragment.setClaim(channelClaim);
}
if (!Helper.isNullOrEmpty(commentHash)) {
commentsFragment.setCommentHash(commentHash);
}
return commentsFragment;
} }
return null; return null;
@@ -527,7 +573,7 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
@Override @Override
public int getItemCount() { public int getItemCount() {
return 2; return 3;
} }
} }
} }
@@ -149,21 +149,23 @@ public class ChannelManagerFragment extends BaseFragment implements ActionMode.C
@Override @Override
public void onSuccess(List<Claim> claims) { public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = Helper.filterDeletedClaims(new ArrayList<>(claims)); Lbry.ownChannels = Helper.filterDeletedClaims(new ArrayList<>(claims));
Context context = getContext();
if (adapter == null) { if (adapter == null) {
adapter = new ClaimListAdapter(claims, context); Context context = getContext();
adapter.setCanEnterSelectionMode(true); if (context != null) {
adapter.setSelectionModeListener(ChannelManagerFragment.this); adapter = new ClaimListAdapter(claims, context);
adapter.setListener(new ClaimListAdapter.ClaimListItemListener() { adapter.setCanEnterSelectionMode(true);
@Override adapter.setSelectionModeListener(ChannelManagerFragment.this);
public void onClaimClicked(Claim claim) { adapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
if (context instanceof MainActivity) { @Override
((MainActivity) context).openChannelClaim(claim); public void onClaimClicked(Claim claim) {
if (context instanceof MainActivity) {
((MainActivity) context).openChannelClaim(claim);
}
} }
});
if (channelList != null) {
channelList.setAdapter(adapter);
} }
});
if (channelList != null) {
channelList.setAdapter(adapter);
} }
} else { } else {
adapter.setItems(claims); adapter.setItems(claims);
@@ -0,0 +1,29 @@
package io.lbry.browser.ui.controls;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.Gravity;
import androidx.appcompat.widget.AppCompatTextView;
public class OutlineIconView extends AppCompatTextView {
private Context context;
public OutlineIconView(Context context) {
super(context);
this.context = context;
init();
}
public OutlineIconView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
private void init() {
setGravity(Gravity.CENTER);
setTypeface(Typeface.createFromAsset(context.getAssets(), "font_awesome_5_free_regular.otf"));
}
}
@@ -446,22 +446,25 @@ public class AllContentFragment extends BaseFragment implements DownloadActionLi
@Override @Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) { public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (contentListAdapter == null) { if (contentListAdapter == null) {
contentListAdapter = new ClaimListAdapter(claims, getContext()); Context context = getContext();
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() { if (context != null) {
@Override contentListAdapter = new ClaimListAdapter(claims, context);
public void onClaimClicked(Claim claim) { contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
Context context = getContext(); @Override
if (context instanceof MainActivity) { public void onClaimClicked(Claim claim) {
MainActivity activity = (MainActivity) context; Context context = getContext();
if (claim.getName().startsWith("@")) { if (context instanceof MainActivity) {
// channel claim MainActivity activity = (MainActivity) context;
activity.openChannelClaim(claim); if (claim.getName().startsWith("@")) {
} else { // channel claim
activity.openFileClaim(claim); activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
} }
} }
} });
}); }
} else { } else {
contentListAdapter.addItems(claims); contentListAdapter.addItems(claims);
} }
File diff suppressed because it is too large. Load diff
@@ -441,7 +441,7 @@ public class FollowingFragment extends BaseFragment implements
private List<String> getChannelIds() { private List<String> getChannelIds() {
if (channelFilterListAdapter != null) { if (channelFilterListAdapter != null) {
Claim selected = channelFilterListAdapter.getSelectedItem(); Claim selected = channelFilterListAdapter.getSelectedItem();
if (selected != null) { if (selected != null && !Helper.isNullOrEmpty(selected.getClaimId())) {
return Arrays.asList(selected.getClaimId()); return Arrays.asList(selected.getClaimId());
} }
} }
@@ -490,6 +490,11 @@ public class FollowingFragment extends BaseFragment implements
String url = subscription.getUrl(); String url = subscription.getUrl();
LbryUri uri = LbryUri.parse(url); LbryUri uri = LbryUri.parse(url);
String claimId = uri.getClaimId(); String claimId = uri.getClaimId();
if (Helper.isNullOrEmpty(claimId) || Helper.isNullOrEmpty(url)) {
// don't add null / empty claim IDs or URLs
continue;
}
channelIds.add(claimId); channelIds.add(claimId);
channelUrls.add(url); channelUrls.add(url);
} catch (LbryUriException ex) { } catch (LbryUriException ex) {
@@ -593,22 +598,25 @@ public class FollowingFragment extends BaseFragment implements
@Override @Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) { public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (contentListAdapter == null) { if (contentListAdapter == null) {
contentListAdapter = new ClaimListAdapter(claims, getContext()); Context context = getContext();
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() { if (context != null) {
@Override contentListAdapter = new ClaimListAdapter(claims, context);
public void onClaimClicked(Claim claim) { contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
Context context = getContext(); @Override
if (context instanceof MainActivity) { public void onClaimClicked(Claim claim) {
MainActivity activity = (MainActivity) context; Context context = getContext();
if (claim.getName().startsWith("@")) { if (context instanceof MainActivity) {
// channel claim MainActivity activity = (MainActivity) context;
activity.openChannelClaim(claim); if (claim.getName().startsWith("@")) {
} else { // channel claim
activity.openFileClaim(claim); activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
} }
} }
} });
}); }
} else { } else {
contentListAdapter.addItems(claims); contentListAdapter.addItems(claims);
} }
@@ -192,7 +192,7 @@ public class SearchFragment extends BaseFragment implements
} }
if (resolved.isMature() && !canShowMatureContent) { if (resolved.isMature() && !canShowMatureContent) {
resultListAdapter.removeFeaturedItem(); resultListAdapter.removeFeaturedItem();
} else { } else if (unresolved != null) {
// only set the values we need // only set the values we need
unresolved.setClaimId(resolved.getClaimId()); unresolved.setClaimId(resolved.getClaimId());
unresolved.setName(resolved.getName()); unresolved.setName(resolved.getName());
@@ -201,6 +201,7 @@ public class SearchFragment extends BaseFragment implements
unresolved.setPermanentUrl(resolved.getPermanentUrl()); unresolved.setPermanentUrl(resolved.getPermanentUrl());
unresolved.setValue(resolved.getValue()); unresolved.setValue(resolved.getValue());
unresolved.setSigningChannel(resolved.getSigningChannel()); unresolved.setSigningChannel(resolved.getSigningChannel());
unresolved.setRepostedClaim(resolved.getRepostedClaim());
unresolved.setUnresolved(false); unresolved.setUnresolved(false);
unresolved.setConfirmations(resolved.getConfirmations()); unresolved.setConfirmations(resolved.getConfirmations());
} }
@@ -352,24 +352,27 @@ public class LibraryFragment extends BaseFragment implements
} }
private void initContentListAdapter(List<Claim> claims) { private void initContentListAdapter(List<Claim> claims) {
contentListAdapter = new ClaimListAdapter(claims, getContext()); Context context = getContext();
contentListAdapter.setCanEnterSelectionMode(currentFilter == FILTER_DOWNLOADS); if (context != null) {
contentListAdapter.setSelectionModeListener(this); contentListAdapter = new ClaimListAdapter(claims, context);
contentListAdapter.setHideFee(currentFilter != FILTER_PURCHASES); contentListAdapter.setCanEnterSelectionMode(currentFilter == FILTER_DOWNLOADS);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() { contentListAdapter.setSelectionModeListener(this);
@Override contentListAdapter.setHideFee(currentFilter != FILTER_PURCHASES);
public void onClaimClicked(Claim claim) { contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
Context context = getContext(); @Override
if (context instanceof MainActivity) { public void onClaimClicked(Claim claim) {
MainActivity activity = (MainActivity) getContext(); Context context = getContext();
if (claim.getName().startsWith("@")) { if (context instanceof MainActivity) {
activity.openChannelUrl(claim.getPermanentUrl()); MainActivity activity = (MainActivity) context;
} else { if (claim.getName().startsWith("@")) {
activity.openFileUrl(claim.getPermanentUrl()); activity.openChannelUrl(claim.getPermanentUrl());
} else {
activity.openFileUrl(claim.getPermanentUrl());
}
} }
} }
} });
}); }
} }
private void fetchDownloads() { private void fetchDownloads() {
@@ -391,7 +394,7 @@ public class LibraryFragment extends BaseFragment implements
} else { } else {
contentListAdapter.addItems(claims); contentListAdapter.addItems(claims);
} }
if (contentList.getAdapter() == null) { if (contentListAdapter != null && contentList.getAdapter() == null) {
contentList.setAdapter(contentListAdapter); contentList.setAdapter(contentListAdapter);
} }
resolveMissingChannelNames(buildUrlsToResolve(claims)); resolveMissingChannelNames(buildUrlsToResolve(claims));
@@ -423,7 +426,7 @@ public class LibraryFragment extends BaseFragment implements
} else { } else {
contentListAdapter.addItems(claims); contentListAdapter.addItems(claims);
} }
if (contentList.getAdapter() == null) { if (contentListAdapter != null && contentList.getAdapter() == null) {
contentList.setAdapter(contentListAdapter); contentList.setAdapter(contentListAdapter);
} }
checkListEmpty(); checkListEmpty();
@@ -459,7 +462,7 @@ public class LibraryFragment extends BaseFragment implements
} else { } else {
contentListAdapter.addItems(claims); contentListAdapter.addItems(claims);
} }
if (contentList.getAdapter() == null) { if (contentListAdapter != null && contentList.getAdapter() == null) {
contentList.setAdapter(contentListAdapter); contentList.setAdapter(contentListAdapter);
} }
checkListEmpty(); checkListEmpty();
@@ -637,18 +640,21 @@ public class LibraryFragment extends BaseFragment implements
public boolean onActionItemClicked(androidx.appcompat.view.ActionMode actionMode, MenuItem menuItem) { public boolean onActionItemClicked(androidx.appcompat.view.ActionMode actionMode, MenuItem menuItem) {
if (R.id.action_delete == menuItem.getItemId()) { if (R.id.action_delete == menuItem.getItemId()) {
if (contentListAdapter != null && contentListAdapter.getSelectedCount() > 0) { if (contentListAdapter != null && contentListAdapter.getSelectedCount() > 0) {
final List<Claim> selectedClaims = new ArrayList<>(contentListAdapter.getSelectedItems()); Context context = getContext();
String message = getResources().getQuantityString(R.plurals.confirm_delete_files, selectedClaims.size()); if (context != null) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()). final List<Claim> selectedClaims = new ArrayList<>(contentListAdapter.getSelectedItems());
setTitle(R.string.delete_selection). String message = getResources().getQuantityString(R.plurals.confirm_delete_files, selectedClaims.size());
setMessage(message) AlertDialog.Builder builder = new AlertDialog.Builder(context).
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { setTitle(R.string.delete_selection).
@Override setMessage(message)
public void onClick(DialogInterface dialogInterface, int i) { .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
handleDeleteSelectedClaims(selectedClaims); @Override
} public void onClick(DialogInterface dialogInterface, int i) {
}).setNegativeButton(R.string.no, null); handleDeleteSelectedClaims(selectedClaims);
builder.show(); }
}).setNegativeButton(R.string.no, null);
builder.show();
}
return true; return true;
} }
} }
@@ -475,6 +475,8 @@ public class PublishFormFragment extends BaseFragment implements
} }
}); });
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(getContext(), R.layout.spinner_item_channel, new ArrayList<>());
channelSpinnerAdapter.addPlaceholder(false);
setupInlineChannelCreator( setupInlineChannelCreator(
inlineChannelCreator, inlineChannelCreator,
inlineChannelCreatorInputName, inlineChannelCreatorInputName,
@@ -483,7 +485,9 @@ public class PublishFormFragment extends BaseFragment implements
inlineChannelCreatorInlineBalanceValue, inlineChannelCreatorInlineBalanceValue,
inlineChannelCreatorCancelLink, inlineChannelCreatorCancelLink,
inlineChannelCreatorCreateButton, inlineChannelCreatorCreateButton,
inlineChannelCreatorProgress inlineChannelCreatorProgress,
channelSpinner,
channelSpinnerAdapter
); );
} }
@@ -724,7 +728,10 @@ public class PublishFormFragment extends BaseFragment implements
private void uploadThumbnail(String thumbnailPath) { private void uploadThumbnail(String thumbnailPath) {
if (uploading) { if (uploading) {
Snackbar.make(getView(), R.string.wait_for_upload, Snackbar.LENGTH_LONG).show(); View view = getView();
if (view != null) {
Snackbar.make(view, R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
}
return; return;
} }
@@ -787,73 +794,75 @@ public class PublishFormFragment extends BaseFragment implements
} }
Context context = getContext(); Context context = getContext();
String outputPath = String.format("%s/videos", Utils.getAppInternalStorageDir(context)); if (context != null) {
File dir = new File(outputPath); String outputPath = String.format("%s/videos", Utils.getAppInternalStorageDir(context));
if (!dir.isDirectory()) { File dir = new File(outputPath);
dir.mkdirs(); if (!dir.isDirectory()) {
} dir.mkdirs();
}
boolean hasFullDuration = videoInformation != null && videoInformation.getDurationSeconds() > 0; boolean hasFullDuration = videoInformation != null && videoInformation.getDurationSeconds() > 0;
Helper.setViewVisibility(optimizationRealProgress, hasFullDuration ? View.VISIBLE : View.GONE); Helper.setViewVisibility(optimizationRealProgress, hasFullDuration ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(optimizationProgress, hasFullDuration ? View.GONE : View.VISIBLE); Helper.setViewVisibility(optimizationProgress, hasFullDuration ? View.GONE : View.VISIBLE);
File sourceFile = new File(filePath); File sourceFile = new File(filePath);
String filename = sourceFile.getName(); String filename = sourceFile.getName();
if (!filename.endsWith(".mp4")) { if (!filename.endsWith(".mp4")) {
int lastDotIndex = filename.lastIndexOf('.'); int lastDotIndex = filename.lastIndexOf('.');
filename = String.format("%s.mp4", lastDotIndex > -1 ? filename.substring(0, lastDotIndex) : filename); filename = String.format("%s.mp4", lastDotIndex > -1 ? filename.substring(0, lastDotIndex) : filename);
} }
String videoFilePath = String.format("%s/%s", outputPath, filename); String videoFilePath = String.format("%s/%s", outputPath, filename);
File targetFile = new File(videoFilePath); File targetFile = new File(videoFilePath);
if (targetFile.exists()) { if (targetFile.exists()) {
targetFile.delete(); targetFile.delete();
} }
transcodeInProgress = true; transcodeInProgress = true;
videoTranscodeTask = new VideoTranscodeTask(filePath, videoFilePath, scalePart, transcodeRequired, new VideoTranscodeTask.VideoTranscodeHandler() { videoTranscodeTask = new VideoTranscodeTask(filePath, videoFilePath, scalePart, transcodeRequired, new VideoTranscodeTask.VideoTranscodeHandler() {
@Override @Override
public void onProgress(int time) { public void onProgress(int time) {
if (context != null) { if (context != null) {
int currentDuration = Double.valueOf(time / 1000.0).intValue(); int currentDuration = Double.valueOf(time / 1000.0).intValue();
int fullDuration = videoInformation != null ? videoInformation.getDurationSeconds() : 0; int fullDuration = videoInformation != null ? videoInformation.getDurationSeconds() : 0;
long elapsed = System.currentTimeMillis() - transcodeStartTime; long elapsed = System.currentTimeMillis() - transcodeStartTime;
String completedDurationText = Helper.formatDuration(currentDuration); String completedDurationText = Helper.formatDuration(currentDuration);
if (fullDuration > 0) { if (fullDuration > 0) {
completedDurationText = String.format("%s / %s", completedDurationText, Helper.formatDuration(fullDuration)); completedDurationText = String.format("%s / %s", completedDurationText, Helper.formatDuration(fullDuration));
int percentComplete = Double.valueOf(Math.ceil((double) currentDuration / (double) fullDuration * 100.0)).intValue(); int percentComplete = Double.valueOf(Math.ceil((double) currentDuration / (double) fullDuration * 100.0)).intValue();
optimizationRealProgress.setProgress(percentComplete); optimizationRealProgress.setProgress(percentComplete);
}
String text = context.getString(R.string.completed_video_duration, completedDurationText);
Helper.setViewText(textOptimizationProgress, text);
Helper.setViewText(textOptimizationElapsed, Helper.formatDuration(Double.valueOf(elapsed / 1000.0).longValue()));
} }
String text = context.getString(R.string.completed_video_duration, completedDurationText);
Helper.setViewText(textOptimizationProgress, text);
Helper.setViewText(textOptimizationElapsed, Helper.formatDuration(Double.valueOf(elapsed / 1000.0).longValue()));
} }
}
@Override @Override
public void onSuccess(String outputFilePath) { public void onSuccess(String outputFilePath) {
transcodedFilePath = outputFilePath; transcodedFilePath = outputFilePath;
transcodeInProgress = false; transcodeInProgress = false;
Helper.setViewText(textOptimizationStatus, R.string.video_optimized); Helper.setViewText(textOptimizationStatus, R.string.video_optimized);
Helper.setViewVisibility(optimizationRealProgress, View.GONE); Helper.setViewVisibility(optimizationRealProgress, View.GONE);
Helper.setViewVisibility(optimizationProgress, View.GONE); Helper.setViewVisibility(optimizationProgress, View.GONE);
Helper.setViewVisibility(textOptimizationProgress, View.GONE); Helper.setViewVisibility(textOptimizationProgress, View.GONE);
} }
@Override @Override
public void onErrorOrCancelled() { public void onErrorOrCancelled() {
transcodeInProgress = false; transcodeInProgress = false;
Helper.setViewText(textOptimizationStatus, R.string.video_optimize_failed); Helper.setViewText(textOptimizationStatus, R.string.video_optimize_failed);
Helper.setViewVisibility(optimizationRealProgress, View.GONE); Helper.setViewVisibility(optimizationRealProgress, View.GONE);
Helper.setViewVisibility(optimizationProgress, View.GONE); Helper.setViewVisibility(optimizationProgress, View.GONE);
Helper.setViewVisibility(textOptimizationProgress, View.GONE); Helper.setViewVisibility(textOptimizationProgress, View.GONE);
} }
}); });
transcodeStartTime = System.currentTimeMillis(); transcodeStartTime = System.currentTimeMillis();
videoTranscodeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); videoTranscodeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
} }
private void cancelOnFatalCondition(String message) { private void cancelOnFatalCondition(String message) {
@@ -974,8 +983,8 @@ public class PublishFormFragment extends BaseFragment implements
} }
} else { } else {
channelSpinnerAdapter.clear(); channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.addPlaceholder(true); channelSpinnerAdapter.addPlaceholder(true);
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.notifyDataSetChanged(); channelSpinnerAdapter.notifyDataSetChanged();
} }
@@ -984,12 +993,14 @@ public class PublishFormFragment extends BaseFragment implements
} }
if (channelSpinnerAdapter != null && channelSpinner != null) { if (channelSpinnerAdapter != null && channelSpinner != null) {
if (editMode && currentClaim.getSigningChannel() != null && !editChannelSpinnerLoaded) { if (editMode) {
int position = channelSpinnerAdapter.getItemPosition(currentClaim.getSigningChannel()); if (currentClaim.getSigningChannel() != null && !editChannelSpinnerLoaded) {
if (position > -1) { int position = channelSpinnerAdapter.getItemPosition(currentClaim.getSigningChannel());
channelSpinner.setSelection(position); if (position > -1) {
channelSpinner.setSelection(position);
}
editChannelSpinnerLoaded = true;
} }
editChannelSpinnerLoaded = true;
} else { } else {
if (channelSpinnerAdapter.getCount() > 2) { if (channelSpinnerAdapter.getCount() > 2) {
// if anonymous displayed, select first channel if available // if anonymous displayed, select first channel if available
@@ -1104,6 +1115,7 @@ public class PublishFormFragment extends BaseFragment implements
// Run the logPublish task // Run the logPublish task
if (!BuildConfig.DEBUG) { if (!BuildConfig.DEBUG) {
claimResult.setSigningChannel(claim.getSigningChannel());
LogPublishTask logPublish = new LogPublishTask(claimResult); LogPublishTask logPublish = new LogPublishTask(claimResult);
logPublish.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); logPublish.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} }
@@ -1274,128 +1286,6 @@ public class PublishFormFragment extends BaseFragment implements
checkRewardsDriver(); checkRewardsDriver();
} }
private void setupInlineChannelCreator(
View container,
TextInputEditText inputChannelName,
TextInputEditText inputDeposit,
View inlineBalanceView,
TextView inlineBalanceValue,
View linkCancel,
MaterialButton buttonCreate,
View progressView) {
inputDeposit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
Helper.setViewVisibility(inlineBalanceView, hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
linkCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Helper.setViewText(inputChannelName, null);
Helper.setViewText(inputDeposit, null);
Helper.setViewVisibility(container, View.GONE);
}
});
buttonCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// validate deposit and channel name
String channelNameString = Helper.normalizeChannelName(Helper.getValue(inputChannelName.getText()));
Claim claimToSave = new Claim();
claimToSave.setName(channelNameString);
String channelName = claimToSave.getName().startsWith("@") ? claimToSave.getName().substring(1) : claimToSave.getName();
String depositString = Helper.getValue(inputDeposit.getText());
if ("@".equals(channelName) || Helper.isNullOrEmpty(channelName)) {
showError(getString(R.string.please_enter_channel_name));
return;
}
if (!LbryUri.isNameValid(channelName)) {
showError(getString(R.string.channel_name_invalid_characters));
return;
}
if (Helper.channelExists(channelName)) {
showError(getString(R.string.channel_name_already_created));
return;
}
double depositAmount = 0;
try {
depositAmount = Double.valueOf(depositString);
} catch (NumberFormatException ex) {
// pass
showError(getString(R.string.please_enter_valid_deposit));
return;
}
if (depositAmount == 0) {
String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(error);
return;
}
if (Lbry.walletBalance == null || Lbry.walletBalance.getAvailable().doubleValue() < depositAmount) {
showError(getString(R.string.deposit_more_than_balance));
return;
}
ChannelCreateUpdateTask task = new ChannelCreateUpdateTask(
claimToSave, new BigDecimal(depositString), false, progressView, new ClaimResultHandler() {
@Override
public void beforeStart() {
Helper.setViewEnabled(inputChannelName, false);
Helper.setViewEnabled(inputDeposit, false);
Helper.setViewEnabled(buttonCreate, false);
Helper.setViewEnabled(linkCancel, false);
}
@Override
public void onSuccess(Claim claimResult) {
if (!BuildConfig.DEBUG) {
LogPublishTask logPublishTask = new LogPublishTask(claimResult);
logPublishTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
// channel created
Bundle bundle = new Bundle();
bundle.putString("claim_id", claimResult.getClaimId());
bundle.putString("claim_name", claimResult.getName());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_CHANNEL_CREATE, bundle);
// add the claim to the channel list and set it as the selected item
channelSpinnerAdapter.add(claimResult);
channelSpinner.setSelection(channelSpinnerAdapter.getCount() - 1);
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
}
@Override
public void onError(Exception error) {
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
showError(error.getMessage());
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
Helper.setViewText(inlineBalanceValue, Helper.shortCurrencyFormat(Lbry.walletBalance.getAvailable().doubleValue()));
}
private void showError(String message) {
Context context = getContext();
if (context != null) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
}
private void checkUploadButton() { private void checkUploadButton() {
} }
@@ -1411,7 +1301,11 @@ public class PublishFormFragment extends BaseFragment implements
@Override @Override
public void onStoragePermissionRefused() { public void onStoragePermissionRefused() {
if (!storageRefusedOnce) { if (!storageRefusedOnce) {
showError(getString(R.string.storage_permission_rationale_images)); try {
showError(getString(R.string.storage_permission_rationale_images));
} catch (IllegalStateException ex) {
// pass
}
storageRefusedOnce = true; storageRefusedOnce = true;
} }
launchPickerPending = false; launchPickerPending = false;
@@ -140,7 +140,7 @@ public class PublishFragment extends BaseFragment implements
preview.setSurfaceProvider(cameraPreview.createSurfaceProvider(camera.getCameraInfo())); preview.setSurfaceProvider(cameraPreview.createSurfaceProvider(camera.getCameraInfo()));
cameraPreviewInitialized = true; cameraPreviewInitialized = true;
} }
} catch (ExecutionException | InterruptedException ex) { } catch (ExecutionException | IllegalArgumentException | InterruptedException ex) {
// pass // pass
} }
} }
@@ -12,6 +12,7 @@ import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.Button; import android.widget.Button;
import android.widget.ProgressBar; import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
@@ -150,26 +151,28 @@ public class PublishesFragment extends BaseFragment implements ActionMode.Callba
@Override @Override
public void onSuccess(List<Claim> claims) { public void onSuccess(List<Claim> claims) {
Lbry.ownClaims = Helper.filterDeletedClaims(new ArrayList<>(claims)); Lbry.ownClaims = Helper.filterDeletedClaims(new ArrayList<>(claims));
Context context = getContext();
if (adapter == null) { if (adapter == null) {
adapter = new ClaimListAdapter(claims, context); Context context = getContext();
adapter.setCanEnterSelectionMode(true); if (context != null) {
adapter.setSelectionModeListener(PublishesFragment.this); adapter = new ClaimListAdapter(claims, context);
adapter.setListener(new ClaimListAdapter.ClaimListItemListener() { adapter.setCanEnterSelectionMode(true);
@Override adapter.setSelectionModeListener(PublishesFragment.this);
public void onClaimClicked(Claim claim) { adapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
if (context instanceof MainActivity) { @Override
MainActivity activity = (MainActivity) context; public void onClaimClicked(Claim claim) {
if (claim.getName().startsWith("@")) { if (context instanceof MainActivity) {
activity.openChannelClaim(claim); MainActivity activity = (MainActivity) context;
} else { if (claim.getName().startsWith("@")) {
activity.openFileClaim(claim); activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
} }
} }
});
if (contentList != null) {
contentList.setAdapter(adapter);
} }
});
if (contentList != null) {
contentList.setAdapter(adapter);
} }
} else { } else {
adapter.setItems(claims); adapter.setItems(claims);
@@ -165,7 +165,8 @@ public class EmailVerificationFragment extends Fragment {
} }
private void checkEmailVerified() { private void checkEmailVerified() {
CheckUserEmailVerifiedTask task = new CheckUserEmailVerifiedTask(new CheckUserEmailVerifiedTask.CheckUserEmailVerifiedHandler() { Context context = getContext();
CheckUserEmailVerifiedTask task = new CheckUserEmailVerifiedTask(context, new CheckUserEmailVerifiedTask.CheckUserEmailVerifiedHandler() {
@Override @Override
public void onUserEmailVerified() { public void onUserEmailVerified() {
if (listener != null) { if (listener != null) {
@@ -1,27 +1,75 @@
package io.lbry.browser.ui.verification; package io.lbry.browser.ui.verification;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.TextView; import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment; import androidx.fragment.app.Fragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import io.lbry.browser.R; import io.lbry.browser.R;
import io.lbry.browser.listener.SignInListener; import io.lbry.browser.listener.SignInListener;
import io.lbry.browser.model.TwitterOauth;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.tasks.TwitterOauthHandler;
import io.lbry.browser.tasks.lbryinc.TwitterVerifyTask;
import io.lbry.browser.tasks.verification.TwitterAccessTokenTask;
import io.lbry.browser.tasks.verification.TwitterRequestTokenTask;
import io.lbry.browser.utils.Helper; import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
import lombok.Setter; import lombok.Setter;
public class ManualVerificationFragment extends Fragment { public class ManualVerificationFragment extends Fragment {
@Setter @Setter
private SignInListener listener; private SignInListener listener;
private PopupWindow popup;
private View mainView;
private View loadingView;
private TwitterOauth currentOauth;
private boolean twitterOauthInProgress = false;
private static final double SKIP_QUEUE_PRICE = 4.99;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_verification_manual, container, false); View root = inflater.inflate(R.layout.fragment_verification_manual, container, false);
Helper.applyHtmlForTextView((TextView) root.findViewById(R.id.verification_manual_discord_verify)); mainView = root.findViewById(R.id.verification_manual_main);
loadingView = root.findViewById(R.id.verification_manual_loading);
Context context = getContext();
MaterialButton buttonSkipQueue = root.findViewById(R.id.verification_manual_skip_queue);
buttonSkipQueue.setText(context.getString(R.string.skip_queue_button_text, String.valueOf(SKIP_QUEUE_PRICE)));
Helper.applyHtmlForTextView(root.findViewById(R.id.verification_manual_discord_verify));
root.findViewById(R.id.verification_manual_twitter_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// start twitter verification
if (currentOauth != null) {
// Twitter three-legged oauth already completed, verify directly
twitterVerify(currentOauth);
} else {
// show twitter sign-in flow
twitterVerificationFlow();
}
}
});
root.findViewById(R.id.verification_manual_continue_button).setOnClickListener(new View.OnClickListener() { root.findViewById(R.id.verification_manual_continue_button).setOnClickListener(new View.OnClickListener() {
@Override @Override
public void onClick(View view) { public void onClick(View view) {
@@ -31,6 +79,205 @@ public class ManualVerificationFragment extends Fragment {
} }
}); });
root.findViewById(R.id.verification_manual_skip_queue).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null) {
listener.onSkipQueueAction();
}
}
});
return root; return root;
} }
private void twitterVerificationFlow() {
twitterOauthInProgress = true;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
showLoading();
String consumerKey = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
String consumerSecret = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
TwitterRequestTokenTask task = new TwitterRequestTokenTask(consumerKey, consumerSecret, new TwitterOauthHandler() {
@Override
public void onSuccess(TwitterOauth twitterOauth) {
twitterOauthInProgress = false;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
showTwitterAuthenticateWithToken(twitterOauth.getOauthToken());
}
@Override
public void onError(Exception error) {
handleFlowError(null);
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void showLoading() {
Helper.setViewVisibility(mainView, View.INVISIBLE);
Helper.setViewVisibility(loadingView, View.VISIBLE);
}
public void hideLoading() {
Helper.setViewVisibility(mainView, View.VISIBLE);
Helper.setViewVisibility(loadingView, View.GONE);
}
private void showTwitterAuthenticateWithToken(String oauthToken) {
Context context = getContext();
if (context != null) {
WebView webView = new WebView(context);
webView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
webView.loadUrl(String.format("https://api.twitter.com/oauth/authorize?oauth_token=%s", oauthToken));
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("https://lbry.tv") || url.equalsIgnoreCase("https://twitter.com/home") /* Return to Twitter */) {
if (url.startsWith("https://lbry.tv") && url.contains("oauth_token") && url.contains("oauth_verifier")) {
// finish 3-legged oauth
twitterOauthInProgress = true;
listener.onManualProgress(twitterOauthInProgress);
finishTwitterOauth(url);
}
if (popup != null) {
popup.dismiss();
}
return false;
}
view.loadUrl(url);
return true;
}
});
View popupView = LayoutInflater.from(context).inflate(R.layout.popup_webview, null);
((LinearLayout) popupView.findViewById(R.id.popup_webivew_container)).addView(webView);
popupView.findViewById(R.id.popup_cancel_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!twitterOauthInProgress && popup != null) {
popup.dismiss();
hideLoading();
}
}
});
float scale = getResources().getDisplayMetrics().density;
popup = new PopupWindow(context);
popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
if (!twitterOauthInProgress) {
hideLoading();
}
popup = null;
}
});
popup.setWidth(Helper.getScaledValue(340, scale));
popup.setHeight(Helper.getScaledValue(480, scale));
popup.setContentView(popupView);
View parent = getView();
popup.setFocusable(true);
popup.showAtLocation(parent, Gravity.CENTER, 0, 0);
popup.update();
}
}
private void finishTwitterOauth(String callbackUrl) {
String params = callbackUrl.substring(callbackUrl.indexOf('?') + 1);
TwitterAccessTokenTask task = new TwitterAccessTokenTask(params, new TwitterOauthHandler() {
@Override
public void onSuccess(TwitterOauth twitterOauth) {
// send request to finish verifying
currentOauth = twitterOauth;
twitterVerify(twitterOauth);
}
@Override
public void onError(Exception error) {
handleFlowError(null);
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void twitterVerify(TwitterOauth twitterOauth) {
Context context = getContext();
if (context != null) {
showLoading();
twitterOauthInProgress = true;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
TwitterVerifyTask task = new TwitterVerifyTask(twitterOauth, null, context, new RewardVerifiedHandler() {
@Override
public void onSuccess(RewardVerified rewardVerified) {
twitterOauthInProgress = false;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
if (Lbryio.currentUser != null) {
Lbryio.currentUser.setRewardApproved(rewardVerified.isRewardApproved());
}
if (rewardVerified.isRewardApproved()) {
if (listener != null) {
listener.onTwitterVerified();
}
} else {
View root = getView();
if (root != null) {
// reward approved wasn't set to true
Snackbar.make(root, getString(R.string.twitter_verification_not_approved), Snackbar.LENGTH_LONG).
setTextColor(Color.WHITE).
setBackgroundTint(Color.RED).show();
}
hideLoading();
}
}
@Override
public void onError(Exception error) {
handleFlowError(error != null ? error.getMessage() : null);
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
twitterOauthInProgress = false;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
hideLoading();
}
}
private void handleFlowError(String extra) {
hideLoading();
twitterOauthInProgress = false;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
showFlowError(extra);
}
private void showFlowError(String extra) {
Context context = getContext();
View root = getView();
if (context != null && root != null) {
String message = !Helper.isNullOrEmpty(extra) ?
getString(R.string.twitter_account_ineligible, extra) :
getString(R.string.twitter_verification_failed);
Snackbar.make(root, message, Snackbar.LENGTH_LONG).
setTextColor(Color.WHITE).
setBackgroundTint(Color.RED).show();
}
}
} }
@@ -2,6 +2,7 @@ package io.lbry.browser.ui.verification;
import android.app.Activity; import android.app.Activity;
import android.content.Context; import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.view.LayoutInflater; import android.view.LayoutInflater;
@@ -243,8 +244,10 @@ public class WalletVerificationFragment extends Fragment {
} }
private void showError(String message) { private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).setBackgroundTint( View view = getView();
getResources().getColor(R.color.red) if (view != null) {
).show(); Snackbar.make(view, message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
} }
} }
@@ -248,6 +248,8 @@ public class InvitesFragment extends BaseFragment implements SdkStatusListener,
} }
}); });
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(getContext(), R.layout.spinner_item_channel, new ArrayList<>());
channelSpinnerAdapter.addPlaceholder(false);
setupInlineChannelCreator( setupInlineChannelCreator(
inlineChannelCreator, inlineChannelCreator,
inlineChannelCreatorInputName, inlineChannelCreatorInputName,
@@ -256,7 +258,9 @@ public class InvitesFragment extends BaseFragment implements SdkStatusListener,
inlineChannelCreatorInlineBalanceValue, inlineChannelCreatorInlineBalanceValue,
inlineChannelCreatorCancelLink, inlineChannelCreatorCancelLink,
inlineChannelCreatorCreateButton, inlineChannelCreatorCreateButton,
inlineChannelCreatorProgress inlineChannelCreatorProgress,
channelSpinner,
channelSpinnerAdapter
); );
} }
@@ -455,120 +459,6 @@ public class InvitesFragment extends BaseFragment implements SdkStatusListener,
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} }
private void setupInlineChannelCreator(
View container,
TextInputEditText inputChannelName,
TextInputEditText inputDeposit,
View inlineBalanceView,
TextView inlineBalanceValue,
View linkCancel,
MaterialButton buttonCreate,
View progressView) {
inputDeposit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
Helper.setViewVisibility(inlineBalanceView, hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
linkCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Helper.setViewText(inputChannelName, null);
Helper.setViewText(inputDeposit, null);
Helper.setViewVisibility(container, View.GONE);
}
});
buttonCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// validate deposit and channel name
String channelNameString = Helper.normalizeChannelName(Helper.getValue(inputChannelName.getText()));
Claim claimToSave = new Claim();
claimToSave.setName(channelNameString);
String channelName = claimToSave.getName().startsWith("@") ? claimToSave.getName().substring(1) : claimToSave.getName();
String depositString = Helper.getValue(inputDeposit.getText());
if ("@".equals(channelName) || Helper.isNullOrEmpty(channelName)) {
showError(getString(R.string.please_enter_channel_name));
return;
}
if (!LbryUri.isNameValid(channelName)) {
showError(getString(R.string.channel_name_invalid_characters));
return;
}
if (Helper.channelExists(channelName)) {
showError(getString(R.string.channel_name_already_created));
return;
}
double depositAmount = 0;
try {
depositAmount = Double.valueOf(depositString);
} catch (NumberFormatException ex) {
// pass
showError(getString(R.string.please_enter_valid_deposit));
return;
}
if (depositAmount == 0) {
String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(error);
return;
}
if (Lbry.walletBalance == null || Lbry.walletBalance.getAvailable().doubleValue() < depositAmount) {
showError(getString(R.string.deposit_more_than_balance));
return;
}
ChannelCreateUpdateTask task = new ChannelCreateUpdateTask(
claimToSave, new BigDecimal(depositString), false, progressView, new ClaimResultHandler() {
@Override
public void beforeStart() {
Helper.setViewEnabled(inputChannelName, false);
Helper.setViewEnabled(inputDeposit, false);
Helper.setViewEnabled(buttonCreate, false);
Helper.setViewEnabled(linkCancel, false);
}
@Override
public void onSuccess(Claim claimResult) {
if (!BuildConfig.DEBUG) {
LogPublishTask logPublishTask = new LogPublishTask(claimResult);
logPublishTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
// channel created
Bundle bundle = new Bundle();
bundle.putString("claim_id", claimResult.getClaimId());
bundle.putString("claim_name", claimResult.getName());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_CHANNEL_CREATE, bundle);
// add the claim to the channel list and set it as the selected item
channelSpinnerAdapter.add(claimResult);
channelSpinner.setSelection(channelSpinnerAdapter.getCount() - 1);
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
}
@Override
public void onError(Exception error) {
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
showError(error.getMessage());
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
Helper.setViewText(inlineBalanceValue, Helper.shortCurrencyFormat(Lbry.walletBalance.getAvailable().doubleValue()));
}
@Override @Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) { public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineChannelCreatorInlineBalanceValue != null) { if (walletBalance != null && inlineChannelCreatorInlineBalanceValue != null) {
@@ -577,14 +467,6 @@ public class InvitesFragment extends BaseFragment implements SdkStatusListener,
checkRewardsDriver(); checkRewardsDriver();
} }
private void showError(String message) {
Context context = getContext();
if (context != null) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
}
private void checkRewardsDriver() { private void checkRewardsDriver() {
Context ctx = getContext(); Context ctx = getContext();
View root = getView(); View root = getView();
@@ -103,16 +103,20 @@ public class TransactionHistoryFragment extends BaseFragment implements Transact
TransactionListTask task = new TransactionListTask(currentTransactionPage, TRANSACTION_PAGE_LIMIT, loading, new TransactionListTask.TransactionListHandler() { TransactionListTask task = new TransactionListTask(currentTransactionPage, TRANSACTION_PAGE_LIMIT, loading, new TransactionListTask.TransactionListHandler() {
@Override @Override
public void onSuccess(List<Transaction> transactions, boolean hasReachedEnd) { public void onSuccess(List<Transaction> transactions, boolean hasReachedEnd) {
Context context = getContext();
transactionsLoading = false; transactionsLoading = false;
transactionsHaveReachedEnd = hasReachedEnd; transactionsHaveReachedEnd = hasReachedEnd;
if (adapter == null) { if (context != null) {
adapter = new TransactionListAdapter(transactions, getContext()); if (adapter == null) {
adapter.setListener(TransactionHistoryFragment.this); adapter = new TransactionListAdapter(transactions, context);
if (transactionList != null) { adapter.setListener(TransactionHistoryFragment.this);
transactionList.setAdapter(adapter); if (transactionList != null) {
transactionList.setAdapter(adapter);
}
} else {
adapter.addTransactions(transactions);
} }
} else {
adapter.addTransactions(transactions);
} }
checkNoTransactions(); checkNoTransactions();
} }
@@ -6,8 +6,10 @@ import android.content.Context;
import android.content.DialogInterface; import android.content.DialogInterface;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.graphics.Color; import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask; import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.util.Base64;
import android.view.GestureDetector; import android.view.GestureDetector;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.MotionEvent; import android.view.MotionEvent;
@@ -19,6 +21,7 @@ import android.widget.TextView;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.browser.customtabs.CustomTabsIntent;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager; import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.DividerItemDecoration;
@@ -30,12 +33,20 @@ import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.switchmaterial.SwitchMaterial; import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.textfield.TextInputEditText; import com.google.android.material.textfield.TextInputEditText;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols; import java.text.DecimalFormatSymbols;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import io.lbry.browser.MainActivity; import io.lbry.browser.MainActivity;
import io.lbry.browser.R; import io.lbry.browser.R;
import io.lbry.browser.adapter.TransactionListAdapter; import io.lbry.browser.adapter.TransactionListAdapter;
@@ -57,6 +68,10 @@ import io.lbry.browser.utils.Lbryio;
public class WalletFragment extends BaseFragment implements SdkStatusListener, WalletBalanceListener { public class WalletFragment extends BaseFragment implements SdkStatusListener, WalletBalanceListener {
private static final String MOONPAY_KEY = "c2tfbGl2ZV9ueVJqVXNDbE5pcnVSdnlCMkJLWW5JcFA5VnA3dWU=";
private static final String MOONPAY_URL_FORMAT =
"https://buy.moonpay.io?apiKey=pk_live_xNFffrN5NWKy6fu0ggbV8VQIwRieRzy&colorCode=%%232F9176&currencyCode=LBC&showWalletAddressForm=true&walletAddress=%s&externalCustomerId=%s";
private View layoutAccountRecommended; private View layoutAccountRecommended;
private View layoutSdkInitializing; private View layoutSdkInitializing;
private View linkSkipAccount; private View linkSkipAccount;
@@ -75,6 +90,7 @@ public class WalletFragment extends BaseFragment implements SdkStatusListener, W
private View inlineBalanceContainer; private View inlineBalanceContainer;
private TextView textWalletInlineBalance; private TextView textWalletInlineBalance;
private MaterialButton buttonSignUp; private MaterialButton buttonSignUp;
private MaterialButton buttonBuyLBC;
private RecyclerView recentTransactionsList; private RecyclerView recentTransactionsList;
private View linkViewAll; private View linkViewAll;
private TextView textConvertCredits; private TextView textConvertCredits;
@@ -125,6 +141,7 @@ public class WalletFragment extends BaseFragment implements SdkStatusListener, W
recentTransactionsList = root.findViewById(R.id.wallet_recent_transactions_list); recentTransactionsList = root.findViewById(R.id.wallet_recent_transactions_list);
linkViewAll = root.findViewById(R.id.wallet_link_view_all); linkViewAll = root.findViewById(R.id.wallet_link_view_all);
textNoRecentTransactions = root.findViewById(R.id.wallet_no_recent_transactions); textNoRecentTransactions = root.findViewById(R.id.wallet_no_recent_transactions);
buttonBuyLBC = root.findViewById(R.id.wallet_buy_lbc_button);
textConvertCredits = root.findViewById(R.id.wallet_hint_convert_credits); textConvertCredits = root.findViewById(R.id.wallet_hint_convert_credits);
textConvertCreditsBittrex = root.findViewById(R.id.wallet_hint_convert_credits_bittrex); textConvertCreditsBittrex = root.findViewById(R.id.wallet_hint_convert_credits_bittrex);
textEarnMoreTips = root.findViewById(R.id.wallet_hint_earn_more_tips); textEarnMoreTips = root.findViewById(R.id.wallet_hint_earn_more_tips);
@@ -313,6 +330,13 @@ public class WalletFragment extends BaseFragment implements SdkStatusListener, W
} }
}); });
buttonBuyLBC.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
launchMoonpayFlow();
}
});
inputSendAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() { inputSendAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override @Override
public void onFocusChange(View view, boolean hasFocus) { public void onFocusChange(View view, boolean hasFocus) {
@@ -407,6 +431,7 @@ public class WalletFragment extends BaseFragment implements SdkStatusListener, W
private void sendCredits() { private void sendCredits() {
// wallet_send task // wallet_send task
View view = getView();
String recipientAddress = Helper.getValue(inputSendAddress.getText()); String recipientAddress = Helper.getValue(inputSendAddress.getText());
String amountString = Helper.getValue(inputSendAmount.getText()); String amountString = Helper.getValue(inputSendAmount.getText());
String amount = null; String amount = null;
@@ -414,13 +439,24 @@ public class WalletFragment extends BaseFragment implements SdkStatusListener, W
amount = new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)). amount = new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).
format(new BigDecimal(amountString).doubleValue()); format(new BigDecimal(amountString).doubleValue());
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
Snackbar.make(getView(), R.string.invalid_amount, Snackbar.LENGTH_LONG). if (view != null) {
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show(); Snackbar.make(view, R.string.invalid_amount, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
return;
}
double actualSendAmount = Double.valueOf(amount);
if (actualSendAmount < Helper.MIN_SPEND) {
if (view != null) {
Snackbar.make(view, R.string.min_spend_required, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
return; return;
} }
disableSendControls(); disableSendControls();
double actualSendAmount = Double.valueOf(amount);
WalletSendTask task = new WalletSendTask(recipientAddress, amount, walletSendProgress, new WalletSendTask.WalletSendHandler() { WalletSendTask task = new WalletSendTask(recipientAddress, amount, walletSendProgress, new WalletSendTask.WalletSendHandler() {
@Override @Override
public void onSuccess() { public void onSuccess() {
@@ -428,16 +464,20 @@ public class WalletFragment extends BaseFragment implements SdkStatusListener, W
String message = getResources().getQuantityString( String message = getResources().getQuantityString(
R.plurals.you_sent_credits, sentAmount == 1.0 ? 1 : 2, R.plurals.you_sent_credits, sentAmount == 1.0 ? 1 : 2,
new DecimalFormat("#,###.##").format(sentAmount)); new DecimalFormat("#,###.##").format(sentAmount));
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).show(); Helper.setViewText(inputSendAddress, null);
inputSendAddress.setText(null); Helper.setViewText(inputSendAmount, null);
inputSendAmount.setText(null); if (view != null) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
}
enableSendControls(); enableSendControls();
} }
@Override @Override
public void onError(Exception error) { public void onError(Exception error) {
Snackbar.make(getView(), R.string.send_credit_error, Snackbar.LENGTH_LONG). if (view != null) {
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show(); Snackbar.make(view, R.string.send_credit_error, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
enableSendControls(); enableSendControls();
} }
}); });
@@ -465,6 +505,48 @@ public class WalletFragment extends BaseFragment implements SdkStatusListener, W
return sp.getBoolean(MainActivity.PREFERENCE_KEY_INTERNAL_SKIP_WALLET_ACCOUNT, false); return sp.getBoolean(MainActivity.PREFERENCE_KEY_INTERNAL_SKIP_WALLET_ACCOUNT, false);
} }
public void launchMoonpayFlow() {
Context context = getContext();
String receiveAddress = null;
if (context != null) {
try {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
receiveAddress = sp.getString(MainActivity.PREFERENCE_KEY_INTERNAL_WALLET_RECEIVE_ADDRESS, null);
if (Helper.isNullOrEmpty(receiveAddress)) {
showError(getString(R.string.receive_address_not_set));
return;
}
long userId = Lbryio.currentUser != null ? Lbryio.currentUser.getId() : 0;
String url = String.format(MOONPAY_URL_FORMAT, receiveAddress,
URLEncoder.encode(String.format("android-%d", userId), StandardCharsets.UTF_8.name()));
String email = Lbryio.getSignedInEmail();
if (!Helper.isNullOrEmpty(email)) {
url = String.format("%s&email=%s", url, URLEncoder.encode(email, StandardCharsets.UTF_8.name()));
}
// Sign the URL
String query = url.substring(url.indexOf("?"));
Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKey = new SecretKeySpec(
new String(Base64.decode(MOONPAY_KEY, Base64.NO_WRAP), StandardCharsets.UTF_8.name()).getBytes(), "HmacSHA256");
hmacSHA256.init(secretKey);
String signature = new String(
Base64.encode(hmacSHA256.doFinal(query.getBytes(StandardCharsets.UTF_8.name())), Base64.NO_WRAP),
StandardCharsets.UTF_8.name());
url = String.format("%s&signature=%s", url, URLEncoder.encode(signature, StandardCharsets.UTF_8.name()));
CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder().setToolbarColor(
ContextCompat.getColor(context, R.color.lbryGreen)
);
CustomTabsIntent intent = builder.build();
intent.launchUrl(context, Uri.parse(url));
} catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException ex) {
showError(getString(R.string.hash_not_supported));
}
}
}
public void onResume() { public void onResume() {
super.onResume(); super.onResume();
Context context = getContext(); Context context = getContext();
@@ -30,6 +30,8 @@ import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView;
import com.google.android.gms.common.util.Hex;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@@ -37,6 +39,9 @@ import org.json.JSONObject;
import java.io.Closeable; import java.io.Closeable;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat; import java.text.DecimalFormat;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
@@ -65,11 +70,14 @@ public final class Helper {
public static final String METHOD_GET = "GET"; public static final String METHOD_GET = "GET";
public static final String METHOD_POST = "POST"; public static final String METHOD_POST = "POST";
public static final String ISO_DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; public static final String ISO_DATE_FORMAT_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS";
public static final String ISO_DATE_FORMAT_JSON = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static final String SDK_AMOUNT_FORMAT = "0.0#######"; public static final String SDK_AMOUNT_FORMAT = "0.0#######";
public static final MediaType FORM_MEDIA_TYPE = MediaType.parse("application/x-www-form-urlencoded"); public static final MediaType FORM_MEDIA_TYPE = MediaType.parse("application/x-www-form-urlencoded");
public static final MediaType JSON_MEDIA_TYPE = MediaType.get("application/json; charset=utf-8"); public static final MediaType JSON_MEDIA_TYPE = MediaType.get("application/json; charset=utf-8");
public static final int CONTENT_PAGE_SIZE = 25; public static final int CONTENT_PAGE_SIZE = 25;
public static final double MIN_DEPOSIT = 0.001; public static final double MIN_DEPOSIT = 0.001;
public static final double MIN_SPEND = 0.0001;
public static final String PLAIN_CURRENCY_FORMAT_PATTERN = "####.##";
public static final String LBC_CURRENCY_FORMAT_PATTERN = "#,###.##"; public static final String LBC_CURRENCY_FORMAT_PATTERN = "#,###.##";
public static final String FILE_SIZE_FORMAT_PATTERN = "#,###.#"; public static final String FILE_SIZE_FORMAT_PATTERN = "#,###.#";
public static final DecimalFormat LBC_CURRENCY_FORMAT = new DecimalFormat(LBC_CURRENCY_FORMAT_PATTERN); public static final DecimalFormat LBC_CURRENCY_FORMAT = new DecimalFormat(LBC_CURRENCY_FORMAT_PATTERN);
@@ -124,6 +132,16 @@ public final class Helper {
return sb.toString(); return sb.toString();
} }
public static String joinL(List<Long> list, String delimiter) {
StringBuilder sb = new StringBuilder();
String delim = "";
for (Long item : list) {
sb.append(delim).append(item);
delim = delimiter;
}
return sb.toString();
}
public static <T> JSONArray jsonArrayFromList(List<T> values) { public static <T> JSONArray jsonArrayFromList(List<T> values) {
JSONArray array = new JSONArray(); JSONArray array = new JSONArray();
for (T value : values) { for (T value : values) {
@@ -550,7 +568,11 @@ public final class Helper {
split[1] split[1]
}; };
return getDataColumn(context, contentUri, selection, selectionArgs); try {
return getDataColumn(context, contentUri, selection, selectionArgs);
} catch (Exception ex) {
return null;
}
} }
} }
// MediaStore (and general) // MediaStore (and general)
@@ -760,4 +782,14 @@ public final class Helper {
} }
return id.toString(); return id.toString();
} }
public static String SHA256(String value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(value.getBytes("UTF-8"));
return Hex.bytesToStringLowercase(hash);
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
return null;
}
}
} }
@@ -1,5 +1,7 @@
package io.lbry.browser.utils; package io.lbry.browser.utils;
import android.util.Log;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
@@ -89,6 +91,8 @@ public final class Lbry {
public static final String METHOD_PREFERENCE_GET = "preference_get"; public static final String METHOD_PREFERENCE_GET = "preference_get";
public static final String METHOD_PREFERENCE_SET = "preference_set"; public static final String METHOD_PREFERENCE_SET = "preference_set";
public static final String METHOD_COMMENT_CREATE = "comment_create";
public static final String METHOD_TXO_LIST = "txo_list"; public static final String METHOD_TXO_LIST = "txo_list";
public static final String METHOD_TXO_SPEND = "txo_spend"; public static final String METHOD_TXO_SPEND = "txo_spend";
@@ -126,7 +130,7 @@ public final class Lbry {
IS_STATUS_PARSED = true; IS_STATUS_PARSED = true;
} catch (JSONException | LbryResponseException ex) { } catch (JSONException | LbryResponseException ex) {
// pass // pass
android.util.Log.e(TAG, "Could not parse status response.", ex); Log.e(TAG, "Could not parse status response.", ex);
} }
} }
@@ -10,6 +10,8 @@ public class LbryAnalytics {
public static final String EVENT_APP_ERROR = "app_error"; public static final String EVENT_APP_ERROR = "app_error";
public static final String EVENT_APP_LAUNCH = "app_launch"; public static final String EVENT_APP_LAUNCH = "app_launch";
public static final String EVENT_COMMENT_CREATE = "comment_create";
public static final String EVENT_BUFFER = "buffer";
public static final String EVENT_EMAIL_ADDED = "email_added"; public static final String EVENT_EMAIL_ADDED = "email_added";
public static final String EVENT_EMAIL_VERIFIED = "email_verified"; public static final String EVENT_EMAIL_VERIFIED = "email_verified";
public static final String EVENT_FIRST_RUN_COMPLETED = "first_run_completed"; public static final String EVENT_FIRST_RUN_COMPLETED = "first_run_completed";
@@ -13,11 +13,12 @@ public class LbryUri {
public static final String LBRY_TV_BASE_URL = "https://lbry.tv"; public static final String LBRY_TV_BASE_URL = "https://lbry.tv";
public static final String PROTO_DEFAULT = "lbry://"; public static final String PROTO_DEFAULT = "lbry://";
public static final String REGEX_INVALID_URI = "[ =&#:$@%?;/\\\\\"<>%\\{\\}|^~\\[\\]`\u0000-\u0008\u000b-\u000c\u000e-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]"; public static final String REGEX_INVALID_URI = "[ =&#:$@%?;/\\\\\"<>%\\{\\}|^~\\[\\]`\u0000-\u0008\u000b-\u000c\u000e-\u001F\uD800-\uDFFF\uFFFE-\uFFFF]";
public static final String REGEX_ADDRESS = "^(b|r)(?=[^0OIl]{32,33})[0-9A-Za-z]{32,33}$"; public static final String REGEX_ADDRESS = "^(b)(?=[^0OIl]{32,33})[0-9A-Za-z]{32,33}$";
public static final int CHANNEL_NAME_MIN_LENGTH = 1; public static final int CHANNEL_NAME_MIN_LENGTH = 1;
public static final int CLAIM_ID_MAX_LENGTH = 40; public static final int CLAIM_ID_MAX_LENGTH = 40;
private static final String REGEX_PART_PROTOCOL = "^((?:lbry://)?)"; private static final String REGEX_PART_PROTOCOL = "^((?:lbry://|https://)?)";
private static final String REGEX_PART_HOST = "((?:open.lbry.com/)?)";
private static final String REGEX_PART_STREAM_OR_CHANNEL_NAME = "([^:$#/]*)"; private static final String REGEX_PART_STREAM_OR_CHANNEL_NAME = "([^:$#/]*)";
private static final String REGEX_PART_MODIFIER_SEPARATOR = "([:$#]?)([^/]*)"; private static final String REGEX_PART_MODIFIER_SEPARATOR = "([:$#]?)([^/]*)";
private static final String QUERY_STRING_BREAKER = "^([\\S]+)([?][\\S]*)"; private static final String QUERY_STRING_BREAKER = "^([\\S]+)([?][\\S]*)";
@@ -58,8 +59,9 @@ public class LbryUri {
return parse(url, false); return parse(url, false);
} }
public static LbryUri parse(String url, boolean requireProto) throws LbryUriException { public static LbryUri parse(String url, boolean requireProto) throws LbryUriException {
Pattern componentsPattern = Pattern.compile(String.format("%s%s%s(/?)%s%s", Pattern componentsPattern = Pattern.compile(String.format("%s%s%s%s(/?)%s%s",
REGEX_PART_PROTOCOL, REGEX_PART_PROTOCOL,
REGEX_PART_HOST,
REGEX_PART_STREAM_OR_CHANNEL_NAME, REGEX_PART_STREAM_OR_CHANNEL_NAME,
REGEX_PART_MODIFIER_SEPARATOR, REGEX_PART_MODIFIER_SEPARATOR,
REGEX_PART_STREAM_OR_CHANNEL_NAME, REGEX_PART_STREAM_OR_CHANNEL_NAME,
@@ -93,37 +95,48 @@ public class LbryUri {
} }
// components[0] = proto // components[0] = proto
// components[1] = streamNameOrChannelName // components[1] = host
// components[2] = primaryModSeparator // components[2] = streamNameOrChannelName
// components[3] = primaryModValue // components[3] = primaryModSeparator
// components[4] = pathSep // components[4] = primaryModValue
// components[5] = possibleStreamName // components[5] = pathSep
// components[6] = secondaryModSeparator // components[6] = possibleStreamName
// components[7] = secondaryModValue // components[7] = secondaryModSeparator
// components[8] = secondaryModValue
if (requireProto && Helper.isNullOrEmpty(components.get(0))) { if (requireProto && Helper.isNullOrEmpty(components.get(0))) {
throw new LbryUriException("LBRY URLs must include a protocol prefix (lbry://)."); throw new LbryUriException("LBRY URLs must include a protocol prefix (lbry://).");
} }
if (Helper.isNullOrEmpty(components.get(1))) { if (Helper.isNullOrEmpty(components.get(2))) {
throw new LbryUriException("URL does not include name."); throw new LbryUriException("URL does not include name.");
} }
for (String component : components.subList(1, components.size())) { for (String component : components.subList(2, components.size())) {
if (component.indexOf(' ') > -1) { if (component.indexOf(' ') > -1) {
throw new LbryUriException("URL cannot include a space."); throw new LbryUriException("URL cannot include a space.");
} }
} }
String streamOrChannelName = components.get(1); String streamOrChannelName = components.get(2);
String primaryModSeparator = components.get(2); String primaryModSeparator = components.get(3);
String primaryModValue = components.get(3); String primaryModValue = components.get(4);
String possibleStreamName = components.get(5); String possibleStreamName = components.get(6);
String secondaryModSeparator = components.get(6); String secondaryModSeparator = components.get(7);
String secondaryModValue = components.get(7); String secondaryModValue = components.get(8);
boolean includesChannel = streamOrChannelName.startsWith("@"); boolean includesChannel = streamOrChannelName.startsWith("@");
boolean isChannel = includesChannel && Helper.isNullOrEmpty(possibleStreamName); boolean isChannel = includesChannel && Helper.isNullOrEmpty(possibleStreamName);
String channelName = includesChannel && streamOrChannelName.length() > 1 ? streamOrChannelName.substring(1) : null; String channelName = includesChannel && streamOrChannelName.length() > 1 ? streamOrChannelName.substring(1) : null;
// It would have thrown already on the RegEx parser if protocol value was incorrect
// open.lbry.com uses ':' as ModSeparators while lbry:// expects '#'
if (components.get(1).equals("open.lbry.com/")) {
if (primaryModSeparator.equals(":"))
primaryModSeparator = "#";
if (secondaryModSeparator.equals(":"))
secondaryModSeparator = "#";
}
if (includesChannel) { if (includesChannel) {
if (Helper.isNullOrEmpty(channelName)) { if (Helper.isNullOrEmpty(channelName)) {
throw new LbryUriException("No channel name after @."); throw new LbryUriException("No channel name after @.");
@@ -147,7 +160,7 @@ public class LbryUri {
LbryUri uri = new LbryUri(); LbryUri uri = new LbryUri();
uri.setChannel(isChannel); uri.setChannel(isChannel);
uri.setPath(Helper.join(components.subList(1, components.size()), "")); uri.setPath(Helper.join(components.subList(2, components.size()), ""));
uri.setStreamName(streamName); uri.setStreamName(streamName);
uri.setStreamClaimId(streamClaimId); uri.setStreamClaimId(streamClaimId);
uri.setChannelName(channelName); uri.setChannelName(channelName);
@@ -2,11 +2,14 @@ package io.lbry.browser.utils;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo; import android.content.pm.PackageInfo;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.net.Uri; import android.net.Uri;
import android.util.Log; import android.util.Log;
import androidx.preference.PreferenceManager;
import com.google.gson.FieldNamingPolicy; import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
@@ -27,6 +30,7 @@ import java.util.concurrent.TimeUnit;
import io.lbry.browser.BuildConfig; import io.lbry.browser.BuildConfig;
import io.lbry.browser.MainActivity; import io.lbry.browser.MainActivity;
import io.lbry.browser.exceptions.AuthTokenInvalidatedException;
import io.lbry.browser.exceptions.LbryioRequestException; import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException; import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.model.Claim; import io.lbry.browser.model.Claim;
@@ -34,6 +38,7 @@ import io.lbry.browser.model.WalletSync;
import io.lbry.browser.model.lbryinc.Reward; import io.lbry.browser.model.lbryinc.Reward;
import io.lbry.browser.model.lbryinc.Subscription; import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.model.lbryinc.User; import io.lbry.browser.model.lbryinc.User;
import io.lbry.lbrysdk.LbrynetService;
import io.lbry.lbrysdk.Utils; import io.lbry.lbrysdk.Utils;
import lombok.Data; import lombok.Data;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
@@ -44,9 +49,6 @@ import okhttp3.Response;
@Data @Data
public final class Lbryio { public final class Lbryio {
// TODO: Get this from the bundled aar
public static String SDK_VERSION = "0.74.0";
public static User currentUser; public static User currentUser;
public static boolean userHasSyncedWallet = false; public static boolean userHasSyncedWallet = false;
public static String lastRemoteHash; public static String lastRemoteHash;
@@ -99,6 +101,7 @@ public final class Lbryio {
} }
url = uriBuilder.build().toString(); url = uriBuilder.build().toString();
} }
/*if (BuildConfig.DEBUG) { /*if (BuildConfig.DEBUG) {
Log.d(TAG, String.format("Request Method: %s, Sending request to URL: %s", method, url)); Log.d(TAG, String.format("Request Method: %s, Sending request to URL: %s", method, url));
}*/ }*/
@@ -202,7 +205,7 @@ public final class Lbryio {
} }
} }
public static User fetchCurrentUser(Context context) { public static User fetchCurrentUser(Context context) throws AuthTokenInvalidatedException {
try { try {
Response response = Lbryio.call("user", "me", context); Response response = Lbryio.call("user", "me", context);
JSONObject object = (JSONObject) parseResponse(response); JSONObject object = (JSONObject) parseResponse(response);
@@ -212,7 +215,23 @@ public final class Lbryio {
return user; return user;
} catch (LbryioRequestException | LbryioResponseException | ClassCastException | IllegalStateException ex) { } catch (LbryioRequestException | LbryioResponseException | ClassCastException | IllegalStateException ex) {
LbryAnalytics.logError(String.format("/user/me failed: %s", ex.getMessage()), ex.getClass().getName()); LbryAnalytics.logError(String.format("/user/me failed: %s", ex.getMessage()), ex.getClass().getName());
android.util.Log.e(TAG, "Could not retrieve the current user", ex);
if (ex instanceof LbryioResponseException) {
LbryioResponseException error = (LbryioResponseException) ex;
if (error.getStatusCode() == 403) {
// auth token invalidated
AUTH_TOKEN = null;
// remove the cached auth token
if (context != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().remove(MainActivity.PREFERENCE_KEY_AUTH_TOKEN).apply();
}
throw new AuthTokenInvalidatedException();
}
}
Log.e(TAG, "Could not retrieve the current user", ex);
return null; return null;
} }
} }
@@ -239,7 +258,7 @@ public final class Lbryio {
options.put("app_version", appVersion); options.put("app_version", appVersion);
options.put("app_id", Lbry.INSTALLATION_ID); options.put("app_id", Lbry.INSTALLATION_ID);
options.put("node_id", ""); options.put("node_id", "");
options.put("daemon_version", SDK_VERSION); options.put("daemon_version", LbrynetService.LBRY_SDK_VERSION);
options.put("operating_system", "android"); options.put("operating_system", "android");
options.put("platform", String.format("Android %s (API %d)", Utils.getAndroidRelease(), Utils.getAndroidSdk())); options.put("platform", String.format("Android %s (API %d)", Utils.getAndroidRelease(), Utils.getAndroidSdk()));
try { try {
@@ -258,7 +277,7 @@ public final class Lbryio {
return currentUser != null && currentUser.isHasVerifiedEmail(); return currentUser != null && currentUser.isHasVerifiedEmail();
} }
public static void authenticate(Context context) { public static void authenticate(Context context) throws AuthTokenInvalidatedException {
User user = fetchCurrentUser(context); User user = fetchCurrentUser(context);
if (user != null) { if (user != null) {
currentUser = user; currentUser = user;
@@ -290,7 +309,7 @@ public final class Lbryio {
context.sendBroadcast(intent); context.sendBroadcast(intent);
} }
} catch (Exception ex) { } catch (Exception ex) {
android.util.Log.e(TAG, "Error sending encrypted auth token action broadcast", ex); Log.e(TAG, "Error sending encrypted auth token action broadcast", ex);
// pass // pass
} }
} }
@@ -40,9 +40,11 @@ public class Lighthouse {
Uri.Builder uriBuilder = Uri.parse(String.format("%s/search", CONNECTION_STRING)).buildUpon(). Uri.Builder uriBuilder = Uri.parse(String.format("%s/search", CONNECTION_STRING)).buildUpon().
appendQueryParameter("s", rawQuery). appendQueryParameter("s", rawQuery).
appendQueryParameter("resolve", "true"). appendQueryParameter("resolve", "true").
appendQueryParameter("nsfw", String.valueOf(nsfw).toLowerCase()).
appendQueryParameter("size", String.valueOf(size)). appendQueryParameter("size", String.valueOf(size)).
appendQueryParameter("from", String.valueOf(from)); appendQueryParameter("from", String.valueOf(from));
if (!nsfw) {
uriBuilder.appendQueryParameter("nsfw", String.valueOf(nsfw).toLowerCase());
}
if (!Helper.isNullOrEmpty(relatedTo)) { if (!Helper.isNullOrEmpty(relatedTo)) {
uriBuilder.appendQueryParameter("related_to", relatedTo); uriBuilder.appendQueryParameter("related_to", relatedTo);
} }
@@ -1878,7 +1878,8 @@ public final class Predefined {
new Language("no", "Norwegian", R.string.norwegian), new Language("no", "Norwegian", R.string.norwegian),
new Language("ro", "Romanian", R.string.romanian), new Language("ro", "Romanian", R.string.romanian),
new Language("hi", "Hindi", R.string.hindi), new Language("hi", "Hindi", R.string.hindi),
new Language("el", "Greek", R.string.greek) new Language("el", "Greek", R.string.greek),
new Language("ca", "Catalan", R.string.catalan)
); );
public static final String LICENSE_COPYRIGHTED = "Copyrighted"; public static final String LICENSE_COPYRIGHTED = "Copyrighted";
@@ -0,0 +1,11 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24"
android:tint="#FFFFFF"
android:alpha="0.8">
<path
android:fillColor="#FF000000"
android:pathData="M12,22c1.1,0 2,-0.9 2,-2h-4c0,1.1 0.89,2 2,2zM18,16v-5c0,-3.07 -1.64,-5.64 -4.5,-6.32L13.5,4c0,-0.83 -0.67,-1.5 -1.5,-1.5s-1.5,0.67 -1.5,1.5v0.68C7.63,5.36 6,7.92 6,11v5l-2,2v1h16v-1l-2,-2z"/>
</vector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 KiB

After

Width:  |  Height:  |  Size: 562 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 278 KiB

After

Width:  |  Height:  |  Size: 523 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 273 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 KiB

After

Width:  |  Height:  |  Size: 562 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 278 KiB

After

Width:  |  Height:  |  Size: 523 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 203 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 KiB

After

Width:  |  Height:  |  Size: 562 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 278 KiB

After

Width:  |  Height:  |  Size: 523 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 333 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 265 KiB

After

Width:  |  Height:  |  Size: 562 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 278 KiB

After

Width:  |  Height:  |  Size: 523 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 477 B

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/red" />
<corners android:radius="16dp" />
</shape>
@@ -11,6 +11,11 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="match_parent"> android:layout_height="match_parent">
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/verification_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<RelativeLayout <RelativeLayout
android:id="@+id/verification_close_button" android:id="@+id/verification_close_button"
android:visibility="gone" android:visibility="gone"
@@ -29,10 +34,6 @@
android:tint="@color/white" /> android:tint="@color/white" />
</RelativeLayout> </RelativeLayout>
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/verification_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar <ProgressBar
android:id="@+id/verification_loading_progress" android:id="@+id/verification_loading_progress"
android:visibility="gone" android:visibility="gone"
+38 -2
View File
@@ -28,20 +28,22 @@
android:focusable="true" android:focusable="true"
android:focusableInTouchMode="true" android:focusableInTouchMode="true"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content">
android:layout_marginRight="24dp">
<EditText <EditText
android:id="@+id/wunderbar" android:id="@+id/wunderbar"
android:background="@android:color/transparent" android:background="@android:color/transparent"
android:layout_centerVertical="true"
android:drawableLeft="@drawable/ic_search" android:drawableLeft="@drawable/ic_search"
android:drawablePadding="8dp" android:drawablePadding="8dp"
android:drawableTint="@color/actionBarForeground" android:drawableTint="@color/actionBarForeground"
android:fontFamily="@font/inter" android:fontFamily="@font/inter"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginRight="24dp"
android:hint="@string/uri_placeholder" android:hint="@string/uri_placeholder"
android:imeOptions="actionGo" android:imeOptions="actionGo"
android:inputType="textNoSuggestions" android:inputType="textNoSuggestions"
android:paddingRight="36dp"
android:selectAllOnFocus="true" android:selectAllOnFocus="true"
android:singleLine="true" android:singleLine="true"
android:textFontWeight="300" android:textFontWeight="300"
@@ -52,6 +54,7 @@
android:background="?attr/selectableItemBackground" android:background="?attr/selectableItemBackground"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginRight="24dp"
android:layout_alignParentRight="true" android:layout_alignParentRight="true"
android:layout_centerVertical="true" android:layout_centerVertical="true"
android:visibility="gone"> android:visibility="gone">
@@ -61,6 +64,39 @@
android:src="@drawable/ic_close" android:src="@drawable/ic_close"
android:tint="@color/actionBarForeground" /> android:tint="@color/actionBarForeground" />
</LinearLayout> </LinearLayout>
<RelativeLayout
android:id="@+id/wunderbar_notifications"
android:clickable="true"
android:background="?attr/selectableItemBackground"
android:layout_width="48dp"
android:layout_height="match_parent"
android:layout_alignParentRight="true"
android:layout_centerVertical="true">
<ImageView
android:id="@+id/notifications_toggle_icon"
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_centerInParent="true"
android:src="@drawable/ic_notifications"
android:tint="@color/actionBarForeground" />
<TextView
android:id="@+id/notifications_badge_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/bg_notification_badge"
android:fontFamily="@font/inter"
android:gravity="center_horizontal"
android:minWidth="12dp"
android:paddingLeft="2dp"
android:paddingRight="2dp"
android:layout_marginTop="12dp"
android:layout_marginLeft="24dp"
android:textColor="@color/white"
android:textSize="10sp"
android:visibility="invisible"
/>
</RelativeLayout>
</RelativeLayout> </RelativeLayout>
</androidx.appcompat.widget.Toolbar> </androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout> </com.google.android.material.appbar.AppBarLayout>
@@ -69,11 +69,22 @@
android:textFontWeight="300" /> android:textFontWeight="300" />
</RelativeLayout> </RelativeLayout>
<com.google.android.material.button.MaterialButton
android:id="@+id/wallet_buy_lbc_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/inter"
android:text="@string/buy_lbc"
android:layout_marginTop="8dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:textSize="16sp" />
<TextView <TextView
android:id="@+id/wallet_hint_convert_credits" android:id="@+id/wallet_hint_convert_credits"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="16dp" android:layout_marginTop="6dp"
android:layout_marginLeft="16dp" android:layout_marginLeft="16dp"
android:layout_marginRight="16dp" android:layout_marginRight="16dp"
android:fontFamily="@font/inter" android:fontFamily="@font/inter"
@@ -0,0 +1,187 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/comment_form_card"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:text="@string/comment_as"
android:fontFamily="@font/inter"
android:textSize="14sp"
android:textFontWeight="300" />
<ProgressBar
android:id="@+id/comment_form_channels_loading"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_width="20dp"
android:layout_height="20dp"
android:visibility="gone" />
</RelativeLayout>
<androidx.appcompat.widget.AppCompatSpinner
android:id="@+id/comment_form_channel_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="4dp" />
<include layout="@layout/container_inline_channel_form" />
<LinearLayout
android:id="@+id/comment_form_reply_to_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:layout_marginBottom="8dp"
android:orientation="horizontal"
android:visibility="gone">
<View
android:id="@+id/comment_form_reply_to_vertical_bar"
android:layout_width="3dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/nextLbryGreen" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginRight="40dp">
<TextView
android:id="@+id/comment_form_replying_to_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/inter"
android:text="@string/replying_to"
android:textColor="@color/lightGrey"
android:textSize="12sp" />
<TextView
android:id="@+id/comment_form_reply_to_body"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:lineSpacingMultiplier="1.05"
android:fontFamily="@font/inter"
android:textFontWeight="300"
android:textSize="14sp" />
</LinearLayout>
<RelativeLayout
android:id="@+id/comment_form_clear_reply_to"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:layout_alignParentRight="true"
android:layout_width="36dp"
android:layout_height="36dp">
<ImageView
android:layout_width="24dp"
android:layout_height="24dp"
android:layout_centerInParent="true"
android:src="@drawable/ic_close"
android:tint="@color/foreground" />
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp">
<RelativeLayout
android:id="@+id/comment_form_avatar_container"
android:layout_width="40dp"
android:layout_height="40dp">
<RelativeLayout
android:layout_centerHorizontal="true"
android:background="@drawable/bg_channel_icon"
android:id="@+id/comment_form_no_thumbnail"
android:layout_width="40dp"
android:layout_height="40dp"
android:visibility="invisible">
<TextView
android:id="@+id/comment_form_thumbnail_alpha"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/inter"
android:textAllCaps="true"
android:textSize="24sp"
android:textColor="@color/white"
android:textFontWeight="300" />
</RelativeLayout>
<ImageView
android:layout_centerInParent="true"
android:id="@+id/comment_form_thumbnail"
android:layout_width="40dp"
android:layout_height="40dp" />
</RelativeLayout>
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/comment_form_avatar_container"
android:layout_marginLeft="16dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/comment_form_body"
android:hint="@string/comment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="@font/inter"
android:textFontWeight="300"
android:inputType="textMultiLine"
android:maxLength="2000"
android:singleLine="false"
android:scrollbars="vertical"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
</RelativeLayout>
<TextView
android:id="@+id/comment_form_text_limit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="2dp"
android:fontFamily="@font/inter"
android:textColor="@color/lightGrey"
android:textFontWeight="300"
android:textSize="12sp" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp">
<com.google.android.material.button.MaterialButton
android:id="@+id/comment_form_post"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/inter" />
<ProgressBar
android:id="@+id/comment_form_post_progress"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_centerVertical="true"
android:layout_toRightOf="@id/comment_form_post"
android:layout_marginLeft="24dp"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
Loaded 100 of 140 files, more files were not shown because too many files have changed in this diff. Show more