Compare commits

..
116 Commits
Author SHA1 Message Date
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
Akinwale Ariwodola e85ca9114c Merge pull request #921 from lbryio/crash-fixes
fixes for Play Store crash reports
2020-05-31 16:20:59 +01:00
Akinwale Ariwodola 85ed2da518 fixes for Play Store crash reports 2020-05-31 16:19:33 +01:00
Clayton Hickey dcc91f75cc Added ability to read comments on claims (#920)
* Added ability to read comments on claims
* Added simple handling for pagination in CommentListTask
2020-05-30 00:47:50 +01:00
Akinwale Ariwodola a40c160ac6 fix selection mode for reposts on Publishes page 2020-05-28 03:45:56 +01:00
Akinwale Ariwodola e6861c8436 set timestamp when building claim object from edited claim 2020-05-28 03:25:42 +01:00
Akinwale Ariwodola e6a5d97fb8 bumpversion 0.15.8 --> 0.15.9 2020-05-28 03:23:45 +01:00
Akinwale Ariwodola ddeb209d51 fix publish release time and crash bug on publish form 2020-05-28 03:22:20 +01:00
Akinwale Ariwodola 3283b3a607 fix channel links on history page 2020-05-27 23:22:08 +01:00
Akinwale Ariwodola 83a41ca6ce auto-rotate video to sensor landscape orientation 2020-05-27 23:16:25 +01:00
Akinwale Ariwodola 6c63eb7d66 better handling of permanent storage permission denial on file view page 2020-05-27 23:11:09 +01:00
Akinwale Ariwodola 7cf9de8c2a fix typo 2020-05-27 23:01:00 +01:00
Akinwale Ariwodola a859682954 fix permission request handling for permanently denied permissions 2020-05-27 22:56:07 +01:00
Akinwale Ariwodola c844c4f896 fix PIP mode display for Android version < 10 2020-05-27 11:20:51 +01:00
Akinwale Ariwodola a49cfe91da remove debug logs 2020-05-27 10:58:28 +01:00
Akinwale Ariwodola 2bacba2c87 properly close all activities when service is stopped 2020-05-27 10:52:25 +01:00
Akinwale Ariwodola e473981063 fix more crash bugs reported in Play Store 2020-05-27 08:25:10 +01:00
Akinwale Ariwodola 34ea4f216c add Dutch and Hindi strings 2020-05-27 02:06:41 +01:00
Akinwale Ariwodola 52e34b3027 don't hide play / pause button while buffering 2020-05-27 01:15:02 +01:00
Akinwale Ariwodola c6a6ea0445 reset click listener onStop 2020-05-27 01:11:18 +01:00
Akinwale Ariwodola 59ae6340e1 disable gif animation in thumbnails 2020-05-27 00:56:07 +01:00
Akinwale Ariwodola cbf2aa2311 bumpversion 0.15.6 --> 0.15.7 2020-05-26 16:26:15 +01:00
Akinwale Ariwodola 94b0c7bc01 Fix additional Play Store crash bugs. 2020-05-26 16:25:37 +01:00
Akinwale Ariwodola 4c50ffac19 Merge pull request #898 from lbryio/user-bugs
fix reported bugs from 0.15.3
2020-05-26 16:09:51 +01:00
Akinwale Ariwodola 551e736651 fix reported bugs from 0.15.3 2020-05-26 16:09:14 +01:00
Akinwale Ariwodola 0380e35966 bumpversion 0.15.5 --> 0.15.6 2020-05-26 10:58:47 +01:00
Akinwale Ariwodola 5de0906fc1 make splash view clickable to prevent clicking views underneath 2020-05-26 10:57:12 +01:00
Akinwale Ariwodola c2f17b6230 Add Italian strings. Save and resume from last media playback position. 2020-05-26 10:38:16 +01:00
Akinwale Ariwodola 6a3bbe6c0d bumpversion 0.15.4 --> 0.15.5 2020-05-25 20:10:34 +01:00
Akinwale Ariwodola 82307c9f98 Increase timeout for remote user requests. Wrap long pre lines in markdown display. 2020-05-25 20:08:24 +01:00
Akinwale Ariwodola d2ec0e2aa1 Display reposts on following page. Update Spanish strings. 2020-05-25 15:15:48 +01:00
Akinwale Ariwodola 3951b1080d different new publish from publish update 2020-05-25 12:14:12 +01:00
Akinwale Ariwodola ef7caeeead Fix subsequent web view display. Add Estonian and Russian strings. 2020-05-25 11:33:12 +01:00
Akinwale Ariwodola 7ef8e2029e Tweak transaction pending text display 2020-05-25 06:03:46 +01:00
Akinwale Ariwodola aaec6ac6a3 wait for uploads to finish before saving channel form 2020-05-25 06:00:34 +01:00
Akinwale Ariwodola 731960da7c bumpversion 0.15.3 --> 0.15.4 2020-05-25 05:50:02 +01:00
Akinwale Ariwodola ac282d2667 log cleanup 2020-05-25 05:48:26 +01:00
Akinwale Ariwodola 7a79601cfc don't enable fullscreen mode when entering PIP mode 2020-05-25 05:47:14 +01:00
Akinwale Ariwodola d1167e4d2b Disable selection mode for purchases. Check additional cases for displaying unsupported content message. 2020-05-25 05:38:25 +01:00
Akinwale Ariwodola 613634adcf get transaction id for first_publish and new_channel rewards 2020-05-25 00:32:21 +01:00
Akinwale Ariwodola acbe33c66d Limit gallery items to 150. Download filtering. Open rewards page from Invites reward driver card. 2020-05-25 00:04:40 +01:00
Akinwale Ariwodola 053ebbd70b dDisplay better error message if authentication fails on first run. Change lineHeight to lineSpacingMultiplier. 2020-05-24 21:27:49 +01:00
Akinwale Ariwodola f5dc4fa4e7 Remove new intent debug logs. Update packages in build.gradle 2020-05-24 20:48:01 +01:00
Akinwale Ariwodola 343270b757 Show auto-claim rewards message at activity level. Add German strings. 2020-05-24 20:34:19 +01:00
Akinwale Ariwodola 65f5626aba More tweaks to PIP mode restore. 2020-05-24 20:29:11 +01:00
Akinwale Ariwodola a051a73c2b Tweak PIP restore. Fix Library wunderbar value. 2020-05-24 18:54:33 +01:00
Akinwale Ariwodola 6840997793 Add 'subscription' to special URLs map. Fix PIP restore for onNewIntent. 2020-05-24 18:46:47 +01:00
Akinwale Ariwodola 2c98ed2d8d Always display rewards driver on Invites page. Rewards drivers minimum display amounts. 2020-05-24 18:37:05 +01:00
Akinwale Ariwodola 6a083c4152 Update Afrikaans strings. Add Vietnamese strings. 2020-05-24 18:18:39 +01:00
Akinwale Ariwodola b60b5d16c3 fix crash bugs reported in Play Store 2020-05-24 10:11:31 +01:00
Akinwale Ariwodola 52cfe8dc12 add blocking param to txo_spend 2020-05-24 05:02:55 +01:00
Akinwale Ariwodola 737afca031 fix onNewIntent logging 2020-05-24 04:50:13 +01:00
Akinwale Ariwodola 456f41d28d Prevent image click through. Add Romanian strings. 2020-05-24 04:43:39 +01:00
Akinwale Ariwodola 238f59ad71 display correct label and amount for tip unlocks in tx history 2020-05-24 00:08:14 +01:00
Akinwale Ariwodola cf6d567193 unify button font 2020-05-23 23:47:32 +01:00
Akinwale Ariwodola 20f8f3852d Merge pull request #888 from lbryio/unlock-tips
add option to unlock all tips
2020-05-23 23:39:16 +01:00
Akinwale Ariwodola 4bb9f5cb43 add option to unlock all tips 2020-05-23 23:37:57 +01:00
Akinwale Ariwodola 540a841255 Fix pip restore and fullscreen quirks. French and Portuguese strings added. 2020-05-23 19:42:30 +01:00
Akinwale Ariwodola 3544637405 Fix reward code claiming. Remove broken French strings file. 2020-05-23 17:48:58 +01:00
Akinwale Ariwodola 651448dfa1 Merge pull request #886 from lbryio/reward-drivers
Add reward drivers. French, Indonesian, Malay and Turkish strings.
2020-05-23 17:46:16 +01:00
Akinwale Ariwodola 4bac266b8b Add reward drivers. French, Indonesian, Malay and Turkish strings. 2020-05-23 17:45:19 +01:00
Akinwale Ariwodola f86b61741d Merge pull request #885 from lbryio/visual-tweaks
Use thin divider in transaction history. Set font for action bar title.
2020-05-23 15:18:43 +01:00
Akinwale Ariwodola 6c60d299af Use thin divider in transaction history page. Set font for action bar title. 2020-05-23 15:17:43 +01:00
Akinwale Ariwodola 08582238c3 Merge pull request #884 from lbryio/dark-theme-fix
Fix dark theme reset error due to WebView. Apply dark theme to web views.
2020-05-23 09:41:59 +01:00
Akinwale Ariwodola b931d0ce7d Fix dark theme reset error due to WebView. Apply dark theme to web views. 2020-05-23 09:37:58 +01:00
Akinwale Ariwodola 5e1fc9dbd8 Merge pull request #883 from lbryio/fullscreen-on-rotate
switch to fullscreen mode on rotate when viewing media
2020-05-23 09:03:00 +01:00
Akinwale Ariwodola de4e6eee25 switch to fullscreen mode on rotate when viewing media 2020-05-23 09:01:30 +01:00
Akinwale Ariwodola d5b4e6990f update material components version 2020-05-23 07:53:58 +01:00
Akinwale Ariwodola 26703815b2 cleanup top level directory 2020-05-23 07:51:56 +01:00
Akinwale Ariwodola 40c36df414 Native rewrite (#878)
* initial native rewrite commit
* update gitlab CI script
* add printVersionName gradle task
* fix Gitlab CI script
* Fix first time wallet sync. add Discover dialog to  Following page.
* Finish Following and All Content views. Add customize your tags view.
* Wallet sync get and set preferences, update interval.
* Editor's Choice. Reposts. Some ontent page tweaks.
* display no related content view when none loaded
* Search cache. File view updates. Floating wallet balance.
* Send tip dialog. Channel page share and follow/unfollow.
* Handle lbry:// url scheme. Properly set URL bar values. SDK 0.71.0.
* Channel follow/unfollow fixes. Display stream cost.
* Channel management and channel creation / editing
* phone number verification and rewards page
* add Invites page
* tweak player loading and playback when loading new claims
* tweak about page layout
* display text and markdown content
* purchase_uri for free content
* don't display invites history if none exist
* fix channel list adapters
* change launch mode from singleInstance to singleTask
* url history and player fixes
* Library page. URL and view history.
* bumpversion 0.15.0 --> 0.15.1
* Make file view a fragment to prevent headaches with multiple Android task recents
* Better handling of file view URLs. Some issue list fixes.
* Abandon channels and bulk delete files tasks. Some visual tweaks.
* bumpversion 0.15.1 --> 0.15.2
* fix some events
* Some visual tweaks. Wunderbar clear focus hotfix for some devices.
* sdk 0.74.0. Publish and Publishes pages.
* Fix displayed amounts. Send Firebase token with install_new.
* Some dark theme and crash fixes. Implement publish form.
* Fix minor typo for string in 'generate_address_hint'.
* Publish form and publish creation flow. UI tweaks and fixes.
* Basic native mobile publishing
* remove closeDatabase calls causing crashes
* Implement file and channel page delete actions. UI action cleanup.
* publish drivers for unresolved file page and featured search result item
* show URL suggestions and data network (DHT) settings
* Filter own claims from downloads. Fix address input.
* fix edit channel crash
* fix for possible blank / invalid video thumbnails
* adjust minimum deposit. fix channel edit mode.
* quick skip and playback speed media controls
* change play and pause icons
* Fix file size display. Tweak playback speed control.
* Add exoplayer mediasession extension. Set player auto attributes.
* Inline publish address validation error. Increase image upload request timeout.
* fix no related content display
* Claim new_android reward. Use canonical_url for share links.
* force US locale for amount / bid values sent with sdk requests
* Afrikaans and Spanish strings
* Add media player error handling policy. Use : in share links.
* don't proceed with publish if optimization is in progress.
2020-05-23 07:49:00 +01:00
Akinwale Ariwodola 6eb20d0e08 sdk 0.73.1 patch 2020-05-14 14:40:12 +01:00
225 changed files with 28070 additions and 3601 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
.buildozer
.buildozer-downloads
.gradle
+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)
[![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" />
@@ -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.
## 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
Contributions to this project are welcome, encouraged, and compensated. For more details, see https://lbry.io/faq/contributing
+21 -9
View File
@@ -1,3 +1,5 @@
import com.google.gms.googleservices.GoogleServicesPlugin
apply plugin: 'com.android.application'
android {
@@ -14,8 +16,8 @@ android {
applicationId "io.lbry.browser"
minSdkVersion 21
targetSdkVersion 29
versionCode 1500
versionName "0.15.0"
versionCode 1514
versionName "0.15.14"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
@@ -52,9 +54,9 @@ task printVersionName {
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.appcompat:appcompat:1.3.0-alpha01'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.google.android.material:material:1.3.0-alpha01'
implementation "androidx.cardview:cardview:1.0.0"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment:2.2.2'
@@ -62,17 +64,25 @@ dependencies {
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
implementation 'androidx.preference:preference:1.1.1'
implementation 'androidx.webkit:webkit:1.3.0-alpha03'
implementation 'androidx.camera:camera-core: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-view:1.0.0-alpha10'
implementation 'androidx.browser:browser:1.2.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.squareup.okhttp3:okhttp:4.4.1'
implementation 'com.google.firebase:firebase-analytics:17.4.0'
implementation 'com.google.firebase:firebase-analytics:17.4.2'
implementation 'com.google.android.gms:play-services-base:17.2.1'
implementation 'com.google.firebase:firebase-messaging:20.1.6'
implementation 'com.google.firebase:firebase-messaging:20.2.0'
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-dash:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.11.4'
implementation 'com.google.android.exoplayer:extension-cast:2.11.4'
implementation 'com.google.android.exoplayer:extension-mediasession:2.11.4'
implementation 'com.google.android:flexbox:2.0.1'
@@ -81,6 +91,8 @@ dependencies {
implementation 'com.github.chrisbanes:PhotoView:2.3.0'
implementation 'com.atlassian.commonmark:commonmark:0.14.0'
implementation 'com.arthenica:mobile-ffmpeg-full-gpl:4.3.1.LTS'
compileOnly 'org.projectlombok:lombok:1.18.10'
annotationProcessor 'org.projectlombok:lombok:1.18.10'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
@@ -89,9 +101,9 @@ dependencies {
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
__32bitImplementation files('libs/lbrysdk-0.73.1-release__arm.aar')
__64bitImplementation files('libs/lbrysdk-0.73.1-release__arm64.aar')
__32bitImplementation 'io.lbry:lbrysdk32:0.76.0'
__64bitImplementation 'io.lbry:lbrysdk64:0.76.0'
}
apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true
GoogleServicesPlugin.config.disableVersionCheck = true
Binary file not shown.
Binary file not shown.
+10 -12
View File
@@ -3,23 +3,28 @@
package="io.lbry.browser"
android:installLocation="auto">
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:largeHeap="true"
android:requestLegacyExternalStorage="true"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
<meta-data android:name="com.google.android.gms.cast.framework.OPTIONS_PROVIDER_CLASS_NAME"
android:value="com.google.android.exoplayer2.ext.cast.DefaultCastOptionsProvider"/>
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="@drawable/ic_lbry" />
@@ -38,8 +43,8 @@
android:label="@string/app_name"
android:supportsPictureInPicture="true"
android:theme="@style/AppTheme.NoActionBar"
android:launchMode="singleInstance"
android:windowSoftInputMode="adjustPan">
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
@@ -55,22 +60,15 @@
<activity
android:name=".FirstRunActivity"
android:launchMode="singleInstance"
android:launchMode="singleTask"
android:parentActivityName=".MainActivity"
android:theme="@style/AppTheme.NoActionBarTranslucent" />
<activity
android:name=".VerificationActivity"
android:launchMode="singleInstance"
android:launchMode="singleTask"
android:parentActivityName=".MainActivity"
android:theme="@style/AppTheme.NoActionBarTranslucent"
android:windowSoftInputMode="adjustResize" />
<activity
android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize|screenLayout"
android:name=".FileViewActivity"
android:launchMode="singleInstance"
android:parentActivityName=".MainActivity"
android:supportsPictureInPicture="true"
android:theme="@style/AppTheme.NoActionBarBlack" />
<service
android:name="io.lbry.browser.LbrynetMessagingService"
File diff suppressed because it is too large. Load diff
@@ -10,7 +10,6 @@ import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.text.HtmlCompat;
@@ -20,10 +19,11 @@ import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.Lbryio;
import io.lbry.lbrysdk.LbrynetService;
public class FirstRunActivity extends AppCompatActivity {
private BroadcastReceiver sdkReadyReceiver;
private BroadcastReceiver sdkReceiver;
private BroadcastReceiver authReceiver;
@Override
@@ -45,19 +45,26 @@ public class FirstRunActivity extends AppCompatActivity {
registerAuthReceiver();
if (!Lbry.SDK_READY) {
findViewById(R.id.welcome_wait_container).setVisibility(View.VISIBLE);
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_SDK_READY);
sdkReadyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// authenticate after we receive the sdk ready event
authenticate();
}
};
registerReceiver(sdkReadyReceiver, filter);
} else {
authenticate();
}
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_SDK_READY);
filter.addAction(LbrynetService.ACTION_STOP_SERVICE);
sdkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (MainActivity.ACTION_SDK_READY.equals(action)) {
// authenticate after we receive the sdk ready event
authenticate();
} else if (LbrynetService.ACTION_STOP_SERVICE.equals(action)) {
finish();
}
}
};
registerReceiver(sdkReceiver, filter);
}
public void onResume() {
@@ -97,7 +104,8 @@ public class FirstRunActivity extends AppCompatActivity {
}
private void handleAuthenticationFailed() {
Toast.makeText(this, "Authentication failed.", Toast.LENGTH_LONG).show();
findViewById(R.id.welcome_progress_bar).setVisibility(View.GONE);
((TextView) findViewById(R.id.welcome_wait_text)).setText(R.string.startup_failed);
}
private void authenticate() {
@@ -121,7 +129,7 @@ public class FirstRunActivity extends AppCompatActivity {
@Override
protected void onDestroy() {
Helper.unregisterReceiver(authReceiver, this);
Helper.unregisterReceiver(sdkReadyReceiver, this);
Helper.unregisterReceiver(sdkReceiver, this);
super.onDestroy();
}
File diff suppressed because it is too large. Load diff
@@ -1,6 +1,9 @@
package io.lbry.browser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
@@ -18,8 +21,10 @@ import io.lbry.browser.listener.SignInListener;
import io.lbry.browser.listener.WalletSyncListener;
import io.lbry.browser.model.lbryinc.User;
import io.lbry.browser.tasks.lbryinc.FetchCurrentUserTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.Lbryio;
import io.lbry.lbrysdk.LbrynetService;
public class VerificationActivity extends FragmentActivity implements SignInListener, WalletSyncListener {
@@ -27,6 +32,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
public static final int VERIFICATION_FLOW_REWARDS = 2;
public static final int VERIFICATION_FLOW_WALLET = 3;
private BroadcastReceiver sdkReceiver;
private String email;
private boolean signedIn;
private int flow;
@@ -54,6 +60,19 @@ public class VerificationActivity extends FragmentActivity implements SignInList
return;
}
IntentFilter filter = new IntentFilter();
filter.addAction(LbrynetService.ACTION_STOP_SERVICE);
sdkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (LbrynetService.ACTION_STOP_SERVICE.equals(action)) {
finish();
}
}
};
registerReceiver(sdkReceiver, filter);
setContentView(R.layout.activity_verification);
ViewPager2 viewPager = findViewById(R.id.verification_pager);
viewPager.setUserInputEnabled(false);
@@ -158,7 +177,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
@Override
public void onError(Exception error) {
showFetchUserError(error.getMessage());
showFetchUserError(error != null ? error.getMessage() : getString(R.string.fetch_current_user_error));
hideLoading();
}
});
@@ -194,7 +213,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
}
@Override
public void onError(Exception error) {
showFetchUserError(error.getMessage());
showFetchUserError(error != null ? error.getMessage() : getString(R.string.fetch_current_user_error));
hideLoading();
}
});
@@ -231,7 +250,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
@Override
public void onError(Exception error) {
showFetchUserError(error.getMessage());
showFetchUserError(error != null ? error.getMessage() : getString(R.string.fetch_current_user_error));
hideLoading();
}
});
@@ -239,7 +258,8 @@ public class VerificationActivity extends FragmentActivity implements SignInList
}
private void showFetchUserError(String message) {
Snackbar.make(findViewById(R.id.verification_pager), message, Snackbar.LENGTH_LONG).setBackgroundTint(Color.RED).show();
Snackbar.make(findViewById(R.id.verification_pager), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
@Override
@@ -268,4 +288,10 @@ public class VerificationActivity extends FragmentActivity implements SignInList
public void onWalletSyncFailed(Exception error) {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
}
@Override
public void onDestroy() {
Helper.unregisterReceiver(sdkReceiver, this);
super.onDestroy();
}
}
@@ -101,7 +101,7 @@ public class ChannelFilterListAdapter extends RecyclerView.Adapter<ChannelFilter
}
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.alphaView.setText(claim.isPlaceholder() ? null : claim.getName().substring(1, 2));
vh.alphaView.setText(claim.isPlaceholder() ? null : claim.getName() != null ? claim.getName().substring(1, 2) : "");
int bgColor = Helper.generateRandomColorForValue(claim.getClaimId());
Helper.setIconViewBackgroundColor(vh.alphaContainer, bgColor, claim.isPlaceholder(), context);
@@ -6,8 +6,8 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
@@ -17,13 +17,18 @@ import com.google.android.material.snackbar.Snackbar;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.listener.SelectionModeListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.LbryFile;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Lbryio;
import lombok.Getter;
import lombok.Setter;
@@ -32,6 +37,13 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
private static final int VIEW_TYPE_CHANNEL = 2;
private static final int VIEW_TYPE_FEATURED = 3; // featured search result
private Map<String, Claim> quickClaimIdMap;
private Map<String, Claim> quickClaimUrlMap;
private Map<String, Boolean> notFoundClaimIdMap;
private Map<String, Boolean> notFoundClaimUrlMap;
@Setter
private boolean hideFee;
@Setter
private boolean canEnterSelectionMode;
private Context context;
@@ -44,11 +56,25 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
private boolean inSelectionMode;
@Setter
private SelectionModeListener selectionModeListener;
private float scale;
public ClaimListAdapter(List<Claim> items, 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<>();
quickClaimIdMap = new HashMap<>();
quickClaimUrlMap = new HashMap<>();
notFoundClaimIdMap = new HashMap<>();
notFoundClaimUrlMap = new HashMap<>();
if (context != null) {
scale = context.getResources().getDisplayMetrics().density;
}
}
public List<Claim> getSelectedItems() {
@@ -73,12 +99,45 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
return null;
}
public void removeFeaturedItem() {
int featuredIndex = -1;
for (int i = 0; i < items.size(); i++) {
if (items.get(i).isFeatured()) {
featuredIndex = i;
break;
}
}
if (featuredIndex > -1) {
items.remove(featuredIndex);
}
}
public List<Claim> getItems() {
return new ArrayList<>(this.items);
}
public void updateSigningChannelForClaim(Claim resolvedClaim) {
for (Claim claim : items) {
if (claim.getClaimId().equalsIgnoreCase(resolvedClaim.getClaimId())) {
claim.setSigningChannel(resolvedClaim.getSigningChannel());
}
}
}
public void clearItems() {
clearSelectedItems();
this.items.clear();
quickClaimIdMap.clear();
quickClaimUrlMap.clear();
notFoundClaimIdMap.clear();
notFoundClaimUrlMap.clear();
notifyDataSetChanged();
}
public Claim getLastItem() {
return items.size() > 0 ? items.get(items.size() - 1) : null;
}
public void addFeaturedItem(Claim claim) {
items.add(0, claim);
notifyDataSetChanged();
@@ -86,14 +145,27 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
public void addItems(List<Claim> claims) {
for (Claim claim : claims) {
if (!items.contains(claim)) {
if (claim != null && !items.contains(claim)) {
items.add(claim);
}
}
notFoundClaimUrlMap.clear();
notFoundClaimIdMap.clear();
notifyDataSetChanged();
}
public void setItems(List<Claim> claims) {
items = new ArrayList<>();
for (Claim claim : claims) {
if (claim != null) {
items.add(claim);
}
}
notifyDataSetChanged();
}
public void setItems(List<Claim> claims) {
items = new ArrayList<>(claims);
public void removeItems(List<Claim> claims) {
items.removeAll(claims);
notifyDataSetChanged();
}
@@ -118,6 +190,9 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
protected View repostInfoView;
protected TextView repostChannelView;
protected View selectedOverlayView;
protected TextView fileSizeView;
protected ProgressBar downloadProgressView;
protected TextView deviceView;
public ViewHolder(View v) {
super(v);
feeContainer = v.findViewById(R.id.claim_fee_container);
@@ -134,6 +209,9 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
repostInfoView = v.findViewById(R.id.claim_repost_info);
repostChannelView = v.findViewById(R.id.claim_repost_channel);
selectedOverlayView = v.findViewById(R.id.claim_selected_overlay);
fileSizeView = v.findViewById(R.id.claim_file_size);
downloadProgressView = v.findViewById(R.id.claim_download_progress);
deviceView = v.findViewById(R.id.claim_view_device);
}
}
@@ -155,6 +233,68 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
return Claim.TYPE_CHANNEL.equalsIgnoreCase(actualClaim.getValueType()) ? VIEW_TYPE_CHANNEL : VIEW_TYPE_STREAM;
}
public void updateFileForClaimByIdOrUrl(LbryFile file, String claimId, String url) {
updateFileForClaimByIdOrUrl(file, claimId, url, false);
}
public void updateFileForClaimByIdOrUrl(LbryFile file, String claimId, String url, boolean skipNotFound) {
if (!skipNotFound) {
if (notFoundClaimIdMap.containsKey(claimId) && notFoundClaimUrlMap.containsKey(url)) {
return;
}
}
if (quickClaimIdMap.containsKey(claimId)) {
quickClaimIdMap.get(claimId).setFile(file);
notifyDataSetChanged();
return;
}
if (quickClaimUrlMap.containsKey(claimId)) {
quickClaimUrlMap.get(claimId).setFile(file);
notifyDataSetChanged();
return;
}
boolean claimFound = false;
for (int i = 0; i < items.size(); i++) {
Claim claim = items.get(i);
if (claimId.equalsIgnoreCase(claim.getClaimId()) || url.equalsIgnoreCase(claim.getPermanentUrl())) {
quickClaimIdMap.put(claimId, claim);
quickClaimUrlMap.put(url, claim);
claim.setFile(file);
notifyDataSetChanged();
claimFound = true;
break;
}
}
if (!claimFound) {
notFoundClaimIdMap.put(claimId, true);
notFoundClaimUrlMap.put(url, true);
}
}
public void clearFileForClaimOrUrl(String outpoint, String url) {
clearFileForClaimOrUrl(outpoint, url, false);
notifyDataSetChanged();
}
public void clearFileForClaimOrUrl(String outpoint, String url, boolean remove) {
int claimIndex = -1;
for (int i = 0; i < items.size(); i++) {
Claim claim = items.get(i);
if (outpoint.equalsIgnoreCase(claim.getOutpoint()) || url.equalsIgnoreCase(claim.getPermanentUrl())) {
claimIndex = i;
claim.setFile(null);
break;
}
}
if (remove && claimIndex > -1) {
Claim removed = items.remove(claimIndex);
selectedItems.remove(removed);
}
notifyDataSetChanged();
}
@Override
public ClaimListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
int viewResourceId = -1;
@@ -171,10 +311,16 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
@Override
public void onBindViewHolder(ClaimListAdapter.ViewHolder vh, int position) {
int type = getItemViewType(position);
int paddingTop = position == 0 ? 16 : 8;
int paddingBottom = position == getItemCount() - 1 ? 16 : 8;
int paddingTopScaled = Helper.getScaledValue(paddingTop, scale);
int paddingBottomScaled = Helper.getScaledValue(paddingBottom, scale);
vh.itemView.setPadding(vh.itemView.getPaddingLeft(), paddingTopScaled, vh.itemView.getPaddingRight(), paddingBottomScaled);
Claim original = items.get(position);
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 signingChannel = item.getSigningChannel();
Claim.StreamMetadata streamMetadata = null;
@@ -189,19 +335,22 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
}
boolean isPending = item.getConfirmations() == 0;
boolean isSelected = isClaimSelected(item);
boolean isSelected = isClaimSelected(original);
vh.itemView.setSelected(isSelected);
vh.selectedOverlayView.setVisibility(isSelected ? View.VISIBLE : View.GONE);
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isPending) {
Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG).show();
Snackbar snackbar = Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG);
TextView snackbarText = snackbar.getView().findViewById(com.google.android.material.R.id.snackbar_text);
snackbarText.setMaxLines(5);
snackbar.show();
return;
}
if (inSelectionMode) {
toggleSelectedClaim(item);
toggleSelectedClaim(original);
} else {
if (listener != null) {
listener.onClaimClicked(item);
@@ -217,7 +366,10 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
}
if (isPending) {
Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG).show();
Snackbar snackbar = Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG);
TextView snackbarText = snackbar.getView().findViewById(com.google.android.material.R.id.snackbar_text);
snackbarText.setMaxLines(5);
snackbar.show();
return false;
}
@@ -227,7 +379,7 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
selectionModeListener.onEnterSelectionMode();
}
}
toggleSelectedClaim(item);
toggleSelectedClaim(original);
return true;
}
});
@@ -243,7 +395,7 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
vh.publishTimeView.setVisibility(!isPending ? View.VISIBLE : View.GONE);
vh.pendingTextView.setVisibility(isPending ? 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.setOnClickListener(new View.OnClickListener() {
@Override
@@ -274,21 +426,46 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
long duration = item.getDuration();
if (!Helper.isNullOrEmpty(thumbnailUrl)) {
Glide.with(context.getApplicationContext()).
asBitmap().
load(thumbnailUrl).
centerCrop().
placeholder(R.drawable.bg_thumbnail_placeholder).
into(vh.thumbnailView);
vh.thumbnailView.setVisibility(View.VISIBLE);
} else {
vh.thumbnailView.setVisibility(View.GONE);
}
BigDecimal cost = streamMetadata != null && streamMetadata.getFee() != null ? new BigDecimal(streamMetadata.getFee().getAmount()) : new BigDecimal(0);
vh.feeContainer.setVisibility(cost.doubleValue() > 0 ? View.VISIBLE : View.GONE);
vh.feeView.setText(cost.doubleValue() > 0 ? Helper.shortCurrencyFormat(cost.divide(new BigDecimal(100000000)).doubleValue()) : null);
BigDecimal cost = item.getActualCost(Lbryio.LBCUSDRate);
vh.feeContainer.setVisibility(cost.doubleValue() > 0 && !hideFee ? View.VISIBLE : View.GONE);
vh.feeView.setText(cost.doubleValue() > 0 ? Helper.shortCurrencyFormat(cost.doubleValue()) : "Paid");
vh.alphaView.setText(item.getName().substring(0, Math.min(5, item.getName().length() - 1)));
vh.publisherView.setText(signingChannel != null ? signingChannel.getName() : context.getString(R.string.anonymous));
vh.publishTimeView.setText(DateUtils.getRelativeTimeSpanString(
publishTime, System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
vh.durationView.setVisibility(duration > 0 ? View.VISIBLE : View.GONE);
vh.durationView.setText(Helper.formatDuration(duration));
LbryFile claimFile = item.getFile();
boolean isDownloading = false;
int progress = 0;
String fileSizeString = claimFile == null ? null : Helper.formatBytes(claimFile.getTotalBytes(), false);
if (claimFile != null &&
!Helper.isNullOrEmpty(claimFile.getDownloadPath()) &&
!claimFile.isCompleted() &&
claimFile.getWrittenBytes() < claimFile.getTotalBytes()) {
isDownloading = true;
progress = claimFile.getTotalBytes() > 0 ?
Double.valueOf(((double) claimFile.getWrittenBytes() / (double) claimFile.getTotalBytes()) * 100.0).intValue() : 0;
fileSizeString = String.format("%s / %s",
Helper.formatBytes(claimFile.getWrittenBytes(), false),
Helper.formatBytes(claimFile.getTotalBytes(), false));
}
Helper.setViewText(vh.fileSizeView, claimFile != null && !Helper.isNullOrEmpty(claimFile.getDownloadPath()) ? fileSizeString : null);
Helper.setViewVisibility(vh.downloadProgressView, isDownloading ? View.VISIBLE : View.INVISIBLE);
Helper.setViewProgress(vh.downloadProgressView, progress);
Helper.setViewText(vh.deviceView, item.getDevice());
} else if (Claim.TYPE_CHANNEL.equalsIgnoreCase(item.getValueType())) {
if (!Helper.isNullOrEmpty(thumbnailUrl)) {
Glide.with(context.getApplicationContext()).
@@ -0,0 +1,218 @@
package io.lbry.browser.adapter;
import android.content.Context;
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 java.util.ArrayList;
import java.util.List;
import androidx.recyclerview.widget.LinearLayoutManager;
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.model.Claim;
import io.lbry.browser.model.ClaimCacheKey;
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> {
private List<Comment> items;
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) {
this(items, context, false);
}
public CommentListAdapter(List<Comment> items, Context context, boolean nested) {
this.items = new ArrayList<>(items);
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();
}
@Override
public int getItemCount() {
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 {
protected TextView channelName;
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) {
super(v);
channelName = v.findViewById(R.id.comment_channel_name);
commentTimeView = v.findViewById(R.id.comment_time);
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;
}
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_comment, parent, false);
return new CommentListAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int 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.commentTimeView.setText(DateUtils.getRelativeTimeSpanString(
(comment.getTimestamp() * 1000), System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
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);
}
}
@@ -95,6 +95,7 @@ public class EditorsChoiceItemAdapter extends RecyclerView.Adapter<EditorsChoice
vh.descriptionView.setText(item.getDescription());
if (!Helper.isNullOrEmpty(item.getThumbnailUrl())) {
Glide.with(context.getApplicationContext()).
asBitmap().
load(item.getThumbnailUrl()).
centerCrop().
placeholder(R.drawable.bg_thumbnail_placeholder).
@@ -0,0 +1,119 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.GalleryItem;
import io.lbry.browser.utils.Helper;
import lombok.Setter;
public class GalleryGridAdapter extends RecyclerView.Adapter<GalleryGridAdapter.ViewHolder> {
private Context context;
private List<GalleryItem> items;
@Setter
private GalleryItemClickListener listener;
public GalleryGridAdapter(List<GalleryItem> items, Context context) {
this.items = new ArrayList<>(items);
this.context = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected ImageView thumbnailView;
protected TextView durationView;
public ViewHolder(View v) {
super(v);
thumbnailView = v.findViewById(R.id.gallery_item_thumbnail);
durationView = v.findViewById(R.id.gallery_item_duration);
}
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
public void addItem(GalleryItem item) {
if (!items.contains(item)) {
items.add(item);
notifyDataSetChanged();
}
}
public void addItems(List<GalleryItem> items) {
for (GalleryItem item : items) {
if (!this.items.contains(item)) {
this.items.add(item);
notifyDataSetChanged();
}
}
}
public void clearItems() {
items.clear();
notifyDataSetChanged();
}
@Override
public GalleryGridAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_gallery, root, false);
return new GalleryGridAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(GalleryGridAdapter.ViewHolder vh, int position) {
GalleryItem item = items.get(position);
String thumbnailUrl = item.getThumbnailPath();
Glide.with(context.getApplicationContext()).load(thumbnailUrl).centerCrop().into(vh.thumbnailView);
vh.durationView.setVisibility(item.getDuration() > 0 ? View.VISIBLE : View.INVISIBLE);
vh.durationView.setText(item.getDuration() > 0 ? Helper.formatDuration(Double.valueOf(item.getDuration() / 1000.0).longValue()) : null);
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null) {
listener.onGalleryItemClicked(item);
}
}
});
}
public interface GalleryItemClickListener {
void onGalleryItemClicked(GalleryItem item);
}
public static class GalleryGridItemDecoration extends RecyclerView.ItemDecoration {
private int spanCount;
private int spacing;
public GalleryGridItemDecoration(int spanCount, int spacing) {
this.spanCount = spanCount;
this.spacing = spacing;
}
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildAdapterPosition(view); // item position
int column = position % spanCount; // item column
outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f / spanCount) * spacing)
if (position >= spanCount) {
outRect.top = spacing; // item top
}
}
}
}
@@ -10,6 +10,7 @@ import android.widget.SpinnerAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import io.lbry.browser.R;
@@ -40,6 +41,35 @@ public class InlineChannelSpinnerAdapter extends ArrayAdapter<Claim> {
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) {
for (int i = 0; i < channels.size(); i++) {
Claim channel = channels.get(i);
if (item.getClaimId() != null && item.getClaimId().equalsIgnoreCase(channel.getClaimId())) {
return i;
}
}
return -1;
}
@Override
public View getDropDownView(int position, View view, ViewGroup parent) {
@@ -0,0 +1,53 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.Language;
import io.lbry.browser.utils.Predefined;
public class LanguageSpinnerAdapter extends ArrayAdapter<Language> {
private int layoutResourceId;
private LayoutInflater inflater;
public LanguageSpinnerAdapter(Context context, int resource) {
super(context, resource, 0, Predefined.PUBLISH_LANGUAGES);
inflater = LayoutInflater.from(context);
layoutResourceId = resource;
}
public int getItemPosition(String languageCode) {
for (int i = 0; i < Predefined.PUBLISH_LANGUAGES.size(); i++) {
Language lang = Predefined.PUBLISH_LANGUAGES.get(i);
if (lang.getCode().equalsIgnoreCase(languageCode)) {
return i;
}
}
return -1;
}
@Override
public View getDropDownView(int position, View view, @NonNull ViewGroup parent) {
return createView(position, view, parent);
}
@Override
public View getView(int position, View view, @NonNull ViewGroup parent) {
return createView(position, view, parent);
}
private View createView(int position, View convertView, ViewGroup parent) {
Language item = getItem(position);
View view = inflater.inflate(layoutResourceId, parent, false);
TextView label = view.findViewById(R.id.item_display_name);
label.setText(item != null ? item.getStringResourceId() : 0);
return view;
}
}
@@ -0,0 +1,52 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import io.lbry.browser.R;
import io.lbry.browser.model.Language;
import io.lbry.browser.model.License;
import io.lbry.browser.utils.Predefined;
public class LicenseSpinnerAdapter extends ArrayAdapter<License> {
private int layoutResourceId;
private LayoutInflater inflater;
public LicenseSpinnerAdapter(Context context, int resource) {
super(context, resource, 0, Predefined.LICENSES);
inflater = LayoutInflater.from(context);
layoutResourceId = resource;
}
public int getItemPosition(String name) {
for (int i = 0; i < Predefined.LICENSES.size(); i++) {
License lic = Predefined.LICENSES.get(i);
if (lic.getName().equalsIgnoreCase(name)) {
return i;
}
}
return -1;
}
@Override
public View getDropDownView(int position, View view, @NonNull ViewGroup parent) {
return createView(position, view, parent);
}
@Override
public View getView(int position, View view, @NonNull ViewGroup parent) {
return createView(position, view, parent);
}
private View createView(int position, View convertView, ViewGroup parent) {
License item = getItem(position);
View view = inflater.inflate(layoutResourceId, parent, false);
TextView label = view.findViewById(R.id.item_display_name);
label.setText(item != null ? item.getStringResourceId() : 0);
return view;
}
}
@@ -159,7 +159,7 @@ public class RewardListAdapter extends RecyclerView.Adapter<RewardListAdapter.Vi
});
vh.textUsdValue.setText(reward.isCustom() || Lbryio.LBCUSDRate == 0 ? null :
String.format("≈$%s", Helper.USD_CURRENCY_FORMAT.format(rewardAmount * Lbryio.LBCUSDRate)));
String.format("≈$%s", Helper.SIMPLE_CURRENCY_FORMAT.format(rewardAmount * Lbryio.LBCUSDRate)));
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
@@ -168,6 +168,10 @@ public class RewardListAdapter extends RecyclerView.Adapter<RewardListAdapter.Vi
return;
}
if (vh.inputCustomCode != null && !vh.inputCustomCode.hasFocus()) {
vh.inputCustomCode.requestFocus();
}
if (clickListener != null) {
clickListener.onRewardClicked(reward, vh.loading);
}
@@ -197,7 +201,8 @@ public class RewardListAdapter extends RecyclerView.Adapter<RewardListAdapter.Vi
public void onClick(View view) {
String claimCode = Helper.getValue(vh.inputCustomCode.getText());
if (Helper.isNullOrEmpty(claimCode)) {
Snackbar.make(view, R.string.please_enter_claim_code, Snackbar.LENGTH_LONG).setBackgroundTint(Color.RED).show();
Snackbar.make(view, R.string.please_enter_claim_code, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
return;
}
@@ -56,6 +56,11 @@ public class SuggestedChannelGridAdapter extends RecyclerView.Adapter<SuggestedC
public int getSelectedCount() { return selectedItems.size(); }
public void clearItems() {
items.clear();
notifyDataSetChanged();
}
public List<Claim> getSelectedItems() {
return this.selectedItems;
}
@@ -72,7 +72,9 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionList
vh.claimView.setText(item.getClaim());
vh.feeView.setText(context.getString(R.string.tx_list_fee, TX_LIST_AMOUNT_FORMAT.format(item.getFee().doubleValue())));
vh.txidLinkView.setText(item.getTxid().substring(0, 7));
vh.dateView.setText(TX_LIST_DATE_FORMAT.format(item.getTxDate()));
vh.dateView.setVisibility(item.getConfirmations() > 0 ? View.VISIBLE : View.GONE);
vh.dateView.setText(item.getConfirmations() > 0 ? TX_LIST_DATE_FORMAT.format(item.getTxDate()) : null);
vh.pendingView.setVisibility(item.getConfirmations() == 0 ? View.VISIBLE : View.GONE);
vh.infoFeeContainer.setVisibility(!Helper.isNullOrEmpty(item.getClaim()) || Math.abs(item.getFee().doubleValue()) > 0 ?
View.VISIBLE : View.GONE);
@@ -111,6 +113,7 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionList
protected TextView feeView;
protected TextView txidLinkView;
protected TextView dateView;
protected TextView pendingView;
protected View infoFeeContainer;
public ViewHolder(View v) {
@@ -121,6 +124,7 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionList
feeView = v.findViewById(R.id.transaction_fee);
txidLinkView = v.findViewById(R.id.transaction_id_link);
dateView = v.findViewById(R.id.transaction_date);
pendingView = v.findViewById(R.id.transaction_pending_text);
infoFeeContainer = v.findViewById(R.id.transaction_info_fee_container);
}
}
@@ -16,6 +16,7 @@ import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.ui.controls.SolidIconView;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
@@ -96,7 +97,7 @@ public class UrlSuggestionListAdapter extends RecyclerView.Adapter<UrlSuggestion
iconStringId = R.string.fa_at;
fullTitle = item.getTitle();
desc = item.getClaim() != null ? item.getClaim().getTitle() :
(item.isUseTextAsDescription() ? item.getText() : String.format(context.getString(R.string.view_channel_url_desc), item.getText()));
((item.isUseTextAsDescription() && !Helper.isNullOrEmpty(item.getText())) ? item.getText() : String.format(context.getString(R.string.view_channel_url_desc), item.getText()));
break;
case UrlSuggestion.TYPE_TAG:
iconStringId = R.string.fa_hashtag;
@@ -113,7 +114,7 @@ public class UrlSuggestionListAdapter extends RecyclerView.Adapter<UrlSuggestion
iconStringId = R.string.fa_file;
fullTitle = item.getTitle();
desc = item.getClaim() != null ? item.getClaim().getTitle() :
(item.isUseTextAsDescription() ? item.getText() : String.format(context.getString(R.string.view_file_url_desc), item.getText()));
((item.isUseTextAsDescription() && !Helper.isNullOrEmpty(item.getText())) ? item.getText() : String.format(context.getString(R.string.view_file_url_desc), item.getText()));
break;
}
@@ -4,7 +4,10 @@ import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.opengl.Visibility;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
@@ -19,8 +22,9 @@ import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
public class DatabaseHelper extends SQLiteOpenHelper {
public static final int DATABASE_VERSION = 1;
public static final int DATABASE_VERSION = 2;
public static final String DATABASE_NAME = "LbryApp.db";
private static DatabaseHelper instance;
private static final String[] SQL_CREATE_TABLES = {
// local subscription store
@@ -36,6 +40,7 @@ public class DatabaseHelper extends SQLiteOpenHelper {
", claim_id TEXT" +
", claim_name TEXT" +
", cost REAL " +
", currency TEXT " +
", title TEXT " +
", publisher_claim_id TEXT" +
", publisher_name TEXT" +
@@ -54,17 +59,25 @@ public class DatabaseHelper extends SQLiteOpenHelper {
"CREATE INDEX idx_view_history_device ON view_history (device)"
};
private static final String[] SQL_V1_V2_UPGRADE = {
"ALTER TABLE view_history ADD COLUMN currency TEXT"
};
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_GET_SUBSCRIPTIONS = "SELECT channel_name, url FROM subscriptions";
private static final String SQL_INSERT_URL_HISTORY = "REPLACE INTO url_history (value, url, type, timestamp) VALUES (?, ?, ?)";
private static final String SQL_INSERT_URL_HISTORY = "REPLACE INTO url_history (value, url, type, timestamp) VALUES (?, ?, ?, ?)";
private static final String SQL_CLEAR_URL_HISTORY = "DELETE FROM url_history";
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_INSERT_VIEW_HISTORY =
"REPLACE INTO view_history (url, claim_id, claim_name, cost, 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 =
"SELECT url, claim_id, claim_name, cost, currency, title, publisher_claim_id, publisher_name, publisher_title, thumbnail_url, device, release_time, timestamp " +
"FROM view_history WHERE '' = ? OR timestamp < ? ORDER BY timestamp DESC LIMIT %d";
private static final String SQL_CLEAR_VIEW_HISTORY = "DELETE FROM view_history";
private static final String SQL_CLEAR_VIEW_HISTORY_BY_DEVICE = "DELETE FROM view_history WHERE device = ?";
private static final String SQL_CLEAR_VIEW_HISTORY_BEFORE_TIME = "DELETE FROM view_history WHERE timestamp < ?";
@@ -75,8 +88,14 @@ public class DatabaseHelper extends SQLiteOpenHelper {
private static final String SQL_UNFOLLOW_TAGS = "UPDATE tags SET is_followed = 0";
private static final String SQL_GET_FOLLOWED_TAGS = "SELECT name FROM tags WHERE is_followed = 1";
public DatabaseHelper(Context context) {
super(context, String.format("%s/%s", context.getFilesDir().getAbsolutePath(), DATABASE_NAME), null, DATABASE_VERSION);
instance = this;
}
public static DatabaseHelper getInstance() {
return instance;
}
public void onCreate(SQLiteDatabase db) {
for (String sql : SQL_CREATE_TABLES) {
@@ -87,7 +106,11 @@ public class DatabaseHelper extends SQLiteOpenHelper {
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion < 2) {
for (String sql : SQL_V1_V2_UPGRADE) {
db.execSQL(sql);
}
}
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
@@ -113,13 +136,9 @@ public class DatabaseHelper extends SQLiteOpenHelper {
while (cursor.moveToNext()) {
UrlSuggestion suggestion = new UrlSuggestion();
suggestion.setText(cursor.getString(0));
suggestion.setUri(cursor.isNull(1) ? null : LbryUri.tryParse(cursor.getString(1)));
suggestion.setType(cursor.getInt(2));
try {
suggestion.setUri(cursor.isNull(1) ? null : LbryUri.parse(cursor.getString(1)));
} catch (LbryUriException ex) {
// don't fail if the LbryUri is invalid
}
suggestion.setTitleUrlOnly(true);
suggestions.add(suggestion);
}
} finally {
@@ -135,6 +154,7 @@ public class DatabaseHelper extends SQLiteOpenHelper {
viewHistory.getClaimId(),
viewHistory.getClaimName(),
viewHistory.getCost() != null ? viewHistory.getCost().doubleValue() : 0,
viewHistory.getCurrency(),
viewHistory.getTitle(),
viewHistory.getPublisherClaimId(),
viewHistory.getPublisherName(),
@@ -146,6 +166,42 @@ public class DatabaseHelper extends SQLiteOpenHelper {
});
}
public static List<ViewHistory> getViewHistory(String lastTimestamp, int pageLimit, SQLiteDatabase db) {
List<ViewHistory> history = new ArrayList<>();
Cursor cursor = null;
try {
String arg = lastTimestamp == null ? "" : lastTimestamp;
cursor = db.rawQuery(String.format(SQL_GET_VIEW_HISTORY, pageLimit), new String[] { arg, arg });
while (cursor.moveToNext()) {
ViewHistory item = new ViewHistory();
int cursorIndex = 0;
item.setUri(LbryUri.tryParse(cursor.getString(cursorIndex++)));
item.setClaimId(cursor.getString(cursorIndex++));
item.setClaimName(cursor.getString(cursorIndex++));
item.setCost(new BigDecimal(cursor.getDouble(cursorIndex++)));
item.setCurrency(cursor.getString(cursorIndex++));
item.setTitle(cursor.getString(cursorIndex++));
item.setPublisherClaimId(cursor.getString(cursorIndex++));
item.setPublisherName(cursor.getString(cursorIndex++));
item.setPublisherTitle(cursor.getString(cursorIndex++));
item.setThumbnailUrl(cursor.getString(cursorIndex++));
item.setDevice(cursor.getString(cursorIndex++));
item.setReleaseTime(cursor.getLong(cursorIndex++));
try {
item.setTimestamp(new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).parse(cursor.getString(cursorIndex)));
} catch (ParseException ex) {
// invalid timestamp (which shouldn't happen). Skip this item
continue;
}
history.add(item);
}
} finally {
Helper.closeCursor(cursor);
}
return history;
}
public static void createOrUpdateTag(Tag tag, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_TAG, new Object[] { tag.getLowercaseName(), tag.isFollowed() ? 1 : 0 });
}
@@ -175,6 +231,9 @@ public class DatabaseHelper extends SQLiteOpenHelper {
public static void deleteSubscription(Subscription subscription, SQLiteDatabase db) {
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) {
List<Subscription> subscriptions = new ArrayList<>();
Cursor cursor = null;
@@ -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);
}
}
@@ -159,7 +159,13 @@ public class CustomizeTagsDialogFragment extends BottomSheetDialogFragment {
}
private void updateKnownTags(String filter, int limit, boolean clearPrevious) {
UpdateSuggestedTagsTask task = new UpdateSuggestedTagsTask(filter, SUGGESTED_LIMIT, followedTagsAdapter, suggestedTagsAdapter, clearPrevious, new UpdateSuggestedTagsTask.KnownTagsHandler() {
UpdateSuggestedTagsTask task = new UpdateSuggestedTagsTask(
filter,
SUGGESTED_LIMIT,
followedTagsAdapter,
suggestedTagsAdapter,
clearPrevious,
false, new UpdateSuggestedTagsTask.KnownTagsHandler() {
@Override
public void onSuccess(List<Tag> tags) {
if (suggestedTagsAdapter == null) {
@@ -84,10 +84,16 @@ public class DiscoverDialogFragment extends BottomSheetDialogFragment {
dialogActionsListener.onResume();
}
}
@Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
super.onDismiss(dialog);
if (dialogActionsListener != null) {
dialogActionsListener.onCancel();
}
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (dialogActionsListener != null) {
dialogActionsListener.onCancel();
}
@@ -24,7 +24,6 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.FileViewActivity;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
@@ -87,7 +86,7 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
textTitle.setText(getString(R.string.repost_title, claim.getTitle()));
inputName.setText(claim.getName());
inputDeposit.setText(R.string.min_repost_deposit);
inputDeposit.setText(R.string.min_deposit);
channelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
@@ -147,16 +146,16 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof FileViewActivity) {
((FileViewActivity) context).addWalletBalanceListener(this);
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
fetchChannels();
}
public void onPause() {
Context context = getContext();
if (context instanceof FileViewActivity) {
((FileViewActivity) context).removeWalletBalanceListener(this);
if (context instanceof MainActivity) {
((MainActivity) context).removeWalletBalanceListener(this);
}
inputDeposit.clearFocus();
super.onPause();
@@ -178,8 +177,8 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
public void onError(Exception error) {
// could not fetch channels
Context context = getContext();
if (context instanceof FileViewActivity) {
((FileViewActivity) context).showError(error.getMessage());
if (context instanceof MainActivity) {
((MainActivity) context).showError(error.getMessage());
}
dismiss();
}
@@ -193,14 +192,16 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
private void loadChannels(List<Claim> channels) {
if (channelSpinnerAdapter == null) {
Context context = getContext();
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, channels);
channelSpinnerAdapter.notifyDataSetChanged();
if (context != null) {
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, channels);
channelSpinnerAdapter.notifyDataSetChanged();
}
} else {
channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.notifyDataSetChanged();
}
if (channelSpinner != null) {
if (channelSpinner != null && channelSpinnerAdapter != null) {
channelSpinner.setAdapter(channelSpinnerAdapter);
}
}
@@ -230,8 +231,18 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
showError(getString(R.string.insufficient_balance));
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();
if (channel == null) {
showError(getString(R.string.please_select_repost_channel));
return;
}
StreamRepostTask task = new StreamRepostTask(name, bid, claim.getClaimId(), channel.getClaimId(), repostProgress, new ClaimResultHandler() {
@Override
public void beforeStart() {
@@ -257,10 +268,13 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
View view = getView();
if (view != null && !Helper.isNullOrEmpty(message)) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
}
private void startLoading() {
@@ -1,197 +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.FileViewActivity;
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());
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 FileViewActivity) {
((FileViewActivity) context).addWalletBalanceListener(this);
}
}
public void onPause() {
Context context = getContext();
if (context instanceof FileViewActivity) {
((FileViewActivity) 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,8 @@
package io.lbry.browser.listener;
public interface CameraPermissionListener {
void onCameraPermissionGranted();
void onCameraPermissionRefused();
void onRecordAudioPermissionGranted();
void onRecordAudioPermissionRefused();
}
@@ -0,0 +1,5 @@
package io.lbry.browser.listener;
public interface DownloadActionListener {
void onDownloadAction(String downloadAction, String uri, String outpoint, String fileInfoJson, double progress);
}
@@ -0,0 +1,9 @@
package io.lbry.browser.listener;
import java.util.List;
import io.lbry.browser.model.Claim;
public interface FetchClaimsListener {
void onClaimsFetched(List<Claim> claims);
}
@@ -0,0 +1,6 @@
package io.lbry.browser.listener;
public interface FilePickerListener {
void onFilePicked(String filePath);
void onFilePickerCancelled();
}
@@ -0,0 +1,6 @@
package io.lbry.browser.listener;
public interface PIPModeListener {
void onEnterPIPMode();
void onExitPIPMode();
}
@@ -0,0 +1,6 @@
package io.lbry.browser.listener;
public interface ScreenOrientationListener {
void onPortraitOrientationEntered();
void onLandscapeOrientationEntered();
}
@@ -0,0 +1,6 @@
package io.lbry.browser.listener;
public interface StoragePermissionListener {
void onStoragePermissionGranted();
void onStoragePermissionRefused();
}
@@ -9,6 +9,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
@@ -18,6 +19,7 @@ import java.util.stream.Stream;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Predefined;
import lombok.Data;
import lombok.EqualsAndHashCode;
@@ -81,6 +83,9 @@ public class Claim {
private GenericMetadata value;
private LbryFile file; // associated file if it exists
// device it was viewed on (for view history)
private String device;
public static Claim claimFromOutput(JSONObject item) {
// we only need name, permanent_url, txid and nout
Claim claim = new Claim();
@@ -92,6 +97,10 @@ public class Claim {
return claim;
}
public String getOutpoint() {
return String.format("%s:%d", txid, nout);
}
public boolean isFree() {
if (!(value instanceof StreamMetadata)) {
return true;
@@ -101,6 +110,24 @@ public class Claim {
return fee == null || Helper.parseDouble(fee.getAmount(), 0) == 0;
}
public BigDecimal getActualCost(double usdRate) {
if (!(value instanceof StreamMetadata)) {
return new BigDecimal(0);
}
Fee fee = ((StreamMetadata) value).getFee();
if (fee != null) {
double amount = Helper.parseDouble(fee.getAmount(), 0);
if ("usd".equalsIgnoreCase(fee.getCurrency())) {
return new BigDecimal(String.valueOf(amount / usdRate));
}
return new BigDecimal(String.valueOf(amount)); // deweys
}
return new BigDecimal(0);
}
public String getMediaType() {
if (value instanceof StreamMetadata) {
StreamMetadata metadata = (StreamMetadata) value;
@@ -130,6 +157,17 @@ public class Claim {
}
return false;
}
public boolean isMature() {
List<String> tags = getTags();
if (tags != null && tags.size() > 0) {
for (String tag : tags) {
if (Predefined.MATURE_TAGS.contains(tag.toLowerCase())) {
return true;
}
}
}
return false;
}
public String getThumbnailUrl() {
if (value != null && value.getThumbnail() != null) {
@@ -227,6 +265,8 @@ public class Claim {
claim.setName(viewHistory.getClaimName());
claim.setValueType(TYPE_STREAM);
claim.setPermanentUrl(viewHistory.getUri().toString());
claim.setDevice(viewHistory.getDevice());
claim.setConfirmations(1);
StreamMetadata value = new StreamMetadata();
value.setTitle(viewHistory.getTitle());
@@ -239,7 +279,8 @@ public class Claim {
if (viewHistory.getCost() != null && viewHistory.getCost().doubleValue() > 0) {
Fee fee = new Fee();
fee.setAmount(String.valueOf(viewHistory.getCost().doubleValue()));
fee.setCurrency("LBC"); // always LBC
fee.setCurrency(viewHistory.getCurrency());
value.setFee(fee);
}
claim.setValue(value);
@@ -248,6 +289,9 @@ public class Claim {
Claim signingChannel = new Claim();
signingChannel.setClaimId(viewHistory.getPublisherClaimId());
signingChannel.setName(viewHistory.getPublisherName());
LbryUri channelUrl = LbryUri.tryParse(String.format("%s#%s", signingChannel.getName(), signingChannel.getClaimId()));
signingChannel.setPermanentUrl(channelUrl != null ? channelUrl.toString() : null);
if (!Helper.isNullOrEmpty(viewHistory.getPublisherTitle())) {
GenericMetadata channelValue = new GenericMetadata();
channelValue.setTitle(viewHistory.getPublisherTitle());
@@ -334,7 +378,8 @@ public class Claim {
Fee fee = null;
if (feeAmount > 0) {
fee = new Fee();
fee.setAmount(String.valueOf(feeAmount));
fee.setAmount(String.valueOf(new BigDecimal(String.valueOf(feeAmount)).divide(new BigDecimal(100000000))));
fee.setCurrency("LBC");
}
((StreamMetadata) metadata).setFee(fee);
@@ -353,9 +398,10 @@ public class Claim {
Claim signingChannel = new Claim();
signingChannel.setClaimId(searchResultObject.getString("channel_claim_id"));
signingChannel.setName(searchResultObject.getString("channel"));
claimUri.setChannelClaimId(signingChannel.getClaimId());
claimUri.setChannelName(signingChannel.getName());
LbryUri channelUri = new LbryUri();
channelUri.setChannelClaimId(signingChannel.getClaimId());
channelUri.setChannelName(signingChannel.getName());
signingChannel.setPermanentUrl(channelUri.toString());
claim.setSigningChannel(signingChannel);
}
@@ -5,34 +5,36 @@ import androidx.annotation.Nullable;
import io.lbry.browser.utils.Helper;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
/**
* Class to represent a key to check equality with another object
*/
@ToString
public class ClaimCacheKey {
@Getter
@Setter
private String claimId;
@Getter
@Setter
private String canonicalUrl;
@Getter
@Setter
private String permanentUrl;
@Getter
@Setter
private String shortUrl;
@Getter
@Setter
private String vanityUrl;
private String url;
public static ClaimCacheKey fromClaimShortUrl(Claim claim) {
ClaimCacheKey key = new ClaimCacheKey();
key.setUrl(claim.getShortUrl());
return key;
}
public static ClaimCacheKey fromClaimPermanentUrl(Claim claim) {
ClaimCacheKey key = new ClaimCacheKey();
key.setUrl(claim.getPermanentUrl());
return key;
}
public static ClaimCacheKey fromClaim(Claim claim) {
ClaimCacheKey key = new ClaimCacheKey();
key.setClaimId(claim.getClaimId());
key.setCanonicalUrl(claim.getCanonicalUrl());
key.setPermanentUrl(claim.getPermanentUrl());
key.setShortUrl(claim.getShortUrl());
key.setUrl(!Helper.isNullOrEmpty(claim.getShortUrl()) ? claim.getShortUrl() : claim.getPermanentUrl());
return key;
}
@@ -41,44 +43,24 @@ public class ClaimCacheKey {
if (obj == null || !(obj instanceof ClaimCacheKey)) {
return false;
}
ClaimCacheKey key = (ClaimCacheKey) obj;
if (!Helper.isNullOrEmpty(claimId) && !Helper.isNullOrEmpty(key.getClaimId())) {
return claimId.equalsIgnoreCase(key.getClaimId());
}
if (!Helper.isNullOrEmpty(permanentUrl) && !Helper.isNullOrEmpty(key.getPermanentUrl())) {
return permanentUrl.equalsIgnoreCase(key.getPermanentUrl());
if (!Helper.isNullOrEmpty(url) && !Helper.isNullOrEmpty(key.getUrl())) {
return url.equalsIgnoreCase(key.getUrl());
}
if (!Helper.isNullOrEmpty(canonicalUrl) && !Helper.isNullOrEmpty(key.getCanonicalUrl())) {
return canonicalUrl.equalsIgnoreCase(key.getCanonicalUrl());
}
if (!Helper.isNullOrEmpty(shortUrl) && !Helper.isNullOrEmpty(key.getShortUrl())) {
return shortUrl.equalsIgnoreCase(key.getShortUrl());
}
if (!Helper.isNullOrEmpty(vanityUrl) && !Helper.isNullOrEmpty(key.getVanityUrl())) {
return vanityUrl.equalsIgnoreCase(key.getVanityUrl());
}
return false;
}
@Override
public int hashCode() {
if (!Helper.isNullOrEmpty(url)) {
return url.hashCode();
}
if (!Helper.isNullOrEmpty(claimId)) {
return claimId.hashCode();
}
if (!Helper.isNullOrEmpty(permanentUrl)) {
return permanentUrl.hashCode();
}
if (!Helper.isNullOrEmpty(canonicalUrl)) {
return canonicalUrl.hashCode();
}
if (!Helper.isNullOrEmpty(shortUrl)) {
return shortUrl.hashCode();
}
if (!Helper.isNullOrEmpty(vanityUrl)) {
return vanityUrl.hashCode();
}
return super.hashCode();
}
@@ -0,0 +1,69 @@
package io.lbry.browser.model;
import org.json.JSONException;
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;
@Data
public class Comment {
public static final double LBC_COST = 1;
public static final int MAX_LENGTH = 2000;
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.text = text;
this.id = id;
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) {
try {
String parentId = null;
if (jsonObject.has("parent_id")) {
parentId = jsonObject.getString("parent_id");
}
Comment comment = new Comment(
Helper.getJSONString("channel_id", null, jsonObject),
jsonObject.getString("channel_name"),
jsonObject.getString("comment"),
jsonObject.getString("comment_id"),
parentId
);
comment.setClaimId(Helper.getJSONString("claim_id", null, jsonObject));
comment.setTimestamp(Helper.getJSONLong("timestamp", 0, jsonObject));
return comment;
} catch (JSONException ex) {
return null;
}
}
}
@@ -0,0 +1,13 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class GalleryItem {
private String id;
private String name;
private String filePath;
private String type;
private String thumbnailPath;
private long duration;
}
@@ -0,0 +1,16 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class Language {
private String code;
private String name;
private int stringResourceId;
public Language(String code, String name, int stringResourceId) {
this.code = code;
this.name = name;
this.stringResourceId = stringResourceId;
}
}
@@ -9,9 +9,12 @@ import org.json.JSONObject;
import java.lang.reflect.Type;
import io.lbry.browser.utils.LbryUri;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class LbryFile {
private Claim.StreamMetadata metadata;
private long addedOn;
@@ -20,6 +23,7 @@ public class LbryFile {
private int blobsRemaining;
private String channelClaimId;
private String channelName;
@EqualsAndHashCode.Include
private String claimId;
private String claimName;
private boolean completed;
@@ -39,16 +43,50 @@ public class LbryFile {
private String streamName;
private String streamingUrl;
private String suggestedFileName;
private long timestamp;
private long totalBytes;
private long totalBytesLowerBound;
private String txid;
private long writtenBytes;
private Claim generatedClaim;
public Claim getClaim() {
if (generatedClaim != null) {
return generatedClaim;
}
generatedClaim = new Claim();
generatedClaim.setValueType(Claim.TYPE_STREAM);
generatedClaim.setPermanentUrl(LbryUri.tryParse(String.format("%s#%s", claimName, claimId)).toString());
generatedClaim.setClaimId(claimId);
generatedClaim.setName(claimName);
generatedClaim.setValue(metadata);
generatedClaim.setConfirmations(1);
generatedClaim.setTxid(txid);
generatedClaim.setNout(nout);
generatedClaim.setFile(this);
if (channelClaimId != null) {
Claim signingChannel = new Claim();
signingChannel.setClaimId(channelClaimId);
signingChannel.setName(channelName);
signingChannel.setPermanentUrl(LbryUri.tryParse(String.format("%s#%s", claimName, claimId)).toString());
generatedClaim.setSigningChannel(signingChannel);
}
return generatedClaim;
}
public static LbryFile fromJSONObject(JSONObject fileObject) {
String fileJson = fileObject.toString();
Type type = new TypeToken<LbryFile>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
LbryFile file = gson.fromJson(fileJson, type);
if (file.getMetadata() != null && file.getMetadata().getReleaseTime() == 0) {
file.getMetadata().setReleaseTime(file.getTimestamp());
}
return file;
}
}
@@ -0,0 +1,20 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class License {
private String name;
private String url;
private int stringResourceId;
public License(String name, int stringResourceId) {
this.name = name;
this.stringResourceId = stringResourceId;
}
public License(String name, String url, int stringResourceId) {
this.name = name;
this.url = url;
this.stringResourceId = stringResourceId;
}
}
@@ -5,7 +5,9 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.exceptions.LbryUriException;
@@ -53,13 +55,22 @@ public class Transaction {
int descStringId = -1;
TransactionInfo info = null;
List<TransactionInfo> infos = new ArrayList<>();
try {
if (jsonObject.has("abandon_info")) {
JSONArray array = jsonObject.getJSONArray("abandon_info");
if (array.length() > 0) {
info = TransactionInfo.fromJSONObject(array.getJSONObject(0));
descStringId = R.string.abandon;
transaction.setAbandonInfo(info);
if (array.length() == 1) {
info = TransactionInfo.fromJSONObject(array.getJSONObject(0));
descStringId = info.getBalanceDelta().doubleValue() == info.getAmount().doubleValue() ? R.string.unlock : R.string.abandon;
transaction.setAbandonInfo(info);
} else {
// multiple abandon infos (txo_spend unlock tip)
descStringId = R.string.unlock;
for (int i = 0; i < array.length(); i++) {
infos.add(TransactionInfo.fromJSONObject(array.getJSONObject(i)));
}
}
}
}
if (info == null && jsonObject.has("claim_info")) {
@@ -94,8 +105,18 @@ public class Transaction {
// pass
}
if (transaction.getValue().doubleValue() == 0 && info != null && info.getBalanceDelta().doubleValue() != 0) {
transaction.setValue(info.getBalanceDelta());
if (transaction.getValue().doubleValue() == 0) {
if (info != null && info.getBalanceDelta().doubleValue() != 0) {
transaction.setValue(info.getBalanceDelta());
} else if (infos.size() > 0) {
BigDecimal total = new BigDecimal(0);
for (TransactionInfo txInfo : infos) {
total = total.add(txInfo.getAmount());
}
transaction.setValue(total);
}
}
if (descStringId == -1) {
@@ -15,6 +15,7 @@ public class UrlSuggestion {
private LbryUri uri;
private Claim claim; // associated claim if resolved
private boolean titleTextOnly;
private boolean titleUrlOnly;
private boolean useTextAsDescription;
public UrlSuggestion() {
@@ -34,6 +35,10 @@ public class UrlSuggestion {
}
public String getTitle() {
if (titleUrlOnly && (type == TYPE_CHANNEL || type == TYPE_FILE)) {
return uri.toString();
}
if (!titleTextOnly) {
switch (type) {
case TYPE_CHANNEL:
@@ -5,6 +5,7 @@ import java.util.Date;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Lbryio;
import lombok.Data;
@Data
@@ -13,6 +14,7 @@ public class ViewHistory {
private String claimId;
private String claimName;
private BigDecimal cost;
private String currency;
private String title;
private String publisherClaimId;
private String publisherName;
@@ -39,9 +41,14 @@ public class ViewHistory {
Claim.StreamMetadata value = (Claim.StreamMetadata) metadata;
history.setReleaseTime(value.getReleaseTime());
if (value.getFee() != null) {
history.setCost(new BigDecimal(value.getFee().getAmount()));
Fee fee = value.getFee();
history.setCost(new BigDecimal(fee.getAmount()));
history.setCurrency(fee.getCurrency());
}
}
if (history.getReleaseTime() == 0) {
history.setReleaseTime(claim.getTimestamp());
}
Claim signingChannel = claim.getSigningChannel();
if (signingChannel != null) {
@@ -1,7 +1,10 @@
package io.lbry.browser.model;
import org.json.JSONObject;
import java.math.BigDecimal;
import io.lbry.browser.utils.Helper;
import lombok.Data;
@Data
@@ -21,4 +24,18 @@ public class WalletBalance {
tips = new BigDecimal(0);
total = new BigDecimal(0);
}
public static WalletBalance fromJSONObject(JSONObject json) {
WalletBalance balance = new WalletBalance();
JSONObject reservedSubtotals = Helper.getJSONObject("reserved_subtotals", json);
balance.setAvailable(new BigDecimal(Helper.getJSONString("available", "0", json)));
balance.setReserved(new BigDecimal(Helper.getJSONString("reserved", "0", json)));
balance.setTotal(new BigDecimal(Helper.getJSONString("total", "0", json)));
if (reservedSubtotals != null) {
balance.setClaims(new BigDecimal(Helper.getJSONString("claims", "0", reservedSubtotals)));
balance.setSupports(new BigDecimal(Helper.getJSONString("supports", "0", reservedSubtotals)));
balance.setTips(new BigDecimal(Helper.getJSONString("tips", "0", reservedSubtotals)));
}
return balance;
}
}
@@ -8,9 +8,13 @@ public class WalletSync {
private String data;
private boolean changed;
public WalletSync(String hash, String data, boolean changed) {
public WalletSync(String hash, String data) {
this.hash = hash;
this.data = data;
}
public WalletSync(String hash, String data, boolean changed) {
this(hash, data);
this.changed = changed;
}
}
@@ -24,6 +24,19 @@ public class User {
private String primaryEmail;
private String rewardStatusChangeTrigger;
private String updatedAt;
private List<String> youtubeChannels;
private List<YoutubeChannel> youtubeChannels;
private List<String> deviceTypes;
@Data
public static class YoutubeChannel {
String ytChannelName;
String lbryChannelName;
String channelClaimId;
String syncStatus;
String statusToken;
boolean transferable;
String transferState;
List<String> publishToAddress;
String publicKey;
}
}
@@ -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);
}
}
@@ -0,0 +1,10 @@
package io.lbry.browser.tasks;
import java.util.List;
import io.lbry.browser.model.Comment;
public interface CommentListHandler {
void onSuccess(List<Comment> comments, boolean hasReachedEnd);
void onError(Exception error);
}
@@ -0,0 +1,93 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.model.Comment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class CommentListTask extends AsyncTask<Void, Void, List<Comment>> {
private final int page;
private final int pageSize;
private final String claim;
private ProgressBar progressBar;
private CommentListHandler handler;
private Exception error;
public CommentListTask(int page, int pageSize, String claim, ProgressBar progressBar, CommentListHandler handler) {
this.page = page;
this.pageSize = pageSize;
this.claim = claim;
this.progressBar = progressBar;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressBar, View.VISIBLE);
}
protected List<Comment> doInBackground(Void... voids) {
List<Comment> comments = null;
try {
Map<String, Object> options = new HashMap<>();
options.put("claim_id", claim);
options.put("page", page);
options.put("page_size", pageSize);
options.put("include_replies", false);
options.put("is_channel_signature_valid", true);
options.put("visible", true);
options.put("hidden", false);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_COMMENT_LIST, options);
JSONArray items = result.getJSONArray("items");
List<Comment> children = new ArrayList<>();
comments = new ArrayList<>();
for (int i = 0; i < items.length(); 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) {
error = ex;
}
return comments;
}
protected void onPostExecute(List<Comment> comments) {
Helper.setViewVisibility(progressBar, View.GONE);
if (handler != null) {
if (comments != null) {
handler.onSuccess(comments, comments.size() < pageSize);
} else {
handler.onError(error);
}
}
}
}
@@ -9,7 +9,7 @@ import java.util.List;
import io.lbry.browser.exceptions.LbryRequestException;
import io.lbry.browser.exceptions.LbryResponseException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.tasks.claim.ClaimSearchTask;
import io.lbry.browser.tasks.claim.ClaimSearchResultHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lighthouse;
@@ -19,11 +19,11 @@ public class LighthouseSearchTask extends AsyncTask<Void, Void, List<Claim>> {
private int from;
private boolean nsfw;
private String relatedTo;
private ClaimSearchTask.ClaimSearchResultHandler handler;
private ClaimSearchResultHandler handler;
private ProgressBar progressBar;
private Exception error;
public LighthouseSearchTask(String rawQuery, int size, int from, boolean nsfw, String relatedTo, ProgressBar progressBar, ClaimSearchTask.ClaimSearchResultHandler handler) {
public LighthouseSearchTask(String rawQuery, int size, int from, boolean nsfw, String relatedTo, ProgressBar progressBar, ClaimSearchResultHandler handler) {
this.rawQuery = rawQuery;
this.size = size;
this.from = from;
@@ -24,6 +24,7 @@ import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Lbryio;
import okhttp3.Response;
// background task to create a diff of local and remote subscriptions and try to merge
public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscription>> {
@@ -33,9 +34,11 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
private List<Subscription> diff;
private MergeSubscriptionsHandler handler;
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.replaceLocal = replaceLocal;
this.context = context;
this.handler = handler;
}
@@ -52,10 +55,17 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
db = ((MainActivity) context).getDbHelper().getWritableDatabase();
}
if (db != null) {
localSubs = DatabaseHelper.getSubscriptions(db);
for (Subscription sub : localSubs) {
if (!combined.contains(sub)) {
combined.add(sub);
if (replaceLocal) {
DatabaseHelper.clearSubscriptions(db);
for (Subscription sub : base) {
DatabaseHelper.createOrUpdateSubscription(sub, db);
}
} else {
localSubs = DatabaseHelper.getSubscriptions(db);
for (Subscription sub : localSubs) {
if (!combined.contains(sub)) {
combined.add(sub);
}
}
}
}
@@ -83,9 +93,13 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
try {
LbryUri uri = LbryUri.parse(local.getUrl());
Map<String, String> options = new HashMap<>();
options.put("claim_id", uri.getChannelClaimId());
options.put("channel_name", local.getChannelName());
Lbryio.call("subscription", "new", options, context);
String channelClaimId = uri.getChannelClaimId();
String channelName = Helper.normalizeChannelName(local.getChannelName());
if (!Helper.isNullOrEmpty(channelClaimId) && !Helper.isNullOrEmpty(channelName)) {
options.put("claim_id", channelClaimId);
options.put("channel_name", channelName);
Lbryio.parseResponse(Lbryio.call("subscription", "new", options, context));
}
} catch (LbryUriException | LbryioRequestException | LbryioResponseException ex) {
// pass
Log.e(TAG, String.format("subscription/new failed: %s", ex.getMessage()), ex);
@@ -93,10 +107,12 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
}
}
for (int i = 0; i < localSubs.size(); i++) {
Subscription local = localSubs.get(i);
if (!base.contains(local) && !diff.contains(local)) {
diff.add(local);
if (!replaceLocal) {
for (int i = 0; i < localSubs.size(); i++) {
Subscription local = localSubs.get(i);
if (!base.contains(local) && !diff.contains(local)) {
diff.add(local);
}
}
}
for (int i = 0; i < remoteSubs.size(); i++) {
@@ -108,11 +124,9 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
}
}
}
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | SQLiteException ex) {
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | IllegalStateException | SQLiteException ex) {
error = ex;
return null;
} finally {
Helper.closeDatabase(db);
}
return combined;
@@ -0,0 +1,45 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import java.util.HashMap;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.utils.Lbry;
public class SetSdkSettingTask extends AsyncTask<Void, Void, Boolean> {
private String key;
private String value;
private GenericTaskHandler handler;
private Exception error;
public SetSdkSettingTask(String key, String value, GenericTaskHandler handler) {
this.key = key;
this.value = value;
this.handler = handler;
}
@Override
protected Boolean doInBackground(Void... params) {
try {
Map<String, Object> options = new HashMap<>();
options.put("key", key);
options.put("value", value);
Lbry.genericApiCall("setting_set", options);
return true;
} catch (ApiCallException ex) {
error = ex;
return false;
}
}
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
handler.onSuccess();
} else {
handler.onError(error);
}
}
}
}
@@ -14,18 +14,27 @@ import io.lbry.browser.utils.Lbry;
public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
private boolean clearPrevious;
private boolean excludeMature;
private int limit;
private String filter;
private TagListAdapter addedTagsAdapter;
private TagListAdapter suggestedTagsAdapter;
private KnownTagsHandler handler;
public UpdateSuggestedTagsTask(String filter, int limit, TagListAdapter addedTagsAdapter, TagListAdapter suggestedTagsAdapter, boolean clearPrevious, KnownTagsHandler handler) {
public UpdateSuggestedTagsTask(
String filter,
int limit,
TagListAdapter addedTagsAdapter,
TagListAdapter suggestedTagsAdapter,
boolean clearPrevious,
boolean excludeMature,
KnownTagsHandler handler) {
this.filter = filter;
this.limit = limit;
this.addedTagsAdapter = addedTagsAdapter;
this.suggestedTagsAdapter = suggestedTagsAdapter;
this.clearPrevious = clearPrevious;
this.excludeMature = excludeMature;
this.handler = handler;
}
@@ -36,10 +45,15 @@ public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
if (suggestedTagsAdapter != null && !clearPrevious) {
tags = new ArrayList<>(suggestedTagsAdapter.getTags());
}
while (tags.size() < limit) {
Tag randomTag = Lbry.knownTags.get(random.nextInt(Lbry.knownTags.size()));
if (!Lbry.followedTags.contains(randomTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(randomTag))) {
tags.add(randomTag);
if (Lbry.knownTags.size() > 0) {
while (tags.size() < limit) {
Tag randomTag = Lbry.knownTags.get(random.nextInt(Lbry.knownTags.size()));
if (excludeMature && randomTag.isMature()) {
continue;
}
if (!Lbry.followedTags.contains(randomTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(randomTag))) {
tags.add(randomTag);
}
}
}
} else {
@@ -49,10 +63,18 @@ public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
}
for (int i = 0; i < Lbry.knownTags.size() && tags.size() < limit - 1; i++) {
Tag knownTag = Lbry.knownTags.get(i);
if ((knownTag.getLowercaseName().startsWith(filter) || knownTag.getLowercaseName().matches(filter)) &&
(!tags.contains(knownTag) &&
!Lbry.followedTags.contains(knownTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(knownTag)))) {
tags.add(knownTag);
if (excludeMature && knownTag.isMature()) {
continue;
}
try {
if ((knownTag.getLowercaseName().startsWith(filter) ||
knownTag.getLowercaseName().matches(filter)) &&
(!tags.contains(knownTag) && !Lbry.followedTags.contains(knownTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(knownTag)))
) {
tags.add(knownTag);
}
} catch (Exception ex) {
// continue
}
}
}
@@ -7,9 +7,9 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Random;
import java.io.File;
import java.util.concurrent.TimeUnit;
import io.lbry.browser.exceptions.LbryResponseException;
import io.lbry.browser.utils.Helper;
@@ -47,14 +47,17 @@ public class UploadImageTask extends AsyncTask<Void, Void, String> {
}
String fileType = String.format("image/%s", extension);
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).
addFormDataPart("name", makeid()).
addFormDataPart("name", Helper.makeid(24)).
addFormDataPart("file", fileName, RequestBody.create(file, MediaType.parse(fileType))).
build();
Request request = new Request.Builder().url("https://spee.ch/api/claim/publish").post(body).build();
OkHttpClient client = new OkHttpClient();
OkHttpClient client = new OkHttpClient.Builder().
writeTimeout(300, TimeUnit.SECONDS).
readTimeout(300, TimeUnit.SECONDS).
build();
Response response = client.newCall(request).execute();
JSONObject json = new JSONObject(response.body().string());
if (json.has("success")) {
if (json.has("success") && Helper.getJSONBoolean("success", false, json)) {
JSONObject data = json.getJSONObject("data");
String url = Helper.getJSONString("url", null, data);
if (Helper.isNullOrEmpty(url)) {
@@ -62,9 +65,15 @@ public class UploadImageTask extends AsyncTask<Void, Void, String> {
}
thumbnailUrl = String.format("%s.%s", url, extension);
} else if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
String message = Helper.getJSONString("message", null, error);
} else if (json.has("error") || json.has("message")) {
JSONObject error = Helper.getJSONObject("error", json);
String message = null;
if (error != null) {
message = Helper.getJSONString("message", null, error);
}
if (Helper.isNullOrEmpty(message)) {
message = Helper.getJSONString("message", null, json);
}
throw new LbryResponseException(Helper.isNullOrEmpty(message) ? "The image failed to upload." : message);
}
} catch (IOException | JSONException | LbryResponseException ex) {
@@ -84,16 +93,6 @@ public class UploadImageTask extends AsyncTask<Void, Void, String> {
}
}
private static String makeid() {
Random random = new Random();
String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
StringBuilder id = new StringBuilder();
for (int i = 0; i < 24; i++) {
id.append(chars.charAt(random.nextInt(chars.length())));
}
return id.toString();
}
public interface UploadThumbnailHandler {
void onSuccess(String url);
void onError(Exception error);
@@ -0,0 +1,63 @@
package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class AbandonChannelTask extends AsyncTask<Void, Void, Boolean> {
private List<String> claimIds;
private List<String> successfulClaimIds;
private List<String> failedClaimIds;
private List<Exception> failedExceptions;
private View progressView;
private AbandonHandler handler;
public AbandonChannelTask(List<String> claimIds, View progressView, AbandonHandler handler) {
this.claimIds = claimIds;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
public Boolean doInBackground(Void... params) {
successfulClaimIds = new ArrayList<>();
failedClaimIds = new ArrayList<>();
failedExceptions = new ArrayList<>();
for (String claimId : claimIds) {
try {
Map<String, Object> options = new HashMap<>();
options.put("claim_id", claimId);
options.put("blocking", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_CHANNEL_ABANDON, options);
successfulClaimIds.add(claimId);
} catch (ApiCallException ex) {
failedClaimIds.add(claimId);
failedExceptions.add(ex);
}
}
return true;
}
protected void onPostExecute(Boolean result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
handler.onComplete(successfulClaimIds, failedClaimIds, failedExceptions);
}
}
}
@@ -0,0 +1,7 @@
package io.lbry.browser.tasks.claim;
import java.util.List;
public interface AbandonHandler {
void onComplete(List<String> successfulClaimIds, List<String> failedClaimIds, List<Exception> errors);
}
@@ -0,0 +1,63 @@
package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class AbandonStreamTask extends AsyncTask<Void, Void, Boolean> {
private List<String> claimIds;
private List<String> successfulClaimIds;
private List<String> failedClaimIds;
private List<Exception> failedExceptions;
private View progressView;
private AbandonHandler handler;
public AbandonStreamTask(List<String> claimIds, View progressView, AbandonHandler handler) {
this.claimIds = claimIds;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
public Boolean doInBackground(Void... params) {
successfulClaimIds = new ArrayList<>();
failedClaimIds = new ArrayList<>();
failedExceptions = new ArrayList<>();
for (String claimId : claimIds) {
try {
Map<String, Object> options = new HashMap<>();
options.put("claim_id", claimId);
options.put("blocking", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_STREAM_ABANDON, options);
successfulClaimIds.add(claimId);
} catch (ApiCallException ex) {
failedClaimIds.add(claimId);
failedExceptions.add(ex);
}
}
return true;
}
protected void onPostExecute(Boolean result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
handler.onComplete(successfulClaimIds, failedClaimIds, failedExceptions);
}
}
}
@@ -1,4 +1,4 @@
package io.lbry.browser.tasks;
package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
@@ -9,7 +9,9 @@ import org.json.JSONObject;
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 io.lbry.browser.exceptions.ApiCallException;
@@ -47,14 +49,28 @@ public class ChannelCreateUpdateTask extends AsyncTask<Void, Void, Claim> {
} else {
options.put("claim_id", claim.getClaimId());
}
options.put("bid", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT).format(deposit.doubleValue()));
options.put("title", claim.getTitle());
options.put("cover_url", claim.getCoverUrl());
options.put("thumbnail_url", claim.getThumbnailUrl());
options.put("description", claim.getDescription());
options.put("website_url", claim.getWebsiteUrl());
options.put("email", claim.getEmail());
options.put("tags", claim.getTags());
options.put("bid", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(deposit.doubleValue()));
if (!Helper.isNullOrEmpty(claim.getTitle())) {
options.put("title", claim.getTitle());
}
if (!Helper.isNullOrEmpty(claim.getCoverUrl())) {
options.put("cover_url", claim.getCoverUrl());
}
if (!Helper.isNullOrEmpty(claim.getThumbnailUrl())) {
options.put("thumbnail_url", claim.getThumbnailUrl());
}
if (!Helper.isNullOrEmpty(claim.getDescription())) {
options.put("description", claim.getDescription());
}
if (!Helper.isNullOrEmpty(claim.getWebsiteUrl())) {
options.put("website_url", claim.getWebsiteUrl());
}
if (!Helper.isNullOrEmpty(claim.getEmail())) {
options.put("email", claim.getEmail());
}
if (claim.getTags() != null && claim.getTags().size() > 0) {
options.put("tags", claim.getTags());
}
options.put("blocking", true);
Claim claimResult = null;
@@ -8,6 +8,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -18,13 +19,16 @@ import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class ClaimListTask extends AsyncTask<Void, Void, List<Claim>> {
private String type;
private List<String> types;
private View progressView;
private ClaimListResultHandler handler;
private Exception error;
public ClaimListTask(String type, View progressView, ClaimListResultHandler handler) {
this.type = type;
this(Arrays.asList(type), progressView, handler);
}
public ClaimListTask(List<String> types, View progressView, ClaimListResultHandler handler) {
this.types = types;
this.progressView = progressView;
this.handler = handler;
}
@@ -36,8 +40,8 @@ public class ClaimListTask extends AsyncTask<Void, Void, List<Claim>> {
try {
Map<String, Object> options = new HashMap<>();
if (!Helper.isNullOrEmpty(type)) {
options.put("claim_type", type);
if (types != null && types.size() > 0) {
options.put("claim_type", types);
}
options.put("page", 1);
options.put("page_size", 999);
@@ -58,7 +62,8 @@ public class ClaimListTask extends AsyncTask<Void, Void, List<Claim>> {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (claims != null) {
handler.onSuccess(claims);
// TODO: Add fix for handling invalid reposts in ClaimListAdapter
handler.onSuccess(Helper.filterInvalidReposts(claims));
} else {
handler.onError(error);
}
@@ -0,0 +1,10 @@
package io.lbry.browser.tasks.claim;
import java.util.List;
import io.lbry.browser.model.Claim;
public interface ClaimSearchResultHandler {
void onSuccess(List<Claim> claims, boolean hasReachedEnd);
void onError(Exception error);
}
@@ -2,7 +2,6 @@ package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import java.util.List;
import java.util.Map;
@@ -40,15 +39,11 @@ public class ClaimSearchTask extends AsyncTask<Void, Void, List<Claim>> {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (claims != null) {
handler.onSuccess(claims, claims.size() < Helper.parseInt(options.get("page_size"), 0));
handler.onSuccess(Helper.filterInvalidReposts(claims), claims.size() < Helper.parseInt(options.get("page_size"), 0));
} else {
handler.onError(error);
}
}
}
public interface ClaimSearchResultHandler {
void onSuccess(List<Claim> claims, boolean hasReachedEnd);
void onError(Exception error);
}
}
@@ -0,0 +1,114 @@
package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class PublishClaimTask extends AsyncTask<Void, Void, Claim> {
private Claim claim;
private String filePath;
private View progressView;
private ClaimResultHandler handler;
private Exception error;
public PublishClaimTask(Claim claim, String filePath, View progressView, ClaimResultHandler handler) {
this.claim = claim;
this.filePath = filePath;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
if (handler != null) {
handler.beforeStart();
}
}
protected Claim doInBackground(Void... params) {
Claim.StreamMetadata metadata = (Claim.StreamMetadata) claim.getValue();
DecimalFormat amountFormat = new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US));
Map<String, Object> options = new HashMap<>();
options.put("blocking", true);
options.put("name", claim.getName());
options.put("bid", amountFormat.format(new BigDecimal(claim.getAmount()).doubleValue()));
options.put("title", Helper.isNullOrEmpty(claim.getTitle()) ? "" : claim.getTitle());
options.put("description", Helper.isNullOrEmpty(claim.getDescription()) ? "" : claim.getDescription());
options.put("thumbnail_url", Helper.isNullOrEmpty(claim.getThumbnailUrl()) ? "" : claim.getThumbnailUrl());
if (!Helper.isNullOrEmpty(filePath)) {
options.put("file_path", filePath);
}
if (claim.getTags() != null && claim.getTags().size() > 0) {
options.put("tags", new ArrayList<>(claim.getTags()));
}
if (metadata.getFee() != null) {
options.put("fee_currency", metadata.getFee().getCurrency());
options.put("fee_amount", amountFormat.format(new BigDecimal(metadata.getFee().getAmount()).doubleValue()));
}
if (claim.getSigningChannel() != null) {
options.put("channel_id", claim.getSigningChannel().getClaimId());
}
if (metadata.getLanguages() != null && metadata.getLanguages().size() > 0) {
options.put("languages", metadata.getLanguages());
}
if (!Helper.isNullOrEmpty(metadata.getLicense())) {
options.put("license", metadata.getLicense());
}
if (!Helper.isNullOrEmpty(metadata.getLicenseUrl())) {
options.put("license_url", metadata.getLicenseUrl());
}
if (metadata.getReleaseTime() > 0) {
options.put("release_time", metadata.getReleaseTime());
} else if (claim.getTimestamp() > 0) {
options.put("release_time", claim.getTimestamp());
} else {
options.put("release_time", Double.valueOf(Math.floor(System.currentTimeMillis() / 1000.0)).intValue());
}
Claim claimResult = null;
try {
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PUBLISH, options);
if (result.has("outputs")) {
JSONArray outputs = result.getJSONArray("outputs");
for (int i = 0; i < outputs.length(); i++) {
JSONObject output = outputs.getJSONObject(i);
if (output.has("claim_id") && output.has("claim_op")) {
claimResult = Claim.claimFromOutput(output);
break;
}
}
}
} catch (ApiCallException | ClassCastException | JSONException ex) {
error = ex;
}
return claimResult;
}
protected void onPostExecute(Claim result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (result != null) {
handler.onSuccess(result);
} else {
handler.onError(error);
}
}
}
}
@@ -0,0 +1,85 @@
package io.lbry.browser.tasks.claim;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class PurchaseListTask extends AsyncTask<Void, Void, List<Claim>> {
private String claimId;
private int page;
private int pageSize;
private ClaimSearchResultHandler handler;
private View progressView;
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) {
this.page = page;
this.pageSize = pageSize;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected List<Claim> doInBackground(Void... params) {
List<Claim> claims = null;
try {
Map<String, Object> options = new HashMap<>();
if (!Helper.isNullOrEmpty(claimId)) {
options.put("claim_id", claimId);
}
if (page > 0) {
options.put("page", page);
}
if (pageSize > 0) {
options.put("page_size", pageSize);
}
options.put("resolve", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PURCHASE_LIST, options);
JSONArray items = result.getJSONArray("items");
claims = new ArrayList<>();
for (int i = 0; i < items.length(); i++) {
Claim claim = Claim.fromJSONObject(items.getJSONObject(i).getJSONObject("claim"));
if (!Helper.isNullOrEmpty(claim.getClaimId())) {
claims.add(claim);
Lbry.addClaimToCache(claim);
}
}
} catch (ApiCallException | JSONException | ClassCastException ex) {
error = ex;
}
return claims;
}
protected void onPostExecute(List<Claim> claims) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (claims != null) {
handler.onSuccess(claims, claims.size() < pageSize);
} else {
handler.onError(error);
}
}
}
}
@@ -34,7 +34,7 @@ public class ResolveTask extends AsyncTask<Void, Void, List<Claim>> {
}
protected List<Claim> doInBackground(Void... params) {
try {
return Lbry.resolve(urls, connectionString);
return Helper.filterInvalidReposts(Lbry.resolve(urls, connectionString));
} catch (ApiCallException ex) {
error = ex;
return null;
@@ -9,7 +9,9 @@ import org.json.JSONObject;
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 io.lbry.browser.exceptions.ApiCallException;
@@ -40,7 +42,7 @@ public class StreamRepostTask extends AsyncTask<Void, Void, Claim> {
try {
Map<String, Object> options = new HashMap<>();
options.put("name", name);
options.put("bid", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT).format(bid.doubleValue()));
options.put("bid", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(bid.doubleValue()));
options.put("claim_id", claimId);
options.put("channel_id", channelId);
@@ -0,0 +1,32 @@
package io.lbry.browser.tasks.file;
import android.os.AsyncTask;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.utils.Lbry;
// Just run delete on the specified claim IDs (no need for a handler)
public class BulkDeleteFilesTask extends AsyncTask<Void, Void, Boolean> {
private List<String> claimIds;
public BulkDeleteFilesTask(List<String> claimIds) {
this.claimIds = claimIds;
}
protected Boolean doInBackground(Void... params) {
for (String claimId : claimIds) {
try {
Map<String, Object> options = new HashMap<>();
options.put("claim_id", claimId);
options.put("delete_from_download_dir", true);
Lbry.genericApiCall(Lbry.METHOD_FILE_DELETE, options);
} catch (ApiCallException ex) {
// pass
}
}
return true;
}
}
@@ -26,6 +26,7 @@ public class DeleteFileTask extends AsyncTask<Void, Void, Boolean> {
options.put("delete_from_download_dir", true);
return (boolean) Lbry.genericApiCall(Lbry.METHOD_FILE_DELETE, options);
} catch (ApiCallException ex) {
error = ex;
return false;
}
}
@@ -12,12 +12,18 @@ import io.lbry.browser.utils.Lbry;
public class FileListTask extends AsyncTask<Void, Void, List<LbryFile>> {
private String claimId;
private boolean downloads;
private int page;
private int pageSize;
private FileListResultHandler handler;
private View progressView;
private ApiCallException error;
public FileListTask(View progressView, FileListResultHandler handler) {
public FileListTask(int page, int pageSize, boolean downloads, View progressView, FileListResultHandler handler) {
this(null, progressView, handler);
this.page = page;
this.pageSize = pageSize;
this.downloads = downloads;
}
public FileListTask(String claimId, View progressView, FileListResultHandler handler) {
@@ -30,7 +36,7 @@ public class FileListTask extends AsyncTask<Void, Void, List<LbryFile>> {
}
protected List<LbryFile> doInBackground(Void... params) {
try {
return Lbry.fileList(claimId);
return Lbry.fileList(claimId, downloads, page, pageSize);
} catch (ApiCallException ex) {
error = ex;
return null;
@@ -40,7 +46,7 @@ public class FileListTask extends AsyncTask<Void, Void, List<LbryFile>> {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (files != null) {
handler.onSuccess(files);
handler.onSuccess(files, files.size() < pageSize);
} else {
handler.onError(error);
}
@@ -48,7 +54,7 @@ public class FileListTask extends AsyncTask<Void, Void, List<LbryFile>> {
}
public interface FileListResultHandler {
void onSuccess(List<LbryFile> files);
void onSuccess(List<LbryFile> files, boolean hasReachedEnd);
void onError(Exception error);
}
}
@@ -64,8 +64,6 @@ public class ChannelSubscribeTask extends AsyncTask<Void, Void, Boolean> {
} catch (LbryioRequestException | LbryioResponseException | SQLiteException ex) {
error = ex;
return false;
} finally {
Helper.closeDatabase(db);
}
return true;
@@ -4,9 +4,12 @@ import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
@@ -14,6 +17,8 @@ import io.lbry.browser.R;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.lbryinc.Reward;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.Lbryio;
@@ -22,15 +27,15 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
private Context context;
private String type;
private String claimCode;
private String rewardCode;
private View progressView;
private double amountClaimed;
private ClaimRewardHandler handler;
private Exception error;
public ClaimRewardTask(String type, String claimCode, View progressView, Context context, ClaimRewardHandler handler) {
public ClaimRewardTask(String type, String rewardCode, View progressView, Context context, ClaimRewardHandler handler) {
this.type = type;
this.claimCode = claimCode;
this.rewardCode = rewardCode;
this.progressView = progressView;
this.context = context;
this.handler = handler;
@@ -43,15 +48,27 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
public String doInBackground(Void... params) {
String message = null;
try {
String txid = null;
if (Reward.TYPE_FIRST_CHANNEL.equalsIgnoreCase(type)) {
// fetch a channel
txid = fetchSingleClaimTxid(Claim.TYPE_CHANNEL);
} else if (Reward.TYPE_FIRST_PUBLISH.equalsIgnoreCase(type)) {
// fetch a publish
txid = fetchSingleClaimTxid(Claim.TYPE_STREAM);
}
// Get a new wallet address for the reward
String address = (String) Lbry.genericApiCall(Lbry.METHOD_ADDRESS_UNUSED);
Map<String, String> options = new HashMap<>();
options.put("reward_type", type);
options.put("wallet_address", address);
if (!Helper.isNullOrEmpty(claimCode)) {
options.put("claim_code", claimCode);
if (!Helper.isNullOrEmpty(rewardCode)) {
options.put("code", rewardCode);
}
if (!Helper.isNullOrEmpty(txid)) {
options.put("transaction_id", txid);
}
JSONObject reward = (JSONObject) Lbryio.parseResponse(
Lbryio.call("reward", "claim", options, Helper.METHOD_POST, null));
amountClaimed = Helper.getJSONDouble("reward_amount", 0, reward);
@@ -61,7 +78,7 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
amountClaimed == 1 ? 1 : 2,
new DecimalFormat(Helper.LBC_CURRENCY_FORMAT_PATTERN).format(amountClaimed)) : "";
message = Helper.getJSONString("reward_notification", defaultMessage, reward);
} catch (ApiCallException | LbryioRequestException | LbryioResponseException ex) {
} catch (ApiCallException | JSONException | LbryioRequestException | LbryioResponseException ex) {
error = ex;
}
@@ -79,6 +96,23 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
}
}
private String fetchSingleClaimTxid(String claimType) throws ApiCallException, JSONException {
Map<String, Object> options = new HashMap<>();
options.put("claim_type", claimType);
options.put("page", 1);
options.put("page_size", 1);
options.put("resolve", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_CLAIM_LIST, options);
JSONArray items = result.getJSONArray("items");
if (items.length() > 0) {
Claim claim = Claim.fromJSONObject(items.getJSONObject(0));
return claim.getTxid();
}
return null;
}
public interface ClaimRewardHandler {
void onSuccess(double amountClaimed, String message);
void onError(Exception error);
@@ -64,8 +64,6 @@ public class FetchSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | IllegalStateException ex) {
error = ex;
return null;
} finally {
Helper.closeDatabase(db);
}
return subscriptions;
@@ -0,0 +1,37 @@
package io.lbry.browser.tasks.localdata;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.UrlSuggestion;
public class FetchRecentUrlHistoryTask extends AsyncTask<Void, Void, List<UrlSuggestion>> {
private DatabaseHelper dbHelper;
private FetchRecentUrlHistoryHandler handler;
public FetchRecentUrlHistoryTask(DatabaseHelper dbHelper, FetchRecentUrlHistoryHandler handler) {
this.dbHelper = dbHelper;
this.handler = handler;
}
protected List<UrlSuggestion> doInBackground(Void... params) {
try {
SQLiteDatabase db = dbHelper.getReadableDatabase();
return DatabaseHelper.getRecentHistory(db);
} catch (SQLiteException ex) {
return new ArrayList<>();
}
}
protected void onPostExecute(List<UrlSuggestion> recentHistory) {
if (handler != null) {
handler.onSuccess(recentHistory);
}
}
public interface FetchRecentUrlHistoryHandler {
void onSuccess(List<UrlSuggestion> recentHistory);
}
}
@@ -0,0 +1,46 @@
package io.lbry.browser.tasks.localdata;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.model.ViewHistory;
import io.lbry.browser.utils.Helper;
public class FetchViewHistoryTask extends AsyncTask<Void, Void, List<ViewHistory>> {
private DatabaseHelper dbHelper;
private FetchViewHistoryHandler handler;
private int pageSize;
private Date lastDate;
public FetchViewHistoryTask(Date lastDate, int pageSize, DatabaseHelper dbHelper, FetchViewHistoryHandler handler) {
this.lastDate = lastDate;
this.pageSize = pageSize;
this.dbHelper = dbHelper;
this.handler = handler;
}
protected List<ViewHistory> doInBackground(Void... params) {
try {
SQLiteDatabase db = dbHelper.getReadableDatabase();
return DatabaseHelper.getViewHistory(
lastDate == null ? null : new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).format(lastDate), pageSize, db);
} catch (SQLiteException ex) {
return new ArrayList<>();
}
}
protected void onPostExecute(List<ViewHistory> history) {
if (handler != null) {
handler.onSuccess(history, history.size() < pageSize);
}
}
public interface FetchViewHistoryHandler {
void onSuccess(List<ViewHistory> history, boolean hasReachedEnd);
}
}
@@ -0,0 +1,137 @@
package io.lbry.browser.tasks.localdata;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.model.GalleryItem;
import io.lbry.browser.utils.Helper;
public class LoadGalleryItemsTask extends AsyncTask<Void, GalleryItem, List<GalleryItem>> {
private static final String TAG = "LoadGalleryItemsTask";
private LoadGalleryHandler handler;
private View progressView;
private Context context;
public LoadGalleryItemsTask(View progressView, Context context, LoadGalleryHandler handler) {
this.progressView = progressView;
this.context = context;
this.handler = handler;
}
protected void onPreExecute(Void... params) {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected List<GalleryItem> doInBackground(Void... params) {
List<GalleryItem> items = new ArrayList<>();
List<GalleryItem> itemsWithThumbnails = new ArrayList<>();
Cursor cursor = null;
if (context != null) {
ContentResolver resolver = context.getContentResolver();
try {
String[] projection = {
MediaStore.MediaColumns._ID,
MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.DISPLAY_NAME,
MediaStore.MediaColumns.MIME_TYPE,
MediaStore.Video.Media.DURATION
};
cursor = resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, null, null,
String.format("%s DESC LIMIT 150", MediaStore.MediaColumns.DATE_MODIFIED));
if (cursor != null) {
while (cursor.moveToNext()) {
int idColumn = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
int nameColumn = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
int typeColumn = cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE);
int pathColumn = cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
int durationColumn = cursor.getColumnIndex(MediaStore.Video.Media.DURATION);
GalleryItem item = new GalleryItem();
item.setId(cursor.getString(idColumn));
item.setName(cursor.getString(nameColumn));
item.setType(cursor.getString(typeColumn));
item.setFilePath(cursor.getString(pathColumn));
item.setDuration(cursor.getLong(durationColumn));
items.add(item);
}
}
} catch (SQLiteException ex) {
// failed to load videos. log and pass
Log.e(TAG, ex.getMessage(), ex);
} finally {
Helper.closeCursor(cursor);
}
// load (or generate) thumbnail for each item
for (GalleryItem item : items) {
String id = item.getId();
File cacheDir = context.getExternalCacheDir();
File thumbnailsDir = new File(String.format("%s/thumbnails", cacheDir.getAbsolutePath()));
if (!thumbnailsDir.isDirectory()) {
thumbnailsDir.mkdirs();
}
String thumbnailPath = String.format("%s/%s.png", thumbnailsDir.getAbsolutePath(), id);
File file = new File(thumbnailPath);
if (!file.exists()) {
// save the thumbnail to the path
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap thumbnail = MediaStore.Video.Thumbnails.getThumbnail(
resolver, Long.parseLong(id), MediaStore.Video.Thumbnails.MINI_KIND, options);
if (thumbnail != null) {
try (FileOutputStream os = new FileOutputStream(thumbnailPath)) {
thumbnail.compress(Bitmap.CompressFormat.PNG, 80, os);
} catch (IOException ex) {
// skip
}
}
}
if (file.exists() && file.length() > 0) {
item.setThumbnailPath(file.getAbsolutePath());
itemsWithThumbnails.add(item);
publishProgress(item);
}
}
}
return itemsWithThumbnails;
}
protected void onProgressUpdate(GalleryItem... items) {
if (handler != null) {
for (GalleryItem item : items) {
handler.onItemLoaded(item);
}
}
}
protected void onPostExecute(List<GalleryItem> items) {
if (handler != null) {
handler.onAllItemsLoaded(items);
}
}
public interface LoadGalleryHandler {
void onItemLoaded(GalleryItem item);
void onAllItemsLoaded(List<GalleryItem> items);
}
}
@@ -9,21 +9,21 @@ import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.tasks.GenericTaskHandler;
public class CreateUrlHistoryTask extends AsyncTask<Void, Void, Boolean> {
private Context context;
public class SaveUrlHistoryTask extends AsyncTask<Void, Void, Boolean> {
private DatabaseHelper dbHelper;
private UrlSuggestion suggestion;
private GenericTaskHandler handler;
private SaveUrlHistoryHandler handler;
private Exception error;
public CreateUrlHistoryTask(UrlSuggestion suggestion, Context context, GenericTaskHandler handler) {
public SaveUrlHistoryTask(UrlSuggestion suggestion, DatabaseHelper dbHelper, SaveUrlHistoryHandler handler) {
this.suggestion = suggestion;
this.context = context;
this.dbHelper = dbHelper;
this.handler = handler;
}
protected Boolean doInBackground(Void... params) {
try {
SQLiteDatabase db = ((MainActivity) context).getDbHelper().getWritableDatabase();
SQLiteDatabase db = dbHelper.getWritableDatabase();
DatabaseHelper.createOrUpdateUrlHistoryItem(suggestion.getText(), suggestion.getUri().toString(), suggestion.getType(), db);
} catch (Exception ex) {
error = ex;
@@ -35,10 +35,15 @@ public class CreateUrlHistoryTask extends AsyncTask<Void, Void, Boolean> {
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
handler.onSuccess();
handler.onSuccess(suggestion);
} else {
handler.onError(error);
}
}
}
public interface SaveUrlHistoryHandler {
void onSuccess(UrlSuggestion item);
void onError(Exception error);
}
}
@@ -0,0 +1,45 @@
package io.lbry.browser.tasks.localdata;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.ViewHistory;
public class SaveViewHistoryTask extends AsyncTask<Void, Void, Boolean> {
private DatabaseHelper dbHelper;
private ViewHistory history;
private SaveViewHistoryHandler handler;
private Exception error;
public SaveViewHistoryTask(ViewHistory history, DatabaseHelper dbHelper, SaveViewHistoryHandler handler) {
this.history = history;
this.dbHelper = dbHelper;
this.handler = handler;
}
protected Boolean doInBackground(Void... params) {
try {
SQLiteDatabase db = dbHelper.getWritableDatabase();
DatabaseHelper.createOrUpdateViewHistoryItem(history, db);
} catch (Exception ex) {
error = ex;
return false;
}
return true;
}
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
handler.onSuccess(history);
} else {
handler.onError(error);
}
}
}
public interface SaveViewHistoryHandler {
void onSuccess(ViewHistory item);
void onError(Exception error);
}
}
@@ -83,7 +83,7 @@ public class LoadSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
if (db != null) {
DatabaseHelper.createOrUpdateSubscription(subscription, db);
}
} catch (LbryUriException | SQLiteException ex) {
} catch (LbryUriException | SQLiteException | IllegalStateException ex) {
// pass
}
}
@@ -91,7 +91,11 @@ public class LoadSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
if (tags != null) {
if (db != null && tags.length() > 0) {
DatabaseHelper.setAllTagsUnfollowed(db);
try {
DatabaseHelper.setAllTagsUnfollowed(db);
} catch (IllegalStateException ex) {
// pass
}
}
followedTags = new ArrayList<>();
@@ -105,7 +109,7 @@ public class LoadSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
if (db != null) {
DatabaseHelper.createOrUpdateTag(tag, db);
}
} catch (SQLiteException ex) {
} catch (SQLiteException | IllegalStateException ex) {
// pass
}
}
@@ -5,7 +5,9 @@ import android.view.View;
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 io.lbry.browser.exceptions.ApiCallException;
@@ -15,14 +17,16 @@ import io.lbry.browser.utils.Lbry;
public class SupportCreateTask extends AsyncTask<Void, Void, Boolean> {
private String claimId;
private String channelId;
private BigDecimal amount;
private boolean tip;
private View progressView;
private GenericTaskHandler handler;
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.channelId = channelId;
this.amount = amount;
this.tip = tip;
this.progressView = progressView;
@@ -38,9 +42,13 @@ public class SupportCreateTask extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
try {
Map<String, Object> options = new HashMap<>();
options.put("blocking", true);
options.put("claim_id", claimId);
options.put("amount", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT).format(amount.doubleValue()));
options.put("amount", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(amount.doubleValue()));
options.put("tip", tip);
if (!Helper.isNullOrEmpty(channelId)) {
options.put("channel_id", channelId);
}
Lbry.genericApiCall(Lbry.METHOD_SUPPORT_CREATE, options);
} catch (ApiCallException ex) {
error = ex;
@@ -45,7 +45,7 @@ public class SyncSetTask extends AsyncTask<Void, Void, String> {
if (handler != null) {
if (!Helper.isNullOrEmpty(hash)) {
handler.onSyncSetSuccess(hash);
} else if (error != null) {
} else {
handler.onSyncSetError(error);
}
}
@@ -0,0 +1,73 @@
package io.lbry.browser.tasks.wallet;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class UnlockTipsTask extends AsyncTask<Void, Void, Boolean> {
private GenericTaskHandler handler;
private Exception error;
public UnlockTipsTask(GenericTaskHandler handler) {
this.handler = handler;
}
public Boolean doInBackground(Void... params) {
List<String> txids = new ArrayList<>();
try {
Map<String, Object> options = new HashMap<>();
options.put("type", "support");
options.put("is_not_my_input", true);
options.put("is_my_output", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_TXO_LIST, options);
if (result.has("items") && !result.isNull("items")) {
JSONArray items = result.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
String txid = Helper.getJSONString("txid", null, item);
if (!Helper.isNullOrEmpty(txid)) {
txids.add(txid);
}
}
}
if (txids.size() > 0) {
options = new HashMap<>();
options.put("txid", txids);
options.put("blocking", true);
Lbry.genericApiCall(Lbry.METHOD_TXO_SPEND, options);
}
return true;
} catch (ApiCallException | ClassCastException | JSONException ex) {
error = ex;
return false;
}
}
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
handler.onSuccess();
} else {
handler.onError(error);
}
}
}
}
@@ -20,19 +20,10 @@ public class WalletBalanceTask extends AsyncTask<Void, Void, WalletBalance> {
}
protected WalletBalance doInBackground(Void... params) {
WalletBalance balance = new WalletBalance();
WalletBalance balance;
try {
JSONObject json = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_WALLET_BALANCE);
JSONObject reservedSubtotals = Helper.getJSONObject("reserved_subtotals", json);
balance.setAvailable(new BigDecimal(Helper.getJSONString("available", "0", json)));
balance.setReserved(new BigDecimal(Helper.getJSONString("reserved", "0", json)));
balance.setTotal(new BigDecimal(Helper.getJSONString("total", "0", json)));
if (reservedSubtotals != null) {
balance.setClaims(new BigDecimal(Helper.getJSONString("claims", "0", reservedSubtotals)));
balance.setSupports(new BigDecimal(Helper.getJSONString("supports", "0", reservedSubtotals)));
balance.setTips(new BigDecimal(Helper.getJSONString("tips", "0", reservedSubtotals)));
}
balance = WalletBalance.fromJSONObject(json);
} catch (ApiCallException | ClassCastException ex) {
error = ex;
return null;
@@ -1,12 +1,36 @@
package io.lbry.browser.ui;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSpinner;
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 io.lbry.browser.BuildConfig;
import io.lbry.browser.MainActivity;
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.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.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.LbryUri;
import lombok.Getter;
import lombok.Setter;
@@ -14,12 +38,205 @@ public class BaseFragment extends Fragment {
@Getter
@Setter
private Map<String, Object> params;
private boolean rewardDriverClickListenerSet;
public boolean shouldHideGlobalPlayer() {
return false;
}
public boolean shouldSuspendGlobalPlayer() {
return false;
}
public void onStart() {
super.onStart();
if (shouldSuspendGlobalPlayer()) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity.suspendGlobalPlayer(context);
}
}
}
public void onStop() {
if (shouldSuspendGlobalPlayer()) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity.resumeGlobalPlayer(context);
}
}
rewardDriverClickListenerSet = false;
super.onStop();
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).setSelectedMenuItemForFragment(this);
MainActivity activity = (MainActivity) context;
activity.setSelectedMenuItemForFragment(this);
if (shouldHideGlobalPlayer()) {
activity.hideGlobalNowPlaying();
} else {
activity.checkNowPlaying();
}
}
}
public void checkRewardsDriverCard(String rewardDriverText, double minCost) {
View root = getView();
if (root != null) {
View rewardDriverCard = root.findViewById(R.id.reward_driver_card);
if (rewardDriverCard != null) {
if (!rewardDriverClickListenerSet) {
rewardDriverCard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).openRewards();
}
}
});
rewardDriverClickListenerSet = true;
}
// only apply to fragments that have the card present
((TextView) rewardDriverCard.findViewById(R.id.reward_driver_text)).setText(rewardDriverText);
boolean showRewardsDriver = Lbry.walletBalance == null ||
minCost == 0 && Lbry.walletBalance.getAvailable().doubleValue() == 0 |
Lbry.walletBalance.getAvailable().doubleValue() < Math.max(minCost, Helper.MIN_DEPOSIT);
rewardDriverCard.setVisibility(showRewardsDriver ? View.VISIBLE : View.GONE);
}
}
}
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,717 @@
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.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;
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);
}
checkCommentSdkInitializing();
}
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();
checkAndLoadComments();
}
private void checkAndLoadComments() {
View root = getView();
if (root != null) {
checkCommentSdkInitializing();
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, 500, 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();
}
}
@Override
public void onError(Exception error) {
// pass
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
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()));
}
}
@@ -1,7 +1,6 @@
package io.lbry.browser.ui.channel;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
@@ -16,25 +15,31 @@ import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import io.lbry.browser.FileViewActivity;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.ClaimListAdapter;
import io.lbry.browser.dialog.ContentFromDialogFragment;
import io.lbry.browser.dialog.ContentSortDialogFragment;
import io.lbry.browser.listener.DownloadActionListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.LbryFile;
import io.lbry.browser.tasks.claim.ClaimSearchResultHandler;
import io.lbry.browser.tasks.claim.ClaimSearchTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.Predefined;
import lombok.Setter;
public class ChannelContentFragment extends Fragment implements SharedPreferences.OnSharedPreferenceChangeListener {
public class ChannelContentFragment extends Fragment implements DownloadActionListener, SharedPreferences.OnSharedPreferenceChangeListener {
@Setter
private String channelId;
@@ -60,7 +65,7 @@ public class ChannelContentFragment extends Fragment implements SharedPreference
ViewGroup container, Bundle savedInstanceState) {
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;
sortLink = root.findViewById(R.id.channel_content_sort_link);
@@ -189,12 +194,20 @@ public class ChannelContentFragment extends Fragment implements SharedPreference
public void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(getContext()).registerOnSharedPreferenceChangeListener(this);
Context context = getContext();
if (context != null) {
((MainActivity) context).addDownloadActionListener(this);
}
PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);
fetchClaimSearchContent();
}
public void onPause() {
PreferenceManager.getDefaultSharedPreferences(getContext()).registerOnSharedPreferenceChangeListener(this);
Context context = getContext();
if (context != null) {
((MainActivity) context).removeDownloadActionListener(this);
}
PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);
super.onPause();
}
@@ -202,15 +215,15 @@ public class ChannelContentFragment extends Fragment implements SharedPreference
Context context = getContext();
boolean canShowMatureContent = false;
if (context != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
canShowMatureContent = sp.getBoolean(MainActivity.PREFERENCE_KEY_SHOW_MATURE_CONTENT, false);
}
return Lbry.buildClaimSearchOptions(
null,
(List) null,
null,
canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),
Arrays.asList(channelId),
!Helper.isNullOrEmpty(channelId) ? Arrays.asList(channelId) : null,
null,
getContentSortOrder(),
contentReleaseTime,
@@ -220,7 +233,7 @@ public class ChannelContentFragment extends Fragment implements SharedPreference
private List<String> getContentSortOrder() {
if (contentSortOrder == null) {
return Arrays.asList(Claim.ORDER_BY_RELEASE_TIME);
return Collections.singletonList(Claim.ORDER_BY_RELEASE_TIME);
}
return contentSortOrder;
}
@@ -242,31 +255,29 @@ public class ChannelContentFragment extends Fragment implements SharedPreference
contentClaimSearchLoading = true;
Helper.setViewVisibility(noContentView, View.GONE);
Map<String, Object> claimSearchOptions = buildContentOptions();
contentClaimSearchTask = new ClaimSearchTask(claimSearchOptions, Lbry.LBRY_TV_CONNECTION_STRING, getLoadingView(), new ClaimSearchTask.ClaimSearchResultHandler() {
contentClaimSearchTask = new ClaimSearchTask(claimSearchOptions, Lbry.LBRY_TV_CONNECTION_STRING, getLoadingView(), new ClaimSearchResultHandler() {
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (contentListAdapter == null) {
contentListAdapter = new ClaimListAdapter(claims, getContext());
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
String claimId = claim.getClaimId();
String url = !Helper.isNullOrEmpty(claim.getShortUrl()) ? claim.getShortUrl() : claim.getPermanentUrl();
if (claim.getName().startsWith("@")) {
// channel claim
Context context = getContext();
if (context != null) {
contentListAdapter = new ClaimListAdapter(claims, context);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).openChannelClaim(claim);
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
// channel claim
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
}
} else {
Intent intent = new Intent(getContext(), FileViewActivity.class);
intent.putExtra("claimId", claimId);
intent.putExtra("url", url);
MainActivity.startingFileViewActivity = true;
startActivity(intent);
}
}
});
});
}
} else {
contentListAdapter.addItems(claims);
}
@@ -299,4 +310,24 @@ public class ChannelContentFragment extends Fragment implements SharedPreference
fetchClaimSearchContent(true);
}
}
public void onDownloadAction(String downloadAction, String uri, String outpoint, String fileInfoJson, double progress) {
if ("abort".equals(downloadAction)) {
if (contentListAdapter != null) {
contentListAdapter.clearFileForClaimOrUrl(outpoint, uri);
}
return;
}
try {
JSONObject fileInfo = new JSONObject(fileInfoJson);
LbryFile claimFile = LbryFile.fromJSONObject(fileInfo);
String claimId = claimFile.getClaimId();
if (contentListAdapter != null) {
contentListAdapter.updateFileForClaimByIdOrUrl(claimFile, claimId, uri);
}
} catch (JSONException ex) {
// invalid file info for download
}
}
}
@@ -18,6 +18,7 @@ import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
@@ -37,6 +38,8 @@ import io.lbry.browser.BuildConfig;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.TagListAdapter;
import io.lbry.browser.listener.FilePickerListener;
import io.lbry.browser.listener.StoragePermissionListener;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.NavMenuItem;
@@ -44,7 +47,7 @@ import io.lbry.browser.model.Tag;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.UpdateSuggestedTagsTask;
import io.lbry.browser.tasks.UploadImageTask;
import io.lbry.browser.tasks.ChannelCreateUpdateTask;
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.BaseFragment;
@@ -54,7 +57,8 @@ import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.LbryUri;
import lombok.Getter;
public class ChannelFormFragment extends BaseFragment implements WalletBalanceListener, TagListAdapter.TagClickListener {
public class ChannelFormFragment extends BaseFragment implements
FilePickerListener, StoragePermissionListener, TagListAdapter.TagClickListener, WalletBalanceListener {
private static final int SUGGESTED_LIMIT = 8;
@@ -68,6 +72,7 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
private TextView linkShowOptional;
private MaterialButton buttonSave;
private NestedScrollView scrollView;
private View inlineBalanceContainer;
private TextView inlineBalanceValue;
private View uploadProgress;
@@ -109,6 +114,7 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_channel_form, container, false);
scrollView = root.findViewById(R.id.channel_form_scroll_view);
linkCancel = root.findViewById(R.id.channel_form_cancel_link);
linkShowOptional = root.findViewById(R.id.channel_form_toggle_optional);
buttonSave = root.findViewById(R.id.channel_form_save_button);
@@ -143,6 +149,7 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
addedTagsAdapter.setCustomizeMode(TagListAdapter.CUSTOMIZE_MODE_REMOVE);
addedTagsAdapter.setClickListener(this);
addedTagsList.setAdapter(addedTagsAdapter);
suggestedTagsAdapter = new TagListAdapter(new ArrayList<>(), getContext());
suggestedTagsAdapter.setCustomizeMode(TagListAdapter.CUSTOMIZE_MODE_ADD);
suggestedTagsAdapter.setClickListener(this);
@@ -165,6 +172,12 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
if (containerOptionalFields.getVisibility() != View.VISIBLE) {
containerOptionalFields.setVisibility(View.VISIBLE);
linkShowOptional.setText(R.string.hide_optional_fields);
scrollView.post(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(NestedScrollView.FOCUS_DOWN);
}
});
} else {
containerOptionalFields.setVisibility(View.GONE);
linkShowOptional.setText(R.string.show_optional_fields);
@@ -197,7 +210,7 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
@Override
public void onClick(View view) {
if (uploading) {
Snackbar.make(getView(), R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
Snackbar.make(view, R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
return;
}
@@ -208,6 +221,11 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (uploading) {
Snackbar.make(view, R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
return;
}
Claim claimToSave = buildChannelClaimToSave();
validateAndSaveClaim(claimToSave);
}
@@ -235,7 +253,13 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
private void checkParams() {
Map<String, Object> params = getParams();
if (params.containsKey("claim")) {
if (params == null) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).onBackPressed();
return;
}
} else if (params.containsKey("claim")) {
Claim claim = (Claim) params.get("claim");
if (claim != null && !claim.equals(this.currentClaim)) {
this.currentClaim = claim;
@@ -275,16 +299,17 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
}
private void validateAndSaveClaim(Claim claim) {
if (!editMode && Helper.isNullOrEmpty(claim.getName())) {
showError(getString(R.string.please_enter_channel_name));
return;
}
String channelName = claim.getName().startsWith("@") ? claim.getName().substring(1) : claim.getName();
if (!LbryUri.isNameValid(channelName)) {
showError(getString(R.string.channel_name_invalid_characters));
return;
}
if (!editMode) {
String channelName = claim.getName().startsWith("@") ? claim.getName().substring(1) : claim.getName();
if (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;
@@ -300,7 +325,7 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
showError(getString(R.string.please_enter_valid_deposit));
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));
showError(error);
return;
@@ -326,6 +351,14 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
logPublish.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
if (!editMode) {
// 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);
}
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
@@ -343,13 +376,6 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
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).show();
}
}
public void checkPermissionsAndLaunchFilePicker(boolean isCover) {
Context context = getContext();
if (MainActivity.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, context)) {
@@ -433,9 +459,15 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
@Override
public void onError(Exception error) {
Snackbar.make(getView(), R.string.image_upload_failed, Snackbar.LENGTH_LONG).setBackgroundTint(
ContextCompat.getColor(context, R.color.red)
).show();
if (getContext() != null) {
showError(getString(R.string.image_upload_failed));
}
if (coverFilePickerActive) {
// cover selected
imageCover.setImageResource(R.drawable.default_channel_cover);
} else if (thumbnailFilePickerActive) {
imageThumbnail.setImageDrawable(null);
}
coverFilePickerActive = false;
thumbnailFilePickerActive = false;
uploading = false;
@@ -470,12 +502,12 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
activity.showNavigationBackIcon();
activity.lockDrawer();
activity.hideFloatingWalletBalance();
activity.addFilePickerListener(this);
activity.addWalletBalanceListener(this);
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(editMode ? R.string.edit_channel : R.string.create_a_channel);
}
activity.setActionBarTitle(editMode ? R.string.edit_channel : R.string.create_a_channel);
}
}
@@ -490,10 +522,12 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) getContext();
activity.removeStoragePermissionListener(this);
activity.removeWalletBalanceListener(this);
activity.restoreToggle();
activity.showFloatingWalletBalance();
if (!MainActivity.startingFilePickerActivity) {
activity.removeFilePickerListener(this);
activity.removeNavFragment(ChannelFormFragment.class, NavMenuItem.ID_ITEM_CHANNELS);
}
}
@@ -503,17 +537,16 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
public void onResume() {
super.onResume();
checkParams();
checkRewardsDriver();
updateFieldsFromCurrentClaim();
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
LbryAnalytics.setCurrentScreen(activity, "Channel Form", "ChannelForm");
activity.addStoragePermissionListener(this);
if (editMode) {
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.edit_channel);
}
activity.setActionBarTitle(R.string.edit_channel);
}
}
String filterText = Helper.getValue(inputTagFilter.getText());
@@ -531,8 +564,11 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
Snackbar.make(getView(), getString(R.string.tag_already_added, tag.getName()), Snackbar.LENGTH_LONG).show();
return;
}
if (addedTagsAdapter.getItemCount() == 5) {
Snackbar.make(getView(), R.string.tag_limit_reached, Snackbar.LENGTH_LONG).show();
return;
}
tag.setFollowed(true);
addedTagsAdapter.addTag(tag);
if (suggestedTagsAdapter != null) {
suggestedTagsAdapter.removeTag(tag);
@@ -543,7 +579,6 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
checkNoTagResults();
}
public void removeTag(Tag tag) {
tag.setFollowed(false);
addedTagsAdapter.removeTag(tag);
updateSuggestedTags(currentFilter, SUGGESTED_LIMIT, false);
checkNoAddedTags();
@@ -555,6 +590,7 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
checkRewardsDriver();
}
public void setFilter(String filter) {
@@ -563,7 +599,14 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
}
private void updateSuggestedTags(String filter, int limit, boolean clearPrevious) {
UpdateSuggestedTagsTask task = new UpdateSuggestedTagsTask(filter, limit, addedTagsAdapter, suggestedTagsAdapter, clearPrevious, new UpdateSuggestedTagsTask.KnownTagsHandler() {
UpdateSuggestedTagsTask task = new UpdateSuggestedTagsTask(
filter,
limit,
addedTagsAdapter,
suggestedTagsAdapter,
clearPrevious,
false,
new UpdateSuggestedTagsTask.KnownTagsHandler() {
@Override
public void onSuccess(List<Tag> tags) {
if (suggestedTagsAdapter == null) {
@@ -586,13 +629,13 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
private Claim buildChannelClaimToSave() {
Claim claim = new Claim();
if (!editMode) {
String name = Helper.getValue(inputChannelName.getText());
if (!name.startsWith("@")) {
name = String.format("@%s", name);
}
claim.setName(name);
} else if (currentClaim != null) {
String name = Helper.getValue(inputChannelName.getText());
if (!name.startsWith("@")) {
name = String.format("@%s", name);
}
claim.setName(name);
if (currentClaim != null) {
claim.setClaimId(currentClaim.getClaimId());
}
@@ -651,4 +694,13 @@ public class ChannelFormFragment extends BaseFragment implements WalletBalanceLi
removeTag(tag);
}
}
private void checkRewardsDriver() {
Context ctx = getContext();
if (ctx != null) {
String rewardsDriverText = String.format("%s\n%s",
getString(R.string.channel_creation_requires_credits), getString(R.string.tap_here_to_get_some));
checkRewardsDriverCard(rewardsDriverText, Helper.MIN_DEPOSIT);
}
}
}
@@ -1,7 +1,9 @@
package io.lbry.browser.ui.channel;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
@@ -11,6 +13,7 @@ import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
@@ -26,23 +29,28 @@ import com.google.android.material.tabs.TabLayoutMediator;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import io.lbry.browser.MainActivity;
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.listener.FetchChannelsListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.ClaimCacheKey;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.tasks.claim.AbandonChannelTask;
import io.lbry.browser.tasks.claim.AbandonHandler;
import io.lbry.browser.tasks.lbryinc.ChannelSubscribeTask;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ResolveTask;
import io.lbry.browser.tasks.lbryinc.FetchStatCountTask;
import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.ui.controls.SolidIconView;
import io.lbry.browser.ui.following.FollowingFragment;
import io.lbry.browser.ui.findcontent.FollowingFragment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
@@ -73,7 +81,6 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private View buttonFollowUnfollow;
private int subCount;
private SolidIconView iconFollowUnfollow;
private View layoutNothingAtLocation;
private View layoutLoadingState;
@@ -119,8 +126,16 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
@Override
public void onClick(View view) {
if (claim != null) {
// show confirmation?
// delete claim task and redirect
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()).
setTitle(R.string.delete_channel).
setMessage(R.string.confirm_delete_channel)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
deleteCurrentClaim();
}
}).setNegativeButton(R.string.no, null);
builder.show();
}
}
});
@@ -131,7 +146,8 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
if (claim != null) {
try {
String shareUrl = LbryUri.parse(
!Helper.isNullOrEmpty(claim.getShortUrl()) ? claim.getShortUrl() : claim.getPermanentUrl()).toTvString();
!Helper.isNullOrEmpty(claim.getCanonicalUrl()) ? claim.getCanonicalUrl() :
(!Helper.isNullOrEmpty(claim.getShortUrl()) ? claim.getShortUrl() : claim.getPermanentUrl())).toTvString();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
@@ -157,21 +173,24 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
}
if (claim != null) {
SendTipDialogFragment dialog = SendTipDialogFragment.newInstance();
CreateSupportDialogFragment dialog = CreateSupportDialogFragment.newInstance();
dialog.setClaim(claim);
dialog.setListener(new SendTipDialogFragment.SendTipListener() {
dialog.setListener(new CreateSupportDialogFragment.CreateSupportListener() {
@Override
public void onTipSent(BigDecimal amount) {
public void onSupportCreated(BigDecimal amount, boolean isTip) {
double sentAmount = amount.doubleValue();
String message = getResources().getQuantityString(
R.plurals.you_sent_a_tip, sentAmount == 1.0 ? 1 : 2,
new DecimalFormat("#,###.##").format(sentAmount));
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).show();
View view = getView();
if (view != null) {
String message = getResources().getQuantityString(
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();
if (context instanceof MainActivity) {
dialog.show(((MainActivity) context).getSupportFragmentManager(), SendTipDialogFragment.TAG);
dialog.show(((MainActivity) context).getSupportFragmentManager(), CreateSupportDialogFragment.TAG);
}
}
}
@@ -225,6 +244,33 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
return root;
}
private void deleteCurrentClaim() {
if (claim != null) {
Helper.setViewVisibility(layoutDisplayArea, View.GONE);
Helper.setViewVisibility(layoutLoadingState, View.VISIBLE);
AbandonChannelTask task = new AbandonChannelTask(Arrays.asList(claim.getClaimId()), layoutResolving, new AbandonHandler() {
@Override
public void onComplete(List<String> successfulClaimIds, List<String> failedClaimIds, List<Exception> errors) {
Context context = getContext();
if (context instanceof MainActivity) {
if (failedClaimIds.size() == 0) {
MainActivity activity = (MainActivity) context;
activity.showMessage(R.string.channel_deleted);
activity.onBackPressed();
} else {
View root = getView();
if (root != null) {
Snackbar.make(root, R.string.channel_failed_delete, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
}
}
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private void checkIsFollowing() {
if (claim != null) {
boolean isFollowing = Lbryio.isFollowing(claim);
@@ -278,43 +324,62 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
boolean updateRequired = false;
Map<String, Object> params = getParams();
if (params.containsKey("claim")) {
Claim claim = (Claim) params.get("claim");
if (claim != null && !claim.equals(this.claim)) {
this.claim = claim;
updateRequired = true;
if (params != null) {
if (params.containsKey("claim")) {
Claim claim = (Claim) params.get("claim");
if (claim != null && !claim.equals(this.claim)) {
this.claim = claim;
updateRequired = true;
}
}
}
if (!updateRequired && params.containsKey("url")) {
String newUrl = params.get("url").toString();
if (!newUrl.equalsIgnoreCase(url) || claim == null) {
this.claim = null;
this.url = newUrl;
updateRequired = true;
if (params.containsKey("url")) {
String newUrl = params.get("url").toString();
if (claim == null || !newUrl.equalsIgnoreCase(url)) {
this.claim = null;
this.url = newUrl;
updateRequired = true;
}
}
}
if (updateRequired) {
resetSubCount();
if (!Helper.isNullOrEmpty(url)) {
resolveUrl();
// check if the claim is already cached
ClaimCacheKey key = new ClaimCacheKey();
key.setUrl(url);
if (Lbry.claimCache.containsKey(key)) {
claim = Lbry.claimCache.get(key);
} else {
resolveUrl();
}
} else if (claim == null) {
// nothing at this location
renderNothingAtLocation();
}
}
if (!Helper.isNullOrEmpty(url)) {
Helper.saveUrlHistory(url, claim != null ? claim.getTitle() : null, UrlSuggestion.TYPE_CHANNEL);
}
if (claim != null) {
renderClaim();
}
}
private void resolveUrl() {
layoutDisplayArea.setVisibility(View.INVISIBLE);
Helper.setViewVisibility(layoutDisplayArea, View.INVISIBLE);
Helper.setViewVisibility(layoutLoadingState, View.VISIBLE);
ResolveTask task = new ResolveTask(url, Lbry.LBRY_TV_CONNECTION_STRING, layoutResolving, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
if (claims.size() > 0 && !Helper.isNullOrEmpty(claims.get(0).getClaimId())) {
claim = claims.get(0);
if (!Helper.isNullOrEmpty(url)) {
Helper.saveUrlHistory(url, claim.getTitle(), UrlSuggestion.TYPE_CHANNEL);
}
renderClaim();
checkOwnChannel();
} else {
@@ -358,11 +423,12 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
String coverUrl = claim.getCoverUrl();
textTitle.setText(Helper.isNullOrEmpty(claim.getTitle()) ? claim.getName() : claim.getTitle());
if (!Helper.isNullOrEmpty(coverUrl)) {
Glide.with(getContext().getApplicationContext()).load(coverUrl).centerCrop().into(imageCover);
Context context = getContext();
if (context != null && !Helper.isNullOrEmpty(coverUrl)) {
Glide.with(context.getApplicationContext()).load(coverUrl).centerCrop().into(imageCover);
}
if (!Helper.isNullOrEmpty(thumbnailUrl)) {
Glide.with(getContext().getApplicationContext()).load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(imageThumbnail);
if (context != null && !Helper.isNullOrEmpty(thumbnailUrl)) {
Glide.with(context.getApplicationContext()).load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(imageThumbnail);
noThumbnailView.setVisibility(View.GONE);
} else {
imageThumbnail.setVisibility(View.GONE);
@@ -376,19 +442,23 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
}
try {
if (tabPager.getAdapter() == null) {
tabPager.setAdapter(new ChannelPagerAdapter(claim, (MainActivity) getContext()));
if (tabPager.getAdapter() == null && context instanceof MainActivity) {
tabPager.setAdapter(new ChannelPagerAdapter(claim, (MainActivity) context));
}
new TabLayoutMediator(tabLayout, tabPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
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();
} catch (IllegalStateException ex) {
// TODO: Fix why this is happening
// pass
}
new TabLayoutMediator(tabLayout, tabPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
tab.setText(position == 0 ? R.string.content : R.string.about);
}
}).attach();
}
private void resetSubCount() {
@@ -452,6 +522,13 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
// pass
}
return aboutFragment;
case 2:
ChannelCommentsFragment commentsFragment = ChannelCommentsFragment.class.newInstance();
if (channelClaim != null) {
commentsFragment.setClaim(channelClaim);
}
return commentsFragment;
}
return null;
@@ -463,7 +540,7 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
@Override
public int getItemCount() {
return 2;
return 3;
}
}
}
@@ -2,6 +2,7 @@ package io.lbry.browser.ui.channel;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
@@ -19,6 +20,7 @@ import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.HashMap;
@@ -32,6 +34,8 @@ import io.lbry.browser.listener.SdkStatusListener;
import io.lbry.browser.listener.SelectionModeListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.NavMenuItem;
import io.lbry.browser.tasks.claim.AbandonChannelTask;
import io.lbry.browser.tasks.claim.AbandonHandler;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.ui.BaseFragment;
@@ -144,22 +148,24 @@ public class ChannelManagerFragment extends BaseFragment implements ActionMode.C
ClaimListTask task = new ClaimListTask(Claim.TYPE_CHANNEL, getLoading(), new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = new ArrayList<>(claims);
Context context = getContext();
Lbry.ownChannels = Helper.filterDeletedClaims(new ArrayList<>(claims));
if (adapter == null) {
adapter = new ClaimListAdapter(claims, context);
adapter.setCanEnterSelectionMode(true);
adapter.setSelectionModeListener(ChannelManagerFragment.this);
adapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
if (context instanceof MainActivity) {
((MainActivity) context).openChannelClaim(claim);
Context context = getContext();
if (context != null) {
adapter = new ClaimListAdapter(claims, context);
adapter.setCanEnterSelectionMode(true);
adapter.setSelectionModeListener(ChannelManagerFragment.this);
adapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
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 {
adapter.setItems(claims);
@@ -260,7 +266,7 @@ public class ChannelManagerFragment extends BaseFragment implements ActionMode.C
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
//handleDeleteSelectedClaims(selectedClaims);
handleDeleteSelectedClaims(selectedClaims);
}
}).setNegativeButton(R.string.no, null);
builder.show();
@@ -270,4 +276,48 @@ public class ChannelManagerFragment extends BaseFragment implements ActionMode.C
return false;
}
private void handleDeleteSelectedClaims(List<Claim> selectedClaims) {
List<String> claimIds = new ArrayList<>();
for (Claim claim : selectedClaims) {
claimIds.add(claim.getClaimId());
}
if (actionMode != null) {
actionMode.finish();
}
Helper.setViewVisibility(channelList, View.INVISIBLE);
Helper.setViewVisibility(fabNewChannel, View.INVISIBLE);
AbandonChannelTask task = new AbandonChannelTask(claimIds, bigLoading, new AbandonHandler() {
@Override
public void onComplete(List<String> successfulClaimIds, List<String> failedClaimIds, List<Exception> errors) {
View root = getView();
if (root != null) {
if (failedClaimIds.size() > 0) {
Snackbar.make(root, R.string.one_or_more_channels_failed_abandon, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
} else if (successfulClaimIds.size() == claimIds.size()) {
try {
String message = getResources().getQuantityString(R.plurals.channels_deleted, successfulClaimIds.size());
Snackbar.make(root, message, Snackbar.LENGTH_LONG).show();
} catch (IllegalStateException ex) {
// pass
}
}
}
Lbry.abandonedClaimIds.addAll(successfulClaimIds);
if (adapter != null) {
adapter.setItems(Helper.filterDeletedClaims(adapter.getItems()));
}
Helper.setViewVisibility(channelList, View.VISIBLE);
Helper.setViewVisibility(fabNewChannel, View.VISIBLE);
checkNoChannels();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
@@ -1,7 +1,6 @@
package io.lbry.browser.ui.allcontent;
package io.lbry.browser.ui.findcontent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
@@ -17,12 +16,14 @@ import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.snackbar.Snackbar;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import io.lbry.browser.FileViewActivity;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.ClaimListAdapter;
@@ -30,9 +31,12 @@ import io.lbry.browser.dialog.ContentFromDialogFragment;
import io.lbry.browser.dialog.ContentScopeDialogFragment;
import io.lbry.browser.dialog.ContentSortDialogFragment;
import io.lbry.browser.dialog.CustomizeTagsDialogFragment;
import io.lbry.browser.listener.DownloadActionListener;
import io.lbry.browser.listener.TagListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.LbryFile;
import io.lbry.browser.model.Tag;
import io.lbry.browser.tasks.claim.ClaimSearchResultHandler;
import io.lbry.browser.tasks.claim.ClaimSearchTask;
import io.lbry.browser.tasks.FollowUnfollowTagTask;
import io.lbry.browser.ui.BaseFragment;
@@ -43,7 +47,7 @@ import io.lbry.browser.utils.Predefined;
import lombok.Getter;
// TODO: Similar code to FollowingFragment and Channel page fragment. Probably make common operations (sorting/filtering) into a control
public class AllContentFragment extends BaseFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
public class AllContentFragment extends BaseFragment implements DownloadActionListener, SharedPreferences.OnSharedPreferenceChangeListener {
@Getter
private boolean singleTagView;
@@ -207,6 +211,7 @@ public class AllContentFragment extends BaseFragment implements SharedPreference
singleTagView = true;
tags = Arrays.asList(tagName);
titleView.setText(Helper.capitalize(tagName));
Helper.setViewVisibility(customizeLink, View.GONE);
} else {
singleTagView = false;
// default to followed Tags scope if any tags are followed
@@ -218,8 +223,8 @@ public class AllContentFragment extends BaseFragment implements SharedPreference
titleView.setText(getString(R.string.all_content));
}
forPrefix.setVisibility(singleTagView ? View.GONE : View.VISIBLE);
scopeLink.setVisibility(singleTagView ? View.GONE : View.VISIBLE);
Helper.setViewVisibility(forPrefix, singleTagView ? View.GONE : View.VISIBLE);
Helper.setViewVisibility(scopeLink, singleTagView ? View.GONE : View.VISIBLE);
if (reload) {
fetchClaimSearchContent(true);
@@ -374,6 +379,7 @@ public class AllContentFragment extends BaseFragment implements SharedPreference
} else {
LbryAnalytics.setCurrentScreen(activity, "All Content", "AllContent");
}
activity.addDownloadActionListener(this);
}
PreferenceManager.getDefaultSharedPreferences(getContext()).registerOnSharedPreferenceChangeListener(this);
@@ -384,7 +390,11 @@ public class AllContentFragment extends BaseFragment implements SharedPreference
}
public void onPause() {
PreferenceManager.getDefaultSharedPreferences(getContext()).unregisterOnSharedPreferenceChangeListener(this);
Context context = getContext();
if (context != null) {
((MainActivity) context).removeDownloadActionListener(this);
}
PreferenceManager.getDefaultSharedPreferences(context).unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@@ -397,7 +407,7 @@ public class AllContentFragment extends BaseFragment implements SharedPreference
}
return Lbry.buildClaimSearchOptions(
null,
(List) null,
(currentContentScope == ContentScopeDialogFragment.ITEM_EVERYONE) ? null : tags,
canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),
null,
@@ -432,32 +442,29 @@ public class AllContentFragment extends BaseFragment implements SharedPreference
contentClaimSearchLoading = true;
Helper.setViewVisibility(noContentView, View.GONE);
Map<String, Object> claimSearchOptions = buildContentOptions();
contentClaimSearchTask = new ClaimSearchTask(claimSearchOptions, Lbry.LBRY_TV_CONNECTION_STRING, getLoadingView(), new ClaimSearchTask.ClaimSearchResultHandler() {
contentClaimSearchTask = new ClaimSearchTask(claimSearchOptions, Lbry.LBRY_TV_CONNECTION_STRING, getLoadingView(), new ClaimSearchResultHandler() {
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (contentListAdapter == null) {
contentListAdapter = new ClaimListAdapter(claims, getContext());
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
String claimId = claim.getClaimId();
String url = !Helper.isNullOrEmpty(claim.getShortUrl()) ? claim.getShortUrl() : claim.getPermanentUrl();
if (claim.getName().startsWith("@")) {
// channel claim
Context context = getContext();
if (context != null) {
contentListAdapter = new ClaimListAdapter(claims, context);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).openChannelClaim(claim);
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
// channel claim
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
}
} else {
Intent intent = new Intent(getContext(), FileViewActivity.class);
intent.putExtra("claimId", claimId);
intent.putExtra("url", url);
MainActivity.startingFileViewActivity = true;
startActivity(intent);
}
}
});
});
}
} else {
contentListAdapter.addItems(claims);
}
@@ -490,4 +497,24 @@ public class AllContentFragment extends BaseFragment implements SharedPreference
fetchClaimSearchContent(true);
}
}
public void onDownloadAction(String downloadAction, String uri, String outpoint, String fileInfoJson, double progress) {
if ("abort".equals(downloadAction)) {
if (contentListAdapter != null) {
contentListAdapter.clearFileForClaimOrUrl(outpoint, uri);
}
return;
}
try {
JSONObject fileInfo = new JSONObject(fileInfoJson);
LbryFile claimFile = LbryFile.fromJSONObject(fileInfo);
String claimId = claimFile.getClaimId();
if (contentListAdapter != null) {
contentListAdapter.updateFileForClaimByIdOrUrl(claimFile, claimId, uri);
}
} catch (JSONException ex) {
// invalid file info for download
}
}
}
@@ -1,7 +1,6 @@
package io.lbry.browser.ui.editorschoice;
package io.lbry.browser.ui.findcontent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
@@ -22,12 +21,12 @@ import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.FileViewActivity;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.EditorsChoiceItemAdapter;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.EditorsChoiceItem;
import io.lbry.browser.tasks.claim.ClaimSearchResultHandler;
import io.lbry.browser.tasks.claim.ClaimSearchTask;
import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.utils.Helper;
@@ -106,7 +105,7 @@ public class EditorsChoiceFragment extends BaseFragment {
}
contentLoading = true;
ClaimSearchTask task = new ClaimSearchTask(buildContentOptions(), Lbry.LBRY_TV_CONNECTION_STRING, loading, new ClaimSearchTask.ClaimSearchResultHandler() {
ClaimSearchTask task = new ClaimSearchTask(buildContentOptions(), Lbry.LBRY_TV_CONNECTION_STRING, loading, new ClaimSearchResultHandler() {
@Override
public void onSuccess(List<Claim> items, boolean hasReachedEnd) {
List<EditorsChoiceItem> data = buildDataFromClaims(items);
@@ -116,11 +115,10 @@ public class EditorsChoiceFragment extends BaseFragment {
@Override
public void onEditorsChoiceItemClicked(EditorsChoiceItem item) {
String url = item.getPermanentUrl();
Intent intent = new Intent(getContext(), FileViewActivity.class);
intent.putExtra("url", url);
MainActivity.startingFileViewActivity = true;
startActivity(intent);
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).openFileUrl(url);
}
}
});
} else {
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,6 @@
package io.lbry.browser.ui.following;
package io.lbry.browser.ui.findcontent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
@@ -20,12 +19,14 @@ import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import io.lbry.browser.FileViewActivity;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.ChannelFilterListAdapter;
@@ -35,8 +36,11 @@ import io.lbry.browser.dialog.ContentFromDialogFragment;
import io.lbry.browser.dialog.ContentSortDialogFragment;
import io.lbry.browser.dialog.DiscoverDialogFragment;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.listener.DownloadActionListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.LbryFile;
import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.tasks.claim.ClaimSearchResultHandler;
import io.lbry.browser.tasks.lbryinc.ChannelSubscribeTask;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimSearchTask;
@@ -53,7 +57,9 @@ import io.lbry.browser.utils.Predefined;
public class FollowingFragment extends BaseFragment implements
FetchSubscriptionsTask.FetchSubscriptionsHandler,
ChannelItemSelectionListener, SharedPreferences.OnSharedPreferenceChangeListener {
ChannelItemSelectionListener,
DownloadActionListener,
SharedPreferences.OnSharedPreferenceChangeListener {
public static boolean resetClaimSearchContent;
private static final int SUGGESTED_PAGE_SIZE = 45;
@@ -83,6 +89,7 @@ public class FollowingFragment extends BaseFragment implements
private boolean contentClaimSearchLoading = false;
private boolean suggestedClaimSearchLoading = false;
private View noContentView;
private boolean subscriptionsShown;
private List<Integer> queuedContentPages = new ArrayList<>();
private List<Integer> queuedSuggestedPages = new ArrayList<>();
@@ -241,9 +248,11 @@ public class FollowingFragment extends BaseFragment implements
discoverLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Helper.setViewEnabled(discoverLink, false);
buildChannelIdsAndUrls();
currentSuggestedPage = 1;
discoverDialog = DiscoverDialogFragment.newInstance();
excludeChannelIdsForDiscover = channelIds != null ? new ArrayList<>(channelIds) : null;
discoverDialog.setAdapter(suggestedChannelAdapter);
discoverDialog.setDialogActionsListener(new DiscoverDialogFragment.DiscoverDialogListener() {
@Override
@@ -258,6 +267,10 @@ public class FollowingFragment extends BaseFragment implements
public void onCancel() {
discoverDialog = null;
excludeChannelIdsForDiscover = null;
if (suggestedChannelAdapter != null) {
suggestedChannelAdapter.clearItems();
}
Helper.setViewEnabled(discoverLink, true);
}
@Override
public void onResume() {
@@ -334,6 +347,7 @@ public class FollowingFragment extends BaseFragment implements
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
LbryAnalytics.setCurrentScreen(activity, "Subscriptions", "Subscriptions");
activity.addDownloadActionListener(this);
}
// check if subscriptions exist
@@ -345,16 +359,20 @@ public class FollowingFragment extends BaseFragment implements
}
if (Lbryio.subscriptions != null && Lbryio.subscriptions.size() > 0) {
fetchLoadedSubscriptions();
fetchLoadedSubscriptions(true);
} else {
fetchSubscriptions();
}
}
public void onPause() {
PreferenceManager.getDefaultSharedPreferences(getContext()).unregisterOnSharedPreferenceChangeListener(this);
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).removeDownloadActionListener(this);
}
PreferenceManager.getDefaultSharedPreferences(context).unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
public void fetchLoadedSubscriptions() {
public void fetchLoadedSubscriptions(boolean showSubscribed) {
subscriptionsList = new ArrayList<>(Lbryio.subscriptions);
buildChannelIdsAndUrls();
if (Lbryio.cacheResolvedSubscriptions.size() > 0) {
@@ -365,7 +383,9 @@ public class FollowingFragment extends BaseFragment implements
fetchClaimSearchContent(resetClaimSearchContent);
resetClaimSearchContent = false;
showSubscribedContent();
if (showSubscribed && subscriptionsList.size() > 0) {
showSubscribedContent();
}
}
public void loadFollowing() {
@@ -379,8 +399,12 @@ public class FollowingFragment extends BaseFragment implements
}
private Map<String, Object> buildSuggestedOptions() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
boolean canShowMatureContent = sp.getBoolean(MainActivity.PREFERENCE_KEY_SHOW_MATURE_CONTENT, false);
Context context = getContext();
boolean canShowMatureContent = false;
if (context != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
canShowMatureContent = sp.getBoolean(MainActivity.PREFERENCE_KEY_SHOW_MATURE_CONTENT, false);
}
return Lbry.buildClaimSearchOptions(
Claim.TYPE_CHANNEL,
@@ -403,7 +427,7 @@ public class FollowingFragment extends BaseFragment implements
}
return Lbry.buildClaimSearchOptions(
Claim.TYPE_STREAM,
Arrays.asList(Claim.TYPE_STREAM, Claim.TYPE_REPOST),
null,
canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),
getChannelIds(),
@@ -417,7 +441,7 @@ public class FollowingFragment extends BaseFragment implements
private List<String> getChannelIds() {
if (channelFilterListAdapter != null) {
Claim selected = channelFilterListAdapter.getSelectedItem();
if (selected != null) {
if (selected != null && !Helper.isNullOrEmpty(selected.getClaimId())) {
return Arrays.asList(selected.getClaimId());
}
}
@@ -446,6 +470,7 @@ public class FollowingFragment extends BaseFragment implements
}
private void showSubscribedContent() {
subscriptionsShown = true;
Helper.setViewText(titleView, R.string.channels_you_follow);
Helper.setViewVisibility(horizontalChannelList, View.VISIBLE);
@@ -465,6 +490,11 @@ public class FollowingFragment extends BaseFragment implements
String url = subscription.getUrl();
LbryUri uri = LbryUri.parse(url);
String claimId = uri.getClaimId();
if (Helper.isNullOrEmpty(claimId) || Helper.isNullOrEmpty(url)) {
// don't add null / empty claim IDs or URLs
continue;
}
channelIds.add(claimId);
channelUrls.add(url);
} catch (LbryUriException ex) {
@@ -472,6 +502,8 @@ public class FollowingFragment extends BaseFragment implements
}
}
}
excludeChannelIdsForDiscover = channelIds != null ? new ArrayList<>(channelIds) : null;
}
private void fetchAndResolveChannelList() {
@@ -500,8 +532,9 @@ public class FollowingFragment extends BaseFragment implements
}
private void updateChannelFilterListAdapter(List<Claim> resolvedSubs, boolean reset) {
if (channelFilterListAdapter == null) {
channelFilterListAdapter = new ChannelFilterListAdapter(getContext());
Context context = getContext();
if (channelFilterListAdapter == null && context != null) {
channelFilterListAdapter = new ChannelFilterListAdapter(context);
channelFilterListAdapter.setListener(new ChannelItemSelectionListener() {
@Override
public void onChannelItemSelected(Claim claim) {
@@ -536,14 +569,16 @@ public class FollowingFragment extends BaseFragment implements
});
}
if (horizontalChannelList != null && horizontalChannelList.getAdapter() == null) {
horizontalChannelList.setAdapter(channelFilterListAdapter);
if (channelFilterListAdapter != null) {
if (horizontalChannelList != null && horizontalChannelList.getAdapter() == null) {
horizontalChannelList.setAdapter(channelFilterListAdapter);
}
if (reset) {
channelFilterListAdapter.clearClaims();
channelFilterListAdapter.setSelectedItem(null);
}
channelFilterListAdapter.addClaims(resolvedSubs);
}
if (reset) {
channelFilterListAdapter.clearClaims();
channelFilterListAdapter.setSelectedItem(null);
}
channelFilterListAdapter.addClaims(resolvedSubs);
}
private void fetchClaimSearchContent() {
@@ -559,32 +594,29 @@ public class FollowingFragment extends BaseFragment implements
contentClaimSearchLoading = true;
Helper.setViewVisibility(noContentView, View.GONE);
Map<String, Object> claimSearchOptions = buildContentOptions();
contentClaimSearchTask = new ClaimSearchTask(claimSearchOptions, Lbry.LBRY_TV_CONNECTION_STRING, getLoadingView(), new ClaimSearchTask.ClaimSearchResultHandler() {
contentClaimSearchTask = new ClaimSearchTask(claimSearchOptions, Lbry.LBRY_TV_CONNECTION_STRING, getLoadingView(), new ClaimSearchResultHandler() {
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (contentListAdapter == null) {
contentListAdapter = new ClaimListAdapter(claims, getContext());
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
String claimId = claim.getClaimId();
String url = !Helper.isNullOrEmpty(claim.getShortUrl()) ? claim.getShortUrl() : claim.getPermanentUrl();
if (claim.getName().startsWith("@")) {
// channel claim
Context context = getContext();
if (context != null) {
contentListAdapter = new ClaimListAdapter(claims, context);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).openChannelClaim(claim);
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
// channel claim
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
}
} else {
Intent intent = new Intent(getContext(), FileViewActivity.class);
intent.putExtra("claimId", claimId);
intent.putExtra("url", url);
MainActivity.startingFileViewActivity = true;
startActivity(intent);
}
}
});
});
}
} else {
contentListAdapter.addItems(claims);
}
@@ -608,11 +640,12 @@ public class FollowingFragment extends BaseFragment implements
}
private void updateSuggestedDoneButtonText() {
int selected = suggestedChannelAdapter == null ? 0 : suggestedChannelAdapter.getSelectedCount();
int remaining = MIN_SUGGESTED_SUBSCRIBE_COUNT - selected;
String buttonText = remaining <= 0 ? getString(R.string.done) : getString(R.string.n_remaining, remaining);
if (suggestedDoneButton != null) {
suggestedDoneButton.setText(buttonText);
Context context = getContext();
if (context != null) {
int selected = suggestedChannelAdapter == null ? 0 : suggestedChannelAdapter.getSelectedCount();
int remaining = MIN_SUGGESTED_SUBSCRIBE_COUNT - selected;
String buttonText = remaining <= 0 ? getString(R.string.done) : getString(R.string.n_remaining, remaining);
Helper.setViewText(suggestedDoneButton, buttonText);
}
}
@@ -631,7 +664,7 @@ public class FollowingFragment extends BaseFragment implements
buildSuggestedOptions(),
Lbry.LBRY_TV_CONNECTION_STRING,
suggestedChannelAdapter == null || suggestedChannelAdapter.getItemCount() == 0 ? bigContentLoading : contentLoading,
new ClaimSearchTask.ClaimSearchResultHandler() {
new ClaimSearchResultHandler() {
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
suggestedHasReachedEnd = hasReachedEnd;
@@ -705,12 +738,11 @@ public class FollowingFragment extends BaseFragment implements
ChannelSubscribeTask task = new ChannelSubscribeTask(getContext(), channelClaimId, subscription, false, new ChannelSubscribeTask.ChannelSubscribeHandler() {
@Override
public void onSuccess() {
if (discoverDialog != null) {
Lbryio.addSubscription(subscription);
Lbryio.addCachedResolvedSubscription(claim);
resetClaimSearchContent = true;
fetchLoadedSubscriptions();
}
Lbryio.addSubscription(subscription);
Lbryio.addCachedResolvedSubscription(claim);
resetClaimSearchContent = true;
fetchLoadedSubscriptions(subscriptionsShown);
saveSharedUserState();
}
@@ -727,12 +759,11 @@ public class FollowingFragment extends BaseFragment implements
ChannelSubscribeTask task = new ChannelSubscribeTask(getContext(), channelClaimId, subscription, true, new ChannelSubscribeTask.ChannelSubscribeHandler() {
@Override
public void onSuccess() {
if (discoverDialog != null) {
Lbryio.removeSubscription(subscription);
Lbryio.removeCachedResolvedSubscription(claim);
resetClaimSearchContent = true;
fetchLoadedSubscriptions();
}
Lbryio.removeSubscription(subscription);
Lbryio.removeCachedResolvedSubscription(claim);
resetClaimSearchContent = true;
fetchLoadedSubscriptions(subscriptionsShown);
saveSharedUserState();
}
@@ -766,4 +797,24 @@ public class FollowingFragment extends BaseFragment implements
fetchClaimSearchContent(true);
}
}
public void onDownloadAction(String downloadAction, String uri, String outpoint, String fileInfoJson, double progress) {
if ("abort".equals(downloadAction)) {
if (contentListAdapter != null) {
contentListAdapter.clearFileForClaimOrUrl(outpoint, uri);
}
return;
}
try {
JSONObject fileInfo = new JSONObject(fileInfoJson);
LbryFile claimFile = LbryFile.fromJSONObject(fileInfo);
String claimId = claimFile.getClaimId();
if (contentListAdapter != null) {
contentListAdapter.updateFileForClaimByIdOrUrl(claimFile, claimId, uri);
}
} catch (JSONException ex) {
// invalid file info for download
}
}
}
@@ -1,4 +1,4 @@
package io.lbry.browser.ui.search;
package io.lbry.browser.ui.findcontent;
import android.content.Context;
import android.content.SharedPreferences;
@@ -15,18 +15,27 @@ import androidx.preference.PreferenceManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.ClaimListAdapter;
import io.lbry.browser.listener.DownloadActionListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.ClaimCacheKey;
import io.lbry.browser.model.LbryFile;
import io.lbry.browser.model.NavMenuItem;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimSearchTask;
import io.lbry.browser.tasks.claim.ClaimSearchResultHandler;
import io.lbry.browser.tasks.LighthouseSearchTask;
import io.lbry.browser.tasks.claim.ResolveTask;
import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.ui.publish.PublishFragment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
@@ -34,10 +43,10 @@ import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
public class SearchFragment extends BaseFragment implements
ClaimListAdapter.ClaimListItemListener, SharedPreferences.OnSharedPreferenceChangeListener {
private ClaimListAdapter resultListAdapter;
ClaimListAdapter.ClaimListItemListener, DownloadActionListener, SharedPreferences.OnSharedPreferenceChangeListener {
private static final int PAGE_SIZE = 25;
private ClaimListAdapter resultListAdapter;
private ProgressBar loadingView;
private RecyclerView resultList;
private TextView noQueryView;
@@ -95,6 +104,7 @@ public class SearchFragment extends BaseFragment implements
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
LbryAnalytics.setCurrentScreen(activity, "Search", "Search");
activity.addDownloadActionListener(this);
}
if (!Helper.isNullOrEmpty(currentQuery)) {
logSearch(currentQuery);
@@ -106,7 +116,11 @@ public class SearchFragment extends BaseFragment implements
}
public void onPause() {
PreferenceManager.getDefaultSharedPreferences(getContext()).unregisterOnSharedPreferenceChangeListener(this);
Context context = getContext();
if (context != null) {
((MainActivity) context).removeDownloadActionListener(this);
}
PreferenceManager.getDefaultSharedPreferences(context).unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
@@ -141,7 +155,7 @@ public class SearchFragment extends BaseFragment implements
private void resolveFeaturedItem(String vanityUrl) {
final ClaimCacheKey key = new ClaimCacheKey();
key.setVanityUrl(vanityUrl);
key.setUrl(vanityUrl);
if (Lbry.claimCache.containsKey(key)) {
Claim cachedClaim = Lbry.claimCache.get(key);
updateFeaturedItemFromResolvedClaim(cachedClaim);
@@ -170,16 +184,27 @@ public class SearchFragment extends BaseFragment implements
if (resultListAdapter != null) {
Claim unresolved = resultListAdapter.getFeaturedItem();
// only set the values we need
unresolved.setClaimId(resolved.getClaimId());
unresolved.setName(resolved.getName());
unresolved.setTimestamp(resolved.getTimestamp());
unresolved.setValueType(resolved.getValueType());
unresolved.setPermanentUrl(resolved.getPermanentUrl());
unresolved.setValue(resolved.getValue());
unresolved.setSigningChannel(resolved.getSigningChannel());
unresolved.setUnresolved(false);
unresolved.setConfirmations(resolved.getConfirmations());
Context context = getContext();
boolean canShowMatureContent = false;
if (context != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
canShowMatureContent = sp.getBoolean(MainActivity.PREFERENCE_KEY_SHOW_MATURE_CONTENT, false);
}
if (resolved.isMature() && !canShowMatureContent) {
resultListAdapter.removeFeaturedItem();
} else if (unresolved != null) {
// only set the values we need
unresolved.setClaimId(resolved.getClaimId());
unresolved.setName(resolved.getName());
unresolved.setTimestamp(resolved.getTimestamp());
unresolved.setValueType(resolved.getValueType());
unresolved.setPermanentUrl(resolved.getPermanentUrl());
unresolved.setValue(resolved.getValue());
unresolved.setSigningChannel(resolved.getSigningChannel());
unresolved.setRepostedClaim(resolved.getRepostedClaim());
unresolved.setUnresolved(false);
unresolved.setConfirmations(resolved.getConfirmations());
}
resultListAdapter.notifyDataSetChanged();
}
@@ -202,39 +227,49 @@ public class SearchFragment extends BaseFragment implements
}
searchLoading = true;
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
boolean canShowMatureContent = sp.getBoolean(MainActivity.PREFERENCE_KEY_SHOW_MATURE_CONTENT, false);
Context context = getContext();
boolean canShowMatureContent = false;
if (context != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
canShowMatureContent = sp.getBoolean(MainActivity.PREFERENCE_KEY_SHOW_MATURE_CONTENT, false);
}
LighthouseSearchTask task = new LighthouseSearchTask(
currentQuery, PAGE_SIZE, currentFrom, canShowMatureContent, null, loadingView, new ClaimSearchTask.ClaimSearchResultHandler() {
currentQuery, PAGE_SIZE, currentFrom, canShowMatureContent, null, loadingView, new ClaimSearchResultHandler() {
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
contentHasReachedEnd = hasReachedEnd;
searchLoading = false;
if (resultListAdapter == null) {
resultListAdapter = new ClaimListAdapter(claims, getContext());
resultListAdapter.addFeaturedItem(buildFeaturedItem(query));
resolveFeaturedItem(buildVanityUrl(query));
resultListAdapter.setListener(SearchFragment.this);
if (resultList != null) {
resultList.setAdapter(resultListAdapter);
Context context = getContext();
if (context != null) {
if (resultListAdapter == null) {
resultListAdapter = new ClaimListAdapter(claims, context);
resultListAdapter.addFeaturedItem(buildFeaturedItem(query));
resolveFeaturedItem(buildVanityUrl(query));
resultListAdapter.setListener(SearchFragment.this);
if (resultList != null) {
resultList.setAdapter(resultListAdapter);
}
} else {
resultListAdapter.addItems(claims);
}
} else {
resultListAdapter.addItems(claims);
}
int itemCount = resultListAdapter.getItemCount();
noQueryView.setVisibility(View.GONE);
noResultsView.setVisibility(itemCount == 0 ? View.VISIBLE : View.GONE);
noResultsView.setText(getString(R.string.search_no_results, currentQuery));
int itemCount = resultListAdapter.getItemCount();
Helper.setViewVisibility(noQueryView, View.GONE);
Helper.setViewVisibility(noResultsView, itemCount == 0 ? View.VISIBLE : View.GONE);
Helper.setViewText(noResultsView, getString(R.string.search_no_results, currentQuery));
}
}
@Override
public void onError(Exception error) {
Context context = getContext();
int itemCount = resultListAdapter == null ? 0 : resultListAdapter.getItemCount();
noQueryView.setVisibility(View.GONE);
noResultsView.setVisibility(itemCount == 0 ? View.VISIBLE : View.GONE);
noResultsView.setText(getString(R.string.search_no_results, currentQuery));
Helper.setViewVisibility(noQueryView, View.GONE);
Helper.setViewVisibility(noResultsView, itemCount == 0 ? View.VISIBLE : View.GONE);
if (context != null) {
Helper.setViewText(noResultsView, getString(R.string.search_no_results, currentQuery));
}
searchLoading = false;
}
});
@@ -247,13 +282,20 @@ public class SearchFragment extends BaseFragment implements
return;
}
if (claim.isUnresolved()) {
// open the publish page
} else if (claim.getName().startsWith("@")) {
((MainActivity) getContext()).openChannelUrl(claim.getPermanentUrl());
} else {
// not a channel
MainActivity.openFileClaim(claim, getContext());
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.isUnresolved()) {
// open the publish page
Map<String, Object> params = new HashMap<>();
params.put("suggestedUrl", claim.getName());
activity.openFragment(PublishFragment.class, true, NavMenuItem.ID_ITEM_NEW_PUBLISH, params);
} else if (claim.getName().startsWith("@")) {
activity.openChannelUrl(claim.getPermanentUrl());
} else {
// not a channel
activity.openFileClaim(claim);
}
}
}
@@ -262,4 +304,24 @@ public class SearchFragment extends BaseFragment implements
search(currentQuery, currentFrom);
}
}
public void onDownloadAction(String downloadAction, String uri, String outpoint, String fileInfoJson, double progress) {
if ("abort".equals(downloadAction)) {
if (resultListAdapter != null) {
resultListAdapter.clearFileForClaimOrUrl(outpoint, uri);
}
return;
}
try {
JSONObject fileInfo = new JSONObject(fileInfoJson);
LbryFile claimFile = LbryFile.fromJSONObject(fileInfo);
String claimId = claimFile.getClaimId();
if (resultListAdapter != null) {
resultListAdapter.updateFileForClaimByIdOrUrl(claimFile, claimId, uri);
}
} catch (JSONException ex) {
// invalid file info for download
}
}
}
@@ -0,0 +1,748 @@
package io.lbry.browser.ui.library;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.snackbar.Snackbar;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.ClaimListAdapter;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.listener.DownloadActionListener;
import io.lbry.browser.listener.SdkStatusListener;
import io.lbry.browser.listener.SelectionModeListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.LbryFile;
import io.lbry.browser.model.ViewHistory;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.tasks.claim.ClaimSearchResultHandler;
import io.lbry.browser.tasks.claim.PurchaseListTask;
import io.lbry.browser.tasks.claim.ResolveTask;
import io.lbry.browser.tasks.file.BulkDeleteFilesTask;
import io.lbry.browser.tasks.file.FileListTask;
import io.lbry.browser.tasks.localdata.FetchViewHistoryTask;
import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.LbryUri;
public class LibraryFragment extends BaseFragment implements
ActionMode.Callback, DownloadActionListener, SelectionModeListener, SdkStatusListener {
private static final int FILTER_DOWNLOADS = 1;
private static final int FILTER_PURCHASES = 2;
private static final int FILTER_HISTORY = 3;
private static final int PAGE_SIZE = 50;
private ActionMode actionMode;
private int currentFilter;
private List<LbryFile> currentFiles;
private View layoutSdkInitializing;
private RecyclerView contentList;
private ClaimListAdapter contentListAdapter;
private ProgressBar listLoading;
private TextView linkFilterDownloads;
private TextView linkFilterPurchases;
private TextView linkFilterHistory;
private View layoutListEmpty;
private TextView textListEmpty;
private int currentPage;
private Date lastDate;
private boolean listReachedEnd;
private boolean contentListLoading;
private boolean initialOwnClaimsFetched;
private CardView cardStats;
private TextView linkStats;
private TextView linkHide;
private View viewStatsDistribution;
private View viewVideoStatsBar;
private View viewAudioStatsBar;
private View viewImageStatsBar;
private View viewOtherStatsBar;
private TextView textStatsTotalSize;
private TextView textStatsTotalSizeUnits;
private TextView textStatsVideoSize;
private TextView textStatsAudioSize;
private TextView textStatsImageSize;
private TextView textStatsOtherSize;
private View legendVideo;
private View legendAudio;
private View legendImage;
private View legendOther;
private long totalBytes;
private long totalVideoBytes;
private long totalAudioBytes;
private long totalImageBytes;
private long totalOtherBytes;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_library, container, false);
layoutSdkInitializing = root.findViewById(R.id.container_library_sdk_initializing);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
contentList = root.findViewById(R.id.library_list);
contentList.setLayoutManager(llm);
listLoading = root.findViewById(R.id.library_list_loading);
linkFilterDownloads = root.findViewById(R.id.library_filter_link_downloads);
linkFilterPurchases = root.findViewById(R.id.library_filter_link_purchases);
linkFilterHistory = root.findViewById(R.id.library_filter_link_history);
layoutListEmpty = root.findViewById(R.id.library_empty_container);
textListEmpty = root.findViewById(R.id.library_list_empty_text);
currentFilter = FILTER_DOWNLOADS;
linkFilterDownloads.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showDownloads();
}
});
linkFilterPurchases.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showPurchases();
}
});
linkFilterHistory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showHistory();
}
});
contentList.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
if (contentListLoading) {
return;
}
LinearLayoutManager lm = (LinearLayoutManager) recyclerView.getLayoutManager();
if (lm != null) {
int visibleItemCount = lm.getChildCount();
int totalItemCount = lm.getItemCount();
int pastVisibleItems = lm.findFirstVisibleItemPosition();
if (pastVisibleItems + visibleItemCount >= totalItemCount) {
if (!listReachedEnd) {
// load more
if (currentFilter == FILTER_DOWNLOADS) {
currentPage++;
fetchDownloads();
} else if (currentFilter == FILTER_HISTORY) {
fetchHistory();
}
}
}
}
}
});
// stats
linkStats = root.findViewById(R.id.library_show_stats);
linkHide = root.findViewById(R.id.library_hide_stats);
cardStats = root.findViewById(R.id.library_storage_stats_card);
viewStatsDistribution = root.findViewById(R.id.library_storage_stat_distribution);
viewVideoStatsBar = root.findViewById(R.id.library_storage_stat_video_bar);
viewAudioStatsBar = root.findViewById(R.id.library_storage_stat_audio_bar);
viewImageStatsBar = root.findViewById(R.id.library_storage_stat_image_bar);
viewOtherStatsBar = root.findViewById(R.id.library_storage_stat_other_bar);
textStatsTotalSize = root.findViewById(R.id.library_storage_stat_used);
textStatsTotalSizeUnits = root.findViewById(R.id.library_storage_stat_unit);
textStatsVideoSize = root.findViewById(R.id.library_storage_stat_video_size);
textStatsAudioSize = root.findViewById(R.id.library_storage_stat_audio_size);
textStatsImageSize = root.findViewById(R.id.library_storage_stat_image_size);
textStatsOtherSize = root.findViewById(R.id.library_storage_stat_other_size);
legendVideo = root.findViewById(R.id.library_storage_legend_video);
legendAudio = root.findViewById(R.id.library_storage_legend_audio);
legendImage = root.findViewById(R.id.library_storage_legend_image);
legendOther = root.findViewById(R.id.library_storage_legend_other);
linkStats.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
updateStats();
cardStats.setVisibility(View.VISIBLE);
checkStatsLink();
}
});
linkHide.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
cardStats.setVisibility(View.GONE);
checkStatsLink();
}
});
return root;
}
public void onResume() {
super.onResume();
Context context = getContext();
Helper.setWunderbarValue(null, context);
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
LbryAnalytics.setCurrentScreen(activity, "Library", "Library");
activity.addDownloadActionListener(this);
}
layoutSdkInitializing.setVisibility(
!Lbry.SDK_READY && currentFilter == FILTER_DOWNLOADS ? View.VISIBLE : View.GONE);
if (!Lbry.SDK_READY) {
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.addSdkStatusListener(this);
}
} else {
onSdkReady();
}
}
public void onPause() {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.removeSdkStatusListener(this);
activity.removeDownloadActionListener(this);
}
super.onPause();
}
public void onSdkReady() {
layoutSdkInitializing.setVisibility(View.GONE);
if (currentFilter == FILTER_DOWNLOADS) {
showDownloads();
} else if (currentFilter == FILTER_HISTORY) {
showHistory();
} else if (currentFilter == FILTER_PURCHASES) {
showPurchases();
}
}
private void showDownloads() {
currentFilter = FILTER_DOWNLOADS;
linkFilterDownloads.setTypeface(null, Typeface.BOLD);
linkFilterPurchases.setTypeface(null, Typeface.NORMAL);
linkFilterHistory.setTypeface(null, Typeface.NORMAL);
if (contentListAdapter != null) {
contentListAdapter.setHideFee(false);
contentListAdapter.clearItems();
contentListAdapter.setCanEnterSelectionMode(true);
}
listReachedEnd = false;
checkStatsLink();
layoutSdkInitializing.setVisibility(Lbry.SDK_READY ? View.GONE : View.VISIBLE);
currentPage = 1;
currentFiles = new ArrayList<>();
if (Lbry.SDK_READY) {
if (!initialOwnClaimsFetched) {
fetchOwnClaimsAndShowDownloads();
} else {
fetchDownloads();
}
}
}
private void fetchOwnClaimsAndShowDownloads() {
if (Lbry.ownClaims != null && Lbry.ownClaims.size() > 0) {
initialOwnClaimsFetched = true;
fetchDownloads();
return;
}
linkStats.setVisibility(View.INVISIBLE);
ClaimListTask task = new ClaimListTask(Arrays.asList(Claim.TYPE_STREAM, Claim.TYPE_REPOST), listLoading, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownClaims = Helper.filterDeletedClaims(new ArrayList<>(claims));
initialOwnClaimsFetched = true;
if (currentFilter == FILTER_DOWNLOADS) {
fetchDownloads();
}
checkStatsLink();
}
@Override
public void onError(Exception error) {
initialOwnClaimsFetched = true;
checkStatsLink();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void showPurchases() {
currentFilter = FILTER_PURCHASES;
linkFilterDownloads.setTypeface(null, Typeface.NORMAL);
linkFilterPurchases.setTypeface(null, Typeface.BOLD);
linkFilterHistory.setTypeface(null, Typeface.NORMAL);
if (contentListAdapter != null) {
contentListAdapter.setHideFee(true);
contentListAdapter.clearItems();
contentListAdapter.setCanEnterSelectionMode(false);
}
listReachedEnd = false;
cardStats.setVisibility(View.GONE);
checkStatsLink();
layoutSdkInitializing.setVisibility(Lbry.SDK_READY ? View.GONE : View.VISIBLE);
currentPage = 1;
if (Lbry.SDK_READY) {
fetchPurchases();
}
}
private void showHistory() {
currentFilter = FILTER_HISTORY;
linkFilterDownloads.setTypeface(null, Typeface.NORMAL);
linkFilterPurchases.setTypeface(null, Typeface.NORMAL);
linkFilterHistory.setTypeface(null, Typeface.BOLD);
if (actionMode != null) {
actionMode.finish();
}
if (contentListAdapter != null) {
contentListAdapter.setHideFee(false);
contentListAdapter.clearItems();
contentListAdapter.setCanEnterSelectionMode(false);
}
listReachedEnd = false;
cardStats.setVisibility(View.GONE);
checkStatsLink();
layoutSdkInitializing.setVisibility(View.GONE);
lastDate = null;
fetchHistory();
}
private void initContentListAdapter(List<Claim> claims) {
Context context = getContext();
if (context != null) {
contentListAdapter = new ClaimListAdapter(claims, context);
contentListAdapter.setCanEnterSelectionMode(currentFilter == FILTER_DOWNLOADS);
contentListAdapter.setSelectionModeListener(this);
contentListAdapter.setHideFee(currentFilter != FILTER_PURCHASES);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
activity.openChannelUrl(claim.getPermanentUrl());
} else {
activity.openFileUrl(claim.getPermanentUrl());
}
}
}
});
}
}
private void fetchDownloads() {
contentListLoading = true;
Helper.setViewVisibility(linkStats, View.GONE);
Helper.setViewVisibility(layoutListEmpty, View.GONE);
FileListTask task = new FileListTask(currentPage, PAGE_SIZE, true, listLoading, new FileListTask.FileListResultHandler() {
@Override
public void onSuccess(List<LbryFile> files, boolean hasReachedEnd) {
listReachedEnd = hasReachedEnd;
List<LbryFile> filteredFiles = Helper.filterDownloads(files);
List<Claim> claims = Helper.claimsFromFiles(filteredFiles);
addFiles(filteredFiles);
updateStats();
checkStatsLink();
if (contentListAdapter == null) {
initContentListAdapter(claims);
} else {
contentListAdapter.addItems(claims);
}
if (contentListAdapter != null && contentList.getAdapter() == null) {
contentList.setAdapter(contentListAdapter);
}
resolveMissingChannelNames(buildUrlsToResolve(claims));
checkListEmpty();
contentListLoading = false;
}
@Override
public void onError(Exception error) {
// pass
checkStatsLink();
checkListEmpty();
contentListLoading = false;
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void fetchPurchases() {
contentListLoading = true;
Helper.setViewVisibility(linkStats, View.GONE);
Helper.setViewVisibility(layoutListEmpty, View.GONE);
PurchaseListTask task = new PurchaseListTask(currentPage, PAGE_SIZE, listLoading, new ClaimSearchResultHandler() {
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
listReachedEnd = hasReachedEnd;
if (contentListAdapter == null) {
initContentListAdapter(claims);
} else {
contentListAdapter.addItems(claims);
}
if (contentListAdapter != null && contentList.getAdapter() == null) {
contentList.setAdapter(contentListAdapter);
}
checkListEmpty();
contentListLoading = false;
}
@Override
public void onError(Exception error) {
checkStatsLink();
checkListEmpty();
contentListLoading = false;
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void fetchHistory() {
contentListLoading = true;
Helper.setViewVisibility(layoutListEmpty, View.GONE);
DatabaseHelper dbHelper = DatabaseHelper.getInstance();
if (dbHelper != null) {
FetchViewHistoryTask task = new FetchViewHistoryTask(lastDate, PAGE_SIZE, dbHelper, new FetchViewHistoryTask.FetchViewHistoryHandler() {
@Override
public void onSuccess(List<ViewHistory> history, boolean hasReachedEnd) {
listReachedEnd = hasReachedEnd;
if (history.size() > 0) {
lastDate = history.get(history.size() - 1).getTimestamp();
}
List<Claim> claims = Helper.claimsFromViewHistory(history);
if (contentListAdapter == null) {
initContentListAdapter(claims);
} else {
contentListAdapter.addItems(claims);
}
if (contentListAdapter != null && contentList.getAdapter() == null) {
contentList.setAdapter(contentListAdapter);
}
checkListEmpty();
contentListLoading = false;
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
checkListEmpty();
contentListLoading = false;
}
}
public void onDownloadAction(String downloadAction, String uri, String outpoint, String fileInfoJson, double progress) {
if ("abort".equals(downloadAction)) {
if (contentListAdapter != null) {
contentListAdapter.clearFileForClaimOrUrl(outpoint, uri, currentFilter == FILTER_DOWNLOADS);
}
return;
}
try {
JSONObject fileInfo = new JSONObject(fileInfoJson);
LbryFile claimFile = LbryFile.fromJSONObject(fileInfo);
String claimId = claimFile.getClaimId();
if (contentListAdapter != null) {
contentListAdapter.updateFileForClaimByIdOrUrl(claimFile, claimId, uri, true);
}
} catch (JSONException ex) {
// invalid file info for download
}
}
private void checkListEmpty() {
layoutListEmpty.setVisibility(contentListAdapter == null || contentListAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
int stringResourceId;
switch (currentFilter) {
case FILTER_DOWNLOADS: default: stringResourceId = R.string.library_no_downloads; break;
case FILTER_HISTORY: stringResourceId = R.string.library_no_history; break;
case FILTER_PURCHASES: stringResourceId = R.string.library_no_purchases; break;
}
textListEmpty.setText(stringResourceId);
}
private void addFiles(List<LbryFile> files) {
if (currentFiles == null) {
currentFiles = new ArrayList<>();
}
for (LbryFile file : files) {
if (!currentFiles.contains(file)) {
currentFiles.add(file);
}
}
}
private void updateStats() {
totalBytes = 0;
totalVideoBytes = 0;
totalAudioBytes = 0;
totalImageBytes = 0;
totalOtherBytes = 0;
if (currentFiles != null) {
for (LbryFile file : currentFiles) {
long writtenBytes = file.getWrittenBytes();
String mime = file.getMimeType();
if (mime != null) {
if (mime.startsWith("video/")) {
totalVideoBytes += writtenBytes;
} else if (mime.startsWith("audio/")) {
totalAudioBytes += writtenBytes;
} else if (mime.startsWith("image/")) {
totalImageBytes += writtenBytes;
} else {
totalOtherBytes += writtenBytes;
}
}
totalBytes += writtenBytes;
}
}
renderStats();
}
private void renderStats() {
String[] totalSizeParts = Helper.formatBytesParts(totalBytes, false);
textStatsTotalSize.setText(totalSizeParts[0]);
textStatsTotalSizeUnits.setText(totalSizeParts[1]);
viewStatsDistribution.setVisibility(totalBytes > 0 ? View.VISIBLE : View.GONE);
int percentVideo = normalizePercent((double) totalVideoBytes / (double) totalBytes * 100.0);
legendVideo.setVisibility(totalVideoBytes > 0 ? View.VISIBLE : View.GONE);
textStatsVideoSize.setText(Helper.formatBytes(totalVideoBytes, false));
applyLayoutWeight(viewVideoStatsBar, percentVideo);
int percentAudio = normalizePercent((double) totalAudioBytes / (double) totalBytes * 100.0);
legendAudio.setVisibility(totalAudioBytes > 0 ? View.VISIBLE : View.GONE);
textStatsAudioSize.setText(Helper.formatBytes(totalAudioBytes, false));
applyLayoutWeight(viewAudioStatsBar, percentAudio);
int percentImage = normalizePercent((double) totalImageBytes / (double) totalBytes * 100.0);
legendImage.setVisibility(totalImageBytes > 0 ? View.VISIBLE : View.GONE);
textStatsImageSize.setText(Helper.formatBytes(totalImageBytes, false));
applyLayoutWeight(viewImageStatsBar, percentImage);
int percentOther = normalizePercent((double) totalOtherBytes / (double) totalBytes * 100.0);
legendOther.setVisibility(totalOtherBytes > 0 ? View.VISIBLE : View.GONE);
textStatsOtherSize.setText(Helper.formatBytes(totalOtherBytes, false));
applyLayoutWeight(viewOtherStatsBar, percentOther);
// We have to get to 100 (or adjust the container accordingly)
int totalPercent = percentVideo + percentAudio + percentImage + percentOther;
((LinearLayout) viewStatsDistribution).setWeightSum(totalPercent);
}
private void applyLayoutWeight(View view, int weight) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
params.weight = weight;
}
private static int normalizePercent(double value) {
if (value > 0 && value < 1) {
return 1;
}
return Double.valueOf(Math.floor(value)).intValue();
}
private void checkStatsLink() {
linkStats.setVisibility(cardStats.getVisibility() == View.VISIBLE ||
listLoading.getVisibility() == View.VISIBLE ||
currentFilter != FILTER_DOWNLOADS ||
!Lbry.SDK_READY ?
View.GONE : View.VISIBLE);
}
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
this.actionMode = actionMode;
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (!activity.isDarkMode()) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
actionMode.getMenuInflater().inflate(R.menu.menu_claim_list, menu);
return true;
}
@Override
public void onDestroyActionMode(ActionMode actionMode) {
if (contentListAdapter != null) {
contentListAdapter.clearSelectedItems();
contentListAdapter.setInSelectionMode(false);
contentListAdapter.notifyDataSetChanged();
}
Context context = getContext();
if (context != null) {
MainActivity activity = (MainActivity) context;
if (!activity.isDarkMode()) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
}
this.actionMode = null;
}
@Override
public boolean onPrepareActionMode(androidx.appcompat.view.ActionMode actionMode, Menu menu) {
menu.findItem(R.id.action_edit).setVisible(false);
return true;
}
@Override
public boolean onActionItemClicked(androidx.appcompat.view.ActionMode actionMode, MenuItem menuItem) {
if (R.id.action_delete == menuItem.getItemId()) {
if (contentListAdapter != null && contentListAdapter.getSelectedCount() > 0) {
Context context = getContext();
if (context != null) {
final List<Claim> selectedClaims = new ArrayList<>(contentListAdapter.getSelectedItems());
String message = getResources().getQuantityString(R.plurals.confirm_delete_files, selectedClaims.size());
AlertDialog.Builder builder = new AlertDialog.Builder(context).
setTitle(R.string.delete_selection).
setMessage(message)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
handleDeleteSelectedClaims(selectedClaims);
}
}).setNegativeButton(R.string.no, null);
builder.show();
}
return true;
}
}
return false;
}
private void handleDeleteSelectedClaims(List<Claim> selectedClaims) {
List<String> claimIds = new ArrayList<>();
for (Claim claim : selectedClaims) {
claimIds.add(claim.getClaimId());
}
new BulkDeleteFilesTask(claimIds).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
Lbry.unsetFilesForCachedClaims(claimIds);
if (currentFilter == FILTER_DOWNLOADS) {
contentListAdapter.removeItems(selectedClaims);
}
if (actionMode != null) {
actionMode.finish();
}
View root = getView();
if (root != null) {
String message = getResources().getQuantityString(R.plurals.files_deleted, claimIds.size());
Snackbar.make(root, message, Snackbar.LENGTH_LONG).show();
}
}
private List<String> buildUrlsToResolve(List<Claim> claims) {
List<String> urls = new ArrayList<>();
for (Claim claim : claims) {
Claim channel = claim.getSigningChannel();
if (channel != null && Helper.isNullOrEmpty(channel.getName()) && !Helper.isNullOrEmpty(channel.getClaimId())) {
LbryUri uri = LbryUri.tryParse(String.format("%s#%s", claim.getName(), claim.getClaimId()));
if (uri != null) {
urls.add(uri.toString());
}
}
}
return urls;
}
private void resolveMissingChannelNames(List<String> urls) {
if (urls.size() > 0) {
ResolveTask task = new ResolveTask(urls, Lbry.SDK_CONNECTION_STRING, null, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
boolean updated = false;
for (Claim claim : claims) {
if (claim.getClaimId() == null) {
continue;
}
if (contentListAdapter != null) {
contentListAdapter.updateSigningChannelForClaim(claim);
updated = true;
}
}
if (updated) {
contentListAdapter.notifyDataSetChanged();
}
}
@Override
public void onError(Exception error) {
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
public void onEnterSelectionMode() {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.startSupportActionMode(this);
}
}
public void onItemSelectionToggled() {
if (actionMode != null) {
actionMode.setTitle(String.valueOf(contentListAdapter.getSelectedCount()));
actionMode.invalidate();
}
}
public void onExitSelectionMode() {
if (actionMode != null) {
actionMode.finish();
}
}
}
@@ -180,10 +180,7 @@ public class AboutFragment extends BaseFragment implements SdkStatusListener {
activity.lockDrawer();
activity.hideFloatingWalletBalance();
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.about_lbry);
}
activity.setActionBarTitle(R.string.about_lbry);
}
}
@@ -193,7 +190,7 @@ public class AboutFragment extends BaseFragment implements SdkStatusListener {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
LbryAnalytics.setCurrentScreen(activity, "Settings", "Settings");
LbryAnalytics.setCurrentScreen(activity, "About", "About");
if (!Lbry.SDK_READY) {
activity.addSdkStatusListener(this);
@@ -2,6 +2,7 @@ package io.lbry.browser.ui.other;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.app.ActionBar;
@@ -9,9 +10,14 @@ import androidx.appcompat.app.AppCompatDelegate;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
import java.io.FileOutputStream;
import java.io.PrintStream;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.lbrysdk.Utils;
public class SettingsFragment extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
@@ -29,10 +35,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
activity.lockDrawer();
activity.hideFloatingWalletBalance();
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.settings);
}
activity.setActionBarTitle(R.string.settings);
}
}
@@ -40,15 +43,18 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
public void onResume() {
super.onResume();
Context context = getContext();
PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);
if (context instanceof MainActivity) {
PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(this);
MainActivity activity = (MainActivity) context;
LbryAnalytics.setCurrentScreen(activity, "Settings", "Settings");
}
}
@Override
public void onPause() {
PreferenceManager.getDefaultSharedPreferences(getContext()).unregisterOnSharedPreferenceChangeListener(this);
Context context = getContext();
if (context != null) {
PreferenceManager.getDefaultSharedPreferences(context).unregisterOnSharedPreferenceChangeListener(this);
}
super.onPause();
}
@Override
@@ -66,13 +72,29 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
if (key.equalsIgnoreCase(MainActivity.PREFERENCE_KEY_DARK_MODE)) {
boolean darkMode = sp.getBoolean(MainActivity.PREFERENCE_KEY_DARK_MODE, false);
AppCompatDelegate.setDefaultNightMode(darkMode ? AppCompatDelegate.MODE_NIGHT_YES : AppCompatDelegate.MODE_NIGHT_NO);
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.getDelegate().applyDayNight();
activity.recreate();
}
} else if (key.equalsIgnoreCase(MainActivity.PREFERENCE_KEY_PARTICIPATE_DATA_NETWORK)) {
boolean dhtEnabled = sp.getBoolean(MainActivity.PREFERENCE_KEY_PARTICIPATE_DATA_NETWORK, false);
updateDHTFileSetting(dhtEnabled);
}
}
private void updateDHTFileSetting(final boolean enabled) {
Context context = getContext();
(new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
PrintStream out = null;
try {
String fileContent = enabled ? "on" : "off";
String path = String.format("%s/%s", Utils.getAppInternalStorageDir(context), "dht");
out = new PrintStream(new FileOutputStream(path));
out.print(fileContent);
} catch (Exception ex) {
// pass
} finally {
Helper.closeCloseable(out);
}
return null;
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,448 @@
package io.lbry.browser.ui.publish;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.CameraX;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.snackbar.Snackbar;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.GalleryGridAdapter;
import io.lbry.browser.listener.CameraPermissionListener;
import io.lbry.browser.listener.FilePickerListener;
import io.lbry.browser.listener.StoragePermissionListener;
import io.lbry.browser.model.GalleryItem;
import io.lbry.browser.model.NavMenuItem;
import io.lbry.browser.tasks.localdata.LoadGalleryItemsTask;
import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
public class PublishFragment extends BaseFragment implements
CameraPermissionListener, FilePickerListener, StoragePermissionListener {
private boolean cameraPreviewInitialized;
private boolean storagePermissionRefusedOnce;
private PreviewView cameraPreview;
private RecyclerView galleryGrid;
private GalleryGridAdapter adapter;
private TextView noVideosLoaded;
private View loading;
private View buttonRecord;
private View buttonTakePhoto;
private View buttonUpload;
private boolean loadGalleryItemsPending;
private boolean launchFilePickerPending;
private boolean recordPending;
private boolean takePhotoPending;
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_publish, container, false);
noVideosLoaded = root.findViewById(R.id.publish_grid_no_videos);
loading = root.findViewById(R.id.publish_grid_loading);
cameraPreview = root.findViewById(R.id.publish_camera_preview);
Context context = getContext();
galleryGrid = root.findViewById(R.id.publish_video_grid);
GridLayoutManager glm = new GridLayoutManager(context, 3);
galleryGrid.setLayoutManager(glm);
galleryGrid.addItemDecoration(new GalleryGridAdapter.GalleryGridItemDecoration(
3, Helper.getScaledValue(3, context.getResources().getDisplayMetrics().density)));
buttonRecord = root.findViewById(R.id.publish_record_button);
buttonTakePhoto = root.findViewById(R.id.publish_photo_button);
buttonUpload = root.findViewById(R.id.publish_upload_button);
buttonRecord.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkCameraPermissionAndRecord();
}
});
buttonTakePhoto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkCameraPermissionAndTakePhoto();
}
});
buttonUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
checkStoragePermissionAndLaunchFilePicker();
}
});
return root;
}
private boolean cameraAvailable() {
Context context = getContext();
return context != null && context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY);
}
private void showCameraPreview() {
buttonRecord.setBackgroundColor(Color.TRANSPARENT);
buttonTakePhoto.setBackgroundColor(Color.TRANSPARENT);
displayPreviewWithCameraX();
}
private void displayPreviewWithCameraX() {
Context context = getContext();
if (context != null && MainActivity.hasPermission(Manifest.permission.CAMERA, context)) {
cameraProviderFuture = ProcessCameraProvider.getInstance(context);
cameraProviderFuture.addListener(new Runnable() {
@Override
public void run() {
try {
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
if (cameraProvider != null) {
Preview preview = new Preview.Builder().build();
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, preview);
preview.setSurfaceProvider(cameraPreview.createSurfaceProvider(camera.getCameraInfo()));
cameraPreviewInitialized = true;
}
} catch (ExecutionException | IllegalArgumentException | InterruptedException ex) {
// pass
}
}
}, ContextCompat.getMainExecutor(context));
}
}
private void checkCameraPermissionAndRecord() {
if (!Lbry.SDK_READY) {
Snackbar.make(getView(), R.string.sdk_initializing_functionality, Snackbar.LENGTH_LONG).show();
return;
}
Context context = getContext();
if (!MainActivity.hasPermission(Manifest.permission.CAMERA, context)) {
recordPending = true;
MainActivity.requestPermission(
Manifest.permission.CAMERA,
MainActivity.REQUEST_CAMERA_PERMISSION,
getString(R.string.camera_permission_rationale_record),
context,
true);
} else {
record();
}
}
private void checkCameraPermissionAndTakePhoto() {
if (!Lbry.SDK_READY) {
Snackbar.make(getView(), R.string.sdk_initializing_functionality, Snackbar.LENGTH_LONG).show();
return;
}
Context context = getContext();
if (!MainActivity.hasPermission(Manifest.permission.CAMERA, context)) {
takePhotoPending = true;
MainActivity.requestPermission(
Manifest.permission.CAMERA,
MainActivity.REQUEST_CAMERA_PERMISSION,
getString(R.string.camera_permission_rationale_photo),
context,
true);
} else {
takePhoto();
}
}
private void takePhoto() {
Context context = getContext();
if (context instanceof MainActivity) {
takePhotoPending = false;
((MainActivity) context).requestTakePhoto();
}
}
private void record() {
Context context = getContext();
if (context instanceof MainActivity) {
recordPending = false;
((MainActivity) context).requestVideoCapture();
}
}
private void checkStoragePermissionAndLaunchFilePicker() {
if (!Lbry.SDK_READY) {
Snackbar.make(getView(), R.string.sdk_initializing_functionality, Snackbar.LENGTH_LONG).show();
return;
}
Context context = getContext();
if (MainActivity.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, context)) {
launchFilePickerPending = false;
launchFilePicker();
} else {
launchFilePickerPending = true;
MainActivity.requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
MainActivity.REQUEST_STORAGE_PERMISSION,
getString(R.string.storage_permission_rationale_images),
context,
true);
}
}
private void launchFilePicker() {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity.startingFilePickerActivity = true;
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.setType("*/*");
((MainActivity) context).startActivityForResult(
Intent.createChooser(intent, getString(R.string.upload_file)),
MainActivity.REQUEST_FILE_PICKER);
}
}
public void onResume() {
super.onResume();
Context context = getContext();
Helper.setWunderbarValue(null, context);
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
LbryAnalytics.setCurrentScreen(activity, "Publish", "Publish");
activity.addCameraPermissionListener(this);
activity.addFilePickerListener(this);
activity.addStoragePermissionListener(this);
activity.hideFloatingWalletBalance();
if (cameraAvailable() && MainActivity.hasPermission(Manifest.permission.CAMERA, context)) {
showCameraPreview();
}
}
if (!storagePermissionRefusedOnce) {
checkStoragePermissionAndLoadVideos();
}
}
@SuppressLint("RestrictedApi")
public void onStop() {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.removeCameraPermissionListener(this);
activity.removeStoragePermissionListener(this);
activity.showFloatingWalletBalance();
if (!MainActivity.startingFilePickerActivity) {
activity.removeFilePickerListener(this);
}
}
if (cameraPreviewInitialized) {
CameraX.unbindAll();
}
super.onStop();
}
private void checkStoragePermissionAndLoadVideos() {
Context context = getContext();
if (MainActivity.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, context)) {
loadGalleryItems();
} else {
loadGalleryItemsPending = true;
MainActivity.requestPermission(
Manifest.permission.WRITE_EXTERNAL_STORAGE,
MainActivity.REQUEST_STORAGE_PERMISSION,
getString(R.string.storage_permission_rationale_download),
context,
true);
}
}
private void loadGalleryItems() {
Context context = getContext();
Helper.setViewVisibility(noVideosLoaded, View.GONE);
LoadGalleryItemsTask task = new LoadGalleryItemsTask(loading, context, new LoadGalleryItemsTask.LoadGalleryHandler() {
@Override
public void onItemLoaded(GalleryItem item) {
if (context != null) {
if (adapter == null) {
adapter = new GalleryGridAdapter(Arrays.asList(item), context);
adapter.setListener(new GalleryGridAdapter.GalleryItemClickListener() {
@Override
public void onGalleryItemClicked(GalleryItem item) {
if (!Lbry.SDK_READY) {
Snackbar.make(getView(), R.string.sdk_initializing_functionality, Snackbar.LENGTH_LONG).show();
return;
}
Context context = getContext();
if (context instanceof MainActivity) {
Map<String, Object> params = new HashMap<>();
params.put("galleryItem", item);
params.put("suggestedUrl", getSuggestedPublishUrl());
((MainActivity) context).openFragment(PublishFormFragment.class, true, NavMenuItem.ID_ITEM_NEW_PUBLISH, params);
}
}
});
} else {
adapter.addItem(item);
}
if (galleryGrid.getAdapter() == null) {
galleryGrid.setAdapter(adapter);
}
Helper.setViewVisibility(loading, adapter == null || adapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
}
@Override
public void onAllItemsLoaded(List<GalleryItem> items) {
if (context != null) {
if (adapter == null) {
adapter = new GalleryGridAdapter(items, context);
} else {
adapter.addItems(items);
}
if (galleryGrid.getAdapter() == null) {
galleryGrid.setAdapter(adapter);
}
}
checkNoVideosLoaded();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void checkNoVideosLoaded() {
Helper.setViewVisibility(noVideosLoaded, adapter == null || adapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
@Override
public void onCameraPermissionGranted() {
if (recordPending) {
// record video
record();
} else if (takePhotoPending) {
// take a photo
takePhoto();
}
}
@Override
public void onCameraPermissionRefused() {
if (takePhotoPending) {
takePhotoPending = false;
Snackbar.make(getView(), R.string.camera_permission_rationale_photo, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
return;
}
recordPending = false;
Snackbar.make(getView(), R.string.camera_permission_rationale_record, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
@Override
public void onRecordAudioPermissionGranted() {
}
@Override
public void onRecordAudioPermissionRefused() {
}
@Override
public void onStoragePermissionGranted() {
if (loadGalleryItemsPending) {
loadGalleryItemsPending = false;
loadGalleryItems();
}
if (launchFilePickerPending) {
launchFilePickerPending = false;
launchFilePicker();
}
}
@Override
public void onStoragePermissionRefused() {
storagePermissionRefusedOnce = true;
View root = getView();
if (root != null) {
Snackbar.make(root, R.string.storage_permission_rationale_videos, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
Helper.setViewText(noVideosLoaded, R.string.storage_permission_rationale_videos);
}
checkNoVideosLoaded();
}
public String getSuggestedPublishUrl() {
Map<String, Object> params = getParams();
if (params != null && params.containsKey("suggestedUrl")) {
return (String) params.get("suggestedUrl");
}
return null;
}
@Override
public boolean shouldHideGlobalPlayer() {
return true;
}
@Override
public boolean shouldSuspendGlobalPlayer() {
return true;
}
@Override
public void onFilePicked(String filePath) {
Context context = getContext();
if (context instanceof MainActivity) {
Map<String, Object> params = new HashMap<>();
params.put("directFilePath", filePath);
params.put("suggestedUrl", getSuggestedPublishUrl());
((MainActivity) context).openFragment(PublishFormFragment.class, true, NavMenuItem.ID_ITEM_NEW_PUBLISH, params);
}
}
@Override
public void onFilePickerCancelled() {
}
}
@@ -0,0 +1,329 @@
package io.lbry.browser.ui.publish;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.view.ActionMode;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.ClaimListAdapter;
import io.lbry.browser.listener.SdkStatusListener;
import io.lbry.browser.listener.SelectionModeListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.NavMenuItem;
import io.lbry.browser.tasks.claim.AbandonHandler;
import io.lbry.browser.tasks.claim.AbandonStreamTask;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
public class PublishesFragment extends BaseFragment implements ActionMode.Callback, SelectionModeListener, SdkStatusListener {
private Button buttonNewPublish;
private FloatingActionButton fabNewPublish;
private ActionMode actionMode;
private View emptyView;
private View layoutSdkInitializing;
private ProgressBar loading;
private ProgressBar bigLoading;
private RecyclerView contentList;
private ClaimListAdapter adapter;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_publishes, container, false);
buttonNewPublish = root.findViewById(R.id.publishes_create_button);
fabNewPublish = root.findViewById(R.id.publishes_fab_new_publish);
buttonNewPublish.setOnClickListener(newPublishClickListener);
fabNewPublish.setOnClickListener(newPublishClickListener);
emptyView = root.findViewById(R.id.publishes_empty_container);
layoutSdkInitializing = root.findViewById(R.id.container_sdk_initializing);
contentList = root.findViewById(R.id.publishes_list);
LinearLayoutManager llm = new LinearLayoutManager(getContext());
contentList.setLayoutManager(llm);
loading = root.findViewById(R.id.publishes_list_loading);
bigLoading = root.findViewById(R.id.publishes_list_big_loading);
layoutSdkInitializing.setVisibility(Lbry.SDK_READY ? View.GONE : View.VISIBLE);
return root;
}
private View.OnClickListener newPublishClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).openFragment(PublishFragment.class, true, NavMenuItem.ID_ITEM_NEW_PUBLISH);
}
}
};
@Override
public void onStart() {
super.onStart();
Context context = getContext();
if (context != null) {
MainActivity activity = (MainActivity) context;
activity.hideFloatingWalletBalance();
}
}
@Override
public void onStop() {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.showFloatingWalletBalance();
}
super.onStop();
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.setWunderbarValue(null);
LbryAnalytics.setCurrentScreen(activity, "Publishes", "Publishes");
}
if (!Lbry.SDK_READY) {
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.addSdkStatusListener(this);
}
} else {
onSdkReady();
}
}
public void onSdkReady() {
Helper.setViewVisibility(layoutSdkInitializing, View.GONE);
Helper.setViewVisibility(fabNewPublish, View.VISIBLE);
if (adapter != null && contentList != null) {
contentList.setAdapter(adapter);
}
fetchPublishes();
}
public View getLoading() {
return (adapter == null || adapter.getItemCount() == 0) ? bigLoading : loading;
}
private void checkNoPublishes() {
Helper.setViewVisibility(emptyView, adapter == null || adapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
private void fetchPublishes() {
Helper.setViewVisibility(emptyView, View.GONE);
ClaimListTask task = new ClaimListTask(Arrays.asList(Claim.TYPE_STREAM, Claim.TYPE_REPOST), getLoading(), new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownClaims = Helper.filterDeletedClaims(new ArrayList<>(claims));
if (adapter == null) {
Context context = getContext();
if (context != null) {
adapter = new ClaimListAdapter(claims, context);
adapter.setCanEnterSelectionMode(true);
adapter.setSelectionModeListener(PublishesFragment.this);
adapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
}
}
});
if (contentList != null) {
contentList.setAdapter(adapter);
}
}
} else {
adapter.setItems(claims);
}
checkNoPublishes();
}
@Override
public void onError(Exception error) {
checkNoPublishes();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void onEnterSelectionMode() {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.startSupportActionMode(this);
}
}
public void onItemSelectionToggled() {
if (actionMode != null) {
actionMode.setTitle(String.valueOf(adapter.getSelectedCount()));
actionMode.invalidate();
}
}
public void onExitSelectionMode() {
if (actionMode != null) {
actionMode.finish();
}
}
@Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
this.actionMode = actionMode;
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (!activity.isDarkMode()) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
}
}
actionMode.getMenuInflater().inflate(R.menu.menu_claim_list, menu);
return true;
}
@Override
public void onDestroyActionMode(ActionMode actionMode) {
if (adapter != null) {
adapter.clearSelectedItems();
adapter.setInSelectionMode(false);
adapter.notifyDataSetChanged();
}
Context context = getContext();
if (context != null) {
MainActivity activity = (MainActivity) context;
if (!activity.isDarkMode()) {
activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
}
this.actionMode = null;
}
@Override
public boolean onPrepareActionMode(androidx.appcompat.view.ActionMode actionMode, Menu menu) {
int selectionCount = adapter != null ? adapter.getSelectedCount() : 0;
menu.findItem(R.id.action_edit).setVisible(selectionCount == 1 &&
Claim.TYPE_STREAM.equalsIgnoreCase(adapter.getSelectedItems().get(0).getValueType()));
return true;
}
@Override
public boolean onActionItemClicked(androidx.appcompat.view.ActionMode actionMode, MenuItem menuItem) {
if (R.id.action_edit == menuItem.getItemId()) {
if (adapter != null && adapter.getSelectedCount() > 0) {
Claim claim = adapter.getSelectedItems().get(0);
// start channel editor with the claim
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).openPublishForm(claim);
}
actionMode.finish();
return true;
}
}
if (R.id.action_delete == menuItem.getItemId()) {
if (adapter != null && adapter.getSelectedCount() > 0) {
final List<Claim> selectedClaims = new ArrayList<>(adapter.getSelectedItems());
String message = getResources().getQuantityString(R.plurals.confirm_delete_publishes, selectedClaims.size());
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()).
setTitle(R.string.delete_selection).
setMessage(message)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
handleDeleteSelectedClaims(selectedClaims);
}
}).setNegativeButton(R.string.no, null);
builder.show();
return true;
}
}
return false;
}
private void handleDeleteSelectedClaims(List<Claim> selectedClaims) {
List<String> claimIds = new ArrayList<>();
for (Claim claim : selectedClaims) {
claimIds.add(claim.getClaimId());
}
if (actionMode != null) {
actionMode.finish();
}
Helper.setViewVisibility(contentList, View.INVISIBLE);
Helper.setViewVisibility(fabNewPublish, View.INVISIBLE);
AbandonStreamTask task = new AbandonStreamTask(claimIds, bigLoading, new AbandonHandler() {
@Override
public void onComplete(List<String> successfulClaimIds, List<String> failedClaimIds, List<Exception> errors) {
View root = getView();
if (root != null) {
if (failedClaimIds.size() > 0) {
Snackbar.make(root, R.string.one_or_more_publishes_failed_abandon, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
} else if (successfulClaimIds.size() == claimIds.size()) {
try {
String message = getResources().getQuantityString(R.plurals.publishes_deleted, successfulClaimIds.size());
Snackbar.make(root, message, Snackbar.LENGTH_LONG).show();
} catch (IllegalStateException ex) {
// pass
}
}
}
Lbry.abandonedClaimIds.addAll(successfulClaimIds);
if (adapter != null) {
adapter.setItems(Helper.filterDeletedClaims(adapter.getItems()));
}
Helper.setViewVisibility(contentList, View.VISIBLE);
Helper.setViewVisibility(fabNewPublish, View.VISIBLE);
checkNoPublishes();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff. Show more