Compare commits

..
271 Commits
Author SHA1 Message Date
Akinwale Ariwodola bdf8a58818 bumpversion 0.16.12 --> 0.16.13 2021-01-12 09:11:26 +01:00
Akinwale Ariwodola e1d51c881a Fix crash bug for anonymous repost claim results. Better handle channel repost navigation. 2021-01-12 09:07:33 +01:00
Akinwale Ariwodola 28212808f8 Merge pull request #1115 from pakar/master
Upgrade ExoPlayer from 2.11.4 to 2.12.2
2021-01-12 08:35:04 +01:00
Akinwale Ariwodola 74f08f8f98 Merge pull request #1102 from kekkyojin/fix-markdown-rendering
Use Base64 to encode html when rendering Markdown files
2021-01-12 08:33:40 +01:00
Akinwale Ariwodola cb5c29fbce Merge pull request #1117 from kekkyojin/fix-nosuchmethod-commons
Fix NoSuchMethod exception for HelperSHA256 on API Level prior to P
2021-01-12 08:32:08 +01:00
Javi Rueda 4d775d3a17 Fix NoSuchMethod exception for HelperSHA256 on API Level prior to P 2021-01-11 20:44:03 +01:00
Patric Karlström fd94ef9fa7 Upgrade ExoPlayer from 2.11.4 to 2.12.2 2021-01-11 01:10:23 +01:00
Javi Rueda 2e0331305a Use Base64 to encode html when rendering Markdown files 2020-12-29 11:30:05 +01:00
Akinwale Ariwodola fb560f8f01 fix last resource build error 2020-12-29 07:20:46 +01:00
Akinwale Ariwodola ef80c9f7fd fix resource build error 2020-12-29 07:13:57 +01:00
Akinwale Ariwodola 99a4a0a22f Remove comment post confirmation. Fix resources build error. 2020-12-29 07:07:53 +01:00
Akinwale Ariwodola 136853853a bumpversion 0.16.11 --> 0.16.12 2020-12-29 07:02:13 +01:00
Akinwale Ariwodola ebf3299c30 add scrollbars attribute to listview 2020-12-29 07:00:45 +01:00
Akinwale Ariwodola 036b49a871 Merge pull request #1097 from kekkyojin/remove_stages_scrollbar
Avoid showing vertical scroll bar on stage error listview
2020-12-29 07:00:02 +01:00
Akinwale Ariwodola 67d5f88d34 Merge pull request #1100 from clay53/master
Changed wallet send notification to accept 4 digit decimal
2020-12-29 06:52:16 +01:00
Akinwale Ariwodola b1e0b9af33 sdk 0.87.0. Show confirmation for unfollow. 2020-12-29 06:47:10 +01:00
Clayton Hickey c30b012787 Changed wallet send notification to accept 4 digit decimal 2020-12-27 03:54:36 -05:00
Javi Rueda c8c6305757 Avoid showing vertical scroll bar on stage error listview 2020-12-22 02:26:37 +01:00
Akinwale Ariwodola ee1d090e62 Merge pull request #1068 from kekkyojin/fix-lintproblems
Some fixes for lint
2020-12-21 19:43:08 +01:00
Javi Rueda 9e56a86492 Some fixes for lint 2020-12-18 14:30:48 +01:00
Akinwale Ariwodola e6b83877f1 Merge pull request #1063 from clay53/1042
Removed comment tips
2020-12-18 13:01:49 +01:00
Akinwale Ariwodola b567e39aef Merge pull request #1069 from kekkyojin/add-twitter-instructions
Provide instructions to add dummy Twitter API credentials
2020-12-18 12:22:03 +01:00
Akinwale Ariwodola ae62dba0a6 Merge pull request #1071 from kekkyojin/sha256-unittest
Add unit test for Helper.SHA256(String)
2020-12-18 12:21:39 +01:00
Akinwale Ariwodola df1e8abf50 Merge pull request #1067 from kekkyojin/use-apache-hex
Replace Hex class from GMS with the one from Apache
2020-12-18 12:20:42 +01:00
Javi Rueda 31cfb26c3b Add unit test for Helper.SHA256(String) 2020-12-15 13:45:32 +01:00
Javi Rueda e5f34dc464 Provide instructions to add dummy Twitter API credentials 2020-12-14 20:38:57 +01:00
Javi Rueda 601031e55d Replace Hex class from GMS with the one from Apache 2020-12-14 18:17:13 +01:00
Akinwale Ariwodola a9aadbe6a8 bumpversion 0.16.10 --> 0.16.11 2020-12-13 18:08:10 +01:00
Akinwale Ariwodola f9a4b71037 fix crash error when following doesn't exist in shared user state 2020-12-13 18:07:19 +01:00
Clayton Hickey 0f10e9dc1f Removed comment tips 2020-12-12 20:11:00 -05:00
Akinwale Ariwodola 0647deb06c Merge pull request #1061 from kekkyojin/startupstage-listview
Use ListView to show startup stage errors
2020-12-12 23:16:17 +01:00
Akinwale Ariwodola b2f5fec293 make the channel filter name alphabet uppercase 2020-12-10 09:57:27 +01:00
Javi Rueda daf4e5aca2 Use ListView to show startup stage errors 2020-12-09 21:05:21 +01:00
Akinwale Ariwodola c1324efb41 bumpversion 0.16.9 --> 0.16.10 2020-12-09 11:47:58 +01:00
Akinwale Ariwodola 6221de2d3c sync notificationsDisabled states for followed channels 2020-12-09 11:31:13 +01:00
Akinwale Ariwodola 983bc68af2 Merge branch 'master' of https://github.com/lbryio/lbry-android 2020-12-09 11:00:25 +01:00
Akinwale Ariwodola f1b167693d SDK 0.86.1. is_seen vs is_read swap. Fix error condition where wallet sync starts if the wallet is not ready. 2020-12-09 10:59:25 +01:00
Akinwale Ariwodola 68ac64b534 Merge pull request #1057 from kekkyojin/sort-commentreplies
Sort replies from oldest to newest
2020-12-05 04:32:41 +01:00
Javi Rueda 6819ae46f9 Sort replies from oldest to newest 2020-12-01 04:58:48 +01:00
Akinwale Ariwodola 6c406c5a85 share_usage_data setting 2020-11-29 05:07:54 +01:00
Akinwale Ariwodola c179243d22 update dependencies 2020-11-26 00:04:37 +01:00
Akinwale Ariwodola d0f5504c80 LbryUri parsing improvements. Remove duplicate code. 2020-11-15 09:11:50 +01:00
Akinwale Ariwodola 896c566a02 Merge pull request #1045 from kekkyojin/open-file-external
Offer opening unsupported filetypes with external app
2020-11-13 15:42:59 +01:00
Javi Rueda da9352cc68 Offer opening unsupported filetypes with external app 2020-10-27 14:28:15 +01:00
Akinwale Ariwodola b8d2375e20 Merge pull request #1044 from ycohen-dev/fix_issue_1043
Fix floating wallet/rewards bar for RTL layout
2020-10-23 13:25:07 +01:00
Akinwale Ariwodola dd52ff9d07 Merge pull request #1033 from kekkyojin/md-text-rendering
Fix for text not rendering after # in markdown
2020-10-23 13:23:15 +01:00
yuval d9891f8a8a Floating wallet balance/rewards now visible in RTL layout
(Fix issue #1043)
2020-10-22 22:22:44 +03:00
Akinwale Ariwodola ea5fe6842d Merge pull request #1041 from ycohen-dev/fix_issue_1040
fix issue 1040
2020-10-21 00:15:36 +01:00
Akinwale Ariwodola fc649187df Merge pull request #1039 from ycohen-dev/fix_issue_1038
fix issue 1038
2020-10-21 00:14:15 +01:00
yuval b0f7c41885 fix issue 1040
Transaction amount text Direction changed to LTR.
Transaction amount pinned to end of view
2020-10-17 22:18:14 +03:00
yuval 45935717c8 fix issue 1038
Replaced gravity pinning to "end" instead of "right"
Pinned claim id which could be in rtl and ltr scripts to the start of the layout
2020-10-16 23:40:28 +03:00
Akinwale Ariwodola ac5e666369 bumpversion 0.16.8 --> 0.16.9 2020-10-16 06:58:57 +01:00
Akinwale Ariwodola ffeb72a383 Publish mature tags. String resource updates. 2020-10-16 06:53:08 +01:00
Akinwale Ariwodola 0ec09d751c Merge pull request #1036 from ycohen-dev/fix_issue_1034
Fix issue #1034
2020-10-16 06:39:45 +01:00
Akinwale Ariwodola b8e4fcff92 Merge pull request #1037 from lbryio/follow-text
add follow text beside follow icon
2020-10-16 06:37:50 +01:00
Akinwale Ariwodola b79f0f4820 add follow text beside follow icon 2020-10-16 06:36:36 +01:00
yuval a1cd58a214 Fix issue #1034
Hide notifications when entering PiP mode
2020-10-16 00:11:08 +03:00
Javi Rueda cfca8facbe Use '%23' instead of '#' when rendering #hashtag style text from markdown 2020-10-15 01:49:53 +02:00
Akinwale Ariwodola 066a0a099c Merge pull request #1032 from lbryio/wallet-balance-page
use credits icon on wallet balance page
2020-10-14 15:33:25 +01:00
Akinwale Ariwodola afeee2e5df use credits icon on wallet balance page 2020-10-14 15:30:59 +01:00
Akinwale Ariwodola 76036acfc7 Merge branch 'master' of https://github.com/lbryio/lbry-android 2020-10-14 15:17:35 +01:00
Akinwale Ariwodola 897bfdaffd fix build error 2020-10-14 15:16:45 +01:00
Akinwale Ariwodola 7475ae323c Merge pull request #1031 from ycohen-dev/fix_issue_1030
Fix issue #1030
2020-10-14 15:12:34 +01:00
Akinwale Ariwodola faf7f3ccbf make credits translatable 2020-10-14 15:11:36 +01:00
Akinwale Ariwodola 4940d1ca33 Merge branch 'master' of https://github.com/lbryio/lbry-android 2020-10-14 15:10:25 +01:00
Akinwale Ariwodola 3d48fa5741 also check pending when checking if item is a placeholder 2020-10-14 15:09:59 +01:00
yuval f9887cffae Fix issue #1030
Dismiss all active dialog fragment when entering PiP mode
So that PiP window contain the video only
2020-10-13 23:17:58 +03:00
Akinwale Ariwodola 6644907665 Merge pull request #1027 from ycohen-dev/fix_issue_1025
Fix issue #1025
2020-10-12 19:25:48 +01:00
Akinwale Ariwodola 5f850685d6 bumpversion 0.16.7 --> 0.16.8 2020-10-12 11:48:24 +01:00
Akinwale Ariwodola 5f9674e49c do not open lbry.*/$/verify links in the app 2020-10-12 11:47:45 +01:00
yuval 0d185c6db3 Fix issue #1025
Increased size of currency selection spinner in publish form fragment
Now spinner is in proper size to display "LBRY Credits" default value
2020-10-10 16:58:29 +03:00
Akinwale Ariwodola 53d22dd22d remove debug logs 2020-10-09 07:43:38 +01:00
Akinwale Ariwodola ff8ffda3c6 bumpversion 0.16.6 --> 0.16.7 2020-10-09 07:39:46 +01:00
Akinwale Ariwodola 64bd540322 In-app notification options (#1023)
* pull-down to refresh in-app notifications
* support deleting notifications
2020-10-09 07:38:47 +01:00
Akinwale Ariwodola 919f9a48f3 Merge pull request #1022 from lbryio/bell-icon
per-channel subscribe notification toggle
2020-10-09 06:58:08 +01:00
Akinwale Ariwodola 746d442051 per-channel subscribe notification toggle 2020-10-09 06:56:13 +01:00
Akinwale Ariwodola 1877b75188 fix strings.xml 2020-10-06 07:14:42 +01:00
Akinwale Ariwodola 6e8c38cace update module versions 2020-10-05 16:56:17 +01:00
Akinwale Ariwodola eab7bab267 Credits icon (#1021)
* new credits icon
* remove references to LBC
2020-10-05 16:50:39 +01:00
Akinwale Ariwodola aab648c3cf Fix errors with deep link handling (#1019) 2020-10-02 12:39:37 +01:00
Javi Rueda f79ff509bd Support some lbry hosts to deep links. Add unit tests (#1008)
* Support lbry.tv and other supported hosts for deep links. Add unit tests for LbryUri parse() method
* add unit test for lbry protocol schema
* Add unit test for lbry.tv deep-link with only channel
2020-10-02 12:34:38 +01:00
Akinwale Ariwodola 1197e990ca cleanup debug logging 2020-10-02 12:09:33 +01:00
Akinwale Ariwodola dce1c0715e move Unpublish button 2020-10-02 12:08:33 +01:00
Akinwale Ariwodola 6a0263c5bc Merge pull request #1013 from clay53/987
Add ability to download & delete your own videos and move unpublish button to description
2020-10-02 11:05:44 +01:00
Akinwale Ariwodola ca64db0499 sdk 0.82.0 2020-10-01 12:42:48 +01:00
Akinwale Ariwodola a5d4eda4d1 bumpversion 0.16.5 --> 0.16.6 2020-09-25 14:45:48 +01:00
Akinwale Ariwodola 5d210961c1 apply mature filter to Editor's Choice 2020-09-25 14:41:40 +01:00
Akinwale Ariwodola 1b88f565af bumpversion 0.16.4 --> 0.16.5 2020-09-23 16:37:41 +01:00
Akinwale Ariwodola 991a98b571 fix shuffle mode player getting stuck 2020-09-23 16:35:59 +01:00
Akinwale Ariwodola 0073277d6e Merge pull request #1017 from lbryio/shuffle-random
keep track of watched content for subsequent shuffle sessions
2020-09-23 16:23:57 +01:00
Akinwale Ariwodola eeca602f7a keep track of watched content for subsequent shuffle sessions 2020-09-23 15:31:34 +01:00
Akinwale Ariwodola 6c171560fd remove Finnish strings 2020-09-18 14:56:35 +01:00
Akinwale Ariwodola 66c4c00215 bumpversion 0.16.3 --> 0.16.4 2020-09-18 14:54:59 +01:00
Akinwale Ariwodola 9b9ef9ab74 Surf mode experiment (#1003)
* surf mode implementation
* occupy entire vertical area
* fix onResume logic
* shuffle mode with selected channel ids
2020-09-18 14:53:19 +01:00
Clayton Hickey 39a289e7f1 Add ability to download & delete your own videos and move unpublish button to description 2020-09-16 14:31:03 -04:00
Akinwale Ariwodola 722c829502 fix paid content stream source 2020-09-14 18:21:31 +01:00
Akinwale Ariwodola 7ecb80d136 Merge pull request #1009 from lbryio/mini-player-margin
add setting for mini-player bottom spacing
2020-09-14 18:05:09 +01:00
Akinwale Ariwodola ea19af04d4 add setting for mini-player bottom spacing 2020-09-14 18:01:38 +01:00
Akinwale Ariwodola 8196b69211 bumpversion 0.16.2 --> 0.16.3 2020-09-14 11:20:47 +01:00
Akinwale Ariwodola dc861caf6c fix websocket for Android < 7.0 2020-09-14 11:19:50 +01:00
Akinwale Ariwodola adb5ffa8d0 exclude x86_64 lib from build 2020-09-14 11:06:39 +01:00
Akinwale Ariwodola d918cb28bd sdk 0.81.0 2020-09-11 13:50:16 +01:00
Akinwale Ariwodola 7ce7314ab9 bumpversion 0.16.1 --> 0.16.2 2020-09-11 13:41:30 +01:00
Javi Rueda 13e5caa0ef Use Start/End instead of Left/Right to support RTL (#1005)
* Use Start/End instead of Left/Right to support RTL
* Change it also for relative layout properties
2020-09-11 13:28:37 +01:00
Akinwale Ariwodola ff59a7a89f Merge pull request #1007 from lbryio/first-run-install-id
generate install_id natively
2020-09-11 13:22:42 +01:00
Akinwale Ariwodola c3efa4d004 generate install_id natively 2020-09-10 12:20:49 +01:00
Akinwale Ariwodola ed50e1300a real time notifications over websocket (#1000)
* real time notifications over websocket
* automatically re-establish websocket connections
2020-09-09 14:16:22 +01:00
Akinwale Ariwodola 86dbfd54d1 Merge pull request #1006 from lbryio/notification-back
proper back navigation to the notifications screen
2020-09-09 14:05:29 +01:00
Akinwale Ariwodola 535120eebd proper back navigation to the notifications screen 2020-09-09 14:03:36 +01:00
Akinwale Ariwodola c1106d7186 display correct playback speed for media 2020-09-04 12:50:22 +01:00
Akinwale Ariwodola 45be7f2c9b Merge pull request #1004 from lbryio/player-resume-black-screen
display player view correctly after dismissing PIP view
2020-09-04 12:33:53 +01:00
Akinwale Ariwodola d6baf3d1c8 display player view correctly after dismissing PIP view 2020-09-04 12:32:53 +01:00
Akinwale Ariwodola 08c38c1723 bumpversion 0.16.0 --> 0.16.1 2020-08-28 10:07:20 +01:00
Javi Rueda af4fa454d3 Add setting to enable sending buffering events (#993)
* Add setting to enable sending buffering events
* Use true as default value
2020-08-28 10:06:41 +01:00
Akinwale Ariwodola 0620582a4e fix in-app notification read background in dark mode 2020-08-28 10:04:10 +01:00
Akinwale Ariwodola b11c07e3d1 fix comment redirect from device notifications 2020-08-28 10:00:57 +01:00
Akinwale Ariwodola 593b34079c load notifications after app startup 2020-08-20 20:47:14 +01:00
Akinwale Ariwodola becb533624 fix notification relative time display 2020-08-20 20:32:22 +01:00
Akinwale Ariwodola 8efc0522f2 load unread count after fetching remote notifications 2020-08-20 20:03:30 +01:00
Akinwale Ariwodola cead924ca5 Notification timestamp timezone fix. Tweak loading unread notification count. 2020-08-20 19:56:35 +01:00
Akinwale Ariwodola f83a043664 fix notification sorting 2020-08-20 19:00:21 +01:00
Akinwale Ariwodola e8a0bca5ea tweak equality check for LbryNotification 2020-08-20 18:45:02 +01:00
Akinwale Ariwodola 1198c2298a add and update translations 2020-08-20 18:28:32 +01:00
Akinwale Ariwodola 7205acb9d6 Sort newly added notifications. Add remote loading TTL. 2020-08-20 18:06:35 +01:00
Akinwale Ariwodola d21cfd55ab Handle special URLs from notifications. Disable auto load/play for comment notifications. 2020-08-20 16:39:45 +01:00
Akinwale Ariwodola 47cbc3624c Merge pull request #980 from lbryio/channel-comment-hash
properly handle channel comment notifications
2020-08-20 16:26:08 +01:00
Akinwale Ariwodola 1f9a0886a0 properly handle channel comment notifications 2020-08-20 16:20:46 +01:00
Akinwale Ariwodola dd5ea68915 new YRBL 2020-08-20 14:52:41 +01:00
Akinwale Ariwodola b3bba4d273 Merge pull request #979 from lbryio/is-seen
check is_seen flag. display comment author thumbnails if present.
2020-08-20 13:30:28 +01:00
Akinwale Ariwodola 10c123ba6a check is_seen flag. display comment author thumbnails if present. 2020-08-20 13:26:41 +01:00
Akinwale Ariwodola a8ba45b941 bumpversion 0.15.17 --> 0.16.0 2020-08-19 18:18:37 +01:00
Akinwale Ariwodola 3652cdf6bc CI apt-transport-https 2020-08-19 18:14:13 +01:00
Akinwale Ariwodola f2a7a8c439 cleanup: yarn.lock 2020-08-19 18:10:57 +01:00
Akinwale Ariwodola 78d5a99441 Gradle fix (#978) 2020-08-19 18:09:37 +01:00
Akinwale Ariwodola 6931dbe79c Instant verification (#974)
* add instant verification options and Google Play Billing
bumpversion 0.15.16 --> 0.15.17
restore account_undergo_review default string
twitter sign-in flow
fix build error
final changes
update api key and secret
* tweak build script
2020-08-19 17:23:35 +01:00
Akinwale Ariwodola 4d024c06cc In-app notifications (#969)
* display notification bell icon beside URL bar
* notification model
* persist received notifications
* Refresh notification list. Add  is_read flag and display unread count.
* Hide notifications when opening the navigatinon drawer. Open selected notification item before hiding the list.
* update local store with remote notifications
* use card view for notification items
* make notification cards clickable
* handle comment hash
* fix remote notifications not loading. fix comment scroll.
* Improve in-app comment notification linking. Add icons.
2020-08-18 14:19:35 +01:00
Akinwale Ariwodola ddcb190457 do not display global background servce initializing indicator 2020-08-07 10:11:57 +01:00
Akinwale Ariwodola dd14b90d7e Merge pull request #967 from kekkyojin/sendto-feat
Allow to publish files via Send To feature
2020-07-29 15:20:59 +01:00
Akinwale Ariwodola 4b86444478 bumpversion 0.15.15 --> 0.15.16 2020-07-27 11:11:10 +01:00
Javi Rueda feb7f260dc Allow to publish files via Send To feature 2020-07-24 01:59:59 +02:00
Akinwale Ariwodola 74c7a1de4d sdk 0.79.1. Clear resolved sub cache after sync. 2020-07-23 20:04:48 +01:00
Akinwale Ariwodola 88a43dc679 set sync interval back to 5 minutes 2020-07-22 05:52:44 +01:00
Akinwale Ariwodola 1bb5ce72fa Proper fix for subscription sync retention. Eliminate double sync attempt on startup. 2020-07-22 05:49:48 +01:00
Akinwale Ariwodola b4ce544965 bumpversion 0.15.14 --> 0.15.15 2020-07-21 21:25:26 +01:00
Akinwale Ariwodola 1ec6f6173a sdk 0.79.0 2020-07-21 21:13:05 +01:00
Akinwale Ariwodola 8ee19b3f5c Sub sync fix (#965)
* improve sub sync merge handling logic
* do not try to re-subscribe local syncs remotely whhen merging
2020-07-21 19:49:22 +01:00
Akinwale Ariwodola 1055392b7f temporarily omit duration 2020-07-21 19:39:47 +01:00
Akinwale Ariwodola c772cf2ead check buffering events (#952)
* check buffering events
* use the claim permanent url for buffer events
* update request parameters
* hash user ids for buffer events
* update buffer event endpoint
2020-07-21 19:30:45 +01:00
Akinwale Ariwodola 481c50f465 fix open.lbry.com regex 2020-07-17 11:39:59 +01:00
Akinwale Ariwodola 71bc969f2a Merge pull request #962 from kekkyojin/deeplink
Add open.lbry.com deep-links
2020-07-17 11:29:16 +01:00
Akinwale Ariwodola e4edebfed7 fix for follow / unfollow confusion 2020-07-16 13:51:08 +01:00
Javi Rueda e8a5ab8307 Add open.lbry.com deep-links 2020-07-13 19:00:12 +02:00
Akinwale Ariwodola 3738f3af21 Merge pull request #954 from lbryio/invalidated-auth
gracefully handle invalidated auth tokens
2020-07-05 19:07:21 +01:00
Akinwale Ariwodola 74d10e4199 gracefully handle invalidated auth tokens 2020-07-05 18:40:31 +01:00
Akinwale Ariwodola 080e00becf Merge pull request #949 from kekkyojin/patch-1
Bintray repository is no longer needed
2020-06-30 15:30:18 +01:00
Javi Rueda 049d905d7d Bintray repository is no longer needed
LBRY SDK is now hosted on JCenter, which is already available out-of-the-box on Android Studio. The Bintray url is no longer reguired. When building LBRY on F-Droid, I have to remove this line on the build YAML script and it is building correctly.

On my local machine, it builds after commenting it.
2020-06-26 21:06:12 +02:00
Akinwale Ariwodola 33094f8c88 fix empty bindArgs crash error for sql query to clear subscriptions 2020-06-25 23:33:04 +01:00
Akinwale Ariwodola 6c44e503db fix subscriptions sync (#947) 2020-06-25 21:16:41 +01:00
Akinwale Ariwodola fa78c80592 fix ClaimListAdapter and strings.xml 2020-06-25 20:42:55 +01:00
Akinwale Ariwodola 07630ca97b fix: crash bugs 2020-06-25 20:23:24 +01:00
Akinwale Ariwodola a2b6d4e570 bumpversion 0.15.13 --> 0.15.14 2020-06-25 20:16:38 +01:00
Akinwale Ariwodola 9d6b3ddf81 combined tip / support dialog and signed supports (#944)
* combined tip / support dialog and signed supports
* update button label when amount is updated
2020-06-25 20:15:58 +01:00
Akinwale Ariwodola 0a2769859a fix issue with featured search result crash 2020-06-24 10:45:29 +01:00
Akinwale Ariwodola c4a1ed801a make FontAwesome strings non-translatable 2020-06-19 07:18:19 +01:00
Akinwale Ariwodola 453394bf1b update README 2020-06-19 06:57:48 +01:00
Akinwale Ariwodola 4b7dfba5a1 sdk 0.76.0 2020-06-15 19:43:41 +01:00
Akinwale Ariwodola e699fcf0b3 remove broken Bengali strings.xml 2020-06-15 19:29:26 +01:00
Akinwale Ariwodola 7e80f707e0 bumpversion 0.15.12 --> 0.15.13 2020-06-15 19:17:18 +01:00
Akinwale Ariwodola 467f037170 sFix default sort on channel page. Add Bengali and Javanese translations. 2020-06-15 19:11:20 +01:00
Akinwale Ariwodola 89d5b40e5f only allow sending to addresses that begin with b 2020-06-15 15:18:42 +01:00
Akinwale Ariwodola 34fba010e1 use lbryplayer.xyz streaming URLs for signed in users 2020-06-15 15:07:17 +01:00
Akinwale Ariwodola d7396bb044 add MoonPay 'Buy LBC' button (#937)
* add MoonPay 'Buy LBC' button
* tweak button style
* tweak MoonPay parameters
2020-06-13 16:14:06 +01:00
joaquimbrugues fda0817ad1 Add Catalan language (#928)
* Add Catalan language
* Add 'catalan' string to strings.xml
* Attempt to fix conflicting changes
2020-06-11 19:41:53 +01:00
Akinwale Ariwodola 895ca75506 Merge pull request #935 from lbryio/edit-publish-channel
auto select corresponding channel when editing a publish
2020-06-11 19:38:24 +01:00
Akinwale Ariwodola a04448ebe8 auto select corresponding channel when editing a publish 2020-06-11 19:31:06 +01:00
Akinwale Ariwodola 26ccbf2709 reduce comment cost from 2 to 1 2020-06-10 09:54:07 +01:00
Akinwale Ariwodola 7d6c11a88c Remove lbrysdk AARs. Add bintray dependencies. 2020-06-09 22:27:42 +01:00
Akinwale Ariwodola 8742913c33 SDK 0.75.0. Update translations. 2020-06-05 15:31:13 +01:00
Akinwale Ariwodola 8e6e0f0099 fix player notification pending intent 2020-06-05 09:42:45 +01:00
Akinwale Ariwodola a4585de807 reset playback notification large icon when content changes 2020-06-05 09:40:22 +01:00
Akinwale Ariwodola 6c24749ad5 tweak player view resume 2020-06-05 09:34:45 +01:00
Akinwale Ariwodola c73509a4ca set large icon for playback notification 2020-06-05 09:30:54 +01:00
Akinwale Ariwodola 673b85b2aa bumpversion 0.15.11 --> 0.15.12 2020-06-05 09:07:35 +01:00
Akinwale Ariwodola fe6e60cd67 implement background playback with control notification 2020-06-05 09:04:24 +01:00
Akinwale Ariwodola 8bcee90d68 Add background playback setting. Fix crash bugs. 2020-06-05 08:25:08 +01:00
Akinwale Ariwodola 084407e129 Update translations. Add Catalan and Serbian strings. 2020-06-05 07:50:52 +01:00
Akinwale Ariwodola 4a3db5ae20 enforce minimum spend / deposits 2020-06-05 07:40:44 +01:00
Akinwale Ariwodola b36813ebe6 fix nsfw search flag 2020-06-05 07:23:56 +01:00
Akinwale Ariwodola cc1ddfa16e use only txids for unlocking tips 2020-06-05 07:17:56 +01:00
Akinwale Ariwodola 5f1775d478 fix possible null item in channel id list 2020-06-05 07:04:54 +01:00
Akinwale Ariwodola 288e35dd64 fix margins 2020-06-02 09:40:17 +01:00
Akinwale Ariwodola d4af28d1c5 display publisher title and thumbnail on file page 2020-06-02 09:34:59 +01:00
Akinwale Ariwodola 37cf85a5f6 bumpversion 0.15.10 --> 0.15.11 2020-06-02 09:05:04 +01:00
Akinwale Ariwodola c2cbd76f49 change comment confirmation title 2020-06-02 09:03:56 +01:00
Akinwale Ariwodola 3d874435c3 change BigDecimal initialisation for comment cost 2020-06-02 08:57:12 +01:00
Akinwale Ariwodola 9ed8864f23 More crash fixes. Change comment cost to 2 LBC. 2020-06-02 08:55:34 +01:00
Akinwale Ariwodola 61263dd59d bumpversion 0.15.9 --> 0.15.10 2020-06-01 08:56:38 +01:00
Akinwale Ariwodola 2707e135c6 comment creation event 2020-06-01 08:53:58 +01:00
Akinwale Ariwodola f9de0d7937 do not prompt again for content that is already purchased 2020-06-01 08:48:17 +01:00
Akinwale Ariwodola f03d58d648 tweak PIP player for certain aspect ratios 2020-06-01 08:33:07 +01:00
Akinwale Ariwodola f49a3570e9 fix file view display for cached reposts 2020-05-31 21:22:37 +01:00
Akinwale Ariwodola 1d97f9008d implement commenting with tips (#922)
* implement commenting with tips
* add comments to channel page
2020-05-31 21:06:03 +01:00
Akinwale Ariwodola e85ca9114c Merge pull request #921 from lbryio/crash-fixes
fixes for Play Store crash reports
2020-05-31 16:20:59 +01:00
Akinwale Ariwodola 85ed2da518 fixes for Play Store crash reports 2020-05-31 16:19:33 +01:00
Clayton Hickey dcc91f75cc Added ability to read comments on claims (#920)
* Added ability to read comments on claims
* Added simple handling for pagination in CommentListTask
2020-05-30 00:47:50 +01:00
Akinwale Ariwodola a40c160ac6 fix selection mode for reposts on Publishes page 2020-05-28 03:45:56 +01:00
Akinwale Ariwodola e6861c8436 set timestamp when building claim object from edited claim 2020-05-28 03:25:42 +01:00
Akinwale Ariwodola e6a5d97fb8 bumpversion 0.15.8 --> 0.15.9 2020-05-28 03:23:45 +01:00
Akinwale Ariwodola ddeb209d51 fix publish release time and crash bug on publish form 2020-05-28 03:22:20 +01:00
Akinwale Ariwodola 3283b3a607 fix channel links on history page 2020-05-27 23:22:08 +01:00
Akinwale Ariwodola 83a41ca6ce auto-rotate video to sensor landscape orientation 2020-05-27 23:16:25 +01:00
Akinwale Ariwodola 6c63eb7d66 better handling of permanent storage permission denial on file view page 2020-05-27 23:11:09 +01:00
Akinwale Ariwodola 7cf9de8c2a fix typo 2020-05-27 23:01:00 +01:00
Akinwale Ariwodola a859682954 fix permission request handling for permanently denied permissions 2020-05-27 22:56:07 +01:00
Akinwale Ariwodola c844c4f896 fix PIP mode display for Android version < 10 2020-05-27 11:20:51 +01:00
Akinwale Ariwodola a49cfe91da remove debug logs 2020-05-27 10:58:28 +01:00
Akinwale Ariwodola 2bacba2c87 properly close all activities when service is stopped 2020-05-27 10:52:25 +01:00
Akinwale Ariwodola e473981063 fix more crash bugs reported in Play Store 2020-05-27 08:25:10 +01:00
Akinwale Ariwodola 34ea4f216c add Dutch and Hindi strings 2020-05-27 02:06:41 +01:00
Akinwale Ariwodola 52e34b3027 don't hide play / pause button while buffering 2020-05-27 01:15:02 +01:00
Akinwale Ariwodola c6a6ea0445 reset click listener onStop 2020-05-27 01:11:18 +01:00
Akinwale Ariwodola 59ae6340e1 disable gif animation in thumbnails 2020-05-27 00:56:07 +01:00
Akinwale Ariwodola cbf2aa2311 bumpversion 0.15.6 --> 0.15.7 2020-05-26 16:26:15 +01:00
Akinwale Ariwodola 94b0c7bc01 Fix additional Play Store crash bugs. 2020-05-26 16:25:37 +01:00
Akinwale Ariwodola 4c50ffac19 Merge pull request #898 from lbryio/user-bugs
fix reported bugs from 0.15.3
2020-05-26 16:09:51 +01:00
Akinwale Ariwodola 551e736651 fix reported bugs from 0.15.3 2020-05-26 16:09:14 +01:00
Akinwale Ariwodola 0380e35966 bumpversion 0.15.5 --> 0.15.6 2020-05-26 10:58:47 +01:00
Akinwale Ariwodola 5de0906fc1 make splash view clickable to prevent clicking views underneath 2020-05-26 10:57:12 +01:00
Akinwale Ariwodola c2f17b6230 Add Italian strings. Save and resume from last media playback position. 2020-05-26 10:38:16 +01:00
Akinwale Ariwodola 6a3bbe6c0d bumpversion 0.15.4 --> 0.15.5 2020-05-25 20:10:34 +01:00
Akinwale Ariwodola 82307c9f98 Increase timeout for remote user requests. Wrap long pre lines in markdown display. 2020-05-25 20:08:24 +01:00
Akinwale Ariwodola d2ec0e2aa1 Display reposts on following page. Update Spanish strings. 2020-05-25 15:15:48 +01:00
Akinwale Ariwodola 3951b1080d different new publish from publish update 2020-05-25 12:14:12 +01:00
Akinwale Ariwodola ef7caeeead Fix subsequent web view display. Add Estonian and Russian strings. 2020-05-25 11:33:12 +01:00
Akinwale Ariwodola 7ef8e2029e Tweak transaction pending text display 2020-05-25 06:03:46 +01:00
Akinwale Ariwodola aaec6ac6a3 wait for uploads to finish before saving channel form 2020-05-25 06:00:34 +01:00
Akinwale Ariwodola 731960da7c bumpversion 0.15.3 --> 0.15.4 2020-05-25 05:50:02 +01:00
Akinwale Ariwodola ac282d2667 log cleanup 2020-05-25 05:48:26 +01:00
Akinwale Ariwodola 7a79601cfc don't enable fullscreen mode when entering PIP mode 2020-05-25 05:47:14 +01:00
Akinwale Ariwodola d1167e4d2b Disable selection mode for purchases. Check additional cases for displaying unsupported content message. 2020-05-25 05:38:25 +01:00
Akinwale Ariwodola 613634adcf get transaction id for first_publish and new_channel rewards 2020-05-25 00:32:21 +01:00
Akinwale Ariwodola acbe33c66d Limit gallery items to 150. Download filtering. Open rewards page from Invites reward driver card. 2020-05-25 00:04:40 +01:00
Akinwale Ariwodola 053ebbd70b dDisplay better error message if authentication fails on first run. Change lineHeight to lineSpacingMultiplier. 2020-05-24 21:27:49 +01:00
Akinwale Ariwodola f5dc4fa4e7 Remove new intent debug logs. Update packages in build.gradle 2020-05-24 20:48:01 +01:00
Akinwale Ariwodola 343270b757 Show auto-claim rewards message at activity level. Add German strings. 2020-05-24 20:34:19 +01:00
Akinwale Ariwodola 65f5626aba More tweaks to PIP mode restore. 2020-05-24 20:29:11 +01:00
Akinwale Ariwodola a051a73c2b Tweak PIP restore. Fix Library wunderbar value. 2020-05-24 18:54:33 +01:00
Akinwale Ariwodola 6840997793 Add 'subscription' to special URLs map. Fix PIP restore for onNewIntent. 2020-05-24 18:46:47 +01:00
Akinwale Ariwodola 2c98ed2d8d Always display rewards driver on Invites page. Rewards drivers minimum display amounts. 2020-05-24 18:37:05 +01:00
Akinwale Ariwodola 6a083c4152 Update Afrikaans strings. Add Vietnamese strings. 2020-05-24 18:18:39 +01:00
Akinwale Ariwodola b60b5d16c3 fix crash bugs reported in Play Store 2020-05-24 10:11:31 +01:00
Akinwale Ariwodola 52cfe8dc12 add blocking param to txo_spend 2020-05-24 05:02:55 +01:00
Akinwale Ariwodola 737afca031 fix onNewIntent logging 2020-05-24 04:50:13 +01:00
Akinwale Ariwodola 456f41d28d Prevent image click through. Add Romanian strings. 2020-05-24 04:43:39 +01:00
Akinwale Ariwodola 238f59ad71 display correct label and amount for tip unlocks in tx history 2020-05-24 00:08:14 +01:00
Akinwale Ariwodola cf6d567193 unify button font 2020-05-23 23:47:32 +01:00
Akinwale Ariwodola 20f8f3852d Merge pull request #888 from lbryio/unlock-tips
add option to unlock all tips
2020-05-23 23:39:16 +01:00
Akinwale Ariwodola 4bb9f5cb43 add option to unlock all tips 2020-05-23 23:37:57 +01:00
Akinwale Ariwodola 540a841255 Fix pip restore and fullscreen quirks. French and Portuguese strings added. 2020-05-23 19:42:30 +01:00
Akinwale Ariwodola 3544637405 Fix reward code claiming. Remove broken French strings file. 2020-05-23 17:48:58 +01:00
Akinwale Ariwodola 651448dfa1 Merge pull request #886 from lbryio/reward-drivers
Add reward drivers. French, Indonesian, Malay and Turkish strings.
2020-05-23 17:46:16 +01:00
Akinwale Ariwodola 4bac266b8b Add reward drivers. French, Indonesian, Malay and Turkish strings. 2020-05-23 17:45:19 +01:00
Akinwale Ariwodola f86b61741d Merge pull request #885 from lbryio/visual-tweaks
Use thin divider in transaction history. Set font for action bar title.
2020-05-23 15:18:43 +01:00
Akinwale Ariwodola 6c60d299af Use thin divider in transaction history page. Set font for action bar title. 2020-05-23 15:17:43 +01:00
Akinwale Ariwodola 08582238c3 Merge pull request #884 from lbryio/dark-theme-fix
Fix dark theme reset error due to WebView. Apply dark theme to web views.
2020-05-23 09:41:59 +01:00
Akinwale Ariwodola b931d0ce7d Fix dark theme reset error due to WebView. Apply dark theme to web views. 2020-05-23 09:37:58 +01:00
Akinwale Ariwodola 5e1fc9dbd8 Merge pull request #883 from lbryio/fullscreen-on-rotate
switch to fullscreen mode on rotate when viewing media
2020-05-23 09:03:00 +01:00
Akinwale Ariwodola de4e6eee25 switch to fullscreen mode on rotate when viewing media 2020-05-23 09:01:30 +01:00
Akinwale Ariwodola d5b4e6990f update material components version 2020-05-23 07:53:58 +01:00
Akinwale Ariwodola 26703815b2 cleanup top level directory 2020-05-23 07:51:56 +01:00
Akinwale Ariwodola 40c36df414 Native rewrite (#878)
* initial native rewrite commit
* update gitlab CI script
* add printVersionName gradle task
* fix Gitlab CI script
* Fix first time wallet sync. add Discover dialog to  Following page.
* Finish Following and All Content views. Add customize your tags view.
* Wallet sync get and set preferences, update interval.
* Editor's Choice. Reposts. Some ontent page tweaks.
* display no related content view when none loaded
* Search cache. File view updates. Floating wallet balance.
* Send tip dialog. Channel page share and follow/unfollow.
* Handle lbry:// url scheme. Properly set URL bar values. SDK 0.71.0.
* Channel follow/unfollow fixes. Display stream cost.
* Channel management and channel creation / editing
* phone number verification and rewards page
* add Invites page
* tweak player loading and playback when loading new claims
* tweak about page layout
* display text and markdown content
* purchase_uri for free content
* don't display invites history if none exist
* fix channel list adapters
* change launch mode from singleInstance to singleTask
* url history and player fixes
* Library page. URL and view history.
* bumpversion 0.15.0 --> 0.15.1
* Make file view a fragment to prevent headaches with multiple Android task recents
* Better handling of file view URLs. Some issue list fixes.
* Abandon channels and bulk delete files tasks. Some visual tweaks.
* bumpversion 0.15.1 --> 0.15.2
* fix some events
* Some visual tweaks. Wunderbar clear focus hotfix for some devices.
* sdk 0.74.0. Publish and Publishes pages.
* Fix displayed amounts. Send Firebase token with install_new.
* Some dark theme and crash fixes. Implement publish form.
* Fix minor typo for string in 'generate_address_hint'.
* Publish form and publish creation flow. UI tweaks and fixes.
* Basic native mobile publishing
* remove closeDatabase calls causing crashes
* Implement file and channel page delete actions. UI action cleanup.
* publish drivers for unresolved file page and featured search result item
* show URL suggestions and data network (DHT) settings
* Filter own claims from downloads. Fix address input.
* fix edit channel crash
* fix for possible blank / invalid video thumbnails
* adjust minimum deposit. fix channel edit mode.
* quick skip and playback speed media controls
* change play and pause icons
* Fix file size display. Tweak playback speed control.
* Add exoplayer mediasession extension. Set player auto attributes.
* Inline publish address validation error. Increase image upload request timeout.
* fix no related content display
* Claim new_android reward. Use canonical_url for share links.
* force US locale for amount / bid values sent with sdk requests
* Afrikaans and Spanish strings
* Add media player error handling policy. Use : in share links.
* don't proceed with publish if optimization is in progress.
2020-05-23 07:49:00 +01:00
234 changed files with 24277 additions and 2797 deletions

No files matched your search

-3
View File
@@ -1,3 +0,0 @@
.buildozer
.buildozer-downloads
.gradle
+1
View File
@@ -60,6 +60,7 @@ buck-out/
# Other Files
app/google-services.json
app/twitter.properties
*.log
.vagrant
*.hprof
+21 -13
View File
@@ -8,10 +8,13 @@ build apk:
stage: build
image: lbry/android-base:platform-28
before_script:
- apt-get -y update && apt-get -y install build-essential ca-certificates curl git gpg-agent openjdk-8-jdk software-properties-common wget zipalign
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install build-essential ca-certificates curl git gpg-agent openjdk-8-jdk software-properties-common wget zipalign git-secret
- git secret reveal
- chmod u+x $CI_PROJECT_DIR/gradlew
- export ANDROID_SDK_ROOT=~/.buildozer/android/platform/android-sdk-23
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -p $CI_PROJECT_DIR -q printVersionName --console=plain | tail -1)
artifacts:
paths:
- bin/browser-*-release__arm.apk
@@ -19,12 +22,7 @@ build apk:
expire_in: 1 week
script:
- export PATH=/usr/bin:$PATH
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install git-secret
- git secret reveal
- yarn
- export ANDROID_SDK_ROOT=~/.buildozer/android/platform/android-sdk-23
- chmod u+x ./release.sh
- ./release.sh
- cp bin/browser-$BUILD_VERSION-release__arm.apk /dev/null
@@ -36,10 +34,15 @@ deploy build.lbry.io:
dependencies:
- build apk
before_script:
- apt-get -y update && apt-get -y install openjdk-8-jdk
- apt-get -y update && apt-get -y install apt-transport-https
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install openjdk-8-jdk git git-secret
- pip install awscli
- chmod u+x $CI_PROJECT_DIR/gradlew
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
- git secret reveal
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -p $CI_PROJECT_DIR -q printVersionName --console=plain | tail -1)
- export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk
- export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk
script:
@@ -55,10 +58,15 @@ release apk:
dependencies:
- build apk
before_script:
- apt-get -y update && apt-get -y install openjdk-8-jdk
- apt-get -y update && apt-get -y install apt-transport-https
- echo "$PGP_PRIVATE_KEY" | gpg --batch --import
- echo "deb https://dl.bintray.com/sobolevn/deb git-secret main" | tee -a /etc/apt/sources.list
- wget -O - https://api.bintray.com/users/sobolevn/keys/gpg/public.key | apt-key add -
- apt-get -y update && apt-get -y install openjdk-8-jdk git git-secret
- pip install awscli githubrelease
- git secret reveal
- chmod u+x $CI_PROJECT_DIR/gradlew
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -q printVersionName --console=plain | tail -1)
- export BUILD_VERSION=$($CI_PROJECT_DIR/gradlew -p $CI_PROJECT_DIR -q printVersionName --console=plain | tail -1)
- export BUILD_APK_FILENAME__32=browser-$BUILD_VERSION-release__arm.apk
- export BUILD_APK_FILENAME__64=browser-$BUILD_VERSION-release__arm64.apk
script:
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -1,2 +1,3 @@
lbry-android.keystore:0d958c531870694624cc877ea98ca1c583485f8ebbb3a5acca58b1930c190d65
app/google-services.json:896a0bee8294a36d061f10fa926129d8a780528b34d0a2f03113400c4246d67c
app/twitter.properties:01212d70712f2041efb5c814bf30ecbf6f72e1ca5179c7647c4f8cbd995dd033
+12 -2
View File
@@ -2,7 +2,7 @@
[![pipeline status](https://ci.lbry.tech/lbry/lbry-android/badges/master/pipeline.svg)](https://ci.lbry.tech/lbry/lbry-android/commits/master)
[![GitHub license](https://img.shields.io/github/license/lbryio/lbry-android)](https://github.com/lbryio/lbry-android/blob/master/LICENSE)
An Android browser and wallet for the [LBRY](https://lbry.com) network. This app bundles [LBRY SDK](https://github.com/lbryio/lbry) as a background service with a UI layer built with React Native.
An Android browser and wallet for the [LBRY](https://lbry.com) network.
<img src="https://spee.ch/@lbry:3f/android-08-homepage.gif" alt="LBRY Android GIF" width="384px" />
@@ -18,7 +18,17 @@ The minimum supported Android version is 5.0 Lollipop. There are two ways to ins
The app can be launched by opening **LBRY** from the device's app drawer or via the shortcut on the home screen if that was created upon installation.
## Running from Source
Please refer to https://github.com/lbryio/lbry-react-native/blob/master/README.md
Clone the repository and open the project in Android Studio. Android Studio will automatically run the initial build process.
Create file 'twitter.properties' in app/ folder with the following content:
```
twitterConsumerKey=XXXXXX
twitterConsumerSecret=XXXXXX
```
Click the Sync button and when process finishes, the Run button to launch the app on your simulator or connected debugging device after the build process is complete.
## Contributing
Contributions to this project are welcome, encouraged, and compensated. For more details, see https://lbry.io/faq/contributing
+57 -20
View File
@@ -1,3 +1,5 @@
import com.google.gms.googleservices.GoogleServicesPlugin
apply plugin: 'com.android.application'
android {
@@ -14,12 +16,17 @@ android {
applicationId "io.lbry.browser"
minSdkVersion 21
targetSdkVersion 29
versionCode 1503
versionName "0.15.3"
versionCode 1613
versionName "0.16.13"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'lib/x86_64/darwin/libscrypt.dylib'
}
productFlavors {
__32bit {
versionCode android.defaultConfig.versionCode * 10 + 1
@@ -36,7 +43,17 @@ android {
}
buildTypes {
debug {
Properties twitterProps = new Properties()
twitterProps.load(project.file('twitter.properties').newDataInputStream())
resValue "string", "TWITTER_CONSUMER_KEY", "\"${twitterProps.getProperty("twitterConsumerKey")}\""
resValue "string", "TWITTER_CONSUMER_SECRET", "\"${twitterProps.getProperty("twitterConsumerSecret")}\""
}
release {
Properties twitterProps = new Properties()
twitterProps.load(project.file('twitter.properties').newDataInputStream())
resValue "string", "TWITTER_CONSUMER_KEY", "\"${twitterProps.getProperty("twitterConsumerKey")}\""
resValue "string", "TWITTER_CONSUMER_SECRET", "\"${twitterProps.getProperty("twitterConsumerSecret")}\""
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
@@ -49,35 +66,49 @@ task printVersionName {
}
}
configurations {
all {
exclude module: 'httpclient'
exclude module: 'commons-logging'
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.appcompat:appcompat:1.3.0-alpha01'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.google.android.material:material:1.3.0-alpha01'
implementation "androidx.cardview:cardview:1.0.0"
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.navigation:navigation-fragment:2.2.2'
implementation 'androidx.navigation:navigation-ui:2.2.2'
implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
implementation 'androidx.navigation:navigation-fragment:2.3.1'
implementation 'androidx.navigation:navigation-ui:2.3.1'
implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
implementation 'androidx.preference:preference:1.1.1'
implementation 'androidx.webkit:webkit:1.4.0-rc01'
implementation 'androidx.camera:camera-core:1.0.0-beta03'
implementation 'androidx.camera:camera-camera2:1.0.0-beta03'
implementation 'androidx.camera:camera-lifecycle:1.0.0-beta03'
implementation 'androidx.camera:camera-view:1.0.0-alpha10'
implementation 'androidx.browser:browser:1.2.0'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'
implementation 'com.squareup.okhttp3:okhttp:4.4.1'
implementation 'com.google.firebase:firebase-analytics:17.4.0'
implementation 'com.google.android.gms:play-services-base:17.2.1'
implementation 'com.google.firebase:firebase-messaging:20.1.6'
implementation 'com.google.firebase:firebase-analytics:18.0.0'
implementation 'com.google.android.gms:play-services-base:17.5.0'
implementation 'com.google.firebase:firebase-messaging:21.0.0'
implementation 'com.google.oauth-client:google-oauth-client:1.30.4'
implementation 'com.android.billingclient:billing:3.0.2'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.google.android.exoplayer:exoplayer-core:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.11.4'
implementation 'com.google.android.exoplayer:extension-cast:2.11.4'
implementation 'com.google.android.exoplayer:extension-mediasession:2.11.4'
implementation 'com.google.android.exoplayer:exoplayer-core:2.12.2'
implementation 'com.google.android.exoplayer:exoplayer-dash:2.12.2'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.12.2'
implementation 'com.google.android.exoplayer:extension-cast:2.12.2'
implementation 'com.google.android.exoplayer:extension-mediasession:2.12.2'
implementation 'com.google.android:flexbox:2.0.1'
@@ -88,17 +119,23 @@ dependencies {
implementation 'com.arthenica:mobile-ffmpeg-full-gpl:4.3.1.LTS'
implementation 'commons-codec:commons-codec:1.15'
implementation 'org.bitcoinj:bitcoinj-tools:0.14.7'
implementation 'org.java-websocket:Java-WebSocket:1.5.1'
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'
androidTestImplementation 'androidx.test:runner:1.3.0'
androidTestImplementation 'androidx.test:rules:1.3.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
__32bitImplementation files('libs/lbrysdk-0.74.0-release__arm.aar')
__64bitImplementation files('libs/lbrysdk-0.74.0-release__arm64.aar')
__32bitImplementation 'io.lbry:lbrysdk32:0.87.0'
__64bitImplementation 'io.lbry:lbrysdk64:0.87.0'
}
apply plugin: 'com.google.gms.google-services'
com.google.gms.googleservices.GoogleServicesPlugin.config.disableVersionCheck = true
GoogleServicesPlugin.config.disableVersionCheck = true
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,15 @@
package io.lbry.browser.utils;
import androidx.test.filters.SmallTest;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
@SmallTest
public class HelperTest {
@Test
public void SHA256() {
assertEquals("de9edb2044d012f04553e49b04d54cbec8e8a46a40ad5a19bc5dcce1da00ecfd", Helper.SHA256(String.valueOf(12345678912345L)));
}
}
+28
View File
@@ -10,6 +10,8 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.android.vending.BILLING" />
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
android:allowBackup="true"
@@ -50,12 +52,38 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="video/*" />
<data android:mimeType="image/*" />
<data android:mimeType="text/*" />
</intent-filter>
<intent-filter>
<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>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" android:host="open.lbry.com"/>
<data android:scheme="https" android:host="lbry.tv" android:pathPattern="/..*/*" />
<data android:scheme="https" android:host="lbry.tv" android:pathPattern="/.*:.*" />
<data android:scheme="https" android:host="lbry.tv" android:pathPattern="/.*#.*" />
<data android:scheme="https" android:host="lbry.lat" android:pathPattern="/..*/*" />
<data android:scheme="https" android:host="lbry.lat" android:pathPattern="/.*:.*" />
<data android:scheme="https" android:host="lbry.lat" android:pathPattern="/.*#.*" />
<data android:scheme="https" android:host="lbry.fr" android:pathPattern="/..*/*" />
<data android:scheme="https" android:host="lbry.fr" android:pathPattern="/.*:.*" />
<data android:scheme="https" android:host="lbry.fr" android:pathPattern="/.*#.*" />
<data android:scheme="https" android:host="lbry.in" android:pathPattern="/..*/*" />
<data android:scheme="https" android:host="lbry.in" android:pathPattern="/.*:.*" />
<data android:scheme="https" android:host="lbry.in" android:pathPattern="/.*#.*" />
<category android:name="android.intent.category.BROWSABLE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
Binary file not shown.
@@ -10,20 +10,31 @@ 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 java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import io.lbry.browser.exceptions.AuthTokenInvalidatedException;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.Lbryio;
import io.lbry.lbrysdk.LbrynetService;
import io.lbry.lbrysdk.ServiceHelper;
import io.lbry.lbrysdk.Utils;
public class FirstRunActivity extends AppCompatActivity {
private BroadcastReceiver sdkReadyReceiver;
private BroadcastReceiver sdkReceiver;
private BroadcastReceiver authReceiver;
@Override
@@ -43,21 +54,51 @@ public class FirstRunActivity extends AppCompatActivity {
});
registerAuthReceiver();
if (!Lbry.SDK_READY) {
findViewById(R.id.welcome_wait_container).setVisibility(View.VISIBLE);
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_SDK_READY);
sdkReadyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
findViewById(R.id.welcome_wait_container).setVisibility(View.VISIBLE);
IntentFilter filter = new IntentFilter();
filter.addAction(MainActivity.ACTION_SDK_READY);
filter.addAction(LbrynetService.ACTION_STOP_SERVICE);
sdkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (MainActivity.ACTION_SDK_READY.equals(action)) {
// authenticate after we receive the sdk ready event
authenticate();
} else if (LbrynetService.ACTION_STOP_SERVICE.equals(action)) {
finish();
if (MainActivity.instance != null) {
MainActivity.instance.finish();
}
}
};
registerReceiver(sdkReadyReceiver, filter);
} else {
authenticate();
}
}
};
registerReceiver(sdkReceiver, filter);
CheckInstallIdTask task = new CheckInstallIdTask(this, new CheckInstallIdTask.InstallIdHandler() {
@Override
public void onInstallIdChecked(boolean result) {
// start the sdk from FirstRun
boolean serviceRunning = MainActivity.isServiceRunning(MainActivity.instance, LbrynetService.class);
if (!serviceRunning) {
Lbry.SDK_READY = false;
ServiceHelper.start(MainActivity.instance, "", LbrynetService.class, "lbrynetservice");
}
if (result) {
// install_id generated and validated, authenticate now
authenticate();
return;
}
// we weren't able to generate the install_id ourselves, depend on the sdk for that
if (Lbry.SDK_READY) {
authenticate();
return;
}
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void onResume() {
@@ -97,7 +138,8 @@ public class FirstRunActivity extends AppCompatActivity {
}
private void handleAuthenticationFailed() {
Toast.makeText(this, "Authentication failed.", Toast.LENGTH_LONG).show();
findViewById(R.id.welcome_progress_bar).setVisibility(View.GONE);
((TextView) findViewById(R.id.welcome_wait_text)).setText(R.string.startup_failed);
}
private void authenticate() {
@@ -121,17 +163,89 @@ public class FirstRunActivity extends AppCompatActivity {
@Override
protected void onDestroy() {
Helper.unregisterReceiver(authReceiver, this);
Helper.unregisterReceiver(sdkReadyReceiver, this);
Helper.unregisterReceiver(sdkReceiver, this);
super.onDestroy();
}
private void generateIdAndAuthenticate() {
}
private static class CheckInstallIdTask extends AsyncTask<Void, Void, Boolean> {
private Context context;
private InstallIdHandler handler;
public CheckInstallIdTask(Context context, InstallIdHandler handler) {
this.context = context;
this.handler = handler;
}
protected Boolean doInBackground(Void... params) {
// Load the installation id from the file system
String lbrynetDir = String.format("%s/%s", Utils.getAppInternalStorageDir(context), "lbrynet");
File dir = new File(lbrynetDir);
boolean dirExists = dir.isDirectory();
if (!dirExists) {
dirExists = dir.mkdirs();
}
if (!dirExists) {
return false;
}
String installIdPath = String.format("%s/install_id", lbrynetDir);
File file = new File(installIdPath);
String installId = null;
if (!file.exists()) {
// generate the install_id
installId = Lbry.generateId();
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(installId);
} catch (IOException ex) {
return false;
} finally {
Helper.closeCloseable(writer);
}
} else {
// read the installation id from the file
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(installIdPath)));
installId = reader.readLine();
} catch (IOException ex) {
return false;
} finally {
Helper.closeCloseable(reader);
}
}
if (!Helper.isNullOrEmpty(installId)) {
Lbry.INSTALLATION_ID = installId;
}
return !Helper.isNullOrEmpty(installId);
}
protected void onPostExecute(Boolean result) {
if (handler != null) {
handler.onInstallIdChecked(result);
}
}
public interface InstallIdHandler {
void onInstallIdChecked(boolean result);
}
}
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);
try {
Lbryio.authenticate(context);
} catch (AuthTokenInvalidatedException ex) {
// pass
}
return null;
}
}
@@ -6,6 +6,7 @@ import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
@@ -20,19 +21,22 @@ import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.lbrysdk.LbrynetService;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class LbrynetMessagingService extends FirebaseMessagingService {
public static final String ACTION_NOTIFICATION_RECEIVED = "io.lbry.browser.Broadcast.NotificationReceived";
private static final String TAG = "LbrynetMessagingService";
private static final String NOTIFICATION_CHANNEL_ID = "io.lbry.browser.LBRY_ENGAGEMENT_CHANNEL";
private static final String TYPE_COMMENT = "comment";
private static final String TYPE_SUBSCRIPTION = "subscription";
private static final String TYPE_REWARD = "reward";
private static final String TYPE_INTERESTS = "interests";
@@ -52,10 +56,7 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
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;
String hash = payload.get("hash"); // comment hash
if (type != null && getEnabledTypes().indexOf(type) > -1 && body != null && body.trim().length() > 0) {
// only log the receive event for valid notifications received
@@ -65,14 +66,41 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
firebaseAnalytics.logEvent(LbryAnalytics.EVENT_LBRY_NOTIFICATION_RECEIVE, bundle);
}
sendNotification(title, body, type, url, name, contentTitle, channelUrl, publishTime);
if (!Helper.isNullOrEmpty(hash)) {
url = String.format("%s?comment_hash=%s", url, hash);
}
sendNotification(title, body, type, url, name);
}
// persist the notification data
try {
DatabaseHelper helper = DatabaseHelper.getInstance();
SQLiteDatabase db = helper.getWritableDatabase();
LbryNotification lnotification = new LbryNotification();
lnotification.setTitle(title);
lnotification.setDescription(body);
lnotification.setTargetUrl(url);
lnotification.setTimestamp(new Date());
DatabaseHelper.createOrUpdateNotification(lnotification, db);
// send a broadcast
Intent intent = new Intent(ACTION_NOTIFICATION_RECEIVED);
intent.putExtra("title", title);
intent.putExtra("body", body);
intent.putExtra("url", url);
intent.putExtra("timestamp", lnotification.getTimestamp().getTime());
sendBroadcast(intent);
} catch (Exception ex) {
// don't fail if any error occurs while saving a notification
Log.e(TAG, "could not save notification", ex);
}
}
}
@Override
public void onNewToken(String token) {
Log.d(TAG, "Refreshed token: " + token);
//Log.d(TAG, "Refreshed token: " + token);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
@@ -97,8 +125,7 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String title, String messageBody, String type, String url, String name,
String contentTitle, String channelUrl, String publishTime) {
private void sendNotification(String title, String messageBody, String type, String url, String name) {
//Intent intent = new Intent(this, MainActivity.class);
//intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (url == null) {
@@ -143,6 +170,9 @@ public class LbrynetMessagingService extends FirebaseMessagingService {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
List<String> enabledTypes = new ArrayList<String>();
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_COMMENTS, true)) {
enabledTypes.add(TYPE_COMMENT);
}
if (sp.getBoolean(MainActivity.PREFERENCE_KEY_NOTIFICATION_SUBSCRIPTIONS, true)) {
enabledTypes.add(TYPE_SUBSCRIPTION);
}
File diff suppressed because it is too large. Load diff
@@ -1,25 +1,47 @@
package io.lbry.browser;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.widget.ViewPager2;
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClientStateListener;
import com.android.billingclient.api.BillingFlowParams;
import com.android.billingclient.api.BillingResult;
import com.android.billingclient.api.Purchase;
import com.android.billingclient.api.PurchasesUpdatedListener;
import com.android.billingclient.api.SkuDetails;
import com.android.billingclient.api.SkuDetailsParams;
import com.android.billingclient.api.SkuDetailsResponseListener;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import io.lbry.browser.adapter.VerificationPagerAdapter;
import io.lbry.browser.listener.SdkStatusListener;
import io.lbry.browser.listener.SignInListener;
import io.lbry.browser.listener.WalletSyncListener;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.model.lbryinc.User;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.tasks.lbryinc.FetchCurrentUserTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.Lbryio;
import io.lbry.lbrysdk.LbrynetService;
public class VerificationActivity extends FragmentActivity implements SignInListener, WalletSyncListener {
@@ -27,14 +49,66 @@ public class VerificationActivity extends FragmentActivity implements SignInList
public static final int VERIFICATION_FLOW_REWARDS = 2;
public static final int VERIFICATION_FLOW_WALLET = 3;
private List<SdkStatusListener> sdkStatusListeners;
private BillingClient billingClient;
private BroadcastReceiver sdkReceiver;
private String email;
private boolean signedIn;
private int flow;
private PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List<Purchase> purchases) {
int responseCode = billingResult.getResponseCode();
if (responseCode == BillingClient.BillingResponseCode.OK && purchases != null)
{
for (Purchase purchase : purchases) {
if (MainActivity.SKU_SKIP.equalsIgnoreCase(purchase.getSku())) {
showLoading();
MainActivity.handleBillingPurchase(
purchase,
billingClient,
VerificationActivity.this, null, new RewardVerifiedHandler() {
@Override
public void onSuccess(RewardVerified rewardVerified) {
if (Lbryio.currentUser != null) {
Lbryio.currentUser.setRewardApproved(rewardVerified.isRewardApproved());
}
if (!rewardVerified.isRewardApproved()) {
// show pending purchase message (possible slow card tx)
Snackbar.make(findViewById(R.id.verification_pager), R.string.purchase_request_pending, Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(findViewById(R.id.verification_pager), R.string.reward_verification_successful, Snackbar.LENGTH_LONG).show();
}
setResult(RESULT_OK);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 3000);
}
@Override
public void onError(Exception error) {
showFetchUserError(getString(R.string.purchase_request_failed_error));
hideLoading();
}
});
}
}
}
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sdkStatusListeners = new ArrayList<>();
signedIn = Lbryio.isSignedIn();
Intent intent = getIntent();
if (intent != null) {
@@ -54,6 +128,32 @@ public class VerificationActivity extends FragmentActivity implements SignInList
return;
}
IntentFilter filter = new IntentFilter();
filter.addAction(LbrynetService.ACTION_STOP_SERVICE);
filter.addAction(MainActivity.ACTION_SDK_READY);
sdkReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (MainActivity.ACTION_SDK_READY.equals(action)) {
for (SdkStatusListener listener : sdkStatusListeners) {
if (listener != null) {
listener.onSdkReady();
}
}
} else if (LbrynetService.ACTION_STOP_SERVICE.equals(action)) {
finish();
}
}
};
registerReceiver(sdkReceiver, filter);
billingClient = BillingClient.newBuilder(this)
.setListener(purchasesUpdatedListener)
.enablePendingPurchases()
.build();
establishBillingClientConnection();
setContentView(R.layout.activity_verification);
ViewPager2 viewPager = findViewById(R.id.verification_pager);
viewPager.setUserInputEnabled(false);
@@ -70,6 +170,24 @@ public class VerificationActivity extends FragmentActivity implements SignInList
});
}
private void establishBillingClientConnection() {
if (billingClient != null) {
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) {
// no need to do anything here. purchases are always checked server-side
}
}
@Override
public void onBillingServiceDisconnected() {
establishBillingClientConnection();
}
});
}
}
public void onResume() {
super.onResume();
LbryAnalytics.setCurrentScreen(this, "Verification", "Verification");
@@ -85,11 +203,13 @@ public class VerificationActivity extends FragmentActivity implements SignInList
flowHandled = true;
} else if (flow == VERIFICATION_FLOW_REWARDS) {
User user = Lbryio.currentUser;
if (!user.isIdentityVerified()) {
// disable phone verification for now
/*if (!user.isIdentityVerified()) {
// phone number verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false);
flowHandled = true;
} else if (!user.isRewardApproved()) {
} else */
if (!user.isRewardApproved()) {
// manual verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false);
flowHandled = true;
@@ -148,7 +268,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
// only sign in required, don't do anything else
showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() {
FetchCurrentUserTask task = new FetchCurrentUserTask(this, new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override
public void onSuccess(User user) {
Lbryio.currentUser = user;
@@ -158,7 +278,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
@Override
public void onError(Exception error) {
showFetchUserError(error.getMessage());
showFetchUserError(error != null ? error.getMessage() : getString(R.string.fetch_current_user_error));
hideLoading();
}
});
@@ -166,7 +286,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
} else {
// change pager view depending on flow
showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() {
FetchCurrentUserTask task = new FetchCurrentUserTask(this, new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override
public void onSuccess(User user) {
hideLoading();
@@ -176,10 +296,14 @@ public class VerificationActivity extends FragmentActivity implements SignInList
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()) {
// skipping phone verification
/*if (!user.isIdentityVerified()) {
// phone number verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_PHONE, false);
} else if (!user.isRewardApproved()) {
} else
*/
if (!user.isRewardApproved()) {
// manual verification required
viewPager.setCurrentItem(VerificationPagerAdapter.PAGE_VERIFICATION_MANUAL, false);
} else {
@@ -194,7 +318,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
}
@Override
public void onError(Exception error) {
showFetchUserError(error.getMessage());
showFetchUserError(error != null ? error.getMessage() : getString(R.string.fetch_current_user_error));
hideLoading();
}
});
@@ -210,7 +334,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
@Override
public void onPhoneVerified() {
showLoading();
FetchCurrentUserTask task = new FetchCurrentUserTask(new FetchCurrentUserTask.FetchUserTaskHandler() {
FetchCurrentUserTask task = new FetchCurrentUserTask(this, new FetchCurrentUserTask.FetchUserTaskHandler() {
@Override
public void onSuccess(User user) {
Lbryio.currentUser = user;
@@ -231,7 +355,7 @@ public class VerificationActivity extends FragmentActivity implements SignInList
@Override
public void onError(Exception error) {
showFetchUserError(error.getMessage());
showFetchUserError(error != null ? error.getMessage() : getString(R.string.fetch_current_user_error));
hideLoading();
}
});
@@ -269,4 +393,68 @@ public class VerificationActivity extends FragmentActivity implements SignInList
public void onWalletSyncFailed(Exception error) {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
}
@Override
public void onSkipQueueAction() {
if (billingClient != null) {
List<String> skuList = new ArrayList<>();
skuList.add(MainActivity.SKU_SKIP);
SkuDetailsParams detailsParams = SkuDetailsParams.newBuilder().
setType(BillingClient.SkuType.INAPP).
setSkusList(skuList).build();
billingClient.querySkuDetailsAsync(detailsParams, new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(@NonNull BillingResult billingResult, @Nullable List<SkuDetails> list) {
if (list != null && list.size() > 0) {
// we only queried one product, so it should be the first item in the list
SkuDetails skuDetails = list.get(0);
// launch the billing flow for skip queue
BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder().
setSkuDetails(skuDetails).build();
billingClient.launchBillingFlow(VerificationActivity.this, billingFlowParams);
}
}
});
}
}
@Override
public void onTwitterVerified() {
Snackbar.make(findViewById(R.id.verification_pager), R.string.reward_verification_successful, Snackbar.LENGTH_LONG).show();
setResult(RESULT_OK);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
finish();
}
}, 3000);
}
@Override
public void onManualProgress(boolean progress) {
if (progress) {
findViewById(R.id.verification_close_button).setVisibility(View.GONE);
} else {
findViewById(R.id.verification_close_button).setVisibility(View.VISIBLE);
}
}
@Override
public void onDestroy() {
Helper.unregisterReceiver(sdkReceiver, this);
super.onDestroy();
}
public void addSdkStatusListener(SdkStatusListener listener) {
if (!sdkStatusListeners.contains(listener)) {
sdkStatusListeners.add(listener);
}
}
public void removeSdkStatusListener(SdkStatusListener listener) {
sdkStatusListeners.remove(listener);
}
}
@@ -101,7 +101,7 @@ public class ChannelFilterListAdapter extends RecyclerView.Adapter<ChannelFilter
}
vh.alphaContainer.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE);
vh.thumbnailView.setVisibility(claim.isPlaceholder() || Helper.isNullOrEmpty(thumbnailUrl) ? View.GONE : View.VISIBLE);
vh.alphaView.setText(claim.isPlaceholder() ? null : claim.getName() != null ? claim.getName().substring(1, 2) : "");
vh.alphaView.setText(claim.isPlaceholder() ? null : claim.getName() != null ? claim.getName().substring(1, 2).toUpperCase() : "");
int bgColor = Helper.generateRandomColorForValue(claim.getClaimId());
Helper.setIconViewBackgroundColor(vh.alphaContainer, bgColor, claim.isPlaceholder(), context);
@@ -8,7 +8,6 @@ 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;
@@ -61,7 +60,13 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
public ClaimListAdapter(List<Claim> items, Context context) {
this.context = context;
this.items = new ArrayList<>(items);
this.items = new ArrayList<>();
for (Claim item : items) {
if (item != null) {
this.items.add(item);
}
}
this.selectedItems = new ArrayList<>();
quickClaimIdMap = new HashMap<>();
quickClaimUrlMap = new HashMap<>();
@@ -140,7 +145,7 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
public void addItems(List<Claim> claims) {
for (Claim claim : claims) {
if (!items.contains(claim)) {
if (claim != null && !items.contains(claim)) {
items.add(claim);
}
}
@@ -150,7 +155,12 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
notifyDataSetChanged();
}
public void setItems(List<Claim> claims) {
items = new ArrayList<>(claims);
items = new ArrayList<>();
for (Claim claim : claims) {
if (claim != null) {
items.add(claim);
}
}
notifyDataSetChanged();
}
@@ -183,6 +193,10 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
protected TextView fileSizeView;
protected ProgressBar downloadProgressView;
protected TextView deviceView;
protected View loadingImagePlaceholder;
protected View loadingTextPlaceholder1;
protected View loadingTextPlaceholder2;
public ViewHolder(View v) {
super(v);
feeContainer = v.findViewById(R.id.claim_fee_container);
@@ -202,6 +216,10 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
fileSizeView = v.findViewById(R.id.claim_file_size);
downloadProgressView = v.findViewById(R.id.claim_download_progress);
deviceView = v.findViewById(R.id.claim_view_device);
loadingImagePlaceholder = v.findViewById(R.id.claim_thumbnail_placeholder);
loadingTextPlaceholder1 = v.findViewById(R.id.claim_text_loading_placeholder_1);
loadingTextPlaceholder2 = v.findViewById(R.id.claim_text_loading_placeholder_2);
}
}
@@ -298,22 +316,19 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
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);
int paddingTopScaled = Helper.getScaledValue(paddingTop, scale);
int paddingBottomScaled = Helper.getScaledValue(paddingBottom, scale);
vh.itemView.setPadding(vh.itemView.getPaddingStart(), paddingTopScaled, vh.itemView.getPaddingEnd(), paddingBottomScaled);
Claim original = items.get(position);
boolean isRepost = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType());
final Claim item = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType()) ? original.getRepostedClaim() : original;
final Claim item = Claim.TYPE_REPOST.equalsIgnoreCase(original.getValueType()) ?
(original.getRepostedClaim() != null ? original.getRepostedClaim() : original): original;
Claim.GenericMetadata metadata = item.getValue();
Claim signingChannel = item.getSigningChannel();
Claim.StreamMetadata streamMetadata = null;
@@ -328,14 +343,17 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
}
boolean isPending = item.getConfirmations() == 0;
boolean isSelected = isClaimSelected(item);
boolean isSelected = isClaimSelected(original);
vh.itemView.setSelected(isSelected);
vh.selectedOverlayView.setVisibility(isSelected ? View.VISIBLE : View.GONE);
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (isPending) {
Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG).show();
Snackbar snackbar = Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG);
TextView snackbarText = snackbar.getView().findViewById(com.google.android.material.R.id.snackbar_text);
snackbarText.setMaxLines(5);
snackbar.show();
return;
}
@@ -356,7 +374,10 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
}
if (isPending) {
Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG).show();
Snackbar snackbar = Snackbar.make(vh.itemView, R.string.item_pending_blockchain, Snackbar.LENGTH_LONG);
TextView snackbarText = snackbar.getView().findViewById(com.google.android.material.R.id.snackbar_text);
snackbarText.setMaxLines(5);
snackbar.show();
return false;
}
@@ -381,9 +402,9 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
});
vh.publishTimeView.setVisibility(!isPending ? View.VISIBLE : View.GONE);
vh.pendingTextView.setVisibility(isPending ? View.VISIBLE : View.GONE);
vh.repostInfoView.setVisibility(isRepost ? View.VISIBLE : View.GONE);
vh.repostChannelView.setText(isRepost ? original.getSigningChannel().getName() : null);
vh.pendingTextView.setVisibility(isPending && !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
vh.repostInfoView.setVisibility(isRepost && type != VIEW_TYPE_FEATURED ? View.VISIBLE : View.GONE);
vh.repostChannelView.setText(isRepost && original.getSigningChannel() != null ? original.getSigningChannel().getName() : null);
vh.repostChannelView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
@@ -404,6 +425,13 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
vh.noThumbnailView.setVisibility(Helper.isNullOrEmpty(thumbnailUrl) ? View.VISIBLE : View.GONE);
Helper.setIconViewBackgroundColor(vh.noThumbnailView, bgColor, false, context);
Helper.setViewVisibility(vh.loadingImagePlaceholder, item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.loadingTextPlaceholder1, item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.loadingTextPlaceholder2, item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.titleView, !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.publisherView, !item.isLoadingPlaceholder() ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(vh.publishTimeView, !item.isLoadingPlaceholder() && !isPending ? View.VISIBLE : View.GONE);
if (type == VIEW_TYPE_FEATURED && item.isUnresolved()) {
vh.durationView.setVisibility(View.GONE);
vh.titleView.setText("Nothing here. Publish something!");
@@ -413,6 +441,7 @@ public class ClaimListAdapter extends RecyclerView.Adapter<ClaimListAdapter.View
long duration = item.getDuration();
if (!Helper.isNullOrEmpty(thumbnailUrl)) {
Glide.with(context.getApplicationContext()).
asBitmap().
load(thumbnailUrl).
centerCrop().
placeholder(R.drawable.bg_thumbnail_placeholder).
@@ -0,0 +1,228 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import io.lbry.browser.R;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.ClaimCacheKey;
import io.lbry.browser.model.Comment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
public class CommentListAdapter extends RecyclerView.Adapter<CommentListAdapter.ViewHolder> {
private List<Comment> items;
private Context context;
private boolean nested;
private float scale;
@Setter
private ClaimListAdapter.ClaimListItemListener listener;
@Setter
private ReplyClickListener replyListener;
public CommentListAdapter(List<Comment> items, Context context) {
this(items, context, false);
}
public CommentListAdapter(List<Comment> items, Context context, boolean nested) {
this.items = new ArrayList<>(items);
this.context = context;
this.nested = nested;
if (context != null) {
scale = context.getResources().getDisplayMetrics().density;
}
for (Comment item : this.items) {
ClaimCacheKey key = new ClaimCacheKey();
key.setClaimId(item.getChannelId());
if (Lbry.claimCache.containsKey(key)) {
item.setPoster(Lbry.claimCache.get(key));
}
}
}
public void clearItems() {
items.clear();
notifyDataSetChanged();
}
public int getPositionForComment(String commentHash) {
for (int i = 0; i < items.size(); i++) {
if (commentHash.equalsIgnoreCase(items.get(i).getId())) {
return i;
}
}
return -1;
}
@Override
public int getItemCount() {
return items != null ? items.size() : 0;
}
public List<String> getClaimUrlsToResolve() {
List<String> urls = new ArrayList<>();
for (int i = 0; i < items.size(); i++) {
Comment item = items.get(i);
if (item.getPoster() == null) {
LbryUri url = LbryUri.tryParse(String.format("%s#%s", item.getChannelName(), item.getChannelId()));
if (url != null && !urls.contains(url.toString())) {
urls.add(url.toString());
}
}
if (item.getReplies().size() > 0) {
for (int j = 0; j < item.getReplies().size(); j++) {
Comment reply = item.getReplies().get(j);
if (reply.getPoster() == null) {
LbryUri url = LbryUri.tryParse(String.format("%s#%s", reply.getChannelName(), reply.getChannelId()));
if (url != null && !urls.contains(url.toString())) {
urls.add(url.toString());
}
}
}
}
}
return urls;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected TextView channelName;
protected TextView commentText;
protected ImageView thumbnailView;
protected View noThumbnailView;
protected TextView alphaView;
protected TextView commentTimeView;
protected View replyLink;
protected RecyclerView repliesList;
public ViewHolder (View v) {
super(v);
channelName = v.findViewById(R.id.comment_channel_name);
commentTimeView = v.findViewById(R.id.comment_time);
commentText = v.findViewById(R.id.comment_text);
replyLink = v.findViewById(R.id.comment_reply_link);
thumbnailView = v.findViewById(R.id.comment_thumbnail);
noThumbnailView = v.findViewById(R.id.comment_no_thumbnail);
alphaView = v.findViewById(R.id.comment_thumbnail_alpha);
repliesList = v.findViewById(R.id.comment_replies);
}
}
public void insert(int index, Comment comment) {
if (!items.contains(comment)) {
items.add(index, comment);
notifyDataSetChanged();
}
}
public void addReply(Comment comment) {
for (int i = 0; i < items.size(); i++) {
Comment parent = items.get(i);
if (parent.getId().equalsIgnoreCase(comment.getParentId())) {
parent.addReply(comment);
notifyDataSetChanged();
break;
}
}
}
public void updatePosterForComment(String channelId, Claim channel) {
for (int i = 0 ; i < items.size(); i++) {
Comment item = items.get(i);
List<Comment> replies = item.getReplies();
if (replies != null && replies.size() > 0) {
for (int j = 0; j < replies.size(); j++) {
Comment reply = item.getReplies().get(j);
if (channelId.equalsIgnoreCase(reply.getChannelId())) {
reply.setPoster(channel);
break;
}
}
}
if (channelId.equalsIgnoreCase(item.getChannelId())) {
item.setPoster(channel);
break;
}
}
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_comment, parent, false);
return new CommentListAdapter.ViewHolder(v);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
Comment comment = items.get(position);
holder.itemView.setPadding(
nested ? Helper.getScaledValue(56, scale) : holder.itemView.getPaddingStart(),
holder.itemView.getPaddingTop(),
nested ? 0 : holder.itemView.getPaddingEnd(),
holder.itemView.getPaddingBottom());
holder.channelName.setText(comment.getChannelName());
holder.commentTimeView.setText(DateUtils.getRelativeTimeSpanString(
(comment.getTimestamp() * 1000), System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
holder.commentText.setText(comment.getText());
holder.replyLink.setVisibility(!nested ? View.VISIBLE : View.GONE);
boolean hasThumbnail = comment.getPoster() != null && !Helper.isNullOrEmpty(comment.getPoster().getThumbnailUrl());
holder.thumbnailView.setVisibility(hasThumbnail ? View.VISIBLE : View.INVISIBLE);
holder.noThumbnailView.setVisibility(!hasThumbnail ? View.VISIBLE : View.INVISIBLE);
int bgColor = Helper.generateRandomColorForValue(comment.getChannelId());
Helper.setIconViewBackgroundColor(holder.noThumbnailView, bgColor, false, context);
if (hasThumbnail) {
Glide.with(context.getApplicationContext()).asBitmap().load(comment.getPoster().getThumbnailUrl()).
apply(RequestOptions.circleCropTransform()).into(holder.thumbnailView);
}
holder.alphaView.setText(comment.getChannelName() != null ? comment.getChannelName().substring(1, 2).toUpperCase() : null);
List<Comment> replies = comment.getReplies();
boolean hasReplies = replies != null && replies.size() > 0;
if (hasReplies) {
holder.repliesList.setLayoutManager(new LinearLayoutManager(context));
holder.repliesList.setAdapter(new CommentListAdapter(replies, context, true));
} else {
holder.repliesList.setAdapter(null);
}
holder.channelName.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null && comment.getPoster() != null) {
listener.onClaimClicked(comment.getPoster());
}
}
});
holder.replyLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (replyListener != null) {
replyListener.onReplyClicked(comment);
}
}
});
}
public interface ReplyClickListener {
void onReplyClicked(Comment comment);
}
}
@@ -95,6 +95,7 @@ public class EditorsChoiceItemAdapter extends RecyclerView.Adapter<EditorsChoice
vh.descriptionView.setText(item.getDescription());
if (!Helper.isNullOrEmpty(item.getThumbnailUrl())) {
Glide.with(context.getApplicationContext()).
asBitmap().
load(item.getThumbnailUrl()).
centerCrop().
placeholder(R.drawable.bg_thumbnail_placeholder).
@@ -10,6 +10,7 @@ import android.widget.SpinnerAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import io.lbry.browser.R;
@@ -40,11 +41,30 @@ public class InlineChannelSpinnerAdapter extends ArrayAdapter<Claim> {
channels.add(1, anonymous);
}
}
public void addAnonymousPlaceholder() {
Claim anonymous = new Claim();
anonymous.setPlaceholderAnonymous(true);
insert(anonymous, 0);
channels.add(0, anonymous);
}
public void addAll(Collection<? extends Claim> collection) {
for (Claim claim : collection) {
if (!channels.contains(claim)) {
channels.add(claim);
}
}
super.addAll(collection);
}
public void clear() {
channels.clear();
super.clear();
}
public int getItemPosition(Claim item) {
for (int i = 0; i < channels.size(); i++) {
Claim channel = channels.get(i);
if (item.getClaimId().equalsIgnoreCase(channel.getClaimId())) {
if (item.getClaimId() != null && item.getClaimId().equalsIgnoreCase(channel.getClaimId())) {
return i;
}
}
@@ -0,0 +1,268 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.graphics.Color;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.snackbar.Snackbar;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;
import io.lbry.browser.R;
import io.lbry.browser.listener.SelectionModeListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.ui.controls.SolidIconView;
import io.lbry.browser.utils.Helper;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Data
@EqualsAndHashCode(callSuper = false)
public class NotificationListAdapter extends RecyclerView.Adapter<NotificationListAdapter.ViewHolder> {
private static final String RULE_CREATOR_SUBSCRIBER = "creator_subscriber";
private static final String RULE_COMMENT = "comment";
private Context context;
private List<LbryNotification> items;
private List<LbryNotification> selectedItems;
@Setter
private NotificationClickListener clickListener;
@Getter
@Setter
private boolean inSelectionMode;
@Setter
private SelectionModeListener selectionModeListener;
public NotificationListAdapter(List<LbryNotification> notifications, Context context) {
this.context = context;
this.items = new ArrayList<>(notifications);
this.selectedItems = new ArrayList<>();
Collections.sort(items, Collections.reverseOrder(new LbryNotification()));
}
public static class ViewHolder extends RecyclerView.ViewHolder {
protected View layoutView;
protected TextView titleView;
protected TextView bodyView;
protected TextView timeView;
protected SolidIconView iconView;
protected ImageView thumbnailView;
protected View selectedOverlayView;
public ViewHolder(View v) {
super(v);
layoutView = v.findViewById(R.id.notification_layout);
titleView = v.findViewById(R.id.notification_title);
bodyView = v.findViewById(R.id.notification_body);
timeView = v.findViewById(R.id.notification_time);
iconView = v.findViewById(R.id.notification_icon);
thumbnailView = v.findViewById(R.id.notification_author_thumbnail);
selectedOverlayView = v.findViewById(R.id.notification_selected_overlay);
}
}
public int getItemCount() {
return items != null ? items.size() : 0;
}
public List<LbryNotification> getSelectedItems() {
return this.selectedItems;
}
public int getSelectedCount() {
return selectedItems != null ? selectedItems.size() : 0;
}
public void clearSelectedItems() {
this.selectedItems.clear();
}
public boolean isNotificationSelected(LbryNotification notification) {
return selectedItems.contains(notification);
}
public void insertNotification(LbryNotification notification, int index) {
if (!items.contains(notification)) {
items.add(index, notification);
}
notifyDataSetChanged();
}
public void addNotification(LbryNotification notification) {
if (!items.contains(notification)) {
items.add(notification);
}
notifyDataSetChanged();
}
public void removeNotifications(List<LbryNotification> notifications) {
for (LbryNotification notification : notifications) {
items.remove(notification);
}
notifyDataSetChanged();
}
public List<String> getAuthorUrls() {
List<String> urls = new ArrayList<>();
for (LbryNotification item : items) {
if (!Helper.isNullOrEmpty(item.getAuthorUrl())) {
urls.add(item.getAuthorUrl());
}
}
return urls;
}
public void updateAuthorClaims(List<Claim> claims) {
for (Claim claim : claims) {
if (claim != null && claim.getThumbnailUrl() != null) {
updateClaimForAuthorUrl(claim);
}
}
notifyDataSetChanged();
}
private void updateClaimForAuthorUrl(Claim claim) {
for (LbryNotification item : items) {
if (claim.getPermanentUrl().equalsIgnoreCase(item.getAuthorUrl())) {
item.setCommentAuthor(claim);
}
}
}
public void addNotifications(List<LbryNotification> notifications) {
for (LbryNotification notification : notifications) {
if (!items.contains(notification)) {
items.add(notification);
}
}
Collections.sort(items, Collections.reverseOrder(new LbryNotification()));
notifyDataSetChanged();
}
@Override
public NotificationListAdapter.ViewHolder onCreateViewHolder(ViewGroup root, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.list_item_notification, root, false);
return new NotificationListAdapter.ViewHolder(v);
}
private int getStringIdForRule(String rule) {
if (RULE_CREATOR_SUBSCRIBER.equalsIgnoreCase(rule)) {
return R.string.fa_heart;
}
if (RULE_COMMENT.equalsIgnoreCase(rule)) {
return R.string.fa_comment_alt;
}
return R.string.fa_asterisk;
}
private int getColorForRule(String rule) {
if (RULE_CREATOR_SUBSCRIBER.equalsIgnoreCase(rule)) {
return Color.RED;
}
if (RULE_COMMENT.equalsIgnoreCase(rule)) {
return ContextCompat.getColor(context, R.color.nextLbryGreen);
}
return ContextCompat.getColor(context, R.color.lbryGreen);
}
@Override
public void onBindViewHolder(NotificationListAdapter.ViewHolder vh, int position) {
LbryNotification notification = items.get(position);
vh.layoutView.setBackgroundColor(ContextCompat.getColor(context, notification.isSeen() ? android.R.color.transparent : R.color.nextLbryGreenSemiTransparent));
vh.selectedOverlayView.setVisibility(isNotificationSelected(notification) ? View.VISIBLE : View.GONE);
vh.titleView.setVisibility(!Helper.isNullOrEmpty(notification.getTitle()) ? View.VISIBLE : View.GONE);
vh.titleView.setText(notification.getTitle());
vh.bodyView.setText(notification.getDescription());
vh.timeView.setText(DateUtils.getRelativeTimeSpanString(
getLocalNotificationTime(notification), System.currentTimeMillis(), 0, DateUtils.FORMAT_ABBREV_RELATIVE));
vh.thumbnailView.setVisibility(notification.getCommentAuthor() == null ? View.INVISIBLE : View.VISIBLE);
if (notification.getCommentAuthor() != null) {
Glide.with(context.getApplicationContext()).load(
notification.getCommentAuthor().getThumbnailUrl()).apply(RequestOptions.circleCropTransform()).into(vh.thumbnailView);
}
vh.iconView.setVisibility(notification.getCommentAuthor() != null ? View.INVISIBLE : View.VISIBLE);
vh.iconView.setText(getStringIdForRule(notification.getRule()));
vh.iconView.setTextColor(getColorForRule(notification.getRule()));
vh.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (inSelectionMode) {
toggleSelectedNotification(notification);
} else {
if (clickListener != null) {
clickListener.onNotificationClicked(notification);
}
}
}
});
vh.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
if (!inSelectionMode) {
inSelectionMode = true;
if (selectionModeListener != null) {
selectionModeListener.onEnterSelectionMode();
}
}
toggleSelectedNotification(notification);
return true;
}
});
}
private void toggleSelectedNotification(LbryNotification notification) {
if (selectedItems.contains(notification)) {
selectedItems.remove(notification);
} else {
selectedItems.add(notification);
}
if (selectionModeListener != null) {
selectionModeListener.onItemSelectionToggled();
}
if (selectedItems.size() == 0) {
inSelectionMode = false;
if (selectionModeListener != null) {
selectionModeListener.onExitSelectionMode();
}
}
notifyDataSetChanged();
}
private long getLocalNotificationTime(LbryNotification notification) {
TimeZone utcTZ = TimeZone.getTimeZone("UTC");
TimeZone targetTZ = TimeZone.getDefault();
Calendar cal = new GregorianCalendar(utcTZ);
cal.setTimeInMillis(notification.getTimestamp().getTime());
cal.add(Calendar.MILLISECOND, utcTZ.getRawOffset() * -1);
cal.add(Calendar.MILLISECOND, targetTZ.getRawOffset());
return cal.getTimeInMillis();
}
public interface NotificationClickListener {
void onNotificationClicked(LbryNotification notification);
}
}
@@ -168,6 +168,10 @@ public class RewardListAdapter extends RecyclerView.Adapter<RewardListAdapter.Vi
return;
}
if (vh.inputCustomCode != null && !vh.inputCustomCode.hasFocus()) {
vh.inputCustomCode.requestFocus();
}
if (clickListener != null) {
clickListener.onRewardClicked(reward, vh.loading);
}
@@ -0,0 +1,68 @@
package io.lbry.browser.adapter;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.model.StartupStage;
public class StartupStageAdapter extends BaseAdapter {
private final List<StartupStage> list;
private final LayoutInflater inflater;
private final String[] stagesString;
public StartupStageAdapter(Context ctx, List<StartupStage> rows) {
this.list = rows;
this.inflater = LayoutInflater.from(ctx);
stagesString = new String[7];
stagesString[0] = ctx.getResources().getString(R.string.installation_id_loaded);
stagesString[1] = ctx.getResources().getString(R.string.known_tags_loaded);
stagesString[2] = ctx.getResources().getString(R.string.exchange_rate_loaded);
stagesString[3] = ctx.getResources().getString(R.string.user_authenticated);
stagesString[4] = ctx.getResources().getString(R.string.installation_registered);
stagesString[5] = ctx.getResources().getString(R.string.subscriptions_loaded);
stagesString[6] = ctx.getResources().getString(R.string.subscriptions_resolved);
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = inflater.inflate(R.layout.list_item_startupstage, viewGroup, false);
ImageView iconView = view.findViewById(R.id.startup_stage_icon);
TextView textView = view.findViewById(R.id.startup_stage_text);
StartupStage item = (StartupStage) getItem(i);
iconView.setImageResource(item.stageDone ? R.drawable.ic_check : R.drawable.ic_close);
iconView.setColorFilter(item.stageDone ? Color.WHITE : Color.RED);
textView.setText(stagesString[item.stage - 1]);
}
return view;
}
}
@@ -72,7 +72,9 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionList
vh.claimView.setText(item.getClaim());
vh.feeView.setText(context.getString(R.string.tx_list_fee, TX_LIST_AMOUNT_FORMAT.format(item.getFee().doubleValue())));
vh.txidLinkView.setText(item.getTxid().substring(0, 7));
vh.dateView.setText(TX_LIST_DATE_FORMAT.format(item.getTxDate()));
vh.dateView.setVisibility(item.getConfirmations() > 0 ? View.VISIBLE : View.GONE);
vh.dateView.setText(item.getConfirmations() > 0 ? TX_LIST_DATE_FORMAT.format(item.getTxDate()) : null);
vh.pendingView.setVisibility(item.getConfirmations() == 0 ? View.VISIBLE : View.GONE);
vh.infoFeeContainer.setVisibility(!Helper.isNullOrEmpty(item.getClaim()) || Math.abs(item.getFee().doubleValue()) > 0 ?
View.VISIBLE : View.GONE);
@@ -111,6 +113,7 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionList
protected TextView feeView;
protected TextView txidLinkView;
protected TextView dateView;
protected TextView pendingView;
protected View infoFeeContainer;
public ViewHolder(View v) {
@@ -121,6 +124,7 @@ public class TransactionListAdapter extends RecyclerView.Adapter<TransactionList
feeView = v.findViewById(R.id.transaction_fee);
txidLinkView = v.findViewById(R.id.transaction_id_link);
dateView = v.findViewById(R.id.transaction_date);
pendingView = v.findViewById(R.id.transaction_pending_text);
infoFeeContainer = v.findViewById(R.id.transaction_info_fee_container);
}
}
@@ -4,31 +4,31 @@ 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.sql.SQLInput;
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.LbryNotification;
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 = 2;
public static final int DATABASE_VERSION = 8;
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)",
"CREATE TABLE subscriptions (url TEXT PRIMARY KEY NOT NULL, channel_name TEXT NOT NULL, is_notifications_disabled INTEGER DEFAULT 0 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)
@@ -48,7 +48,20 @@ public class DatabaseHelper extends SQLiteOpenHelper {
", thumbnail_url TEXT" +
", release_time INTEGER " +
", device TEXT" +
", timestamp TEXT NOT NULL)"
", timestamp TEXT NOT NULL)",
"CREATE TABLE notifications (" +
" id INTEGER PRIMARY KEY NOT NULL" +
", remote_id INTEGER NOT NULL" +
", author_url TEXT" +
", title TEXT" +
", description TEXT" +
", thumbnail_url TEXT" +
", target_url TEXT" +
", rule TEXT" +
", is_read INTEGER DEFAULT 0 NOT NULL" +
", is_seen INTEGER DEFAULT 0 NOT NULL " +
", timestamp TEXT NOT NULL)",
"CREATE TABLE shuffle_watched (id INTEGER PRIMARY KEY NOT NULL, claim_id TEXT NOT NULL)"
};
private static final String[] SQL_CREATE_INDEXES = {
"CREATE UNIQUE INDEX idx_subscription_url ON subscriptions (url)",
@@ -56,22 +69,69 @@ public class DatabaseHelper extends SQLiteOpenHelper {
"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)"
"CREATE INDEX idx_view_history_device ON view_history (device)",
"CREATE UNIQUE INDEX idx_notification_remote_id ON notifications (remote_id)",
"CREATE INDEX idx_notification_timestamp ON notifications (timestamp)",
"CREATE UNIQUE INDEX idx_shuffle_watched_claim ON shuffle_watched (claim_id)",
};
private static final String[] SQL_V1_V2_UPGRADE = {
"ALTER TABLE view_history ADD COLUMN currency TEXT"
};
private static final String SQL_INSERT_SUBSCRIPTION = "REPLACE INTO subscriptions (channel_name, url) VALUES (?, ?)";
private static final String[] SQL_V2_V3_UPGRADE = {
"CREATE TABLE notifications (" +
" id INTEGER PRIMARY KEY NOT NULL" +
", title TEXT" +
", description TEXT" +
", thumbnail_url TEXT" +
", target_url TEXT" +
", is_read INTEGER DEFAULT 0 NOT NULL" +
", timestamp TEXT NOT NULL)",
"CREATE INDEX idx_notification_timestamp ON notifications (timestamp)"
};
private static final String[] SQL_V3_V4_UPGRADE = {
"ALTER TABLE notifications ADD COLUMN remote_id INTEGER",
"CREATE UNIQUE INDEX idx_notification_remote_id ON notifications (remote_id)"
};
private static final String[] SQL_V4_V5_UPGRADE = {
"ALTER TABLE notifications ADD COLUMN rule TEXT",
"ALTER TABLE notifications ADD COLUMN is_seen TEXT"
};
private static final String[] SQL_V5_V6_UPGRADE = {
"ALTER TABLE notifications ADD COLUMN author_url TEXT"
};
private static final String[] SQL_V6_V7_UPGRADE = {
"CREATE TABLE shuffle_watched (id INTEGER PRIMARY KEY NOT NULL, claim_id TEXT NOT NULL)",
"CREATE UNIQUE INDEX idx_shuffle_watched_claim ON shuffle_watched (claim_id)"
};
private static final String[] SQL_V7_V8_UPGRADE = {
"AlTER TABLE subscriptions ADD COLUMN is_notifications_disabled INTEGER DEFAULT 0 NOT NULL"
};
private static final String SQL_INSERT_SUBSCRIPTION = "REPLACE INTO subscriptions (channel_name, url, is_notifications_disabled) VALUES (?, ?, ?)";
private static final String SQL_UPDATE_SUBSCRIPTION_NOTIFICATION = "UPDATE subscriptions SET is_notification_disabled = ? WHERE url = ?";
private static final String SQL_CLEAR_SUBSCRIPTIONS = "DELETE FROM subscriptions";
private static final String SQL_DELETE_SUBSCRIPTION = "DELETE FROM subscriptions WHERE url = ?";
private static final String SQL_GET_SUBSCRIPTIONS = "SELECT channel_name, url FROM subscriptions";
private static final String SQL_GET_SUBSCRIPTIONS = "SELECT channel_name, url, is_notifications_disabled 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_NOTIFICATION = "REPLACE INTO notifications (remote_id, author_url, title, description, rule, target_url, is_read, is_seen, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_GET_NOTIFICATIONS = "SELECT id, remote_id, author_url, title, description, rule, target_url, is_read, is_seen, timestamp FROM notifications ORDER BY timestamp DESC LIMIT 500";
private static final String SQL_GET_UNREAD_NOTIFICATIONS_COUNT = "SELECT COUNT(id) FROM notifications WHERE is_read <> 1";
private static final String SQL_GET_UNSEEN_NOTIFICATIONS_COUNT = "SELECT COUNT(id) FROM notifications WHERE is_seen <> 1";
private static final String SQL_MARK_NOTIFICATIONS_READ = "UPDATE notifications SET is_read = 1 WHERE is_read = 0";
private static final String SQL_MARK_NOTIFICATIONS_SEEN = "UPDATE notifications SET is_seen = 1 WHERE is_seen = 0";
private static final String SQL_MARK_NOTIFICATION_READ_AND_SEEN = "UPDATE notifications SET is_read = 1, is_seen = 1 WHERE id = ?";
private static final String SQL_INSERT_SHUFFLE_WATCHED = "REPLACE INTO shuffle_watched (claim_id) VALUES (?)";
private static final String SQL_GET_SHUFFLE_WATCHED_CLAIMS = "SELECT claim_id FROM shuffle_watched";
private static final String SQL_INSERT_VIEW_HISTORY =
"REPLACE INTO view_history (url, claim_id, claim_name, cost, currency, title, publisher_claim_id, publisher_name, publisher_title, thumbnail_url, device, release_time, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
private static final String SQL_GET_VIEW_HISTORY =
@@ -110,6 +170,36 @@ public class DatabaseHelper extends SQLiteOpenHelper {
db.execSQL(sql);
}
}
if (oldVersion < 3) {
for (String sql : SQL_V2_V3_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 4) {
for (String sql : SQL_V3_V4_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 5) {
for (String sql : SQL_V4_V5_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 6) {
for (String sql : SQL_V5_V6_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 7) {
for (String sql : SQL_V6_V7_UPGRADE) {
db.execSQL(sql);
}
}
if (oldVersion < 8) {
for (String sql : SQL_V7_V8_UPGRADE) {
db.execSQL(sql);
}
}
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
@@ -126,6 +216,7 @@ public class DatabaseHelper extends SQLiteOpenHelper {
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<>();
@@ -225,11 +316,21 @@ public class DatabaseHelper extends SQLiteOpenHelper {
}
public static void createOrUpdateSubscription(Subscription subscription, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_SUBSCRIPTION, new Object[] { subscription.getChannelName(), subscription.getUrl() });
db.execSQL(SQL_INSERT_SUBSCRIPTION, new Object[] {
subscription.getChannelName(),
subscription.getUrl(),
subscription.isNotificationsDisabled() ? 1 : 0
});
}
public static void setSubscriptionNotificationDisabled(boolean flag, String url, SQLiteDatabase db) {
db.execSQL(SQL_UPDATE_SUBSCRIPTION_NOTIFICATION, new Object[] { flag ? 1 : 0, url });
}
public static void deleteSubscription(Subscription subscription, SQLiteDatabase db) {
db.execSQL(SQL_DELETE_SUBSCRIPTION, new Object[] { subscription.getUrl() });
}
public static void clearSubscriptions(SQLiteDatabase db) {
db.execSQL(SQL_CLEAR_SUBSCRIPTIONS);
}
public static List<Subscription> getSubscriptions(SQLiteDatabase db) {
List<Subscription> subscriptions = new ArrayList<>();
Cursor cursor = null;
@@ -239,6 +340,7 @@ public class DatabaseHelper extends SQLiteOpenHelper {
Subscription subscription = new Subscription();
subscription.setChannelName(cursor.getString(0));
subscription.setUrl(cursor.getString(1));
subscription.setNotificationsDisabled(cursor.getInt(2) == 1);
subscriptions.add(subscription);
}
} finally {
@@ -247,4 +349,112 @@ public class DatabaseHelper extends SQLiteOpenHelper {
return subscriptions;
}
public static void createOrUpdateNotification(LbryNotification notification, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_NOTIFICATION, new Object[] {
notification.getRemoteId(),
notification.getAuthorUrl(),
notification.getTitle(),
notification.getDescription(),
notification.getRule(),
notification.getTargetUrl(),
notification.isRead() ? 1 : 0,
notification.isSeen() ? 1 : 0,
new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).format(notification.getTimestamp() != null ? notification.getTimestamp() : new Date())
});
}
public static List<LbryNotification> getNotifications(SQLiteDatabase db) {
List<LbryNotification> notifications = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_NOTIFICATIONS, null);
while (cursor.moveToNext()) {
LbryNotification notification = new LbryNotification();
int columnIndex = 0;
notification.setId(cursor.getLong(columnIndex++));
notification.setRemoteId(cursor.getLong(columnIndex++));
notification.setAuthorUrl(cursor.getString(columnIndex++));
notification.setTitle(cursor.getString(columnIndex++));
notification.setDescription(cursor.getString(columnIndex++));
notification.setRule(cursor.getString(columnIndex++));
notification.setTargetUrl(cursor.getString(columnIndex++));
notification.setRead(cursor.getInt(columnIndex++) == 1);
notification.setSeen(cursor.getInt(columnIndex++) == 1);
try {
notification.setTimestamp(new SimpleDateFormat(Helper.ISO_DATE_FORMAT_PATTERN).parse(cursor.getString(columnIndex++)));
} catch (ParseException ex) {
// invalid timestamp (which shouldn't happen). Skip this item
continue;
}
notifications.add(notification);
}
} finally {
Helper.closeCursor(cursor);
}
return notifications;
}
public static void deleteNotifications(List<LbryNotification> notifications, SQLiteDatabase db) {
StringBuilder sb = new StringBuilder("DELETE FROM notifications WHERE remote_id IN (");
List<Object> remoteIds = new ArrayList<>();
String delim = "";
for (int i = 0; i < notifications.size(); i++) {
remoteIds.add(String.valueOf(notifications.get(i).getRemoteId()));
sb.append(delim).append("?");
delim = ",";
}
sb.append(")");
String sql = sb.toString();
db.execSQL(sql, remoteIds.toArray());
}
public static int getUnreadNotificationsCount(SQLiteDatabase db) {
int count = 0;
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_UNREAD_NOTIFICATIONS_COUNT, null);
if (cursor.moveToNext()) {
count = cursor.getInt(0);
}
} finally {
Helper.closeCursor(cursor);
}
return count;
}
public static int getUnseenNotificationsCount(SQLiteDatabase db) {
int count = 0;
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_UNSEEN_NOTIFICATIONS_COUNT, null);
if (cursor.moveToNext()) {
count = cursor.getInt(0);
}
} finally {
Helper.closeCursor(cursor);
}
return count;
}
public static void markNotificationsSeen(SQLiteDatabase db) {
db.execSQL(SQL_MARK_NOTIFICATIONS_SEEN);
}
public static void markNotificationsRead(SQLiteDatabase db) {
db.execSQL(SQL_MARK_NOTIFICATIONS_READ);
}
public static void markNotificationReadAndSeen(long notificationId, SQLiteDatabase db) {
db.execSQL(SQL_MARK_NOTIFICATION_READ_AND_SEEN, new Object[] { notificationId });
}
public static void createOrUpdateShuffleWatched(String claimId, SQLiteDatabase db) {
db.execSQL(SQL_INSERT_SHUFFLE_WATCHED, new Object[] { claimId });
}
public static List<String> getShuffleWatchedClaims(SQLiteDatabase db) {
List<String> claimIds = new ArrayList<>();
Cursor cursor = null;
try {
cursor = db.rawQuery(SQL_GET_SHUFFLE_WATCHED_CLAIMS, null);
while (cursor.moveToNext()) {
claimIds.add(cursor.getString(0));
}
} finally {
Helper.closeCursor(cursor);
}
return claimIds;
}
}
@@ -0,0 +1,347 @@
package io.lbry.browser.dialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.text.HtmlCompat;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.tasks.wallet.SupportCreateTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import lombok.Setter;
public class CreateSupportDialogFragment extends BottomSheetDialogFragment implements WalletBalanceListener {
public static final String TAG = "CreateSupportDialog";
private MaterialButton sendButton;
private View cancelLink;
private TextInputEditText inputAmount;
private View inlineBalanceContainer;
private TextView inlineBalanceValue;
private ProgressBar sendProgress;
private InlineChannelSpinnerAdapter channelSpinnerAdapter;
private AppCompatSpinner channelSpinner;
private SwitchMaterial switchTip;
private boolean fetchingChannels;
private ProgressBar progressLoadingChannels;
@Setter
private CreateSupportListener listener;
@Setter
private Claim claim;
public static CreateSupportDialogFragment newInstance() {
return new CreateSupportDialogFragment();
}
private void disableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(false);
}
channelSpinner.setEnabled(false);
switchTip.setEnabled(false);
sendButton.setEnabled(false);
cancelLink.setEnabled(false);
}
private void enableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(true);
}
channelSpinner.setEnabled(true);
switchTip.setEnabled(true);
sendButton.setEnabled(true);
cancelLink.setEnabled(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_create_support, container, false);
inputAmount = view.findViewById(R.id.create_support_input_amount);
inlineBalanceContainer = view.findViewById(R.id.create_support_inline_balance_container);
inlineBalanceValue = view.findViewById(R.id.create_support_inline_balance_value);
sendProgress = view.findViewById(R.id.create_support_progress);
cancelLink = view.findViewById(R.id.create_support_cancel_link);
sendButton = view.findViewById(R.id.create_support_send);
channelSpinner = view.findViewById(R.id.create_support_channel_spinner);
switchTip = view.findViewById(R.id.create_support_make_tip_switch);
progressLoadingChannels = view.findViewById(R.id.create_support_channel_progress);
inputAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
inputAmount.setHint(hasFocus ? getString(R.string.zero) : "");
inlineBalanceContainer.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
inputAmount.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
updateSendButtonText();
}
@Override
public void afterTextChanged(Editable editable) {
}
});
updateInfoText();
updateSendButtonText();
String channel = null;
if (Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType())) {
channel = claim.getTitleOrName();
} else if (claim.getSigningChannel() != null) {
channel = claim.getPublisherTitle();
}
TextView titleView = view.findViewById(R.id.create_support_title);
String tipTitleText = Helper.isNullOrEmpty(channel) ? getString(R.string.send_a_tip) : getString(R.string.send_a_tip_to, channel);
titleView.setText(tipTitleText);
switchTip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
if (checked) {
// show tip info
titleView.setText(tipTitleText);
updateSendButtonText();
} else {
// show support info
titleView.setText(R.string.support_this_content);
sendButton.setText(R.string.send_revocable_support);
}
updateInfoText();
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String amountString = Helper.getValue(inputAmount.getText());
if (Helper.isNullOrEmpty(amountString)) {
showError(getString(R.string.invalid_amount));
return;
}
BigDecimal amount = new BigDecimal(amountString);
if (amount.doubleValue() > Lbry.walletBalance.getAvailable().doubleValue()) {
showError(getString(R.string.insufficient_balance));
return;
}
if (amount.doubleValue() < Helper.MIN_SPEND) {
showError(getString(R.string.min_spend_required));
return;
}
Claim selectedChannel = (Claim) channelSpinner.getSelectedItem();
String channelId = !fetchingChannels && selectedChannel != null ? selectedChannel.getClaimId() : null;
boolean isTip = switchTip.isChecked();
SupportCreateTask task = new SupportCreateTask(
claim.getClaimId(), channelId, amount, isTip, sendProgress, new GenericTaskHandler() {
@Override
public void beforeStart() {
disableControls();
}
@Override
public void onSuccess() {
enableControls();
if (listener != null) {
listener.onSupportCreated(amount, isTip);
}
dismiss();
}
@Override
public void onError(Exception error) {
showError(error.getMessage());
enableControls();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
cancelLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
onWalletBalanceUpdated(Lbry.walletBalance);
updateInfoText();
return view;
}
private void updateSendButtonText() {
boolean isTip = switchTip.isChecked();
if (!isTip) {
sendButton.setText(R.string.send_revocable_support);
} else {
String amountString = Helper.getValue(inputAmount.getText(), "0");
double parsedAmount = Helper.parseDouble(amountString, 0);
String text = getResources().getQuantityString(R.plurals.send_lbc_tip, parsedAmount == 1.0 ? 1 : 2, amountString);
sendButton.setText(text);
}
}
private void updateInfoText() {
View view = getView();
if (view != null && switchTip != null) {
TextView infoText = view.findViewById(R.id.create_support_info);
boolean isTip = switchTip.isChecked();
infoText.setMovementMethod(LinkMovementMethod.getInstance());
if (!isTip) {
infoText.setText(HtmlCompat.fromHtml(getString(R.string.support_info), HtmlCompat.FROM_HTML_MODE_LEGACY));
} else if (claim != null) {
infoText.setText(HtmlCompat.fromHtml(
Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType()) ?
getString(R.string.send_tip_info_channel, claim.getTitleOrName()) :
getString(R.string.send_tip_info_content, claim.getTitleOrName()),
HtmlCompat.FROM_HTML_MODE_LEGACY));
}
}
}
private void fetchChannels() {
if (Lbry.ownChannels != null && Lbry.ownChannels.size() > 0) {
updateChannelList(Lbry.ownChannels);
return;
}
fetchingChannels = true;
disableChannelSpinner();
ClaimListTask task = new ClaimListTask(Claim.TYPE_CHANNEL, progressLoadingChannels, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = new ArrayList<>(claims);
updateChannelList(Lbry.ownChannels);
enableChannelSpinner();
fetchingChannels = false;
}
@Override
public void onError(Exception error) {
enableChannelSpinner();
fetchingChannels = false;
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void disableChannelSpinner() {
Helper.setViewEnabled(channelSpinner, false);
}
private void enableChannelSpinner() {
Helper.setViewEnabled(channelSpinner, true);
}
private void updateChannelList(List<Claim> channels) {
if (channelSpinnerAdapter == null) {
Context context = getContext();
if (context != null) {
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, new ArrayList<>(channels));
channelSpinnerAdapter.addAnonymousPlaceholder();
channelSpinnerAdapter.notifyDataSetChanged();
}
} else {
channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.addAnonymousPlaceholder();
channelSpinnerAdapter.notifyDataSetChanged();
}
if (channelSpinner != null) {
channelSpinner.setAdapter(channelSpinnerAdapter);
}
if (channelSpinnerAdapter != null && channelSpinner != null) {
if (channelSpinnerAdapter.getCount() > 1) {
channelSpinner.setSelection(1);
}
}
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
updateInfoText();
fetchChannels();
}
public void onPause() {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).removeWalletBalanceListener(this);
}
super.onPause();
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
public interface CreateSupportListener {
void onSupportCreated(BigDecimal amount, boolean isTip);
}
}
@@ -192,14 +192,16 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
private void loadChannels(List<Claim> channels) {
if (channelSpinnerAdapter == null) {
Context context = getContext();
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, channels);
channelSpinnerAdapter.notifyDataSetChanged();
if (context != null) {
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, channels);
channelSpinnerAdapter.notifyDataSetChanged();
}
} else {
channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.notifyDataSetChanged();
}
if (channelSpinner != null) {
if (channelSpinner != null && channelSpinnerAdapter != null) {
channelSpinner.setAdapter(channelSpinnerAdapter);
}
}
@@ -229,8 +231,18 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
showError(getString(R.string.insufficient_balance));
return;
}
if (bid.doubleValue() < Helper.MIN_DEPOSIT) {
String message = getResources().getQuantityString(R.plurals.min_deposit_required, 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(message);
return;
}
Claim channel = (Claim) channelSpinner.getSelectedItem();
if (channel == null) {
showError(getString(R.string.please_select_repost_channel));
return;
}
StreamRepostTask task = new StreamRepostTask(name, bid, claim.getClaimId(), channel.getClaimId(), repostProgress, new ClaimResultHandler() {
@Override
public void beforeStart() {
@@ -256,10 +268,13 @@ public class RepostClaimDialogFragment extends BottomSheetDialogFragment impleme
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
View view = getView();
if (view != null && !Helper.isNullOrEmpty(message)) {
Snackbar.make(view, message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
}
private void startLoading() {
@@ -1,196 +0,0 @@
package io.lbry.browser.dialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import androidx.core.text.HtmlCompat;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.tasks.wallet.SupportCreateTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import lombok.Setter;
public class SendTipDialogFragment extends BottomSheetDialogFragment implements WalletBalanceListener {
public static final String TAG = "SendTipDialog";
private MaterialButton sendButton;
private View cancelLink;
private TextInputEditText inputAmount;
private View inlineBalanceContainer;
private TextView inlineBalanceValue;
private ProgressBar sendProgress;
@Setter
private SendTipListener listener;
@Setter
private Claim claim;
public static SendTipDialogFragment newInstance() {
return new SendTipDialogFragment();
}
private void disableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(false);
}
sendButton.setEnabled(false);
cancelLink.setEnabled(false);
}
private void enableControls() {
Dialog dialog = getDialog();
if (dialog != null) {
dialog.setCanceledOnTouchOutside(true);
}
sendButton.setEnabled(true);
cancelLink.setEnabled(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.dialog_send_tip, container, false);
inputAmount = view.findViewById(R.id.tip_input_amount);
inlineBalanceContainer = view.findViewById(R.id.tip_inline_balance_container);
inlineBalanceValue = view.findViewById(R.id.tip_inline_balance_value);
sendProgress = view.findViewById(R.id.tip_send_progress);
cancelLink = view.findViewById(R.id.tip_cancel_link);
sendButton = view.findViewById(R.id.tip_send);
inputAmount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
inputAmount.setHint(hasFocus ? getString(R.string.zero) : "");
inlineBalanceContainer.setVisibility(hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
TextView infoText = view.findViewById(R.id.tip_info);
infoText.setMovementMethod(LinkMovementMethod.getInstance());
infoText.setText(HtmlCompat.fromHtml(
Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType()) ?
getString(R.string.send_tip_info_channel, claim.getTitleOrName()) :
getString(R.string.send_tip_info_content, claim.getTitleOrName()),
HtmlCompat.FROM_HTML_MODE_LEGACY));
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String amountString = Helper.getValue(inputAmount.getText());
if (Helper.isNullOrEmpty(amountString)) {
showError(getString(R.string.invalid_amount));
return;
}
BigDecimal amount = new BigDecimal(amountString);
if (amount.doubleValue() > Lbry.walletBalance.getAvailable().doubleValue()) {
showError(getString(R.string.insufficient_balance));
return;
}
SupportCreateTask task = new SupportCreateTask(claim.getClaimId(), amount, true, sendProgress, new GenericTaskHandler() {
@Override
public void beforeStart() {
disableControls();
}
@Override
public void onSuccess() {
enableControls();
if (listener != null) {
listener.onTipSent(amount);
}
dismiss();
}
@Override
public void onError(Exception error) {
showError(error.getMessage());
enableControls();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
cancelLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dismiss();
}
});
String channel = null;
if (Claim.TYPE_CHANNEL.equalsIgnoreCase(claim.getValueType())) {
channel = claim.getTitleOrName();
} else if (claim.getSigningChannel() != null) {
channel = claim.getPublisherTitle();
}
((TextView) view.findViewById(R.id.tip_send_title)).setText(
Helper.isNullOrEmpty(channel) ? getString(R.string.send_a_tip) : getString(R.string.send_a_tip_to, channel)
);
onWalletBalanceUpdated(Lbry.walletBalance);
return view;
}
public void onResume() {
super.onResume();
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
}
public void onPause() {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).removeWalletBalanceListener(this);
}
super.onPause();
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void showError(String message) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).
setTextColor(Color.WHITE).
show();
}
public interface SendTipListener {
void onTipSent(BigDecimal amount);
}
}
@@ -0,0 +1,4 @@
package io.lbry.browser.exceptions;
public class AuthTokenInvalidatedException extends Exception {
}
@@ -0,0 +1,6 @@
package io.lbry.browser.listener;
public interface PIPModeListener {
void onEnterPIPMode();
void onExitPIPMode();
}
@@ -0,0 +1,6 @@
package io.lbry.browser.listener;
public interface ScreenOrientationListener {
void onPortraitOrientationEntered();
void onLandscapeOrientationEntered();
}
@@ -7,4 +7,7 @@ public interface SignInListener {
void onPhoneAdded(String countryCode, String phoneNumber);
void onPhoneVerified();
void onManualVerifyContinue();
void onSkipQueueAction();
void onTwitterVerified();
void onManualProgress(boolean progress);
}
@@ -54,6 +54,7 @@ public class Claim {
@EqualsAndHashCode.Include
private boolean placeholder;
private boolean placeholderAnonymous;
private boolean loadingPlaceholder;
private boolean featured;
private boolean unresolved; // used for featured
private String address;
@@ -289,6 +290,9 @@ public class Claim {
Claim signingChannel = new Claim();
signingChannel.setClaimId(viewHistory.getPublisherClaimId());
signingChannel.setName(viewHistory.getPublisherName());
LbryUri channelUrl = LbryUri.tryParse(String.format("%s#%s", signingChannel.getName(), signingChannel.getClaimId()));
signingChannel.setPermanentUrl(channelUrl != null ? channelUrl.toString() : null);
if (!Helper.isNullOrEmpty(viewHistory.getPublisherTitle())) {
GenericMetadata channelValue = new GenericMetadata();
channelValue.setTitle(viewHistory.getPublisherTitle());
@@ -0,0 +1,73 @@
package io.lbry.browser.model;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.utils.Helper;
import lombok.Data;
@Data
public class Comment implements Comparable<Comment> {
public static final int MAX_LENGTH = 2000;
private Claim poster;
private String claimId;
private List<Comment> replies;
private long timestamp;
private String channelId;
private String channelName, text, id, parentId;
public Comment(String channelId, String channelName, String text, String id, String parentId) {
this.channelId = channelId;
this.channelName = channelName;
this.text = text;
this.id = id;
this.parentId = parentId;
this.replies = new ArrayList<>();
}
public Comment() {
replies = new ArrayList<>();
}
public void addReply(Comment reply) {
if (replies == null) {
replies = new ArrayList<>();
}
if (!replies.contains(reply)) {
replies.add(reply);
}
}
public static Comment fromJSONObject(JSONObject jsonObject) {
try {
String parentId = null;
if (jsonObject.has("parent_id")) {
parentId = jsonObject.getString("parent_id");
}
Comment comment = new Comment(
Helper.getJSONString("channel_id", null, jsonObject),
jsonObject.getString("channel_name"),
jsonObject.getString("comment"),
jsonObject.getString("comment_id"),
parentId
);
comment.setClaimId(Helper.getJSONString("claim_id", null, jsonObject));
comment.setTimestamp(Helper.getJSONLong("timestamp", 0, jsonObject));
return comment;
} catch (JSONException ex) {
return null;
}
}
@Override
public int compareTo(Comment comment) {
return (int)(this.getTimestamp() - comment.getTimestamp());
}
}
@@ -20,6 +20,7 @@ public class NavMenuItem {
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;
public static final int ID_ITEM_SHUFFLE = 104;
// Your Content
public static final int ID_ITEM_CHANNELS = 201;
@@ -0,0 +1,11 @@
package io.lbry.browser.model;
public class StartupStage {
public Integer stage;
public Boolean stageDone;
public StartupStage(Integer stage, Boolean stageDone) {
this.stage = stage;
this.stageDone = stageDone;
}
}
@@ -5,7 +5,9 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import io.lbry.browser.R;
import io.lbry.browser.exceptions.LbryUriException;
@@ -53,13 +55,22 @@ public class Transaction {
int descStringId = -1;
TransactionInfo info = null;
List<TransactionInfo> infos = new ArrayList<>();
try {
if (jsonObject.has("abandon_info")) {
JSONArray array = jsonObject.getJSONArray("abandon_info");
if (array.length() > 0) {
info = TransactionInfo.fromJSONObject(array.getJSONObject(0));
descStringId = R.string.abandon;
transaction.setAbandonInfo(info);
if (array.length() == 1) {
info = TransactionInfo.fromJSONObject(array.getJSONObject(0));
descStringId = info.getBalanceDelta().doubleValue() == info.getAmount().doubleValue() ? R.string.unlock : R.string.abandon;
transaction.setAbandonInfo(info);
} else {
// multiple abandon infos (txo_spend unlock tip)
descStringId = R.string.unlock;
for (int i = 0; i < array.length(); i++) {
infos.add(TransactionInfo.fromJSONObject(array.getJSONObject(i)));
}
}
}
}
if (info == null && jsonObject.has("claim_info")) {
@@ -94,8 +105,18 @@ public class Transaction {
// pass
}
if (transaction.getValue().doubleValue() == 0 && info != null && info.getBalanceDelta().doubleValue() != 0) {
transaction.setValue(info.getBalanceDelta());
if (transaction.getValue().doubleValue() == 0) {
if (info != null && info.getBalanceDelta().doubleValue() != 0) {
transaction.setValue(info.getBalanceDelta());
} else if (infos.size() > 0) {
BigDecimal total = new BigDecimal(0);
for (TransactionInfo txInfo : infos) {
total = total.add(txInfo.getAmount());
}
transaction.setValue(total);
}
}
if (descStringId == -1) {
@@ -0,0 +1,9 @@
package io.lbry.browser.model;
import lombok.Data;
@Data
public class TwitterOauth {
private String oauthToken;
private String oauthTokenSecret;
}
@@ -1,7 +1,10 @@
package io.lbry.browser.model;
import org.json.JSONObject;
import java.math.BigDecimal;
import io.lbry.browser.utils.Helper;
import lombok.Data;
@Data
@@ -21,4 +24,18 @@ public class WalletBalance {
tips = new BigDecimal(0);
total = new BigDecimal(0);
}
public static WalletBalance fromJSONObject(JSONObject json) {
WalletBalance balance = new WalletBalance();
JSONObject reservedSubtotals = Helper.getJSONObject("reserved_subtotals", json);
balance.setAvailable(new BigDecimal(Helper.getJSONString("available", "0", json)));
balance.setReserved(new BigDecimal(Helper.getJSONString("reserved", "0", json)));
balance.setTotal(new BigDecimal(Helper.getJSONString("total", "0", json)));
if (reservedSubtotals != null) {
balance.setClaims(new BigDecimal(Helper.getJSONString("claims", "0", reservedSubtotals)));
balance.setSupports(new BigDecimal(Helper.getJSONString("supports", "0", reservedSubtotals)));
balance.setTips(new BigDecimal(Helper.getJSONString("tips", "0", reservedSubtotals)));
}
return balance;
}
}
@@ -0,0 +1,40 @@
package io.lbry.browser.model.lbryinc;
import java.util.Comparator;
import java.util.Date;
import io.lbry.browser.model.Claim;
import lombok.Data;
import lombok.EqualsAndHashCode;
@Data
@EqualsAndHashCode(callSuper = false, onlyExplicitlyIncluded = true)
public class LbryNotification implements Comparator<LbryNotification> {
private long id;
@EqualsAndHashCode.Include
private long remoteId;
private String title;
private String description;
private String thumbnailUrl;
private String rule;
private String targetUrl;
private boolean read;
private boolean seen;
private Date timestamp;
// only for comment notifications
private String authorUrl;
private Claim commentAuthor;
public int compare(LbryNotification a, LbryNotification b) {
long t1 = a.getTimestamp() != null ? a.getTimestamp().getTime() : 0;
long t2 = b.getTimestamp() != null ? b.getTimestamp().getTime() : 0;
if (t1 < t2) {
return -1;
}
if (t1 > t2) {
return 1;
}
return 0;
}
}
@@ -0,0 +1,9 @@
package io.lbry.browser.model.lbryinc;
import lombok.Data;
@Data
public class RewardVerified {
private long userId;
private boolean isRewardApproved;
}
@@ -11,17 +11,21 @@ public class Subscription {
@Getter
@Setter
private String url;
@Getter
@Setter
private boolean isNotificationsDisabled;
public Subscription() {
}
public Subscription(String channelName, String url) {
public Subscription(String channelName, String url, boolean isNotificationsDisabled) {
this.channelName = channelName;
this.url = url;
this.isNotificationsDisabled = isNotificationsDisabled;
}
public static Subscription fromClaim(Claim claim) {
return new Subscription(claim.getName(), claim.getPermanentUrl());
return new Subscription(claim.getName(), claim.getPermanentUrl(), false);
}
public String toString() {
return url;
@@ -0,0 +1,65 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.util.concurrent.TimeUnit;
import io.lbry.browser.utils.Helper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class BufferEventTask extends AsyncTask<Void, Void, Void> {
private static final String TAG = "LbryBufferEvent";
private static final String ENDPOINT = "https://collector-service.api.lbry.tv/api/v1/events/video";
private String streamUrl;
private String userIdHash;
private long streamDuration;
private long streamPosition;
private long bufferDuration;
public BufferEventTask(String streamUrl, long streamDuration, long streamPosition, long bufferDuration, String userIdHash) {
this.streamUrl = streamUrl;
this.bufferDuration = bufferDuration;
this.streamDuration = streamDuration;
this.streamPosition = streamPosition;
this.userIdHash = userIdHash;
}
protected Void doInBackground(Void... params) {
JSONObject requestBody = new JSONObject();
JSONObject data = new JSONObject();
try {
data.put("url", streamUrl);
data.put("position", streamPosition);
data.put("stream_duration", streamDuration);
//data.put("duration", bufferDuration);
requestBody.put("device", "android");
requestBody.put("type", "buffering");
requestBody.put("client", userIdHash);
requestBody.put("data", data);
RequestBody body = RequestBody.create(requestBody.toString(), Helper.JSON_MEDIA_TYPE);
Request request = new Request.Builder().url(ENDPOINT).post(body).build();
OkHttpClient client = new OkHttpClient.Builder().
writeTimeout(60, TimeUnit.SECONDS).
readTimeout(60, TimeUnit.SECONDS).
build();
Response response = client.newCall(request).execute();
String responseString = response.body().string();
Log.d(TAG, String.format("buffer event sent: %s", responseString));
} catch (Exception ex) {
// we don't want to fail if a buffer event fails to register
Log.d(TAG, String.format("buffer event log failed: %s", ex.getMessage()), ex);
}
return null;
}
}
@@ -0,0 +1,94 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.Comment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.Lbryio;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class CommentCreateTask extends AsyncTask<Void, Void, Comment> {
private static final String STATUS_ENDPOINT = "https://comments.lbry.com";
private Comment comment;
private View progressView;
private CommentCreateWithTipHandler handler;
private Exception error;
public CommentCreateTask(Comment comment, View progressView, CommentCreateWithTipHandler handler) {
this.comment = comment;
this.progressView = progressView;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
public Comment doInBackground(Void... params) {
Comment createdComment = null;
try {
// check comments status endpoint
Request request = new Request.Builder().url(STATUS_ENDPOINT).build();
OkHttpClient client = new OkHttpClient.Builder().
writeTimeout(30, TimeUnit.SECONDS).
readTimeout(30, TimeUnit.SECONDS).
build();
Response response = client.newCall(request).execute();
JSONObject status = new JSONObject(response.body().string());
String statusText = Helper.getJSONString("text", null, status);
boolean isRunning = Helper.getJSONBoolean("is_running", false, status);
if (!"ok".equalsIgnoreCase(statusText) || !isRunning) {
throw new ApiCallException("The comment server is not available at this time. Please try again later.");
}
Map<String, Object> options = new HashMap<>();
options.put("comment", comment.getText());
options.put("claim_id", comment.getClaimId());
options.put("channel_id", comment.getChannelId());
options.put("channel_name", comment.getChannelName());
if (!Helper.isNullOrEmpty(comment.getParentId())) {
options.put("parent_id", comment.getParentId());
}
JSONObject jsonObject = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_COMMENT_CREATE, options);
createdComment = Comment.fromJSONObject(jsonObject);
} catch (ApiCallException | ClassCastException | IOException | JSONException ex) {
error = ex;
}
return createdComment;
}
protected void onPostExecute(Comment createdComment) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (createdComment != null) {
handler.onSuccess(createdComment);
} else {
handler.onError(error);
}
}
}
public interface CommentCreateWithTipHandler {
void onSuccess(Comment createdComment);
void onError(Exception error);
}
}
@@ -0,0 +1,10 @@
package io.lbry.browser.tasks;
import java.util.List;
import io.lbry.browser.model.Comment;
public interface CommentListHandler {
void onSuccess(List<Comment> comments, boolean hasReachedEnd);
void onError(Exception error);
}
@@ -0,0 +1,98 @@
package io.lbry.browser.tasks;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.model.Comment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class CommentListTask extends AsyncTask<Void, Void, List<Comment>> {
private final int page;
private final int pageSize;
private final String claim;
private ProgressBar progressBar;
private CommentListHandler handler;
private Exception error;
public CommentListTask(int page, int pageSize, String claim, ProgressBar progressBar, CommentListHandler handler) {
this.page = page;
this.pageSize = pageSize;
this.claim = claim;
this.progressBar = progressBar;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressBar, View.VISIBLE);
}
protected List<Comment> doInBackground(Void... voids) {
List<Comment> comments = null;
try {
Map<String, Object> options = new HashMap<>();
options.put("claim_id", claim);
options.put("page", page);
options.put("page_size", pageSize);
options.put("hidden", false);
options.put("include_replies", false);
options.put("is_channel_signature_valid", true);
options.put("skip_validation", true);
options.put("visible", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_COMMENT_LIST, options);
JSONArray items = result.getJSONArray("items");
List<Comment> children = new ArrayList<>();
comments = new ArrayList<>();
for (int i = 0; i < items.length(); i++) {
Comment comment = Comment.fromJSONObject(items.getJSONObject(i));
if (comment != null) {
if (!Helper.isNullOrEmpty(comment.getParentId())) {
children.add(comment);
} else {
comments.add(comment);
}
}
}
// Sort all replies from oldest to newest at once
Collections.sort(children);
for (Comment child : children) {
for (Comment parent : comments) {
if (parent.getId().equalsIgnoreCase(child.getParentId())) {
parent.addReply(child);
break;
}
}
}
} catch (Exception ex) {
error = ex;
}
return comments;
}
protected void onPostExecute(List<Comment> comments) {
Helper.setViewVisibility(progressBar, View.GONE);
if (handler != null) {
if (comments != null) {
handler.onSuccess(comments, comments.size() < pageSize);
} else {
handler.onError(error);
}
}
}
}
@@ -34,9 +34,11 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
private List<Subscription> diff;
private MergeSubscriptionsHandler handler;
private Exception error;
private boolean replaceLocal;
public MergeSubscriptionsTask(List<Subscription> base, Context context, MergeSubscriptionsHandler handler) {
public MergeSubscriptionsTask(List<Subscription> base, boolean replaceLocal, Context context, MergeSubscriptionsHandler handler) {
this.base = base;
this.replaceLocal = replaceLocal;
this.context = context;
this.handler = handler;
}
@@ -53,10 +55,17 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
db = ((MainActivity) context).getDbHelper().getWritableDatabase();
}
if (db != null) {
localSubs = DatabaseHelper.getSubscriptions(db);
for (Subscription sub : localSubs) {
if (!combined.contains(sub)) {
combined.add(sub);
if (replaceLocal) {
DatabaseHelper.clearSubscriptions(db);
for (Subscription sub : base) {
DatabaseHelper.createOrUpdateSubscription(sub, db);
}
} else {
localSubs = DatabaseHelper.getSubscriptions(db);
for (Subscription sub : localSubs) {
if (!combined.contains(sub)) {
combined.add(sub);
}
}
}
}
@@ -64,48 +73,55 @@ public class MergeSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
// fetch remote subscriptions
JSONArray array = (JSONArray) Lbryio.parseResponse(Lbryio.call("subscription", "list", context));
if (array != null) {
// check for any remote subs that may have been removed, and unsubscribe from them
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
// TODO: Refactor by creating static Subscription.fromJSON method
String claimId = item.getString("claim_id");
String channelName = item.getString("channel_name");
boolean isNotificationsDisabled = item.getBoolean("is_notifications_disabled");
LbryUri url = new LbryUri();
url.setChannelName(channelName);
url.setClaimId(claimId);
Subscription subscription = new Subscription(channelName, url.toString());
Subscription subscription = new Subscription(channelName, url.toString(), isNotificationsDisabled);
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());
List<Subscription> remoteUnsubs = new ArrayList<>();
List<Subscription> finalRemoteSubs = new ArrayList<>();
if (remoteSubs.size() > 0) {
for (int i = 0; i < remoteSubs.size(); i++) {
Subscription sub = remoteSubs.get(i);
if (!combined.contains(sub)) {
Map<String, String> options = new HashMap<>();
options.put("claim_id", uri.getChannelClaimId());
options.put("channel_name", Helper.normalizeChannelName(local.getChannelName()));
Lbryio.parseResponse(Lbryio.call("subscription", "new", options, context));
} catch (LbryUriException | LbryioRequestException | LbryioResponseException ex) {
// pass
Log.e(TAG, String.format("subscription/new failed: %s", ex.getMessage()), ex);
LbryUri uri = LbryUri.tryParse(sub.getUrl());
if (uri != null) {
options.put("claim_id", uri.getChannelClaimId());
Lbryio.parseResponse(Lbryio.call("subscription", "delete", options, context));
remoteUnsubs.add(sub);
} else {
finalRemoteSubs.add(sub);
}
}
}
}
for (int i = 0; i < localSubs.size(); i++) {
Subscription local = localSubs.get(i);
if (!base.contains(local) && !diff.contains(local)) {
diff.add(local);
if (!replaceLocal) {
for (int i = 0; i < localSubs.size(); i++) {
Subscription local = localSubs.get(i);
if (!base.contains(local) && !diff.contains(local)) {
diff.add(local);
}
}
}
for (int i = 0; i < remoteSubs.size(); i++) {
Subscription remote = remoteSubs.get(i);
if (!combined.contains(remote)) {
combined.add(remote);
if (!diff.contains(remote)) {
diff.add(remote);
for (int i = 0; i < finalRemoteSubs.size(); i++) {
Subscription remote = finalRemoteSubs.get(i);
if (!combined.contains(remote)) {
combined.add(remote);
if (!diff.contains(remote)) {
diff.add(remote);
}
}
}
}
@@ -0,0 +1,8 @@
package io.lbry.browser.tasks;
import io.lbry.browser.model.lbryinc.RewardVerified;
public interface RewardVerifiedHandler {
void onSuccess(RewardVerified rewardVerified);
void onError(Exception error);
}
@@ -0,0 +1,8 @@
package io.lbry.browser.tasks;
import io.lbry.browser.model.TwitterOauth;
public interface TwitterOauthHandler {
void onSuccess(TwitterOauth twitterOauth);
void onError(Exception error);
}
@@ -45,13 +45,15 @@ public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
if (suggestedTagsAdapter != null && !clearPrevious) {
tags = new ArrayList<>(suggestedTagsAdapter.getTags());
}
while (tags.size() < limit) {
Tag randomTag = Lbry.knownTags.get(random.nextInt(Lbry.knownTags.size()));
if (excludeMature && randomTag.isMature()) {
continue;
}
if (!Lbry.followedTags.contains(randomTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(randomTag))) {
tags.add(randomTag);
if (Lbry.knownTags.size() > 0) {
while (tags.size() < limit) {
Tag randomTag = Lbry.knownTags.get(random.nextInt(Lbry.knownTags.size()));
if (excludeMature && randomTag.isMature()) {
continue;
}
if (!Lbry.followedTags.contains(randomTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(randomTag))) {
tags.add(randomTag);
}
}
}
} else {
@@ -64,10 +66,15 @@ public class UpdateSuggestedTagsTask extends AsyncTask<Void, Void, List<Tag>> {
if (excludeMature && knownTag.isMature()) {
continue;
}
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);
try {
if ((knownTag.getLowercaseName().startsWith(filter) ||
knownTag.getLowercaseName().matches(filter)) &&
(!tags.contains(knownTag) && !Lbry.followedTags.contains(knownTag) && (addedTagsAdapter == null || !addedTagsAdapter.getTags().contains(knownTag)))
) {
tags.add(knownTag);
}
} catch (Exception ex) {
// continue
}
}
}
@@ -62,7 +62,8 @@ public class ClaimListTask extends AsyncTask<Void, Void, List<Claim>> {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (claims != null) {
handler.onSuccess(claims);
// TODO: Add fix for handling invalid reposts in ClaimListAdapter
handler.onSuccess(Helper.filterInvalidReposts(claims));
} else {
handler.onError(error);
}
@@ -29,7 +29,7 @@ public class ClaimSearchTask extends AsyncTask<Void, Void, List<Claim>> {
}
protected List<Claim> doInBackground(Void... params) {
try {
return Helper.filterInvalidReposts(Lbry.claimSearch(options, connectionString));
return Lbry.claimSearch(options, connectionString);
} catch (ApiCallException ex) {
error = ex;
return null;
@@ -39,7 +39,7 @@ public class ClaimSearchTask extends AsyncTask<Void, Void, List<Claim>> {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (claims != null) {
handler.onSuccess(claims, claims.size() < Helper.parseInt(options.get("page_size"), 0));
handler.onSuccess(Helper.filterInvalidReposts(claims), claims.size() < Helper.parseInt(options.get("page_size"), 0));
} else {
handler.onError(error);
}
@@ -73,6 +73,14 @@ public class PublishClaimTask extends AsyncTask<Void, Void, Claim> {
options.put("license_url", metadata.getLicenseUrl());
}
if (metadata.getReleaseTime() > 0) {
options.put("release_time", metadata.getReleaseTime());
} else if (claim.getTimestamp() > 0) {
options.put("release_time", claim.getTimestamp());
} else {
options.put("release_time", Double.valueOf(Math.floor(System.currentTimeMillis() / 1000.0)).intValue());
}
Claim claimResult = null;
try {
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PUBLISH, options);
@@ -18,12 +18,19 @@ import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class PurchaseListTask extends AsyncTask<Void, Void, List<Claim>> {
private String claimId;
private int page;
private int pageSize;
private ClaimSearchResultHandler handler;
private View progressView;
private Exception error;
public PurchaseListTask(String claimId, View progressView, ClaimSearchResultHandler handler) {
this.claimId = claimId;
this.progressView = progressView;
this.handler = handler;
}
public PurchaseListTask(int page, int pageSize, View progressView, ClaimSearchResultHandler handler) {
this.page = page;
this.pageSize = pageSize;
@@ -38,8 +45,15 @@ public class PurchaseListTask extends AsyncTask<Void, Void, List<Claim>> {
List<Claim> claims = null;
try {
Map<String, Object> options = new HashMap<>();
options.put("page", page);
options.put("page_size", pageSize);
if (!Helper.isNullOrEmpty(claimId)) {
options.put("claim_id", claimId);
}
if (page > 0) {
options.put("page", page);
}
if (pageSize > 0) {
options.put("page_size", pageSize);
}
options.put("resolve", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PURCHASE_LIST, options);
@@ -47,9 +61,10 @@ public class PurchaseListTask extends AsyncTask<Void, Void, List<Claim>> {
claims = new ArrayList<>();
for (int i = 0; i < items.length(); i++) {
Claim claim = Claim.fromJSONObject(items.getJSONObject(i).getJSONObject("claim"));
claims.add(claim);
Lbry.addClaimToCache(claim);
if (!Helper.isNullOrEmpty(claim.getClaimId())) {
claims.add(claim);
Lbry.addClaimToCache(claim);
}
}
} catch (ApiCallException | JSONException | ClassCastException ex) {
error = ex;
@@ -0,0 +1,68 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import io.lbry.browser.MainActivity;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
import okhttp3.Response;
public class AndroidPurchaseTask extends AsyncTask<Void, Void, RewardVerified> {
private Context context;
private View progressView;
private String purchaseToken;
private RewardVerifiedHandler handler;
private Exception error;
public AndroidPurchaseTask(String purchaseToken, View progressView, Context context, RewardVerifiedHandler handler) {
this.purchaseToken = purchaseToken;
this.progressView = progressView;
this.context = context;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected RewardVerified doInBackground(Void... params) {
try {
Map<String, String> options = new HashMap<>();
options.put("purchase_token", purchaseToken);
JSONObject object = (JSONObject) Lbryio.parseResponse(Lbryio.call("verification", "android_purchase", options, context));
Type type = new TypeToken<RewardVerified>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
return gson.fromJson(object.toString(), type);
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(RewardVerified result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (result != null) {
handler.onSuccess(result);
} else {
handler.onError(error);
}
}
}
}
@@ -51,11 +51,11 @@ public class ChannelSubscribeTask extends AsyncTask<Void, Void, Boolean> {
options.put("claim_id", channelClaimId);
if (!isUnsubscribing) {
options.put("channel_name", subscription.getChannelName());
options.put("notifications_disabled", String.valueOf(subscription.isNotificationsDisabled()).toLowerCase());
}
String action = isUnsubscribing ? "delete" : "new";
Lbryio.call("subscription", action, options, context);
Object response = Lbryio.parseResponse(Lbryio.call("subscription", action, options, context));
if (!isUnsubscribing) {
Lbryio.addSubscription(subscription);
} else {
@@ -4,9 +4,12 @@ import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
@@ -14,6 +17,8 @@ import io.lbry.browser.R;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.lbryinc.Reward;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.Lbryio;
@@ -22,15 +27,15 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
private Context context;
private String type;
private String claimCode;
private String rewardCode;
private View progressView;
private double amountClaimed;
private ClaimRewardHandler handler;
private Exception error;
public ClaimRewardTask(String type, String claimCode, View progressView, Context context, ClaimRewardHandler handler) {
public ClaimRewardTask(String type, String rewardCode, View progressView, Context context, ClaimRewardHandler handler) {
this.type = type;
this.claimCode = claimCode;
this.rewardCode = rewardCode;
this.progressView = progressView;
this.context = context;
this.handler = handler;
@@ -43,15 +48,27 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
public String doInBackground(Void... params) {
String message = null;
try {
String txid = null;
if (Reward.TYPE_FIRST_CHANNEL.equalsIgnoreCase(type)) {
// fetch a channel
txid = fetchSingleClaimTxid(Claim.TYPE_CHANNEL);
} else if (Reward.TYPE_FIRST_PUBLISH.equalsIgnoreCase(type)) {
// fetch a publish
txid = fetchSingleClaimTxid(Claim.TYPE_STREAM);
}
// Get a new wallet address for the reward
String address = (String) Lbry.genericApiCall(Lbry.METHOD_ADDRESS_UNUSED);
Map<String, String> options = new HashMap<>();
options.put("reward_type", type);
options.put("wallet_address", address);
if (!Helper.isNullOrEmpty(claimCode)) {
options.put("claim_code", claimCode);
if (!Helper.isNullOrEmpty(rewardCode)) {
options.put("code", rewardCode);
}
if (!Helper.isNullOrEmpty(txid)) {
options.put("transaction_id", txid);
}
JSONObject reward = (JSONObject) Lbryio.parseResponse(
Lbryio.call("reward", "claim", options, Helper.METHOD_POST, null));
amountClaimed = Helper.getJSONDouble("reward_amount", 0, reward);
@@ -61,7 +78,7 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
amountClaimed == 1 ? 1 : 2,
new DecimalFormat(Helper.LBC_CURRENCY_FORMAT_PATTERN).format(amountClaimed)) : "";
message = Helper.getJSONString("reward_notification", defaultMessage, reward);
} catch (ApiCallException | LbryioRequestException | LbryioResponseException ex) {
} catch (ApiCallException | JSONException | LbryioRequestException | LbryioResponseException ex) {
error = ex;
}
@@ -79,6 +96,23 @@ public class ClaimRewardTask extends AsyncTask<Void, Void, String> {
}
}
private String fetchSingleClaimTxid(String claimType) throws ApiCallException, JSONException {
Map<String, Object> options = new HashMap<>();
options.put("claim_type", claimType);
options.put("page", 1);
options.put("page_size", 1);
options.put("resolve", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_CLAIM_LIST, options);
JSONArray items = result.getJSONArray("items");
if (items.length() > 0) {
Claim claim = Claim.fromJSONObject(items.getJSONObject(0));
return claim.getTxid();
}
return null;
}
public interface ClaimRewardHandler {
void onSuccess(double amountClaimed, String message);
void onError(Exception error);
@@ -1,20 +1,23 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.os.AsyncTask;
import io.lbry.browser.model.lbryinc.User;
import io.lbry.browser.utils.Lbryio;
public class FetchCurrentUserTask extends AsyncTask<Void, Void, User> {
private Context context;
private Exception error;
private FetchUserTaskHandler handler;
public FetchCurrentUserTask(FetchUserTaskHandler handler) {
public FetchCurrentUserTask(Context context, FetchUserTaskHandler handler) {
this.context = context;
this.handler = handler;
}
protected User doInBackground(Void... params) {
try {
return Lbryio.fetchCurrentUser(null);
return Lbryio.fetchCurrentUser(context);
} catch (Exception ex) {
error = ex;
return null;
@@ -49,11 +49,12 @@ public class FetchSubscriptionsTask extends AsyncTask<Void, Void, List<Subscript
JSONObject item = array.getJSONObject(i);
String claimId = item.getString("claim_id");
String channelName = item.getString("channel_name");
boolean isNotificationsDisabled = item.getBoolean("is_notifications_disabled");
LbryUri url = new LbryUri();
url.setChannelName(channelName);
url.setClaimId(claimId);
Subscription subscription = new Subscription(channelName, url.toString());
Subscription subscription = new Subscription(channelName, url.toString(), isNotificationsDisabled);
subscriptions.add(subscription);
// Persist the subscription locally if it doesn't exist
if (db != null) {
@@ -0,0 +1,33 @@
package io.lbry.browser.tasks.lbryinc;
import android.os.AsyncTask;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class NotificationDeleteTask extends AsyncTask<Void, Void, Boolean> {
private List<Long> ids;
public NotificationDeleteTask(List<Long> ids) {
this.ids = ids;
}
protected Boolean doInBackground(Void... params) {
Map<String, String> options = new HashMap<>();
options.put("notification_ids", Helper.joinL(ids, ","));
try {
Object result = Lbryio.parseResponse(Lbryio.call("notification", "delete", options, null));
return "ok".equalsIgnoreCase(result.toString());
} catch (LbryioResponseException | LbryioRequestException ex) {
// pass
}
return false;
}
}
@@ -0,0 +1,128 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import io.lbry.browser.MainActivity;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.model.lbryinc.LbryNotification;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class NotificationListTask extends AsyncTask<Void, Void, List<LbryNotification>> {
private static final String TAG = "Notifications";
private Context context;
private ListNotificationsHandler handler;
private ProgressBar progressBar;
private Exception error;
public NotificationListTask(Context context, ProgressBar progressBar, ListNotificationsHandler handler) {
this.context = context;
this.progressBar = progressBar;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressBar, View.VISIBLE);
}
protected List<LbryNotification> doInBackground(Void... params) {
List<LbryNotification> notifications = new ArrayList<>();
SQLiteDatabase db = null;
try {
JSONArray array = (JSONArray) Lbryio.parseResponse(Lbryio.call("notification", "list", context));
if (array != null) {
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
if (item.has("notification_parameters")) {
LbryNotification notification = new LbryNotification();
JSONObject notificationParams = item.getJSONObject("notification_parameters");
if (notificationParams.has("device")) {
JSONObject device = notificationParams.getJSONObject("device");
notification.setTitle(Helper.getJSONString("title", null, device));
notification.setDescription(Helper.getJSONString("text", null, device));
notification.setTargetUrl(Helper.getJSONString("target", null, device));
}
if (notificationParams.has("dynamic") && !notificationParams.isNull("dynamic")) {
JSONObject dynamic = notificationParams.getJSONObject("dynamic");
if (dynamic.has("comment_author")) {
notification.setAuthorUrl(Helper.getJSONString("comment_author", null, dynamic));
}
if (dynamic.has("channelURI")) {
String channelUrl = Helper.getJSONString("channelURI", null, dynamic);
if (!Helper.isNullOrEmpty(channelUrl)) {
notification.setTargetUrl(channelUrl);
}
}
if (dynamic.has("hash") && "comment".equalsIgnoreCase(Helper.getJSONString("notification_rule", null, item))) {
notification.setTargetUrl(String.format("%s?comment_hash=%s", notification.getTargetUrl(), dynamic.getString("hash")));
}
}
notification.setRule(Helper.getJSONString("notification_rule", null, item));
notification.setRemoteId(Helper.getJSONLong("id", 0, item));
notification.setRead(Helper.getJSONBoolean("is_read", false, item));
notification.setSeen(Helper.getJSONBoolean("is_seen", false, item));
try {
SimpleDateFormat dateFormat = new SimpleDateFormat(Helper.ISO_DATE_FORMAT_JSON, Locale.US);
notification.setTimestamp(dateFormat.parse(Helper.getJSONString("created_at", dateFormat.format(new Date()), item)));
} catch (ParseException ex) {
notification.setTimestamp(new Date());
}
if (notification.getRemoteId() > 0 && !Helper.isNullOrEmpty(notification.getDescription())) {
notifications.add(notification);
}
}
}
if (context instanceof MainActivity) {
db = ((MainActivity) context).getDbHelper().getWritableDatabase();
for (LbryNotification notification : notifications) {
DatabaseHelper.createOrUpdateNotification(notification, db);
}
}
}
} catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException | SQLiteException | IllegalStateException ex) {
Log.e(TAG, ex.getMessage(), ex);
error = ex;
return null;
}
return notifications;
}
protected void onPostExecute(List<LbryNotification> notifications) {
Helper.setViewVisibility(progressBar, View.GONE);
if (handler != null) {
if (notifications != null) {
handler.onSuccess(notifications);
} else {
handler.onError(error);
}
}
}
public interface ListNotificationsHandler {
void onSuccess(List<LbryNotification> notifications);
void onError(Exception exception);
}
}
@@ -0,0 +1,47 @@
package io.lbry.browser.tasks.lbryinc;
import android.os.AsyncTask;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.LbryioRequestException;
import io.lbry.browser.exceptions.LbryioResponseException;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class NotificationUpdateTask extends AsyncTask<Void, Void, Boolean> {
private List<Long> ids;
private boolean seen;
private boolean read;
private boolean updateRead;
public NotificationUpdateTask(List<Long> ids, boolean seen) {
this(ids, false, true, false);
}
public NotificationUpdateTask(List<Long> ids, boolean read, boolean seen, boolean updateRead) {
this.ids = ids;
this.read = read;
this.seen = seen;
this.updateRead = updateRead;
}
protected Boolean doInBackground(Void... params) {
Map<String, String> options = new HashMap<>();
options.put("notification_ids", Helper.joinL(ids, ","));
options.put("is_seen", String.valueOf(seen));
if (updateRead) {
options.put("is_read", String.valueOf(read));
}
try {
Object result = Lbryio.parseResponse(Lbryio.call("notification", "edit", options, null));
return "ok".equalsIgnoreCase(result.toString());
} catch (LbryioResponseException | LbryioRequestException ex) {
}
return false;
}
}
@@ -0,0 +1,68 @@
package io.lbry.browser.tasks.lbryinc;
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import io.lbry.browser.model.TwitterOauth;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
public class TwitterVerifyTask extends AsyncTask<Void, Void, RewardVerified> {
private Context context;
private View progressView;
private TwitterOauth twitterOauth;
private RewardVerifiedHandler handler;
private Exception error;
public TwitterVerifyTask(TwitterOauth twitterOauth, View progressView, Context context, RewardVerifiedHandler handler) {
this.twitterOauth = twitterOauth;
this.progressView = progressView;
this.context = context;
this.handler = handler;
}
protected void onPreExecute() {
Helper.setViewVisibility(progressView, View.VISIBLE);
}
protected RewardVerified doInBackground(Void... params) {
try {
Map<String, String> options = new HashMap<>();
options.put("oauth_token", twitterOauth.getOauthToken());
options.put("oauth_token_secret", twitterOauth.getOauthTokenSecret());
JSONObject object = (JSONObject) Lbryio.parseResponse(Lbryio.call("verification", "twitter_verify", options, context));
Type type = new TypeToken<RewardVerified>(){}.getType();
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
return gson.fromJson(object.toString(), type);
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(RewardVerified result) {
Helper.setViewVisibility(progressView, View.GONE);
if (handler != null) {
if (result != null) {
handler.onSuccess(result);
} else {
handler.onError(error);
}
}
}
}
@@ -54,24 +54,25 @@ public class LoadGalleryItemsTask extends AsyncTask<Void, GalleryItem, List<Gall
cursor = resolver.query(
MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
projection, null, null,
String.format("%s DESC", MediaStore.MediaColumns.DATE_MODIFIED));
while (cursor.moveToNext()) {
int idColumn = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
int nameColumn = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
int typeColumn = cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE);
int pathColumn = cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
int durationColumn = cursor.getColumnIndex(MediaStore.Video.Media.DURATION);
String.format("%s DESC LIMIT 150", MediaStore.MediaColumns.DATE_MODIFIED));
if (cursor != null) {
while (cursor.moveToNext()) {
int idColumn = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
int nameColumn = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
int typeColumn = cursor.getColumnIndex(MediaStore.MediaColumns.MIME_TYPE);
int pathColumn = cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
int durationColumn = cursor.getColumnIndex(MediaStore.Video.Media.DURATION);
GalleryItem item = new GalleryItem();
item.setId(cursor.getString(idColumn));
item.setName(cursor.getString(nameColumn));
item.setType(cursor.getString(typeColumn));
item.setFilePath(cursor.getString(pathColumn));
item.setDuration(cursor.getLong(durationColumn));
items.add(item);
GalleryItem item = new GalleryItem();
item.setId(cursor.getString(idColumn));
item.setName(cursor.getString(nameColumn));
item.setType(cursor.getString(typeColumn));
item.setFilePath(cursor.getString(pathColumn));
item.setDuration(cursor.getLong(durationColumn));
items.add(item);
}
}
} catch (SQLiteException ex) {
// failed to load videos. log and pass
Log.e(TAG, ex.getMessage(), ex);
} finally {
@@ -1,20 +1,28 @@
package io.lbry.browser.tasks.verification;
import android.content.Context;
import android.os.AsyncTask;
import io.lbry.browser.exceptions.AuthTokenInvalidatedException;
import io.lbry.browser.model.lbryinc.User;
import io.lbry.browser.utils.Lbryio;
public class CheckUserEmailVerifiedTask extends AsyncTask<Void, Void, Boolean> {
private Context context;
private CheckUserEmailVerifiedHandler handler;
public CheckUserEmailVerifiedTask(CheckUserEmailVerifiedHandler handler) {
public CheckUserEmailVerifiedTask(Context context, CheckUserEmailVerifiedHandler handler) {
this.context = context;
this.handler = handler;
}
protected Boolean doInBackground(Void... params) {
User user = Lbryio.fetchCurrentUser(null);
return user != null && user.isHasVerifiedEmail();
try {
User user = Lbryio.fetchCurrentUser(context);
return user != null && user.isHasVerifiedEmail();
} catch (AuthTokenInvalidatedException ex) {
return false;
}
}
protected void onPostExecute(Boolean result) {
@@ -0,0 +1,68 @@
package io.lbry.browser.tasks.verification;
import android.os.AsyncTask;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.http.GenericUrl;
import io.lbry.browser.VerificationActivity;
import io.lbry.browser.model.TwitterOauth;
import io.lbry.browser.tasks.TwitterOauthHandler;
import io.lbry.browser.utils.Helper;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TwitterAccessTokenTask extends AsyncTask<Void, Void, String> {
private static final String ENDPOINT = "https://api.twitter.com/oauth/access_token";
private Exception error;
private String oauthParams;
private TwitterOauthHandler handler;
public TwitterAccessTokenTask(String oauthParams, TwitterOauthHandler handler) {
this.oauthParams = oauthParams;
this.handler = handler;
}
public String doInBackground(Void... params) {
try {
String url = String.format("%s?%s", ENDPOINT, oauthParams);
RequestBody body = RequestBody.create(new byte[0]);
Request request = new Request.Builder().url(url).post(body).build();
OkHttpClient client = new OkHttpClient.Builder().build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(String response) {
if (!Helper.isNullOrEmpty(response)) {
String[] pairs = response.split("&");
TwitterOauth twitterOauth = new TwitterOauth();
for (String pair : pairs) {
String[] parts = pair.split("=");
if (parts.length != 2) {
continue;
}
String key = parts[0];
String value = parts[1];
if ("oauth_token".equalsIgnoreCase(key)) {
twitterOauth.setOauthToken(value);
} else if ("oauth_token_secret".equalsIgnoreCase(key)) {
twitterOauth.setOauthTokenSecret(value);
}
}
handler.onSuccess(twitterOauth);
} else {
handler.onError(error);
}
}
}
@@ -0,0 +1,88 @@
package io.lbry.browser.tasks.verification;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Base64;
import com.google.api.client.auth.oauth.OAuthHmacSigner;
import com.google.api.client.auth.oauth.OAuthParameters;
import com.google.api.client.http.GenericUrl;
import java.nio.charset.StandardCharsets;
import io.lbry.browser.VerificationActivity;
import io.lbry.browser.model.TwitterOauth;
import io.lbry.browser.tasks.TwitterOauthHandler;
import io.lbry.browser.utils.Helper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class TwitterRequestTokenTask extends AsyncTask<Void, Void, String> {
private static final String ENDPOINT = "https://api.twitter.com/oauth/request_token";
private String consumerKey;
private String consumerSecret;
private Exception error;
private TwitterOauthHandler handler;
public TwitterRequestTokenTask(String consumerKey, String consumerSecret, TwitterOauthHandler handler) {
this.consumerKey = consumerKey;
this.consumerSecret = consumerSecret;
this.handler = handler;
}
public String doInBackground(Void... params) {
try {
OAuthHmacSigner signer = new OAuthHmacSigner();
signer.clientSharedSecret = new String(
Base64.decode(consumerSecret, Base64.NO_WRAP), StandardCharsets.UTF_8.name());
OAuthParameters oauthParams = new OAuthParameters();
oauthParams.callback = "https://lbry.tv";
oauthParams.consumerKey = new String(
Base64.decode(consumerKey, Base64.NO_WRAP), StandardCharsets.UTF_8.name());;
oauthParams.signatureMethod = "HMAC-SHA-1";
oauthParams.signer = signer;
oauthParams.computeNonce();
oauthParams.computeTimestamp();
oauthParams.computeSignature("POST", new GenericUrl(ENDPOINT));
RequestBody body = RequestBody.create(new byte[0]);
Request request = new Request.Builder().url(ENDPOINT).addHeader(
"Authorization", oauthParams.getAuthorizationHeader()).post(body).build();
OkHttpClient client = new OkHttpClient.Builder().build();
Response response = client.newCall(request).execute();
return response.body().string();
} catch (Exception ex) {
error = ex;
return null;
}
}
protected void onPostExecute(String response) {
if (!Helper.isNullOrEmpty(response)) {
String[] pairs = response.split("&");
TwitterOauth twitterOauth = new TwitterOauth();
for (String pair : pairs) {
String[] parts = pair.split("=");
if (parts.length != 2) {
continue;
}
String key = parts[0];
String value = parts[1];
if ("oauth_token".equalsIgnoreCase(key)) {
twitterOauth.setOauthToken(value);
} else if ("oauth_token_secret".equalsIgnoreCase(key)) {
twitterOauth.setOauthTokenSecret(value);
}
}
handler.onSuccess(twitterOauth);
} else {
handler.onError(error);
}
}
}
@@ -18,6 +18,7 @@ import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.model.Tag;
import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryUri;
@@ -69,6 +70,8 @@ public class LoadSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
value.has("subscriptions") && !value.isNull("subscriptions") ? value.getJSONArray("subscriptions") : null;
JSONArray tags =
value.has("tags") && !value.isNull("tags") ? value.getJSONArray("tags") : null;
JSONArray following =
value.has("following") && !value.isNull("following") ? value.getJSONArray("following") : null;
if (subscriptionUrls != null) {
subscriptions = new ArrayList<>();
@@ -78,7 +81,8 @@ public class LoadSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
LbryUri uri = LbryUri.parse(LbryUri.normalize(url));
Subscription subscription = new Subscription();
subscription.setChannelName(uri.getChannelName());
subscription.setUrl(url);
subscription.setUrl(uri.toString());
subscription.setNotificationsDisabled(isNotificationsDisabledForSubUrl(uri.toString(), following));
subscriptions.add(subscription);
if (db != null) {
DatabaseHelper.createOrUpdateSubscription(subscription, db);
@@ -91,7 +95,11 @@ public class LoadSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
if (tags != null) {
if (db != null && tags.length() > 0) {
DatabaseHelper.setAllTagsUnfollowed(db);
try {
DatabaseHelper.setAllTagsUnfollowed(db);
} catch (IllegalStateException ex) {
// pass
}
}
followedTags = new ArrayList<>();
@@ -105,7 +113,7 @@ public class LoadSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
if (db != null) {
DatabaseHelper.createOrUpdateTag(tag, db);
}
} catch (SQLiteException ex) {
} catch (SQLiteException | IllegalStateException ex) {
// pass
}
}
@@ -121,6 +129,28 @@ public class LoadSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
return false;
}
protected boolean isNotificationsDisabledForSubUrl(String url, JSONArray following) {
if (following == null) {
return true;
}
try {
for (int i = 0; i < following.length(); i++) {
JSONObject item = following.getJSONObject(i);
String itemUrl = Helper.getJSONString("url", null, item);
boolean notificationsDisabled = Helper.getJSONBoolean("notificationsDisabled", true, item);
if (url.equalsIgnoreCase(itemUrl)) {
return notificationsDisabled;
}
}
} catch (JSONException ex) {
// pass
}
// always default notifications disabled to true
return true;
}
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
@@ -2,6 +2,7 @@ package io.lbry.browser.tasks.wallet;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@@ -11,9 +12,11 @@ import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.model.lbryinc.Subscription;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Lbryio;
/*
@@ -40,9 +43,16 @@ public class SaveSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
// data to save
// current subscriptions
List<Subscription> subs = new ArrayList<>(Lbryio.subscriptions);
List<String> subscriptionUrls = new ArrayList<>();
for (Subscription subscription : Lbryio.subscriptions) {
subscriptionUrls.add(subscription.getUrl());
try {
for (Subscription subscription : subs) {
LbryUri uri = LbryUri.parse(LbryUri.normalize(subscription.getUrl()));
subscriptionUrls.add(uri.toString());
}
} catch (LbryUriException ex) {
error = ex;
return false;
}
// followed tags
@@ -62,6 +72,7 @@ public class SaveSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
JSONObject value = shared.getJSONObject("value");
value.put("subscriptions", Helper.jsonArrayFromList(subscriptionUrls));
value.put("tags", Helper.jsonArrayFromList(followedTags));
value.put("following", buildUpdatedNotificationsDisabledStates(subs));
sharedObject = shared;
}
}
@@ -71,6 +82,7 @@ public class SaveSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
JSONObject value = new JSONObject();
value.put("subscriptions", Helper.jsonArrayFromList(subscriptionUrls));
value.put("tags", Helper.jsonArrayFromList(followedTags));
value.put("following", buildUpdatedNotificationsDisabledStates(subs));
sharedObject = new JSONObject();
sharedObject.put("type", "object");
@@ -91,6 +103,26 @@ public class SaveSharedUserStateTask extends AsyncTask<Void, Void, Boolean> {
return false;
}
private static JSONArray buildUpdatedNotificationsDisabledStates(List<Subscription> subscriptions) {
JSONArray states = new JSONArray();
for (Subscription subscription : subscriptions) {
if (!Helper.isNullOrEmpty(subscription.getUrl())) {
try {
JSONObject item = new JSONObject();
LbryUri uri = LbryUri.parse(LbryUri.normalize(subscription.getUrl()));
item.put("uri", uri.toString());
item.put("notificationsDisabled", subscription.isNotificationsDisabled());
states.put(item);
} catch (JSONException | LbryUriException ex) {
// pass
}
}
}
return states;
}
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
@@ -17,14 +17,16 @@ import io.lbry.browser.utils.Lbry;
public class SupportCreateTask extends AsyncTask<Void, Void, Boolean> {
private String claimId;
private String channelId;
private BigDecimal amount;
private boolean tip;
private View progressView;
private GenericTaskHandler handler;
private Exception error;
public SupportCreateTask(String claimId, BigDecimal amount, boolean tip, View progressView, GenericTaskHandler handler) {
public SupportCreateTask(String claimId, String channelId, BigDecimal amount, boolean tip, View progressView, GenericTaskHandler handler) {
this.claimId = claimId;
this.channelId = channelId;
this.amount = amount;
this.tip = tip;
this.progressView = progressView;
@@ -40,9 +42,13 @@ public class SupportCreateTask extends AsyncTask<Void, Void, Boolean> {
protected Boolean doInBackground(Void... params) {
try {
Map<String, Object> options = new HashMap<>();
options.put("blocking", true);
options.put("claim_id", claimId);
options.put("amount", new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US)).format(amount.doubleValue()));
options.put("tip", tip);
if (!Helper.isNullOrEmpty(channelId)) {
options.put("channel_id", channelId);
}
Lbry.genericApiCall(Lbry.METHOD_SUPPORT_CREATE, options);
} catch (ApiCallException ex) {
error = ex;
@@ -107,7 +107,7 @@ public class SyncGetTask extends AsyncTask<Void, Void, WalletSync> {
if (applySyncChanges) {
if (applySyncSuccessful) {
handler.onSyncApplySuccess(syncHash, syncData);
} else {
} else if (syncApplyError != null) {
handler.onSyncApplyError(syncApplyError);
}
}
@@ -0,0 +1,73 @@
package io.lbry.browser.tasks.wallet;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.lbry.browser.exceptions.ApiCallException;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
public class UnlockTipsTask extends AsyncTask<Void, Void, Boolean> {
private GenericTaskHandler handler;
private Exception error;
public UnlockTipsTask(GenericTaskHandler handler) {
this.handler = handler;
}
public Boolean doInBackground(Void... params) {
List<String> txids = new ArrayList<>();
try {
Map<String, Object> options = new HashMap<>();
options.put("type", "support");
options.put("is_not_my_input", true);
options.put("is_my_output", true);
JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_TXO_LIST, options);
if (result.has("items") && !result.isNull("items")) {
JSONArray items = result.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
JSONObject item = items.getJSONObject(i);
String txid = Helper.getJSONString("txid", null, item);
if (!Helper.isNullOrEmpty(txid)) {
txids.add(txid);
}
}
}
if (txids.size() > 0) {
options = new HashMap<>();
options.put("txid", txids);
options.put("blocking", true);
Lbry.genericApiCall(Lbry.METHOD_TXO_SPEND, options);
}
return true;
} catch (ApiCallException | ClassCastException | JSONException ex) {
error = ex;
return false;
}
}
protected void onPostExecute(Boolean result) {
if (handler != null) {
if (result) {
handler.onSuccess();
} else {
handler.onError(error);
}
}
}
}
@@ -20,19 +20,10 @@ public class WalletBalanceTask extends AsyncTask<Void, Void, WalletBalance> {
}
protected WalletBalance doInBackground(Void... params) {
WalletBalance balance = new WalletBalance();
WalletBalance balance;
try {
JSONObject json = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_WALLET_BALANCE);
JSONObject reservedSubtotals = Helper.getJSONObject("reserved_subtotals", json);
balance.setAvailable(new BigDecimal(Helper.getJSONString("available", "0", json)));
balance.setReserved(new BigDecimal(Helper.getJSONString("reserved", "0", json)));
balance.setTotal(new BigDecimal(Helper.getJSONString("total", "0", json)));
if (reservedSubtotals != null) {
balance.setClaims(new BigDecimal(Helper.getJSONString("claims", "0", reservedSubtotals)));
balance.setSupports(new BigDecimal(Helper.getJSONString("supports", "0", reservedSubtotals)));
balance.setTips(new BigDecimal(Helper.getJSONString("tips", "0", reservedSubtotals)));
}
balance = WalletBalance.fromJSONObject(json);
} catch (ApiCallException | ClassCastException ex) {
error = ex;
return null;
@@ -33,6 +33,7 @@ public class WalletSendTask extends AsyncTask<Void, Void, Boolean> {
Map<String, Object> options = new HashMap<>();
options.put("addresses", Arrays.asList(recipientAddress));
options.put("amount", amount);
options.put("blocking", true);
Lbry.genericApiCall(Lbry.METHOD_WALLET_SEND, options);
} catch (ApiCallException ex) {
error = ex;
@@ -1,12 +1,36 @@
package io.lbry.browser.ui;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.fragment.app.Fragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.util.Map;
import io.lbry.browser.BuildConfig;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.claim.ChannelCreateUpdateTask;
import io.lbry.browser.tasks.claim.ClaimResultHandler;
import io.lbry.browser.tasks.lbryinc.LogPublishTask;
import io.lbry.browser.ui.wallet.RewardsFragment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.LbryUri;
import lombok.Getter;
import lombok.Setter;
@@ -14,6 +38,7 @@ public class BaseFragment extends Fragment {
@Getter
@Setter
private Map<String, Object> params;
private boolean rewardDriverClickListenerSet;
public boolean shouldHideGlobalPlayer() {
return false;
@@ -40,6 +65,15 @@ public class BaseFragment extends Fragment {
MainActivity.resumeGlobalPlayer(context);
}
}
if (params != null && params.containsKey("source") && "notification".equalsIgnoreCase(params.get("source").toString())) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).navigateBackToNotifications();
}
}
rewardDriverClickListenerSet = false;
super.onStop();
}
@@ -57,4 +91,160 @@ public class BaseFragment extends Fragment {
}
}
}
public void checkRewardsDriverCard(String rewardDriverText, double minCost) {
View root = getView();
if (root != null) {
View rewardDriverCard = root.findViewById(R.id.reward_driver_card);
if (rewardDriverCard != null) {
if (!rewardDriverClickListenerSet) {
rewardDriverCard.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).openRewards();
}
}
});
rewardDriverClickListenerSet = true;
}
// only apply to fragments that have the card present
((TextView) rewardDriverCard.findViewById(R.id.reward_driver_text)).setText(rewardDriverText);
boolean showRewardsDriver = Lbry.walletBalance == null ||
minCost == 0 && Lbry.walletBalance.getAvailable().doubleValue() == 0 |
Lbry.walletBalance.getAvailable().doubleValue() < Math.max(minCost, Helper.MIN_DEPOSIT);
rewardDriverCard.setVisibility(showRewardsDriver ? View.VISIBLE : View.GONE);
}
}
}
public void showError(String message) {
Context context = getContext();
if (context != null) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
}
public void setupInlineChannelCreator(
View container,
TextInputEditText inputChannelName,
TextInputEditText inputDeposit,
View inlineBalanceView,
TextView inlineBalanceValue,
View linkCancel,
MaterialButton buttonCreate,
View progressView,
AppCompatSpinner channelSpinner,
InlineChannelSpinnerAdapter channelSpinnerAdapter) {
inputDeposit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
Helper.setViewVisibility(inlineBalanceView, hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
linkCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Helper.setViewText(inputChannelName, null);
Helper.setViewText(inputDeposit, null);
Helper.setViewVisibility(container, View.GONE);
}
});
buttonCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// validate deposit and channel name
String channelNameString = Helper.normalizeChannelName(Helper.getValue(inputChannelName.getText()));
Claim claimToSave = new Claim();
claimToSave.setName(channelNameString);
String channelName = claimToSave.getName().startsWith("@") ? claimToSave.getName().substring(1) : claimToSave.getName();
String depositString = Helper.getValue(inputDeposit.getText());
if ("@".equals(channelName) || Helper.isNullOrEmpty(channelName)) {
showError(getString(R.string.please_enter_channel_name));
return;
}
if (!LbryUri.isNameValid(channelName)) {
showError(getString(R.string.channel_name_invalid_characters));
return;
}
if (Helper.channelExists(channelName)) {
showError(getString(R.string.channel_name_already_created));
return;
}
double depositAmount = 0;
try {
depositAmount = Double.valueOf(depositString);
} catch (NumberFormatException ex) {
// pass
showError(getString(R.string.please_enter_valid_deposit));
return;
}
if (depositAmount == 0) {
String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(error);
return;
}
if (Lbry.walletBalance == null || Lbry.walletBalance.getAvailable().doubleValue() < depositAmount) {
showError(getString(R.string.deposit_more_than_balance));
return;
}
ChannelCreateUpdateTask task = new ChannelCreateUpdateTask(
claimToSave, new BigDecimal(depositString), false, progressView, new ClaimResultHandler() {
@Override
public void beforeStart() {
Helper.setViewEnabled(inputChannelName, false);
Helper.setViewEnabled(inputDeposit, false);
Helper.setViewEnabled(buttonCreate, false);
Helper.setViewEnabled(linkCancel, false);
}
@Override
public void onSuccess(Claim claimResult) {
if (!BuildConfig.DEBUG) {
LogPublishTask logPublishTask = new LogPublishTask(claimResult);
logPublishTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
// channel created
Bundle bundle = new Bundle();
bundle.putString("claim_id", claimResult.getClaimId());
bundle.putString("claim_name", claimResult.getName());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_CHANNEL_CREATE, bundle);
// add the claim to the channel list and set it as the selected item
if (channelSpinnerAdapter != null) {
channelSpinnerAdapter.add(claimResult);
}
if (channelSpinner != null && channelSpinnerAdapter != null) {
channelSpinner.setSelection(channelSpinnerAdapter.getCount() - 1);
}
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
}
@Override
public void onError(Exception error) {
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
showError(error.getMessage());
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
Helper.setViewText(inlineBalanceValue, Helper.shortCurrencyFormat(Lbry.walletBalance.getAvailable().doubleValue()));
}
}
@@ -0,0 +1,701 @@
package io.lbry.browser.ui.channel;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatSpinner;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputEditText;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import io.lbry.browser.BuildConfig;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.adapter.ClaimListAdapter;
import io.lbry.browser.adapter.CommentListAdapter;
import io.lbry.browser.adapter.InlineChannelSpinnerAdapter;
import io.lbry.browser.listener.SdkStatusListener;
import io.lbry.browser.listener.WalletBalanceListener;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.Comment;
import io.lbry.browser.model.WalletBalance;
import io.lbry.browser.tasks.CommentCreateTask;
import io.lbry.browser.tasks.CommentListHandler;
import io.lbry.browser.tasks.CommentListTask;
import io.lbry.browser.tasks.claim.ChannelCreateUpdateTask;
import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ClaimListTask;
import io.lbry.browser.tasks.claim.ClaimResultHandler;
import io.lbry.browser.tasks.claim.ResolveTask;
import io.lbry.browser.tasks.lbryinc.LogPublishTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.LbryUri;
import lombok.Setter;
public class ChannelCommentsFragment extends Fragment implements SdkStatusListener, WalletBalanceListener {
@Setter
private Claim claim;
@Setter
private String commentHash;
private CommentListAdapter commentListAdapter;
private Comment replyToComment;
private View containerReplyToComment;
private TextView textReplyingTo;
private TextView textReplyToBody;
private View buttonClearReplyToComment;
private boolean postingComment;
private boolean fetchingChannels;
private View progressLoadingChannels;
private View progressPostComment;
private InlineChannelSpinnerAdapter commentChannelSpinnerAdapter;
private AppCompatSpinner commentChannelSpinner;
private TextInputEditText inputComment;
private TextView textCommentLimit;
private MaterialButton buttonPostComment;
private ImageView commentPostAsThumbnail;
private View commentPostAsNoThumbnail;
private TextView commentPostAsAlpha;
private View inlineChannelCreator;
private TextInputEditText inlineChannelCreatorInputName;
private TextInputEditText inlineChannelCreatorInputDeposit;
private View inlineChannelCreatorInlineBalance;
private TextView inlineChannelCreatorInlineBalanceValue;
private View inlineChannelCreatorCancelLink;
private View inlineChannelCreatorProgress;
private MaterialButton inlineChannelCreatorCreateButton;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_channel_comments, container, false);
containerReplyToComment = root.findViewById(R.id.comment_form_reply_to_container);
textReplyingTo = root.findViewById(R.id.comment_form_replying_to_text);
textReplyToBody = root.findViewById(R.id.comment_form_reply_to_body);
buttonClearReplyToComment = root.findViewById(R.id.comment_form_clear_reply_to);
commentChannelSpinner = root.findViewById(R.id.comment_form_channel_spinner);
progressLoadingChannels = root.findViewById(R.id.comment_form_channels_loading);
progressPostComment = root.findViewById(R.id.comment_form_post_progress);
inputComment = root.findViewById(R.id.comment_form_body);
textCommentLimit = root.findViewById(R.id.comment_form_text_limit);
buttonPostComment = root.findViewById(R.id.comment_form_post);
commentPostAsThumbnail = root.findViewById(R.id.comment_form_thumbnail);
commentPostAsNoThumbnail = root.findViewById(R.id.comment_form_no_thumbnail);
commentPostAsAlpha = root.findViewById(R.id.comment_form_thumbnail_alpha);
inlineChannelCreator = root.findViewById(R.id.container_inline_channel_form_create);
inlineChannelCreatorInputName = root.findViewById(R.id.inline_channel_form_input_name);
inlineChannelCreatorInputDeposit = root.findViewById(R.id.inline_channel_form_input_deposit);
inlineChannelCreatorInlineBalance = root.findViewById(R.id.inline_channel_form_inline_balance_container);
inlineChannelCreatorInlineBalanceValue = root.findViewById(R.id.inline_channel_form_inline_balance_value);
inlineChannelCreatorProgress = root.findViewById(R.id.inline_channel_form_create_progress);
inlineChannelCreatorCancelLink = root.findViewById(R.id.inline_channel_form_cancel_link);
inlineChannelCreatorCreateButton = root.findViewById(R.id.inline_channel_form_create_button);
RecyclerView commentList = root.findViewById(R.id.channel_comments_list);
commentList.setLayoutManager(new LinearLayoutManager(getContext()));
initCommentForm(root);
setupInlineChannelCreator(
inlineChannelCreator,
inlineChannelCreatorInputName,
inlineChannelCreatorInputDeposit,
inlineChannelCreatorInlineBalance,
inlineChannelCreatorInlineBalanceValue,
inlineChannelCreatorCancelLink,
inlineChannelCreatorCreateButton,
inlineChannelCreatorProgress,
commentChannelSpinner,
commentChannelSpinnerAdapter
);
return root;
}
public void onResume() {
super.onResume();
Context context = getContext();
if (!Lbry.SDK_READY) {
if (context instanceof MainActivity) {
((MainActivity) context).addSdkStatusListener(this);
}
} else {
onSdkReady();
}
if (context instanceof MainActivity) {
((MainActivity) context).addWalletBalanceListener(this);
}
checkAndLoadComments();
}
public void onStop() {
super.onStop();
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.removeSdkStatusListener(this);
activity.removeWalletBalanceListener(this);
}
}
private void checkCommentSdkInitializing() {
View root = getView();
if (root != null) {
TextView commentsSDKInitializing = root.findViewById(R.id.channel_comments_sdk_initializing);
Helper.setViewVisibility(commentsSDKInitializing, Lbry.SDK_READY ? View.GONE : View.VISIBLE);
}
}
@Override
public void onSdkReady() {
fetchChannels();
}
private void checkAndLoadComments() {
View root = getView();
if (root != null) {
RecyclerView commentsList = root.findViewById(R.id.channel_comments_list);
if (commentsList == null || commentsList.getAdapter() == null || commentsList.getAdapter().getItemCount() == 0) {
loadComments();
}
}
}
private void loadComments() {
View root = getView();
ProgressBar relatedLoading = root.findViewById(R.id.channel_comments_progress);
if (claim != null && root != null) {
CommentListTask task = new CommentListTask(1, 200, claim.getClaimId(), relatedLoading, new CommentListHandler() {
@Override
public void onSuccess(List<Comment> comments, boolean hasReachedEnd) {
Context ctx = getContext();
View root = getView();
if (ctx != null && root != null) {
commentListAdapter = new CommentListAdapter(comments, ctx);
commentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
if (!Helper.isNullOrEmpty(claim.getName()) &&
claim.getName().startsWith("@") &&
ctx instanceof MainActivity) {
((MainActivity) ctx).openChannelClaim(claim);
}
}
});
commentListAdapter.setReplyListener(new CommentListAdapter.ReplyClickListener() {
@Override
public void onReplyClicked(Comment comment) {
setReplyToComment(comment);
}
});
RecyclerView relatedContentList = root.findViewById(R.id.channel_comments_list);
relatedContentList.setAdapter(commentListAdapter);
commentListAdapter.notifyDataSetChanged();
checkNoComments();
resolveCommentPosters();
scrollToCommentHash();
}
}
@Override
public void onError(Exception error) {
// pass
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private void scrollToCommentHash() {
View root = getView();
// check for the position of commentHash if set
if (root != null && !Helper.isNullOrEmpty(commentHash) && commentListAdapter != null && commentListAdapter.getItemCount() > 0) {
RecyclerView commentList = root.findViewById(R.id.channel_comments_list);
int position = commentListAdapter.getPositionForComment(commentHash);
if (position > -1 && commentList.getLayoutManager() != null) {
NestedScrollView scrollView = root.findViewById(R.id.channel_comments_area);
scrollView.requestChildFocus(commentList, commentList);
commentList.getLayoutManager().scrollToPosition(position);
}
}
}
private void resolveCommentPosters() {
if (commentListAdapter != null) {
List<String> urlsToResolve = new ArrayList<>(commentListAdapter.getClaimUrlsToResolve());
if (urlsToResolve.size() > 0) {
ResolveTask task = new ResolveTask(urlsToResolve, Lbry.SDK_CONNECTION_STRING, null, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
if (commentListAdapter != null) {
for (Claim claim : claims) {
if (claim.getClaimId() != null) {
commentListAdapter.updatePosterForComment(claim.getClaimId(), claim);
}
}
commentListAdapter.notifyDataSetChanged();
}
}
@Override
public void onError(Exception error) {
// pass
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
}
@Override
public void onWalletBalanceUpdated(WalletBalance walletBalance) {
if (walletBalance != null && inlineChannelCreatorInlineBalanceValue != null) {
inlineChannelCreatorInlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void fetchChannels() {
if (Lbry.ownChannels != null && Lbry.ownChannels.size() > 0) {
updateChannelList(Lbry.ownChannels);
return;
}
fetchingChannels = true;
disableChannelSpinner();
ClaimListTask task = new ClaimListTask(Claim.TYPE_CHANNEL, progressLoadingChannels, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = new ArrayList<>(claims);
updateChannelList(Lbry.ownChannels);
enableChannelSpinner();
fetchingChannels = false;
}
@Override
public void onError(Exception error) {
enableChannelSpinner();
fetchingChannels = false;
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void disableChannelSpinner() {
Helper.setViewEnabled(commentChannelSpinner, false);
hideInlineChannelCreator();
}
private void enableChannelSpinner() {
Helper.setViewEnabled(commentChannelSpinner, true);
if (commentChannelSpinner != null) {
Claim selectedClaim = (Claim) commentChannelSpinner.getSelectedItem();
if (selectedClaim != null) {
if (selectedClaim.isPlaceholder()) {
showInlineChannelCreator();
} else {
hideInlineChannelCreator();
}
}
}
}
private void showInlineChannelCreator() {
Helper.setViewVisibility(inlineChannelCreator, View.VISIBLE);
}
private void hideInlineChannelCreator() {
Helper.setViewVisibility(inlineChannelCreator, View.GONE);
}
private void updateChannelList(List<Claim> channels) {
if (commentChannelSpinnerAdapter == null) {
Context context = getContext();
if (context != null) {
commentChannelSpinnerAdapter = new InlineChannelSpinnerAdapter(context, R.layout.spinner_item_channel, new ArrayList<>(channels));
commentChannelSpinnerAdapter.addPlaceholder(false);
commentChannelSpinnerAdapter.notifyDataSetChanged();
}
} else {
commentChannelSpinnerAdapter.clear();
commentChannelSpinnerAdapter.addAll(channels);
commentChannelSpinnerAdapter.addPlaceholder(false);
commentChannelSpinnerAdapter.notifyDataSetChanged();
}
if (commentChannelSpinner != null) {
commentChannelSpinner.setAdapter(commentChannelSpinnerAdapter);
}
if (commentChannelSpinnerAdapter != null && commentChannelSpinner != null) {
if (commentChannelSpinnerAdapter.getCount() > 1) {
commentChannelSpinner.setSelection(1);
}
}
}
private void initCommentForm(View root) {
textCommentLimit.setText(String.format("%d / %d", Helper.getValue(inputComment.getText()).length(), Comment.MAX_LENGTH));
buttonClearReplyToComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
clearReplyToComment();
}
});
buttonPostComment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!Lbry.SDK_READY) {
Snackbar.make(root.findViewById(R.id.channel_comments_area), R.string.sdk_initializing_functionality, Snackbar.LENGTH_LONG).show();
return;
}
validateAndCheckPostComment();
}
});
inputComment.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
int len = charSequence.length();
textCommentLimit.setText(String.format("%d / %d", len, Comment.MAX_LENGTH));
}
@Override
public void afterTextChanged(Editable editable) {
}
});
commentChannelSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
Object item = adapterView.getItemAtPosition(position);
if (item instanceof Claim) {
Claim claim = (Claim) item;
if (claim.isPlaceholder()) {
if (!fetchingChannels) {
showInlineChannelCreator();
}
} else {
hideInlineChannelCreator();
updatePostAsChannel(claim);
}
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void validateAndCheckPostComment() {
String comment = Helper.getValue(inputComment.getText());
Claim channel = (Claim) commentChannelSpinner.getSelectedItem();
if (Helper.isNullOrEmpty(comment)) {
showError(getString(R.string.please_enter_comment));
return;
}
if (channel == null || Helper.isNullOrEmpty(channel.getClaimId())) {
showError(getString(R.string.please_select_channel));
return;
}
postComment();
}
private void updatePostAsChannel(Claim channel) {
boolean hasThumbnail = !Helper.isNullOrEmpty(channel.getThumbnailUrl());
Helper.setViewVisibility(commentPostAsThumbnail, hasThumbnail ? View.VISIBLE : View.INVISIBLE);
Helper.setViewVisibility(commentPostAsNoThumbnail, !hasThumbnail ? View.VISIBLE : View.INVISIBLE);
Helper.setViewText(commentPostAsAlpha, channel.getName() != null ? channel.getName().substring(1, 2).toUpperCase() : null);
Context context = getContext();
int bgColor = Helper.generateRandomColorForValue(channel.getClaimId());
Helper.setIconViewBackgroundColor(commentPostAsNoThumbnail, bgColor, false, context);
if (hasThumbnail && context != null) {
Glide.with(context.getApplicationContext()).
asBitmap().
load(channel.getThumbnailUrl()).
apply(RequestOptions.circleCropTransform()).
into(commentPostAsThumbnail);
}
}
private void beforePostComment() {
postingComment = true;
Helper.setViewEnabled(commentChannelSpinner, false);
Helper.setViewEnabled(inputComment, false);
Helper.setViewEnabled(buttonClearReplyToComment, false);
Helper.setViewEnabled(buttonPostComment, false);
}
private void afterPostComment() {
Helper.setViewEnabled(commentChannelSpinner, true);
Helper.setViewEnabled(inputComment, true);
Helper.setViewEnabled(buttonClearReplyToComment, true);
Helper.setViewEnabled(buttonPostComment, true);
postingComment = false;
}
private Comment buildPostComment() {
Comment comment = new Comment();
Claim channel = (Claim) commentChannelSpinner.getSelectedItem();
comment.setClaimId(claim.getClaimId());
comment.setChannelId(channel.getClaimId());
comment.setChannelName(channel.getName());
comment.setText(Helper.getValue(inputComment.getText()));
comment.setPoster(channel);
if (replyToComment != null) {
comment.setParentId(replyToComment.getId());
}
return comment;
}
private void setReplyToComment(Comment comment) {
replyToComment = comment;
Helper.setViewText(textReplyingTo, getString(R.string.replying_to, comment.getChannelName()));
Helper.setViewText(textReplyToBody, comment.getText());
Helper.setViewVisibility(containerReplyToComment, View.VISIBLE);
inputComment.requestFocus();
Context context = getContext();
if (context != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(inputComment, InputMethodManager.SHOW_FORCED);
}
}
private void clearReplyToComment() {
Helper.setViewText(textReplyingTo, null);
Helper.setViewText(textReplyToBody, null);
Helper.setViewVisibility(containerReplyToComment, View.GONE);
replyToComment = null;
}
private void postComment() {
if (postingComment) {
return;
}
Comment comment = buildPostComment();
beforePostComment();
CommentCreateTask task = new CommentCreateTask(comment, progressPostComment, new CommentCreateTask.CommentCreateWithTipHandler() {
@Override
public void onSuccess(Comment createdComment) {
inputComment.setText(null);
clearReplyToComment();
if (commentListAdapter != null) {
createdComment.setPoster(comment.getPoster());
if (!Helper.isNullOrEmpty(createdComment.getParentId())) {
commentListAdapter.addReply(createdComment);
} else {
commentListAdapter.insert(0, createdComment);
}
}
afterPostComment();
checkNoComments();
Bundle bundle = new Bundle();
bundle.putString("claim_id", claim != null ? claim.getClaimId() : null);
bundle.putString("claim_name", claim != null ? claim.getName() : null);
LbryAnalytics.logEvent(LbryAnalytics.EVENT_COMMENT_CREATE, bundle);
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).showMessage(R.string.comment_posted);
}
}
@Override
public void onError(Exception error) {
try {
showError(error != null ? error.getMessage() : getString(R.string.comment_error));
} catch (IllegalStateException ex) {
// pass
}
afterPostComment();
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void showError(String message) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).showError(message);
}
}
private void checkNoComments() {
View root = getView();
if (root != null) {
Helper.setViewVisibility(root.findViewById(R.id.channel_no_comments),
commentListAdapter == null || commentListAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
}
}
private void setupInlineChannelCreator(
View container,
TextInputEditText inputChannelName,
TextInputEditText inputDeposit,
View inlineBalanceView,
TextView inlineBalanceValue,
View linkCancel,
MaterialButton buttonCreate,
View progressView,
AppCompatSpinner channelSpinner,
InlineChannelSpinnerAdapter channelSpinnerAdapter) {
inputDeposit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
Helper.setViewVisibility(inlineBalanceView, hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
linkCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Helper.setViewText(inputChannelName, null);
Helper.setViewText(inputDeposit, null);
Helper.setViewVisibility(container, View.GONE);
}
});
buttonCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// validate deposit and channel name
String channelNameString = Helper.normalizeChannelName(Helper.getValue(inputChannelName.getText()));
Claim claimToSave = new Claim();
claimToSave.setName(channelNameString);
String channelName = claimToSave.getName().startsWith("@") ? claimToSave.getName().substring(1) : claimToSave.getName();
String depositString = Helper.getValue(inputDeposit.getText());
if ("@".equals(channelName) || Helper.isNullOrEmpty(channelName)) {
showError(getString(R.string.please_enter_channel_name));
return;
}
if (!LbryUri.isNameValid(channelName)) {
showError(getString(R.string.channel_name_invalid_characters));
return;
}
if (Helper.channelExists(channelName)) {
showError(getString(R.string.channel_name_already_created));
return;
}
double depositAmount = 0;
try {
depositAmount = Double.valueOf(depositString);
} catch (NumberFormatException ex) {
// pass
showError(getString(R.string.please_enter_valid_deposit));
return;
}
if (depositAmount == 0) {
String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(error);
return;
}
if (Lbry.walletBalance == null || Lbry.walletBalance.getAvailable().doubleValue() < depositAmount) {
showError(getString(R.string.deposit_more_than_balance));
return;
}
ChannelCreateUpdateTask task = new ChannelCreateUpdateTask(
claimToSave, new BigDecimal(depositString), false, progressView, new ClaimResultHandler() {
@Override
public void beforeStart() {
Helper.setViewEnabled(inputChannelName, false);
Helper.setViewEnabled(inputDeposit, false);
Helper.setViewEnabled(buttonCreate, false);
Helper.setViewEnabled(linkCancel, false);
}
@Override
public void onSuccess(Claim claimResult) {
if (!BuildConfig.DEBUG) {
LogPublishTask logPublishTask = new LogPublishTask(claimResult);
logPublishTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
// channel created
Bundle bundle = new Bundle();
bundle.putString("claim_id", claimResult.getClaimId());
bundle.putString("claim_name", claimResult.getName());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_CHANNEL_CREATE, bundle);
// add the claim to the channel list and set it as the selected item
if (channelSpinnerAdapter != null) {
channelSpinnerAdapter.add(claimResult);
}
if (channelSpinner != null && channelSpinnerAdapter != null) {
channelSpinner.setSelection(channelSpinnerAdapter.getCount() - 1);
}
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
}
@Override
public void onError(Exception error) {
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
showError(error.getMessage());
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
Helper.setViewText(inlineBalanceValue, Helper.shortCurrencyFormat(Lbry.walletBalance.getAvailable().doubleValue()));
}
}
@@ -20,6 +20,7 @@ import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -64,7 +65,7 @@ public class ChannelContentFragment extends Fragment implements DownloadActionLi
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_channel_content, container, false);
currentSortBy = ContentSortDialogFragment.ITEM_SORT_BY_TRENDING;
currentSortBy = ContentSortDialogFragment.ITEM_SORT_BY_NEW;
currentContentFrom = ContentFromDialogFragment.ITEM_FROM_PAST_WEEK;
sortLink = root.findViewById(R.id.channel_content_sort_link);
@@ -219,20 +220,22 @@ public class ChannelContentFragment extends Fragment implements DownloadActionLi
}
return Lbry.buildClaimSearchOptions(
null,
(List) null,
null,
canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),
Arrays.asList(channelId),
!Helper.isNullOrEmpty(channelId) ? Arrays.asList(channelId) : null,
null,
getContentSortOrder(),
contentReleaseTime,
0,
0,
currentClaimSearchPage == 0 ? 1 : currentClaimSearchPage,
Helper.CONTENT_PAGE_SIZE);
}
private List<String> getContentSortOrder() {
if (contentSortOrder == null) {
return Arrays.asList(Claim.ORDER_BY_RELEASE_TIME);
return Collections.singletonList(Claim.ORDER_BY_RELEASE_TIME);
}
return contentSortOrder;
}
@@ -258,22 +261,25 @@ public class ChannelContentFragment extends Fragment implements DownloadActionLi
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (contentListAdapter == null) {
contentListAdapter = new ClaimListAdapter(claims, getContext());
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
// channel claim
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
Context context = getContext();
if (context != null) {
contentListAdapter = new ClaimListAdapter(claims, context);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
// channel claim
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
}
}
}
});
});
}
} else {
contentListAdapter.addItems(claims);
}
@@ -140,7 +140,6 @@ public class ChannelFormFragment extends BaseFragment implements
Context context = getContext();
FlexboxLayoutManager flm1 = new FlexboxLayoutManager(context);
FlexboxLayoutManager flm2 = new FlexboxLayoutManager(context);
FlexboxLayoutManager flm3 = new FlexboxLayoutManager(context);
addedTagsList = root.findViewById(R.id.form_added_tags);
addedTagsList.setLayoutManager(flm1);
suggestedTagsList = root.findViewById(R.id.form_suggested_tags);
@@ -211,7 +210,7 @@ public class ChannelFormFragment extends BaseFragment implements
@Override
public void onClick(View view) {
if (uploading) {
Snackbar.make(getView(), R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
Snackbar.make(view, R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
return;
}
@@ -222,6 +221,11 @@ public class ChannelFormFragment extends BaseFragment implements
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (uploading) {
Snackbar.make(view, R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
return;
}
Claim claimToSave = buildChannelClaimToSave();
validateAndSaveClaim(claimToSave);
}
@@ -249,7 +253,13 @@ public class ChannelFormFragment extends BaseFragment implements
private void checkParams() {
Map<String, Object> params = getParams();
if (params.containsKey("claim")) {
if (params == null) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).onBackPressed();
return;
}
} else if (params.containsKey("claim")) {
Claim claim = (Claim) params.get("claim");
if (claim != null && !claim.equals(this.currentClaim)) {
this.currentClaim = claim;
@@ -315,7 +325,7 @@ public class ChannelFormFragment extends BaseFragment implements
showError(getString(R.string.please_enter_valid_deposit));
return;
}
if (depositAmount == 0) {
if (depositAmount < Helper.MIN_DEPOSIT) {
String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(error);
return;
@@ -366,13 +376,6 @@ public class ChannelFormFragment extends BaseFragment implements
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void showError(String message) {
Context context = getContext();
if (context != null) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
}
public void checkPermissionsAndLaunchFilePicker(boolean isCover) {
Context context = getContext();
if (MainActivity.hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, context)) {
@@ -503,10 +506,8 @@ public class ChannelFormFragment extends BaseFragment implements
activity.addFilePickerListener(this);
activity.addWalletBalanceListener(this);
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(editMode ? R.string.edit_channel : R.string.create_a_channel);
}
activity.setActionBarTitle(editMode ? R.string.edit_channel : R.string.create_a_channel);
}
}
@@ -536,6 +537,7 @@ public class ChannelFormFragment extends BaseFragment implements
public void onResume() {
super.onResume();
checkParams();
checkRewardsDriver();
updateFieldsFromCurrentClaim();
Context context = getContext();
@@ -544,10 +546,7 @@ public class ChannelFormFragment extends BaseFragment implements
LbryAnalytics.setCurrentScreen(activity, "Channel Form", "ChannelForm");
activity.addStoragePermissionListener(this);
if (editMode) {
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.edit_channel);
}
activity.setActionBarTitle(R.string.edit_channel);
}
}
String filterText = Helper.getValue(inputTagFilter.getText());
@@ -591,6 +590,7 @@ public class ChannelFormFragment extends BaseFragment implements
if (walletBalance != null && inlineBalanceValue != null) {
inlineBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
checkRewardsDriver();
}
public void setFilter(String filter) {
@@ -694,4 +694,13 @@ public class ChannelFormFragment extends BaseFragment implements
removeTag(tag);
}
}
private void checkRewardsDriver() {
Context ctx = getContext();
if (ctx != null) {
String rewardsDriverText = String.format("%s\n%s",
getString(R.string.channel_creation_requires_credits), getString(R.string.tap_here_to_get_some));
checkRewardsDriverCard(rewardsDriverText, Helper.MIN_DEPOSIT);
}
}
}
@@ -6,16 +6,15 @@ import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.viewpager2.adapter.FragmentStateAdapter;
@@ -36,7 +35,7 @@ import java.util.Map;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.dialog.SendTipDialogFragment;
import io.lbry.browser.dialog.CreateSupportDialogFragment;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.listener.FetchChannelsListener;
import io.lbry.browser.model.Claim;
@@ -50,6 +49,7 @@ import io.lbry.browser.tasks.claim.ClaimListResultHandler;
import io.lbry.browser.tasks.claim.ResolveTask;
import io.lbry.browser.tasks.lbryinc.FetchStatCountTask;
import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.ui.controls.OutlineIconView;
import io.lbry.browser.ui.controls.SolidIconView;
import io.lbry.browser.ui.findcontent.FollowingFragment;
import io.lbry.browser.utils.Helper;
@@ -62,7 +62,7 @@ import lombok.SneakyThrows;
public class ChannelFragment extends BaseFragment implements FetchChannelsListener {
private Claim claim;
private boolean subscribing;
private String url;
private String currentUrl;
private View layoutResolving;
private View layoutDisplayArea;
@@ -80,11 +80,18 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private View buttonShare;
private View buttonTip;
private View buttonFollowUnfollow;
private View buttonBell;
private SolidIconView iconBell;
private int subCount;
private SolidIconView iconFollowUnfollow;
private TextView textFollow;
private OutlineIconView iconFollow;
private SolidIconView iconUnfollow;
private View layoutNothingAtLocation;
private View layoutLoadingState;
// if this is set, scroll to the specific comment on load
private String commentHash;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_channel, container, false);
@@ -106,7 +113,11 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
buttonShare = root.findViewById(R.id.channel_view_share);
buttonTip = root.findViewById(R.id.channel_view_tip);
buttonFollowUnfollow = root.findViewById(R.id.channel_view_follow_unfollow);
iconFollowUnfollow = root.findViewById(R.id.channel_view_icon_follow_unfollow);
textFollow = root.findViewById(R.id.channel_view_text_follow);
iconFollow = root.findViewById(R.id.channel_view_icon_follow);
iconUnfollow = root.findViewById(R.id.channel_view_icon_unfollow);
buttonBell = root.findViewById(R.id.channel_view_subscribe_notify);
iconBell = root.findViewById(R.id.channel_view_icon_bell);
tabPager = root.findViewById(R.id.channel_view_pager);
tabLayout = root.findViewById(R.id.channel_view_tabs);
@@ -174,26 +185,65 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
}
if (claim != null) {
SendTipDialogFragment dialog = SendTipDialogFragment.newInstance();
CreateSupportDialogFragment dialog = CreateSupportDialogFragment.newInstance();
dialog.setClaim(claim);
dialog.setListener(new SendTipDialogFragment.SendTipListener() {
dialog.setListener(new CreateSupportDialogFragment.CreateSupportListener() {
@Override
public void onTipSent(BigDecimal amount) {
public void onSupportCreated(BigDecimal amount, boolean isTip) {
double sentAmount = amount.doubleValue();
String message = getResources().getQuantityString(
R.plurals.you_sent_a_tip, sentAmount == 1.0 ? 1 : 2,
new DecimalFormat("#,###.##").format(sentAmount));
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).show();
View view = getView();
if (view != null) {
String message = getResources().getQuantityString(
isTip ? R.plurals.you_sent_a_tip : R.plurals.you_sent_a_support, sentAmount == 1.0 ? 1 : 2,
new DecimalFormat("#,###.##").format(sentAmount));
Snackbar.make(view, message, Snackbar.LENGTH_LONG).show();
}
}
});
Context context = getContext();
if (context instanceof MainActivity) {
dialog.show(((MainActivity) context).getSupportFragmentManager(), SendTipDialogFragment.TAG);
dialog.show(((MainActivity) context).getSupportFragmentManager(), CreateSupportDialogFragment.TAG);
}
}
}
});
buttonBell.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (claim != null) {
boolean isNotificationsDisabled = Lbryio.isNotificationsDisabled(claim);
final Subscription subscription = Subscription.fromClaim(claim);
subscription.setNotificationsDisabled(!isNotificationsDisabled);
view.setEnabled(false);
Context context = getContext();
new ChannelSubscribeTask(context, claim.getClaimId(), subscription, false, new ChannelSubscribeTask.ChannelSubscribeHandler() {
@Override
public void onSuccess() {
view.setEnabled(true);
Lbryio.updateSubscriptionNotificationsDisabled(subscription);
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).showMessage(subscription.isNotificationsDisabled() ?
R.string.receive_no_notifications : R.string.receive_all_notifications);
}
checkIsFollowing();
if (context != null) {
context.sendBroadcast(new Intent(MainActivity.ACTION_SAVE_SHARED_USER_STATE));
}
}
@Override
public void onError(Exception exception) {
view.setEnabled(true);
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
});
buttonFollowUnfollow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
@@ -202,39 +252,22 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
return;
}
subscribing = true;
boolean isFollowing = Lbryio.isFollowing(claim);
Subscription subscription = Subscription.fromClaim(claim);
buttonFollowUnfollow.setEnabled(false);
new ChannelSubscribeTask(getContext(), claim.getClaimId(), subscription, isFollowing, new ChannelSubscribeTask.ChannelSubscribeHandler() {
@Override
public void onSuccess() {
if (isFollowing) {
Lbryio.removeSubscription(subscription);
Lbryio.removeCachedResolvedSubscription(claim);
} else {
Lbryio.addSubscription(subscription);
Lbryio.addCachedResolvedSubscription(claim);
}
buttonFollowUnfollow.setEnabled(true);
subscribing = false;
checkIsFollowing();
FollowingFragment.resetClaimSearchContent = true;
if (Lbry.SDK_READY) {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).saveSharedUserState();
}
}
}
@Override
public void onError(Exception exception) {
buttonFollowUnfollow.setEnabled(true);
subscribing = false;
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
if (isFollowing) {
Context context = getContext();
AlertDialog.Builder builder = new AlertDialog.Builder(context).
setTitle(R.string.confirm_unfollow).
setMessage(R.string.confirm_unfollow_message)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
doFollowUnfollow(isFollowing, view);
}
}).setNegativeButton(R.string.no, null);
builder.show();
} else {
doFollowUnfollow(isFollowing, view);
}
}
}
});
@@ -242,6 +275,39 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
return root;
}
private void doFollowUnfollow(boolean isFollowing, View view) {
subscribing = true;
Subscription subscription = Subscription.fromClaim(claim);
view.setEnabled(false);
new ChannelSubscribeTask(getContext(), claim.getClaimId(), subscription, isFollowing, new ChannelSubscribeTask.ChannelSubscribeHandler() {
@Override
public void onSuccess() {
if (isFollowing) {
Lbryio.removeSubscription(subscription);
Lbryio.removeCachedResolvedSubscription(claim);
} else {
Lbryio.addSubscription(subscription);
Lbryio.addCachedResolvedSubscription(claim);
}
buttonFollowUnfollow.setEnabled(true);
subscribing = false;
checkIsFollowing();
FollowingFragment.resetClaimSearchContent = true;
Context context = getContext();
if (context != null) {
context.sendBroadcast(new Intent(MainActivity.ACTION_SAVE_SHARED_USER_STATE));
}
}
@Override
public void onError(Exception exception) {
buttonFollowUnfollow.setEnabled(true);
subscribing = false;
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void deleteCurrentClaim() {
if (claim != null) {
Helper.setViewVisibility(layoutDisplayArea, View.GONE);
@@ -258,7 +324,7 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
} else {
View root = getView();
if (root != null) {
Snackbar.make(root, R.string.channel_failed_delete, Toast.LENGTH_LONG).
Snackbar.make(root, R.string.channel_failed_delete, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
}
@@ -272,12 +338,14 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private void checkIsFollowing() {
if (claim != null) {
boolean isFollowing = Lbryio.isFollowing(claim);
if (iconFollowUnfollow != null) {
iconFollowUnfollow.setText(isFollowing ? R.string.fa_heart_broken : R.string.fa_heart);
Context context = getContext();
if (context != null) {
iconFollowUnfollow.setTextColor(ContextCompat.getColor(context, isFollowing ? R.color.foreground : R.color.red));
}
boolean notificationsDisabled = Lbryio.isNotificationsDisabled(claim);
Helper.setViewVisibility(iconFollow, !isFollowing ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(textFollow, !isFollowing ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(iconUnfollow, isFollowing ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(buttonBell, isFollowing ? View.VISIBLE : View.GONE);
if (iconBell != null) {
iconBell.setText(notificationsDisabled ? R.string.fa_bell : R.string.fa_bell_slash);
}
}
}
@@ -321,29 +389,49 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private void checkParams() {
boolean updateRequired = false;
Map<String, Object> params = getParams();
if (params.containsKey("claim")) {
Claim claim = (Claim) params.get("claim");
if (claim != null && !claim.equals(this.claim)) {
this.claim = claim;
updateRequired = true;
String newUrl = null;
if (params != null) {
if (params.containsKey("claim")) {
Claim claim = (Claim) params.get("claim");
if (claim != null && !claim.equals(this.claim)) {
this.claim = claim;
updateRequired = true;
}
}
}
if (params.containsKey("url")) {
String newUrl = params.get("url").toString();
if (claim == null || !newUrl.equalsIgnoreCase(url)) {
this.claim = null;
this.url = newUrl;
updateRequired = true;
if (params.containsKey("url")) {
LbryUri newLbryUri = LbryUri.tryParse(params.get("url").toString());
if (newLbryUri != null) {
newUrl = newLbryUri.toString();
String qs = newLbryUri.getQueryString();
if (!Helper.isNullOrEmpty(qs)) {
String[] qsPairs = qs.split("&");
for (String pair : qsPairs) {
String[] parts = pair.split("=");
if (parts.length < 2) {
continue;
}
if ("comment_hash".equalsIgnoreCase(parts[0])) {
commentHash = parts[1];
break;
}
}
}
if (claim == null || !newUrl.equalsIgnoreCase(currentUrl)) {
this.claim = null;
this.currentUrl = newUrl;
updateRequired = true;
}
}
}
}
if (updateRequired) {
resetSubCount();
if (!Helper.isNullOrEmpty(url)) {
if (!Helper.isNullOrEmpty(currentUrl)) {
// check if the claim is already cached
ClaimCacheKey key = new ClaimCacheKey();
key.setUrl(url);
key.setUrl(currentUrl);
if (Lbry.claimCache.containsKey(key)) {
claim = Lbry.claimCache.get(key);
} else {
@@ -355,8 +443,8 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
}
}
if (!Helper.isNullOrEmpty(url)) {
Helper.saveUrlHistory(url, claim != null ? claim.getTitle() : null, UrlSuggestion.TYPE_CHANNEL);
if (!Helper.isNullOrEmpty(currentUrl)) {
Helper.saveUrlHistory(currentUrl, claim != null ? claim.getTitle() : null, UrlSuggestion.TYPE_CHANNEL);
}
if (claim != null) {
@@ -367,13 +455,13 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private void resolveUrl() {
Helper.setViewVisibility(layoutDisplayArea, View.INVISIBLE);
Helper.setViewVisibility(layoutLoadingState, View.VISIBLE);
ResolveTask task = new ResolveTask(url, Lbry.LBRY_TV_CONNECTION_STRING, layoutResolving, new ClaimListResultHandler() {
ResolveTask task = new ResolveTask(currentUrl, Lbry.LBRY_TV_CONNECTION_STRING, layoutResolving, new ClaimListResultHandler() {
@Override
public void onSuccess(List<Claim> claims) {
if (claims.size() > 0 && !Helper.isNullOrEmpty(claims.get(0).getClaimId())) {
claim = claims.get(0);
if (!Helper.isNullOrEmpty(url)) {
Helper.saveUrlHistory(url, claim.getTitle(), UrlSuggestion.TYPE_CHANNEL);
if (!Helper.isNullOrEmpty(currentUrl)) {
Helper.saveUrlHistory(currentUrl, claim.getTitle(), UrlSuggestion.TYPE_CHANNEL);
}
renderClaim();
@@ -439,18 +527,31 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
try {
if (tabPager.getAdapter() == null && context instanceof MainActivity) {
tabPager.setAdapter(new ChannelPagerAdapter(claim, (MainActivity) context));
tabPager.setAdapter(new ChannelPagerAdapter(claim, commentHash, (MainActivity) context));
if (!Helper.isNullOrEmpty(commentHash)) {
// set the Comments tab active if a comment hash is set
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
tabPager.setCurrentItem(2);
}
}, 500);
}
}
new TabLayoutMediator(tabLayout, tabPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
switch (position) {
case 0: tab.setText(R.string.content); break;
case 1: tab.setText(R.string.about); break;
case 2: tab.setText(R.string.comments); break;
}
}
}).attach();
} catch (IllegalStateException ex) {
// TODO: Fix why this is happening
// pass
}
new TabLayoutMediator(tabLayout, tabPager, new TabLayoutMediator.TabConfigurationStrategy() {
@Override
public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
tab.setText(position == 0 ? R.string.content : R.string.about);
}
}).attach();
}
private void resetSubCount() {
@@ -485,9 +586,11 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
private static class ChannelPagerAdapter extends FragmentStateAdapter {
private Claim channelClaim;
public ChannelPagerAdapter(Claim channelClaim, FragmentActivity activity) {
private String commentHash;
public ChannelPagerAdapter(Claim channelClaim, String commentHash, FragmentActivity activity) {
super(activity);
this.channelClaim = channelClaim;
this.commentHash = commentHash;
}
@SneakyThrows
@@ -514,6 +617,16 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
// pass
}
return aboutFragment;
case 2:
ChannelCommentsFragment commentsFragment = ChannelCommentsFragment.class.newInstance();
if (channelClaim != null) {
commentsFragment.setClaim(channelClaim);
}
if (!Helper.isNullOrEmpty(commentHash)) {
commentsFragment.setCommentHash(commentHash);
}
return commentsFragment;
}
return null;
@@ -525,7 +638,7 @@ public class ChannelFragment extends BaseFragment implements FetchChannelsListen
@Override
public int getItemCount() {
return 2;
return 3;
}
}
}
@@ -149,21 +149,23 @@ public class ChannelManagerFragment extends BaseFragment implements ActionMode.C
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownChannels = Helper.filterDeletedClaims(new ArrayList<>(claims));
Context context = getContext();
if (adapter == null) {
adapter = new ClaimListAdapter(claims, context);
adapter.setCanEnterSelectionMode(true);
adapter.setSelectionModeListener(ChannelManagerFragment.this);
adapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
if (context instanceof MainActivity) {
((MainActivity) context).openChannelClaim(claim);
Context context = getContext();
if (context != null) {
adapter = new ClaimListAdapter(claims, context);
adapter.setCanEnterSelectionMode(true);
adapter.setSelectionModeListener(ChannelManagerFragment.this);
adapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
if (context instanceof MainActivity) {
((MainActivity) context).openChannelClaim(claim);
}
}
});
if (channelList != null) {
channelList.setAdapter(adapter);
}
});
if (channelList != null) {
channelList.setAdapter(adapter);
}
} else {
adapter.setItems(claims);
@@ -0,0 +1,29 @@
package io.lbry.browser.ui.controls;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.Gravity;
import androidx.appcompat.widget.AppCompatTextView;
public class OutlineIconView extends AppCompatTextView {
private Context context;
public OutlineIconView(Context context) {
super(context);
this.context = context;
init();
}
public OutlineIconView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
init();
}
private void init() {
setGravity(Gravity.CENTER);
setTypeface(Typeface.createFromAsset(context.getAssets(), "font_awesome_5_free_regular.otf"));
}
}
@@ -407,13 +407,15 @@ public class AllContentFragment extends BaseFragment implements DownloadActionLi
}
return Lbry.buildClaimSearchOptions(
null,
(List) null,
(currentContentScope == ContentScopeDialogFragment.ITEM_EVERYONE) ? null : tags,
canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),
null,
null,
getContentSortOrder(),
contentReleaseTime,
0,
0,
currentClaimSearchPage == 0 ? 1 : currentClaimSearchPage,
Helper.CONTENT_PAGE_SIZE);
}
@@ -446,22 +448,25 @@ public class AllContentFragment extends BaseFragment implements DownloadActionLi
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (contentListAdapter == null) {
contentListAdapter = new ClaimListAdapter(claims, getContext());
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
// channel claim
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
Context context = getContext();
if (context != null) {
contentListAdapter = new ClaimListAdapter(claims, context);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
// channel claim
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
}
}
}
});
});
}
} else {
contentListAdapter.addItems(claims);
}
@@ -32,6 +32,7 @@ import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.Predefined;
public class EditorsChoiceFragment extends BaseFragment {
@@ -72,7 +73,7 @@ public class EditorsChoiceFragment extends BaseFragment {
return Lbry.buildClaimSearchOptions(
Claim.TYPE_REPOST,
null,
null, /*canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),*/
canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),
new ArrayList<>(titleChannelIdsMap.values()),
null,
Arrays.asList(Claim.ORDER_BY_RELEASE_TIME),
File diff suppressed because it is too large. Load diff
@@ -248,6 +248,8 @@ public class FollowingFragment extends BaseFragment implements
discoverLink.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Helper.setViewEnabled(discoverLink, false);
buildChannelIdsAndUrls();
currentSuggestedPage = 1;
discoverDialog = DiscoverDialogFragment.newInstance();
@@ -268,6 +270,7 @@ public class FollowingFragment extends BaseFragment implements
if (suggestedChannelAdapter != null) {
suggestedChannelAdapter.clearItems();
}
Helper.setViewEnabled(discoverLink, true);
}
@Override
public void onResume() {
@@ -424,13 +427,15 @@ public class FollowingFragment extends BaseFragment implements
}
return Lbry.buildClaimSearchOptions(
Claim.TYPE_STREAM,
Arrays.asList(Claim.TYPE_STREAM, Claim.TYPE_REPOST),
null,
canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),
getChannelIds(),
null,
getContentSortOrder(),
contentReleaseTime,
0,
0,
currentClaimSearchPage == 0 ? 1 : currentClaimSearchPage,
Helper.CONTENT_PAGE_SIZE);
}
@@ -438,7 +443,7 @@ public class FollowingFragment extends BaseFragment implements
private List<String> getChannelIds() {
if (channelFilterListAdapter != null) {
Claim selected = channelFilterListAdapter.getSelectedItem();
if (selected != null) {
if (selected != null && !Helper.isNullOrEmpty(selected.getClaimId())) {
return Arrays.asList(selected.getClaimId());
}
}
@@ -487,6 +492,11 @@ public class FollowingFragment extends BaseFragment implements
String url = subscription.getUrl();
LbryUri uri = LbryUri.parse(url);
String claimId = uri.getClaimId();
if (Helper.isNullOrEmpty(claimId) || Helper.isNullOrEmpty(url)) {
// don't add null / empty claim IDs or URLs
continue;
}
channelIds.add(claimId);
channelUrls.add(url);
} catch (LbryUriException ex) {
@@ -524,8 +534,9 @@ public class FollowingFragment extends BaseFragment implements
}
private void updateChannelFilterListAdapter(List<Claim> resolvedSubs, boolean reset) {
if (channelFilterListAdapter == null) {
channelFilterListAdapter = new ChannelFilterListAdapter(getContext());
Context context = getContext();
if (channelFilterListAdapter == null && context != null) {
channelFilterListAdapter = new ChannelFilterListAdapter(context);
channelFilterListAdapter.setListener(new ChannelItemSelectionListener() {
@Override
public void onChannelItemSelected(Claim claim) {
@@ -560,14 +571,16 @@ public class FollowingFragment extends BaseFragment implements
});
}
if (horizontalChannelList != null && horizontalChannelList.getAdapter() == null) {
horizontalChannelList.setAdapter(channelFilterListAdapter);
if (channelFilterListAdapter != null) {
if (horizontalChannelList != null && horizontalChannelList.getAdapter() == null) {
horizontalChannelList.setAdapter(channelFilterListAdapter);
}
if (reset) {
channelFilterListAdapter.clearClaims();
channelFilterListAdapter.setSelectedItem(null);
}
channelFilterListAdapter.addClaims(resolvedSubs);
}
if (reset) {
channelFilterListAdapter.clearClaims();
channelFilterListAdapter.setSelectedItem(null);
}
channelFilterListAdapter.addClaims(resolvedSubs);
}
private void fetchClaimSearchContent() {
@@ -587,22 +600,25 @@ public class FollowingFragment extends BaseFragment implements
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (contentListAdapter == null) {
contentListAdapter = new ClaimListAdapter(claims, getContext());
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
// channel claim
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
Context context = getContext();
if (context != null) {
contentListAdapter = new ClaimListAdapter(claims, context);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
// channel claim
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
}
}
}
});
});
}
} else {
contentListAdapter.addItems(claims);
}
@@ -626,11 +642,12 @@ public class FollowingFragment extends BaseFragment implements
}
private void updateSuggestedDoneButtonText() {
int selected = suggestedChannelAdapter == null ? 0 : suggestedChannelAdapter.getSelectedCount();
int remaining = MIN_SUGGESTED_SUBSCRIBE_COUNT - selected;
String buttonText = remaining <= 0 ? getString(R.string.done) : getString(R.string.n_remaining, remaining);
if (suggestedDoneButton != null) {
suggestedDoneButton.setText(buttonText);
Context context = getContext();
if (context != null) {
int selected = suggestedChannelAdapter == null ? 0 : suggestedChannelAdapter.getSelectedCount();
int remaining = MIN_SUGGESTED_SUBSCRIBE_COUNT - selected;
String buttonText = remaining <= 0 ? getString(R.string.done) : getString(R.string.n_remaining, remaining);
Helper.setViewText(suggestedDoneButton, buttonText);
}
}
@@ -192,7 +192,7 @@ public class SearchFragment extends BaseFragment implements
}
if (resolved.isMature() && !canShowMatureContent) {
resultListAdapter.removeFeaturedItem();
} else {
} else if (unresolved != null) {
// only set the values we need
unresolved.setClaimId(resolved.getClaimId());
unresolved.setName(resolved.getName());
@@ -201,6 +201,7 @@ public class SearchFragment extends BaseFragment implements
unresolved.setPermanentUrl(resolved.getPermanentUrl());
unresolved.setValue(resolved.getValue());
unresolved.setSigningChannel(resolved.getSigningChannel());
unresolved.setRepostedClaim(resolved.getRepostedClaim());
unresolved.setUnresolved(false);
unresolved.setConfirmations(resolved.getConfirmations());
}
@@ -239,31 +240,36 @@ public class SearchFragment extends BaseFragment implements
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
contentHasReachedEnd = hasReachedEnd;
searchLoading = false;
if (resultListAdapter == null) {
resultListAdapter = new ClaimListAdapter(claims, getContext());
resultListAdapter.addFeaturedItem(buildFeaturedItem(query));
resolveFeaturedItem(buildVanityUrl(query));
resultListAdapter.setListener(SearchFragment.this);
if (resultList != null) {
resultList.setAdapter(resultListAdapter);
Context context = getContext();
if (context != null) {
if (resultListAdapter == null) {
resultListAdapter = new ClaimListAdapter(claims, context);
resultListAdapter.addFeaturedItem(buildFeaturedItem(query));
resolveFeaturedItem(buildVanityUrl(query));
resultListAdapter.setListener(SearchFragment.this);
if (resultList != null) {
resultList.setAdapter(resultListAdapter);
}
} else {
resultListAdapter.addItems(claims);
}
} else {
resultListAdapter.addItems(claims);
}
int itemCount = resultListAdapter.getItemCount();
noQueryView.setVisibility(View.GONE);
noResultsView.setVisibility(itemCount == 0 ? View.VISIBLE : View.GONE);
noResultsView.setText(getString(R.string.search_no_results, currentQuery));
int itemCount = resultListAdapter.getItemCount();
Helper.setViewVisibility(noQueryView, View.GONE);
Helper.setViewVisibility(noResultsView, itemCount == 0 ? View.VISIBLE : View.GONE);
Helper.setViewText(noResultsView, getString(R.string.search_no_results, currentQuery));
}
}
@Override
public void onError(Exception error) {
Context context = getContext();
int itemCount = resultListAdapter == null ? 0 : resultListAdapter.getItemCount();
noQueryView.setVisibility(View.GONE);
noResultsView.setVisibility(itemCount == 0 ? View.VISIBLE : View.GONE);
noResultsView.setText(getString(R.string.search_no_results, currentQuery));
Helper.setViewVisibility(noQueryView, View.GONE);
Helper.setViewVisibility(noResultsView, itemCount == 0 ? View.VISIBLE : View.GONE);
if (context != null) {
Helper.setViewText(noResultsView, getString(R.string.search_no_results, currentQuery));
}
searchLoading = false;
}
});
@@ -0,0 +1,835 @@
package io.lbry.browser.ui.findcontent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.PlaybackParameters;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.audio.AudioAttributes;
import com.google.android.exoplayer2.database.ExoDatabaseProvider;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.cache.CacheDataSourceFactory;
import com.google.android.exoplayer2.upstream.cache.LeastRecentlyUsedCacheEvictor;
import com.google.android.exoplayer2.upstream.cache.SimpleCache;
import com.google.android.exoplayer2.util.Util;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import io.lbry.browser.MainActivity;
import io.lbry.browser.R;
import io.lbry.browser.data.DatabaseHelper;
import io.lbry.browser.exceptions.LbryUriException;
import io.lbry.browser.model.Claim;
import io.lbry.browser.model.lbryinc.Reward;
import io.lbry.browser.tasks.BufferEventTask;
import io.lbry.browser.tasks.GenericTaskHandler;
import io.lbry.browser.tasks.claim.ClaimSearchResultHandler;
import io.lbry.browser.tasks.claim.ClaimSearchTask;
import io.lbry.browser.tasks.lbryinc.ClaimRewardTask;
import io.lbry.browser.tasks.lbryinc.LogFileViewTask;
import io.lbry.browser.ui.BaseFragment;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbry;
import io.lbry.browser.utils.LbryAnalytics;
import io.lbry.browser.utils.LbryUri;
import io.lbry.browser.utils.Lbryio;
import io.lbry.browser.utils.Predefined;
public class ShuffleFragment extends BaseFragment {
private static final int PAGE_SIZE = 50;
private int currentClaimSearchPage;
private int playlistIndex;
private Claim current;
private List<Claim> playlist;
private List<String> watchedContentClaimIds;
private long sessionStart;
private ProgressBar surfModeLoading;
private TextView textTitle;
private TextView textPublisher;
private Player player;
private long elapsedDuration = 0;
private long totalDuration = 0;
private boolean elapsedPlaybackScheduled;
private ScheduledExecutorService elapsedPlaybackScheduler;
private boolean playbackStarted;
private long startTimeMillis;
private boolean isPlaying;
private boolean newPlayerCreated;
private String currentUrl;
private Player.EventListener playerListener;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_shuffle, container, false);
surfModeLoading = root.findViewById(R.id.shuffle_loading);
textTitle = root.findViewById(R.id.shuffle_content_title);
textPublisher = root.findViewById(R.id.shuffle_content_publisher);
playerListener = new Player.EventListener() {
@Override
public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
if (playbackState == Player.STATE_READY) {
elapsedDuration = MainActivity.appPlayer.getCurrentPosition();
totalDuration = MainActivity.appPlayer.getDuration() < 0 ? 0 : MainActivity.appPlayer.getDuration();
if (!playbackStarted) {
logPlay(currentUrl, startTimeMillis);
playbackStarted = true;
isPlaying = true;
if (current != null) {
saveWatchedContent(current.getClaimId());
}
}
renderTotalDuration();
scheduleElapsedPlayback();
hideBuffering();
} else if (playbackState == Player.STATE_BUFFERING) {
Context ctx = getContext();
boolean sendBufferingEvents = true;
if (ctx != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
sendBufferingEvents = sp.getBoolean(MainActivity.PREFERENCE_KEY_SEND_BUFFERING_EVENTS, true);
}
if (MainActivity.appPlayer != null && MainActivity.appPlayer.getCurrentPosition() > 0 && sendBufferingEvents) {
// we only want to log a buffer event after the media has already started playing
String mediaSourceUrl = getStreamingUrl();
long duration = MainActivity.appPlayer.getDuration();
long position = MainActivity.appPlayer.getCurrentPosition();
String userIdHash = Lbryio.currentUser != null ? String.valueOf(Lbryio.currentUser.getId()) : "0";
if (mediaSourceUrl.startsWith(FileViewFragment.CDN_PREFIX)) {
BufferEventTask bufferEvent = new BufferEventTask(current.getPermanentUrl(), duration, position, 1, userIdHash);
bufferEvent.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
}
showBuffering();
} else if (playbackState == Player.STATE_ENDED) {
playNextClaim();
} else {
hideBuffering();
}
}
};
Context context = getContext();
PlayerView playerView = root.findViewById(R.id.shuffle_exoplayer_view);
playerView.setOnTouchListener(new SwipeListener(playerView, context) {
@Override
public void onSwipeLeft() { playNextClaim(); }
@Override
public void onSwipeRight() { playPreviousClaim(); }
});
root.findViewById(R.id.shuffle_share_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (current != null) {
try {
String shareUrl = LbryUri.parse(
!Helper.isNullOrEmpty(current.getCanonicalUrl()) ? current.getCanonicalUrl() :
(!Helper.isNullOrEmpty(current.getShortUrl()) ? current.getShortUrl() : current.getPermanentUrl())).toTvString();
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, shareUrl);
MainActivity.startingShareActivity = true;
Intent shareUrlIntent = Intent.createChooser(shareIntent, getString(R.string.share_lbry_content));
shareUrlIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(shareUrlIntent);
} catch (LbryUriException ex) {
// pass
}
}
}
});
root.setOnTouchListener(new SwipeListener(root, context) {
@Override
public void onSwipeLeft() { playNextClaim(); }
@Override
public void onSwipeRight() { playPreviousClaim(); }
});
return root;
}
private String getStreamingUrl() {
return current != null ? String.format("https://cdn.lbryplayer.xyz/content/claims/%s/%s/stream", current.getName(), current.getClaimId()) : "";
}
private Map<String, Object> buildContentOptions() {
Context context = getContext();
boolean canShowMatureContent = false;
if (context != null) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
canShowMatureContent = sp.getBoolean(MainActivity.PREFERENCE_KEY_SHOW_MATURE_CONTENT, false);
}
return Lbry.buildClaimSearchOptions(
Claim.TYPE_STREAM,
canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS),
null/*contentChannelIds*/,
Arrays.asList(Claim.ORDER_BY_TRENDING_GROUP),
121, // 2 minutes or less
1,
currentClaimSearchPage == 0 ? 1 : currentClaimSearchPage,
PAGE_SIZE);
}
public void onStart() {
super.onStart();
MainActivity activity = (MainActivity) getContext();
if (activity != null) {
activity.hideFloatingWalletBalance();
}
}
public void onResume() {
super.onResume();
sessionStart = System.currentTimeMillis();
MainActivity activity = (MainActivity) getContext();
if (activity != null) {
LbryAnalytics.setCurrentScreen(activity, "Shuffle", "Shuffle");
}
if (MainActivity.appPlayer != null && MainActivity.nowPlayingSource != MainActivity.SOURCE_NOW_PLAYING_SHUFFLE) {
MainActivity.appPlayer.setPlayWhenReady(false);
}
if (playlist == null) {
loadWatchedContentList();
} else {
if (current != null) {
playbackCurrentClaim();
} else {
startPlaylist();
}
loadAndScheduleDurations();
}
if (MainActivity.appPlayer != null) {
if (MainActivity.playerReassigned) {
setPlayerForPlayerView();
MainActivity.playerReassigned = false;
}
}
}
private void setPlayerForPlayerView() {
View root = getView();
if (root != null) {
PlayerView view = root.findViewById(R.id.shuffle_exoplayer_view);
view.setVisibility(View.VISIBLE);
view.setPlayer(null);
view.setPlayer(MainActivity.appPlayer);
}
}
public void onPause() {
if (MainActivity.appPlayer != null && MainActivity.appPlayer.isPlaying()) {
MainActivity.nowPlayingSource = MainActivity.SOURCE_NOW_PLAYING_SHUFFLE;
}
super.onPause();
}
public void onStop() {
long sessionDuration = System.currentTimeMillis() - sessionStart;
if (sessionStart > 0 && sessionDuration > 0) {
Bundle bundle = new Bundle();
bundle.putLong("duration_ms", sessionDuration);
bundle.putInt("duration", Double.valueOf(Math.ceil(sessionDuration / 1000.0)).intValue());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_SHUFFLE_SESSION, bundle);
}
sessionStart = 0;
MainActivity activity = (MainActivity) getContext();
if (activity != null) {
activity.hideFloatingWalletBalance();
}
super.onStop();
}
private void loadWatchedContentList() {
(new AsyncTask<Void, Void, List<String>>() {
protected List<String> doInBackground(Void... params) {
MainActivity activity = (MainActivity) getContext();
if (activity != null) {
try {
SQLiteDatabase db = activity.getDbHelper().getReadableDatabase();
return DatabaseHelper.getShuffleWatchedClaims(db);
} catch (Exception ex) {
// pass
}
}
return null;
}
protected void onPostExecute(List<String> claimIds) {
watchedContentClaimIds = new ArrayList<>(claimIds);
if (playlist == null) {
loadContent();
}
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void saveWatchedContent(final String claimId) {
(new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
MainActivity activity = (MainActivity) getContext();
if (activity != null) {
try {
SQLiteDatabase db = activity.getDbHelper().getWritableDatabase();
DatabaseHelper.createOrUpdateShuffleWatched(claimId, db);
} catch (Exception ex) {
// pass
}
}
return null;
}
}).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void loadContent() {
if (playlist == null || playlist.size() == 0) {
Helper.setViewVisibility(surfModeLoading, View.VISIBLE);
}
Map<String, Object> claimSearchOptions = buildContentOptions();
ClaimSearchTask task = new ClaimSearchTask(claimSearchOptions, Lbry.LBRY_TV_CONNECTION_STRING, null, new ClaimSearchResultHandler() {
@Override
public void onSuccess(List<Claim> claims, boolean hasReachedEnd) {
if (playlist == null) {
playlist = new ArrayList<>(claims);
startPlaylist();
} else {
for (Claim claim : claims) {
if (!playlist.contains(claim)) {
playlist.add(claim);
}
}
}
Helper.setViewVisibility(surfModeLoading, View.GONE);
}
@Override
public void onError(Exception error) {
Helper.setViewVisibility(surfModeLoading, View.GONE);
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void startPlaylist() {
if (playlist == null || playlist.size() == 0) {
return;
}
playlistIndex = 0;
current = playlist.get(playlistIndex);
checkCurrentClaimIsVideo(false);
checkCurrentClaimWatched(false);
playbackCurrentClaim();
}
private void checkCurrentClaimIsVideo(boolean previous) {
while (current == null || current.getMediaType() == null || !current.getMediaType().startsWith("video")) {
// only play videos
if (previous) {
playlistIndex--;
} else {
playlistIndex++;
checkPlaylistSize();
}
current = playlist.get(playlistIndex);
}
}
private void checkCurrentClaimWatched(boolean previous) {
if (current != null && watchedContentClaimIds != null) {
while (watchedContentClaimIds.contains(current.getClaimId())) {
if (previous) {
playlistIndex--;
} else {
playlistIndex++;
checkPlaylistSize();
}
current = playlist.get(playlistIndex);
}
}
}
private void playPreviousClaim() {
if (playlist == null || playlist.size() == 0) {
return;
}
if (playlistIndex > 0) {
playlistIndex--;
}
current = playlist.get(playlistIndex);
checkCurrentClaimIsVideo(true);
checkCurrentClaimWatched(true);
playbackCurrentClaim();
}
private void playNextClaim() {
if (playlist == null || playlist.size() == 0) {
return;
}
if (playlistIndex < playlist.size() - 1) {
playlistIndex++;
}
checkPlaylistSize();
current = playlist.get(playlistIndex);
checkCurrentClaimIsVideo(false);
checkCurrentClaimWatched(false);
playbackCurrentClaim();
}
private void checkPlaylistSize() {
if (playlist.size() - playlistIndex < 10) {
currentClaimSearchPage++;
loadContent();
}
}
private void playbackCurrentClaim() {
resetPlayer();
String publisherText = !Helper.isNullOrEmpty(current.getPublisherTitle()) ?
String.format("%s (%s)", current.getPublisherTitle(), current.getPublisherName()) :
!Helper.isNullOrEmpty(current.getPublisherName()) ? current.getPublisherName() : getString(R.string.anonymous);
textTitle.setText(current.getTitle());
textPublisher.setText(publisherText);
Context context = getContext();
if (MainActivity.appPlayer == null && context != null) {
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setUsage(C.USAGE_MEDIA)
.setContentType(C.CONTENT_TYPE_MOVIE)
.build();
MainActivity.appPlayer = new SimpleExoPlayer.Builder(context).build();
MainActivity.appPlayer.setWakeMode(C.WAKE_MODE_NETWORK);
MainActivity.appPlayer.setAudioAttributes(audioAttributes, true);
MainActivity.playerCache =
new SimpleCache(context.getCacheDir(),
new LeastRecentlyUsedCacheEvictor(1024 * 1024 * 256), new ExoDatabaseProvider(context));
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.initMediaSession();
activity.initPlaybackNotification();
}
if (playerListener != null) {
MainActivity.appPlayer.addListener(playerListener);
}
newPlayerCreated = true;
}
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.initPlaybackNotification();
}
View root = getView();
if (root != null) {
PlayerView view = root.findViewById(R.id.shuffle_exoplayer_view);
view.setShutterBackgroundColor(Color.TRANSPARENT);
view.setPlayer(MainActivity.appPlayer);
view.setUseController(true);
if (context instanceof MainActivity) {
((MainActivity) context).getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
if (MainActivity.nowPlayingClaim != null &&
MainActivity.nowPlayingClaim.getClaimId().equalsIgnoreCase(current.getClaimId()) &&
!newPlayerCreated) {
// if the claim is already playing, we don't need to reload the media source
return;
}
if (MainActivity.appPlayer != null) {
showBuffering();
if (context instanceof MainActivity) {
((MainActivity) context).setNowPlayingClaim(current, current.getPermanentUrl());
}
MainActivity.appPlayer.setPlayWhenReady(true);
String userAgent = Util.getUserAgent(context, getString(R.string.app_name));
String mediaSourceUrl = getStreamingUrl();
MediaSource mediaSource = new ProgressiveMediaSource.Factory(
new CacheDataSourceFactory(MainActivity.playerCache, new DefaultDataSourceFactory(context, userAgent)),
new DefaultExtractorsFactory()
).setLoadErrorHandlingPolicy(new FileViewFragment.StreamLoadErrorPolicy()).createMediaSource(Uri.parse(mediaSourceUrl));
MainActivity.appPlayer.prepare(mediaSource, true, true);
}
}
}
private void resetPlayer() {
elapsedDuration = 0;
totalDuration = 0;
renderElapsedDuration();
renderTotalDuration();
elapsedPlaybackScheduled = false;
if (elapsedPlaybackScheduler != null) {
elapsedPlaybackScheduler.shutdownNow();
elapsedPlaybackScheduler = null;
}
playbackStarted = false;
startTimeMillis = 0;
/*if (MainActivity.appPlayer != null) {
MainActivity.appPlayer.stop(true);
MainActivity.appPlayer.removeListener(fileViewPlayerListener);
PlaybackParameters params = new PlaybackParameters(1.0f);
MainActivity.appPlayer.setPlaybackParameters(params);
}*/
}
private void logPlay(String url, long startTimeMillis) {
long timeToStartMillis = startTimeMillis > 0 ? System.currentTimeMillis() - startTimeMillis : 0;
Bundle bundle = new Bundle();
bundle.putString("uri", url);
bundle.putLong("time_to_start_ms", timeToStartMillis);
bundle.putLong("time_to_start_seconds", Double.valueOf(timeToStartMillis / 1000.0).longValue());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_PLAY, bundle);
logFileView(current.getPermanentUrl(), timeToStartMillis);
}
private void logFileView(String url, long timeToStart) {
if (current != null) {
LogFileViewTask task = new LogFileViewTask(url, current, timeToStart, new GenericTaskHandler() {
@Override
public void beforeStart() { }
@Override
public void onSuccess() {
claimEligibleRewards();
}
@Override
public void onError(Exception error) { }
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private void showBuffering() {
View root = getView();
if (root != null) {
root.findViewById(R.id.player_buffering_progress).setVisibility(View.VISIBLE);
PlayerView playerView = root.findViewById(R.id.shuffle_exoplayer_view);
playerView.findViewById(R.id.player_skip_back_10).setVisibility(View.INVISIBLE);
playerView.findViewById(R.id.player_skip_forward_10).setVisibility(View.INVISIBLE);
}
}
private void hideBuffering() {
View root = getView();
if (root != null) {
root.findViewById(R.id.player_buffering_progress).setVisibility(View.INVISIBLE);
PlayerView playerView = root.findViewById(R.id.shuffle_exoplayer_view);
playerView.findViewById(R.id.player_skip_back_10).setVisibility(View.VISIBLE);
playerView.findViewById(R.id.player_skip_forward_10).setVisibility(View.VISIBLE);
}
}
private void renderElapsedDuration() {
View view = getView();
if (view != null) {
Helper.setViewText(view.findViewById(R.id.player_duration_elapsed), Helper.formatDuration(Double.valueOf(elapsedDuration / 1000.0).longValue()));
}
}
private void renderTotalDuration() {
View view = getView();
if (view != null) {
Helper.setViewText(view.findViewById(R.id.player_duration_total), Helper.formatDuration(Double.valueOf(totalDuration / 1000.0).longValue()));
}
}
private void loadAndScheduleDurations() {
if (MainActivity.appPlayer != null && playbackStarted) {
elapsedDuration = MainActivity.appPlayer.getCurrentPosition() < 0 ? 0 : MainActivity.appPlayer.getCurrentPosition();
totalDuration = MainActivity.appPlayer.getDuration() < 0 ? 0 : MainActivity.appPlayer.getDuration();
renderElapsedDuration();
renderTotalDuration();
scheduleElapsedPlayback();
}
}
private void scheduleElapsedPlayback() {
if (!elapsedPlaybackScheduled) {
elapsedPlaybackScheduler = Executors.newSingleThreadScheduledExecutor();
elapsedPlaybackScheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).runOnUiThread(new Runnable() {
@Override
public void run() {
if (MainActivity.appPlayer != null) {
elapsedDuration = MainActivity.appPlayer.getCurrentPosition();
int elapsedSeconds = Double.valueOf(elapsedDuration / 1000.0).intValue();
renderElapsedDuration();
}
}
});
}
}
}, 0, 500, TimeUnit.MILLISECONDS);
elapsedPlaybackScheduled = true;
}
}
// TODO: Move this call to MainActivity?
private void claimEligibleRewards() {
// attempt to claim eligible rewards after viewing or playing a file (fail silently)
Context context = getContext();
ClaimRewardTask firstStreamTask = new ClaimRewardTask(Reward.TYPE_FIRST_STREAM, null, null, context, eligibleRewardHandler);
ClaimRewardTask dailyViewTask = new ClaimRewardTask(Reward.TYPE_DAILY_VIEW, null, null, context, eligibleRewardHandler);
firstStreamTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
dailyViewTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private ClaimRewardTask.ClaimRewardHandler eligibleRewardHandler = new ClaimRewardTask.ClaimRewardHandler() {
@Override
public void onSuccess(double amountClaimed, String message) {
if (Helper.isNullOrEmpty(message)) {
message = getResources().getQuantityString(
R.plurals.claim_reward_message,
amountClaimed == 1 ? 1 : 2,
new DecimalFormat(Helper.LBC_CURRENCY_FORMAT_PATTERN).format(amountClaimed));
}
Context context = getContext();
if (context instanceof MainActivity) {
((MainActivity) context).showMessage(message);
}
}
@Override
public void onError(Exception error) {
// pass
}
};
private static class SwipeListener implements View.OnTouchListener {
private final GestureDetector gestureDetector;
private final View control;
public SwipeListener(View control, Context context) {
this.control = control;
gestureDetector = new GestureDetector(context, new SwipeGestureListener());
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
return gestureDetector.onTouchEvent(motionEvent);
}
public void onSwipeLeft() { }
public void onSwipeRight() { }
public void onSwipeTop() { }
public void onSwipeBottom() { }
private final class SwipeGestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
if (control instanceof PlayerView) {
return false;
}
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
result = true;
}
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
result = true;
}
} catch (Exception ex) {
// pass
}
return result;
}
}
}
@Override
public boolean shouldHideGlobalPlayer() {
return true;
}
private static final List<String> contentChannelIds = Arrays.asList(
"3fec094c5937e9eb4e8f5e71e4ca430e8a993d03",
"6184648aab0431c4c95c649072d1f9ff08b9bb7c",
"b5d31cde873073718c033076656a27471e392afc",
"7317cdf6f62be93b22295062e191f6ba59a5db26",
"1cdb5d0bdcb484907d0a2fea4efdfe0153838642",
"b516294f541a18ce00b71a60b2c82ad2f87ff78d",
"91e42cc450075f2c4c245bac7617bf903f16b4ce",
"b6e207c5f8c58e7c8362cd05a1501bf2f5b694f2",
"25f384bd95e218f6ac37fcaca99ed40f36760d8c",
"f33657a2fcbab2dc3ce555d5d6728f8758af7bc7",
"294f5c164da5ac9735658b2d58d8fee6745dfc45",
"119a2e8c0b50f78d3861636d37c3b44ba8e689b5",
"7b23cca3f49059f005e812be03931c81272eaac4",
"fb0efeaa3788d1292bb49a94d77622503fe08129",
"797a528c49b6535560f7fd8222b121b0223287c8",
"bc490776f367b8afccf0ea7349d657431ba1ded6",
"48c7ea8bc2c4adba09bf21a29689e3b8c2967522",
"bf7490f905904e79de5c90e472bb9e6f26e634a0",
"df961194a798cc76306b9290701130c592530fb6",
"cf0be9078d76951e2e228df68b5b0bbf71313aaa",
"d746ac8d782f94d12d176c7a591f5bf8365bef3d",
"1f30267438257020f08abf452746a48e53a71ad5",
"4ad942982e43326c7700b1b6443049b3cfd82161",
"1cdb5d0bdcb484907d0a2fea4efdfe0153838642",
"6616707e1109aaa1c11b9f399f914d0cfb4f5303",
"4ee7cfaf1fc50a6df858ed0b99c278d633bccca9",
"b7d02b4a0036114732c072269adb891dc5e34ca4",
"9c51c1a119137cd17ed5ae09daa80c1cab6ac01d",
"5f2a5c14b971a6f5eed0a67dc7af3a3fe5c0b6a4",
"0e2b5b4cf59e859860000ff123dc12a317ad416b",
"3fe68ad3da93065e35c37b14fbeef88b4b7785ed",
"fd7ffcbafb74412a8812df4720feaf11fe70fe12",
"b4c30fe36b79870a79c55e1e909adb5ad23f323f",
"92c0f2f3239f1f61496997bd2cdc197ec51bd423",
"29193e9240a71a735639c66ee954e68414f11236",
"25f384bd95e218f6ac37fcaca99ed40f36760d8c",
"87b13b074936b1f42a7c6758c7c2995f58c602e7",
"8d935c6c30510e1dfc10f803a9646fa8aa128b07",
"8f4fecfc836ea33798ee3e5cef56926fa54e2cf9",
"9a5dfcb1a4b29c3a1598392d039744b9938b5a26",
"c5724e280283cd985186af9a62494aae377daabd",
"b39833be3032bbe1005f4f719f379a4621faeb13",
"589276465a23c589801d874f484cc39f307d7ec7",
"fb364ef587872515f545a5b4b3182b58073f230f",
"6c0bf1fed2705d675da950a94e4af004ec975a06",
"b924ac36b7499591f7929d9c4903de79b07b1cb9",
"113515e893b8186595595e594ecc410bae50c026",
"72f9815b087b6d346745e3de71a6ce5fe73a8677",
"b0198a465290f065378f3535666bee0653d6a9bb",
"020ebeb40642bfb4bc3d9f6d28c098afc0a47481",
"5c15e604c4207f52c8cf58fe21e63164c230e257",
"273a2fa759f1a9f56b078633ea2f08fc2406002a",
"930fc43ca7bae20d4706543e97175d1872b0671f",
"0cb2ec46f06ba85520a1c1a56706acf35d5176dd",
"057053dfb657aaa98553e2c544b06e1a2371557e",
"64e091964a611a48424d254a3de2b952d0d6565a",
"50ebba2b06908f93d7963b1c6826cc0fd6104477",
"374ff82251a384601da73f30485c3ac8d7f4176b",
"1487afc813124abbeb0629d2172be0f01ccec3bf",
"6a4fa1a68b92336e64006a4310cb160b07854329",
"15f986a262fc6eff5774050c94d174c0533d505d",
"6184648aab0431c4c95c649072d1f9ff08b9bb7c",
"1efa9b640ad980b2ec53834d60e9cff9554979cd",
"064d4999ea15e433e06f16f391922390acab01cb",
"4884e30b93b3c4c123a83154516196095f9e831e",
"2827bfc459c12d7c6d280cbacee750811291d4ba",
"9626816275585ac3443e7cddd1272c8652c23f1d",
"a2e1bb1fed32c6a6290b679785dd31ca5c59cb5f",
"d9535951222dd7a1ff7f763872cb0df44f7962bf",
"243b6f18093ff97c861d0568c7d3379606201a4b",
"1ce5ac7bab7f2e82af02305ced3c095e320b52e5",
"3e63119a8503a6f666b0a736c8fdeb9e79d11eb4",
"e33372c0d8b2cdd3e12252962ee1671d66143075",
"7364ba2ac9090e468855ce9074bb50c306196f4c",
"d6350f9158825662b99e4b5e0442bcc94d39bc11",
"2a294ea41312c6da8de5ebd0f18dbfb2963bb1a4",
"44c49bbab8a3e9999f3ba9dee0186288b1d960a7",
"2305db36455aa0d18571015b9e9bd0950262aa0f",
"82f1d8c257d3e76b711a5cecd1e49bd3fa6a9de9",
"faed2b028a9b5a712d5180eaa6fd2aa619f941bc",
"39ac239b5687f7d1c2ba74cd020b3547545dfdaf",
"5737eb22f6119f27c9afccfe73ba710afd885371",
"5f22b6daf7204d73cf79d3ff0b46fc4fe237c7f7",
"3583f5a570af6870504eea5a5f7afad6e1508508",
"b0e489f986c345aef23c4a48d91cbcf5a6fdb9ac",
"ba79c80788a9e1751e49ad401f5692d86f73a2db",
"c54323436f50c633c870298bb374ac8e7560e6cd",
"83725c7ee23bd4a8ca28a4fab0e313409def1dc7",
"61c4e8636704f2f38bbe88b1f30ef0d74d6c0f49",
"87ef9ba36019f7f3bf217cf47511645893b13f2e",
"1bd0adfcf1c75bafc1ba3fc9b65a1a0470df6a91",
"1be15348c51955179b7bf9aa90230a9425927ef6",
"1f45ab3495df2c3be7d9c882bca9966305115cbb",
"7317777e3751efa66218f6da5ef0d01dda69af48",
"3346a4ff80b70ee7eea8a79fc79f19c43bb4464a",
"452916a904030d2ce4ea2440fad2d0774e7296d9",
"2675ef3adf52ebf8a44ff5da4306c293dfa6f901",
"e2a76643735f8611a561794509c6bb2aac70eb04",
"dc577db3caf5ff83a3b573ba92f2d447f067eee1",
"89c4cf244099918b1d3ed413df27d4216e97b499",
"4b2b5822c8af3074c6ef9b789a8142d0ef623402",
"3c5794f775975669745c412b0c30f48991d9e455",
"1df464dbb302ced815c61431a5548a273e6de8e1"
);
}
@@ -213,6 +213,7 @@ public class LibraryFragment extends BaseFragment implements
super.onResume();
Context context = getContext();
Helper.setWunderbarValue(null, context);
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
LbryAnalytics.setCurrentScreen(activity, "Library", "Library");
@@ -267,6 +268,7 @@ public class LibraryFragment extends BaseFragment implements
checkStatsLink();
layoutSdkInitializing.setVisibility(Lbry.SDK_READY ? View.GONE : View.VISIBLE);
currentPage = 1;
currentFiles = new ArrayList<>();
if (Lbry.SDK_READY) {
if (!initialOwnClaimsFetched) {
fetchOwnClaimsAndShowDownloads();
@@ -312,7 +314,7 @@ public class LibraryFragment extends BaseFragment implements
if (contentListAdapter != null) {
contentListAdapter.setHideFee(true);
contentListAdapter.clearItems();
contentListAdapter.setCanEnterSelectionMode(true);
contentListAdapter.setCanEnterSelectionMode(false);
}
listReachedEnd = false;
@@ -350,24 +352,27 @@ public class LibraryFragment extends BaseFragment implements
}
private void initContentListAdapter(List<Claim> claims) {
contentListAdapter = new ClaimListAdapter(claims, getContext());
contentListAdapter.setCanEnterSelectionMode(true);
contentListAdapter.setSelectionModeListener(this);
contentListAdapter.setHideFee(currentFilter != FILTER_PURCHASES);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) getContext();
if (claim.getName().startsWith("@")) {
activity.openChannelUrl(claim.getPermanentUrl());
} else {
activity.openFileUrl(claim.getPermanentUrl());
Context context = getContext();
if (context != null) {
contentListAdapter = new ClaimListAdapter(claims, context);
contentListAdapter.setCanEnterSelectionMode(currentFilter == FILTER_DOWNLOADS);
contentListAdapter.setSelectionModeListener(this);
contentListAdapter.setHideFee(currentFilter != FILTER_PURCHASES);
contentListAdapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
activity.openChannelUrl(claim.getPermanentUrl());
} else {
activity.openFileUrl(claim.getPermanentUrl());
}
}
}
}
});
});
}
}
private void fetchDownloads() {
@@ -380,7 +385,6 @@ public class LibraryFragment extends BaseFragment implements
listReachedEnd = hasReachedEnd;
List<LbryFile> filteredFiles = Helper.filterDownloads(files);
List<Claim> claims = Helper.claimsFromFiles(filteredFiles);
addFiles(filteredFiles);
updateStats();
checkStatsLink();
@@ -390,7 +394,7 @@ public class LibraryFragment extends BaseFragment implements
} else {
contentListAdapter.addItems(claims);
}
if (contentList.getAdapter() == null) {
if (contentListAdapter != null && contentList.getAdapter() == null) {
contentList.setAdapter(contentListAdapter);
}
resolveMissingChannelNames(buildUrlsToResolve(claims));
@@ -422,7 +426,7 @@ public class LibraryFragment extends BaseFragment implements
} else {
contentListAdapter.addItems(claims);
}
if (contentList.getAdapter() == null) {
if (contentListAdapter != null && contentList.getAdapter() == null) {
contentList.setAdapter(contentListAdapter);
}
checkListEmpty();
@@ -458,7 +462,7 @@ public class LibraryFragment extends BaseFragment implements
} else {
contentListAdapter.addItems(claims);
}
if (contentList.getAdapter() == null) {
if (contentListAdapter != null && contentList.getAdapter() == null) {
contentList.setAdapter(contentListAdapter);
}
checkListEmpty();
@@ -636,18 +640,21 @@ public class LibraryFragment extends BaseFragment implements
public boolean onActionItemClicked(androidx.appcompat.view.ActionMode actionMode, MenuItem menuItem) {
if (R.id.action_delete == menuItem.getItemId()) {
if (contentListAdapter != null && contentListAdapter.getSelectedCount() > 0) {
final List<Claim> selectedClaims = new ArrayList<>(contentListAdapter.getSelectedItems());
String message = getResources().getQuantityString(R.plurals.confirm_delete_files, selectedClaims.size());
AlertDialog.Builder builder = new AlertDialog.Builder(getContext()).
setTitle(R.string.delete_selection).
setMessage(message)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
handleDeleteSelectedClaims(selectedClaims);
}
}).setNegativeButton(R.string.no, null);
builder.show();
Context context = getContext();
if (context != null) {
final List<Claim> selectedClaims = new ArrayList<>(contentListAdapter.getSelectedItems());
String message = getResources().getQuantityString(R.plurals.confirm_delete_files, selectedClaims.size());
AlertDialog.Builder builder = new AlertDialog.Builder(context).
setTitle(R.string.delete_selection).
setMessage(message)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
handleDeleteSelectedClaims(selectedClaims);
}
}).setNegativeButton(R.string.no, null);
builder.show();
}
return true;
}
}
@@ -180,10 +180,7 @@ public class AboutFragment extends BaseFragment implements SdkStatusListener {
activity.lockDrawer();
activity.hideFloatingWalletBalance();
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.about_lbry);
}
activity.setActionBarTitle(R.string.about_lbry);
}
}
@@ -4,9 +4,13 @@ import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.InputType;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.preference.EditTextPreference;
import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager;
@@ -23,6 +27,15 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.settings, rootKey);
PreferenceManager manager = getPreferenceManager();
EditTextPreference miniPlayerBottomMarginPreference = manager.findPreference(MainActivity.PREFERENCE_KEY_MINI_PLAYER_BOTTOM_MARGIN);
miniPlayerBottomMarginPreference.setOnBindEditTextListener(new EditTextPreference.OnBindEditTextListener() {
@Override
public void onBindEditText(@NonNull EditText editText) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
}
});
}
@Override
@@ -35,10 +48,7 @@ public class SettingsFragment extends PreferenceFragmentCompat implements Shared
activity.lockDrawer();
activity.hideFloatingWalletBalance();
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.settings);
}
activity.setActionBarTitle(R.string.settings);
}
}
@@ -102,6 +102,7 @@ public class PublishFormFragment extends BaseFragment implements
private static final int MAX_VIDEO_DIMENSION = 1920;
private static final int MAX_BITRATE = 5000000; // 5mbps
private boolean storageRefusedOnce;
private static final int SUGGESTED_LIMIT = 8;
private boolean editMode;
@@ -256,7 +257,7 @@ public class PublishFormFragment extends BaseFragment implements
suggestedTagsAdapter.setClickListener(this);
suggestedTagsList.setAdapter(suggestedTagsAdapter);
matureTagsAdapter = new TagListAdapter(Helper.getTagObjectsForTags(Predefined.MATURE_TAGS), context);
matureTagsAdapter = new TagListAdapter(Helper.getTagObjectsForTags(Predefined.PUBLISH_MATURE_TAGS), context);
matureTagsAdapter.setCustomizeMode(TagListAdapter.CUSTOMIZE_MODE_ADD);
matureTagsAdapter.setClickListener(this);
matureTagsList.setAdapter(matureTagsAdapter);
@@ -428,10 +429,10 @@ public class PublishFormFragment extends BaseFragment implements
@Override
public void onClick(View view) {
if (uploading) {
Snackbar.make(view, R.string.publish_no_thumbnail, Snackbar.LENGTH_LONG).show();
Snackbar.make(view, R.string.publish_thumbnail_in_progress, Snackbar.LENGTH_LONG).show();
return;
} else if (Helper.isNullOrEmpty(uploadedThumbnailUrl)) {
showError(getString(R.string.publish_thumbnail_in_progress));
showError(getString(R.string.publish_no_thumbnail));
return;
}
@@ -474,6 +475,8 @@ public class PublishFormFragment extends BaseFragment implements
}
});
channelSpinnerAdapter = new InlineChannelSpinnerAdapter(getContext(), R.layout.spinner_item_channel, new ArrayList<>());
channelSpinnerAdapter.addPlaceholder(false);
setupInlineChannelCreator(
inlineChannelCreator,
inlineChannelCreatorInputName,
@@ -482,7 +485,9 @@ public class PublishFormFragment extends BaseFragment implements
inlineChannelCreatorInlineBalanceValue,
inlineChannelCreatorCancelLink,
inlineChannelCreatorCreateButton,
inlineChannelCreatorProgress
inlineChannelCreatorProgress,
channelSpinner,
channelSpinnerAdapter
);
}
@@ -499,10 +504,7 @@ public class PublishFormFragment extends BaseFragment implements
activity.addFilePickerListener(this);
activity.addWalletBalanceListener(this);
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(editMode ? R.string.edit_content : R.string.new_publish);
}
activity.setActionBarTitle(editMode ? R.string.edit_content : R.string.new_publish);
}
}
@@ -583,58 +585,63 @@ public class PublishFormFragment extends BaseFragment implements
private void updateFieldsFromCurrentClaim() {
if (currentClaim != null && !editFieldsLoaded) {
Context context = getContext();
Claim.StreamMetadata metadata = (Claim.StreamMetadata) currentClaim.getValue();
uploadedThumbnailUrl = currentClaim.getThumbnailUrl();
if (context != null && !Helper.isNullOrEmpty(uploadedThumbnailUrl)) {
Glide.with(context.getApplicationContext()).load(uploadedThumbnailUrl).centerCrop().into(imageThumbnail);
}
inputTitle.setText(currentClaim.getTitle());
inputDescription.setText(currentClaim.getDescription());
if (addedTagsAdapter != null && currentClaim.getTagObjects() != null) {
addedTagsAdapter.addTags(currentClaim.getTagObjects());
updateSuggestedTags(currentFilter, SUGGESTED_LIMIT, true);
}
if (metadata.getFee() != null) {
Fee fee = metadata.getFee();
switchPrice.setChecked(true);
inputPrice.setText(fee.getAmount());
priceCurrencySpinner.setSelection("lbc".equalsIgnoreCase(fee.getCurrency()) ? 0 : 1);
}
inputAddress.setText(currentClaim.getName());
inputDeposit.setText(currentClaim.getAmount());
if (metadata.getLanguages() != null && metadata.getLanguages().size() > 0) {
// get the first language
String langCode = metadata.getLanguages().get(0);
int langCodePosition = ((LanguageSpinnerAdapter) languageSpinner.getAdapter()).getItemPosition(langCode);
if (langCodePosition > -1) {
languageSpinner.setSelection(langCodePosition);
}
}
if (!Helper.isNullOrEmpty(metadata.getLicense())) {
LicenseSpinnerAdapter adapter = (LicenseSpinnerAdapter) licenseSpinner.getAdapter();
int licPosition = adapter.getItemPosition(metadata.getLicense());
if (licPosition == -1) {
licPosition = adapter.getItemPosition(Predefined.LICENSE_OTHER);
}
if (licPosition > -1) {
licenseSpinner.setSelection(licPosition);
try {
Claim.StreamMetadata metadata = (Claim.StreamMetadata) currentClaim.getValue();
uploadedThumbnailUrl = currentClaim.getThumbnailUrl();
if (context != null && !Helper.isNullOrEmpty(uploadedThumbnailUrl)) {
Glide.with(context.getApplicationContext()).load(uploadedThumbnailUrl).centerCrop().into(imageThumbnail);
}
License selectedLicense = (License) licenseSpinner.getSelectedItem();
boolean otherLicense = Arrays.asList(
Predefined.LICENSE_COPYRIGHTED.toLowerCase(),
Predefined.LICENSE_OTHER.toLowerCase()).contains(selectedLicense.getName().toLowerCase());
inputOtherLicenseDescription.setText(otherLicense ? metadata.getLicense() : null);
}
inputTitle.setText(currentClaim.getTitle());
inputDescription.setText(currentClaim.getDescription());
if (addedTagsAdapter != null && currentClaim.getTagObjects() != null) {
addedTagsAdapter.addTags(currentClaim.getTagObjects());
updateSuggestedTags(currentFilter, SUGGESTED_LIMIT, true);
}
inputAddress.setEnabled(false);
editMode = true;
editFieldsLoaded = true;
if (metadata.getFee() != null) {
Fee fee = metadata.getFee();
switchPrice.setChecked(true);
inputPrice.setText(fee.getAmount());
priceCurrencySpinner.setSelection("lbc".equalsIgnoreCase(fee.getCurrency()) ? 0 : 1);
}
inputAddress.setText(currentClaim.getName());
inputDeposit.setText(currentClaim.getAmount());
if (metadata.getLanguages() != null && metadata.getLanguages().size() > 0) {
// get the first language
String langCode = metadata.getLanguages().get(0);
int langCodePosition = ((LanguageSpinnerAdapter) languageSpinner.getAdapter()).getItemPosition(langCode);
if (langCodePosition > -1) {
languageSpinner.setSelection(langCodePosition);
}
}
if (!Helper.isNullOrEmpty(metadata.getLicense())) {
LicenseSpinnerAdapter adapter = (LicenseSpinnerAdapter) licenseSpinner.getAdapter();
int licPosition = adapter.getItemPosition(metadata.getLicense());
if (licPosition == -1) {
licPosition = adapter.getItemPosition(Predefined.LICENSE_OTHER);
}
if (licPosition > -1) {
licenseSpinner.setSelection(licPosition);
}
License selectedLicense = (License) licenseSpinner.getSelectedItem();
boolean otherLicense = Arrays.asList(
Predefined.LICENSE_COPYRIGHTED.toLowerCase(),
Predefined.LICENSE_OTHER.toLowerCase()).contains(selectedLicense.getName().toLowerCase());
inputOtherLicenseDescription.setText(otherLicense ? metadata.getLicense() : null);
}
inputAddress.setEnabled(false);
editMode = true;
editFieldsLoaded = true;
} catch (ClassCastException ex) {
// invalid claim value type
cancelOnFatalCondition(getString(R.string.publish_invalid_claim_type));
}
}
}
@@ -721,7 +728,10 @@ public class PublishFormFragment extends BaseFragment implements
private void uploadThumbnail(String thumbnailPath) {
if (uploading) {
Snackbar.make(getView(), R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
View view = getView();
if (view != null) {
Snackbar.make(view, R.string.wait_for_upload, Snackbar.LENGTH_LONG).show();
}
return;
}
@@ -784,73 +794,75 @@ public class PublishFormFragment extends BaseFragment implements
}
Context context = getContext();
String outputPath = String.format("%s/videos", Utils.getAppInternalStorageDir(context));
File dir = new File(outputPath);
if (!dir.isDirectory()) {
dir.mkdirs();
}
if (context != null) {
String outputPath = String.format("%s/videos", Utils.getAppInternalStorageDir(context));
File dir = new File(outputPath);
if (!dir.isDirectory()) {
dir.mkdirs();
}
boolean hasFullDuration = videoInformation != null && videoInformation.getDurationSeconds() > 0;
Helper.setViewVisibility(optimizationRealProgress, hasFullDuration ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(optimizationProgress, hasFullDuration ? View.GONE : View.VISIBLE);
boolean hasFullDuration = videoInformation != null && videoInformation.getDurationSeconds() > 0;
Helper.setViewVisibility(optimizationRealProgress, hasFullDuration ? View.VISIBLE : View.GONE);
Helper.setViewVisibility(optimizationProgress, hasFullDuration ? View.GONE : View.VISIBLE);
File sourceFile = new File(filePath);
String filename = sourceFile.getName();
if (!filename.endsWith(".mp4")) {
int lastDotIndex = filename.lastIndexOf('.');
filename = String.format("%s.mp4", lastDotIndex > -1 ? filename.substring(0, lastDotIndex) : filename);
}
File sourceFile = new File(filePath);
String filename = sourceFile.getName();
if (!filename.endsWith(".mp4")) {
int lastDotIndex = filename.lastIndexOf('.');
filename = String.format("%s.mp4", lastDotIndex > -1 ? filename.substring(0, lastDotIndex) : filename);
}
String videoFilePath = String.format("%s/%s", outputPath, filename);
File targetFile = new File(videoFilePath);
if (targetFile.exists()) {
targetFile.delete();
}
String videoFilePath = String.format("%s/%s", outputPath, filename);
File targetFile = new File(videoFilePath);
if (targetFile.exists()) {
targetFile.delete();
}
transcodeInProgress = true;
videoTranscodeTask = new VideoTranscodeTask(filePath, videoFilePath, scalePart, transcodeRequired, new VideoTranscodeTask.VideoTranscodeHandler() {
@Override
public void onProgress(int time) {
if (context != null) {
int currentDuration = Double.valueOf(time / 1000.0).intValue();
int fullDuration = videoInformation != null ? videoInformation.getDurationSeconds() : 0;
long elapsed = System.currentTimeMillis() - transcodeStartTime;
String completedDurationText = Helper.formatDuration(currentDuration);
if (fullDuration > 0) {
completedDurationText = String.format("%s / %s", completedDurationText, Helper.formatDuration(fullDuration));
int percentComplete = Double.valueOf(Math.ceil((double) currentDuration / (double) fullDuration * 100.0)).intValue();
optimizationRealProgress.setProgress(percentComplete);
transcodeInProgress = true;
videoTranscodeTask = new VideoTranscodeTask(filePath, videoFilePath, scalePart, transcodeRequired, new VideoTranscodeTask.VideoTranscodeHandler() {
@Override
public void onProgress(int time) {
if (context != null) {
int currentDuration = Double.valueOf(time / 1000.0).intValue();
int fullDuration = videoInformation != null ? videoInformation.getDurationSeconds() : 0;
long elapsed = System.currentTimeMillis() - transcodeStartTime;
String completedDurationText = Helper.formatDuration(currentDuration);
if (fullDuration > 0) {
completedDurationText = String.format("%s / %s", completedDurationText, Helper.formatDuration(fullDuration));
int percentComplete = Double.valueOf(Math.ceil((double) currentDuration / (double) fullDuration * 100.0)).intValue();
optimizationRealProgress.setProgress(percentComplete);
}
String text = context.getString(R.string.completed_video_duration, completedDurationText);
Helper.setViewText(textOptimizationProgress, text);
Helper.setViewText(textOptimizationElapsed, Helper.formatDuration(Double.valueOf(elapsed / 1000.0).longValue()));
}
String text = context.getString(R.string.completed_video_duration, completedDurationText);
Helper.setViewText(textOptimizationProgress, text);
Helper.setViewText(textOptimizationElapsed, Helper.formatDuration(Double.valueOf(elapsed / 1000.0).longValue()));
}
}
@Override
public void onSuccess(String outputFilePath) {
transcodedFilePath = outputFilePath;
transcodeInProgress = false;
Helper.setViewText(textOptimizationStatus, R.string.video_optimized);
Helper.setViewVisibility(optimizationRealProgress, View.GONE);
Helper.setViewVisibility(optimizationProgress, View.GONE);
Helper.setViewVisibility(textOptimizationProgress, View.GONE);
}
@Override
public void onSuccess(String outputFilePath) {
transcodedFilePath = outputFilePath;
transcodeInProgress = false;
Helper.setViewText(textOptimizationStatus, R.string.video_optimized);
Helper.setViewVisibility(optimizationRealProgress, View.GONE);
Helper.setViewVisibility(optimizationProgress, View.GONE);
Helper.setViewVisibility(textOptimizationProgress, View.GONE);
}
@Override
public void onErrorOrCancelled() {
transcodeInProgress = false;
Helper.setViewText(textOptimizationStatus, R.string.video_optimize_failed);
Helper.setViewVisibility(optimizationRealProgress, View.GONE);
Helper.setViewVisibility(optimizationProgress, View.GONE);
Helper.setViewVisibility(textOptimizationProgress, View.GONE);
}
});
@Override
public void onErrorOrCancelled() {
transcodeInProgress = false;
Helper.setViewText(textOptimizationStatus, R.string.video_optimize_failed);
Helper.setViewVisibility(optimizationRealProgress, View.GONE);
Helper.setViewVisibility(optimizationProgress, View.GONE);
Helper.setViewVisibility(textOptimizationProgress, View.GONE);
}
});
transcodeStartTime = System.currentTimeMillis();
videoTranscodeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
transcodeStartTime = System.currentTimeMillis();
videoTranscodeTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
}
private void cancelOnFatalCondition(String message) {
@@ -875,6 +887,7 @@ public class PublishFormFragment extends BaseFragment implements
}
checkParams();
checkRewardsDriver();
updateFieldsFromCurrentClaim();
if (currentClaim == null && (currentGalleryItem != null || !Helper.isNullOrEmpty(currentFilePath))) {
@@ -889,10 +902,7 @@ public class PublishFormFragment extends BaseFragment implements
LbryAnalytics.setCurrentScreen(activity, "Channel Form", "ChannelForm");
activity.addStoragePermissionListener(this);
if (editMode) {
ActionBar actionBar = activity.getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle(R.string.edit_content);
}
activity.setActionBarTitle(R.string.edit_content);
}
}
@@ -973,8 +983,8 @@ public class PublishFormFragment extends BaseFragment implements
}
} else {
channelSpinnerAdapter.clear();
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.addPlaceholder(true);
channelSpinnerAdapter.addAll(channels);
channelSpinnerAdapter.notifyDataSetChanged();
}
@@ -983,12 +993,14 @@ public class PublishFormFragment extends BaseFragment implements
}
if (channelSpinnerAdapter != null && channelSpinner != null) {
if (editMode && currentClaim.getSigningChannel() != null && !editChannelSpinnerLoaded) {
int position = channelSpinnerAdapter.getItemPosition(currentClaim.getSigningChannel());
if (position > -1) {
channelSpinner.setSelection(position);
if (editMode) {
if (currentClaim.getSigningChannel() != null && !editChannelSpinnerLoaded) {
int position = channelSpinnerAdapter.getItemPosition(currentClaim.getSigningChannel());
if (position > -1) {
channelSpinner.setSelection(position);
}
editChannelSpinnerLoaded = true;
}
editChannelSpinnerLoaded = true;
} else {
if (channelSpinnerAdapter.getCount() > 2) {
// if anonymous displayed, select first channel if available
@@ -1042,6 +1054,16 @@ public class PublishFormFragment extends BaseFragment implements
metadata.setLicenseUrl(selectedLicense.getUrl());
}
// set release time from current claim (on edit)
if (currentClaim != null) {
Claim.StreamMetadata currentMetadata = (Claim.StreamMetadata) currentClaim.getValue();
metadata.setReleaseTime(currentMetadata.getReleaseTime());
if (metadata.getReleaseTime() == 0) {
metadata.setReleaseTime(currentClaim.getTimestamp());
}
claim.setTimestamp(currentClaim.getTimestamp());
}
claim.setValueType(Claim.TYPE_STREAM);
claim.setValue(metadata);
@@ -1093,6 +1115,7 @@ public class PublishFormFragment extends BaseFragment implements
// Run the logPublish task
if (!BuildConfig.DEBUG) {
claimResult.setSigningChannel(claim.getSigningChannel());
LogPublishTask logPublish = new LogPublishTask(claimResult);
logPublish.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
@@ -1101,13 +1124,13 @@ public class PublishFormFragment extends BaseFragment implements
Bundle bundle = new Bundle();
bundle.putString("claim_id", claimResult.getClaimId());
bundle.putString("claim_name", claimResult.getName());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_PUBLISH, bundle);
LbryAnalytics.logEvent(editMode ? LbryAnalytics.EVENT_PUBLISH_UPDATE : LbryAnalytics.EVENT_PUBLISH, bundle);
Context context = getContext();
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
activity.showMessage(R.string.publish_successful);
activity.openPublishesOnSuccessfulPublish();
activity.sendBroadcast(new Intent(MainActivity.ACTION_PUBLISH_SUCCESSFUL));
}
}
@@ -1260,128 +1283,7 @@ public class PublishFormFragment extends BaseFragment implements
if (walletBalance != null && inlineDepositBalanceValue != null) {
inlineDepositBalanceValue.setText(Helper.shortCurrencyFormat(walletBalance.getAvailable().doubleValue()));
}
}
private void setupInlineChannelCreator(
View container,
TextInputEditText inputChannelName,
TextInputEditText inputDeposit,
View inlineBalanceView,
TextView inlineBalanceValue,
View linkCancel,
MaterialButton buttonCreate,
View progressView) {
inputDeposit.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
Helper.setViewVisibility(inlineBalanceView, hasFocus ? View.VISIBLE : View.INVISIBLE);
}
});
linkCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Helper.setViewText(inputChannelName, null);
Helper.setViewText(inputDeposit, null);
Helper.setViewVisibility(container, View.GONE);
}
});
buttonCreate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// validate deposit and channel name
String channelNameString = Helper.normalizeChannelName(Helper.getValue(inputChannelName.getText()));
Claim claimToSave = new Claim();
claimToSave.setName(channelNameString);
String channelName = claimToSave.getName().startsWith("@") ? claimToSave.getName().substring(1) : claimToSave.getName();
String depositString = Helper.getValue(inputDeposit.getText());
if ("@".equals(channelName) || Helper.isNullOrEmpty(channelName)) {
showError(getString(R.string.please_enter_channel_name));
return;
}
if (!LbryUri.isNameValid(channelName)) {
showError(getString(R.string.channel_name_invalid_characters));
return;
}
if (Helper.channelExists(channelName)) {
showError(getString(R.string.channel_name_already_created));
return;
}
double depositAmount = 0;
try {
depositAmount = Double.valueOf(depositString);
} catch (NumberFormatException ex) {
// pass
showError(getString(R.string.please_enter_valid_deposit));
return;
}
if (depositAmount == 0) {
String error = getResources().getQuantityString(R.plurals.min_deposit_required, depositAmount == 1 ? 1 : 2, String.valueOf(Helper.MIN_DEPOSIT));
showError(error);
return;
}
if (Lbry.walletBalance == null || Lbry.walletBalance.getAvailable().doubleValue() < depositAmount) {
showError(getString(R.string.deposit_more_than_balance));
return;
}
ChannelCreateUpdateTask task = new ChannelCreateUpdateTask(
claimToSave, new BigDecimal(depositString), false, progressView, new ClaimResultHandler() {
@Override
public void beforeStart() {
Helper.setViewEnabled(inputChannelName, false);
Helper.setViewEnabled(inputDeposit, false);
Helper.setViewEnabled(buttonCreate, false);
Helper.setViewEnabled(linkCancel, false);
}
@Override
public void onSuccess(Claim claimResult) {
if (!BuildConfig.DEBUG) {
LogPublishTask logPublishTask = new LogPublishTask(claimResult);
logPublishTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
// channel created
Bundle bundle = new Bundle();
bundle.putString("claim_id", claimResult.getClaimId());
bundle.putString("claim_name", claimResult.getName());
LbryAnalytics.logEvent(LbryAnalytics.EVENT_CHANNEL_CREATE, bundle);
// add the claim to the channel list and set it as the selected item
channelSpinnerAdapter.add(claimResult);
channelSpinner.setSelection(channelSpinnerAdapter.getCount() - 1);
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
}
@Override
public void onError(Exception error) {
Helper.setViewEnabled(inputChannelName, true);
Helper.setViewEnabled(inputDeposit, true);
Helper.setViewEnabled(buttonCreate, true);
Helper.setViewEnabled(linkCancel, true);
showError(error.getMessage());
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
Helper.setViewText(inlineBalanceValue, Helper.shortCurrencyFormat(Lbry.walletBalance.getAvailable().doubleValue()));
}
private void showError(String message) {
Context context = getContext();
if (context != null) {
Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
checkRewardsDriver();
}
private void checkUploadButton() {
@@ -1398,15 +1300,25 @@ public class PublishFormFragment extends BaseFragment implements
@Override
public void onStoragePermissionRefused() {
showError(getString(R.string.storage_permission_rationale_images));
if (!storageRefusedOnce) {
try {
showError(getString(R.string.storage_permission_rationale_images));
} catch (IllegalStateException ex) {
// pass
}
storageRefusedOnce = true;
}
launchPickerPending = false;
}
@Override
public void onFilePicked(String filePath) {
if (Helper.isNullOrEmpty(filePath)) {
Snackbar.make(getView(), R.string.undetermined_image_filepath, Snackbar.LENGTH_LONG).setBackgroundTint(
ContextCompat.getColor(getContext(), R.color.red)).show();
View view = getView();
if (view != null) {
Snackbar.make(view, R.string.undetermined_image_filepath, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
return;
}
@@ -1429,6 +1341,15 @@ public class PublishFormFragment extends BaseFragment implements
// At some point in the future, allow file picking for publish file?
}
private void checkRewardsDriver() {
Context ctx = getContext();
if (ctx != null) {
String rewardsDriverText = String.format("%s\n%s",
getString(R.string.publishing_requires_credits), getString(R.string.tap_here_to_get_some));
checkRewardsDriverCard(rewardsDriverText, Helper.MIN_DEPOSIT);
}
}
private static class VideoProbeTask extends AsyncTask<Void, Void, VideoInformation> {
private String filePath;
private VideoProbeHandler handler;
@@ -12,7 +12,6 @@ import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.camera.core.Camera;
@@ -52,6 +51,8 @@ import io.lbry.browser.utils.LbryAnalytics;
public class PublishFragment extends BaseFragment implements
CameraPermissionListener, FilePickerListener, StoragePermissionListener {
private boolean cameraPreviewInitialized;
private boolean storagePermissionRefusedOnce;
private PreviewView cameraPreview;
private RecyclerView galleryGrid;
private GalleryGridAdapter adapter;
@@ -122,7 +123,7 @@ public class PublishFragment extends BaseFragment implements
private void displayPreviewWithCameraX() {
Context context = getContext();
if (context != null) {
if (context != null && MainActivity.hasPermission(Manifest.permission.CAMERA, context)) {
cameraProviderFuture = ProcessCameraProvider.getInstance(context);
cameraProviderFuture.addListener(new Runnable() {
@Override
@@ -137,8 +138,9 @@ public class PublishFragment extends BaseFragment implements
Camera camera = cameraProvider.bindToLifecycle((LifecycleOwner) context, cameraSelector, preview);
preview.setSurfaceProvider(cameraPreview.createSurfaceProvider(camera.getCameraInfo()));
cameraPreviewInitialized = true;
}
} catch (ExecutionException | InterruptedException ex) {
} catch (ExecutionException | IllegalArgumentException | InterruptedException ex) {
// pass
}
}
@@ -252,7 +254,9 @@ public class PublishFragment extends BaseFragment implements
}
}
checkStoragePermissionAndLoadVideos();
if (!storagePermissionRefusedOnce) {
checkStoragePermissionAndLoadVideos();
}
}
@SuppressLint("RestrictedApi")
@@ -267,7 +271,9 @@ public class PublishFragment extends BaseFragment implements
activity.removeFilePickerListener(this);
}
}
CameraX.unbindAll();
if (cameraPreviewInitialized) {
CameraX.unbindAll();
}
super.onStop();
}
@@ -361,13 +367,13 @@ public class PublishFragment extends BaseFragment implements
public void onCameraPermissionRefused() {
if (takePhotoPending) {
takePhotoPending = false;
Snackbar.make(getView(), R.string.camera_permission_rationale_photo, Toast.LENGTH_LONG).
Snackbar.make(getView(), R.string.camera_permission_rationale_photo, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
return;
}
recordPending = false;
Snackbar.make(getView(), R.string.camera_permission_rationale_record, Toast.LENGTH_LONG).
Snackbar.make(getView(), R.string.camera_permission_rationale_record, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
@@ -395,9 +401,15 @@ public class PublishFragment extends BaseFragment implements
@Override
public void onStoragePermissionRefused() {
Snackbar.make(getView(), R.string.storage_permission_rationale_videos, Snackbar.LENGTH_LONG).setBackgroundTint(
ContextCompat.getColor(getContext(), R.color.red)
).show();
storagePermissionRefusedOnce = true;
View root = getView();
if (root != null) {
Snackbar.make(root, R.string.storage_permission_rationale_videos, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
Helper.setViewText(noVideosLoaded, R.string.storage_permission_rationale_videos);
}
checkNoVideosLoaded();
}
public String getSuggestedPublishUrl() {
@@ -12,6 +12,7 @@ import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
@@ -150,21 +151,28 @@ public class PublishesFragment extends BaseFragment implements ActionMode.Callba
@Override
public void onSuccess(List<Claim> claims) {
Lbry.ownClaims = Helper.filterDeletedClaims(new ArrayList<>(claims));
Context context = getContext();
if (adapter == null) {
adapter = new ClaimListAdapter(claims, context);
adapter.setCanEnterSelectionMode(true);
adapter.setSelectionModeListener(PublishesFragment.this);
adapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
if (context instanceof MainActivity) {
((MainActivity) context).openFileClaim(claim);
Context context = getContext();
if (context != null) {
adapter = new ClaimListAdapter(claims, context);
adapter.setCanEnterSelectionMode(true);
adapter.setSelectionModeListener(PublishesFragment.this);
adapter.setListener(new ClaimListAdapter.ClaimListItemListener() {
@Override
public void onClaimClicked(Claim claim) {
if (context instanceof MainActivity) {
MainActivity activity = (MainActivity) context;
if (claim.getName().startsWith("@")) {
activity.openChannelClaim(claim);
} else {
activity.openFileClaim(claim);
}
}
}
});
if (contentList != null) {
contentList.setAdapter(adapter);
}
});
if (contentList != null) {
contentList.setAdapter(adapter);
}
} else {
adapter.setItems(claims);
@@ -234,7 +242,8 @@ public class PublishesFragment extends BaseFragment implements ActionMode.Callba
@Override
public boolean onPrepareActionMode(androidx.appcompat.view.ActionMode actionMode, Menu menu) {
int selectionCount = adapter != null ? adapter.getSelectedCount() : 0;
menu.findItem(R.id.action_edit).setVisible(selectionCount == 1);
menu.findItem(R.id.action_edit).setVisible(selectionCount == 1 &&
Claim.TYPE_STREAM.equalsIgnoreCase(adapter.getSelectedItems().get(0).getValueType()));
return true;
}
@@ -1,11 +1,14 @@
package io.lbry.browser.ui.verification;
import android.app.Activity;
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.view.inputmethod.InputMethodManager;
import android.widget.ProgressBar;
import android.widget.TextView;
@@ -67,8 +70,12 @@ public class EmailVerificationFragment extends Fragment {
inputEmail.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
String layoutHint = !hasFocus ? "" : getString(R.string.email);
inputLayoutEmail.setHint(layoutHint);
try {
String layoutHint = !hasFocus ? "" : getString(R.string.email);
inputLayoutEmail.setHint(layoutHint);
} catch (IllegalStateException ex) {
// pass
}
}
});
buttonContinue.setOnClickListener(new View.OnClickListener() {
@@ -95,12 +102,21 @@ public class EmailVerificationFragment extends Fragment {
private void addEmail() {
currentEmail = Helper.getValue(inputEmail.getText());
if (Helper.isNullOrEmpty(currentEmail) || currentEmail.indexOf("@") == -1) {
Snackbar.make(getView(), R.string.provide_valid_email, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
if (Helper.isNullOrEmpty(currentEmail) || !currentEmail.contains("@")) {
View view = getView();
if (view != null) {
Snackbar.make(view, R.string.provide_valid_email, Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
return;
}
Context context = getContext();
if (context != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputEmail.getWindowToken(), 0);
}
EmailNewTask task = new EmailNewTask(currentEmail, emailAddProgress, new EmailNewTask.EmailNewHandler() {
@Override
public void beforeStart() {
@@ -127,8 +143,11 @@ public class EmailVerificationFragment extends Fragment {
@Override
public void onError(Exception error) {
Snackbar.make(getView(), error.getMessage(), Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
View view = getView();
if (view != null && error != null) {
Snackbar.make(getView(), error.getMessage(), Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
};
Helper.setViewVisibility(buttonContinue, View.VISIBLE);
}
});
@@ -146,7 +165,8 @@ public class EmailVerificationFragment extends Fragment {
}
private void checkEmailVerified() {
CheckUserEmailVerifiedTask task = new CheckUserEmailVerifiedTask(new CheckUserEmailVerifiedTask.CheckUserEmailVerifiedHandler() {
Context context = getContext();
CheckUserEmailVerifiedTask task = new CheckUserEmailVerifiedTask(context, new CheckUserEmailVerifiedTask.CheckUserEmailVerifiedHandler() {
@Override
public void onUserEmailVerified() {
if (listener != null) {
@@ -185,14 +205,20 @@ public class EmailVerificationFragment extends Fragment {
@Override
public void onSuccess() {
Snackbar.make(getView(), R.string.please_follow_instructions, Snackbar.LENGTH_LONG).show();
View view = getView();
if (view != null) {
Snackbar.make(view, R.string.please_follow_instructions, Snackbar.LENGTH_LONG).show();
}
Helper.setViewEnabled(buttonResend, true);
}
@Override
public void onError(Exception error) {
Snackbar.make(getView(), error.getMessage(), Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
View view = getView();
if (view != null && error != null) {
Snackbar.make(view, error.getMessage(), Snackbar.LENGTH_LONG).
setBackgroundTint(Color.RED).setTextColor(Color.WHITE).show();
}
Helper.setViewEnabled(buttonResend, true);
}
});
@@ -1,27 +1,75 @@
package io.lbry.browser.ui.verification;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.snackbar.Snackbar;
import io.lbry.browser.R;
import io.lbry.browser.listener.SignInListener;
import io.lbry.browser.model.TwitterOauth;
import io.lbry.browser.model.lbryinc.RewardVerified;
import io.lbry.browser.tasks.RewardVerifiedHandler;
import io.lbry.browser.tasks.TwitterOauthHandler;
import io.lbry.browser.tasks.lbryinc.TwitterVerifyTask;
import io.lbry.browser.tasks.verification.TwitterAccessTokenTask;
import io.lbry.browser.tasks.verification.TwitterRequestTokenTask;
import io.lbry.browser.utils.Helper;
import io.lbry.browser.utils.Lbryio;
import lombok.Setter;
public class ManualVerificationFragment extends Fragment {
@Setter
private SignInListener listener;
private PopupWindow popup;
private View mainView;
private View loadingView;
private TwitterOauth currentOauth;
private boolean twitterOauthInProgress = false;
private static final double SKIP_QUEUE_PRICE = 4.99;
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_verification_manual, container, false);
Helper.applyHtmlForTextView((TextView) root.findViewById(R.id.verification_manual_discord_verify));
mainView = root.findViewById(R.id.verification_manual_main);
loadingView = root.findViewById(R.id.verification_manual_loading);
Context context = getContext();
MaterialButton buttonSkipQueue = root.findViewById(R.id.verification_manual_skip_queue);
buttonSkipQueue.setText(context.getString(R.string.skip_queue_button_text, String.valueOf(SKIP_QUEUE_PRICE)));
Helper.applyHtmlForTextView(root.findViewById(R.id.verification_manual_discord_verify));
root.findViewById(R.id.verification_manual_twitter_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// start twitter verification
if (currentOauth != null) {
// Twitter three-legged oauth already completed, verify directly
twitterVerify(currentOauth);
} else {
// show twitter sign-in flow
twitterVerificationFlow();
}
}
});
root.findViewById(R.id.verification_manual_continue_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
@@ -31,6 +79,205 @@ public class ManualVerificationFragment extends Fragment {
}
});
root.findViewById(R.id.verification_manual_skip_queue).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (listener != null) {
listener.onSkipQueueAction();
}
}
});
return root;
}
private void twitterVerificationFlow() {
twitterOauthInProgress = true;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
showLoading();
String consumerKey = getResources().getString(R.string.TWITTER_CONSUMER_KEY);
String consumerSecret = getResources().getString(R.string.TWITTER_CONSUMER_SECRET);
TwitterRequestTokenTask task = new TwitterRequestTokenTask(consumerKey, consumerSecret, new TwitterOauthHandler() {
@Override
public void onSuccess(TwitterOauth twitterOauth) {
twitterOauthInProgress = false;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
showTwitterAuthenticateWithToken(twitterOauth.getOauthToken());
}
@Override
public void onError(Exception error) {
handleFlowError(null);
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
public void showLoading() {
Helper.setViewVisibility(mainView, View.INVISIBLE);
Helper.setViewVisibility(loadingView, View.VISIBLE);
}
public void hideLoading() {
Helper.setViewVisibility(mainView, View.VISIBLE);
Helper.setViewVisibility(loadingView, View.GONE);
}
private void showTwitterAuthenticateWithToken(String oauthToken) {
Context context = getContext();
if (context != null) {
WebView webView = new WebView(context);
webView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
webView.loadUrl(String.format("https://api.twitter.com/oauth/authorize?oauth_token=%s", oauthToken));
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("https://lbry.tv") || url.equalsIgnoreCase("https://twitter.com/home") /* Return to Twitter */) {
if (url.startsWith("https://lbry.tv") && url.contains("oauth_token") && url.contains("oauth_verifier")) {
// finish 3-legged oauth
twitterOauthInProgress = true;
listener.onManualProgress(twitterOauthInProgress);
finishTwitterOauth(url);
}
if (popup != null) {
popup.dismiss();
}
return false;
}
view.loadUrl(url);
return true;
}
});
View popupView = LayoutInflater.from(context).inflate(R.layout.popup_webview, null);
((LinearLayout) popupView.findViewById(R.id.popup_webivew_container)).addView(webView);
popupView.findViewById(R.id.popup_cancel_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!twitterOauthInProgress && popup != null) {
popup.dismiss();
hideLoading();
}
}
});
float scale = getResources().getDisplayMetrics().density;
popup = new PopupWindow(context);
popup.setOnDismissListener(new PopupWindow.OnDismissListener() {
@Override
public void onDismiss() {
if (!twitterOauthInProgress) {
hideLoading();
}
popup = null;
}
});
popup.setWidth(Helper.getScaledValue(340, scale));
popup.setHeight(Helper.getScaledValue(480, scale));
popup.setContentView(popupView);
View parent = getView();
popup.setFocusable(true);
popup.showAtLocation(parent, Gravity.CENTER, 0, 0);
popup.update();
}
}
private void finishTwitterOauth(String callbackUrl) {
String params = callbackUrl.substring(callbackUrl.indexOf('?') + 1);
TwitterAccessTokenTask task = new TwitterAccessTokenTask(params, new TwitterOauthHandler() {
@Override
public void onSuccess(TwitterOauth twitterOauth) {
// send request to finish verifying
currentOauth = twitterOauth;
twitterVerify(twitterOauth);
}
@Override
public void onError(Exception error) {
handleFlowError(null);
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
private void twitterVerify(TwitterOauth twitterOauth) {
Context context = getContext();
if (context != null) {
showLoading();
twitterOauthInProgress = true;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
TwitterVerifyTask task = new TwitterVerifyTask(twitterOauth, null, context, new RewardVerifiedHandler() {
@Override
public void onSuccess(RewardVerified rewardVerified) {
twitterOauthInProgress = false;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
if (Lbryio.currentUser != null) {
Lbryio.currentUser.setRewardApproved(rewardVerified.isRewardApproved());
}
if (rewardVerified.isRewardApproved()) {
if (listener != null) {
listener.onTwitterVerified();
}
} else {
View root = getView();
if (root != null) {
// reward approved wasn't set to true
Snackbar.make(root, getString(R.string.twitter_verification_not_approved), Snackbar.LENGTH_LONG).
setTextColor(Color.WHITE).
setBackgroundTint(Color.RED).show();
}
hideLoading();
}
}
@Override
public void onError(Exception error) {
handleFlowError(error != null ? error.getMessage() : null);
}
});
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
twitterOauthInProgress = false;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
hideLoading();
}
}
private void handleFlowError(String extra) {
hideLoading();
twitterOauthInProgress = false;
if (listener != null) {
listener.onManualProgress(twitterOauthInProgress);
}
showFlowError(extra);
}
private void showFlowError(String extra) {
Context context = getContext();
View root = getView();
if (context != null && root != null) {
String message = !Helper.isNullOrEmpty(extra) ?
getString(R.string.twitter_account_ineligible, extra) :
getString(R.string.twitter_verification_failed);
Snackbar.make(root, message, Snackbar.LENGTH_LONG).
setTextColor(Color.WHITE).
setBackgroundTint(Color.RED).show();
}
}
}
@@ -1,5 +1,6 @@
package io.lbry.browser.ui.verification;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
@@ -7,6 +8,7 @@ import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
@@ -79,6 +81,12 @@ public class PhoneVerificationFragment extends Fragment {
return;
}
Context context = getContext();
if (context != null) {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(inputPhoneNumber.getWindowToken(), 0);
}
addPhoneNumber();
}
});
Loaded 100 of 234 files, more files were not shown because too many files have changed in this diff. Show more