Compare commits

...
152 Commits
Author SHA1 Message Date
Akinwale Ariwodola 9aaa4db5f0 fix some events 2020-05-18 03:57:06 +01:00
Akinwale Ariwodola d4d58d7508 bumpversion 0.15.1 --> 0.15.2 2020-05-18 03:34:31 +01:00
Akinwale Ariwodola 5eb35e3283 Abandon channels and bulk delete files tasks. Some visual tweaks. 2020-05-18 03:29:30 +01:00
Akinwale Ariwodola a42442b13b Better handling of file view URLs. Some issue list fixes. 2020-05-17 20:52:38 +01:00
Akinwale Ariwodola f317aa2174 Make file view a fragment to prevent headaches with multiple Android task recents 2020-05-17 15:48:07 +01:00
Akinwale Ariwodola 82dc0255f1 bumpversion 0.15.0 --> 0.15.1 2020-05-15 20:07:53 +01:00
Akinwale Ariwodola 244d54ed39 Library page. URL and view history. 2020-05-15 20:07:05 +01:00
Akinwale Ariwodola 47f56950a5 url history and player fixes 2020-05-14 19:25:16 +01:00
Akinwale Ariwodola fb2b798106 change launch mode from singleInstance to singleTask 2020-05-14 13:33:27 +01:00
Akinwale Ariwodola 7cf97feb9e fix channel list adapters 2020-05-14 04:14:06 +01:00
Akinwale Ariwodola d1faaa9362 don't display invites history if none exist 2020-05-14 03:47:51 +01:00
Akinwale Ariwodola aad718c714 purchase_uri for free content 2020-05-14 03:43:08 +01:00
Akinwale Ariwodola 6bed7bfd2f display text and markdown content 2020-05-14 03:36:46 +01:00
Akinwale Ariwodola df4785fb5f tweak about page layout 2020-05-14 02:24:00 +01:00
Akinwale Ariwodola 9eb7177a15 tweak player loading and playback when loading new claims 2020-05-14 02:18:54 +01:00
Akinwale Ariwodola 103565d57c SDK 0.73.1. Finish file view experience. 2020-05-14 01:59:29 +01:00
Akinwale Ariwodola da4591fb2e remove debug log 2020-05-12 17:22:22 +01:00
Akinwale Ariwodola 6ac4a25715 sdk 0.72.0. Customize player view and controls. 2020-05-12 17:17:42 +01:00
Akinwale Ariwodola b4599ec7c5 add Invites page 2020-05-11 19:38:21 +01:00
Akinwale Ariwodola bc2e8b7ec0 phone number verification and rewards page 2020-05-10 23:11:48 +01:00
Akinwale Ariwodola 2df4d76927 Channel management and channel creation / editing 2020-05-07 19:06:59 +01:00
Akinwale Ariwodola f45c517048 Channel follow/unfollow fixes. Display stream cost. 2020-05-05 01:25:30 +01:00
Akinwale Ariwodola c78f669fb1 Handle lbry:// url scheme. Properly set URL bar values. SDK 0.71.0. 2020-05-03 22:39:04 +01:00
Akinwale Ariwodola 78dd587901 Send tip dialog. Channel page share and follow/unfollow. 2020-05-03 13:46:31 +01:00
Akinwale Ariwodola 8cb51f5c17 Search cache. File view updates. Floating wallet balance. 2020-05-02 17:41:23 +01:00
Akinwale Ariwodola f4b28c4d90 display no related content view when none loaded 2020-05-01 16:52:29 +01:00
Akinwale Ariwodola cfa7e07eba Editor's Choice. Reposts. Some ontent page tweaks. 2020-05-01 13:49:56 +01:00
Akinwale Ariwodola 5ceb081972 Wallet sync get and set preferences, update interval. 2020-05-01 04:44:40 +01:00
Akinwale Ariwodola 1d1c761d3f Finish Following and All Content views. Add customize your tags view. 2020-04-30 19:05:37 +01:00
Akinwale Ariwodola 59584c1be7 Fix first time wallet sync. add Discover dialog to Following page. 2020-04-29 01:35:51 +01:00
Akinwale Ariwodola 10175470de fix Gitlab CI script 2020-04-28 14:39:57 +01:00
Akinwale Ariwodola 2604baa221 add printVersionName gradle task 2020-04-28 14:34:50 +01:00
Akinwale Ariwodola 1adf073de6 update gitlab CI script 2020-04-28 14:31:03 +01:00
Akinwale Ariwodola cf052f9c80 initial native rewrite commit 2020-04-28 14:25:39 +01:00
Akinwale Ariwodola cc3055f1c9 bumpversion 0.14.1 --> 0.14.2 2020-03-31 21:32:35 +01:00
Akinwale Ariwodola 25a1eac43b sdk 0.67.1 2020-03-31 21:18:19 +01:00
Akinwale Ariwodola ff30e7f6a4 bumpversion 0.14.0 --> 0.14.1 2020-03-26 19:06:51 +01:00
Akinwale Ariwodola 3fcc01597d sdk 0.65.0 2020-03-26 19:03:47 +01:00
Akinwale Ariwodola cbc4a662e6 bumpversion 0.13.4 --> 0.14.0 2020-03-23 09:45:21 +01:00
Akinwale Ariwodola 5aa0513324 add getNativeBooleanSetting method 2020-03-21 09:18:48 +01:00
Akinwale Ariwodola 4d1f142f9c check sdk ready 2020-03-20 11:15:41 +01:00
Akinwale Ariwodola e9c8f9432f fix service notification not opening the app 2020-03-20 09:27:54 +01:00
Akinwale Ariwodola 56c375f344 lbry.tv hybrid mode (#869)
* lbry.tv experiment build
* add task for checking if the sdk is ready
* fix for special urls
* send onSdkStatusResponse events
* persist dht setting to file system
2020-03-20 08:30:34 +01:00
Akinwale Ariwodola 5b165a2339 remove dht debug logs 2020-03-17 23:10:10 +01:00
Akinwale Ariwodola bfd3c711ab 0.13.4 patch (#868)
* 0.13.4 patch
* update gitlab CI
2020-03-16 18:50:17 +01:00
Akinwale Ariwodola 4627e284fa sdk 0.64.0. check dht setting on startup. 2020-03-13 17:06:05 +01:00
Akinwale Ariwodola ea8ac783a8 bumpversion 0.13.2 --> 0.13.3 2020-03-13 08:32:09 +01:00
Akinwale Ariwodola 966dd2bf2c add log method to utility module 2020-03-13 02:03:39 +01:00
Akinwale Ariwodola 364de592fa use snake case for payload keys 2020-03-12 21:16:39 +01:00
Akinwale Ariwodola d38241f0d1 check for contentTitle and channelUrl in payload 2020-03-11 15:55:35 +01:00
Akinwale Ariwodola e217be6b67 Fast lite mode (native code) (#864)
* fast loading lite mode
* add react methods for lbrynet dir and platform
* send additional url parameters for cold start
* pending intent
* update gitlab CI
2020-03-11 15:21:41 +01:00
Akinwale Ariwodola 37f84f0399 versionCode for productFlavors 2020-03-03 16:48:22 +01:00
Akinwale Ariwodola b618b9fa2b sdk 0.62.0. update secret files. 2020-03-02 18:39:35 +01:00
Akinwale Ariwodola 37b893103d readme: lbrynet-daemon -> LBRY SDK 2020-03-02 16:45:23 +01:00
Akinwale Ariwodola e2d4852df7 include google-services.sample.json for test / debug builds 2020-03-02 16:41:10 +01:00
Akinwale Ariwodola 1e0298d73a update readme 2020-03-02 16:22:19 +01:00
Akinwale Ariwodola 64c13295d6 update release.sh for unsigned APKs 2020-03-01 21:37:57 +01:00
Akinwale Ariwodola 0261ece709 remove release signingConfig since we sign with jarsigner 2020-03-01 21:18:26 +01:00
Akinwale Ariwodola a5799347ad New build (#854)
* new project structure compatiable with Android Studio
2020-02-27 19:20:06 +01:00
Akinwale Ariwodola 6c7c4d1a88 app head: following page sign in message 2020-02-25 19:39:58 +01:00
Akinwale Ariwodola f5390316a7 app head: fix suggested subscriptions state handling 2020-02-25 19:35:54 +01:00
Akinwale Ariwodola da1ea77aa9 pass conf to get_loggly_handler 2020-02-25 08:34:50 +01:00
Akinwale Ariwodola 8ea48977ae sdk 0.61.0 2020-02-24 20:29:09 +01:00
Akinwale Ariwodola 6721db54e2 bumpversion 0.13.0 --> 0.13.1 2020-02-24 15:59:57 +01:00
Akinwale Ariwodola 6a7079c8b2 app head: basic repost redirect handling 2020-02-24 15:58:33 +01:00
Akinwale Ariwodola 8cc7e9d6c9 Following rework (#852)
* app head: following rework
* sdk 0.60.0. app head: following rework changes.
* app head: search and related content fixes
* app head: following rework updates
2020-02-24 15:21:13 +01:00
Akinwale Ariwodola d0ac41c242 app head: timing 2020-02-17 18:34:28 +01:00
Akinwale Ariwodola bc8f476ef1 Merge pull request #850 from lbryio/app-timing
app cold and warm start timing
2020-02-17 07:32:49 +01:00
Akinwale Ariwodola 2d01b63cfe app cold and warm start timing 2020-02-17 07:19:16 +01:00
Akinwale Ariwodola 88dc31e9af Merge pull request #832 from michaeltintiuc/fix-npm-install
Fix npm install
2020-02-07 16:26:05 +01:00
Thomas Zarebczan 8d1e5eb64d Merge pull request #834 from ykris45/patch-3
Update LICENSE
2020-02-03 17:04:42 -05:00
Akinwale Ariwodola 8113ef3f8a app head: fix splash screen stuck on authenticating 2020-02-03 09:21:22 +01:00
Akinwale Ariwodola a74ed0e93b bumpversion 0.12.3 --> 0.13.0 2020-02-03 07:28:28 +01:00
Akinwale Ariwodola 11f42bf71e app head: resolved search nsfw 2020-02-03 07:27:40 +01:00
YULIUS KURNIAWAN KRISTIANTO 8eb96025ec Update LICENSE 2020-02-03 04:38:17 +07:00
Akinwale Ariwodola 1ece7ff433 sdk 0.56.0 fixes 2020-01-31 19:43:49 +01:00
Michael Tintiuc e312c451f8 Fix npm install 2020-01-31 19:51:32 +02:00
Akinwale Ariwodola bb64e91648 sdk 0.56.0 2020-01-31 16:47:25 +01:00
Akinwale Ariwodola 69398f6a2c app head: search page fixes 2020-01-31 09:15:37 +01:00
Akinwale Ariwodola bef7aa0ae9 app head: Invites page 2020-01-29 12:26:57 +01:00
Akinwale Ariwodola 2776696501 app head: fix thumbnailUrl check 2020-01-23 02:16:12 +01:00
Akinwale Ariwodola fa075df278 app head: additional thumbnailUrl check 2020-01-23 00:56:11 +01:00
Akinwale Ariwodola 05311fd3a1 app head: fix additional channel creator edit error 2020-01-22 21:21:42 +01:00
Akinwale Ariwodola 79001239d9 app head: fix channel creator edit error 2020-01-22 18:40:19 +01:00
Akinwale Ariwodola e344733bf0 sdk 0.54.1 2020-01-22 15:04:44 +01:00
Akinwale Ariwodola 282fdbb903 app head: download confirmation dialog 2020-01-20 23:36:35 +01:00
Akinwale Ariwodola ee7c571101 download manager tweaks 2020-01-20 23:11:46 +01:00
Akinwale Ariwodola 87e42d6b7e app head: error on publish to existing content address 2020-01-20 21:53:57 +01:00
Akinwale Ariwodola 8fcf135280 add Stop action to download notifications 2020-01-20 21:42:25 +01:00
Akinwale Ariwodola ae9364ad7e add filter to only get active downloads on service startup 2020-01-20 18:55:02 +01:00
Akinwale Ariwodola 6aa44d8a9e tweak sdkCall params and sdk poll interval 2020-01-17 07:24:50 +01:00
Akinwale Ariwodola 3f013d1272 bumpversion 0.12.2 --> 0.12.3 2020-01-17 06:53:51 +01:00
Akinwale Ariwodola 94d1f5a4eb fix queued download file_list response handling 2020-01-17 06:44:43 +01:00
Akinwale Ariwodola 1d8a7d838b Merge pull request #818 from lbryio/sdk-0.53
sdk 0.53
2020-01-17 06:00:08 +01:00
Akinwale Ariwodola c5d441fa1f sdk 0.53.3 2020-01-17 05:59:04 +01:00
Akinwale Ariwodola 4276a78a81 sdk 0.53.2 service updates 2020-01-16 22:34:36 +01:00
Akinwale Ariwodola 36c24a448f Playable downloads (#817) 2020-01-16 22:05:22 +01:00
Akinwale Ariwodola 4bf1051549 app head: playable downloads update 2020-01-16 22:03:19 +01:00
Akinwale Ariwodola fc4ab3128c app headd: fix error on opening related content or urls 2020-01-14 02:30:35 +01:00
Akinwale Ariwodola 65d32ea13e app head: react navigation drawer workaround 2020-01-13 12:24:32 +01:00
Akinwale Ariwodola 4cd8c80226 optimise download manager update broadcasts 2020-01-13 12:05:02 +01:00
Akinwale Ariwodola 7adcdc43cf app head: remove calls to doCheckSubscriptionsInit 2020-01-10 23:41:47 +01:00
Akinwale Ariwodola 77852dc135 app head: style fixes 2020-01-10 00:38:25 +01:00
Akinwale Ariwodola 746ca62ca7 app head: fix claim result item channel render checks 2020-01-09 20:34:52 +01:00
Akinwale Ariwodola 5e993f0fcc spinner dropdown styling 2020-01-09 20:20:22 +01:00
Akinwale Ariwodola 168dbba62c app head: fullscreen media player restore tweak 2020-01-09 19:00:25 +01:00
Akinwale Ariwodola 4db7bf814c app head: latest changes 2020-01-09 18:18:41 +01:00
Akinwale Ariwodola 21a3ff318b update font files 2020-01-09 15:44:10 +01:00
Akinwale Ariwodola 116de67d4c app head: downgrade drawer navigator 2020-01-07 11:21:30 +01:00
Akinwale Ariwodola c6b8dfd539 app head: download and open file button fixes 2020-01-07 08:50:24 +01:00
Akinwale Ariwodola 37f33e9943 fix WebView package 2020-01-07 08:35:06 +01:00
Akinwale Ariwodola 4bae7fdf94 app head: fix tag search result 2020-01-06 23:02:06 +01:00
Akinwale Ariwodola c455bde154 app head: performance and fixes. disable hermes engine. 2020-01-06 21:55:59 +01:00
Akinwale Ariwodola 5aa4321787 app head: merge resolved search commits 2020-01-05 19:08:52 +01:00
Akinwale Ariwodola 27a2100c72 app head: resolved search updates 2020-01-05 18:12:49 +01:00
Akinwale Ariwodola 4fc82c6527 app head: resolved search 2020-01-05 13:58:12 +01:00
Akinwale Ariwodola 56486ad274 app head: storage permission checks 2020-01-04 07:11:50 +01:00
Akinwale Ariwodola 99a38e655b bumpversion 0.12.1 --> 0.12.2 2020-01-03 19:12:14 +01:00
Akinwale Ariwodola 262050147d sdk 0.51.2 2020-01-03 18:55:47 +01:00
Akinwale Ariwodola 5ff2e608c2 app head: reactotron and search improvements 2019-12-29 11:17:13 +01:00
Akinwale Ariwodola 4e305faf5b app head: remove console.log 2019-12-29 07:24:26 +01:00
Akinwale Ariwodola 0bdbb843fb add android:exported to activity definition in manifest 2019-12-29 07:20:48 +01:00
Akinwale Ariwodola c8736ad26e update gradle dependencies 2019-12-29 07:15:14 +01:00
Akinwale Ariwodola 57d6b72f5a First run changes (#809)
* don't request for storage permission on first startup
* app head: download button tweaks
* fix download manager
2019-12-28 16:06:14 +01:00
Akinwale Ariwodola d0117b14db React Native 0.61 (#808)
* support for RN 0.61.5
* update gradle_dependencies
2019-12-28 15:42:26 +01:00
Akinwale Ariwodola 6729842ed8 app head: channel name and follower background 2019-12-20 18:55:10 +01:00
Akinwale Ariwodola 723ade8ba6 bumpversion 0.12.0 --> 0.12.1 2019-12-20 09:03:00 +01:00
Akinwale Ariwodola 83066232b6 sdk 0.50.1 2019-12-20 09:02:10 +01:00
Akinwale Ariwodola 4dc0b19c5d Merge pull request #800 from lbryio/snackbars
snackbar support
2019-12-20 08:00:07 +01:00
Akinwale Ariwodola a58cc820ef app head: update master 2019-12-18 16:51:07 +01:00
Akinwale Ariwodola 2b3397bc85 snackbar support 2019-12-18 11:48:29 +01:00
Akinwale Ariwodola a519b5c0b1 app head: display balance on LBC input focus 2019-12-13 17:36:01 +01:00
Akinwale Ariwodola fb3a34c871 disable sound on download notifications 2019-12-13 15:10:02 +01:00
Akinwale Ariwodola a1bc3fcd7e fix notification icon 2019-12-13 14:51:44 +01:00
Akinwale Ariwodola 7daf3c6f55 add headers download to CI for 64-bit build 2019-12-11 17:06:28 +01:00
Akinwale Ariwodola 7d032179ef fix CI build 2019-12-11 16:20:45 +01:00
Akinwale Ariwodola 156507f8f7 remove headers file and dynamically download for build 2019-12-11 16:15:16 +01:00
Akinwale Ariwodola 032a1927db bumpversion 0.11.1 --> 0.12.0 2019-12-11 09:08:42 +01:00
Akinwale Ariwodola f24bf570ef app head: fixes before release 2019-12-11 09:08:26 +01:00
Akinwale Ariwodola 75c2ece016 add headers file to package (#792)
* latest headers
2019-12-11 08:46:34 +01:00
Akinwale Ariwodola 0c1c1a6c79 sdk 0.49.0 2019-12-10 16:30:18 +01:00
Akinwale Ariwodola 5af25a9d43 app head: update 2019-12-06 17:24:34 +01:00
Akinwale Ariwodola 55fec0f578 sdk 0.48.0 2019-12-05 13:42:42 +01:00
Akinwale Ariwodola b61fc3a148 Merge pull request #786 from lbryio/i18n
add language constant for app launch
2019-12-05 13:20:18 +01:00
Akinwale Ariwodola e3cd0fc2b1 add language constant for app launch 2019-12-05 13:19:22 +01:00
g1tman fe01f50c65 Perf: Use of sort and sorted functions optimized (#748)
* Update mixer.py
* Update graph.py
* Update mixer.py
* Update mixer.py
* Update bdistapk.py
* Update toolchain.py
* Update build.py
* Update build.py
2019-11-25 11:28:16 +01:00
Akinwale Ariwodola cd378d16e3 app head: fetching cost info fix 2019-11-12 21:10:57 +01:00
Akinwale Ariwodola e951fabf1c bumpversion 0.11.0 --> 0.11.1 2019-11-12 16:21:22 +01:00
Akinwale Ariwodola 48543a48fb log events for received and opened notifications (#760)
* log events for received and opened notifications
* app head: update to master
2019-11-12 15:50:47 +01:00
Akinwale Ariwodola 2699893581 bumpversion 0.10.2 --> 0.11.0 2019-11-04 08:49:41 +01:00
Akinwale Ariwodola 21914a0bd7 Merge pull request #752 from lbryio/fcm-data
handle FCM data-only messages
2019-11-04 08:48:50 +01:00
Akinwale Ariwodola d83667682d handle FCM data-only messages 2019-11-01 06:54:32 +01:00
1746 changed files with 31745 additions and 196102 deletions

No files matched your search

+64 -14
View File
@@ -1,17 +1,67 @@
.buildozer
.buildozer-downloads
# OSX
#
.DS_Store
# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
# Android/IntelliJ
#
build/
.idea
.gradle
app/node_modules/
bin
buildozer.spec
build.log
recipes/**/*.pyc
src/main/assets/index.android.bundle
src/main/assets/index.android.bundle.meta
local.properties
*.iml
# node.js
#
node_modules/
npm-debug.log
yarn-error.log
# BUCK
buck-out/
\.buckd/
*.keystore
!debug.keystore
# fastlane
#
# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the
# screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/
*/fastlane/report.xml
*/fastlane/Preview.html
*/fastlane/screenshots
# Bundle artifact
*.jsbundle
# CocoaPods
/ios/Pods/
# Other Files
app/google-services.json
*.log
.vagrant
lbry-android.keystore
p4a/pythonforandroid/bootstraps/lbry/build/templates/google-services.json
.gitsecret/keys/random_seed
*.hprof
app/build
bin
+26 -59
View File
@@ -1,79 +1,45 @@
stages:
- build
- build2
- deploy
- release
build arm64 apk:
build apk:
stage: build
image: lbry/android-base:latest
image: lbry/android-base:platform-28
before_script:
- export BUILD_VERSION=$(cat $CI_PROJECT_DIR/src/main/python/main.py | grep --color=never -oP '([0-9]+\.?)+')
- git submodule sync --recursive
- git submodule update --init --force --recursive
- apt-get -y update && apt-get -y install build-essential ca-certificates curl git gpg-agent openjdk-8-jdk software-properties-common wget zipalign
- chmod u+x $CI_PROJECT_DIR/gradlew
- export ANDROID_SDK_ROOT=~/.buildozer/android/platform/android-sdk-23
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
artifacts:
paths:
- bin/browser-*-release__arm.apk
- bin/browser-*-release__arm64.apk
expire_in: 1 week
script:
- export PATH=/usr/bin:$PATH
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- cd app
- npm install
- cd ..
- wget -q 'https://eu.crystax.net/download/crystax-ndk-10.3.2-linux-x86_64.tar.xz' -P ~/.buildozer/android/
- tar -xf ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz -C ~/.buildozer/android/
- rm -rf ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
- ln -s ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21 ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
- cp -f $CI_PROJECT_DIR/scripts/build-target-python.sh ~/.buildozer/android/crystax-ndk-10.3.2/build/tools/build-target-python.sh
- cp -f $CI_PROJECT_DIR/scripts/mangled-glibc-syscalls__arm64.h ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21/arch-arm64/usr/include/crystax/bionic/libc/include/sys/mangled-glibc-syscalls.h
- rm ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install git-secret
- git secret reveal
- mv buildozer.spec.arm64.ci buildozer.spec
- "./release.sh | grep -Fv -e 'working:' -e 'copy' -e 'Compiling' --line-buffered"
- cp $CI_PROJECT_DIR/bin/browser-$BUILD_VERSION-release.apk $CI_PROJECT_DIR/bin/browser-$BUILD_VERSION-release__arm64.apk
- cp $CI_PROJECT_DIR/bin/browser-$BUILD_VERSION-release.apk /dev/null
build arm apk:
stage: build2
image: lbry/android-base:latest
before_script:
- export BUILD_VERSION=$(cat $CI_PROJECT_DIR/src/main/python/main.py | grep --color=never -oP '([0-9]+\.?)+')
- git submodule sync --recursive
- git submodule update --init --force --recursive
artifacts:
paths:
- bin/browser-*-release__arm.apk
expire_in: 1 week
script:
- export PATH=/usr/bin:$PATH
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- cd app
- npm install
- cd ..
- wget -q 'https://eu.crystax.net/download/crystax-ndk-10.3.2-linux-x86_64.tar.xz' -P ~/.buildozer/android/
- tar -xf ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz -C ~/.buildozer/android/
- rm -rf ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
- ln -s ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21 ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
- cp -f $CI_PROJECT_DIR/p4a/pythonforandroid/bootstraps/lbry/build/templates/build.tmpl.gradle.arm $CI_PROJECT_DIR/p4a/pythonforandroid/bootstraps/lbry/build/templates/build.tmpl.gradle
- cp -f $CI_PROJECT_DIR/scripts/build-target-python.sh ~/.buildozer/android/crystax-ndk-10.3.2/build/tools/build-target-python.sh
- cp -f $CI_PROJECT_DIR/scripts/mangled-glibc-syscalls.h ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21/arch-arm/usr/include/crystax/bionic/libc/include/sys/mangled-glibc-syscalls.h
- rm ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz
- git secret reveal
- mv buildozer.spec.arm.ci buildozer.spec
- "./release.sh | grep -Fv -e 'working:' -e 'copy' -e 'Compiling' --line-buffered"
- cp $CI_PROJECT_DIR/bin/browser-$BUILD_VERSION-release.apk $CI_PROJECT_DIR/bin/browser-$BUILD_VERSION-release__arm.apk
- cp $CI_PROJECT_DIR/bin/browser-$BUILD_VERSION-release.apk /dev/null
- yarn
- chmod u+x ./release.sh
- ./release.sh
- cp bin/browser-$BUILD_VERSION-release__arm.apk /dev/null
- cp bin/browser-$BUILD_VERSION-release__arm64.apk /dev/null
deploy build.lbry.io:
image: python:latest
image: python:stretch
stage: deploy
dependencies:
- build arm apk
- build arm64 apk
- build apk
before_script:
- apt-get -y update && apt-get -y install openjdk-8-jdk
- pip install awscli
- export BUILD_VERSION=$(cat $CI_PROJECT_DIR/src/main/python/main.py | grep --color=never -oP '([0-9]+\.?)+')
- chmod u+x $CI_PROJECT_DIR/gradlew
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
- export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk
- export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk
script:
@@ -82,16 +48,17 @@ deploy build.lbry.io:
- aws s3 cp bin/$BUILD_APK_FILENAME__64 s3://build.lbry.io/android/push.apk
release apk:
image: python:latest
image: python:stretch
stage: release
only:
- tags
dependencies:
- build arm apk
- build arm64 apk
- build apk
before_script:
- apt-get -y update && apt-get -y install openjdk-8-jdk
- pip install awscli githubrelease
- export BUILD_VERSION=$(cat $CI_PROJECT_DIR/src/main/python/main.py | grep --color=never -oP '([0-9]+\.?)+')
- chmod u+x $CI_PROJECT_DIR/gradlew
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
- export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk
- export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk
script:
+1 -3
View File
@@ -1,3 +1 @@
[submodule "app"]
path = app
url = https://github.com/lbryio/lbry-react-native
Binary file not shown.
+2 -2
View File
@@ -1,2 +1,2 @@
lbry-android.keystore:
p4a/pythonforandroid/bootstraps/lbry/build/templates/google-services.json
lbry-android.keystore:0d958c531870694624cc877ea98ca1c583485f8ebbb3a5acca58b1930c190d65
app/google-services.json:896a0bee8294a36d061f10fa926129d8a780528b34d0a2f03113400c4246d67c
-137
View File
@@ -1,137 +0,0 @@
## Linux Build Instructions
This app has currently only been built on Ubuntu 14.04, 16.04, 17.10, and 18.04, but these instructions, or an analog of them, should work on most Linux or macOS environments. An abridged version of these instructions is available at [QUICKSTART.md](QUICKSTART.md).
For instructions on how to build using a Docker image, please see [DOCKER.md](DOCKER.md).
### Install Prerequisites
#### Requirements
* JDK 1.8
* Android SDK
* Crystax Android NDK
* Buildozer
* Node.js
* npm
* yarn
#### apt Packages
Install all apt packages required by running the following commands:
```
sudo dpkg --add-architecture i386
sudo apt-get -y update
sudo apt-get install -y curl ca-certificates software-properties-common gpg-agent wget
sudo add-apt-repository ppa:deadsnakes/ppa -y && \
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get -y update && apt-get -y install autoconf autogen automake libtool libffi-dev \
build-essential python3.7 python3.7-dev python3.7-venv python3-pip ccache git libncurses5:i386 libstdc++6:i386 \
libgtk2.0-0:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 libidn11:i386 python2.7 python2.7-dev \
python-pip openjdk-8-jdk unzip zlib1g-dev zlib1g:i386 m4 libc6-dev-i386 yarn gawk nodejs npm
```
Alternatively, the JDK available from http://www.oracle.com/technetwork/java/javase/downloads/index.html can be installed instead of the `openjdk-8-jdk` package.
#### Install Cython and Setuptools
```
sudo -H pip install --upgrade cython==0.28.1 setuptools
```
#### Install buildozer
A forked version of `buildozer` needs to be installed in order to copy the React Native UI source files into the corresponding directories.
```
git clone https://github.com/lbryio/buildozer.git
cd buildozer && python2.7 setup.py install && cd ..
```
#### Create buildozer.spec
Assuming `lbry-android` as the current working folder:
* Copy `buildozer.spec.sample` to `buildozer.spec` in the `lbry-android` folder. Running `buildozer init` instead will create a new `buildozer.spec` file.
* Update `buildozer.spec` settings to match your environment. The basic recommended settings are outlined below.
| Setting | Description |
|:------------------- |:-----------------------------|
| title | application title |
| package.name | package name (e.g. browser) |
| package.domain | package domain (e.g. io.lbry) |
| source.dir | the location of the application main.py |
| version | application version |
| requirements | the Python module requirements for building the application |
| services | list of Android background services and their corresponding Python entry points |
| android.permissions | Android manifest permissions required by the application. This should be set to `INTERNET` at the very least to enable internet connectivity |
| android.api | Android API version (Should be at least 23 for Gradle build support) |
| android.sdk | Android SDK version (Should be at least 23 for Gradle build support) |
| android.ndk | Android NDK version (not required when using crystax Android NDK) |
| android.ndk_path | Android NDK path. This should be set to the crystax Android NDK path) |
| android.sdk_path | Android SDK path. This should be set to the path where the Android SDK is manually set up (if not set up in the `.buildozer` path). |
| p4a.source_dir | Path to the python-for-android repository folder. Currently set to the included `p4a` folder |
| p4a.local_recipes | Path to a folder containing python_for_android recipes to be used in the build. The included `recipes` folder includes recipes for a successful build |
#### Create google-services.json
The `google-services.json` file is required for the build to be successful due to the Firebase implementation. Simply copy the provided sample file into the same destination folder.
```
cd lbry-android
cp p4a/pythonforandroid/bootstraps/lbry/build/templates/google-services.sample.json p4a/pythonforandroid/bootstraps/lbry/build/templates/google-services.json
```
#### Setup Android SDK for buildozer
Download the Android SDK, platform and build tools archives.
* Android API 23 SDK - https://dl.google.com/android/android-sdk_r23-linux.tgz
* Android API 28 platform - https://dl.google.com/android/repository/platform-28_r06.zip
* Android build tools 26.0.2 - https://dl.google.com/android/repository/build-tools_r26.0.2-linux.zip
Create the `.buildozer` path (and the `android` sub-path) in your home folder if it doesn't already exist.
`mkdir ~/.buildozer`
`mkdir ~/.buildozer/android`
Extract the API 23 SDK to the `~/.buildozer/android` path and rename the extracted folder.
```
tar -xf android-sdk_r23-linux.tgz ~/.buildozer/android/platform/
mv ~/.buildozer/android/platform/android-sdk-linux ~/.buildozer/android/platform/android-sdk-23
```
Extract the API 28 platform archive into the `android-sdk-23` folder and rename the extracted folder.
```
unzip ~/.buildozer/android/platform/platform-28_r06.zip -d ~/.buildozer/android/platform/android-sdk-23/platforms
mv ~/.buildozer/android/platform/android-sdk-23/platforms/android-9 ~/.buildozer/android/platform/android-sdk-23/platforms/android-2
```
Extract the build tools 26.0.2 build tools into the `android-sdk-23` folder and rename the extracted folder.
```
mkdir -p ~/.buildozer/android/platform/android-sdk-23/build-tools
unzip ~/.buildozer/android/platform/build-tools_r26.0.2-linux.zip -d ~/.buildozer/android/platform/android-sdk-23/build-tools
mv ~/.buildozer/android/platform/android-sdk-23/build-tools/android-8.1.0 ~/.buildozer/android/platform/android-sdk-23/build-tools/26.0.2
```
Finally, create the Android SDK license file. This prevents being prompted to accept the SDK license during the build process.
```
mkdir -p ~/.buildozer/android/platform/android-sdk-23/licenses
echo $'\nd56f5187479451eabf01fb78af6dfcb131a6481e' > ~/.buildozer/android/platform/android-sdk-23/licenses/android-sdk-license
```
#### Setup Crystax Android NDK for buildozer
* Download the Crystax Android NDK from https://us.crystax.net/download/crystax-ndk-10.3.2-linux-x86_64.tar.xz and extract. Remember to update `android.ndk_path` in your `buildozer.spec` to the path of the extracted Crystax NDK archive.
* Copy `build-target-python.sh` from the `scripts` folder in the cloned `lbry-android` repository to the `crystax-ndk-10.3.2/build/tools/` folder.
* Copy `mangled-glibc-syscalls.h` from the `scripts` folder in the cloned `lbry-android` repository to the `crystax-ndk-10.3.2/platforms/android-21/arch-arm/usr/include/crystax/bionic/libc/include/sys/` folder.
* Delete the `android-9` folder in `crystax-ndk-10.3.2/platforms`, and create a symbolic link named `android-9` to the `android-21` folder.
#### Build and Deploy
Run `npm install -g react-native-cli` to install React Native CLI tools.
Initialise git submodules by running `git submodule update --init --recursive` in the `lbry-android` folder.
Run `npm i` in the `lbry-android/app` folder to install the necessary modules required by the React Native user interface, and then run `./bundle.sh`.
Run `./build.sh` in `lbry-android` to build the APK. The output can be found in the `bin` subdirectory.
To build and deploy, you can run `./deploy.sh`. This requires a connected device or a running Android emulator.
#### Development
If you already installed `Android SDK` and `adb`
* Run `adb reverse tcp:8081 tcp:8081`
* Then go to the `lbry-android/app` folder and run `npm start`
Note: You need to have your device connected with USB debugging.
Once the bundler is ready, run the LBRY Browser app on your device and then shake the device violently until you see the React Native dev menu. You can enable "Live Reloading" and "Hot Reloading" from this menu, so any changes you make to the React Native code will be visible as you save. This will only reload React Native Javascript files. Native Java code needs to be redeployed by running the command `./deploy.sh`
-156
View File
@@ -1,156 +0,0 @@
# lbry-android development environment inside docker
[scripts/lbry-android.sh](scripts/lbry-android.sh) is a bash script to create a
docker container for lbry-android development.
This is a hybrid approach where the apk is built inside docker, but you run
Android Studio, `adb`, and the app hot-reload bundler, directly on your host.
## Features
* Clones lbry-android source code to a directory on the host, and mounts it
inside the container.
* Installs all build dependencies inside the container, leaving your host
computer clean.
* Mounted `.buildozer` directory to save container space. (Docker containers
should stay under 10GB, and `.buildozer` is too big, so it has to stay in a
mounted host directory instead.)
* The biggest downloads are cached in `.buildozer-downloads` directory so you
can easily remove `.buildozer` and not have to re-download the large cryostax
NDK more than once.
* Instructions for installing on a real Android device, and for setting up
hot-reload.
* Only a handful of commands to go from zero->hero.
## Requirements
Install all of the following on your host computer:
* Tested on Linux x86_64 with BASH.
* [Install Android Studio](https://developer.android.com/studio/).
* The normal install auto-creates a directory in `$HOME/Android/Sdk` to store
SDK downloads in your home directory.
* [Install nodejs](https://nodejs.org/en/download/package-manager/).
* [Install yarn](https://yarnpkg.com/lang/en/docs/install).
* [Install Docker](https://docs.docker.com/install/).
* Install `sudo` and give your user account access to run `sudo docker`.
## Install
Clone `lbry-android`:
```
LBRY_GIT=$HOME/git/vendor/lbryio/
mkdir -p $LBRY_GIT
git clone https://github.com/lbryio/lbry-android.git $LBRY_GIT/lbry-android
cd $LBRY_GIT/lbry-android
git submodule update --init --recursive
```
Install a bash alias to the [scripts/lbry-android.sh](scripts/lbry-android.sh)
script:
```
echo "alias lbry-android=$LBRY_GIT/lbry-android/scripts/lbry-android.sh" >> $HOME/.bashrc
source ~/.bashrc
```
## Usage
* First create the base docker image:
```
lbry-android docker-build
```
(If anytime you change the docker build scripts in the [scripts](scripts)
subdirectory, you should rebuild the image again.)
* Setup buildozer and install dependencies:
```
lbry-android setup
```
* Build the apk:
```
lbry-android build
```
The apk will be built and end up in the `lbry-android/bin/` subdirectory.
## Running on a real Android device
Once you have the apk built, you can install it on a real Android device to
start testing.
Follow the Android documentation for [enabling USB
debugging](https://developer.android.com/studio/command-line/adb#Enabling) on
your device.
Once you have enabled debugging, do the following:
* Plug your device into a USB port on the host computer.
* Run:
```~/Android/Sdk/platform-tools/adb devices```
* ADB should list your device like so:
```
[ryan@t440s lbry-android]$ adb devices
List of devices attached
HT71R0000000 device
```
* The first time you connect, you should see a modal dialog on the device
asking to confirm the host id. You must approve it, or adb will fail to
connect.
* If after trying several times, adb is still not connecting to your device,
and adb lists your device as `unauthorized`, you may need to [follow this
advice](https://stackoverflow.com/a/38380384/56560) and delete your
`$HOME/.android` directory.
* Install the apk (whatever the current version is called) to the device:
```
~/Android/Sdk/platform-tools/adb install ./bin/browser-0.7.5-debug.apk
```
* Open the app on your device, and follow the initial steps to get to the main
lbry-android browser page.
* Create a tcp tunnel over the adb bridge, for the app to handle live-reload:
```
~/Android/Sdk/platform-tools/adb reverse tcp:8081 tcp:8081
```
* Start the live-reload server on the host:
```
cd app/
yarn install
yarn start
```
* With your device currently running the lbry-android app, shake the device
from side to side, and a menu will appear. Choose `Enable Hot Reloading`.
* The app should reload itself.
* Now make a change to the source code to test hot reload. From the host, open
up the main page view source code: `app/src/component/uriBar/view.js`. Find
the line that reads `Search movies, music, and more` (This is the main search
bar at the top of the app.) - Change some of the text and save the file.
* If hot-reload is working, within a few seconds the phone should reload the
page automatically and show the change that you made.
* If the hot-reload does not work, try closing the app (dismiss the window from
the tab overview, via android square button) and reload the app.
-71
View File
@@ -1,71 +0,0 @@
# Introduction
The purpose of this guide is to help whomever is interested in running the LBRY Android application from scratch on their device, but they're main computing platform is not Linux but macOS.
## Estimated build time
25 - 40 minutes (depending on Internet connection speeds)
## What do you need?
* A computer running the latest OS
* Internet access to download modules and packages
* At least 15GB of free disk space
* Docker
* Patience
## Step 1/6
Create an application on [Firebase](https://console.firebase.google.com). In the **Android package name** field, input `io.lbry.browser`. Download the resulting `google-services.json` file and keep it safe, you'll be needing it later.
## Step 2/6
Start the docker application and paste all of these lines into Terminal:
```bash
docker run -it lbry/android-base:latest /bin/bash
wget "https://www.crystax.net/download/crystax-ndk-10.3.2-linux-x86_64.tar.xz" -P ~/.buildozer/android/
tar -xvf ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz -C ~/.buildozer/android/
rm -rf ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
ln -s ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21 ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
git clone https://github.com/lbryio/lbry-android
cd lbry-android
git submodule update --init --recursive
cp buildozer.spec.sample buildozer.spec
cd app;npm i;cd ..
cp scripts/build-target-python.sh ~/.buildozer/android/crystax-ndk-10.3.2/build/tools/build-target-python.sh
cp scripts/mangled-glibc-syscalls.h ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21/arch-arm/usr/include/crystax/bionic/libc/include/sys/mangled-glibc-syscalls.h
cd p4a/pythonforandroid/bootstraps/lbry/build/templates
apt install nano -y
```
## Step 3/6
Copy the contents of the `google-services.json` you downloaded earlier and paste them into Terminal after running the next command:
```bash
nano google-services.json
```
Type `^X` to save and exit.
## Step 4/6
Paste more lines and I guess check your email, this will take some time:
```bash
cd /lbry-android/app
./bundle.sh
cd ..
buildozer android debug
```
When the build is complete, you should see a message like: `[INFO]: # APK renamed to browser-0.7.3-debug.apk`. You will need this filename for the next step.
## Step 5/6
In a separate Terminal window:
```bash
docker ps # get container name
docker cp CONTAINER_NAME:/lbry-android/bin/STEP_4_FILENAME ~/Desktop/ # copies STEP_4_FILENAME to your Desktop
```
## Step 6/6
- Download [Android File Transfer](https://www.android.com/filetransfer) and install it.
- On your Android device, install [File Explorer](https://play.google.com/store/apps/details?id=com.mauriciotogneri.fileexplorer).
- Plug in your Android device and swipe down from the top into the "USB for file transfer" settings (or similar name on your device) and make sure "Transfer files" is selected.
- Open **Android File Transfer** on your computer and drag and drop `STEP_4_FILENAME` from your Desktop to the `Downloads` folder on the Android device.
- Back on the Android device, navigate to `STEP_4_FILENAME` in the `Downloads` folder and tap it to begin installation.
-32
View File
@@ -1,32 +0,0 @@
FROM thyrlian/android-sdk
## Dependencies to run as root:
ENV DEBIAN_FRONTEND=noninteractive
RUN dpkg --add-architecture i386 && \
apt-get -y update && \
apt-get install -y \
curl ca-certificates software-properties-common gpg-agent wget \
python3.7 python3.7-dev python3-pip python2.7 python2.7-dev python3.7-venv \
python-pip zlib1g-dev m4 zlib1g:i386 libc6-dev-i386 gawk nodejs npm unzip openjdk-8-jdk \
autoconf autogen automake libtool libffi-dev build-essential \
ccache git libncurses5:i386 libstdc++6:i386 \
libgtk2.0-0:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 libidn11:i386 && \
npm install -g yarn react-native-cli && \
pip2 install --upgrade cython setuptools && \
pip2 install git+https://github.com/lbryio/buildozer.git@master && \
ln -s /src/scripts/build-docker.sh /usr/local/bin/build && \
adduser lbry-android --gecos GECOS --shell /bin/bash --disabled-password --home /home/lbry-android && \
mkdir /home/lbry-android/.npm-packages && \
echo "prefix=/home/lbry-android/.npm-packages" > /home/lbry-android/.npmrc && \
chown -R lbry-android:lbry-android /home/lbry-android && \
mkdir /src && \
chown lbry-android:lbry-android /src && \
mkdir /dist && \
chown lbry-android:lbry-android /dist
## Further setup done by lbry-android user:
USER lbry-android
COPY scripts/docker-build.sh /home/lbry-android/bin/build
COPY scripts/docker-setup.sh /home/lbry-android/bin/setup
CMD ["/home/lbry-android/bin/build"]
+1 -1
View File
@@ -1,6 +1,6 @@
The MIT License (MIT)
Copyright (c) 2017-2019 LBRY Inc
Copyright (c) 2017-2020 LBRY Inc
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-113
View File
@@ -1,113 +0,0 @@
# Introduction
If you would like to contribute to the Android app, but find the build documentation a little daunting, this guide lets you copy-paste your way to a successful APK build.
### Estimated build time
25 - 40 minutes (depending on Internet connection speeds)
### What do you need?
* A computer running [Ubuntu 18.04](https://ubuntu.com/download/desktop)
* Internet access to download modules and packages.
* At least 15GB of free disk space.
* Alternatively, Docker. You can skip steps 1 through 5 if you make use of the `lbry/android-base` Docker base image. Scroll down to [Fast Track](#Fast-Track) at the bottom of the page if you would prefer to use Docker.
### Step 1 of 10
Install all the apt packages required by running the following commands. You can copy-paste this directly to your terminal.
```
sudo dpkg --add-architecture i386
sudo apt-get -y update
sudo apt-get install -y curl ca-certificates software-properties-common gpg-agent wget
sudo add-apt-repository ppa:deadsnakes/ppa -y && \
curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list
sudo apt-get -y update && apt-get -y install autoconf autogen automake libtool libffi-dev \
build-essential python3.7 python3.7-dev python3.7-venv python3-pip ccache git libncurses5:i386 libstdc++6:i386 \
libgtk2.0-0:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 libidn11:i386 python2.7 python2.7-dev \
python-pip openjdk-8-jdk unzip zlib1g-dev zlib1g:i386 m4 libc6-dev-i386 yarn gawk nodejs npm
```
### Step 2 of 10
Install a couple of packages using the Python package installer
```
sudo -H pip install --upgrade cython==0.28.1 setuptools
```
### Step 3 of 10
Install [buildozer](https://github.com/lbryio/buildozer.git), a tool for creating the apk package using the python for android toolchain.
```
git clone https://github.com/lbryio/buildozer.git
cd buildozer && python2.7 setup.py install && cd ..
```
### Step 4 of 10
The Android SDK needs to be setup for buildozer. This requires creating a few directories and downloading a number of files. Run the following commands to create the buildozer directory, download the required archives and extract them into their proper destination folders.
```
mkdir -p ~/.buildozer/android/platform
wget 'https://dl.google.com/android/android-sdk_r23-linux.tgz' -P ~/.buildozer/android/platform/ && \
wget 'https://dl.google.com/android/repository/platform-28_r06.zip' -P ~/.buildozer/android/platform/ && \
wget 'https://dl.google.com/android/repository/build-tools_r26.0.2-linux.zip' -P ~/.buildozer/android/platform/
tar -xvf ~/.buildozer/android/platform/android-sdk_r23-linux.tgz -C ~/.buildozer/android/platform/ && \
mv ~/.buildozer/android/platform/android-sdk-linux ~/.buildozer/android/platform/android-sdk-23 && \
unzip ~/.buildozer/android/platform/platform-28_r06.zip -d ~/.buildozer/android/platform/android-sdk-23/platforms && \
mv ~/.buildozer/android/platform/android-sdk-23/platforms/android-9 ~/.buildozer/android/platform/android-sdk-23/platforms/android-28 && \
mkdir -p ~/.buildozer/android/platform/android-sdk-23/build-tools && \
unzip ~/.buildozer/android/platform/build-tools_r26.0.2-linux.zip -d ~/.buildozer/android/platform/android-sdk-23/build-tools && \
mkdir -p ~/.buildozer/android/platform/android-sdk-23/licenses && \
echo $'\nd56f5187479451eabf01fb78af6dfcb131a6481e' > ~/.buildozer/android/platform/android-sdk-23/licenses/android-sdk-license
```
### Step 5 of 10
Install the react-native-cli npm package.
```
sudo npm install -g react-native-cli
```
### Step 6 of 10
Install the Crystax NDK which is required for building Python 3.7 for the mobile app, and a number of native C / C++ modules and packages used by the app. Run the following commands to download and extract the NDK.
```
wget 'https://www.crystax.net/download/crystax-ndk-10.3.2-linux-x86_64.tar.xz' -P ~/.buildozer/android/ && \
tar -xvf ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz -C ~/.buildozer/android/ && \
rm -rf ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9 && \
ln -s ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21 ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
```
### Step 7 of 10
Clone the [lbryio/lbry-android git repository](https://github.com/lbryio/lbry-android), initialise submodules and create your `buildozer.spec` and `google-services.json` files. The provided `buildozer.spec.sample` contains defaults provided you followed steps 1 through 5 exactly as described. You can also customise the spec file if you want to. The `google-services.sample.json` can be used to ensure the build completes successfully.
```
git clone https://github.com/lbryio/lbry-android
cd lbry-android
git submodule update --init --recursive
cp buildozer.spec.sample buildozer.spec
cp p4a/pythonforandroid/bootstraps/lbry/templates/google-services.sample.json p4a/pythonforandroid/bootstraps/lbry/templates/google-services.json
```
### Step 8 of 10
Install the npm packages required for the app's React Native code, and create the React Native app bundle.
```
cd app
npm install
./bundle.sh
cd ..
```
### Step 9 of 10
Copy a couple of required files from the repository for the build to be successful.
```
cp scripts/build-target-python.sh ~/.buildozer/android/crystax-ndk-10.3.2/build/tools/build-target-python.sh
cp scripts/mangled-glibc-syscalls.h ~/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21/arch-arm/usr/include/crystax/bionic/libc/include/sys/mangled-glibc-syscalls.h
```
### Step 10 of 10
If you made it this far, you're finally ready to build the package! You just have to run a single command to generate the APK.
```
buildozer android debug
```
### Fast Track {#Fast-Track}
Install Docker and start a container using the `lbry/android-base` image, which is about 1.72GB in size. Run the following commands for Ubuntu and then follow steps 6 through 10 in the container's bash prompt.
```
sudo apt-get install docker-ce
docker run -it lbry/android-base:latest /bin/bash
```
**Pro Tip:** You can also make use of Docker to run your builds on macOS or Windows.
+3 -3
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 [lbrynet-daemon](https://github.com/lbryio/lbry) as a background service with a UI layer built with React Native. The APK is built using buildozer and the Gradle build tool.
An Android browser and wallet for the [LBRY](https://lbry.com) network. This app bundles [LBRY SDK](https://github.com/lbryio/lbry) as a background service with a UI layer built with React Native.
<img src="https://spee.ch/@lbry:3f/android-08-homepage.gif" alt="LBRY Android GIF" width="384px" />
@@ -15,10 +15,10 @@ The minimum supported Android version is 5.0 Lollipop. There are two ways to ins
1. Direct APK install available at [http://build.lbry.io/android/latest.apk](http://build.lbry.io/android/latest.apk). You will need to enable installation from third-party sources on your device in order to install from this source.
## Usage
The app can be launched by opening **LBRY Browser** from the device's app drawer or via the shortcut on the home screen if that was created upon installation.
The app can be launched by opening **LBRY** from the device's app drawer or via the shortcut on the home screen if that was created upon installation.
## Running from Source
The app is built from source via [Buildozer](https://github.com/kivy/buildozer). After cloning the repository, copy `buildozer.spec.sample` to `buildozer.spec` and modify this file as necessary for your environment. Please see [BUILD.md](BUILD.md) for detailed build instructions.
Please refer to https://github.com/lbryio/lbry-react-native/blob/master/README.md
## Contributing
Contributions to this project are welcome, encouraged, and compensated. For more details, see https://lbry.io/faq/contributing
Vendored
-100
View File
@@ -1,100 +0,0 @@
echoed=false
Vagrant.configure("2") do |config|
config.vm.box = "ubuntu/bionic64"
#config.disksize.size = "20GB"
config.vm.provider "virtualbox" do |v|
host = RbConfig::CONFIG['host_os']
# Give VM 1/4 system memory & access to all cpu cores on the host
if host =~ /darwin/
cpus = `sysctl -n hw.ncpu`.to_i
# sysctl returns Bytes and we need to convert to MB
mem = `sysctl -n hw.memsize`.to_i / 1024 / 1024 / 4
elsif host =~ /linux/
cpus = `nproc`.to_i
# meminfo shows KB and we need to convert to MB
mem = `grep 'MemTotal' /proc/meminfo | sed -e 's/MemTotal://' -e 's/ kB//'`.to_i / 1024 / 4
else
cpus = `wmic cpu get NumberOfCores`.split("\n")[2].to_i
mem = `wmic OS get TotalVisibleMemorySize`.split("\n")[2].to_i / 1024 /4
end
mem = mem / 1024 / 4
mem = [mem, 2048].max # Minimum 2048
if echoed === false
echoed=true
puts("Memory", mem)
puts("CPUs", cpus)
end
#v.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/home_vagrant_lbry-android", "1"]
#v.customize ["setextradata", :id, "VBoxInternal2/SharedFoldersEnableSymlinksCreate/vagrant", "1"]
v.customize ["modifyvm", :id, "--memory", mem]
v.customize ["modifyvm", :id, "--cpus", cpus]
end
config.vm.synced_folder "./", "/home/vagrant/lbry-android"
config.vm.provision "shell", inline: <<-SHELL
dpkg --add-architecture i386
apt-get update
apt-get install -y libssl-dev
apt-get install -y python3.6 python3.6-dev python3-pip autoconf libffi-dev pkg-config libtool build-essential ccache git libncurses5:i386 libstdc++6:i386 libgtk2.0-0:i386 libpangox-1.0-0:i386 libpangoxft-1.0-0:i386 libidn11:i386 python2.7 python2.7-dev openjdk-8-jdk unzip zlib1g-dev zlib1g:i386 m4 libc6-dev-i386 python-pip
pip install -f --upgrade setuptools pyopenssl
git clone https://github.com/lbryio/buildozer.git
cd buildozer
python2.7 setup.py install
cd ../
rm -rf ./buildozer
# Install additonal buildozer dependencies
sudo apt-get install cython
# Install node
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -
sudo apt-get install -y nodejs
export HOME=/home/vagrant
cp $HOME/lbry-android/buildozer.spec.vagrant $HOME/lbry-android/buildozer.spec
mkdir -p cd $HOME/.buildozer/android/platform/
wget -q 'https://us.crystax.net/download/crystax-ndk-10.3.2-linux-x86_64.tar.xz' -P $HOME/.buildozer/android/
wget -q 'https://dl.google.com/android/android-sdk_r23-linux.tgz' -P $HOME/.buildozer/android/platform/
wget -q 'https://dl.google.com/android/repository/platform-27_r01.zip' -P $HOME/.buildozer/android/platform/
wget -q 'https://dl.google.com/android/repository/build-tools_r26.0.1-linux.zip' -P $HOME/.buildozer/android/platform/
tar -xf ~/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz -C $HOME/.buildozer/android/
rm $HOME/.buildozer/android/crystax-ndk-10.3.2-linux-x86_64.tar.xz
ln -s $HOME/.buildozer/android/crystax-ndk-10.3.2/platforms/android-21 $HOME/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
cp -f $HOME/lbry-android/scripts/build-target-python.sh $HOME/.buildozer/android/crystax-ndk-10.3.2/build/tools/build-target-python.sh
rm -rf $HOME/.buildozer/android/crystax-ndk-10.3.2/platforms/android-9
tar -xf $HOME/.buildozer/android/platform/android-sdk_r23-linux.tgz -C $HOME/.buildozer/android/platform/
rm $HOME/.buildozer/android/platform/android-sdk_r23-linux.tgz
mv $HOME/.buildozer/android/platform/android-sdk-linux $HOME/.buildozer/android/platform/android-sdk-23
unzip -qq $HOME/.buildozer/android/platform/android-23_r02.zip -d $HOME/.buildozer/android/platform/android-sdk-23/platforms
rm $HOME/.buildozer/android/platform/platform-27_r01.zip
mv $HOME/.buildozer/android/platform/android-sdk-23/platforms/android-8.1.0 $HOME/.buildozer/android/platform/android-sdk-23/platforms/android-27
mkdir -p $HOME/.buildozer/android/platform/android-sdk-23/build-tools
unzip -qq $HOME/.buildozer/android/platform/build-tools_r26.0.1-linux.zip -d $HOME/.buildozer/android/platform/android-sdk-23/build-tools
rm $HOME/.buildozer/android/platform/build-tools_r26.0.1-linux.zip
mv $HOME/.buildozer/android/platform/android-sdk-23/build-tools/android-8.0.0 $HOME/.buildozer/android/platform/android-sdk-23/build-tools/26.0.1
mkdir -p $HOME/.buildozer/android/platform/android-sdk-23/licenses
rm -rf $HOME/.buildozer/android/platform/android-sdk-23/tools
# https://dl.google.com/android/repository/sdk-tools-linux-3859397.zip
wget -q https://dl.google.com/android/repository/tools_r25.2.5-linux.zip
unzip -o -q ./tools_r25.2.5-linux.zip -d $HOME/.buildozer/android/platform/android-sdk-23/
rm sdk-tools-linux-3859397.zip
echo $'\nd56f5187479451eabf01fb78af6dfcb131a6481e' > $HOME/.buildozer/android/platform/android-sdk-23/licenses/android-sdk-license
sudo chown -r vagrant $HOME
echo "Installing React Native via NPM..."
sudo npm install -g react-native-cli
SHELL
end
Submodule app deleted from 5915919560.
+1
View File
@@ -0,0 +1 @@
/build
+97
View File
@@ -0,0 +1,97 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 29
buildToolsVersion "29.0.1"
flavorDimensions "default"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId "io.lbry.browser"
minSdkVersion 21
targetSdkVersion 29
versionCode 1502
versionName "0.15.2"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
productFlavors {
__32bit {
versionCode android.defaultConfig.versionCode * 10 + 1
ndk {
abiFilter "armeabi-v7a"
}
}
__64bit {
versionCode android.defaultConfig.versionCode * 10 + 2
ndk {
abiFilter "arm64-v8a"
}
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
task printVersionName {
doLast {
println android.defaultConfig.versionName
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0'
implementation "androidx.cardview:cardview:1.0.0"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment:2.2.2'
implementation 'androidx.navigation:navigation-ui:2.2.2'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
implementation 'androidx.preference:preference:1.1.1'
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.android.gms:play-services-base:17.2.1'
implementation 'com.google.firebase:firebase-messaging:20.1.6'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.google.android.exoplayer:exoplayer-core:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-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:flexbox:2.0.1'
implementation 'com.hbb20:ccp:2.3.8'
implementation 'com.github.chrisbanes:PhotoView:2.3.0'
implementation 'com.atlassian.commonmark:commonmark:0.14.0'
compileOnly 'org.projectlombok:lombok:1.18.10'
annotationProcessor 'org.projectlombok:lombok:1.18.10'
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
testImplementation 'junit:junit:4.12'
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')
}
apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true
Binary file not shown.
@@ -37,4 +37,5 @@
}
],
"configuration_version": "1"
}
}
Binary file not shown.
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
@@ -0,0 +1,27 @@
package io.lbry.browser;
import android.content.Context;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("io.lbry.browser", appContext.getPackageName());
}
}
+89
View File
@@ -0,0 +1,89 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.lbry.browser"
android:installLocation="auto">
<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: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" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="@color/lbryGreen" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="@string/default_notification_channel_id"/>
<meta-data android:name="wakelock" android:value="0"/>
<activity
android:configChanges="orientation|keyboardHidden|screenSize|smallestScreenSize|screenLayout"
android:name=".MainActivity"
android:label="@string/app_name"
android:supportsPictureInPicture="true"
android:theme="@style/AppTheme.NoActionBar"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="lbry" />
</intent-filter>
</activity>
<activity
android:name=".FirstRunActivity"
android:launchMode="singleTask"
android:parentActivityName=".MainActivity"
android:theme="@style/AppTheme.NoActionBarTranslucent" />
<activity
android:name=".VerificationActivity"
android:launchMode="singleTask"
android:parentActivityName=".MainActivity"
android:theme="@style/AppTheme.NoActionBarTranslucent"
android:windowSoftInputMode="adjustResize" />
<service
android:name="io.lbry.browser.LbrynetMessagingService"
android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<provider
android:name="io.lbry.browser.LocalFileProvider"
android:authorities="io.lbry.browser.fileprovider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths" />
</provider>
</application>
</manifest>
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

@@ -0,0 +1,138 @@
package io.lbry.browser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
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;
import androidx.preference.PreferenceManager;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.Lbryio;
public class FirstRunActivity extends AppCompatActivity {
private BroadcastReceiver sdkReadyReceiver;
private BroadcastReceiver authReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first_run);
TextView welcomeTos = findViewById(R.id.welcome_text_view_tos);
welcomeTos.setMovementMethod(LinkMovementMethod.getInstance());
welcomeTos.setText(HtmlCompat.fromHtml(getString(R.string.welcome_tos), HtmlCompat.FROM_HTML_MODE_LEGACY));
findViewById(R.id.welcome_link_use_lbry).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finishFirstRun();
}
});
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();
}
}
public void onResume() {
super.onResume();
LbryAnalytics.setCurrentScreen(this, "First Run", "FirstRun");
}
private void registerAuthReceiver() {
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_USER_AUTHENTICATION_SUCCESS);
filter.addAction(MainActivity.ACTION_USER_AUTHENTICATION_FAILED);
authReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (MainActivity.ACTION_USER_AUTHENTICATION_SUCCESS.equals(intent.getAction())) {
handleAuthenticationSuccess();
} else {
handleAuthenticationFailed();
}
}
};
registerReceiver(authReceiver, filter);
}
private void handleAuthenticationSuccess() {
// first_auth completed event
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean firstAuthCompleted = sp.getBoolean(MainActivity.PREFERENCE_KEY_INTERNAL_FIRST_AUTH_COMPLETED, false);
if (!firstAuthCompleted) {
LbryAnalytics.logEvent(LbryAnalytics.EVENT_FIRST_USER_AUTH);
sp.edit().putBoolean(MainActivity.PREFERENCE_KEY_INTERNAL_FIRST_AUTH_COMPLETED, true).apply();
}
findViewById(R.id.welcome_wait_container).setVisibility(View.GONE);
findViewById(R.id.welcome_display).setVisibility(View.VISIBLE);
findViewById(R.id.welcome_link_use_lbry).setVisibility(View.VISIBLE);
}
private void handleAuthenticationFailed() {
Toast.makeText(this, "Authentication failed.", Toast.LENGTH_LONG).show();
}
private void authenticate() {
new AuthenticateTask(this).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void finishFirstRun() {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putBoolean(MainActivity.PREFERENCE_KEY_INTERNAL_FIRST_RUN_COMPLETED, true).apply();
// first_run_completed event
LbryAnalytics.logEvent(LbryAnalytics.EVENT_FIRST_RUN_COMPLETED);
finish();
}
@Override
public void onBackPressed() {
return;
}
@Override
protected void onDestroy() {
Helper.unregisterReceiver(authReceiver, this);
Helper.unregisterReceiver(sdkReadyReceiver, this);
super.onDestroy();
}
private static class AuthenticateTask extends AsyncTask<Void, Void, Void> {
private Context context;
public AuthenticateTask(Context context) {
this.context = context;
}
protected Void doInBackground(Void... params) {
Lbryio.authenticate(context);
return null;
}
}
}
@@ -9,15 +9,22 @@ import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.os.Bundle;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.preference.PreferenceManager;
import android.util.Log;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import io.lbry.browser.reactmodules.UtilityModule;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.lbrysdk.LbrynetService;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
@@ -25,35 +32,40 @@ import java.util.Map;
public class LbrynetMessagingService extends FirebaseMessagingService {
private static final String TAG = "LbrynetMessagingService";
private static final String NOTIFICATION_CHANNEL_ID = "io.lbry.browser.LBRY_ENGAGEMENT_CHANNEL";
private static final String TYPE_SUBSCRIPTION = "subscription";
private static final String TYPE_REWARD = "reward";
private static final String TYPE_INTERESTS = "interests";
private static final String TYPE_CREATOR = "creator";
private FirebaseAnalytics firebaseAnalytics;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "From: " + remoteMessage.getFrom());
Map<String, String> payload = remoteMessage.getData();
String type = null;
String url = null;
if (payload != null) {
type = payload.get("type");
url = payload.get("target");
if (firebaseAnalytics == null) {
firebaseAnalytics = FirebaseAnalytics.getInstance(this);
}
if (type != null && getEnabledTypes().indexOf(type) > -1) {
// Check if message contains a notification payload.
RemoteMessage.Notification remoteNotification = remoteMessage.getNotification();
if (remoteNotification != null) {
Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
sendNotification(remoteNotification.getTitle(), remoteNotification.getBody(), type, url);
Map<String, String> payload = remoteMessage.getData();
if (payload != null) {
String type = payload.get("type");
String url = payload.get("target");
String title = payload.get("title");
String body = payload.get("body");
String name = payload.get("name"); // notification name
String contentTitle = payload.get("content_title");
String channelUrl = payload.get("channel_url");
//String publishTime = payload.get("publish_time");
String publishTime = null;
if (type != null && getEnabledTypes().indexOf(type) > -1 && body != null && body.trim().length() > 0) {
// only log the receive event for valid notifications received
if (firebaseAnalytics != null) {
Bundle bundle = new Bundle();
bundle.putString("name", name);
firebaseAnalytics.logEvent(LbryAnalytics.EVENT_LBRY_NOTIFICATION_RECEIVE, bundle);
}
sendNotification(title, body, type, url, name, contentTitle, channelUrl, publishTime);
}
}
}
@@ -80,12 +92,13 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
// TODO: Implement this method to send token to your app server.
}
/**
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String title, String messageBody, String type, String url) {
private void sendNotification(String title, String messageBody, String type, String url, String name,
String contentTitle, String channelUrl, String publishTime) {
//Intent intent = new Intent(this, MainActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (url == null) {
@@ -98,6 +111,7 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
}
Intent launchIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
launchIntent.putExtra("notification_name", name);
launchIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, launchIntent, PendingIntent.FLAG_ONE_SHOT);
@@ -118,27 +132,27 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
NOTIFICATION_CHANNEL_ID, "LBRY Engagement", NotificationManager.IMPORTANCE_DEFAULT);
NOTIFICATION_CHANNEL_ID, "LBRY Engagement", NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(9898, notificationBuilder.build());
notificationManager.notify(3, notificationBuilder.build());
}
public List<String> getEnabledTypes() {
SharedPreferences sp = getSharedPreferences(MainActivity.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
List<String> enabledTypes = new ArrayList<String>();
if (sp.getBoolean(UtilityModule.RECEIVE_SUBSCRIPTION_NOTIFICATIONS, true)) {
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_SUBSCRIPTIONS, true)) {
enabledTypes.add(TYPE_SUBSCRIPTION);
}
if (sp.getBoolean(UtilityModule.RECEIVE_REWARD_NOTIFICATIONS, true)) {
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_REWARDS, true)) {
enabledTypes.add(TYPE_REWARD);
}
if (sp.getBoolean(UtilityModule.RECEIVE_INTERESTS_NOTIFICATIONS, true)) {
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_CONTENT_INTERESTS, true)) {
enabledTypes.add(TYPE_INTERESTS);
}
if (sp.getBoolean(UtilityModule.RECEIVE_CREATOR_NOTIFICATIONS, true)) {
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_CREATOR, true)) {
enabledTypes.add(TYPE_CREATOR);
}
@@ -1,6 +1,6 @@
package io.lbry.browser;
import android.support.v4.content.FileProvider;
import androidx.core.content.FileProvider;
public class LocalFileProvider extends FileProvider {
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,271 @@
package io.lbry.browser;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;
import com.google.android.material.snackbar.Snackbar;
import java.util.Arrays;
import io.lbry.browser.adapter.VerificationPagerAdapter;
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.LbryAnalytics;
import io.lbry.browser.utils.Lbryio;
public class VerificationActivity extends FragmentActivity implements SignInListener, WalletSyncListener {
public static final int VERIFICATION_FLOW_SIGN_IN = 1;
public static final int VERIFICATION_FLOW_REWARDS = 2;
public static final int VERIFICATION_FLOW_WALLET = 3;
private String email;
private boolean signedIn;
private int flow;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
signedIn = Lbryio.isSignedIn();
Intent intent = getIntent();
if (intent != null) {
flow = intent.getIntExtra("flow", -1);
if (flow == -1 || (flow == VERIFICATION_FLOW_SIGN_IN && signedIn)) {
// no flow specified (or user is already signed in), just exit
setResult(signedIn ? RESULT_OK : RESULT_CANCELED);
finish();
return;
}
}
if (!Arrays.asList(VERIFICATION_FLOW_SIGN_IN, VERIFICATION_FLOW_REWARDS, VERIFICATION_FLOW_WALLET).contains(flow)) {
// invalid flow specified
setResult(RESULT_CANCELED);
finish();
return;
}
setContentView(R.layout.activity_verification);
ViewPager2 viewPager = findViewById(R.id.verification_pager);
viewPager.setUserInputEnabled(false);
viewPager.setSaveEnabled(false);
viewPager.setAdapter(new VerificationPagerAdapter(this));
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
findViewById(R.id.verification_close_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
setResult(RESULT_CANCELED);
finish();
}
});
}
public void onResume() {
super.onResume();
LbryAnalytics.setCurrentScreen(this, "Verification", "Verification");
checkFlow();
}
public void checkFlow() {
ViewPager2 viewPager = findViewById(R.id.verification_pager);
if (Lbryio.isSignedIn()) {
boolean flowHandled = false;
if (flow == VERIFICATION_FLOW_WALLET) {
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_WALLET, false);
flowHandled = true;
} else if (flow == VERIFICATION_FLOW_REWARDS) {
User user = Lbryio.currentUser;
if (!user.isIdentityVerified()) {
// phone number verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false);
flowHandled = true;
} else if (!user.isRewardApproved()) {
// manual verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false);
flowHandled = true;
}
}
if (!flowHandled) {
// user has already been verified and or reward approved
setResult(RESULT_CANCELED);
finish();
return;
}
}
}
public void showLoading() {
findViewById(R.id.verification_loading_progress).setVisibility(View.VISIBLE);
findViewById(R.id.verification_pager).setVisibility(View.INVISIBLE);
findViewById(R.id.verification_close_button).setVisibility(View.GONE);
}
public void hideLoading() {
findViewById(R.id.verification_loading_progress).setVisibility(View.GONE);
findViewById(R.id.verification_pager).setVisibility(View.VISIBLE);
}
@Override
public void onBackPressed() {
// ignore back press
return;
}
public void onEmailAdded(String email) {
this.email = email;
findViewById(R.id.verification_close_button).setVisibility(View.GONE);
Bundle bundle = new Bundle();
bundle.putString("email", email);
LbryAnalytics.logEvent(LbryAnalytics.EVENT_EMAIL_ADDED, bundle);
}
public void onEmailEdit() {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
}
public void onEmailVerified() {
Snackbar.make(findViewById(R.id.verification_pager), R.string.sign_in_successful, Snackbar.LENGTH_LONG).show();
sendBroadcast(new Intent(MainActivity.ACTION_USER_SIGN_IN_SUCCESS));
Bundle bundle = new Bundle();
bundle.putString("email", email);
LbryAnalytics.logEvent(LbryAnalytics.EVENT_EMAIL_VERIFIED, bundle);
if (flow == VERIFICATION_FLOW_SIGN_IN) {
final Intent resultIntent = new Intent();
resultIntent.putExtra("flow", VERIFICATION_FLOW_SIGN_IN);
resultIntent.putExtra("email", email);
// only sign in required, don't do anything else
showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override
public void onSuccess(User user) {
Lbryio.currentUser = user;
setResult(RESULT_OK, resultIntent);
finish();
}
@Override
public void onError(Exception error) {
showFetchUserError(error.getMessage());
hideLoading();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
// change pager view depending on flow
showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override
public void onSuccess(User user) {
hideLoading();
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
Lbryio.currentUser = user;
ViewPager2 viewPager = findViewById(R.id.verification_pager);
// for rewards, (show phone verification if not done, or manual verification if required)
if (flow == VERIFICATION_FLOW_REWARDS) {
if (!user.isIdentityVerified()) {
// phone number verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false);
} else if (!user.isRewardApproved()) {
// manual verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false);
} else {
// fully verified
setResult(RESULT_OK);
finish();
}
} else if (flow == VERIFICATION_FLOW_WALLET) {
// for wallet sync, if password unlock is required, show password entry page
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_WALLET, false);
}
}
@Override
public void onError(Exception error) {
showFetchUserError(error.getMessage());
hideLoading();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
@Override
public void onPhoneAdded(String countryCode, String phoneNumber) {
}
@Override
public void onPhoneVerified() {
showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override
public void onSuccess(User user) {
Lbryio.currentUser = user;
if (user.isIdentityVerified() && user.isRewardApproved()) {
// verified for rewards
LbryAnalytics.logEvent(LbryAnalytics.EVENT_REWARD_ELIGIBILITY_COMPLETED);
setResult(RESULT_OK);
finish();
return;
}
// show manual verification page if the user is still not reward approved
ViewPager2 viewPager = findViewById(R.id.verification_pager);
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false);
hideLoading();
}
@Override
public void onError(Exception error) {
showFetchUserError(error.getMessage());
hideLoading();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void showFetchUserError(String message) {
Snackbar.make(findViewById(R.id.verification_pager), message, Snackbar.LENGTH_LONG).setBackgroundTint(Color.RED).show();
}
@Override
public void onManualVerifyContinue() {
setResult(RESULT_OK);
finish();
}
@Override
public void onWalletSyncProcessing() {
findViewById(R.id.verification_close_button).setVisibility(View.GONE);
}
@Override
public void onWalletSyncWaitingForInput() {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
}
@Override
public void onWalletSyncEnabled() {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
setResult(RESULT_OK);
finish();
}
@Override
public void onWalletSyncFailed(Exception error) {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
}
}
@@ -0,0 +1,125 @@
package io.lbry.browser.adapter;
import android.content.Context;
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 com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
import io.lbry.browser.listener.ChannelItemSelectionListener;
import io.lbry.browser.utils.Helper;
import lombok.Getter;
import lombok.Setter;
public class ChannelFilterListAdapter extends RecyclerView.Adapter<ChannelFilterListAdapter.ViewHolder> {
private Context context;
private List<Claim> items;
@Getter
@Setter
private Claim selectedItem;
@Setter
private ChannelItemSelectionListener listener;
public ChannelFilterListAdapter(Context context) {
this.context = context;
this.items = new ArrayList<>();
// Always list the placeholder as the first item
Claim claim = new Claim();
claim.setPlaceholder(true);
items.add(claim);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected View mediaContainer;
protected View alphaContainer;
protected View allView;
protected ImageView thumbnailView;
protected TextView alphaView;
protected TextView titleView;
public ViewHolder(View v) {
super(v);
mediaContainer = v.findViewById(R.id.channel_filter_media_container);
alphaContainer = v.findViewById(R.id.channel_filter_no_thumbnail);
alphaView = v.findViewById(R.id.channel_filter_alpha_view);
thumbnailView = v.findViewById(R.id.channel_filter_thumbnail);
titleView = v.findViewById(R.id.channel_filter_title);
allView = v.findViewById(R.id.channel_filter_all_container);
}
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
public boolean isClaimSelected(Claim claim) {
return claim.equals(selectedItem);
}
public void clearClaims() {
items = new ArrayList<>(items.subList(0, 1));
notifyDataSetChanged();
}
public void addClaims(List<Claim> claims) {
for (Claim claim : claims) {
if (!items.contains(claim)) {
items.add(claim);
}
}
notifyDataSetChanged();
}
@Override
public ChannelFilterListAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_channel_filter, root, false);
return new ChannelFilterListAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(ChannelFilterListAdapter.ViewHolder vh, int position) {
Claim claim = items.get(position);
vh.alphaView.setVisibility(claim.isPlaceholder() ? View.GONE : View.VISIBLE);
vh.titleView.setVisibility(claim.isPlaceholder() ? View.INVISIBLE : View.VISIBLE);
vh.allView.setVisibility(claim.isPlaceholder() ? View.VISIBLE : View.GONE);
vh.titleView.setText(Helper.isNullOrEmpty(claim.getTitle()) ? claim.getName() : claim.getTitle());
String thumbnailUrl = claim.getThumbnailUrl();
if (!Helper.isNullOrEmpty(thumbnailUrl) && context != null) {
Glide.with(context.getApplicationContext()).load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(vh.thumbnailView);
}
vh.alphaContainer.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE);
vh.thumbnailView.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.GONE : View.VISIBLE);
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);
vh.itemView.setSelected(isClaimSelected(claim));
vh.itemView.setOnClickListener(view -> {
if (claim.isPlaceholder()) {
selectedItem = null;
if (listener != null) {
listener.onChannelSelectionCleared();
}
} else if (!claim.equals(selectedItem)) {
selectedItem = claim;
if (listener != null) {
listener.onChannelItemSelected(claim);
}
}
notifyDataSetChanged();
});
}
}
@@ -0,0 +1,467 @@
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.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
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;
public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.ViewHolder> {
private static final int VIEW_TYPE_STREAM = 1;
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 canEnterSelectionMode;
private Context context;
private List<Claim> items;
private List<Claim> selectedItems;
@Setter
private ClaimListItemListener listener;
@Getter
@Setter
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.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() {
return this.selectedItems;
}
public int getSelectedCount() {
return selectedItems != null ? selectedItems.size() : 0;
}
public void clearSelectedItems() {
this.selectedItems.clear();
}
public boolean isClaimSelected(Claim claim) {
return selectedItems.contains(claim);
}
public Claim getFeaturedItem() {
for (Claim claim : items) {
if (claim.isFeatured()) {
return claim;
}
}
return null;
}
public List<Claim> getItems() {
return new ArrayList<>(this.items);
}
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();
}
public void addItems(List<Claim> claims) {
for (Claim claim : claims) {
if (!items.contains(claim)) {
items.add(claim);
}
}
notFoundClaimUrlMap.clear();
notFoundClaimIdMap.clear();
notifyDataSetChanged();
}
public void setItems(List<Claim> claims) {
items = new ArrayList<>(claims);
notifyDataSetChanged();
}
public void removeItems(List<Claim> claims) {
items.removeAll(claims);
notifyDataSetChanged();
}
public void removeItem(Claim claim) {
items.remove(claim);
selectedItems.remove(claim);
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected View feeContainer;
protected TextView feeView;
protected ImageView thumbnailView;
protected View noThumbnailView;
protected TextView alphaView;
protected TextView vanityUrlView;
protected TextView durationView;
protected TextView titleView;
protected TextView publisherView;
protected TextView publishTimeView;
protected TextView pendingTextView;
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);
feeView = v.findViewById(R.id.claim_fee);
alphaView = v.findViewById(R.id.claim_thumbnail_alpha);
noThumbnailView = v.findViewById(R.id.claim_no_thumbnail);
thumbnailView = v.findViewById(R.id.claim_thumbnail);
vanityUrlView = v.findViewById(R.id.claim_vanity_url);
durationView = v.findViewById(R.id.claim_duration);
titleView = v.findViewById(R.id.claim_title);
publisherView = v.findViewById(R.id.claim_publisher);
publishTimeView = v.findViewById(R.id.claim_publish_time);
pendingTextView = v.findViewById(R.id.claim_pending_text);
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);
}
}
@Override
public int getItemCount() {
return items != null ? items.size() : 0;
}
@Override
public int getItemViewType(int position) {
if (items.get(position).isFeatured()) {
return VIEW_TYPE_FEATURED;
}
Claim claim = items.get(position);
String valueType = items.get(position).getValueType();
Claim actualClaim = Claim.TYPE_REPOST.equalsIgnoreCase(valueType) ? claim.getRepostedClaim() : claim;
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;
switch (viewType) {
case VIEW_TYPE_FEATURED: viewResourceId = R.layout.list_item_featured_search_result; break;
case VIEW_TYPE_CHANNEL: viewResourceId = R.layout.list_item_channel; break;
case VIEW_TYPE_STREAM: default: viewResourceId = R.layout.list_item_stream; break;
}
View v = LayoutInflater.from(context).inflate(viewResourceId, parent, false);
return new ClaimListAdapter.ViewHolder(v);
}
public int getScaledValue(int value) {
return (int) (value * scale + 0.5f);
}
@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 = getScaledValue(paddingTop);
int paddingBottomScaled = getScaledValue(paddingBottom);
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;
Claim.GenericMetadata metadata = item.getValue();
Claim signingChannel = item.getSigningChannel();
Claim.StreamMetadata streamMetadata = null;
if (metadata instanceof Claim.StreamMetadata) {
streamMetadata = (Claim.StreamMetadata) metadata;
}
String thumbnailUrl = item.getThumbnailUrl();
long publishTime = (streamMetadata != null && streamMetadata.getReleaseTime() > 0) ? streamMetadata.getReleaseTime() * 1000 : item.getTimestamp() * 1000;
int bgColor = Helper.generateRandomColorForValue(item.getClaimId());
if (bgColor == 0) {
bgColor = Helper.generateRandomColorForValue(item.getName());
}
boolean isPending = item.getConfirmations() == 0;
boolean isSelected = isClaimSelected(item);
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();
return;
}
if (inSelectionMode) {
toggleSelectedClaim(item);
} else {
if (listener != null) {
listener.onClaimClicked(item);
}
}
}
});
vh.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (!canEnterSelectionMode) {
return false;
}
if (isPending) {
Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG).show();
return false;
}
if (!inSelectionMode) {
inSelectionMode = true;
if (selectionModeListener != null) {
selectionModeListener.onEnterSelectionMode();
}
}
toggleSelectedClaim(item);
return true;
}
});
vh.publisherView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null && signingChannel != null) {
listener.onClaimClicked(signingChannel);
}
}
});
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.repostChannelView.setText(isRepost ? original.getSigningChannel().getName() : null);
vh.repostChannelView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null) {
listener.onClaimClicked(original.getSigningChannel());
}
}
});
vh.titleView.setText(Helper.isNullOrEmpty(item.getTitle()) ? item.getName() : item.getTitle());
if (type == VIEW_TYPE_FEATURED) {
LbryUri vanityUrl = new LbryUri();
vanityUrl.setClaimName(item.getName());
vh.vanityUrlView.setText(vanityUrl.toString());
}
vh.feeContainer.setVisibility(item.isUnresolved() || !Claim.TYPE_STREAM.equalsIgnoreCase(item.getValueType()) ? View.GONE : View.VISIBLE);
vh.noThumbnailView.setVisibility(Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE);
Helper.setIconViewBackgroundColor(vh.noThumbnailView, bgColor, false, context);
if (type == VIEW_TYPE_FEATURED && item.isUnresolved()) {
vh.durationView.setVisibility(View.GONE);
vh.titleView.setText("Nothing here. Publish something!");
vh.alphaView.setText(item.getName().substring(0, Math.min(5, item.getName().length() - 1)));
} else {
if (Claim.TYPE_STREAM.equalsIgnoreCase(item.getValueType())) {
long duration = item.getDuration();
if (!Helper.isNullOrEmpty(thumbnailUrl)) {
Glide.with(context.getApplicationContext()).
load(thumbnailUrl).
centerCrop().
placeholder(R.drawable.bg_thumbnail_placeholder).
into(vh.thumbnailView);
}
BigDecimal cost = item.getActualCost(Lbryio.LBCUSDRate);
vh.feeContainer.setVisibility(cost.doubleValue() > 0 ? 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 && !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, fileSizeString);
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()).
load(thumbnailUrl).
centerCrop().
placeholder(R.drawable.bg_thumbnail_placeholder).
apply(RequestOptions.circleCropTransform()).
into(vh.thumbnailView);
}
vh.alphaView.setText(item.getName().substring(1, 2).toUpperCase());
vh.publisherView.setText(item.getName());
vh.publishTimeView.setText(DateUtils.getRelativeTimeSpanString(
publishTime, System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
}
}
}
private void toggleSelectedClaim(Claim claim) {
if (selectedItems.contains(claim)) {
selectedItems.remove(claim);
} else {
selectedItems.add(claim);
}
if (selectionModeListener != null) {
selectionModeListener.onItemSelectionToggled();
}
if (selectedItems.size() == 0) {
inSelectionMode = false;
if (selectionModeListener != null) {
selectionModeListener.onExitSelectionMode();
}
}
notifyDataSetChanged();
}
public interface ClaimListItemListener {
void onClaimClicked(Claim claim);
}
}
@@ -0,0 +1,117 @@
package io.lbry.browser.adapter;
import android.content.Context;
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.EditorsChoiceItem;
import io.lbry.browser.utils.Helper;
import lombok.Setter;
public class EditorsChoiceItemAdapter extends RecyclerView.Adapter<EditorsChoiceItemAdapter.ViewHolder> {
private static final int VIEW_TYPE_HEADER = 1;
private static final int VIEW_TYPE_CONTENT = 2;
private Context context;
private List<EditorsChoiceItem> items;
@Setter
private EditorsChoiceItemListener listener;
public EditorsChoiceItemAdapter(List<EditorsChoiceItem> items, Context context) {
this.context = context;
this.items = new ArrayList<>(items);
}
public void addFeaturedItem(EditorsChoiceItem item) {
items.add(0, item);
notifyDataSetChanged();
}
public void addItems(List<EditorsChoiceItem> items) {
for (EditorsChoiceItem item : items) {
if (!this.items.contains(item)) {
this.items.add(item);
}
}
notifyDataSetChanged();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected ImageView thumbnailView;
protected TextView descriptionView;
protected TextView headerView;
protected TextView titleView;
protected View cardView;
public ViewHolder(View v) {
super(v);
cardView = v.findViewById(R.id.editors_choice_content_card);
descriptionView = v.findViewById(R.id.editors_choice_content_description);
titleView = v.findViewById(R.id.editors_choice_content_title);
thumbnailView = v.findViewById(R.id.editors_choice_content_thumbnail);
headerView = v.findViewById(R.id.editors_choice_header_title);
}
}
@Override
public int getItemCount() {
return items != null ? items.size() : 0;
}
@Override
public int getItemViewType(int position) {
return items.get(position).isHeader() ? VIEW_TYPE_HEADER : VIEW_TYPE_CONTENT;
}
@Override
public EditorsChoiceItemAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_editors_choice, parent, false);
return new EditorsChoiceItemAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(EditorsChoiceItemAdapter.ViewHolder vh, int position) {
int type = getItemViewType(position);
EditorsChoiceItem item = items.get(position);
vh.headerView.setVisibility(type == VIEW_TYPE_HEADER ? View.VISIBLE : View.GONE);
vh.cardView.setVisibility(type == VIEW_TYPE_CONTENT ? View.VISIBLE : View.GONE);
vh.headerView.setText(item.getTitle());
vh.titleView.setText(item.getTitle());
vh.descriptionView.setText(item.getDescription());
if (!Helper.isNullOrEmpty(item.getThumbnailUrl())) {
Glide.with(context.getApplicationContext()).
load(item.getThumbnailUrl()).
centerCrop().
placeholder(R.drawable.bg_thumbnail_placeholder).
into(vh.thumbnailView);
}
vh.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null) {
listener.onEditorsChoiceItemClicked(item);
}
}
});
}
public interface EditorsChoiceItemListener {
void onEditorsChoiceItemClicked(EditorsChoiceItem item);
}
}
@@ -0,0 +1,70 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.SpinnerAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
public class InlineChannelSpinnerAdapter extends ArrayAdapter<Claim> {
private List<Claim> channels;
private int layoutResourceId;
private LayoutInflater inflater;
public InlineChannelSpinnerAdapter(Context context, int resource, List<Claim> channels) {
super(context, resource, 0, channels);
inflater = LayoutInflater.from(context);
layoutResourceId = resource;
this.channels = new ArrayList<>(channels);
}
public void addPlaceholder(boolean includeAnonymous) {
Claim placeholder = new Claim();
placeholder.setPlaceholder(true);
insert(placeholder, 0);
channels.add(0, placeholder);
if (includeAnonymous) {
Claim anonymous = new Claim();
anonymous.setPlaceholderAnonymous(true);
insert(anonymous, 1);
channels.add(1, anonymous);
}
}
@Override
public View getDropDownView(int position, View view, ViewGroup parent) {
return createView(position, view, parent);
}
@Override
public View getView(int position, View view, ViewGroup parent) {
return createView(position, view, parent);
}
private View createView(int position, View convertView, ViewGroup parent){
View view = inflater.inflate(layoutResourceId, parent, false);
Context context = getContext();
Claim channel = getItem(position);
String name = channel.getName();
if (channel.isPlaceholder()) {
name = context.getString(R.string.create_a_channel);
} else if (channel.isPlaceholderAnonymous()) {
name = context.getString(R.string.anonymous);
}
TextView label = view.findViewById(R.id.channel_item_name);
label.setText(name);
return view;
}
}
@@ -0,0 +1,92 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.lbryinc.Invitee;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
public class InviteeListAdapter extends RecyclerView.Adapter<InviteeListAdapter.ViewHolder> {
private Context context;
private List<Invitee> items;
public InviteeListAdapter(List<Invitee> invitees, Context context) {
this.context = context;
this.items = new ArrayList<>(invitees);
}
public void clear() {
items.clear();
notifyDataSetChanged();
}
public List<Invitee> getItems() {
return new ArrayList<>(items);
}
public void addHeader() {
Invitee header = new Invitee();
header.setHeader(true);
items.add(0, header);
}
public void addInvitees(List<Invitee> Invitees) {
for (Invitee tx : Invitees) {
if (!items.contains(tx)) {
items.add(tx);
}
}
notifyDataSetChanged();
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
@Override
public InviteeListAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_invitee, root, false);
return new InviteeListAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(InviteeListAdapter.ViewHolder vh, int position) {
Invitee item = items.get(position);
vh.emailView.setText(item.isHeader() ? context.getString(R.string.email) : item.getEmail());
vh.emailView.setTypeface(null, item.isHeader() ? Typeface.BOLD : Typeface.NORMAL);
String rewardText = context.getString(
item.isInviteRewardClaimed() ? R.string.claimed :
(item.isInviteRewardClaimable() ? R.string.claimable : R.string.unclaimable));
vh.rewardView.setText(item.isHeader() ? context.getString(R.string.reward) : rewardText);
vh.rewardView.setTypeface(null, item.isHeader() ? Typeface.BOLD : Typeface.NORMAL);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected TextView emailView;
protected TextView rewardView;
public ViewHolder(View v) {
super(v);
emailView = v.findViewById(R.id.invitee_email);
rewardView = v.findViewById(R.id.invitee_reward);
}
}
}
@@ -0,0 +1,117 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.NavMenuItem;
import io.lbry.browser.ui.controls.SolidIconView;
import io.lbry.browser.utils.Helper;
import lombok.Getter;
import lombok.Setter;
public class NavigationMenuAdapter extends RecyclerView.Adapter<NavigationMenuAdapter.ViewHolder> {
private static final int TYPE_GROUP = 1;
private static final int TYPE_ITEM = 2;
private Context context;
private List<NavMenuItem> menuItems;
private NavMenuItem currentItem;
@Setter
private NavigationMenuItemClickListener listener;
public NavigationMenuAdapter(List<NavMenuItem> menuItems, Context context) {
this.menuItems = new ArrayList<>(menuItems);
this.context = context;
}
public void setCurrentItem(int id) {
for (NavMenuItem item : menuItems) {
if (item.getId() == id) {
this.currentItem = item;
break;
}
}
notifyDataSetChanged();
}
public void setExtraLabelForItem(int id, String extraLabel) {
for (NavMenuItem item : menuItems) {
if (item.getId() == id) {
item.setExtraLabel(extraLabel);
break;
}
}
notifyDataSetChanged();
}
public void setCurrentItem(NavMenuItem currentItem) {
this.currentItem = currentItem;
notifyDataSetChanged();
}
public int getCurrentItemId() {
return currentItem != null ? currentItem.getId() : -1;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected SolidIconView iconView;
protected TextView titleView;
public ViewHolder(View v) {
super(v);
titleView = v.findViewById(R.id.nav_menu_title);
iconView = v.findViewById(R.id.nav_menu_item_icon);
}
}
@Override
public int getItemCount() {
return menuItems != null ? menuItems.size() : 0;
}
@Override
public int getItemViewType(int position) {
return menuItems.get(position).isGroup() ? TYPE_GROUP : TYPE_ITEM;
}
@Override
public NavigationMenuAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(viewType == TYPE_GROUP ?
R.layout.list_item_nav_menu_group : R.layout.list_item_nav_menu_item, parent, false);
return new NavigationMenuAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder vh, int position) {
int type = getItemViewType(position);
NavMenuItem item = menuItems.get(position);
String displayTitle = !Helper.isNullOrEmpty(item.getExtraLabel()) ? String.format("%s (%s)", item.getTitle(), item.getExtraLabel()) : item.getTitle();
vh.titleView.setText(displayTitle);
if (type == TYPE_ITEM && vh.iconView != null) {
vh.iconView.setText(item.getIcon());
}
vh.itemView.setSelected(item.equals(currentItem));
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null) {
listener.onNavigationMenuItemClicked(item);
}
}
});
}
public interface NavigationMenuItemClickListener {
void onNavigationMenuItemClicked(NavMenuItem menuItem);
}
}
@@ -0,0 +1,215 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.lbryinc.Reward;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
import lombok.Getter;
import lombok.Setter;
public class RewardListAdapter extends RecyclerView.Adapter<RewardListAdapter.ViewHolder> {
public static final int DISPLAY_MODE_ALL = 1;
public static final int DISPLAY_MODE_UNCLAIMED = 2;
private Context context;
@Setter
private List<Reward> all;
private List<Reward> items;
@Setter
private RewardClickListener clickListener;
@Getter
private int displayMode;
public RewardListAdapter(List<Reward> all, Context context) {
this.all = new ArrayList<>(all);
this.items = new ArrayList<>(all);
this.context = context;
this.displayMode = DISPLAY_MODE_ALL;
addCustomReward();
}
public void setRewards(List<Reward> rewards) {
this.all = new ArrayList<>(rewards);
updateItemsForDisplayMode();
notifyDataSetChanged();
}
public void setDisplayMode(int displayMode) {
this.displayMode = displayMode;
updateItemsForDisplayMode();
notifyDataSetChanged();
}
private void updateItemsForDisplayMode() {
if (displayMode == DISPLAY_MODE_ALL) {
items = new ArrayList<>(all);
} else if (displayMode == DISPLAY_MODE_UNCLAIMED) {
items = new ArrayList<>();
for (Reward reward : all) {
if (!reward.isClaimed()) {
items.add(reward);
}
}
}
addCustomReward();
}
private void addCustomReward() {
Reward custom = new Reward();
custom.setCustom(true);
custom.setRewardTitle(context.getString(R.string.custom_reward_title));
custom.setRewardDescription(context.getString(R.string.custom_reward_description));
items.add(custom);
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected View iconClaimed;
protected View loading;
protected View upTo;
protected TextView textTitle;
protected TextView textDescription;
protected TextView textLbcValue;
protected TextView textUsdValue;
protected TextView textLinkTransaction;
protected EditText inputCustomCode;
protected MaterialButton buttonClaimCustom;
public ViewHolder(View v) {
super(v);
iconClaimed = v.findViewById(R.id.reward_item_claimed_icon);
upTo = v.findViewById(R.id.reward_item_up_to);
loading = v.findViewById(R.id.reward_item_loading);
textTitle = v.findViewById(R.id.reward_item_title);
textDescription = v.findViewById(R.id.reward_item_description);
textLbcValue = v.findViewById(R.id.reward_item_lbc_value);
textLinkTransaction = v.findViewById(R.id.reward_item_tx_link);
textUsdValue = v.findViewById(R.id.reward_item_usd_value);
inputCustomCode = v.findViewById(R.id.reward_item_custom_code_input);
buttonClaimCustom = v.findViewById(R.id.reward_item_custom_claim_button);
}
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
public void addReward(Reward reward) {
if (!items.contains(reward)) {
items.add(reward);
}
notifyDataSetChanged();
}
public List<Reward> getRewards() {
return new ArrayList<>(items);
}
@Override
public RewardListAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_reward, root, false);
return new RewardListAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(RewardListAdapter.ViewHolder vh, int position) {
Reward reward = items.get(position);
String displayAmount = reward.getDisplayAmount();
double rewardAmount = 0;
if (!"?".equals(displayAmount)) {
rewardAmount = Double.valueOf(displayAmount);
}
boolean hasTransaction = !Helper.isNullOrEmpty(reward.getTransactionId()) && reward.getTransactionId().length() > 7;
vh.iconClaimed.setVisibility(reward.isClaimed() ? View.VISIBLE : View.INVISIBLE);
vh.inputCustomCode.setVisibility(reward.isCustom() ? View.VISIBLE : View.GONE);
vh.buttonClaimCustom.setVisibility(reward.isCustom() ? View.VISIBLE : View.GONE);
vh.textTitle.setText(reward.getRewardTitle());
vh.textDescription.setText(reward.getRewardDescription());
vh.upTo.setVisibility(reward.shouldDisplayRange() ? View.VISIBLE : View.GONE);
vh.textLbcValue.setText(reward.isCustom() ? "?" : Helper.LBC_CURRENCY_FORMAT.format(Helper.parseDouble(reward.getDisplayAmount(), 0)));
vh.textLinkTransaction.setVisibility(hasTransaction ? View.VISIBLE : View.GONE);
vh.textLinkTransaction.setText(hasTransaction ? reward.getTransactionId().substring(0, 7) : null);
vh.textLinkTransaction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (context != null) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s/%s", Helper.EXPLORER_TX_PREFIX, reward.getTransactionId())));
context.startActivity(intent);
}
}
});
vh.textUsdValue.setText(reward.isCustom() || Lbryio.LBCUSDRate == 0 ? null :
String.format("≈$%s", Helper.USD_CURRENCY_FORMAT.format(rewardAmount * Lbryio.LBCUSDRate)));
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (reward.isClaimed()) {
return;
}
if (clickListener != null) {
clickListener.onRewardClicked(reward, vh.loading);
}
}
});
vh.inputCustomCode.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) {
String value = charSequence.toString().trim();
vh.buttonClaimCustom.setEnabled(value.length() > 0);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
vh.buttonClaimCustom.setOnClickListener(new View.OnClickListener() {
@Override
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();
return;
}
if (clickListener != null) {
clickListener.onCustomClaimButtonClicked(claimCode, vh.inputCustomCode, vh.buttonClaimCustom, vh.loading);
}
}
});
}
public interface RewardClickListener {
void onRewardClicked(Reward reward, View loadingView);
void onCustomClaimButtonClicked(String code, EditText inputCustomCode, MaterialButton buttonClaim, View loadingView);
}
}
@@ -0,0 +1,127 @@
package io.lbry.browser.adapter;
import android.content.Context;
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 com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
import io.lbry.browser.listener.ChannelItemSelectionListener;
import io.lbry.browser.utils.Helper;
import lombok.Setter;
public class SuggestedChannelGridAdapter extends RecyclerView.Adapter<SuggestedChannelGridAdapter.ViewHolder> {
private Context context;
private List<Claim> items;
private List<Claim> selectedItems;
@Setter
private ChannelItemSelectionListener listener;
public SuggestedChannelGridAdapter(List<Claim> items, Context context) {
this.items = new ArrayList<>(items);
this.selectedItems = new ArrayList<>();
this.context = context;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected View noThumbnailView;
protected ImageView thumbnailView;
protected TextView alphaView;
protected TextView titleView;
protected TextView tagView;
public ViewHolder(View v) {
super(v);
noThumbnailView = v.findViewById(R.id.suggested_channel_no_thumbnail);
alphaView = v.findViewById(R.id.suggested_channel_alpha_view);
thumbnailView = v.findViewById(R.id.suggested_channel_thumbnail);
titleView = v.findViewById(R.id.suggested_channel_title);
tagView = v.findViewById(R.id.suggested_channel_tag);
}
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
public int getSelectedCount() { return selectedItems.size(); }
public void clearItems() {
items.clear();
notifyDataSetChanged();
}
public List<Claim> getSelectedItems() {
return this.selectedItems;
}
public void clearSelectedItems() {
this.selectedItems.clear();
}
public boolean isClaimSelected(Claim claim) {
return selectedItems.contains(claim);
}
public void addClaims(List<Claim> claims) {
for (Claim claim : claims) {
if (!items.contains(claim)) {
items.add(claim);
}
}
notifyDataSetChanged();
}
@Override
public SuggestedChannelGridAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_suggested_channel, root, false);
return new SuggestedChannelGridAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(SuggestedChannelGridAdapter.ViewHolder vh, int position) {
Claim claim = items.get(position);
String thumbnailUrl = claim.getThumbnailUrl();
int bgColor = Helper.generateRandomColorForValue(claim.getClaimId());
Helper.setIconViewBackgroundColor(vh.noThumbnailView, bgColor, false, context);
vh.noThumbnailView.setVisibility(Helper.isNullOrEmpty(thumbnailUrl) ? View.INVISIBLE : View.VISIBLE);
vh.alphaView.setText(claim.getName().substring(1, 2));
if (!Helper.isNullOrEmpty(thumbnailUrl)) {
vh.thumbnailView.setVisibility(View.VISIBLE);
Glide.with(context.getApplicationContext()).load(thumbnailUrl).apply(RequestOptions.circleCropTransform()).into(vh.thumbnailView);
} else {
vh.thumbnailView.setVisibility(View.GONE);
}
vh.titleView.setText(Helper.isNullOrEmpty(claim.getTitle()) ? claim.getName() : claim.getTitle());
String firstTag = claim.getFirstTag();
vh.tagView.setVisibility(Helper.isNullOrEmpty(firstTag) ? View.INVISIBLE : View.VISIBLE);
vh.tagView.setBackgroundResource(R.drawable.bg_tag);
vh.tagView.setText(firstTag);
vh.itemView.setSelected(isClaimSelected(claim));
vh.itemView.setOnClickListener(view -> {
if (selectedItems.contains(claim)) {
selectedItems.remove(claim);
if (listener != null) {
listener.onChannelItemDeselected(claim);
}
} else {
selectedItems.add(claim);
if (listener != null) {
listener.onChannelItemSelected(claim);
}
}
notifyDataSetChanged();
});
}
}
@@ -0,0 +1,108 @@
package io.lbry.browser.adapter;
import android.content.Context;
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 java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.Tag;
import lombok.Getter;
import lombok.Setter;
public class TagListAdapter extends RecyclerView.Adapter<TagListAdapter.ViewHolder> {
public static final int CUSTOMIZE_MODE_NONE = 0;
public static final int CUSTOMIZE_MODE_ADD = 1;
public static final int CUSTOMIZE_MODE_REMOVE = 2;
private Context context;
private List<Tag> items;
@Setter
private TagClickListener clickListener;
@Getter
@Setter
private int customizeMode;
public TagListAdapter(List<Tag> tags, Context context) {
this.context = context;
this.items = new ArrayList<>(tags);
this.customizeMode = CUSTOMIZE_MODE_NONE;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected ImageView iconView;
protected TextView nameView;
public ViewHolder(View v) {
super(v);
iconView = v.findViewById(R.id.tag_action);
nameView = v.findViewById(R.id.tag_name);
}
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
public void addTag(Tag tag) {
if (!items.contains(tag)) {
items.add(tag);
}
notifyDataSetChanged();
}
public List<Tag> getTags() {
return new ArrayList<>(items);
}
public void setTags(List<Tag> tags) {
items = new ArrayList<>(tags);
notifyDataSetChanged();
}
public void addTags(List<Tag> tags) {
for (Tag tag : tags) {
if (!items.contains(tag)) {
items.add(tag);
}
}
notifyDataSetChanged();
}
public void removeTag(Tag tag) {
items.remove(tag);
notifyDataSetChanged();
}
@Override
public TagListAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_tag, root, false);
return new TagListAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(TagListAdapter.ViewHolder vh, int position) {
Tag tag = items.get(position);
vh.nameView.setText(tag.getName().toLowerCase());
vh.iconView.setVisibility(customizeMode == CUSTOMIZE_MODE_NONE ? View.GONE : View.VISIBLE);
vh.iconView.setImageResource(customizeMode == CUSTOMIZE_MODE_REMOVE ? R.drawable.ic_close : R.drawable.ic_add);
vh.itemView.setBackgroundResource(tag.isMature() ? R.drawable.bg_tag_mature : R.drawable.bg_tag);
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (clickListener != null) {
clickListener.onTagClicked(tag, customizeMode);
}
}
});
}
public interface TagClickListener {
void onTagClicked(Tag tag, int customizeMode);
}
}
@@ -0,0 +1,132 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.Transaction;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
public class TransactionListAdapter extends RecyclerView.Adapter<TransactionListAdapter.ViewHolder> {
private static final DecimalFormat TX_LIST_AMOUNT_FORMAT = new DecimalFormat("#,##0.0000");
private static final SimpleDateFormat TX_LIST_DATE_FORMAT = new SimpleDateFormat("MMM d");
private Context context;
private List<Transaction> items;
@Setter
private TransactionClickListener listener;
public TransactionListAdapter(List<Transaction> transactions, Context context) {
this.context = context;
this.items = new ArrayList<>(transactions);
}
public void clear() {
items.clear();
notifyDataSetChanged();
}
public List<Transaction> getItems() {
return new ArrayList<>(items);
}
public void addTransactions(List<Transaction> transactions) {
for (Transaction tx : transactions) {
if (!items.contains(tx)) {
items.add(tx);
}
}
notifyDataSetChanged();
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
@Override
public TransactionListAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_transaction, root, false);
return new TransactionListAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(TransactionListAdapter.ViewHolder vh, int position) {
Transaction item = items.get(position);
vh.descView.setText(item.getDescriptionStringId());
vh.amountView.setText(TX_LIST_AMOUNT_FORMAT.format(item.getValue().doubleValue()));
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.infoFeeContainer.setVisibility(!Helper.isNullOrEmpty(item.getClaim()) || Math.abs(item.getFee().doubleValue()) > 0 ?
View.VISIBLE : View.GONE);
vh.claimView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
LbryUri claimUrl = item.getClaimUrl();
if (claimUrl != null && listener != null) {
listener.onClaimUrlClicked(claimUrl);
}
}
});
vh.txidLinkView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (context != null) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(String.format("%s/%s", Helper.EXPLORER_TX_PREFIX, item.getTxid())));
context.startActivity(intent);
}
}
});
vh.itemView.setOnClickListener(view -> {
if (listener != null) {
listener.onTransactionClicked(item);
}
});
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected TextView descView;
protected TextView amountView;
protected TextView claimView;
protected TextView feeView;
protected TextView txidLinkView;
protected TextView dateView;
protected View infoFeeContainer;
public ViewHolder(View v) {
super(v);
descView = v.findViewById(R.id.transaction_desc);
amountView = v.findViewById(R.id.transaction_amount);
claimView = v.findViewById(R.id.transaction_claim);
feeView = v.findViewById(R.id.transaction_fee);
txidLinkView = v.findViewById(R.id.transaction_id_link);
dateView = v.findViewById(R.id.transaction_date);
infoFeeContainer = v.findViewById(R.id.transaction_info_fee_container);
}
}
public interface TransactionClickListener {
void onTransactionClicked(Transaction transaction);
void onClaimUrlClicked(LbryUri uri);
}
}
@@ -0,0 +1,147 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
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;
public class UrlSuggestionListAdapter extends RecyclerView.Adapter<UrlSuggestionListAdapter.ViewHolder> {
private Context context;
private List<UrlSuggestion> items;
@Setter
private UrlSuggestionClickListener listener;
public UrlSuggestionListAdapter(Context context) {
this.context = context;
this.items = new ArrayList<>();
}
public void clear() {
items.clear();
notifyDataSetChanged();
}
public List<UrlSuggestion> getItems() {
return new ArrayList<>(items);
}
public List<String> getItemUrls() {
List<String> uris = new ArrayList<>();
for (int i = 0; i < items.size(); i++) {
LbryUri uri = items.get(i).getUri();
if (uri != null) {
uris.add(uri.toString());
}
}
return uris;
}
public void setClaimForUrl(LbryUri url, Claim claim) {
for (int i = 0; i < items.size(); i++) {
LbryUri thisUrl = items.get(i).getUri();
try {
if (thisUrl != null) {
LbryUri vanity = LbryUri.parse(thisUrl.toVanityString());
if (thisUrl.equals(url) || vanity.equals(url)) {
items.get(i).setClaim(claim);
}
}
} catch (LbryUriException ex) {
// pass
}
}
}
public void addUrlSuggestions(List<UrlSuggestion> urlSuggestions) {
for (UrlSuggestion urlSuggestion : urlSuggestions) {
if (!items.contains(urlSuggestion)) {
items.add(urlSuggestion);
}
}
notifyDataSetChanged();
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
@Override
public UrlSuggestionListAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_url_suggestion, root, false);
return new UrlSuggestionListAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(UrlSuggestionListAdapter.ViewHolder vh, int position) {
UrlSuggestion item = items.get(position);
String fullTitle, desc;
int iconStringId;
switch (item.getType()) {
case UrlSuggestion.TYPE_CHANNEL:
iconStringId = R.string.fa_at;
fullTitle = item.getTitle();
desc = item.getClaim() != null ? item.getClaim().getTitle() :
((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;
fullTitle = String.format(context.getString(R.string.tag_url_title), item.getText());
desc = String.format(context.getString(R.string.explore_tag_url_desc), item.getText());
break;
case UrlSuggestion.TYPE_SEARCH:
iconStringId = R.string.fa_search;
fullTitle = String.format(context.getString(R.string.search_url_title), item.getText());
desc = String.format(context.getString(R.string.search_url_desc), item.getText());
break;
case UrlSuggestion.TYPE_FILE:
default:
iconStringId = R.string.fa_file;
fullTitle = item.getTitle();
desc = item.getClaim() != null ? item.getClaim().getTitle() :
((item.isUseTextAsDescription() && !Helper.isNullOrEmpty(item.getText())) ? item.getText() : String.format(context.getString(R.string.view_file_url_desc), item.getText()));
break;
}
vh.iconView.setText(iconStringId);
vh.titleView.setText(fullTitle);
vh.descView.setText(desc);
vh.itemView.setOnClickListener(view -> {
if (listener != null) {
listener.onUrlSuggestionClicked(item);
}
});
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected SolidIconView iconView;
protected TextView titleView;
protected TextView descView;
public ViewHolder(View v) {
super(v);
iconView = v.findViewById(R.id.url_suggestion_icon);
titleView = v.findViewById(R.id.url_suggestion_title);
descView = v.findViewById(R.id.url_suggestion_description);
}
}
public interface UrlSuggestionClickListener {
void onUrlSuggestionClicked(UrlSuggestion urlSuggestion);
}
}
@@ -0,0 +1,71 @@
package io.lbry.browser.adapter;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
import io.lbry.browser.listener.SignInListener;
import io.lbry.browser.listener.WalletSyncListener;
import io.lbry.browser.ui.verification.EmailVerificationFragment;
import io.lbry.browser.ui.verification.ManualVerificationFragment;
import io.lbry.browser.ui.verification.PhoneVerificationFragment;
import io.lbry.browser.ui.verification.WalletVerificationFragment;
import lombok.SneakyThrows;
/**
* 4 fragments
* - Email collect / verify (sign in)
* - Phone number collect / verify (rewards)
* - Wallet password
* - Manual verification page
*/
public class VerificationPagerAdapter extends FragmentStateAdapter {
public static final int PAGE_VERIFICATION_EMAIL = 0;
public static final int PAGE_VERIFICATION_PHONE = 1;
public static final int PAGE_VERIFICATION_WALLET = 2;
public static final int PAGE_VERIFICATION_MANUAL = 3;
private FragmentActivity activity;
public VerificationPagerAdapter(FragmentActivity activity) {
super(activity);
this.activity = activity;
}
@SneakyThrows
@Override
public Fragment createFragment(int position) {
switch (position) {
case 0:
default:
EmailVerificationFragment evFragment = EmailVerificationFragment.class.newInstance();
if (activity instanceof SignInListener) {
evFragment.setListener((SignInListener) activity);
}
return evFragment;
case 1:
PhoneVerificationFragment pvFragment = PhoneVerificationFragment.class.newInstance();
if (activity instanceof SignInListener) {
pvFragment.setListener((SignInListener) activity);
}
return pvFragment;
case 2:
WalletVerificationFragment wvFragment = WalletVerificationFragment.class.newInstance();
if (activity instanceof WalletSyncListener) {
wvFragment.setListener((WalletSyncListener) activity);
}
return wvFragment;
case 3:
ManualVerificationFragment mvFragment = ManualVerificationFragment.class.newInstance();
if (activity instanceof SignInListener) {
mvFragment.setListener((SignInListener) activity);
}
return mvFragment;
}
}
@Override
public int getItemCount() {
return 4;
}
}
@@ -0,0 +1,237 @@
package io.lbry.browser.data;
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;
import java.util.List;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.model.Tag;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.model.ViewHistory;
import io.lbry.browser.model.lbryinc.Subscription;
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 String DATABASE_NAME = "LbryApp.db";
private static DatabaseHelper instance;
private static final String[] SQL_CREATE_TABLES = {
// local subscription store
"CREATE TABLE subscriptions (url TEXT PRIMARY KEY NOT NULL, channel_name TEXT NOT NULL)",
// url entry / suggestion history
"CREATE TABLE url_history (id INTEGER PRIMARY KEY NOT NULL, value TEXT NOT NULL, url TEXT, type INTEGER NOT NULL, timestamp TEXT NOT NULL)",
// tags (known and followed)
"CREATE TABLE tags (id INTEGER PRIMARY KEY NOT NULL, name TEXT NOT NULL, is_followed INTEGER NOT NULL)",
// view history (stores only stream claims that have resolved)
"CREATE TABLE view_history (" +
" id INTEGER PRIMARY KEY NOT NULL" +
", url TEXT NOT NULL" +
", claim_id TEXT" +
", claim_name TEXT" +
", cost REAL " +
", title TEXT " +
", publisher_claim_id TEXT" +
", publisher_name TEXT" +
", publisher_title TEXT" +
", thumbnail_url TEXT" +
", release_time INTEGER " +
", device TEXT" +
", timestamp TEXT NOT NULL)"
};
private static final String[] SQL_CREATE_INDEXES = {
"CREATE UNIQUE INDEX idx_subscription_url ON subscriptions (url)",
"CREATE UNIQUE INDEX idx_url_history_value ON url_history (value)",
"CREATE UNIQUE INDEX idx_url_history_url ON url_history (url)",
"CREATE UNIQUE INDEX idx_tag_name ON tags (name)",
"CREATE UNIQUE INDEX idx_view_history_url_device ON view_history (url, device)",
"CREATE INDEX idx_view_history_device ON view_history (device)"
};
private static final String SQL_INSERT_SUBSCRIPTION = "REPLACE INTO subscriptions (channel_name, url) VALUES (?, ?)";
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_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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_GET_VIEW_HISTORY =
"SELECT url, claim_id, claim_name, cost, 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 < ?";
private static final String SQL_CLEAR_VIEW_HISTORY_BY_DEVICE_BEFORE_TIME = "DELETE FROM view_history WHERE device = ? AND timestamp < ?";
private static final String SQL_INSERT_TAG = "REPLACE INTO tags (name, is_followed) VALUES (?, ?)";
private static final String SQL_GET_KNOWN_TAGS = "SELECT name, is_followed FROM tags";
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) {
db.execSQL(sql);
}
for (String sql : SQL_CREATE_INDEXES) {
db.execSQL(sql);
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public static void createOrUpdateUrlHistoryItem(String text, String url, int type, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_URL_HISTORY, new Object[] {
text, url, type, new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).format(new Date())
});
}
public static void clearUrlHistory(SQLiteDatabase db) {
db.execSQL(SQL_CLEAR_URL_HISTORY);
}
public static void clearUrlHistoryBefore(Date date, SQLiteDatabase db) {
db.execSQL(SQL_CLEAR_URL_HISTORY_BEFORE_TIME, new Object[] { new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).format(new Date()) });
}
// History items are essentially url suggestions
public static List<UrlSuggestion> getRecentHistory(SQLiteDatabase db) {
List<UrlSuggestion> suggestions = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_RECENT_URL_HISTORY, null);
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));
suggestion.setTitleUrlOnly(true);
suggestions.add(suggestion);
}
} finally {
Helper.closeCursor(cursor);
}
return suggestions;
}
// View history items are stream claims
public static void createOrUpdateViewHistoryItem(ViewHistory viewHistory, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_VIEW_HISTORY, new Object[] {
viewHistory.getUri().toString(),
viewHistory.getClaimId(),
viewHistory.getClaimName(),
viewHistory.getCost() != null ? viewHistory.getCost().doubleValue() : 0,
viewHistory.getTitle(),
viewHistory.getPublisherClaimId(),
viewHistory.getPublisherName(),
viewHistory.getPublisherTitle(),
viewHistory.getThumbnailUrl(),
viewHistory.getDevice(),
viewHistory.getReleaseTime(),
new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).format(new Date())
});
}
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.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 });
}
public static void setAllTagsUnfollowed(SQLiteDatabase db) {
db.execSQL(SQL_UNFOLLOW_TAGS);
}
public static List<Tag> getTags(SQLiteDatabase db) {
List<Tag> tags = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_KNOWN_TAGS, null);
while (cursor.moveToNext()) {
Tag tag = new Tag();
tag.setName(cursor.getString(0));
tag.setFollowed(cursor.getInt(1) == 1);
tags.add(tag);
}
} finally {
Helper.closeCursor(cursor);
}
return tags;
}
public static void createOrUpdateSubscription(Subscription subscription, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_SUBSCRIPTION, new Object[] { subscription.getChannelName(), subscription.getUrl() });
}
public static void deleteSubscription(Subscription subscription, SQLiteDatabase db) {
db.execSQL(SQL_DELETE_SUBSCRIPTION, new Object[] { subscription.getUrl() });
}
public static List<Subscription> getSubscriptions(SQLiteDatabase db) {
List<Subscription> subscriptions = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_SUBSCRIPTIONS, null);
while (cursor.moveToNext()) {
Subscription subscription = new Subscription();
subscription.setChannelName(cursor.getString(0));
subscription.setUrl(cursor.getString(1));
subscriptions.add(subscription);
}
} finally {
Helper.closeCursor(cursor);
}
return subscriptions;
}
}
@@ -0,0 +1,112 @@
package io.lbry.browser.dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import io.lbry.browser.R;
import lombok.Setter;
public class ContentFromDialogFragment extends BottomSheetDialogFragment {
public static final String TAG = "ContentFromDialog";
public static final int ITEM_FROM_PAST_24_HOURS = 1;
public static final int ITEM_FROM_PAST_WEEK = 2;
public static final int ITEM_FROM_PAST_MONTH = 3;
public static final int ITEM_FROM_PAST_YEAR = 4;
public static final int ITEM_FROM_ALL_TIME = 5;
@Setter
private ContentFromListener contentFromListener;
private int currentFromItem;
public static ContentFromDialogFragment newInstance() {
return new ContentFromDialogFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_content_from, container,false);
ContentFromItemClickListener clickListener = new ContentFromItemClickListener(this, contentFromListener);
view.findViewById(R.id.content_from_past_24_hours_item).setOnClickListener(clickListener);
view.findViewById(R.id.content_from_past_week_item).setOnClickListener(clickListener);
view.findViewById(R.id.content_from_past_month_item).setOnClickListener(clickListener);
view.findViewById(R.id.content_from_past_year_item).setOnClickListener(clickListener);
view.findViewById(R.id.content_from_all_time_item).setOnClickListener(clickListener);
checkSelectedFromItem(currentFromItem, view);
return view;
}
public static void checkSelectedFromItem(int fromItem, View parent) {
int checkViewId = -1;
switch (fromItem) {
case ITEM_FROM_PAST_24_HOURS: checkViewId = R.id.content_from_past_24_hours_item_selected; break;
case ITEM_FROM_PAST_WEEK: checkViewId = R.id.content_from_past_week_item_selected; break;
case ITEM_FROM_PAST_MONTH: checkViewId = R.id.content_from_past_month_item_selected; break;
case ITEM_FROM_PAST_YEAR: checkViewId = R.id.content_from_past_year_item_selected; break;
case ITEM_FROM_ALL_TIME: checkViewId = R.id.content_from_all_time_item_selected; break;
}
if (parent != null && checkViewId > -1) {
parent.findViewById(checkViewId).setVisibility(View.VISIBLE);
}
}
public void setCurrentFromItem(int fromItem) {
this.currentFromItem = fromItem;
}
private static class ContentFromItemClickListener implements View.OnClickListener {
private final int[] checkViewIds = {
R.id.content_from_past_24_hours_item,
R.id.content_from_past_week_item,
R.id.content_from_past_month_item,
R.id.content_from_past_year_item,
R.id.content_from_all_time_item
};
private BottomSheetDialogFragment dialog;
private ContentFromListener listener;
public ContentFromItemClickListener(BottomSheetDialogFragment dialog, ContentFromListener listener) {
this.dialog = dialog;
this.listener = listener;
}
public void onClick(View view) {
int currentFromItem = -1;
if (dialog != null) {
View dialogView = dialog.getView();
if (dialogView != null) {
for (int id : checkViewIds) {
dialogView.findViewById(id).setVisibility(View.GONE);
}
}
}
switch (view.getId()) {
case R.id.content_from_past_24_hours_item: currentFromItem = ITEM_FROM_PAST_24_HOURS; break;
case R.id.content_from_past_week_item: currentFromItem = ITEM_FROM_PAST_WEEK; break;
case R.id.content_from_past_month_item: currentFromItem = ITEM_FROM_PAST_MONTH; break;
case R.id.content_from_past_year_item: currentFromItem = ITEM_FROM_PAST_YEAR; break;
case R.id.content_from_all_time_item: currentFromItem = ITEM_FROM_ALL_TIME; break;
}
checkSelectedFromItem(currentFromItem, view);
if (listener != null) {
listener.onContentFromItemSelected(currentFromItem);
}
if (dialog != null) {
dialog.dismiss();
}
}
}
public interface ContentFromListener {
void onContentFromItemSelected(int contentFromItem);
}
}
@@ -0,0 +1,96 @@
package io.lbry.browser.dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import io.lbry.browser.R;
import lombok.Setter;
public class ContentScopeDialogFragment extends BottomSheetDialogFragment {
public static final String TAG = "ContentScopeDialog";
public static final int ITEM_EVERYONE = 1;
public static final int ITEM_TAGS = 2;
@Setter
private ContentScopeListener contentScopeListener;
private int currentScopeItem;
public static ContentScopeDialogFragment newInstance() {
return new ContentScopeDialogFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_content_scope, container,false);
ContentScopeItemClickListener clickListener = new ContentScopeItemClickListener(this, contentScopeListener);
view.findViewById(R.id.content_scope_everyone_item).setOnClickListener(clickListener);
view.findViewById(R.id.content_scope_tags_item).setOnClickListener(clickListener);
checkSelectedScopeItem(currentScopeItem, view);
return view;
}
public static void checkSelectedScopeItem(int scope, View parent) {
int checkViewId = -1;
switch (scope) {
case ITEM_EVERYONE: checkViewId = R.id.content_scope_everyone_item_selected; break;
case ITEM_TAGS: checkViewId = R.id.content_scope_tags_item_selected; break;
}
if (parent != null && checkViewId > -1) {
parent.findViewById(checkViewId).setVisibility(View.VISIBLE);
}
}
public void setCurrentScopeItem(int scopeItem) {
this.currentScopeItem = scopeItem;
}
private static class ContentScopeItemClickListener implements View.OnClickListener {
private final int[] checkViewIds = {
R.id.content_scope_everyone_item_selected, R.id.content_scope_tags_item_selected
};
private BottomSheetDialogFragment dialog;
private ContentScopeListener listener;
public ContentScopeItemClickListener(BottomSheetDialogFragment dialog, ContentScopeListener listener) {
this.dialog = dialog;
this.listener = listener;
}
public void onClick(View view) {
int scopeItem = -1;
if (dialog != null) {
View dialogView = dialog.getView();
if (dialogView != null) {
for (int id : checkViewIds) {
dialogView.findViewById(id).setVisibility(View.GONE);
}
}
}
switch (view.getId()) {
case R.id.content_scope_everyone_item: scopeItem = ITEM_EVERYONE; break;
case R.id.content_scope_tags_item: scopeItem = ITEM_TAGS; break;
}
checkSelectedScopeItem(scopeItem, view);
if (listener != null) {
listener.onContentScopeItemSelected(scopeItem);
}
if (dialog != null) {
dialog.dismiss();
}
}
}
public interface ContentScopeListener {
void onContentScopeItemSelected(int scopeItem);
}
}
@@ -0,0 +1,100 @@
package io.lbry.browser.dialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import io.lbry.browser.R;
import lombok.Setter;
public class ContentSortDialogFragment extends BottomSheetDialogFragment {
public static final String TAG = "ContentSortDialog";
public static final int ITEM_SORT_BY_TRENDING = 1;
public static final int ITEM_SORT_BY_NEW = 2;
public static final int ITEM_SORT_BY_TOP = 3;
@Setter
private SortByListener sortByListener;
private int currentSortByItem;
public static ContentSortDialogFragment newInstance() {
return new ContentSortDialogFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_content_sort, container,false);
SortByItemClickListener clickListener = new SortByItemClickListener(this, sortByListener);
view.findViewById(R.id.sort_by_trending_item).setOnClickListener(clickListener);
view.findViewById(R.id.sort_by_new_item).setOnClickListener(clickListener);
view.findViewById(R.id.sort_by_top_item).setOnClickListener(clickListener);
checkSelectedSortByItem(currentSortByItem, view);
return view;
}
public static void checkSelectedSortByItem(int sortByItem, View parent) {
int checkViewId = -1;
switch (sortByItem) {
case ITEM_SORT_BY_TRENDING: checkViewId = R.id.sort_by_trending_item_selected; break;
case ITEM_SORT_BY_NEW: checkViewId = R.id.sort_by_new_item_selected; break;
case ITEM_SORT_BY_TOP: checkViewId = R.id.sort_by_top_item_selected; break;
}
if (parent != null && checkViewId > -1) {
parent.findViewById(checkViewId).setVisibility(View.VISIBLE);
}
}
public void setCurrentSortByItem(int sortByItem) {
this.currentSortByItem = sortByItem;
}
private static class SortByItemClickListener implements View.OnClickListener {
private final int[] checkViewIds = {
R.id.sort_by_trending_item_selected, R.id.sort_by_new_item_selected, R.id.sort_by_top_item_selected
};
private BottomSheetDialogFragment dialog;
private SortByListener listener;
public SortByItemClickListener(BottomSheetDialogFragment dialog, SortByListener listener) {
this.dialog = dialog;
this.listener = listener;
}
public void onClick(View view) {
int selectedSortByItem = -1;
if (dialog != null) {
View dialogView = dialog.getView();
if (dialogView != null) {
for (int id : checkViewIds) {
dialogView.findViewById(id).setVisibility(View.GONE);
}
}
}
switch (view.getId()) {
case R.id.sort_by_trending_item: selectedSortByItem = ITEM_SORT_BY_TRENDING; break;
case R.id.sort_by_new_item: selectedSortByItem = ITEM_SORT_BY_NEW; break;
case R.id.sort_by_top_item: selectedSortByItem = ITEM_SORT_BY_TOP; break;
}
checkSelectedSortByItem(selectedSortByItem, view);
if (listener != null) {
listener.onSortByItemSelected(selectedSortByItem);
}
if (dialog != null) {
dialog.dismiss();
}
}
}
public interface SortByListener {
void onSortByItemSelected(int sortBy);
}
}
@@ -0,0 +1,180 @@
package io.lbry.browser.dialog;
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 androidx.recyclerview.widget.RecyclerView;
import com.google.android.flexbox.FlexboxLayoutManager;
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.util.ArrayList;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.adapter.TagListAdapter;
import io.lbry.browser.listener.TagListener;
import io.lbry.browser.model.Tag;
import io.lbry.browser.tasks.UpdateSuggestedTagsTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import lombok.Setter;
public class CustomizeTagsDialogFragment extends BottomSheetDialogFragment {
public static final String TAG = "CustomizeTagsDialog";
private static final int SUGGESTED_LIMIT = 8;
private String currentFilter;
private RecyclerView followedTagsList;
private RecyclerView suggestedTagsList;
private TagListAdapter followedTagsAdapter;
private TagListAdapter suggestedTagsAdapter;
private View noTagsView;
private View noResultsView;
@Setter
private TagListener listener;
private void checkNoTags() {
Helper.setViewVisibility(noTagsView, followedTagsAdapter == null || followedTagsAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
private void checkNoResults() {
Helper.setViewVisibility(noResultsView, suggestedTagsAdapter == null || suggestedTagsAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
public void addTag(Tag tag) {
if (followedTagsAdapter.getTags().contains(tag)) {
Snackbar.make(getView(), getString(R.string.tag_already_added, tag.getName()), Snackbar.LENGTH_LONG).show();
return;
}
tag.setFollowed(true);
followedTagsAdapter.addTag(tag);
if (suggestedTagsAdapter != null) {
suggestedTagsAdapter.removeTag(tag);
}
updateKnownTags(currentFilter, SUGGESTED_LIMIT, false);
if (listener != null) {
listener.onTagAdded(tag);
}
checkNoTags();
checkNoResults();
}
public void removeTag(Tag tag) {
tag.setFollowed(false);
followedTagsAdapter.removeTag(tag);
updateKnownTags(currentFilter, SUGGESTED_LIMIT, false);
if (listener != null) {
listener.onTagRemoved(tag);
}
checkNoTags();
checkNoResults();
}
public void setFilter(String filter) {
currentFilter = filter;
updateKnownTags(currentFilter, SUGGESTED_LIMIT, true);
}
public static CustomizeTagsDialogFragment newInstance() {
return new CustomizeTagsDialogFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_customize_tags, container, false);
noResultsView = view.findViewById(R.id.customize_no_tag_results);
noTagsView = view.findViewById(R.id.customize_no_followed_tags);
followedTagsAdapter = new TagListAdapter(Lbry.followedTags, getContext());
followedTagsAdapter.setCustomizeMode(TagListAdapter.CUSTOMIZE_MODE_REMOVE);
followedTagsAdapter.setClickListener(customizeTagClickListener);
suggestedTagsAdapter = new TagListAdapter(new ArrayList<>(), getContext());
suggestedTagsAdapter.setCustomizeMode(TagListAdapter.CUSTOMIZE_MODE_ADD);
suggestedTagsAdapter.setClickListener(customizeTagClickListener);
FlexboxLayoutManager flm1 = new FlexboxLayoutManager(getContext());
followedTagsList = view.findViewById(R.id.customize_tags_followed_list);
followedTagsList.setLayoutManager(flm1);
followedTagsList.setAdapter(followedTagsAdapter);
FlexboxLayoutManager flm2 = new FlexboxLayoutManager(getContext());
suggestedTagsList = view.findViewById(R.id.customize_tags_suggested_list);
suggestedTagsList.setLayoutManager(flm2);
suggestedTagsList.setAdapter(suggestedTagsAdapter);
TextInputEditText filterInput = view.findViewById(R.id.customize_tag_filter_input);
filterInput.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) {
String value = Helper.getValue(charSequence);
setFilter(value);
}
@Override
public void afterTextChanged(Editable editable) {
}
});
MaterialButton doneButton = view.findViewById(R.id.customize_done_button);
doneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
checkNoTags();
return view;
}
private TagListAdapter.TagClickListener customizeTagClickListener = new TagListAdapter.TagClickListener() {
@Override
public void onTagClicked(Tag tag, int customizeMode) {
if (customizeMode == TagListAdapter.CUSTOMIZE_MODE_ADD) {
addTag(tag);
} else if (customizeMode == TagListAdapter.CUSTOMIZE_MODE_REMOVE) {
removeTag(tag);
}
}
};
public void onResume() {
super.onResume();
updateKnownTags(null, SUGGESTED_LIMIT, true);
}
private void updateKnownTags(String filter, int limit, boolean clearPrevious) {
UpdateSuggestedTagsTask task = new UpdateSuggestedTagsTask(filter, SUGGESTED_LIMIT, followedTagsAdapter, suggestedTagsAdapter, clearPrevious, new UpdateSuggestedTagsTask.KnownTagsHandler() {
@Override
public void onSuccess(List<Tag> tags) {
if (suggestedTagsAdapter == null) {
suggestedTagsAdapter = new TagListAdapter(tags, getContext());
suggestedTagsAdapter.setCustomizeMode(TagListAdapter.CUSTOMIZE_MODE_ADD);
suggestedTagsAdapter.setClickListener(customizeTagClickListener);
if (suggestedTagsList != null) {
suggestedTagsList.setAdapter(suggestedTagsAdapter);
}
} else {
suggestedTagsAdapter.setTags(tags);
}
checkNoResults();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
@@ -0,0 +1,107 @@
package io.lbry.browser.dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import io.lbry.browser.R;
import io.lbry.browser.adapter.SuggestedChannelGridAdapter;
import lombok.Getter;
import lombok.Setter;
public class DiscoverDialogFragment extends BottomSheetDialogFragment {
public static final String TAG = "DiscoverDialog";
@Getter
private SuggestedChannelGridAdapter adapter;
@Setter
private DiscoverDialogListener dialogActionsListener;
public static DiscoverDialogFragment newInstance() {
return new DiscoverDialogFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_discover, container, false);
RecyclerView grid = view.findViewById(R.id.discover_channel_grid);
GridLayoutManager glm = new GridLayoutManager(getContext(), 3);
grid.setLayoutManager(glm);
grid.setAdapter(adapter);
grid.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
GridLayoutManager lm = (GridLayoutManager) recyclerView.getLayoutManager();
if (lm != null) {
int visibleItemCount = lm.getChildCount();
int totalItemCount = lm.getItemCount();
int pastVisibleItems = lm.findFirstVisibleItemPosition();
if (pastVisibleItems + visibleItemCount >= totalItemCount) {
if (dialogActionsListener != null) {
dialogActionsListener.onScrollEndReached();
}
}
}
}
});
MaterialButton doneButton = view.findViewById(R.id.discover_done_button);
doneButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
return view;
}
public void setAdapter(SuggestedChannelGridAdapter adapter) {
this.adapter = adapter;
if (getView() != null) {
((RecyclerView) getView().findViewById(R.id.discover_channel_grid)).setAdapter(adapter);
}
}
public void setLoading(boolean loading) {
if (getView() != null) {
getView().findViewById(R.id.discover_loading).setVisibility(loading ? View.VISIBLE : View.GONE);
}
}
@Override
public void onResume() {
super.onResume();
if (dialogActionsListener != null) {
dialogActionsListener.onResume();
}
}
@Override
public void onCancel(DialogInterface dialog) {
super.onDismiss(dialog);
if (dialogActionsListener != null) {
dialogActionsListener.onCancel();
}
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (dialogActionsListener != null) {
dialogActionsListener.onCancel();
}
}
public interface DiscoverDialogListener {
void onResume();
void onCancel();
void onScrollEndReached();
}
}
@@ -0,0 +1,291 @@
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.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSpinner;
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.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.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.tasks.claim.ClaimResultHandler;
import io.lbry.browser.tasks.claim.StreamRepostTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
public class RepostClaimDialogFragment extends BottomSheetDialogFragment implements WalletBalanceListener {
public static final String TAG = "RepostClaimDialog";
private MaterialButton buttonRepost;
private View linkCancel;
private TextInputEditText inputDeposit;
private View inlineBalanceContainer;
private TextView inlineBalanceValue;
private ProgressBar repostProgress;
private TextView textTitle;
private AppCompatSpinner channelSpinner;
private InlineChannelSpinnerAdapter channelSpinnerAdapter;
private TextView textNamePrefix;
private EditText inputName;
private TextView linkToggleAdvanced;
private View advancedContainer;
@Setter
private RepostClaimListener listener;
@Setter
private Claim claim;
public static RepostClaimDialogFragment newInstance() {
return new RepostClaimDialogFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_repost_claim, container, false);
buttonRepost = view.findViewById(R.id.repost_button);
linkCancel = view.findViewById(R.id.repost_cancel_link);
inputDeposit = view.findViewById(R.id.repost_input_deposit);
inlineBalanceContainer = view.findViewById(R.id.repost_inline_balance_container);
inlineBalanceValue = view.findViewById(R.id.repost_inline_balance_value);
repostProgress = view.findViewById(R.id.repost_progress);
textTitle = view.findViewById(R.id.repost_title);
channelSpinner = view.findViewById(R.id.repost_channel_spinner);
textNamePrefix = view.findViewById(R.id.repost_name_prefix);
inputName = view.findViewById(R.id.repost_name_input);
linkToggleAdvanced = view.findViewById(R.id.repost_toggle_advanced);
advancedContainer = view.findViewById(R.id.repost_advanced_container);
textTitle.setText(getString(R.string.repost_title, claim.getTitle()));
inputName.setText(claim.getName());
inputDeposit.setText(R.string.min_repost_deposit);
channelSpinner.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;
textNamePrefix.setText(String.format("%s%s/", LbryUri.PROTO_DEFAULT, claim.getName()));
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
inputDeposit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
inputDeposit.setHint(hasFocus ? getString(R.string.zero) : "");
inlineBalanceContainer.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
linkCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
linkToggleAdvanced.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (advancedContainer.getVisibility() != View.VISIBLE) {
advancedContainer.setVisibility(View.VISIBLE);
linkToggleAdvanced.setText(R.string.hide_advanced);
} else {
advancedContainer.setVisibility(View.GONE);
linkToggleAdvanced.setText(R.string.show_advanced);
}
}
});
buttonRepost.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
validateAndRepostClaim();
}
});
onWalletBalanceUpdated(Lbry.walletBalance);
return view;
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
fetchChannels();
}
public void onPause() {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).removeWalletBalanceListener(this);
}
inputDeposit.clearFocus();
super.onPause();
}
private void fetchChannels() {
if (Lbry.ownChannels == null || Lbry.ownChannels.size() == 0) {
startLoading();
ClaimListTask task = new ClaimListTask(Claim.TYPE_CHANNEL, repostProgress, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = new ArrayList<>(claims);
loadChannels(claims);
finishLoading();
}
@Override
public void onError(Exception error) {
// could not fetch channels
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).showError(error.getMessage());
}
dismiss();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
loadChannels(Lbry.ownChannels);
}
}
private void loadChannels(List<Claim> channels) {
if (channelSpinnerAdapter == null) {
Context context = getContext();
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, channels);
channelSpinnerAdapter.notifyDataSetChanged();
} else {
channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.notifyDataSetChanged();
}
if (channelSpinner != null) {
channelSpinner.setAdapter(channelSpinnerAdapter);
}
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void validateAndRepostClaim() {
String name = Helper.getValue(inputName.getText());
if (Helper.isNullOrEmpty(name) || !LbryUri.isNameValid(name)) {
showError(getString(R.string.repost_name_invalid_characters));
return;
}
String depositString = Helper.getValue(inputDeposit.getText());
if (Helper.isNullOrEmpty(depositString)) {
showError(getString(R.string.invalid_amount));
return;
}
BigDecimal bid = new BigDecimal(depositString);
if (bid.doubleValue() > Lbry.walletBalance.getAvailable().doubleValue()) {
showError(getString(R.string.insufficient_balance));
return;
}
Claim channel = (Claim) channelSpinner.getSelectedItem();
StreamRepostTask task = new StreamRepostTask(name, bid, claim.getClaimId(), channel.getClaimId(), repostProgress, new ClaimResultHandler() {
@Override
public void beforeStart() {
startLoading();
}
@Override
public void onSuccess(Claim claimResult) {
if (listener != null) {
listener.onClaimReposted(claimResult);
}
finishLoading();
dismiss();
}
@Override
public void onError(Exception error) {
showError(error.getMessage());
finishLoading();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
private void startLoading() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(false);
}
linkCancel.setEnabled(false);
buttonRepost.setEnabled(false);
inputName.setEnabled(false);
channelSpinner.setEnabled(false);
linkToggleAdvanced.setVisibility(View.INVISIBLE);
}
private void finishLoading() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(true);
}
linkCancel.setEnabled(true);
buttonRepost.setEnabled(true);
inputName.setEnabled(true);
channelSpinner.setEnabled(true);
linkToggleAdvanced.setVisibility(View.VISIBLE);
}
public interface RepostClaimListener {
void onClaimReposted(Claim claim);
}
}
@@ -0,0 +1,196 @@
package io.lbry.browser.dialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.core.text.HtmlCompat;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.tasks.wallet.SupportCreateTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import lombok.Setter;
public class SendTipDialogFragment extends BottomSheetDialogFragment implements WalletBalanceListener {
public static final String TAG = "SendTipDialog";
private MaterialButton sendButton;
private View cancelLink;
private TextInputEditText inputAmount;
private View inlineBalanceContainer;
private TextView inlineBalanceValue;
private ProgressBar sendProgress;
@Setter
private SendTipListener listener;
@Setter
private Claim claim;
public static SendTipDialogFragment newInstance() {
return new SendTipDialogFragment();
}
private void disableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(false);
}
sendButton.setEnabled(false);
cancelLink.setEnabled(false);
}
private void enableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(true);
}
sendButton.setEnabled(true);
cancelLink.setEnabled(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_send_tip, container, false);
inputAmount = view.findViewById(R.id.tip_input_amount);
inlineBalanceContainer = view.findViewById(R.id.tip_inline_balance_container);
inlineBalanceValue = view.findViewById(R.id.tip_inline_balance_value);
sendProgress = view.findViewById(R.id.tip_send_progress);
cancelLink = view.findViewById(R.id.tip_cancel_link);
sendButton = view.findViewById(R.id.tip_send);
inputAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
inputAmount.setHint(hasFocus ? getString(R.string.zero) : "");
inlineBalanceContainer.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
TextView infoText = view.findViewById(R.id.tip_info);
infoText.setMovementMethod(LinkMovementMethod.getInstance());
infoText.setText(HtmlCompat.fromHtml(
Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType()) ?
getString(R.string.send_tip_info_channel, claim.getTitleOrName()) :
getString(R.string.send_tip_info_content, claim.getTitleOrName()),
HtmlCompat.FROM_HTML_MODE_LEGACY));
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String amountString = Helper.getValue(inputAmount.getText());
if (Helper.isNullOrEmpty(amountString)) {
showError(getString(R.string.invalid_amount));
return;
}
BigDecimal amount = new BigDecimal(amountString);
if (amount.doubleValue() > Lbry.walletBalance.getAvailable().doubleValue()) {
showError(getString(R.string.insufficient_balance));
return;
}
SupportCreateTask task = new SupportCreateTask(claim.getClaimId(), amount, true, sendProgress, new GenericTaskHandler() {
@Override
public void beforeStart() {
disableControls();
}
@Override
public void onSuccess() {
enableControls();
if (listener != null) {
listener.onTipSent(amount);
}
dismiss();
}
@Override
public void onError(Exception error) {
showError(error.getMessage());
enableControls();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
cancelLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
String channel = null;
if (Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType())) {
channel = claim.getTitleOrName();
} else if (claim.getSigningChannel() != null) {
channel = claim.getPublisherTitle();
}
((TextView) view.findViewById(R.id.tip_send_title)).setText(
Helper.isNullOrEmpty(channel) ? getString(R.string.send_a_tip) : getString(R.string.send_a_tip_to, channel)
);
onWalletBalanceUpdated(Lbry.walletBalance);
return view;
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
}
public void onPause() {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).removeWalletBalanceListener(this);
}
super.onPause();
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
public interface SendTipListener {
void onTipSent(BigDecimal amount);
}
}
@@ -0,0 +1,13 @@
package io.lbry.browser.exceptions;
public class ApiCallException extends Exception {
public ApiCallException() {
super();
}
public ApiCallException(String message) {
super(message);
}
public ApiCallException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,13 @@
package io.lbry.browser.exceptions;
public class LbryRequestException extends Exception {
public LbryRequestException() {
super();
}
public LbryRequestException(String message) {
super(message);
}
public LbryRequestException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,13 @@
package io.lbry.browser.exceptions;
public class LbryResponseException extends Exception {
public LbryResponseException() {
super();
}
public LbryResponseException(String message) {
super(message);
}
public LbryResponseException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,13 @@
package io.lbry.browser.exceptions;
public class LbryUriException extends Exception {
public LbryUriException() {
super();
}
public LbryUriException(String message) {
super(message);
}
public LbryUriException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,13 @@
package io.lbry.browser.exceptions;
public class LbryioRequestException extends Exception {
public LbryioRequestException() {
super();
}
public LbryioRequestException(String message) {
super(message);
}
public LbryioRequestException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,25 @@
package io.lbry.browser.exceptions;
import lombok.Getter;
public class LbryioResponseException extends Exception {
@Getter
private int statusCode;
public LbryioResponseException() {
super();
}
public LbryioResponseException(String message) {
super(message);
}
public LbryioResponseException(String message, Throwable cause) {
super(message, cause);
}
public LbryioResponseException(String message, int statusCode) {
super(message);
this.statusCode = statusCode;
}
public LbryioResponseException(String message, Throwable cause, int statusCode) {
super(message, cause);
this.statusCode = statusCode;
}
}
@@ -0,0 +1,13 @@
package io.lbry.browser.exceptions;
public class WalletException extends Exception {
public WalletException() {
super();
}
public WalletException(String message) {
super(message);
}
public WalletException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,9 @@
package io.lbry.browser.listener;
import io.lbry.browser.model.Claim;
public interface ChannelItemSelectionListener {
void onChannelItemSelected(Claim claim);
void onChannelItemDeselected(Claim claim);
void onChannelSelectionCleared();
}
@@ -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 FetchChannelsListener {
void onChannelsFetched(List<Claim> channels);
}
@@ -0,0 +1,5 @@
package io.lbry.browser.listener;
public interface SdkStatusListener {
void onSdkReady();
}
@@ -0,0 +1,7 @@
package io.lbry.browser.listener;
public interface SelectionModeListener {
void onEnterSelectionMode();
void onExitSelectionMode();
void onItemSelectionToggled();
}
@@ -0,0 +1,10 @@
package io.lbry.browser.listener;
public interface SignInListener {
void onEmailAdded(String email);
void onEmailEdit();
void onEmailVerified();
void onPhoneAdded(String countryCode, String phoneNumber);
void onPhoneVerified();
void onManualVerifyContinue();
}
@@ -0,0 +1,6 @@
package io.lbry.browser.listener;
public interface StoragePermissionListener {
void onStoragePermissionGranted();
void onStoragePermissionRefused();
}
@@ -0,0 +1,8 @@
package io.lbry.browser.listener;
import io.lbry.browser.model.Tag;
public interface TagListener {
void onTagAdded(Tag tag);
void onTagRemoved(Tag tag);
}
@@ -0,0 +1,7 @@
package io.lbry.browser.listener;
import io.lbry.browser.model.WalletBalance;
public interface WalletBalanceListener {
void onWalletBalanceUpdated(WalletBalance walletBalance);
}
@@ -0,0 +1,8 @@
package io.lbry.browser.listener;
public interface WalletSyncListener {
void onWalletSyncProcessing();
void onWalletSyncWaitingForInput();
void onWalletSyncEnabled();
void onWalletSyncFailed(Exception error);
}
@@ -0,0 +1,476 @@
package io.lbry.browser.model;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
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;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
public class Claim {
public static final String CLAIM_TYPE_CLAIM = "claim";
public static final String CLAIM_TYPE_UPDATE = "update";
public static final String CLAIM_TYPE_SUPPORT = "support";
public static final String TYPE_STREAM = "stream";
public static final String TYPE_CHANNEL = "channel";
public static final String TYPE_REPOST = "repost";
public static final String STREAM_TYPE_AUDIO = "audio";
public static final String STREAM_TYPE_IMAGE = "image";
public static final String STREAM_TYPE_VIDEO = "video";
public static final String STREAM_TYPE_SOFTWARE = "software";
public static final String ORDER_BY_EFFECTIVE_AMOUNT = "effective_amount";
public static final String ORDER_BY_RELEASE_TIME = "release_time";
public static final String ORDER_BY_TRENDING_GROUP = "trending_group";
public static final String ORDER_BY_TRENDING_MIXED = "trending_mixed";
public static final List<String> CLAIM_TYPES = Arrays.asList(TYPE_CHANNEL, TYPE_STREAM);
public static final List<String> STREAM_TYPES = Arrays.asList(
STREAM_TYPE_AUDIO, STREAM_TYPE_IMAGE, STREAM_TYPE_SOFTWARE, STREAM_TYPE_VIDEO
);
public static final String RELEASE_TIME_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
@EqualsAndHashCode.Include
private boolean placeholder;
private boolean placeholderAnonymous;
private boolean featured;
private boolean unresolved; // used for featured
private String address;
private String amount;
private String canonicalUrl;
@EqualsAndHashCode.Include
private String claimId;
private int claimSequence;
private String claimOp;
private long confirmations;
private boolean decodedClaim;
private long timestamp;
private long height;
private boolean isMine;
private String name;
private String normalizedName;
private int nout;
private String permanentUrl;
private String shortUrl;
private String txid;
private String type; // claim | update | support
private String valueType; // stream | channel | repost
private Claim repostedClaim;
private Claim signingChannel;
private String repostChannelUrl;
private boolean isChannelSignatureValid;
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();
claim.setClaimId(Helper.getJSONString("claim_id", null, item));
claim.setName(Helper.getJSONString("name", null, item));
claim.setPermanentUrl(Helper.getJSONString("permanent_url", null, item));
claim.setTxid(Helper.getJSONString("txid", null, item));
claim.setNout(Helper.getJSONInt("nout", -1, item));
return claim;
}
public String getOutpoint() {
return String.format("%s:%d", txid, nout);
}
public boolean isFree() {
if (!(value instanceof StreamMetadata)) {
return true;
}
Fee fee = ((StreamMetadata) value).getFee();
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)).divide(new BigDecimal(100000000)); // deweys
}
return new BigDecimal(0);
}
public String getMediaType() {
if (value instanceof StreamMetadata) {
StreamMetadata metadata = (StreamMetadata) value;
String mediaType = metadata.getSource() != null ? metadata.getSource().getMediaType() : null;
return mediaType;
}
return null;
}
public boolean isPlayable() {
if (value instanceof StreamMetadata) {
StreamMetadata metadata = (StreamMetadata) value;
String mediaType = metadata.getSource() != null ? metadata.getSource().getMediaType() : null;
if (mediaType != null) {
return mediaType.startsWith("video") || mediaType.startsWith("audio");
}
}
return false;
}
public boolean isViewable() {
if (value instanceof StreamMetadata) {
StreamMetadata metadata = (StreamMetadata) value;
String mediaType = metadata.getSource() != null ? metadata.getSource().getMediaType() : null;
if (mediaType != null) {
return mediaType.startsWith("image") || mediaType.startsWith("text");
}
}
return false;
}
public String getThumbnailUrl() {
if (value != null && value.getThumbnail() != null) {
return value.getThumbnail().getUrl();
}
return null;
}
public String getCoverUrl() {
if (TYPE_CHANNEL.equals(valueType) && value != null && value instanceof ChannelMetadata && ((ChannelMetadata) value).getCover() != null) {
return ((ChannelMetadata) value).getCover().getUrl();
}
return null;
}
public String getFirstCharacter() {
if (name != null) {
return name.startsWith("@") ? name.substring(1) : name;
}
return "";
}
public String getFirstTag() {
if (value != null && value.tags != null && value.tags.size() > 0) {
return value.tags.get(0);
}
return null;
}
public String getDescription() {
return (value != null) ? value.getDescription() : null;
}
public String getWebsiteUrl() {
return (value instanceof ChannelMetadata) ? ((ChannelMetadata) value).getWebsiteUrl() : null;
}
public String getEmail() {
return (value instanceof ChannelMetadata) ? ((ChannelMetadata) value).getEmail() : null;
}
public String getPublisherName() {
if (signingChannel != null) {
return signingChannel.getName();
}
return "Anonymous";
}
public String getPublisherTitle() {
if (signingChannel != null) {
return Helper.isNullOrEmpty(signingChannel.getTitle()) ? signingChannel.getName() : signingChannel.getTitle();
}
return "Anonymous";
}
public List<String> getTags() {
return (value != null && value.getTags() != null) ? new ArrayList<>(value.getTags()) : new ArrayList<>();
}
public List<Tag> getTagObjects() {
List<Tag> tags = new ArrayList<>();
if (value != null && value.getTags() != null) {
for (String value : value.getTags()) {
tags.add(new Tag(value));
}
}
return tags;
}
public String getTitle() {
return (value != null) ? value.getTitle() : null;
}
public String getTitleOrName() {
return (value != null) ? value.getTitle() : getName();
}
public long getDuration() {
if (value instanceof StreamMetadata) {
StreamMetadata metadata = (StreamMetadata) value;
if (STREAM_TYPE_VIDEO.equalsIgnoreCase(metadata.getStreamType()) && metadata.getVideo() != null) {
return metadata.getVideo().getDuration();
} else if (STREAM_TYPE_AUDIO.equalsIgnoreCase(metadata.getStreamType()) && metadata.getAudio() != null) {
return metadata.getAudio().getDuration();
}
}
return 0;
}
public static Claim fromViewHistory(ViewHistory viewHistory) {
// only for stream claims
Claim claim = new Claim();
claim.setClaimId(viewHistory.getClaimId());
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());
value.setReleaseTime(viewHistory.getReleaseTime());
if (!Helper.isNullOrEmpty(viewHistory.getThumbnailUrl())) {
Resource thumbnail = new Resource();
thumbnail.setUrl(viewHistory.getThumbnailUrl());
value.setThumbnail(thumbnail);
}
if (viewHistory.getCost() != null && viewHistory.getCost().doubleValue() > 0) {
Fee fee = new Fee();
fee.setAmount(String.valueOf(viewHistory.getCost().doubleValue()));
fee.setCurrency("LBC"); // always LBC
}
claim.setValue(value);
if (!Helper.isNullOrEmpty(viewHistory.getPublisherClaimId())) {
Claim signingChannel = new Claim();
signingChannel.setClaimId(viewHistory.getPublisherClaimId());
signingChannel.setName(viewHistory.getPublisherName());
if (!Helper.isNullOrEmpty(viewHistory.getPublisherTitle())) {
GenericMetadata channelValue = new GenericMetadata();
channelValue.setTitle(viewHistory.getPublisherTitle());
signingChannel.setValue(channelValue);
}
claim.setSigningChannel(signingChannel);
}
return claim;
}
public static Claim fromJSONObject(JSONObject claimObject) {
Claim claim = null;
String claimJson = claimObject.toString();
Type type = new TypeToken<Claim>(){}.getType();
Type streamMetadataType = new TypeToken<StreamMetadata>(){}.getType();
Type channelMetadataType = new TypeToken<ChannelMetadata>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
claim = gson.fromJson(claimJson, type);
try {
String valueType = claim.getValueType();
// Specific value type parsing
if (TYPE_REPOST.equalsIgnoreCase(valueType)) {
JSONObject repostedClaimObject = claimObject.getJSONObject("reposted_claim");
claim.setRepostedClaim(Claim.fromJSONObject(repostedClaimObject));
} else {
JSONObject value = claimObject.getJSONObject("value");
if (value != null) {
String valueJson = value.toString();
if (TYPE_STREAM.equalsIgnoreCase(valueType)) {
claim.setValue(gson.fromJson(valueJson, streamMetadataType));
} else if (TYPE_CHANNEL.equalsIgnoreCase(valueType)) {
claim.setValue(gson.fromJson(valueJson, channelMetadataType));
}
}
}
} catch (JSONException ex) {
// pass
}
return claim;
}
public static Claim fromSearchJSONObject(JSONObject searchResultObject) {
Claim claim = new Claim();
LbryUri claimUri = new LbryUri();
try {
claim.setClaimId(searchResultObject.getString("claimId"));
claim.setName(searchResultObject.getString("name"));
claim.setConfirmations(1);
if (claim.getName().startsWith("@")) {
claimUri.setChannelClaimId(claim.getClaimId());
claimUri.setChannelName(claim.getName());
claim.setValueType(TYPE_CHANNEL);
} else {
claimUri.setStreamClaimId(claim.getClaimId());
claimUri.setStreamName(claim.getName());
claim.setValueType(TYPE_STREAM);
}
int duration = searchResultObject.isNull("duration") ? 0 : searchResultObject.getInt("duration");
long feeAmount = searchResultObject.isNull("fee") ? 0 : searchResultObject.getLong("fee");
String releaseTimeString = !searchResultObject.isNull("release_time") ? searchResultObject.getString("release_time") : null;
long releaseTime = 0;
try {
releaseTime = Double.valueOf(new SimpleDateFormat(RELEASE_TIME_DATE_FORMAT).parse(releaseTimeString).getTime() / 1000.0).longValue();
} catch (ParseException ex) {
// pass
}
GenericMetadata metadata = (duration > 0 || releaseTime > 0 || feeAmount > 0) ? new StreamMetadata() : new GenericMetadata();
metadata.setTitle(searchResultObject.getString("title"));
if (metadata instanceof StreamMetadata) {
StreamInfo streamInfo = new StreamInfo();
if (duration > 0) {
// assume stream type video
((StreamMetadata) metadata).setStreamType(STREAM_TYPE_VIDEO);
streamInfo.setDuration(duration);
}
Fee fee = null;
if (feeAmount > 0) {
fee = new Fee();
fee.setAmount(String.valueOf(feeAmount));
}
((StreamMetadata) metadata).setFee(fee);
((StreamMetadata) metadata).setVideo(streamInfo);
((StreamMetadata) metadata).setReleaseTime(releaseTime);
}
claim.setValue(metadata);
if (!searchResultObject.isNull("thumbnail_url")) {
Resource thumbnail = new Resource();
thumbnail.setUrl(searchResultObject.getString("thumbnail_url"));
claim.getValue().setThumbnail(thumbnail);
}
if (!searchResultObject.isNull("channel_claim_id") && !searchResultObject.isNull("channel")) {
Claim signingChannel = new Claim();
signingChannel.setClaimId(searchResultObject.getString("channel_claim_id"));
signingChannel.setName(searchResultObject.getString("channel"));
LbryUri channelUri = new LbryUri();
channelUri.setChannelClaimId(signingChannel.getClaimId());
channelUri.setChannelName(signingChannel.getName());
signingChannel.setPermanentUrl(channelUri.toString());
claim.setSigningChannel(signingChannel);
}
} catch (JSONException ex) {
// pass
}
claim.setPermanentUrl(claimUri.toString());
return claim;
}
@Data
public static class Meta {
private long activationHeight;
private int claimsInChannel;
private int creationHeight;
private int creationTimestamp;
private String effectiveAmount;
private long expirationHeight;
private boolean isControlling;
private String supportAmount;
private int reposted;
private double trendingGlobal;
private double trendingGroup;
private double trendingLocal;
private double trendingMixed;
}
@Data
public static class GenericMetadata {
private String title;
private String description;
private Resource thumbnail;
private List<String> languages;
private List<String> tags;
private List<Location> locations;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class ChannelMetadata extends GenericMetadata {
private String publicKey;
private String publicKeyId;
private Resource cover;
private String email;
private String websiteUrl;
private List<String> featured;
}
@Data
@EqualsAndHashCode(callSuper = true)
public static class StreamMetadata extends GenericMetadata {
private String license;
private String licenseUrl;
private long releaseTime;
private String author;
private Fee fee;
private String streamType; // video | audio | image | software
private Source source;
private StreamInfo video;
private StreamInfo audio;
private StreamInfo image;
private StreamInfo software;
@Data
public static class Source {
private String sdHash;
private String mediaType;
private String hash;
private String name;
private long size;
}
}
// only support "url" for now
@Data
public static class Resource {
private String url;
}
@Data
public static class StreamInfo {
private long duration; // video / audio
private long height; // video / image
private long width; // video / image
private String os; // software
}
}
@@ -0,0 +1,68 @@
package io.lbry.browser.model;
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 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.setUrl(!Helper.isNullOrEmpty(claim.getShortUrl()) ? claim.getShortUrl() : claim.getPermanentUrl());
return key;
}
@Override
public boolean equals(@Nullable Object obj) {
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(url) && !Helper.isNullOrEmpty(key.getUrl())) {
return url.equalsIgnoreCase(key.getUrl());
}
return false;
}
@Override
public int hashCode() {
if (!Helper.isNullOrEmpty(url)) {
return url.hashCode();
}
if (!Helper.isNullOrEmpty(claimId)) {
return claimId.hashCode();
}
return super.hashCode();
}
}
@@ -0,0 +1,26 @@
package io.lbry.browser.model;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
public class ClaimSearchCacheValue {
@Getter
@Setter
private List<Claim> claims;
@Getter
@Setter
private long timestamp;
public ClaimSearchCacheValue(List<Claim> claims, long timestamp) {
this.claims = new ArrayList<>(claims);
this.timestamp = timestamp;
}
public boolean isExpired(long ttl) {
return System.currentTimeMillis() - timestamp > ttl;
}
}
@@ -0,0 +1,23 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class EditorsChoiceItem {
private boolean header;
private String title;
private String parent;
private String description;
private String thumbnailUrl;
private String permanentUrl;
public static EditorsChoiceItem fromClaim(Claim claim) {
EditorsChoiceItem item = new EditorsChoiceItem();
item.setTitle(claim.getTitle());
item.setDescription(claim.getDescription());
item.setThumbnailUrl(claim.getThumbnailUrl());
item.setPermanentUrl(claim.getPermanentUrl());
return item;
}
}
@@ -0,0 +1,10 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class Fee {
private String amount;
private String currency;
private String address;
}
@@ -0,0 +1,92 @@
package io.lbry.browser.model;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.lang.reflect.Type;
import 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;
private int blobsCompleted;
private int blobsInStream;
private int blobsRemaining;
private String channelClaimId;
private String channelName;
@EqualsAndHashCode.Include
private String claimId;
private String claimName;
private boolean completed;
private String downloadDirectory;
private String downloadPath;
private String fileName;
private String key;
private String mimeType;
private int nout;
private String outpoint;
private int pointsPaid;
private String protobuf;
private String sdHash;
private String status;
private boolean stopped;
private String streamHash;
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,13 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class Location {
private double latitude;
private double longitude;
private String country;
private String state;
private String city;
private String code;
}
@@ -0,0 +1,68 @@
package io.lbry.browser.model;
import android.content.Context;
import androidx.core.content.res.ResourcesCompat;
import java.util.ArrayList;
import java.util.List;
import lombok.Data;
@Data
public class NavMenuItem {
public static final int ID_GROUP_FIND_CONTENT = 100;
public static final int ID_GROUP_YOUR_CONTENT = 200;
public static final int ID_GROUP_WALLET = 300;
public static final int ID_GROUP_OTHER = 400;
// Find Content
public static final int ID_ITEM_FOLLOWING = 101;
public static final int ID_ITEM_EDITORS_CHOICE = 102;
public static final int ID_ITEM_ALL_CONTENT = 103;
// Your Content
public static final int ID_ITEM_CHANNELS = 201;
public static final int ID_ITEM_LIBRARY = 202;
public static final int ID_ITEM_PUBLISHES = 203;
public static final int ID_ITEM_NEW_PUBLISH = 204;
// Wallet
public static final int ID_ITEM_WALLET = 301;
public static final int ID_ITEM_REWARDS = 302;
public static final int ID_ITEM_INVITES = 303;
// Other
public static final int ID_ITEM_SETTINGS = 401;
public static final int ID_ITEM_ABOUT = 402;
private Context context;
private int id;
private boolean group;
private int icon;
private String title;
private String extraLabel;
private String name; // same as title, but only as en lang for events
private List<NavMenuItem> items;
public NavMenuItem(int id, int titleResourceId, boolean group, Context context) {
this.context = context;
this.id = id;
this.group = group;
if (titleResourceId > 0) {
this.title = context.getString(titleResourceId);
}
if (group) {
this.items = new ArrayList<>();
}
}
public NavMenuItem(int id, int iconStringId, int titleResourceId, String name, Context context) {
this.context = context;
this.id = id;
this.icon = iconStringId;
this.title = context.getString(titleResourceId);
this.name = name;
}
}
@@ -0,0 +1,44 @@
package io.lbry.browser.model;
import java.util.Comparator;
import io.lbry.browser.utils.Predefined;
import lombok.Getter;
import lombok.Setter;
public class Tag implements Comparator<Tag> {
@Getter
@Setter
private String name;
@Getter
@Setter
private boolean followed;
public Tag() {
}
public Tag(String name) {
this.name = name;
}
public String getLowercaseName() {
return name.toLowerCase();
}
public boolean isMature() {
return Predefined.MATURE_TAGS.contains(name.toLowerCase());
}
public String toString() {
return getLowercaseName();
}
public boolean equals(Object o) {
return (o instanceof Tag) && ((Tag) o).getName().equalsIgnoreCase(name);
}
public int hashCode() {
return name.toLowerCase().hashCode();
}
public int compare(Tag a, Tag b) {
return a.getLowercaseName().compareToIgnoreCase(b.getLowercaseName());
}
}
@@ -0,0 +1,133 @@
package io.lbry.browser.model;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.util.Date;
import io.lbry.browser.R;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryUri;
import lombok.Data;
@Data
public class Transaction {
private int confirmations;
private Date txDate;
private String date;
private String claim;
private String claimId;
private String txid;
private BigDecimal value;
private BigDecimal fee;
private long timestamp;
private int descriptionStringId;
private TransactionInfo abandonInfo;
private TransactionInfo claimInfo;
private TransactionInfo supportInfo;
private TransactionInfo updateInfo;
public LbryUri getClaimUrl() {
if (!Helper.isNullOrEmpty(claim) && !Helper.isNullOrEmpty(claimId)) {
try {
return LbryUri.parse(LbryUri.normalize(String.format("%s#%s", claim, claimId)));
} catch (LbryUriException ex) {
// pass
}
}
return null;
}
public static Transaction fromJSONObject(JSONObject jsonObject) {
Transaction transaction = new Transaction();
transaction.setConfirmations(Helper.getJSONInt("confirmations", -1, jsonObject));
transaction.setDate(Helper.getJSONString("date", null, jsonObject));
transaction.setTxid(Helper.getJSONString("txid", null, jsonObject));
transaction.setValue(new BigDecimal(Helper.getJSONString("value", "0", jsonObject)));
transaction.setFee(new BigDecimal(Helper.getJSONString("fee", "0", jsonObject)));
transaction.setTimestamp(Helper.getJSONLong("timestamp", 0, jsonObject) * 1000);
transaction.setTxDate(new Date(transaction.getTimestamp()));
int descStringId = -1;
TransactionInfo info = null;
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 (info == null && jsonObject.has("claim_info")) {
JSONArray array = jsonObject.getJSONArray("claim_info");
if (array.length() > 0) {
info = TransactionInfo.fromJSONObject(array.getJSONObject(0));
descStringId = info.getClaimName().startsWith("@") ? R.string.channel : R.string.publish;
transaction.setClaimInfo(info);
}
}
if (info == null && jsonObject.has("support_info")) {
JSONArray array = jsonObject.getJSONArray("support_info");
if (array.length() > 0) {
info = TransactionInfo.fromJSONObject(array.getJSONObject(0));
descStringId = info.isTip() ? R.string.tip : R.string.support;
transaction.setSupportInfo(info);
}
}
if (info == null && jsonObject.has("update_info")) {
JSONArray array = jsonObject.getJSONArray("update_info");
if (array.length() > 0) {
info = TransactionInfo.fromJSONObject(array.getJSONObject(0));
descStringId = info.getClaimName().startsWith("@") ? R.string.channel_update : R.string.publish_update;
transaction.setUpdateInfo(info);
}
}
if (info != null) {
transaction.setClaim(info.getClaimName());
transaction.setClaimId(info.getClaimId());
}
} catch (JSONException ex) {
// pass
}
if (transaction.getValue().doubleValue() == 0 && info != null && info.getBalanceDelta().doubleValue() != 0) {
transaction.setValue(info.getBalanceDelta());
}
if (descStringId == -1) {
descStringId = transaction.getValue().signum() == -1 || transaction.getFee().signum() == -1 ? R.string.spend : R.string.receive;
}
transaction.setDescriptionStringId(descStringId);
return transaction;
}
@Data
public static class TransactionInfo {
private String address;
private BigDecimal amount;
private BigDecimal balanceDelta;
private String claimId;
private String claimName;
private boolean isTip;
private int nout;
public static TransactionInfo fromJSONObject(JSONObject jsonObject) {
TransactionInfo info = new TransactionInfo();
info.setAddress(Helper.getJSONString("address", null, jsonObject));
info.setAmount(new BigDecimal(Helper.getJSONString("amount", "0", jsonObject)));
info.setBalanceDelta(new BigDecimal(Helper.getJSONString("balance_delta", "0", jsonObject)));
info.setClaimId(Helper.getJSONString("claim_id", null, jsonObject));
info.setClaimName(Helper.getJSONString("claim_name", null, jsonObject));
info.setTip(Helper.getJSONBoolean("is_tip", false, jsonObject));
info.setNout(Helper.getJSONInt("nout", -1, jsonObject));
return info;
}
}
}
@@ -0,0 +1,55 @@
package io.lbry.browser.model;
import io.lbry.browser.utils.LbryUri;
import lombok.Data;
@Data
public class UrlSuggestion {
public static final int TYPE_CHANNEL = 1;
public static final int TYPE_FILE = 2;
public static final int TYPE_SEARCH = 3;
public static final int TYPE_TAG = 4;
private int type;
private String text;
private LbryUri uri;
private Claim claim; // associated claim if resolved
private boolean titleTextOnly;
private boolean titleUrlOnly;
private boolean useTextAsDescription;
public UrlSuggestion() {
}
public UrlSuggestion(int type, String text) {
this.type = type;
this.text = text;
}
public UrlSuggestion(int type, String text, LbryUri uri) {
this(type, text);
this.uri = uri;
}
public UrlSuggestion(int type, String text, LbryUri uri, boolean titleTextOnly) {
this(type, text, uri);
this.titleTextOnly = titleTextOnly;
}
public String getTitle() {
if (titleUrlOnly && (type == TYPE_CHANNEL || type == TYPE_FILE)) {
return uri.toString();
}
if (!titleTextOnly) {
switch (type) {
case TYPE_CHANNEL:
return String.format("%s - %s", text.startsWith("@") ? text.substring(1) : text, uri.toVanityString());
case TYPE_FILE:
return String.format("%s - %s", text, uri.toVanityString());
case TYPE_TAG:
return String.format("%s - #%s", text, text);
}
}
return text;
}
}
@@ -0,0 +1,61 @@
package io.lbry.browser.model;
import java.math.BigDecimal;
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
public class ViewHistory {
private LbryUri uri;
private String claimId;
private String claimName;
private BigDecimal cost;
private String title;
private String publisherClaimId;
private String publisherName;
private String publisherTitle;
private String thumbnailUrl;
private String device;
private long releaseTime;
private Date timestamp;
public static ViewHistory fromClaimWithUrlAndDeviceName(Claim claim, String url, String deviceName) {
ViewHistory history = new ViewHistory();
LbryUri uri = LbryUri.tryParse(url);
if (uri == null) {
uri = LbryUri.tryParse(claim.getPermanentUrl());
}
history.setUri(uri);
history.setClaimId(claim.getClaimId());
history.setClaimName(claim.getName());
history.setTitle(claim.getTitle());
history.setThumbnailUrl(claim.getThumbnailUrl());
Claim.GenericMetadata metadata = claim.getValue();
if (metadata instanceof Claim.StreamMetadata) {
Claim.StreamMetadata value = (Claim.StreamMetadata) metadata;
history.setReleaseTime(value.getReleaseTime());
if (value.getFee() != null) {
history.setCost(claim.getActualCost(Lbryio.LBCUSDRate));
}
}
if (history.getReleaseTime() == 0) {
history.setReleaseTime(claim.getTimestamp());
}
Claim signingChannel = claim.getSigningChannel();
if (signingChannel != null) {
history.setPublisherClaimId(signingChannel.getClaimId());
history.setPublisherName(signingChannel.getName());
history.setPublisherTitle(signingChannel.getTitle());
}
history.setDevice(deviceName);
return history;
}
}
@@ -0,0 +1,24 @@
package io.lbry.browser.model;
import java.math.BigDecimal;
import lombok.Data;
@Data
public class WalletBalance {
private BigDecimal available;
private BigDecimal reserved;
private BigDecimal claims;
private BigDecimal supports;
private BigDecimal tips;
private BigDecimal total;
public WalletBalance() {
available = new BigDecimal(0);
reserved = new BigDecimal(0);
claims = new BigDecimal(0);
supports = new BigDecimal(0);
tips = new BigDecimal(0);
total = new BigDecimal(0);
}
}
@@ -0,0 +1,20 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class WalletSync {
private String hash;
private String data;
private 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;
}
}
@@ -0,0 +1,11 @@
package io.lbry.browser.model.lbryinc;
import lombok.Data;
@Data
public class Invitee {
private boolean header;
private String email;
private boolean inviteRewardClaimed;
private boolean inviteRewardClaimable;
}
@@ -0,0 +1,69 @@
package io.lbry.browser.model.lbryinc;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.lang.reflect.Type;
import io.lbry.browser.model.Claim;
import io.lbry.browser.utils.Helper;
import lombok.Data;
@Data
public class Reward {
public static final String TYPE_NEW_DEVELOPER = "new_developer";
public static final String TYPE_NEW_USER = "new_user";
public static final String TYPE_CONFIRM_EMAIL = "email_provided";
public static final String TYPE_FIRST_CHANNEL = "new_channel";
public static final String TYPE_FIRST_STREAM = "first_stream";
public static final String TYPE_MANY_DOWNLOADS = "many_downloads";
public static final String TYPE_FIRST_PUBLISH = "first_publish";
public static final String TYPE_REFERRAL = "referrer";
public static final String TYPE_REFEREE = "referee";
public static final String TYPE_REWARD_CODE = "reward_code";
public static final String TYPE_SUBSCRIPTION = "subscription";
public static final String YOUTUBE_CREATOR = "youtube_creator";
public static final String TYPE_DAILY_VIEW = "daily_view";
public static final String TYPE_NEW_ANDROID = "new_android";
private boolean custom;
private long id;
private String rewardType;
private double rewardAmount;
private String transactionId;
private String createdAt;
private String updatedAt;
private String rewardTitle;
private String rewardDescription;
private String rewardNotification;
private String rewardRange;
public String getDisplayAmount() {
if (shouldDisplayRange()) {
return rewardRange.split("-")[1];
}
if (rewardAmount > 0) {
return String.valueOf(rewardAmount);
}
return "?";
}
public boolean isClaimed() {
return !Helper.isNullOrEmpty(transactionId);
}
public boolean shouldDisplayRange() {
return (!isClaimed() && !Helper.isNullOrEmpty(rewardRange) && rewardRange.indexOf('-') > -1);
}
public static Reward fromJSONObject(JSONObject rewardObject) {
String rewardJson = rewardObject.toString();
Type type = new TypeToken<Reward>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
return gson.fromJson(rewardJson, type);
}
}
@@ -0,0 +1,36 @@
package io.lbry.browser.model.lbryinc;
import io.lbry.browser.model.Claim;
import lombok.Getter;
import lombok.Setter;
public class Subscription {
@Getter
@Setter
private String channelName;
@Getter
@Setter
private String url;
public Subscription() {
}
public Subscription(String channelName, String url) {
this.channelName = channelName;
this.url = url;
}
public static Subscription fromClaim(Claim claim) {
return new Subscription(claim.getName(), claim.getPermanentUrl());
}
public String toString() {
return url;
}
public boolean equals(Object o) {
return (o instanceof Subscription) && url != null && url.equalsIgnoreCase(((Subscription) o).getUrl());
}
public int hashCode() {
return url.toLowerCase().hashCode();
}
}
@@ -0,0 +1,42 @@
package io.lbry.browser.model.lbryinc;
import java.util.List;
import lombok.Data;
@Data
public class User {
private String createdAt;
private String familyName;
private String givenName;
private List<String> groups;
private boolean hasVerifiedEmail;
private long id;
private boolean inviteRewardClaimed;
private String invitedAt;
private long inivtedById;
private int invitesRemaining;
private boolean isEmailEnabled;
private boolean isIdentityVerified;
private boolean isRewardApproved;
private String language;
private long manualApprovalUserId;
private String primaryEmail;
private String rewardStatusChangeTrigger;
private String updatedAt;
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,91 @@
package io.lbry.browser.tasks;
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.util.HashMap;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.tasks.claim.ClaimResultHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class ChannelCreateUpdateTask extends AsyncTask<Void, Void, Claim> {
private Claim claim;
private BigDecimal deposit;
private boolean update;
private Exception error;
private ClaimResultHandler handler;
private View progressView;
public ChannelCreateUpdateTask(Claim claim, BigDecimal deposit, boolean update, View progressView, ClaimResultHandler handler) {
this.claim = claim;
this.deposit = deposit;
this.update = update;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
if (handler != null) {
handler.beforeStart();
}
}
protected Claim doInBackground(Void... params) {
Map<String, Object> options = new HashMap<>();
if (!update) {
options.put("name", claim.getName());
} 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("blocking", true);
Claim claimResult = null;
String method = !update ? Lbry.METHOD_CHANNEL_CREATE : Lbry.METHOD_CHANNEL_UPDATE;
try {
JSONObject result = (JSONObject) Lbry.genericApiCall(method, 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,65 @@
package io.lbry.browser.tasks;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import io.lbry.browser.MainActivity;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.Tag;
import io.lbry.browser.utils.Lbry;
public class FollowUnfollowTagTask extends AsyncTask<Void, Void, Boolean> {
private Tag tag;
private boolean unfollowing;
private Context context;
private FollowUnfollowTagHandler handler;
private Exception error;
public FollowUnfollowTagTask(Tag tag, boolean unfollowing, Context context, FollowUnfollowTagHandler handler) {
this.tag = tag;
this.context = context;
this.unfollowing = unfollowing;
this.handler = handler;
}
public Boolean doInBackground(Void... params) {
try {
SQLiteDatabase db = null;
if (context instanceof MainActivity) {
db = ((MainActivity) context).getDbHelper().getWritableDatabase();
if (db != null) {
if (!Lbry.knownTags.contains(tag)) {
DatabaseHelper.createOrUpdateTag(tag, db);
Lbry.addKnownTag(tag);
}
tag.setFollowed(!unfollowing);
DatabaseHelper.createOrUpdateTag(tag, db);
if (unfollowing) {
Lbry.removeFollowedTag(tag);
} else {
Lbry.addFollowedTag(tag);
}
return true;
}
}
} catch (Exception ex) {
error = ex;
}
return false;
}
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
handler.onSuccess(tag, unfollowing);
} else {
handler.onError(error);
}
}
}
public interface FollowUnfollowTagHandler {
void onSuccess(Tag tag, boolean unfollowing);
void onError(Exception error);
}
}
@@ -0,0 +1,7 @@
package io.lbry.browser.tasks;
public interface GenericTaskHandler {
void beforeStart();
void onSuccess();
void onError(Exception error);
}
@@ -0,0 +1,51 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.view.View;
import java.util.List;
import io.lbry.browser.exceptions.LbryRequestException;
import io.lbry.browser.exceptions.LbryResponseException;
import io.lbry.browser.model.UrlSuggestion;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lighthouse;
public class LighthouseAutoCompleteTask extends AsyncTask<Void, Void, List<UrlSuggestion>> {
private String text;
private AutoCompleteResultHandler handler;
private View progressView;
private Exception error;
public LighthouseAutoCompleteTask(String text, View progressView, AutoCompleteResultHandler handler) {
this.text = text;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected List<UrlSuggestion> doInBackground(Void... params) {
try {
return Lighthouse.autocomplete(text);
} catch (LbryRequestException | LbryResponseException ex) {
error = ex;
return null;
}
}
protected void onPostExecute(List<UrlSuggestion> suggestions) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (suggestions != null) {
handler.onSuccess(suggestions);
} else {
handler.onError(error);
}
}
}
public interface AutoCompleteResultHandler {
void onSuccess(List<UrlSuggestion> suggestions);
void onError(Exception error);
}
}
@@ -0,0 +1,56 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
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.utils.Helper;
import io.lbry.browser.utils.Lighthouse;
public class LighthouseSearchTask extends AsyncTask<Void, Void, List<Claim>> {
private String rawQuery;
private int size;
private int from;
private boolean nsfw;
private String relatedTo;
private ClaimSearchTask.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) {
this.rawQuery = rawQuery;
this.size = size;
this.from = from;
this.nsfw = nsfw;
this.relatedTo = relatedTo;
this.progressBar = progressBar;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressBar, View.VISIBLE);
}
protected List<Claim> doInBackground(Void... params) {
try {
return Lighthouse.search(rawQuery, size, from, nsfw, relatedTo);
} catch (LbryRequestException | LbryResponseException ex) {
error = ex;
return null;
}
}
protected void onPostExecute(List<Claim> claims) {
Helper.setViewVisibility(progressBar, View.GONE);
if (handler != null) {
if (claims != null) {
handler.onSuccess(claims, claims.size() < size);
} else {
handler.onError(error);
}
}
}
}
@@ -0,0 +1,59 @@
package io.lbry.browser.tasks;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import java.util.List;
import io.lbry.browser.MainActivity;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.exceptions.LbryRequestException;
import io.lbry.browser.exceptions.LbryResponseException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.Tag;
import io.lbry.browser.utils.Helper;
public class LoadTagsTask extends AsyncTask<Void, Void, List<Tag>> {
private Context context;
private LoadTagsHandler handler;
private Exception error;
public LoadTagsTask(Context context, LoadTagsHandler handler) {
this.context = context;
this.handler = handler;
}
protected List<Tag> doInBackground(Void... params) {
List<Tag> tags = null;
SQLiteDatabase db = null;
try {
if (context instanceof MainActivity) {
db = ((MainActivity) context).getDbHelper().getReadableDatabase();
if (db != null) {
tags = DatabaseHelper.getTags(db);
}
}
} catch (SQLiteException ex) {
error = ex;
}
return tags;
}
protected void onPostExecute(List<Tag> tags) {
if (handler != null) {
if (tags != null) {
handler.onSuccess(tags);
} else {
handler.onError(error);
}
}
}
public interface LoadTagsHandler {
void onSuccess(List<Tag> tags);
void onError(Exception error);
}
}
@@ -0,0 +1,134 @@
package io.lbry.browser.tasks;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import android.util.Log;
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.MainActivity;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
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;
// background task to create a diff of local and remote subscriptions and try to merge
public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscription>> {
private static final String TAG = "MergeSubscriptionsTask";
private Context context;
private List<Subscription> base;
private List<Subscription> diff;
private MergeSubscriptionsHandler handler;
private Exception error;
public MergeSubscriptionsTask(List<Subscription> base, Context context, MergeSubscriptionsHandler handler) {
this.base = base;
this.context = context;
this.handler = handler;
}
protected List<Subscription> doInBackground(Void... params) {
List<Subscription> combined = new ArrayList<>(base);
List<Subscription> localSubs = new ArrayList<>();
List<Subscription> remoteSubs = new ArrayList<>();
diff = new ArrayList<>();
SQLiteDatabase db = null;
try {
// fetch local subscriptions
if (context instanceof MainActivity) {
db = ((MainActivity) context).getDbHelper().getWritableDatabase();
}
if (db != null) {
localSubs = DatabaseHelper.getSubscriptions(db);
for (Subscription sub : localSubs) {
if (!combined.contains(sub)) {
combined.add(sub);
}
}
}
// fetch remote subscriptions
JSONArray array = (JSONArray) Lbryio.parseResponse(Lbryio.call("subscription", "list", context));
if (array != null) {
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String claimId = item.getString("claim_id");
String channelName = item.getString("channel_name");
LbryUri url = new LbryUri();
url.setChannelName(channelName);
url.setClaimId(claimId);
Subscription subscription = new Subscription(channelName, url.toString());
remoteSubs.add(subscription);
}
}
for (int i = 0; i < combined.size(); i++) {
Subscription local = combined.get(i);
if (!remoteSubs.contains(local)) {
// add to remote subscriptions
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);
} catch (LbryUriException | LbryioRequestException | LbryioResponseException ex) {
// pass
Log.e(TAG, String.format("subscription/new failed: %s", ex.getMessage()), ex);
}
}
}
for (int i = 0; i < localSubs.size(); i++) {
Subscription local = localSubs.get(i);
if (!base.contains(local) && !diff.contains(local)) {
diff.add(local);
}
}
for (int i = 0; i < remoteSubs.size(); i++) {
Subscription remote = remoteSubs.get(i);
if (!combined.contains(remote)) {
combined.add(remote);
if (!diff.contains(remote)) {
diff.add(remote);
}
}
}
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | SQLiteException ex) {
error = ex;
return null;
} finally {
Helper.closeDatabase(db);
}
return combined;
}
protected void onPostExecute(List<Subscription> subscriptions) {
if (handler != null) {
if (subscriptions != null) {
handler.onSuccess(subscriptions, diff);
} else {
handler.onError(error);
}
}
}
public interface MergeSubscriptionsHandler {
void onSuccess(List<Subscription> subscriptions, List<Subscription> diff);
void onError(Exception error);
}
}
@@ -0,0 +1,55 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.Buffer;
import io.lbry.browser.utils.Helper;
public class ReadTextFileTask extends AsyncTask<Void, Void, String> {
private String filePath;
private Exception error;
private ReadTextFileHandler handler;
public ReadTextFileTask(String filePath, ReadTextFileHandler handler) {
this.filePath = filePath;
this.handler = handler;
}
protected String doInBackground(Void... params) {
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException ex) {
error = ex;
return null;
} finally {
Helper.closeCloseable(reader);
}
return sb.toString();
}
protected void onPostExecute(String text) {
if (handler != null) {
if (!Helper.isNull(text)) {
handler.onSuccess(text);
} else {
handler.onError(error);
}
}
}
public interface ReadTextFileHandler {
void onSuccess(String text);
void onError(Exception error);
}
}
@@ -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);
}
}
}
}
@@ -0,0 +1,70 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import io.lbry.browser.adapter.TagListAdapter;
import io.lbry.browser.model.Tag;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
private boolean clearPrevious;
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) {
this.filter = filter;
this.limit = limit;
this.addedTagsAdapter = addedTagsAdapter;
this.suggestedTagsAdapter = suggestedTagsAdapter;
this.clearPrevious = clearPrevious;
this.handler = handler;
}
protected List<Tag> doInBackground(Void... params) {
List<Tag> tags = new ArrayList<>();
if (Helper.isNullOrEmpty(filter)) {
Random random = new Random();
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);
}
}
} else {
Tag filterTag = new Tag(filter);
if (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(filterTag)) {
tags.add(new Tag(filter));
}
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);
}
}
}
return tags;
}
protected void onPostExecute(List<Tag> tags) {
if (handler != null) {
handler.onSuccess(tags);
}
}
public interface KnownTagsHandler {
void onSuccess(List<Tag> tags);
}
}
@@ -0,0 +1,101 @@
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.util.Random;
import java.io.File;
import io.lbry.browser.exceptions.LbryResponseException;
import io.lbry.browser.utils.Helper;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class UploadImageTask extends AsyncTask<Void, Void, String> {
private String filePath;
private View progressView;
private UploadThumbnailHandler handler;
private Exception error;
public UploadImageTask(String filePath, View progressView, UploadThumbnailHandler handler) {
this.filePath = filePath;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected String doInBackground(Void... params) {
String thumbnailUrl = null;
try {
File file = new File(filePath);
String fileName = file.getName();
int dotIndex = fileName.lastIndexOf('.');
String extension = "jpg";
if (dotIndex > -1) {
extension = fileName.substring(dotIndex + 1);
}
String fileType = String.format("image/%s", extension);
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).
addFormDataPart("name", makeid()).
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();
Response response = client.newCall(request).execute();
JSONObject json = new JSONObject(response.body().string());
if (json.has("success")) {
JSONObject data = json.getJSONObject("data");
String url = Helper.getJSONString("url", null, data);
if (Helper.isNullOrEmpty(url)) {
throw new LbryResponseException("Invalid thumbnail url returned after upload.");
}
thumbnailUrl = String.format("%s.%s", url, extension);
} else if (json.has("error")) {
JSONObject error = json.getJSONObject("error");
String message = Helper.getJSONString("message", null, error);
throw new LbryResponseException(Helper.isNullOrEmpty(message) ? "The image failed to upload." : message);
}
} catch (IOException | JSONException | LbryResponseException ex) {
error = ex;
}
return thumbnailUrl;
}
protected void onPostExecute(String thumbnailUrl) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (!Helper.isNullOrEmpty(thumbnailUrl)) {
handler.onSuccess(thumbnailUrl);
} else {
handler.onError(error);
}
}
}
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", false);
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,10 @@
package io.lbry.browser.tasks.claim;
import java.util.List;
import io.lbry.browser.model.Claim;
public interface ClaimListResultHandler {
void onSuccess(List<Claim> claims);
void onError(Exception error);
}
@@ -0,0 +1,67 @@
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 ClaimListTask extends AsyncTask<Void, Void, List<Claim>> {
private String type;
private View progressView;
private ClaimListResultHandler handler;
private Exception error;
public ClaimListTask(String type, View progressView, ClaimListResultHandler handler) {
this.type = type;
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(type)) {
options.put("claim_type", type);
}
options.put("page", 1);
options.put("page_size", 999);
options.put("resolve", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_CLAIM_LIST, options);
JSONArray items = result.getJSONArray("items");
claims = new ArrayList<>();
for (int i = 0; i < items.length(); i++) {
claims.add(Claim.fromJSONObject(items.getJSONObject(i)));
}
} catch (ApiCallException | JSONException 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);
} else {
handler.onError(error);
}
}
}
}
Loaded 100 of 1746 files, more files were not shown because too many files have changed in this diff. Show more