209 Commits

Author SHA1 Message Date
Balazs Toldi
d5092f50f6 Fix issue with sharing urls
Closes #139
2023-08-18 21:26:12 +02:00
Balazs Toldi
d216fc4640 Fix issue with comment editing
In some change the behavior for detecting the users comments broke making it impossible to edit or delete previously created comments. Closes #136
2023-08-18 21:14:29 +02:00
Balazs Toldi
f61c12a30b Fix some malformed links 2023-08-18 21:09:28 +02:00
Balazs Toldi
495a1d025f Fix bug with inserting malformed image links 2023-08-18 15:39:56 +02:00
Balazs Toldi
0e31e40ef1 Send Private messages from ViewUserDetailActivity 2023-08-18 15:39:34 +02:00
Balazs Toldi
bae68d4a99 Fix PrivateMessageDataSource making way to many requests 2023-08-18 13:18:21 +02:00
Balazs Toldi
3e17e3364d Sending private messages 2023-08-18 09:46:51 +02:00
Balazs Toldi
9626500586 Fix names on private message page 2023-08-18 09:46:51 +02:00
Balazs Toldi
92fcb811c3 Rebase to master 2023-08-18 09:46:43 +02:00
Balazs Toldi
81e2fdcf91 Fix lifecycle for ViewUser/ViewCommunity activities 2023-08-18 09:22:35 +02:00
Balazs Toldi
171338f492 Nicer stats for communities
This commit adds more info on the community detail page. The design is heavily inspired by Memmy.

Closes #45
2023-08-18 08:55:56 +02:00
Balazs Toldi
cc21588a66 Nicer stats for users
This commit adds more info on the user detail page. The design is heavily inspired by Memmy
2023-08-17 23:35:07 +02:00
Balazs Toldi
b5356ee5eb Fix long display name issues 2023-08-17 22:27:45 +02:00
Balazs Toldi
ec9be3f6af Fix compact view showing username instead of the community name
Closes #131
2023-08-17 22:02:48 +02:00
Balazs Toldi
ac5e67c032 Added LemmyPostAPI
Forgot to include in my prev commit.

Added LemmyPostAPI

Forgot to include in my prev commit.
2023-08-17 16:27:00 +02:00
Balazs Toldi
fd24f04254 Report posts and comments.
Closes #92
2023-08-17 15:46:18 +02:00
Balazs Toldi
0b74574fa6 Merge remote-tracking branch 'codeberg/master' 2023-08-17 08:43:15 +02:00
Balazs Toldi
2704ff0ecf Show community and user display name
Closes #34
2023-08-17 08:43:10 +02:00
owatnext
f4c33e08e2 Translated using Weblate (Welsh)
Currently translated at 0.6% (8 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/cy/
2023-08-16 23:29:15 +00:00
SinTan1729
5dddf2e39d Translated using Weblate (Bengali)
Currently translated at 2.5% (32 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/bn/
2023-08-16 23:29:15 +00:00
abiiM
487afce565 Translated using Weblate (Spanish)
Currently translated at 91.8% (1133 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/es/
2023-08-16 23:29:15 +00:00
JnkLtt
f31a13568c Translated using Weblate (German)
Currently translated at 94.4% (1166 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/de/
2023-08-16 23:29:14 +00:00
genoxidedev1
04341991bf Translated using Weblate (German)
Currently translated at 94.4% (1166 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/de/
2023-08-16 23:29:14 +00:00
Balazs Toldi
a7c2a67d0c Better loading for View User datail activity
Closes #64
2023-08-16 19:44:46 +02:00
Balazs Toldi
4ec6666f93 Make instance names clickable 2023-08-16 19:35:40 +02:00
Bazsalanszky
fcc0181075 Better post layout on post detail page 2023-08-16 16:54:27 +02:00
Bazsalanszky
1c4e5f3659 Fix compile issue 2023-08-16 10:31:53 +02:00
Balazs Toldi
a120fcf068 Better post layout on post listing
This commit fixes the issue where the user and community names had multiple line breaks in them if they were too long. I broke the instance part to a different textview with different colours.
2023-08-16 08:11:31 +02:00
Balazs Toldi
0328f34df2 Fix separated up/down vote counts when on the right side
Closes #123
2023-08-15 21:44:20 +02:00
Bazsalanszky
7849115000 Merge pull request 'Fix instance URL field hint on Login activity' (#121) from bugfix/instance_url_overlap into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/121
2023-08-15 16:19:48 +00:00
Balazs Toldi
41e14aab9d Fix instance URL field hint on Login activity 2023-08-15 15:57:38 +02:00
Bazsalanszky
074b5d012c Merge pull request 'fix #110 default colors' (#118) from American_Jesus/Infinity-For-Lemmy:fix-110-colors into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/118
Reviewed-by: Bazsalanszky <bazsalanszky@noreply.codeberg.org>
2023-08-15 13:39:59 +00:00
Generator
8a3ee7931d fix #110 default colors 2023-08-15 14:19:51 +01:00
Balazs Toldi
dce5a8d89c Fix resolving communities from non-home instance URLs 2023-08-15 08:23:14 +02:00
Balazs Toldi
a82f2b68e3 Merge branch 'feature/bugfixes' 2023-08-15 08:11:01 +02:00
Balazs Toldi
a36ddccefd Fix parsing user display name 2023-08-15 08:10:21 +02:00
Balazs Toldi
bbe696a37b Fix anonymous link resolving 2023-08-15 07:55:07 +02:00
Bazsalanszky
13ec5f84c4 Merge pull request 'Nightly build fixes' (#116) from feature/nightly into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/116
2023-08-15 05:33:17 +00:00
Balazs Toldi
587ebbb309 Change nightly build app name 2023-08-15 07:15:43 +02:00
Balazs Toldi
485611970f Potential fix for nightly build version codes 2023-08-15 07:15:19 +02:00
Bazsalanszky
c0738947b7 Merge pull request 'Nightly releases' (#109) from feature/nightly into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/109
2023-08-14 19:16:31 +00:00
Balazs Toldi
f1145d826e Merge remote-tracking branch 'codeberg/feature/nightly' into feature/nightly 2023-08-14 21:14:19 +02:00
Balazs Toldi
aa4f587443 Minro change to nightly.yaml 2023-08-14 21:14:09 +02:00
Balazs Toldi
e559e4acd2 Minro change to nightly.yaml 2023-08-14 21:14:09 +02:00
Balazs Toldi
db1e000325 Minro change to nightly.yaml 2023-08-14 21:14:09 +02:00
Balazs Toldi
4f57c17f73 Minro change to nightly.yaml 2023-08-14 21:14:09 +02:00
Balazs Toldi
21af736fa4 Check nightly build 2023-08-14 21:14:09 +02:00
Balazs Toldi
72ba80ff87 Use secrets in update-fdroid-data step 2023-08-14 21:14:09 +02:00
Bazsalanszky
450e96fdbe Merge pull request 'Set Dracula default dark theme. fix #86' (#110) from American_Jesus/Infinity-For-Lemmy:default-theme-dracula into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/110
Reviewed-by: Bazsalanszky <bazsalanszky@noreply.codeberg.org>
2023-08-14 19:11:38 +00:00
Generator
fcc60e1b16 remove extra double quote 2023-08-14 15:56:22 +01:00
owatnext
e888282d24 Translated using Weblate (Welsh)
Currently translated at 0.4% (5 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/cy/
2023-08-14 14:53:05 +00:00
SinTan1729
237d33f2e4 Translated using Weblate (Bengali)
Currently translated at 1.5% (19 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/bn/
2023-08-14 14:53:05 +00:00
American_Jesus
babb0d28bb Translated using Weblate (Portuguese)
Currently translated at 99.0% (1222 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/pt/
2023-08-14 14:53:05 +00:00
ybinnenweg
53eb7cbe91 Translated using Weblate (Dutch)
Currently translated at 83.6% (1032 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/nl/
2023-08-14 14:53:04 +00:00
Bazsalanszky
fed84f9942 Translated using Weblate (Hungarian)
Currently translated at 82.8% (1022 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/hu/
2023-08-14 14:53:04 +00:00
DestroyerAce
d4896a1f87 Translated using Weblate (Hindi)
Currently translated at 71.8% (887 of 1234 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/hi/
2023-08-14 14:53:04 +00:00
Generator
21879bec7d Set Dracula default dark theme 2023-08-14 14:41:01 +01:00
Balazs Toldi
bb143cfecb Minro change to nightly.yaml 2023-08-14 10:49:48 +02:00
Balazs Toldi
6475b4808a Minro change to nightly.yaml 2023-08-14 10:44:04 +02:00
Balazs Toldi
57a58cc518 Minro change to nightly.yaml 2023-08-14 10:39:36 +02:00
Balazs Toldi
8a5b6aa972 Minro change to nightly.yaml 2023-08-14 10:35:05 +02:00
Balazs Toldi
6813770d57 Check nightly build 2023-08-14 10:16:48 +02:00
Balazs Toldi
118b6cd430 Use secrets in update-fdroid-data step 2023-08-14 10:09:59 +02:00
Balazs Toldi
b984e35284 Change image for update-fdroid-data task in nightly.yaml 2023-08-14 09:21:05 +02:00
Balazs Toldi
f2a2a3029d Minor change in nightly pipeline 2023-08-14 09:12:06 +02:00
Balazs Toldi
b4ab1ba414 Update nightly build with signing keys 2023-08-14 08:47:20 +02:00
Balazs Toldi
d244e0ed42 Link resolver to change API base url.
This fixes the issue when opening a link while the app is fully closed
2023-08-14 08:09:51 +02:00
Balazs Toldi
81c190a9c0 Fix steps in nightly build 2023-08-13 22:08:19 +02:00
Balazs Toldi
e2f36c334b Fix steps in nightly build 2023-08-13 22:04:25 +02:00
Balazs Toldi
891215fcb3 Fix path for pull-repo-config step in nightly 2023-08-13 21:58:56 +02:00
Balazs Toldi
04e022cbbc Do not run the build pipeline on cron jobs 2023-08-13 21:54:51 +02:00
Balazs Toldi
1f4f3a475d Fix nightly build apk name 2023-08-13 21:52:52 +02:00
Balazs Toldi
3e6d435116 Fix nightly build indentation in CI definition 2023-08-13 21:42:20 +02:00
Balazs Toldi
9c6f946602 Test nightly build CI 2023-08-13 21:39:19 +02:00
Balazs Toldi
053c9e73b0 Fix parsing Community/post title with "&" characters 2023-08-13 17:03:25 +02:00
Balazs Toldi
acd1aef851 Fix editing post with empty URL field 2023-08-13 16:44:36 +02:00
Balazs Toldi
a3a753a9dd Add "Nightly" build type variant 2023-08-13 15:57:32 +02:00
Balazs Toldi
0ea491bcfc Fix issue with changing comment sort type on post page 2023-08-12 21:54:29 +02:00
Balazs Toldi
946d35b5d9 Show account qualified name in the navigation drawer.
Closes #24
2023-08-12 21:47:38 +02:00
Balazs Toldi
5098cb698d Show account qualified name in the navigation drawer.
Closes #24
2023-08-12 21:25:30 +02:00
Balazs Toldi
47a06c372e Merge remote-tracking branch 'codeberg/master' 2023-08-12 21:02:49 +02:00
Balazs Toldi
7877001533 Fix bugs related to fetching blocked users 2023-08-12 21:02:44 +02:00
Balazs Toldi
23d41846d0 Fix dialog title on blocking community page 2023-08-12 20:44:24 +02:00
Balazs Toldi
dc4dc17b6c Block user/community on post detail view 2023-08-12 20:43:07 +02:00
owatnext
6c8892938a Added translation using Weblate (Welsh) 2023-08-12 13:52:16 +00:00
SinTan1729
2f2d86bc3f Added translation using Weblate (Bengali) 2023-08-11 23:42:10 +00:00
Balazs Toldi
ecd3d008de Merge remote-tracking branch 'codeberg/master' 2023-08-11 23:59:46 +02:00
Balazs Toldi
f5172a17db Fix removing blocked things 2023-08-11 23:59:42 +02:00
Eryk Michalak
662a5bd597 Translated using Weblate (Polish)
Currently translated at 89.3% (1100 of 1231 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/pl/
2023-08-11 21:54:17 +00:00
Balazs Toldi
6621748de5 Block User option
This commit adds implementation to the block/unblock user option
2023-08-11 23:54:10 +02:00
Balazs Toldi
37fa76b79a Merge remote-tracking branch 'codeberg/master' 2023-08-11 23:21:13 +02:00
Balazs Toldi
c7acb50522 Do not show a follow button when searching for a user
Lemmy does not handle following users. An option for this was shown on the search results. Close #103
2023-08-11 23:21:09 +02:00
creepen
64304ad637 Translated using Weblate (Russian)
Currently translated at 98.8% (1208 of 1222 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/ru/
2023-08-11 18:09:56 +00:00
Balazs Toldi
635ca332da Merge remote-tracking branch 'codeberg/master' 2023-08-11 20:09:39 +02:00
Balazs Toldi
e2a15ab925 Add blocked thing listing activity
Added activity that displays the blocked users and communities
2023-08-11 20:09:34 +02:00
Balazs Toldi
016801419f Remove "Add to multicommunity" option from user/community pages 2023-08-11 10:49:01 +02:00
American_Jesus
48d79bc353 Translated using Weblate (Portuguese)
Currently translated at 90.5% (1107 of 1222 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/pt/
2023-08-11 08:44:01 +00:00
frenki
b8094fded8 Translated using Weblate (Italian)
Currently translated at 92.8% (1135 of 1222 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/it/
2023-08-11 08:44:01 +00:00
Bazsalanszky
8c82ba0e91 Translated using Weblate (Hungarian)
Currently translated at 80.7% (987 of 1222 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/hu/
2023-08-11 08:44:01 +00:00
JnkLtt
3ff9c06843 Translated using Weblate (German)
Currently translated at 95.0% (1162 of 1222 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/de/
2023-08-11 08:44:01 +00:00
Balazs Toldi
45ae8342ee Merge remote-tracking branch 'codeberg/master' 2023-08-11 10:43:54 +02:00
Balazs Toldi
b8c3dae807 Rename Home feed to "Subscribed" feed 2023-08-11 10:42:09 +02:00
Balazs Toldi
3afd2601f0 Fix issue with default sort times
Previously, if the default sort type is set to "top of x time", most failed to load any posts.
2023-08-11 08:42:16 +02:00
Balazs Toldi
82414bba55 Highlight pinned posts
This commits adds a pin icon to featured posts on communities or on the instance.
2023-08-10 21:44:36 +02:00
Balazs Toldi
7a39b2341b Small fixes related to parsing and soring
Closes #96
2023-08-10 21:12:49 +02:00
Balazs Toldi
37ab47bc34 Fix wierd issue when trying to open reddit@lemmy.world 2023-08-10 21:03:04 +02:00
Balazs Toldi
21b111cc2d Fix crash when trying to share sack trace
Closes #80
2023-08-10 20:44:26 +02:00
Bazsalanszky
b3c2f6213d Fix crash when unsaving post on a post detail page
Closes #90
2023-08-10 17:23:36 +02:00
Bazsalanszky
c3de94012a Merge remote-tracking branch 'origin/master' 2023-08-10 17:18:37 +02:00
Bazsalanszky
804eb64b5b Fix downvote count not being visible on comments 2023-08-10 17:18:31 +02:00
Bazsalanszky
6a4aa8075d Post detail up/downvote separation
This commit separates the up and downvote values on a post detail page.
2023-08-10 17:17:08 +02:00
Bazsalanszky
692aca4eca Translated using Weblate (Hungarian)
Currently translated at 79.4% (971 of 1222 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/hu/
2023-08-10 11:58:06 +00:00
Bazsalanszky
dd00802561 Merge remote-tracking branch 'weblate/master' 2023-08-10 13:43:36 +02:00
Bazsalanszky
a3e0fea200 Translated using Weblate (Hungarian)
Currently translated at 77.9% (952 of 1222 strings)

Translation: Infinity for Lemmy/App
Translate-URL: https://translate.codeberg.org/projects/infinity-for-lemmy/app/hu/
2023-08-10 11:39:34 +00:00
Bazsalanszky
304125ea0d Merge remote-tracking branch 'weblate/master' 2023-08-10 13:38:56 +02:00
Bazsalanszky
a465ebb5b4 Switch to codeberg translate!
Switched to codeberg translate instead of the hosted weblate
2023-08-10 13:35:31 +02:00
balazs
b39d00eba6 Translated using Weblate (Hungarian)
Currently translated at 78.6% (961 of 1222 strings)

Translation: Infinity for Lemmy/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/hu/
2023-08-10 13:26:09 +02:00
balazs
1ebdce309d Translated using Weblate (Hungarian)
Currently translated at 78.6% (961 of 1222 strings)

Translation: Infinity for Lemmy/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/hu/
2023-08-10 11:16:46 +02:00
balazs
d29b7585f7 Translated using Weblate (Hungarian)
Currently translated at 78.3% (957 of 1222 strings)

Translation: Infinity for Lemmy/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/hu/
2023-08-10 11:16:46 +02:00
Bazsalanszky
276560678c Minor change in strings.xml 2023-08-10 11:16:39 +02:00
Bazsalanszky
10c23a65c5 Changes on the separate up/down vote view on posts 2023-08-10 11:08:34 +02:00
Bazsalanszky
4e4f4377e7 Update woodpecker pipeline 2023-08-10 11:00:56 +02:00
Bazsalanszky
2e6c9db614 Separate comment up and downvotes
This commit makes it possible to separate up and downvotes in the comments as well.
2023-08-10 10:59:02 +02:00
Bazsalanszky
2375ba9d35 Merge remote-tracking branch 'weblate/master' 2023-08-10 09:08:44 +02:00
Allan Nordhøy
a11ccb7cf6 Added translation using Weblate (Norwegian Bokmål) 2023-08-10 03:22:13 +02:00
Bruno Guerreiro
a54241294d Translated using Weblate (Portuguese)
Currently translated at 87.3% (1066 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/pt/
2023-08-09 20:39:29 +02:00
Bazsalanszky
46b509c1fb Merge remote-tracking branch 'origin/master' 2023-08-09 20:39:24 +02:00
Bazsalanszky
b13dd58c70 Basic up/down vote separation
This commit adds separation option of the up and downvote scres for post on the main page.
2023-08-09 20:39:12 +02:00
Bruno Guerreiro
4312b250ce Translated using Weblate (Portuguese)
Currently translated at 86.8% (1061 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/pt/
2023-08-08 16:15:04 +02:00
Alex
ff4c9180a0 Translated using Weblate (French)
Currently translated at 94.1% (1150 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/fr/
2023-08-08 16:15:04 +02:00
Balazs Toldi
be0bd40995 Show NSFW communities on search
There was a bug in the code that caused the nsfw settings to report "false" value in the community search.
2023-08-08 16:13:16 +02:00
Bruno Guerreiro
726d6d0faf Translated using Weblate (Portuguese)
Currently translated at 86.3% (1054 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/pt/
2023-08-08 07:28:03 +02:00
Bruno Guerreiro
14ce356c4d Translated using Weblate (Portuguese)
Currently translated at 86.3% (1054 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/pt/
2023-08-07 15:41:50 +02:00
Bazsalanszky
930a425af5 Merge pull request 'README.md add download badges' (#79) from American_Jesus/Infinity-For-Lemmy:readme-badges into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/79
2023-08-07 13:33:28 +00:00
Generator
7168cecbcb README.md add download badges
Centrer logo image
2023-08-07 14:26:06 +01:00
Bazsalanszky
7f067023e7 Merge pull request 'Fix CI link' (#76) from Gusted/Infinity-For-Lemmy:fix-ci-link into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/76
2023-08-07 12:29:29 +00:00
Bazsalanszky
167aecb696 Fix crashes related to incorrect instance URL 2023-08-07 13:56:20 +02:00
Bazsalanszky
9872e6e806 Linkify community and user names
This commit makes user and community names clickable in post/comments. Closes #71?
2023-08-07 13:49:18 +02:00
Hosted Weblate
05adc343a2 Update translation files
Updated by "Remove blank strings" hook in Weblate.

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/
2023-08-07 09:03:26 +02:00
Anonymous
58e3dfa084 Translated using Weblate (Chinese (Simplified))
Currently translated at 91.8% (1121 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/zh_Hans/
2023-08-07 09:02:59 +02:00
Anonymous
3068423c01 Translated using Weblate (Vietnamese)
Currently translated at 91.1% (1113 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/vi/
2023-08-07 09:02:53 +02:00
Anonymous
3c960f60d1 Translated using Weblate (Ukrainian)
Currently translated at 94.7% (1157 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/uk/
2023-08-07 09:02:47 +02:00
Anonymous
a153fc4afb Translated using Weblate (Turkish)
Currently translated at 91.1% (1113 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/tr/
2023-08-07 09:02:40 +02:00
Anonymous
4a19fbb745 Translated using Weblate (Somali)
Currently translated at 2.9% (36 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/so/
2023-08-07 09:02:34 +02:00
Anonymous
bb8c10fc98 Translated using Weblate (Russian)
Currently translated at 94.7% (1157 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/ru/
2023-08-07 09:02:29 +02:00
Anonymous
97af73f055 Translated using Weblate (Romanian)
Currently translated at 94.7% (1157 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/ro/
2023-08-07 09:02:22 +02:00
Anonymous
73d18082c4 Translated using Weblate (Portuguese)
Currently translated at 85.3% (1042 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/pt/
2023-08-07 09:02:16 +02:00
Anonymous
4b78e80edd Translated using Weblate (Portuguese (Brazil))
Currently translated at 94.7% (1157 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/pt_BR/
2023-08-07 09:02:10 +02:00
Anonymous
78ba4b0fda Translated using Weblate (Polish)
Currently translated at 86.8% (1061 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/pl/
2023-08-07 09:02:04 +02:00
Anonymous
a1c5baac6b Translated using Weblate (Dutch)
Currently translated at 81.7% (998 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/nl/
2023-08-07 09:01:58 +02:00
Anonymous
c4b811090d Translated using Weblate (Japanese)
Currently translated at 81.4% (994 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/ja/
2023-08-07 09:01:51 +02:00
Anonymous
fbdccfb639 Translated using Weblate (Italian)
Currently translated at 91.1% (1113 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/it/
2023-08-07 09:01:45 +02:00
Anonymous
c1162fd618 Translated using Weblate (Hungarian)
Currently translated at 77.8% (951 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/hu/
2023-08-07 09:01:39 +02:00
Anonymous
4d7a148cfe Translated using Weblate (Croatian)
Currently translated at 74.4% (909 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/hr/
2023-08-07 09:01:32 +02:00
Anonymous
c7b1602648 Translated using Weblate (Hindi)
Currently translated at 71.0% (868 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/hi/
2023-08-07 09:01:24 +02:00
Anonymous
a82a454ad2 Translated using Weblate (French)
Currently translated at 82.2% (1004 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/fr/
2023-08-07 09:01:17 +02:00
Anonymous
9533378003 Translated using Weblate (Spanish)
Currently translated at 91.1% (1113 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/es/
2023-08-07 09:01:11 +02:00
Anonymous
dc1edcc78c Translated using Weblate (German)
Currently translated at 94.7% (1157 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/de/
2023-08-07 09:01:06 +02:00
Anonymous
6d8b040f6d Translated using Weblate (Czech)
Currently translated at 91.1% (1113 of 1221 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/cs/
2023-08-07 09:01:00 +02:00
Bazsalanszky
60f07f7707 Empty login fields crash fix
This commit resolves the issue where the app crashes on the Login page if one of the mandatory filed is left empty.
2023-08-07 08:45:44 +02:00
balazs
f6b7130d0c Translated using Weblate (Hungarian)
Currently translated at 78.0% (951 of 1218 strings)

Translation: LemmInfinity/Codeberg
Translate-URL: https://hosted.weblate.org/projects/lemminfinity/codeberg/hu/
2023-08-07 08:43:51 +02:00
Bazsalanszky
9fea056063 Empty login fields crash fix
This commit resolves the issue where the app crashes on the Login page if one of the mandatory filed is left empty.
2023-08-07 08:43:42 +02:00
Gusted
859e9ab5d6 Fix CI link
The CI link currently links to an blank page, I'm not sure if it worked before and got broken by the [`1.0.0`](https://github.com/woodpecker-ci/woodpecker/releases/tag/v1.0.0) release of Woodpecker CI.
2023-08-06 20:31:13 +00:00
Bazsalanszky
4821718407 Add weblate to contributions section of readme
This is a requirement for getting the Libre plan on weblate.
2023-08-06 22:14:39 +02:00
Bazsalanszky
67a13f8ecb Fix "show all comments" button crash
Closes #72
2023-08-06 21:31:15 +02:00
Bazsalanszky
40e4782b32 Minor fix to ViewUserDetailActivity 2023-08-06 10:38:47 +02:00
Bazsalanszky
2ab5ab3ce5 Fix posting from community home page
This commit resolves the issue that made the app crash after trying to post from a community home page. Closes #70
2023-08-06 09:37:46 +02:00
Bazsalanszky
88fb054640 Fix bottom navigation bar profile button
Closes #69
2023-08-06 09:21:10 +02:00
Bazsalanszky
4ce8fd6a63 Fix view all comments button 2023-08-05 19:53:49 +02:00
Balazs Toldi
ffc2d669e5 Show images in comments and post
Replace image links in posts and comments with actual images.
2023-08-05 19:07:23 +02:00
Bazsalanszky
926e1162f0 Removed more reddit related options
Removed options related to reddit, like flairs and awards.
2023-08-05 18:06:50 +02:00
Bazsalanszky
6cf69ee26d Disable downvote button when downvotes are disable on the account's instance
This commit hides the downvote button from account where the instance disabled the downvote functionality.

Note: You need to switch accounts to take effect!
2023-08-05 17:09:48 +02:00
Bazsalanszky
279820c1be Remove award and flair related settings
These do not work on Lemmy. We do not need them.
2023-08-05 16:27:58 +02:00
Bazsalanszky
1d7031f3d4 Fix issues related to image loading
Resolved some issues related to loading icons of users on community pages
2023-08-05 16:20:33 +02:00
Bazsalanszky
252e00b67a Fix issue related to loading community data
In some cases loading the creation date of the community made the app crash. Now it has been resolved.
2023-08-05 16:19:37 +02:00
Bazsalanszky
a8d63c7480 Fix loading community and user images
This commit resolves two issues:
1. Loading community icons on the homepage sometimes showed the wrong community icon
2. Loading user avatars failed before when tried them in the comments
2023-08-05 16:01:28 +02:00
Bazsalanszky
2020172b56 Unsave comment fix
Resolve issue where unsaving the app crashes the app.

Closes #55
2023-08-05 14:41:31 +02:00
Bazsalanszky
2d55a4c8ec Fix issue with NSFW Communites
This commit resolves the issue where posts from NSFW communities appeared on the Home page, but not when opening the community it self.

Closes #49
2023-08-05 14:32:15 +02:00
Bazsalanszky
20a3e0220b Fix CrashReportsFragment url
Now uses the our repo instead of the upstream one!
2023-08-05 14:21:44 +02:00
Bazsalanszky
feeeefa2d2 Possible fix to loading videos on home page 2023-08-05 14:21:08 +02:00
Bazsalanszky
d25137020f Bug report template 2023-08-05 14:19:23 +02:00
Bazsalanszky
3c4fb4162e Merge remote-tracking branch 'origin/master' 2023-08-05 14:17:27 +02:00
Bazsalanszky
28e9ae950e Bug report issue template 2023-08-05 14:16:22 +02:00
Bazsalanszky
888e741aa9 Parse video posts
Parse post with direct links to videos as Video type posts. Autoplay also works with these.
2023-08-05 13:57:07 +02:00
Bazsalanszky
9f7a6e1738 Merge pull request 'I replaced the empty community icon with one that uses a lemmy-like icon instead' (#57) from carrotcake/Infinity-For-Lemmy:new-picture into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/57
2023-08-05 11:34:53 +00:00
Bazsalanszky
76f4a0738f Merge pull request 'Update locale-pt' (#53) from American_Jesus/Infinity-For-Lemmy:locale-pt into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/53
2023-08-05 11:33:16 +00:00
carrotcake
63327946be I replaced the empty community icon with one that uses a lemmy-like icon instead 2023-08-04 22:58:56 -04:00
Bazsalanszky
84d90adc54 Updated fastlane short description 2023-08-04 17:09:36 +02:00
Generator
cf15732a39 fix string 2023-08-04 15:38:14 +01:00
Generator
2eee73753f change Popular to Local 2023-08-04 15:33:37 +01:00
Generator
62d097357a fix strings and typos 2023-08-04 15:29:41 +01:00
Bazsalanszky
c35a690335 Updated README with more accureate information
Updated README to report all the supported features by the app.
2023-08-04 16:17:17 +02:00
Generator
18af76ce92 update locale pt 2023-08-04 15:13:11 +01:00
Bazsalanszky
6e7256d9a5 Minor fix for "Cake day" parsing
It now only shows the date
2023-08-04 15:59:18 +02:00
Bazsalanszky
2af6c5a742 Show more context when loading a single comment
This commit makes it so that when loading a single comment (e.g. from the inbox) it also shows the parent comment.

Closes #47
2023-08-04 15:55:40 +02:00
Bazsalanszky
5c39fddbc6 Fix bug with the "show all comments" button
Fix bug where if the "Show all comments" button is pressed, the original comment disappears.
Closes #36
2023-08-04 15:30:20 +02:00
Bazsalanszky
a708853199 Fix community icon on compact view
Closes #43
2023-08-04 15:22:53 +02:00
Bazsalanszky
acb651cf92 Merge pull request 'Remove reddit related stuff' (#51) from reddit_removal into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/51
2023-08-04 13:06:20 +00:00
Bazsalanszky
562c91acb2 Fix sort types in settings
Closes #25
2023-08-04 15:00:42 +02:00
Bazsalanszky
484f9607b1 Removed description from the community view page
The community's description was shown both on the community page (bellow the subscription button) and on the about page. Now it's only on the about page, to make the UI less cluttered.
Closes #42
2023-08-04 14:38:34 +02:00
Bazsalanszky
9149ee224c Better since time on Community Pages 2023-08-04 14:34:30 +02:00
Bazsalanszky
1bb1d3b9af Fix sort types on search page
Closes #19
2023-08-04 14:05:40 +02:00
Bazsalanszky
0b76390069 View user bug fix
Resolved the issue where clicking on a user from the inbox was not functioning properly.
2023-08-04 13:19:24 +02:00
Bazsalanszky
5de8751079 Remove some reddit specific options from a few places
Removed multireddits. Also remove the "random" option from the "more options" menu
2023-08-04 13:19:24 +02:00
Bazsalanszky
4bfe1b0c02 Remove unused elements from navigation drawer
This makes it more accurate for Lemmy.
2023-08-04 13:19:24 +02:00
Kuro
15c1676d0b Removed mentionings of reddit in english and german and a few mentionings in other languages. 2023-08-04 13:19:24 +02:00
Bazsalanszky
49ff90aad1 Merge pull request 'Removed mentionings of reddit in english and german and a few mentionings in other languages.' (#44) from Kuro/Infinity-For-Lemmy:removing_reddit_strings into master
Reviewed-on: https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/pulls/44
2023-08-04 07:48:20 +00:00
Kuro
6adaaf1965 Removed mentionings of reddit in english and german and a few mentionings in other languages. 2023-08-03 15:28:27 +02:00
Balazs Toldi
6d114f84fa Fix post when editing a text only post 2023-08-03 09:02:08 +02:00
194 changed files with 30287 additions and 23671 deletions

BIN
.assets/IzzyOnDroid.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

BIN
.assets/codeberg.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -0,0 +1,49 @@
---
name: "Bug Report"
about: "Report a Bug!"
title: " [Bug] "
ref: "master"
labels:
- Kind/Bug
---
### Description of the Issue:
<!-- Provide a clear and concise description of what the issue is about. -->
### Steps to Reproduce:
<!-- Explain the steps to reproduce the issue, if applicable. -->
1.
2.
3.
### Expected Behavior:
<!-- Describe what you expected to happen. -->
### Actual Behavior:
<!-- Describe what actually happened. Include screenshots if applicable. -->
### App Information:
- **Version:** <!-- e.g. 1.0.0 -->
- **Device:** <!-- e.g. Samsung Galaxy S10 -->
- **Android Version:** <!-- e.g. Android 11 -->
- **Installation Source:** <!-- e.g. Google Play Store, APK -->
### Log Files:
<!-- If applicable, include log files or error messages related to this issue. -->
### Additional Context:
<!-- Add any other context about the problem here, such as relevant system configuration or screenshots. -->
### Potential Solutions or Workarounds:
<!-- If you know of any potential solutions or workarounds for this issue, please describe them here. -->

View File

@@ -1,4 +1,4 @@
pipeline:
steps:
build:
image: alvrme/alpine-android:android-33-jdk11
commands:
@@ -24,4 +24,6 @@ pipeline:
prerelease: true
note: "This is an alpha release. Expect many bugs and unfinished features!"
when:
event: [ tag ]
event: [ tag ]
when:
event: [ push, tag, pull_request ]

76
.woodpecker/nightly.yaml Normal file
View File

@@ -0,0 +1,76 @@
clone:
git:
image: woodpeckerci/plugin-git
settings:
partial: false
steps:
build:
image: alvrme/alpine-android:android-33-jdk11
commands:
- ./gradlew :app:assembleNightly
sign:
image: alvrme/alpine-android:android-33-jdk11
commands:
- ./scripts/apk-sign.sh eu.toldi.infinityforlemmy.nightly.apk app/build/outputs/apk/nightly/eu.toldi.infinityforlemmy.nightly.apk
secrets: [ APK_KS_PASS, APK_KS, APK_KS_ALIAS ]
pull-repo-config:
image: codeberg.org/freeyourgadget/android-fdroid-tools:latest
commands:
- cd ..
- pwd
- mkdir repoconfig
- cd repoconfig
- pwd
- git clone --depth 1 https://codeberg.org/Bazsalanszky/fdroid-repo-config
- cp /woodpecker/src/codeberg.org/Bazsalanszky/Infinity-For-Lemmy/eu.toldi.infinityforlemmy.nightly.apk fdroid-repo-config/repo/
pull-pages:
image: codeberg.org/freeyourgadget/android-fdroid-tools:latest
commands:
- cd ..
- pwd
- mkdir pages
- cd pages
- pwd
- git clone --depth 2 https://codeberg.org/Bazsalanszky/pages
- cd pages
- git config user.name "CODEBERG CI"
- git config user.email "noreply@nodomain.nodomain"
# reset and remove, later force push, to keep repo size small
- git reset --soft HEAD~1
- git status
update-fdroid-data:
image: cs8898/android-fdroid-sdk:33.0.0
commands:
- pwd
- cd ../repoconfig/fdroid-repo-config/
- echo -n "$${FDROID_KS}" | base64 -d > keystore.p12
- cat keystore.p12 | sha256sum
- sed -i "s|KS_PASS|$${FDROID_KS_PASS}|g" config.yml
- sed -i "s|KEY_PASS|$${FDROID_KEY_PASS}|g" config.yml
- fdroid update
- fdroid deploy
- ls -laR repo
secrets: [ FDROID_KS_PASS, FDROID_KEY_PASS, FDROID_KS ]
push-pages-update-repo:
image: codeberg.org/freeyourgadget/android-fdroid-tools:latest
commands:
- if [ -f .do_not_build ]; then return 0; fi
- cd ../pages/pages/
- git add -A
- git status
- git diff
- ls -lsR fdroid/repo
- git commit -m "autodeploy"
- git remote remove origin
- git remote add origin https://Bazsalanszky:"$${GITEA_ACCESS_TOKEN}"@codeberg.org/Bazsalanszky/pages.git
# force push as we removed all data
- git push -f origin main
- cd ../../
- pwd
- ls -la
secrets: [ GITEA_ACCESS_TOKEN ]
when:
event: cron

View File

@@ -6,31 +6,28 @@
A Lemmy client for Android written in Java. It's a fork of the [Infinity for Reddit](https://github.com/Docile-Alligator/Infinity-For-Reddit) project, currenty in early development.
<img align="right" src="https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/raw/branch/master/fastlane/metadata/android/en-US/images/icon.png" width=200>
</div>
<br>
<div align="center">
<img src="https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/raw/branch/master/fastlane/metadata/android/en-US/images/icon.png" width=256>
[![status-badge](https://ci.codeberg.org/api/badges/12474/status.svg)](https://ci.codeberg.org/12474)
[![status-badge](https://ci.codeberg.org/api/badges/12474/status.svg)](https://ci.codeberg.org/repos/12474)
[![Liberapay patrons](https://img.shields.io/liberapay/patrons/bazsalanszky)](https://liberapay.com/Bazsalanszky)
<a href="https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/issues">Report a Bug</a>
</div>
<br>
<div align="center">
<a href="https://apt.izzysoft.de/fdroid/index/apk/eu.toldi.infinityforlemmy">
<img src="./.assets/IzzyOnDroid.png" height="80">
</a>
<a href="https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/releases/">
<img src="./.assets/codeberg.png" height="80">
</a>
</div>
---
## Action Items for Infinity for Lemmy
@@ -41,15 +38,17 @@ Infinity for Lemmy is currently in the early stages of development. Expect many
- [x] Support for multiple account handling
- [x] Functionality for post upvotes/downvotes
- [x] Functionality to browse comments
- [ ] Capability for creating a new post
- [x] Capability for creating a new post
- [x] Ability to create comments
- [x] Edit/Delete posts and comments
- [x] Basic inbox
- [ ] Elimination of code/string references specific to Reddit
- [ ] Incorporation of private messaging feature
- [ ] Feature for saving posts
- [x] Feature for saving posts/comments
- [x] Resolving links
- [ ] Account editing function
- [ ] Multi community view?
## Contributing
First off, thanks for taking the time to contribute! Contributions are what makes the open source community such an amazing place to learn, inspire, and create. Any contributions you make are **greatly appreciated**.
@@ -65,10 +64,15 @@ Don't forget to give the project a star! Thanks again!
4. Push to the Branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request
Here are other ways you can help:
### Translation
- [Report Bugs](https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/issues)
You can alos help Infinity for Lemmy by translating it to your native langugage! Translations are done via [Weblate](https://translate.codeberg.org/projects/infinity-for-lemmy/app/)!
[![Translation](https://translate.codeberg.org/widgets/infinity-for-lemmy/-/app/multi-auto.svg)](https://translate.codeberg.org/engage/infinity-for-lemmy/)
### Reporting bugs
You can also contribute by [reporting bugs](https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/issues)
<p align="right">(<a href="#top">back to top</a>)</p>
@@ -82,7 +86,6 @@ Distributed under the AGPL-3.0 License. See <a href="https://codeberg.org/Bazsal
[@bazsalanszky@lemmy.toldi.eu](https://lemmy.toldi.eu/u/bazsalanszky) - (Owner)
Project Link: [https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy](https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy)
<p align="right">(<a href="#top">back to top</a>)</p>

View File

@@ -1,5 +1,18 @@
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
def getCommitVersionCode = { ->
try {
def stdout = new ByteArrayOutputStream()
exec {
commandLine 'git', 'rev-list', 'HEAD', '--count'
standardOutput = stdout
}
return Integer.valueOf(stdout.toString().trim())
} catch (ignored) {
return null
}
}
android {
@@ -8,8 +21,8 @@ android {
applicationId "eu.toldi.infinityforlemmy"
minSdk 21
targetSdk 33
versionCode 126
versionName "0.0.6"
versionCode 128
versionName "0.0.8"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
javaCompileOptions {
annotationProcessorOptions {
@@ -18,10 +31,12 @@ android {
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
minifiedRelease {
initWith buildTypes.release
zipAlignEnabled true
@@ -33,7 +48,33 @@ android {
applicationIdSuffix '.debug'
versionNameSuffix ' (DEBUG)'
}
nightly {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
applicationIdSuffix '.nightly'
versionNameSuffix ' (NIGHTLY)'
}
applicationVariants.all { variant ->
variant.resValue "string", "applicationId", variant.applicationId
if (variant.buildType.name == 'nightly') {
variant.outputs.all {
setVersionCodeOverride(getCommitVersionCode())
setVersionNameOverride(variant.versionName)
outputFileName = "${applicationId}.apk"
}
}
}
}
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
@@ -169,6 +210,7 @@ dependencies {
implementation "io.noties.markwon:recycler-table:$markwonVersion"
implementation "io.noties.markwon:simple-ext:$markwonVersion"
implementation "io.noties.markwon:inline-parser:$markwonVersion"
implementation "io.noties.markwon:image-glide:$markwonVersion"
implementation 'com.atlassian.commonmark:commonmark-ext-gfm-tables:0.14.0'
implementation 'me.saket:better-link-movement-method:2.2.0'
@@ -200,3 +242,4 @@ dependencies {
// debugImplementation because LeakCanary should only run in debug builds.
//debugImplementation 'com.squareup.leakcanary:leakcanary-android:x.y'
}

View File

@@ -402,6 +402,11 @@
android:label="@string/subscriptions"
android:parentActivityName=".activities.MainActivity"
android:theme="@style/AppTheme.Slidable" />
<activity
android:name=".activities.BlockedThingListingActivity"
android:label="@string/blocks"
android:parentActivityName=".activities.MainActivity"
android:theme="@style/AppTheme.Slidable" />
<activity
android:name=".activities.SubredditSelectionActivity"
android:label="@string/community_selection_activity_label"

View File

@@ -8,6 +8,7 @@ import dagger.BindsInstance;
import dagger.Component;
import eu.toldi.infinityforlemmy.activities.AccountPostsActivity;
import eu.toldi.infinityforlemmy.activities.AccountSavedThingActivity;
import eu.toldi.infinityforlemmy.activities.BlockedThingListingActivity;
import eu.toldi.infinityforlemmy.activities.CommentActivity;
import eu.toldi.infinityforlemmy.activities.CreateMultiRedditActivity;
import eu.toldi.infinityforlemmy.activities.CustomThemeListingActivity;
@@ -65,7 +66,10 @@ import eu.toldi.infinityforlemmy.activities.ViewVideoActivity;
import eu.toldi.infinityforlemmy.activities.WebViewActivity;
import eu.toldi.infinityforlemmy.activities.WikiActivity;
import eu.toldi.infinityforlemmy.bottomsheetfragments.AccountChooserBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.CommentMoreBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.FlairBottomSheetFragment;
import eu.toldi.infinityforlemmy.fragments.BlockedCommunitiesListingFragment;
import eu.toldi.infinityforlemmy.fragments.BlockedUsersListingFragment;
import eu.toldi.infinityforlemmy.fragments.CommentsListingFragment;
import eu.toldi.infinityforlemmy.fragments.FollowedUsersListingFragment;
import eu.toldi.infinityforlemmy.fragments.HistoryPostFragment;
@@ -73,6 +77,7 @@ import eu.toldi.infinityforlemmy.fragments.InboxFragment;
import eu.toldi.infinityforlemmy.fragments.MorePostsInfoFragment;
import eu.toldi.infinityforlemmy.fragments.MultiRedditListingFragment;
import eu.toldi.infinityforlemmy.fragments.PostFragment;
import eu.toldi.infinityforlemmy.fragments.PrivateMessageFragment;
import eu.toldi.infinityforlemmy.fragments.SidebarFragment;
import eu.toldi.infinityforlemmy.fragments.SubredditListingFragment;
import eu.toldi.infinityforlemmy.fragments.SubscribedSubredditsListingFragment;
@@ -307,6 +312,15 @@ public interface AppComponent {
void inject(MorePostsInfoFragment morePostsInfoFragment);
void inject(BlockedThingListingActivity blockedThingListingActivity);
void inject(BlockedCommunitiesListingFragment blockedCommunitiesListingFragment);
void inject(BlockedUsersListingFragment blockedUsersListingFragment);
void inject(CommentMoreBottomSheetFragment commentMoreBottomSheetFragment);
void inject(PrivateMessageFragment privateMessageFragment);
@Component.Factory
interface Factory {

View File

@@ -1,7 +1,6 @@
package eu.toldi.infinityforlemmy;
import android.os.AsyncTask;
import android.text.Html;
import androidx.annotation.NonNull;
@@ -9,9 +8,6 @@ import org.json.JSONException;
import org.json.JSONObject;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.JSONUtils;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import retrofit2.Call;
import retrofit2.Callback;
@@ -83,7 +79,7 @@ public class FetchMyInfo {
if (!person.isNull("banner")) {
bannerImageUrl = person.getString("banner");
}
display_name = person.getString("name");
display_name = (person.has("display_name")) ? person.getString("display_name") : person.getString("name");
redditDataRoomDatabase.accountDao().updateAccountInfo(name, profileImageUrl, bannerImageUrl);
} catch (JSONException e) {
parseFailed = true;

View File

@@ -10,15 +10,14 @@ import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import eu.toldi.infinityforlemmy.apis.StreamableAPI;
import eu.toldi.infinityforlemmy.network.SortTypeConverterFactory;
import eu.toldi.infinityforlemmy.privatemessage.LemmyPrivateMessageAPI;
import eu.toldi.infinityforlemmy.comment.LemmyCommentAPI;
import eu.toldi.infinityforlemmy.post.LemmyPostAPI;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import okhttp3.ConnectionPool;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.guava.GuavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
@Module(includes = AppModule.class)
abstract class NetworkModule {
@@ -216,4 +215,22 @@ abstract class NetworkModule {
static StreamableAPI provideStreamableApi(@Named("streamable") Retrofit streamableRetrofit) {
return streamableRetrofit.create(StreamableAPI.class);
}
@Provides
@Singleton
static LemmyPostAPI providePostAPI(@Named("no_oauth") RetrofitHolder retrofitHolder) {
return new LemmyPostAPI(retrofitHolder);
}
@Provides
@Singleton
static LemmyCommentAPI provideCommentAPI(@Named("no_oauth") RetrofitHolder retrofitHolder) {
return new LemmyCommentAPI(retrofitHolder);
}
@Provides
@Singleton
static LemmyPrivateMessageAPI provideLemmyPrivateMessageAPI(@Named("base") RetrofitHolder retrofit) {
return new LemmyPrivateMessageAPI(retrofit);
}
}

View File

@@ -110,9 +110,9 @@ class ParseSubscribedThing {
boolean postingRestrictedToMods = community.getBoolean("posting_restricted_to_mods");
int instanceId = community.getInt("instance_id");
int subscribers = data.getJSONObject("counts").getInt("subscribers");
boolean isBlocked = data.getBoolean("blocked");
newSubscribedSubredditData.add(new SubscribedSubredditData(id, title, LemmyUtils.actorID2FullName(actorId), iconUrl, accountName));
newSubredditData.add(new SubredditData(id,name,title,description,removed,published,updated,deleted,nsfw,actorId,local,iconUrl,bannerImageUrl,hidden,postingRestrictedToMods,instanceId,subscribers));
newSubredditData.add(new SubredditData(id, name, title, description, removed, published, updated, deleted, nsfw, actorId, local, iconUrl, bannerImageUrl, hidden, postingRestrictedToMods, instanceId, subscribers, isBlocked));
}
} catch (JSONException e) {

View File

@@ -13,6 +13,10 @@ import androidx.sqlite.db.SupportSQLiteDatabase;
import eu.toldi.infinityforlemmy.account.Account;
import eu.toldi.infinityforlemmy.account.AccountDao;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityDao;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserDao;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
import eu.toldi.infinityforlemmy.customtheme.CustomTheme;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeDao;
import eu.toldi.infinityforlemmy.multireddit.AnonymousMultiredditSubreddit;
@@ -38,7 +42,7 @@ import eu.toldi.infinityforlemmy.user.UserData;
@Database(entities = {Account.class, SubredditData.class, SubscribedSubredditData.class, UserData.class,
SubscribedUserData.class, MultiReddit.class, CustomTheme.class, RecentSearchQuery.class,
ReadPost.class, PostFilter.class, PostFilterUsage.class, AnonymousMultiredditSubreddit.class}, version = 23)
ReadPost.class, PostFilter.class, PostFilterUsage.class, AnonymousMultiredditSubreddit.class, BlockedUserData.class, BlockedCommunityData.class}, version = 26)
public abstract class RedditDataRoomDatabase extends RoomDatabase {
public static RedditDataRoomDatabase create(final Context context) {
@@ -49,7 +53,7 @@ public abstract class RedditDataRoomDatabase extends RoomDatabase {
MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13,
MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17,
MIGRATION_17_18, MIGRATION_18_19, MIGRATION_19_20, MIGRATION_20_21,
MIGRATION_21_22, MIGRATION_22_23)
MIGRATION_21_22, MIGRATION_22_23, MIGRATION_23_24, MIGRATION_24_25, MIGRATION_25_26)
.build();
}
@@ -59,6 +63,10 @@ public abstract class RedditDataRoomDatabase extends RoomDatabase {
public abstract SubscribedSubredditDao subscribedSubredditDao();
public abstract BlockedUserDao blockedUserDao();
public abstract BlockedCommunityDao blockedCommunityDao();
public abstract UserDao userDao();
public abstract SubscribedUserDao subscribedUserDao();
@@ -383,4 +391,29 @@ public abstract class RedditDataRoomDatabase extends RoomDatabase {
}
}
};
private static final Migration MIGRATION_23_24 = new Migration(23, 24) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE accounts ADD COLUMN can_downvote INTEGER DEFAULT 1 NOT NULL");
}
};
private static final Migration MIGRATION_24_25 = new Migration(24, 25) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE subreddits ADD COLUMN blocked INTEGER DEFAULT 1 NOT NULL");
}
};
private static final Migration MIGRATION_25_26 = new Migration(25, 26) {
@Override
public void migrate(@NonNull SupportSQLiteDatabase database) {
database.execSQL("CREATE TABLE blocked_users" +
"(name TEXT, id INTEGER NOT NULL, avatar TEXT, qualified_name TEXT, account_name TEXT NOT NULL, PRIMARY KEY( id, account_name))");
database.execSQL("CREATE TABLE blocked_communities" +
"(name TEXT, icon TEXT, id INTEGER NOT NULL, qualified_name TEXT, account_name TEXT NOT NULL, PRIMARY KEY( id, account_name))");
}
};
}

View File

@@ -24,7 +24,11 @@ public class RetrofitHolder {
}
public String getBaseURL() {
return baseURL;
String result = baseURL;
if (baseURL.endsWith("/")) {
result = baseURL.substring(0, baseURL.length() - 1);
}
return result;
}
public RetrofitHolder(OkHttpClient okHttpClient) {

View File

@@ -43,7 +43,7 @@ public class SortType {
TOP_TWELVE_HOURS("TopTwelveHour", "Top"),
TOP_DAY("TopDay", "Top"),
TOP_WEEK("TopWeek", "Top"),
TOP_MONTH("month", "Top"),
TOP_MONTH("TopMonth", "Top"),
TOP_THREE_MONTHS("TopThreeMonths", "Top"),
TOP_SIX_MONTHS("TopSixMonths", "Top"),
TOP_NINE_MONTHS("TopNineMonths", "Top"),

View File

@@ -32,6 +32,9 @@ public class Account implements Parcelable {
@ColumnInfo(name = "instance_url")
private String instance_url;
@ColumnInfo(name = "can_downvote")
private boolean canDownvote = true;
@Ignore
protected Account(Parcel in) {
accountName = in.readString();
@@ -42,6 +45,7 @@ public class Account implements Parcelable {
code = in.readString();
isCurrentUser = in.readByte() != 0;
instance_url = in.readString();
canDownvote = in.readByte() != 0;
}
public static final Creator<Account> CREATOR = new Creator<Account>() {
@@ -58,11 +62,11 @@ public class Account implements Parcelable {
@Ignore
public static Account getAnonymousAccount() {
return new Account("-",null, null, null, null, null, false,null);
return new Account("-",null, null, null, null, null, false,null,true);
}
public Account(@NonNull String accountName, String display_name, String accessToken, String code,
String profileImageUrl, String bannerImageUrl, boolean isCurrentUser,String instance_url) {
String profileImageUrl, String bannerImageUrl, boolean isCurrentUser,String instance_url, boolean canDownvote) {
this.accountName = accountName;
this.display_name = display_name;
this.accessToken = accessToken;
@@ -71,6 +75,7 @@ public class Account implements Parcelable {
this.bannerImageUrl = bannerImageUrl;
this.isCurrentUser = isCurrentUser;
this.instance_url = instance_url;
this.canDownvote = canDownvote;
}
@NonNull
@@ -116,6 +121,10 @@ public class Account implements Parcelable {
return instance_url;
}
public boolean canDownvote() {
return canDownvote;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(accountName);
@@ -126,5 +135,6 @@ public class Account implements Parcelable {
dest.writeString(code);
dest.writeByte((byte) (isCurrentUser ? 1 : 0));
dest.writeString(instance_url);
dest.writeByte((byte) (canDownvote ? 1 : 0));
}
}

View File

@@ -0,0 +1,85 @@
package eu.toldi.infinityforlemmy.account;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
import eu.toldi.infinityforlemmy.subreddit.ParseSubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Retrofit;
public class FetchBlockedThings {
public static void fetchBlockedThings(Retrofit mRetrofit, String accessToken, String accountName, FetchBlockedThingsListener fetchBlockedThingsListener) {
LemmyAPI lemmyAPI = mRetrofit.create(LemmyAPI.class);
Call<String> call = lemmyAPI.getSiteInfo(accessToken);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, retrofit2.Response<String> response) {
if (response.isSuccessful()) {
String siteInfo = response.body();
if (siteInfo != null) {
List<BlockedUserData> blockedUsers = new ArrayList<>();
List<BlockedCommunityData> blockedCommunities = new ArrayList<>();
try {
JSONObject siteInfoJson = new JSONObject(siteInfo).getJSONObject("my_user");
JSONArray blockedUsersJson = (siteInfoJson.has("person_blocks")) ? siteInfoJson.getJSONArray("person_blocks") : null;
JSONArray blockedCommunitiesJson = (siteInfoJson.has("community_blocks")) ? siteInfoJson.getJSONArray("community_blocks") : null;
if (blockedUsersJson != null) {
for (int i = 0; i < blockedUsersJson.length(); i++) {
JSONObject blockedUserJson = blockedUsersJson.getJSONObject(i).getJSONObject("target");
int id = blockedUserJson.getInt("id");
String name = blockedUserJson.getString("name");
String avatar = "";
if (blockedUserJson.has("avatar"))
avatar = blockedUserJson.getString("avatar");
String qualifiedName = LemmyUtils.actorID2FullName(blockedUserJson.getString("actor_id"));
BlockedUserData blockedUserData = new BlockedUserData(id, name, avatar, qualifiedName, accountName);
blockedUsers.add(blockedUserData);
}
}
if (blockedCommunitiesJson != null) {
for (int i = 0; i < blockedCommunitiesJson.length(); i++) {
JSONObject blockedCommunityJson = blockedCommunitiesJson.getJSONObject(i);
SubredditData blockedCommunityData = ParseSubredditData.parseSubredditData(blockedCommunityJson, true);
blockedCommunities.add(new BlockedCommunityData(blockedCommunityData, accountName));
}
}
fetchBlockedThingsListener.onFetchBlockedThingsSuccess(blockedUsers, blockedCommunities);
} catch (JSONException e) {
e.printStackTrace();
fetchBlockedThingsListener.onFetchBlockedThingsFailure();
}
} else {
fetchBlockedThingsListener.onFetchBlockedThingsFailure();
}
} else {
fetchBlockedThingsListener.onFetchBlockedThingsFailure();
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
fetchBlockedThingsListener.onFetchBlockedThingsFailure();
}
});
}
public interface FetchBlockedThingsListener {
void onFetchBlockedThingsSuccess(List<BlockedUserData> blockedUsers, List<BlockedCommunityData> blockedCommunities);
void onFetchBlockedThingsFailure();
}
}

View File

@@ -0,0 +1,462 @@
package eu.toldi.infinityforlemmy.activities;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.view.inputmethod.EditorInfoCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.tabs.TabLayout;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.List;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.ActivityToolbarInterface;
import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.account.FetchBlockedThings;
import eu.toldi.infinityforlemmy.asynctasks.InsertBlockedThings;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.ViewPagerBugFixed;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
import eu.toldi.infinityforlemmy.events.GoBackToMainPageEvent;
import eu.toldi.infinityforlemmy.events.SwitchAccountEvent;
import eu.toldi.infinityforlemmy.fragments.BlockedCommunitiesListingFragment;
import eu.toldi.infinityforlemmy.fragments.BlockedUsersListingFragment;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
import retrofit2.Retrofit;
public class BlockedThingListingActivity extends BaseActivity implements ActivityToolbarInterface {
public static final String EXTRA_SHOW_MULTIREDDITS = "ESM";
private static final String INSERT_SUBSCRIBED_SUBREDDIT_STATE = "ISSS";
private static final String INSERT_MULTIREDDIT_STATE = "IMS";
@BindView(R.id.coordinator_layout_subscribed_thing_listing_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_subscribed_thing_listing_activity)
AppBarLayout appBarLayout;
@BindView(R.id.collapsing_toolbar_layout_subscribed_thing_listing_activity)
CollapsingToolbarLayout collapsingToolbarLayout;
@BindView(R.id.toolbar_subscribed_thing_listing_activity)
Toolbar toolbar;
@BindView(R.id.search_edit_text_subscribed_thing_listing_activity)
EditText searchEditText;
@BindView(R.id.tab_layout_subscribed_thing_listing_activity)
TabLayout tabLayout;
@BindView(R.id.view_pager_subscribed_thing_listing_activity)
ViewPagerBugFixed viewPager;
@BindView(R.id.fab_subscribed_thing_listing_activity)
FloatingActionButton fab;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("no_oauth")
RetrofitHolder mRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
@Named("current_account")
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
private String mAccessToken;
private String mAccountName;
private String mAccountQualifiedName;
private boolean mInsertSuccess = false;
private boolean mInsertMultiredditSuccess = false;
private boolean showMultiReddits = false;
private SectionsPagerAdapter sectionsPagerAdapter;
private Menu mMenu;
@Override
protected void onCreate(Bundle savedInstanceState) {
((Infinity) getApplication()).getAppComponent().inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subscribed_thing_listing);
ButterKnife.bind(this);
EventBus.getDefault().register(this);
applyCustomTheme();
if (mSharedPreferences.getBoolean(SharedPreferencesUtils.SWIPE_RIGHT_TO_GO_BACK, true)) {
mSliderPanel = Slidr.attach(this);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
Window window = getWindow();
if (isChangeStatusBarIconColor()) {
addOnOffsetChangedListener(appBarLayout);
}
if (isImmersiveInterface()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.setDecorFitsSystemWindows(false);
} else {
window.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
adjustToolbar(toolbar);
int navBarHeight = getNavBarHeight();
if (navBarHeight > 0) {
CoordinatorLayout.LayoutParams params = (CoordinatorLayout.LayoutParams) fab.getLayoutParams();
params.bottomMargin += navBarHeight;
fab.setLayoutParams(params);
}
}
}
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setToolbarGoToTop(toolbar);
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, "-");
mAccountQualifiedName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_QUALIFIED_NAME, "-");
if (savedInstanceState != null) {
mInsertSuccess = savedInstanceState.getBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE);
mInsertMultiredditSuccess = savedInstanceState.getBoolean(INSERT_MULTIREDDIT_STATE);
} else {
showMultiReddits = getIntent().getBooleanExtra(EXTRA_SHOW_MULTIREDDITS, false);
}
if (mAccessToken == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
searchEditText.setImeOptions(searchEditText.getImeOptions() | EditorInfoCompat.IME_FLAG_NO_PERSONALIZED_LEARNING);
}
searchEditText.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) {
}
@Override
public void afterTextChanged(Editable editable) {
sectionsPagerAdapter.changeSearchQuery(editable.toString());
}
});
initializeViewPagerAndLoadSubscriptions();
}
@Override
public SharedPreferences getDefaultSharedPreferences() {
return mSharedPreferences;
}
@Override
protected CustomThemeWrapper getCustomThemeWrapper() {
return mCustomThemeWrapper;
}
@Override
protected void applyCustomTheme() {
coordinatorLayout.setBackgroundColor(mCustomThemeWrapper.getBackgroundColor());
applyAppBarLayoutAndCollapsingToolbarLayoutAndToolbarTheme(appBarLayout, collapsingToolbarLayout, toolbar);
applyTabLayoutTheme(tabLayout);
applyFABTheme(fab, mSharedPreferences.getBoolean(SharedPreferencesUtils.USE_CIRCULAR_FAB, false));
searchEditText.setTextColor(mCustomThemeWrapper.getToolbarPrimaryTextAndIconColor());
searchEditText.setHintTextColor(mCustomThemeWrapper.getToolbarSecondaryTextColor());
}
private void initializeViewPagerAndLoadSubscriptions() {
fab.setOnClickListener(view -> {
Intent intent = new Intent(this, CreateMultiRedditActivity.class);
startActivity(intent);
});
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOffscreenPageLimit(2);
if (viewPager.getCurrentItem() != 2) {
fab.hide();
}
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
if (position == 0) {
unlockSwipeRightToGoBack();
fab.hide();
} else {
lockSwipeRightToGoBack();
if (position != 2) {
fab.hide();
} else {
fab.show();
}
}
}
});
tabLayout.setupWithViewPager(viewPager);
if (showMultiReddits) {
viewPager.setCurrentItem(2, false);
}
loadBlocks(false);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.subscribed_thing_listing_activity, menu);
mMenu = menu;
applyMenuItemTheme(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
if (item.getItemId() == R.id.action_search_subscribed_thing_listing_activity) {
item.setVisible(false);
searchEditText.setVisibility(View.VISIBLE);
searchEditText.requestFocus();
if (searchEditText.requestFocus()) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchEditText, InputMethodManager.SHOW_IMPLICIT);
}
return true;
} else if (item.getItemId() == android.R.id.home) {
if (searchEditText.getVisibility() == View.VISIBLE) {
Utils.hideKeyboard(this);
searchEditText.setVisibility(View.GONE);
searchEditText.setText("");
mMenu.findItem(R.id.action_search_subscribed_thing_listing_activity).setVisible(true);
sectionsPagerAdapter.changeSearchQuery("");
return true;
}
finish();
return true;
}
return false;
}
@Override
public void onBackPressed() {
if (searchEditText.getVisibility() == View.VISIBLE) {
Utils.hideKeyboard(this);
searchEditText.setVisibility(View.GONE);
searchEditText.setText("");
mMenu.findItem(R.id.action_search_subscribed_thing_listing_activity).setVisible(true);
sectionsPagerAdapter.changeSearchQuery("");
} else {
super.onBackPressed();
}
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(INSERT_SUBSCRIBED_SUBREDDIT_STATE, mInsertSuccess);
outState.putBoolean(INSERT_MULTIREDDIT_STATE, mInsertMultiredditSuccess);
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
public void loadBlocks(boolean forceLoad) {
if (mAccessToken != null && !(!forceLoad && mInsertSuccess)) {
FetchBlockedThings.fetchBlockedThings(mRetrofit.getRetrofit(), mAccessToken, mAccountQualifiedName, new FetchBlockedThings.FetchBlockedThingsListener() {
@Override
public void onFetchBlockedThingsSuccess(List<BlockedUserData> blockedUsers, List<BlockedCommunityData> blockedCommunities) {
InsertBlockedThings.insertBlockedThings(mExecutor, new Handler(), mRedditDataRoomDatabase, mAccountQualifiedName,
blockedCommunities, blockedUsers, () -> {
mInsertSuccess = true;
sectionsPagerAdapter.stopRefreshProgressbar();
});
}
@Override
public void onFetchBlockedThingsFailure() {
}
});
}
}
@Subscribe
public void onAccountSwitchEvent(SwitchAccountEvent event) {
finish();
}
@Subscribe
public void goBackToMainPageEvent(GoBackToMainPageEvent event) {
finish();
}
@Override
public void onLongPress() {
if (sectionsPagerAdapter != null) {
sectionsPagerAdapter.goBackToTop();
}
}
@Override
public void lockSwipeRightToGoBack() {
if (mSliderPanel != null) {
mSliderPanel.lock();
}
}
@Override
public void unlockSwipeRightToGoBack() {
if (mSliderPanel != null) {
mSliderPanel.unlock();
}
}
private class SectionsPagerAdapter extends FragmentPagerAdapter {
private BlockedCommunitiesListingFragment blockedCommunitiesListingFragment;
private BlockedUsersListingFragment followedUsersListingFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
}
@NonNull
@Override
public Fragment getItem(int position) {
switch (position) {
default:
case 0: {
BlockedCommunitiesListingFragment fragment = new BlockedCommunitiesListingFragment();
Bundle bundle = new Bundle();
bundle.putBoolean(BlockedCommunitiesListingFragment.EXTRA_IS_SUBREDDIT_SELECTION, false);
bundle.putString(BlockedCommunitiesListingFragment.EXTRA_ACCOUNT_NAME, mAccountName);
bundle.putString(BlockedCommunitiesListingFragment.EXTRA_ACCOUNT_QUALIFIED_NAME, mAccountQualifiedName);
bundle.putString(BlockedCommunitiesListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
fragment.setArguments(bundle);
return fragment;
}
case 1: {
BlockedUsersListingFragment fragment = new BlockedUsersListingFragment();
Bundle bundle = new Bundle();
bundle.putString(BlockedUsersListingFragment.EXTRA_ACCOUNT_NAME, mAccountQualifiedName);
bundle.putString(BlockedUsersListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
fragment.setArguments(bundle);
return fragment;
}
}
}
@Override
public int getCount() {
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return Utils.getTabTextWithCustomFont(typeface, getString(R.string.communities));
case 1:
return Utils.getTabTextWithCustomFont(typeface, getString(R.string.users));
case 2:
return Utils.getTabTextWithCustomFont(typeface, getString(R.string.multi_reddits));
}
return null;
}
@NonNull
@Override
public Object instantiateItem(@NonNull ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
if (position == 0) {
blockedCommunitiesListingFragment = (BlockedCommunitiesListingFragment) fragment;
} else if (position == 1) {
followedUsersListingFragment = (BlockedUsersListingFragment) fragment;
}
return fragment;
}
void stopRefreshProgressbar() {
if (blockedCommunitiesListingFragment != null) {
((FragmentCommunicator) blockedCommunitiesListingFragment).stopRefreshProgressbar();
}
if (followedUsersListingFragment != null) {
((FragmentCommunicator) followedUsersListingFragment).stopRefreshProgressbar();
}
}
void goBackToTop() {
if (viewPager.getCurrentItem() == 0) {
blockedCommunitiesListingFragment.goBackToTop();
} else if (viewPager.getCurrentItem() == 1) {
followedUsersListingFragment.goBackToTop();
}
}
void changeSearchQuery(String searchQuery) {
if (blockedCommunitiesListingFragment != null) {
blockedCommunitiesListingFragment.changeSearchQuery(searchQuery);
}
if (followedUsersListingFragment != null) {
followedUsersListingFragment.changeSearchQuery(searchQuery);
}
}
}
}

View File

@@ -513,8 +513,8 @@ public class CommentActivity extends BaseActivity implements UploadImageEnabledA
int start = Math.max(binding.commentCommentEditText.getSelectionStart(), 0);
int end = Math.max(binding.commentCommentEditText.getSelectionEnd(), 0);
binding.commentCommentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
"[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
"![" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "![]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
}
@Override

View File

@@ -345,7 +345,7 @@ public class EditCommentActivity extends BaseActivity implements UploadImageEnab
int start = Math.max(contentEditText.getSelectionStart(), 0);
int end = Math.max(contentEditText.getSelectionEnd(), 0);
contentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
"[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
"![" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "![]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
}
}

View File

@@ -174,7 +174,7 @@ public class EditPostActivity extends BaseActivity implements UploadImageEnabled
mGlide = Glide.with(this);
if (mPost.getUrl().matches(picturePattern)) {
if (mPost.getUrl() != null && mPost.getUrl().matches(picturePattern)) {
loadImage();
}
@@ -308,7 +308,7 @@ public class EditPostActivity extends BaseActivity implements UploadImageEnabled
isSubmitting = true;
Snackbar.make(coordinatorLayout, R.string.posting, Snackbar.LENGTH_SHORT).show();
mRetrofit.getRetrofit().create(LemmyAPI.class).postUpdate(new EditPostDTO(mPost.getId(), titleEditText.getText().toString(), linkEditText.getText().toString(), contentEditText.getText().toString(), mPost.isNSFW(), null, mAccessToken))
mRetrofit.getRetrofit().create(LemmyAPI.class).postUpdate(new EditPostDTO(mPost.getId(), titleEditText.getText().toString(), (linkEditText.getText().toString().isEmpty()) ? null : linkEditText.getText().toString(), contentEditText.getText().toString(), mPost.isNSFW(), null, mAccessToken))
.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
@@ -456,7 +456,7 @@ public class EditPostActivity extends BaseActivity implements UploadImageEnabled
int start = Math.max(contentEditText.getSelectionStart(), 0);
int end = Math.max(contentEditText.getSelectionEnd(), 0);
contentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
"[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
"![" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "![]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
}
}

View File

@@ -272,7 +272,7 @@ public class FilteredPostsActivity extends BaseActivity implements SortTypeSelec
switch (postType) {
case PostPagingSource.TYPE_FRONT_PAGE:
case PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE:
getSupportActionBar().setTitle(R.string.home);
getSupportActionBar().setTitle(R.string.subscribed_feed);
break;
case PostPagingSource.TYPE_SEARCH:
getSupportActionBar().setTitle(R.string.search);

View File

@@ -55,6 +55,7 @@ import eu.toldi.infinityforlemmy.events.PassPrivateMessageEvent;
import eu.toldi.infinityforlemmy.events.PassPrivateMessageIndexEvent;
import eu.toldi.infinityforlemmy.events.SwitchAccountEvent;
import eu.toldi.infinityforlemmy.fragments.InboxFragment;
import eu.toldi.infinityforlemmy.fragments.PrivateMessageFragment;
import eu.toldi.infinityforlemmy.message.CommentInteraction;
import eu.toldi.infinityforlemmy.message.FetchMessage;
import eu.toldi.infinityforlemmy.message.ReadMessage;
@@ -180,7 +181,7 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
if (i == EditorInfo.IME_ACTION_DONE) {
Utils.hideKeyboard(this);
Intent pmIntent = new Intent(this, SendPrivateMessageActivity.class);
pmIntent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, thingEditText.getText().toString());
//pmIntent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, thingEditText.getText().toString());
startActivity(pmIntent);
return true;
}
@@ -193,7 +194,7 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
-> {
Utils.hideKeyboard(this);
Intent pmIntent = new Intent(this, SendPrivateMessageActivity.class);
pmIntent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, thingEditText.getText().toString());
//pmIntent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, thingEditText.getText().toString());
startActivity(pmIntent);
})
.setNegativeButton(R.string.cancel, null)
@@ -330,7 +331,7 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
if (resultCode == RESULT_OK && requestCode == SEARCH_USER_REQUEST_CODE && data != null) {
String username = data.getStringExtra(SearchActivity.EXTRA_RETURN_USER_NAME);
Intent intent = new Intent(this, SendPrivateMessageActivity.class);
intent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, username);
//intent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, username);
startActivity(intent);
}
}
@@ -441,7 +442,7 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
@NonNull
@Override
public Fragment createFragment(int position) {
InboxFragment fragment = new InboxFragment();
Fragment fragment = new InboxFragment();
Bundle bundle = new Bundle();
bundle.putString(InboxFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
switch (position) {
@@ -450,11 +451,9 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
break;
case 1:
bundle.putString(InboxFragment.EXTRA_MESSAGE_WHERE, FetchMessage.WHERE_MENTIONS);
fragment.setArguments(bundle);
break;
case 2:
bundle.putString(InboxFragment.EXTRA_MESSAGE_WHERE, FetchMessage.WHERE_MESSAGES);
fragment.setArguments(bundle);
fragment = new PrivateMessageFragment();
break;
}
fragment.setArguments(bundle);

View File

@@ -79,9 +79,9 @@ public class LinkResolverActivity extends AppCompatActivity {
private Uri getRedditUriByPath(String path) {
if (path.charAt(0) != '/') {
return Uri.parse("https://www.reddit.com/" + path);
return Uri.parse(mRetrofit.getBaseURL() + path);
} else {
return Uri.parse("https://www.reddit.com" + path);
return Uri.parse(mRetrofit.getBaseURL() + path);
}
}
@@ -91,6 +91,10 @@ public class LinkResolverActivity extends AppCompatActivity {
((Infinity) getApplication()).getAppComponent().inject(this);
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
if (mAccessToken != null) {
String instance = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_INSTANCE, null);
mRetrofit.setBaseURL(instance);
}
Uri uri = getIntent().getData();
if (uri == null) {
@@ -227,6 +231,7 @@ public class LinkResolverActivity extends AppCompatActivity {
intent.putExtra(ViewPostDetailActivity.EXTRA_MESSAGE_FULLNAME, messageFullname);
intent.putExtra(ViewPostDetailActivity.EXTRA_NEW_ACCOUNT_NAME, newAccountName);
intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_ID, comment.getId());
intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_PARENT_ID, comment.getParentId());
startActivity(intent);
}
@@ -246,6 +251,7 @@ public class LinkResolverActivity extends AppCompatActivity {
intent.putExtra(ViewPostDetailActivity.EXTRA_MESSAGE_FULLNAME, messageFullname);
intent.putExtra(ViewPostDetailActivity.EXTRA_NEW_ACCOUNT_NAME, newAccountName);
intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_ID, comment.getId());
intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_PARENT_ID, comment.getParentId());
startActivity(intent);
}

View File

@@ -6,6 +6,7 @@ import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.util.Log;
import android.util.Patterns;
import android.view.InflateException;
@@ -26,6 +27,8 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.Executor;
import javax.inject.Inject;
@@ -43,6 +46,8 @@ import eu.toldi.infinityforlemmy.asynctasks.ParseAndInsertNewAccount;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
import eu.toldi.infinityforlemmy.dto.AccountLoginDTO;
import eu.toldi.infinityforlemmy.site.FetchSiteInfo;
import eu.toldi.infinityforlemmy.site.SiteInfo;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
import retrofit2.Call;
@@ -137,15 +142,18 @@ public class LoginActivity extends BaseActivity {
loginButton.setOnClickListener(view -> {
Log.i("LoginActivity", "Login button clicked");
if(!checkFields())
return;
loginButton.setEnabled(false);
progressBar.setVisibility(ProgressBar.VISIBLE);
String username = username_input.getText().toString().trim();
String instance = correctURL(instance_input.getText().toString().trim());
if (!Patterns.WEB_URL.matcher(instance).matches()) {
instance_input.setError("Invalid instance URL");
try {
URL urlObj = new URL(instance);
instance = urlObj.getProtocol() + "://" + urlObj.getHost() + "/";
} catch (MalformedURLException e) {
instance_input.setError("Invalid URL");
Toast.makeText(LoginActivity.this, "Invalid instance URL", Toast.LENGTH_SHORT).show();
loginButton.setEnabled(true);
progressBar.setVisibility(ProgressBar.GONE);
return;
}
Log.i("LoginActivity", "Instance: " + instance);
@@ -153,6 +161,7 @@ public class LoginActivity extends BaseActivity {
mRetrofit.setBaseURL(instance);
LemmyAPI api = mRetrofit.getRetrofit().create(LemmyAPI.class);
Call<String> accessTokenCall = api.userLogin(accountLoginDTO);
String finalInstance = instance;
accessTokenCall.enqueue(new Callback<String>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
@@ -176,17 +185,35 @@ public class LoginActivity extends BaseActivity {
accessToken, new FetchMyInfo.FetchMyInfoListener() {
@Override
public void onFetchMyInfoSuccess(String name, String display_name, String profileImageUrl, String bannerImageUrl) {
FetchSiteInfo.fetchSiteInfo(mRetrofit.getRetrofit(), accessToken, new FetchSiteInfo.FetchSiteInfoListener() {
@Override
public void onFetchSiteInfoSuccess(SiteInfo siteInfo) {
boolean canDownvote = siteInfo.isEnable_downvotes();
ParseAndInsertNewAccount.parseAndInsertNewAccount(mExecutor, new Handler(), name,display_name, accessToken, profileImageUrl, bannerImageUrl, authCode, finalInstance,canDownvote, mRedditDataRoomDatabase.accountDao(),
() -> {
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
finish();
});
mCurrentAccountSharedPreferences.edit().putBoolean(SharedPreferencesUtils.CAN_DOWNVOTE, canDownvote).apply();
}
@Override
public void onFetchSiteInfoFailed() {
ParseAndInsertNewAccount.parseAndInsertNewAccount(mExecutor, new Handler(), name,display_name, accessToken, profileImageUrl, bannerImageUrl, authCode, finalInstance,true, mRedditDataRoomDatabase.accountDao(),
() -> {
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
finish();
});
mCurrentAccountSharedPreferences.edit().putBoolean(SharedPreferencesUtils.CAN_DOWNVOTE, true).apply();
}
});
mCurrentAccountSharedPreferences.edit().putString(SharedPreferencesUtils.ACCESS_TOKEN, accessToken)
.putString(SharedPreferencesUtils.ACCOUNT_NAME, display_name)
.putString(SharedPreferencesUtils.ACCOUNT_QUALIFIED_NAME, name)
.putString(SharedPreferencesUtils.ACCOUNT_INSTANCE,instance)
.putString(SharedPreferencesUtils.ACCOUNT_INSTANCE,finalInstance)
.putString(SharedPreferencesUtils.ACCOUNT_IMAGE_URL, profileImageUrl).apply();
ParseAndInsertNewAccount.parseAndInsertNewAccount(mExecutor, new Handler(), name,display_name, accessToken, profileImageUrl, bannerImageUrl, authCode,instance, mRedditDataRoomDatabase.accountDao(),
() -> {
Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent);
finish();
});
}
@Override
@@ -240,6 +267,26 @@ public class LoginActivity extends BaseActivity {
});
}
private boolean checkFields() {
boolean result = true;
Editable username = username_input.getText();
Editable password = password_input.getText();
Editable instance = instance_input.getText();
if(instance == null || instance.toString().isEmpty()) {
instance_input.setError(getString(R.string.instance_cannot_be_empty));
result = false;
}
if(username == null || username.toString().isEmpty()) {
username_input.setError(getString(R.string.username_cannot_be_empty));
result = false;
}
if(password == null || password.toString().isEmpty()) {
password_input.setError(getString(R.string.password_cannot_be_empty));
result = false;
}
return result;
}
private static String correctURL(String url) {
if (url == null || url.isEmpty()) {
throw new IllegalArgumentException("URL cannot be null or empty");

View File

@@ -481,7 +481,6 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
Intent intent = new Intent(this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName);
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mAccountQualifiedName);
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mAccountName);
startActivity(intent);
break;
}
@@ -808,17 +807,17 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
adapter = new NavigationDrawerRecyclerViewMergedAdapter(this, mSharedPreferences,
mNsfwAndSpoilerSharedPreferences, mNavigationDrawerSharedPreferences, mSecuritySharedPreferences,
mCustomThemeWrapper, mAccountName, new NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener() {
@Override
public void onMenuClick(int stringId) {
Intent intent = null;
if (stringId == R.string.profile) {
intent = new Intent(MainActivity.this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName);
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mAccountQualifiedName);
} else if (stringId == R.string.subscriptions) {
intent = new Intent(MainActivity.this, SubscribedThingListingActivity.class);
} else if (stringId == R.string.multi_reddit) {
mCustomThemeWrapper, mAccountName, mAccountQualifiedName, new NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener() {
@Override
public void onMenuClick(int stringId) {
Intent intent = null;
if (stringId == R.string.profile) {
intent = new Intent(MainActivity.this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName);
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mAccountQualifiedName);
} else if (stringId == R.string.subscriptions) {
intent = new Intent(MainActivity.this, SubscribedThingListingActivity.class);
} else if (stringId == R.string.multi_reddit) {
intent = new Intent(MainActivity.this, SubscribedThingListingActivity.class);
intent.putExtra(SubscribedThingListingActivity.EXTRA_SHOW_MULTIREDDITS, true);
} else if (stringId == R.string.history) {
@@ -883,6 +882,8 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
});
} else if (stringId == R.string.anonymous_account_instance) {
changeAnonymousAccountInstance();
} else if (stringId == R.string.blocks) {
intent = new Intent(MainActivity.this, BlockedThingListingActivity.class);
}
if (intent != null) {
startActivity(intent);
@@ -931,7 +932,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
new TabLayoutMediator(tabLayout, viewPager2, (tab, position) -> {
switch (position) {
case 0:
Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_1_TITLE, getString(R.string.home)));
Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_1_TITLE, getString(R.string.subscribed_feed)));
break;
case 1:
Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_TITLE, getString(R.string.local)));
@@ -1400,10 +1401,6 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
goToUser();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_RANDOM: {
randomThing();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_HIDE_READ_POSTS: {
if (sectionsPagerAdapter != null) {
sectionsPagerAdapter.hideReadPosts();

View File

@@ -511,7 +511,7 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
}
private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, communityData.getQualified_name(), mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl;
displaySubredditIcon();
loadSubredditIconSuccessful = true;
@@ -792,7 +792,7 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
int start = Math.max(contentEditText.getSelectionStart(), 0);
int end = Math.max(contentEditText.getSelectionEnd(), 0);
contentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
"[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
"![" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "![]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
}
}

View File

@@ -488,7 +488,7 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
}
private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName,
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, communityData.getQualified_name(),
mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl;
displaySubredditIcon();
@@ -722,7 +722,7 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
int start = Math.max(contentEditText.getSelectionStart(), 0);
int end = Math.max(contentEditText.getSelectionEnd(), 0);
contentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
"[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
"![" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "![]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
}
}

View File

@@ -450,7 +450,7 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
}
private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName,
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, communityData.getQualified_name(),
mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl;
displaySubredditIcon();
@@ -673,8 +673,8 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
int start = Math.max(contentEditText.getSelectionStart(), 0);
int end = Math.max(contentEditText.getSelectionEnd(), 0);
contentEditText.getText().replace(Math.min(start, end), Math.max(start, end),
"[" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "[]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
"![" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "![]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
}
@Override

View File

@@ -558,10 +558,6 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
goToUser();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_RANDOM: {
random();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_HIDE_READ_POSTS: {
if (sectionsPagerAdapter != null) {
sectionsPagerAdapter.hideReadPosts();
@@ -788,7 +784,8 @@ public class SearchResultActivity extends BaseActivity implements SortTypeSelect
bundle.putString(SubredditListingFragment.EXTRA_QUERY, mQuery);
bundle.putBoolean(SubredditListingFragment.EXTRA_IS_GETTING_SUBREDDIT_INFO, false);
bundle.putString(SubredditListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(SubredditListingFragment.EXTRA_ACCOUNT_NAME, mAccountQualifiedName);
bundle.putString(SubredditListingFragment.EXTRA_ACCOUNT_NAME, mAccountName);
bundle.putString(SubredditListingFragment.EXTRA_ACCOUNT_QUALIFIED_NAME, mAccountQualifiedName);
mFragment.setArguments(bundle);
return mFragment;
}

View File

@@ -119,7 +119,8 @@ public class SearchSubredditsResultActivity extends BaseActivity implements Acti
bundle.putString(SubredditListingFragment.EXTRA_QUERY, query);
bundle.putBoolean(SubredditListingFragment.EXTRA_IS_GETTING_SUBREDDIT_INFO, true);
bundle.putString(SubredditListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(SubredditListingFragment.EXTRA_ACCOUNT_NAME, mAccountQualifiedName);
bundle.putString(SubredditListingFragment.EXTRA_ACCOUNT_NAME, mAccountName);
bundle.putString(SubredditListingFragment.EXTRA_ACCOUNT_QUALIFIED_NAME, mAccountQualifiedName);
bundle.putBoolean(SubredditListingFragment.EXTRA_IS_MULTI_SELECTION, getIntent().getBooleanExtra(EXTRA_IS_MULTI_SELECTION, false));
mFragment.setArguments(bundle);
} else {

View File

@@ -1,8 +1,13 @@
package eu.toldi.infinityforlemmy.activities;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
@@ -10,12 +15,20 @@ import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.snackbar.Snackbar;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
@@ -23,13 +36,24 @@ import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.UploadImageEnabledActivity;
import eu.toldi.infinityforlemmy.UploadedImage;
import eu.toldi.infinityforlemmy.adapters.MarkdownBottomBarRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.bottomsheetfragments.UploadedImagesBottomSheetFragment;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.message.ComposeMessage;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.privatemessage.LemmyPrivateMessageAPI;
import eu.toldi.infinityforlemmy.privatemessage.PrivateMessage;
import eu.toldi.infinityforlemmy.user.BasicUserInfo;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
import eu.toldi.infinityforlemmy.utils.Utils;
public class SendPrivateMessageActivity extends BaseActivity {
public static final String EXTRA_RECIPIENT_USERNAME = "ERU";
public class SendPrivateMessageActivity extends BaseActivity implements UploadImageEnabledActivity {
public static final String EXTRA_RECIPIENT_USER_INFO = "ERUI";
private static final int PICK_IMAGE_REQUEST_CODE = 100;
private static final int CAPTURE_IMAGE_REQUEST_CODE = 200;
@BindView(R.id.coordinator_layout_send_private_message_activity)
CoordinatorLayout coordinatorLayout;
@BindView(R.id.appbar_layout_send_private_message_activity)
@@ -40,15 +64,20 @@ public class SendPrivateMessageActivity extends BaseActivity {
EditText usernameEditText;
@BindView(R.id.divider_1_send_private_message_activity)
View divider1;
@BindView(R.id.subjet_edit_text_send_private_message_activity)
EditText subjectEditText;
@BindView(R.id.divider_2_send_private_message_activity)
View divider2;
@BindView(R.id.content_edit_text_send_private_message_activity)
EditText messageEditText;
@BindView(R.id.markdown_bottom_bar_recycler_view_send_private_message_activity)
RecyclerView markdownBottomBarRecyclerView;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Named("no_oauth")
RetrofitHolder mRetrofit;
@Inject
Executor mExecutor;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@@ -57,15 +86,24 @@ public class SendPrivateMessageActivity extends BaseActivity {
SharedPreferences mCurrentAccountSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
LemmyPrivateMessageAPI mLemmyPrivateMessageAPI;
private String mAccessToken;
private BasicUserInfo mRecipientBasicUserInfo;
private boolean isSubmitting = false;
private ArrayList<UploadedImage> uploadedImages = new ArrayList<>();
private Uri capturedImageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
((Infinity) getApplication()).getAppComponent().inject(this);
setImmersiveModeNotApplicable();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_private_message);
@@ -77,14 +115,66 @@ public class SendPrivateMessageActivity extends BaseActivity {
addOnOffsetChangedListener(appBarLayout);
}
MarkdownBottomBarRecyclerViewAdapter adapter = new MarkdownBottomBarRecyclerViewAdapter(
mCustomThemeWrapper, new MarkdownBottomBarRecyclerViewAdapter.ItemClickListener() {
@Override
public void onClick(int item) {
MarkdownBottomBarRecyclerViewAdapter.bindEditTextWithItemClickListener(
SendPrivateMessageActivity.this, messageEditText, item);
}
@Override
public void onUploadImage() {
Utils.hideKeyboard(SendPrivateMessageActivity.this);
UploadedImagesBottomSheetFragment fragment = new UploadedImagesBottomSheetFragment();
Bundle arguments = new Bundle();
arguments.putParcelableArrayList(UploadedImagesBottomSheetFragment.EXTRA_UPLOADED_IMAGES,
uploadedImages);
fragment.setArguments(arguments);
fragment.show(getSupportFragmentManager(), fragment.getTag());
}
});
markdownBottomBarRecyclerView.setLayoutManager(new LinearLayoutManagerBugFixed(this,
LinearLayoutManagerBugFixed.HORIZONTAL, false));
markdownBottomBarRecyclerView.setAdapter(adapter);
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
setSupportActionBar(toolbar);
String username = getIntent().getStringExtra(EXTRA_RECIPIENT_USERNAME);
if (username != null) {
usernameEditText.setText(username);
if (savedInstanceState != null) {
mRecipientBasicUserInfo = savedInstanceState.getParcelable(EXTRA_RECIPIENT_USER_INFO);
} else {
mRecipientBasicUserInfo = getIntent().getParcelableExtra(EXTRA_RECIPIENT_USER_INFO);
}
if (mRecipientBasicUserInfo != null) {
usernameEditText.setText(mRecipientBasicUserInfo.getQualifiedName());
usernameEditText.setEnabled(false);
} else {
finish();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_REQUEST_CODE) {
if (data == null) {
Toast.makeText(SendPrivateMessageActivity.this, R.string.error_getting_image, Toast.LENGTH_LONG).show();
return;
}
Utils.uploadImageToReddit(this, mExecutor, mRetrofit,
mAccessToken, messageEditText, coordinatorLayout, data.getData(), uploadedImages);
} else if (requestCode == CAPTURE_IMAGE_REQUEST_CODE) {
Utils.uploadImageToReddit(this, mExecutor, mRetrofit,
mAccessToken, messageEditText, coordinatorLayout, capturedImageUri, uploadedImages);
}
}
}
@Override
@@ -108,12 +198,6 @@ public class SendPrivateMessageActivity extends BaseActivity {
return true;
}
if (subjectEditText.getText() == null || subjectEditText.getText().toString().equals("")) {
isSubmitting = false;
Snackbar.make(coordinatorLayout, R.string.message_subject_required, Snackbar.LENGTH_LONG).show();
return true;
}
if (messageEditText.getText() == null || messageEditText.getText().toString().equals("")) {
isSubmitting = false;
Snackbar.make(coordinatorLayout, R.string.message_content_required, Snackbar.LENGTH_LONG).show();
@@ -125,32 +209,26 @@ public class SendPrivateMessageActivity extends BaseActivity {
Snackbar sendingSnackbar = Snackbar.make(coordinatorLayout, R.string.sending_message, Snackbar.LENGTH_INDEFINITE);
sendingSnackbar.show();
ComposeMessage.composeMessage(mOauthRetrofit, mAccessToken, getResources().getConfiguration().locale,
usernameEditText.getText().toString(), subjectEditText.getText().toString(),
messageEditText.getText().toString(), new ComposeMessage.ComposeMessageListener() {
@Override
public void composeMessageSuccess() {
isSubmitting = false;
item.setEnabled(true);
item.getIcon().setAlpha(255);
Toast.makeText(SendPrivateMessageActivity.this, R.string.send_message_success, Toast.LENGTH_SHORT).show();
finish();
}
mLemmyPrivateMessageAPI.sendPrivateMessage(mAccessToken, mRecipientBasicUserInfo.getId(), messageEditText.getText().toString(), new LemmyPrivateMessageAPI.PrivateMessageSentListener() {
@Override
public void onPrivateMessageSentSuccess(@NonNull PrivateMessage privateMessage) {
isSubmitting = false;
item.setEnabled(true);
item.getIcon().setAlpha(255);
Toast.makeText(SendPrivateMessageActivity.this, R.string.send_message_success, Toast.LENGTH_SHORT).show();
finish();
}
@Override
public void composeMessageFailed(String errorMessage) {
isSubmitting = false;
sendingSnackbar.dismiss();
item.setEnabled(true);
item.getIcon().setAlpha(255);
@Override
public void onPrivateMessageSentError() {
isSubmitting = false;
sendingSnackbar.dismiss();
item.setEnabled(true);
item.getIcon().setAlpha(255);
if (errorMessage == null || errorMessage.equals("")) {
Snackbar.make(coordinatorLayout, R.string.send_message_failed, Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(coordinatorLayout, errorMessage, Snackbar.LENGTH_LONG).show();
}
}
});
Snackbar.make(coordinatorLayout, R.string.send_message_failed, Snackbar.LENGTH_LONG).show();
}
});
}
}
return false;
@@ -159,6 +237,7 @@ public class SendPrivateMessageActivity extends BaseActivity {
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(EXTRA_RECIPIENT_USER_INFO, mRecipientBasicUserInfo);
}
@Override
@@ -177,19 +256,49 @@ public class SendPrivateMessageActivity extends BaseActivity {
applyAppBarLayoutAndCollapsingToolbarLayoutAndToolbarTheme(appBarLayout, null, toolbar);
int primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
usernameEditText.setTextColor(primaryTextColor);
subjectEditText.setTextColor(primaryTextColor);
messageEditText.setTextColor(primaryTextColor);
int secondaryTextColor = mCustomThemeWrapper.getSecondaryTextColor();
usernameEditText.setHintTextColor(secondaryTextColor);
subjectEditText.setHintTextColor(secondaryTextColor);
messageEditText.setHintTextColor(secondaryTextColor);
int dividerColor = mCustomThemeWrapper.getDividerColor();
divider1.setBackgroundColor(dividerColor);
divider2.setBackgroundColor(dividerColor);
if (typeface != null) {
usernameEditText.setTypeface(typeface);
subjectEditText.setTypeface(typeface);
messageEditText.setTypeface(typeface);
}
}
@Override
public void uploadImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
getResources().getString(R.string.select_from_gallery)), PICK_IMAGE_REQUEST_CODE);
}
@Override
public void captureImage() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
capturedImageUri = FileProvider.getUriForFile(this, "eu.toldi.infinityforlemmy.provider",
File.createTempFile("captured_image", ".jpg", getExternalFilesDir(Environment.DIRECTORY_PICTURES)));
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedImageUri);
startActivityForResult(pictureIntent, CAPTURE_IMAGE_REQUEST_CODE);
} catch (IOException ex) {
Toast.makeText(this, R.string.error_creating_temp_file, Toast.LENGTH_SHORT).show();
} catch (ActivityNotFoundException e) {
Toast.makeText(this, R.string.no_camera_available, Toast.LENGTH_SHORT).show();
}
}
@Override
public void insertImageUrl(UploadedImage uploadedImage) {
int start = Math.max(messageEditText.getSelectionStart(), 0);
int end = Math.max(messageEditText.getSelectionEnd(), 0);
messageEditText.getText().replace(Math.min(start, end), Math.max(start, end),
"![" + uploadedImage.imageName + "](" + uploadedImage.imageUrl + ")",
0, "![]()".length() + uploadedImage.imageName.length() + uploadedImage.imageUrl.length());
}
}

View File

@@ -73,7 +73,6 @@ import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
import retrofit2.Retrofit;
;
public class SubscribedThingListingActivity extends BaseActivity implements ActivityToolbarInterface {
@@ -233,7 +232,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
});
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
viewPager.setOffscreenPageLimit(3);
viewPager.setOffscreenPageLimit(1);
if (viewPager.getCurrentItem() != 2) {
fab.hide();
}
@@ -358,7 +357,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
}
if (!(!forceLoad && mInsertMultiredditSuccess)) {
loadMultiReddits();
//loadMultiReddits();
}
}
@@ -412,7 +411,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
public void success() {
Toast.makeText(SubscribedThingListingActivity.this,
R.string.delete_multi_reddit_success, Toast.LENGTH_SHORT).show();
loadMultiReddits();
//loadMultiReddits();
}
@Override
@@ -439,7 +438,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
@Subscribe
public void onRefreshMultiRedditsEvent(RefreshMultiRedditsEvent event) {
loadMultiReddits();
//loadMultiReddits();
}
@Override
@@ -477,6 +476,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
@Override
public Fragment getItem(int position) {
switch (position) {
default:
case 0: {
SubscribedSubredditsListingFragment fragment = new SubscribedSubredditsListingFragment();
Bundle bundle = new Bundle();
@@ -487,28 +487,12 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
fragment.setArguments(bundle);
return fragment;
}
case 1: {
FollowedUsersListingFragment fragment = new FollowedUsersListingFragment();
Bundle bundle = new Bundle();
bundle.putString(FollowedUsersListingFragment.EXTRA_ACCOUNT_NAME, mAccountName == null ? "-" : mAccountName);
bundle.putString(FollowedUsersListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
fragment.setArguments(bundle);
return fragment;
}
default: {
MultiRedditListingFragment fragment = new MultiRedditListingFragment();
Bundle bundle = new Bundle();
bundle.putString(MultiRedditListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(MultiRedditListingFragment.EXTRA_ACCOUNT_NAME, mAccountName == null ? "-" : mAccountName);
fragment.setArguments(bundle);
return fragment;
}
}
}
@Override
public int getCount() {
return 3;
return 1;
}
@Override

View File

@@ -946,10 +946,6 @@ public class ViewMultiRedditDetailActivity extends BaseActivity implements SortT
goToUser();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_RANDOM: {
random();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_HIDE_READ_POSTS: {
if (mFragment instanceof PostFragment) {
((PostFragment) mFragment).hideReadPosts();

View File

@@ -95,6 +95,7 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
public static final String EXTRA_POST_ID = "EPI";
public static final String EXTRA_POST_LIST_POSITION = "EPLP";
public static final String EXTRA_SINGLE_COMMENT_ID = "ESCI";
public static final String EXTRA_SINGLE_COMMENT_PARENT_ID = "ESCPI";
public static final String EXTRA_CONTEXT_NUMBER = "ECN";
public static final String EXTRA_MESSAGE_FULLNAME = "ENI";
public static final String EXTRA_NEW_ACCOUNT_NAME = "ENAN";
@@ -870,6 +871,7 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
bundle.putParcelable(ViewPostDetailFragment.EXTRA_POST_DATA, post);
bundle.putInt(ViewPostDetailFragment.EXTRA_POST_LIST_POSITION, position);
bundle.putInt(ViewPostDetailFragment.EXTRA_SINGLE_COMMENT_ID, getIntent().getIntExtra(EXTRA_SINGLE_COMMENT_ID, 0));
bundle.putInt(ViewPostDetailFragment.EXTRA_SINGLE_COMMENT_PARENT_ID, getIntent().getIntExtra(EXTRA_SINGLE_COMMENT_PARENT_ID, 0));
bundle.putString(ViewPostDetailFragment.EXTRA_CONTEXT_NUMBER, getIntent().getStringExtra(EXTRA_CONTEXT_NUMBER));
bundle.putString(ViewPostDetailFragment.EXTRA_MESSAGE_FULLNAME, getIntent().getStringExtra(EXTRA_MESSAGE_FULLNAME));
} else {
@@ -891,6 +893,7 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
bundle.putInt(ViewPostDetailFragment.EXTRA_POST_LIST_POSITION, postListPosition);
}
bundle.putInt(ViewPostDetailFragment.EXTRA_SINGLE_COMMENT_ID, getIntent().getIntExtra(EXTRA_SINGLE_COMMENT_ID, 0));
bundle.putInt(ViewPostDetailFragment.EXTRA_SINGLE_COMMENT_PARENT_ID, getIntent().getIntExtra(EXTRA_SINGLE_COMMENT_PARENT_ID, 0));
bundle.putString(ViewPostDetailFragment.EXTRA_CONTEXT_NUMBER, getIntent().getStringExtra(EXTRA_CONTEXT_NUMBER));
bundle.putString(ViewPostDetailFragment.EXTRA_MESSAGE_FULLNAME, getIntent().getStringExtra(EXTRA_MESSAGE_FULLNAME));
}

View File

@@ -5,6 +5,7 @@ import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
@@ -27,6 +28,7 @@ import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import javax.inject.Inject;
@@ -46,14 +48,15 @@ import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.events.PassPrivateMessageEvent;
import eu.toldi.infinityforlemmy.events.PassPrivateMessageIndexEvent;
import eu.toldi.infinityforlemmy.events.RepliedToPrivateMessageEvent;
import eu.toldi.infinityforlemmy.message.Message;
import eu.toldi.infinityforlemmy.message.ReadMessage;
import eu.toldi.infinityforlemmy.message.ReplyMessage;
import eu.toldi.infinityforlemmy.privatemessage.LemmyPrivateMessageAPI;
import eu.toldi.infinityforlemmy.privatemessage.PrivateMessage;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import retrofit2.Retrofit;
public class ViewPrivateMessagesActivity extends BaseActivity implements ActivityToolbarInterface {
public static final String EXTRA_PRIVATE_MESSAGE = "EPM";
public static final String EXTRA_PRIVATE_MESSAGE_INDEX = "EPM";
public static final String EXTRA_MESSAGE_POSITION = "EMP";
private static final String USER_AVATAR_STATE = "UAS";
@@ -91,14 +94,19 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
@Inject
LemmyPrivateMessageAPI mLemmyPrivateMessageAPI;
private LinearLayoutManagerBugFixed mLinearLayoutManager;
private PrivateMessagesDetailRecyclerViewAdapter mAdapter;
@State
Message privateMessage;
PrivateMessage privateMessage;
@State
Message replyTo;
PrivateMessage replyTo;
private String mAccessToken;
private String mAccountName;
private String mAccountQualifiedName;
private String mUserAvatar;
private ArrayList<ProvideUserAvatarCallback> mProvideUserAvatarCallbacks;
private boolean isLoadingUserAvatar = false;
@@ -128,6 +136,11 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit
addOnOffsetChangedListener(mAppBarLayout);
}
Intent intent = getIntent();
privateMessage = intent.getParcelableExtra(EXTRA_PRIVATE_MESSAGE);
Log.i("ViewPrivate", "privateMessage: " + privateMessage);
setSupportActionBar(mToolbar);
setToolbarGoToTop(mToolbar);
@@ -135,6 +148,7 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
mAccountQualifiedName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_QUALIFIED_NAME, null);
if (savedInstanceState != null) {
mUserAvatar = savedInstanceState.getString(USER_AVATAR_STATE);
@@ -144,36 +158,37 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit
bindView();
}
} else {
if (privateMessage != null) {
bindView();
}
EventBus.getDefault().post(new PassPrivateMessageIndexEvent(getIntent().getIntExtra(EXTRA_PRIVATE_MESSAGE_INDEX, -1)));
}
}
private void bindView() {
if (privateMessage != null) {
if (privateMessage.getAuthor().equals(mAccountName)) {
setTitle(privateMessage.getDestination());
if (privateMessage.getCreatorQualifiedName().equals(mAccountQualifiedName)) {
setTitle(privateMessage.getRecipientName());
mToolbar.setOnClickListener(view -> {
if (privateMessage.isDestinationDeleted()) {
return;
}
Intent intent = new Intent(this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, privateMessage.getDestination());
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, privateMessage.getRecipientName());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, privateMessage.getRecipientQualifiedName());
startActivity(intent);
});
} else {
setTitle(privateMessage.getAuthor());
setTitle(privateMessage.getCreatorName());
mToolbar.setOnClickListener(view -> {
if (privateMessage.isAuthorDeleted()) {
return;
}
Intent intent = new Intent(this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, privateMessage.getAuthor());
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, privateMessage.getCreatorName());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, privateMessage.getCreatorQualifiedName());
startActivity(intent);
});
}
}
mAdapter = new PrivateMessagesDetailRecyclerViewAdapter(this, mSharedPreferences,
getResources().getConfiguration().locale, privateMessage, mAccountName, mCustomThemeWrapper);
getResources().getConfiguration().locale, privateMessage, mAccountQualifiedName, mCustomThemeWrapper);
mLinearLayoutManager = new LinearLayoutManagerBugFixed(this);
mLinearLayoutManager.setStackFromEnd(true);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
@@ -184,45 +199,40 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit
if (!mEditText.getText().toString().equals("")) {
//Send Message
if (privateMessage != null) {
ArrayList<Message> replies = privateMessage.getReplies();
List<PrivateMessage> replies = privateMessage.getReplies();
if (replyTo == null) {
replyTo = privateMessage;
}
isSendingMessage = true;
mSendImageView.setColorFilter(mSecondaryTextColor, android.graphics.PorterDuff.Mode.SRC_IN);
ReplyMessage.replyMessage(mEditText.getText().toString(), replyTo.getFullname(),
getResources().getConfiguration().locale, mOauthRetrofit, mAccessToken,
new ReplyMessage.ReplyMessageListener() {
@Override
public void replyMessageSuccess(Message message) {
if (mAdapter != null) {
mAdapter.addReply(message);
}
goToBottom();
mEditText.setText("");
mSendImageView.setColorFilter(mSendMessageIconColor, android.graphics.PorterDuff.Mode.SRC_IN);
isSendingMessage = false;
EventBus.getDefault().post(new RepliedToPrivateMessageEvent(message, getIntent().getIntExtra(EXTRA_MESSAGE_POSITION, -1)));
}
@Override
public void replyMessageFailed(String errorMessage) {
if (errorMessage != null && !errorMessage.equals("")) {
Snackbar.make(mCoordinatorLayout, errorMessage, Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(mCoordinatorLayout, R.string.reply_message_failed, Snackbar.LENGTH_LONG).show();
}
mSendImageView.setColorFilter(mSendMessageIconColor, android.graphics.PorterDuff.Mode.SRC_IN);
isSendingMessage = false;
}
});
mLemmyPrivateMessageAPI.sendPrivateMessage(mAccessToken, replyTo.getCreatorId(), mEditText.getText().toString(), new LemmyPrivateMessageAPI.PrivateMessageSentListener() {
@Override
public void onPrivateMessageSentSuccess(@NonNull PrivateMessage privateMessage) {
if (mAdapter != null) {
mAdapter.addReply(privateMessage);
}
goToBottom();
mEditText.setText("");
isSendingMessage = false;
EventBus.getDefault().post(new RepliedToPrivateMessageEvent(privateMessage, getIntent().getIntExtra(EXTRA_MESSAGE_POSITION, -1)));
}
@Override
public void onPrivateMessageSentError() {
Snackbar.make(mCoordinatorLayout, R.string.reply_message_failed, Snackbar.LENGTH_LONG).show();
mSendImageView.setColorFilter(mSendMessageIconColor, android.graphics.PorterDuff.Mode.SRC_IN);
isSendingMessage = false;
}
});
StringBuilder fullnames = new StringBuilder();
if (privateMessage.isNew()) {
fullnames.append(privateMessage.getFullname()).append(",");
}
if (replies != null && !replies.isEmpty()) {
for (Message m : replies) {
if (m.isNew()) {
for (PrivateMessage m : replies) {
if (!m.getRead()) {
fullnames.append(m).append(",");
}
}

View File

@@ -3,12 +3,14 @@ package eu.toldi.infinityforlemmy.activities;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
@@ -18,6 +20,7 @@ import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
@@ -36,6 +39,7 @@ import androidx.viewpager2.widget.ViewPager2;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.evernote.android.state.State;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.appbar.MaterialToolbar;
@@ -82,6 +86,8 @@ import eu.toldi.infinityforlemmy.bottomsheetfragments.RandomBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTimeBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTypeBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.UrlMenuBottomSheetFragment;
import eu.toldi.infinityforlemmy.community.BlockCommunity;
import eu.toldi.infinityforlemmy.community.CommunityStats;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.NavigationWrapper;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
@@ -162,12 +168,23 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
TextView communityFullNameTextView;
@BindView(R.id.subscriber_count_text_view_view_subreddit_detail_activity)
TextView nSubscribersTextView;
@BindView(R.id.online_subscriber_count_text_view_view_subreddit_detail_activity)
TextView nOnlineSubscribersTextView;
@BindView(R.id.since_text_view_view_subreddit_detail_activity)
TextView sinceTextView;
@BindView(R.id.creation_time_text_view_view_subreddit_detail_activity)
TextView creationTimeTextView;
@BindView(R.id.active_user_count_text_view_view_subreddit_detail_activity)
TextView nActiveUsersTextView;
@BindView(R.id.post_count_text_view_view_subreddit_detail_activity)
TextView nPostsTextView;
@BindView(R.id.comment_count_text_view_view_subreddit_detail_activity)
TextView nCommentsTextView;
@BindView(R.id.subscriber_count_image_view_view_subreddit_detail_activity)
ImageView nSubscribersImageView;
@BindView(R.id.active_user_count_image_view_view_subreddit_detail_activity)
ImageView nActiveUsersImageView;
@BindView(R.id.post_count_image_view_view_subreddit_detail_activity)
ImageView nPostsImageView;
@BindView(R.id.comment_count_image_view_view_subreddit_detail_activity)
ImageView nCommentsImageView;
@BindView(R.id.description_text_view_view_subreddit_detail_activity)
TextView descriptionTextView;
@Inject
@@ -210,6 +227,11 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
private String communityName;
private int communityId;
@State
SubredditData communityData;
@State
CommunityStats mCommunityStats;
private String description;
private String qualifiedName;
@@ -360,19 +382,33 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
mMessageFullname = savedInstanceState.getInt(MESSAGE_FULLNAME_STATE);
mNewAccountName = savedInstanceState.getString(NEW_ACCOUNT_NAME_STATE);
if (mFetchSubredditInfoSuccess) {
nOnlineSubscribersTextView.setText(getString(R.string.online_subscribers_number_detail, mNCurrentOnlineSubscribers));
}
}
checkNewAccountAndBindView();
fetchSubredditData();
if (communityName != null) {
if (communityData != null) {
setupVisibleElements();
}
}
@Override
protected void onStart() {
super.onStart();
Log.e("ViewSubredditDetail", "onStart");
if (communityData != null) {
setupVisibleElements();
} else {
fetchSubredditData();
}
}
@Override
protected void onStop() {
super.onStop();
mFetchSubredditInfoSuccess = false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (sectionsPagerAdapter != null) {
@@ -414,9 +450,13 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
subscribeSubredditChip.setTextColor(mCustomThemeWrapper.getChipTextColor());
int primaryTextColor = mCustomThemeWrapper.getPrimaryTextColor();
nSubscribersTextView.setTextColor(primaryTextColor);
nOnlineSubscribersTextView.setTextColor(primaryTextColor);
sinceTextView.setTextColor(primaryTextColor);
creationTimeTextView.setTextColor(primaryTextColor);
nActiveUsersTextView.setTextColor(primaryTextColor);
nPostsTextView.setTextColor(primaryTextColor);
nCommentsTextView.setTextColor(primaryTextColor);
nSubscribersImageView.setColorFilter(mCustomThemeWrapper.getPrimaryTextColor(), PorterDuff.Mode.SRC_IN);
nActiveUsersImageView.setColorFilter(mCustomThemeWrapper.getPrimaryTextColor(), PorterDuff.Mode.SRC_IN);
nPostsImageView.setColorFilter(mCustomThemeWrapper.getPrimaryTextColor(), PorterDuff.Mode.SRC_IN);
nCommentsImageView.setColorFilter(mCustomThemeWrapper.getPrimaryTextColor(), PorterDuff.Mode.SRC_IN);
descriptionTextView.setTextColor(primaryTextColor);
navigationWrapper.applyCustomTheme(mCustomThemeWrapper.getBottomAppBarIconColor(), mCustomThemeWrapper.getBottomAppBarBackgroundColor());
applyTabLayoutTheme(tabLayout);
@@ -425,9 +465,9 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
subredditNameTextView.setTypeface(typeface);
subscribeSubredditChip.setTypeface(typeface);
nSubscribersTextView.setTypeface(typeface);
nOnlineSubscribersTextView.setTypeface(typeface);
sinceTextView.setTypeface(typeface);
creationTimeTextView.setTypeface(typeface);
nActiveUsersTextView.setTypeface(typeface);
nPostsTextView.setTypeface(typeface);
nCommentsTextView.setTypeface(typeface);
descriptionTextView.setTypeface(typeface);
}
unsubscribedColor = mCustomThemeWrapper.getUnsubscribed();
@@ -551,15 +591,24 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
communityFullNameTextView.setText(qualifiedName);
String nSubscribers = getString(R.string.subscribers_number_detail, subredditData.getNSubscribers());
nSubscribersTextView.setText(nSubscribers);
creationTimeTextView.setText(subredditData.getCreatedUTC());
if (mCommunityStats != null) {
nActiveUsersTextView.setText(getString(R.string.active_users_number_detail, mCommunityStats.getActiveUsers()));
nPostsTextView.setText(getString(R.string.post_count_detail, mCommunityStats.getPosts()));
nCommentsTextView.setText(getString(R.string.comment_count_detail, mCommunityStats.getComments()));
} else {
nActiveUsersTextView.setVisibility(View.GONE);
nPostsTextView.setVisibility(View.GONE);
nCommentsTextView.setVisibility(View.GONE);
nActiveUsersImageView.setVisibility(View.GONE);
nPostsImageView.setVisibility(View.GONE);
nCommentsImageView.setVisibility(View.GONE);
}
description = subredditData.getDescription();
if (hideSubredditDescription || description.equals("")) {
descriptionTextView.setVisibility(View.GONE);
} else {
descriptionTextView.setVisibility(View.VISIBLE);
markwon.setMarkdown(descriptionTextView, description);
}
descriptionTextView.setVisibility(View.GONE);
if (subredditData.isNSFW()) {
if (nsfwWarningBuilder == null
@@ -693,14 +742,15 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
qualifiedName = LemmyUtils.actorID2FullName(communityData.getActorId());
if (communityName == null) {
communityName = communityData.getTitle();
setupVisibleElements();
}
mCommunityStats = communityData.getCommunityStats();
setupVisibleElements();
communityId = communityData.getId();
ViewSubredditDetailActivity.this.communityData = communityData;
setupSubscribeChip();
mNCurrentOnlineSubscribers = nCurrentOnlineSubscribers;
nOnlineSubscribersTextView.setText(getString(R.string.online_subscribers_number_detail, nCurrentOnlineSubscribers));
InsertSubredditData.insertSubredditData(mExecutor, new Handler(), mRedditDataRoomDatabase,
communityData, () -> mFetchSubredditInfoSuccess = true);
}
@@ -733,6 +783,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
case SharedPreferencesUtils.OTHER_ACTIVITIES_BOTTOM_APP_BAR_OPTION_PROFILE: {
Intent intent = new Intent(this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName);
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mAccountQualifiedName);
startActivity(intent);
break;
}
@@ -1126,6 +1177,11 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.view_subreddit_detail_activity, menu);
if (communityData != null && communityData.isBlocked()) {
menu.findItem(R.id.block_community_view_subreddit_detail_activity).setVisible(false);
} else {
menu.findItem(R.id.unblock_community_view_subreddit_detail_activity).setVisible(false);
}
applyMenuItemTheme(menu);
return true;
}
@@ -1154,22 +1210,6 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
PostLayoutBottomSheetFragment postLayoutBottomSheetFragment = new PostLayoutBottomSheetFragment();
postLayoutBottomSheetFragment.show(getSupportFragmentManager(), postLayoutBottomSheetFragment.getTag());
return true;
} else if (itemId == R.id.action_select_user_flair_view_subreddit_detail_activity) {
if (mAccessToken == null) {
Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
Intent selectUserFlairIntent = new Intent(this, SelectUserFlairActivity.class);
selectUserFlairIntent.putExtra(SelectUserFlairActivity.EXTRA_SUBREDDIT_NAME, communityName);
startActivity(selectUserFlairIntent);
return true;
} else if (itemId == R.id.action_add_to_multireddit_view_subreddit_detail_activity) {
if (mAccessToken == null) {
Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
Intent intent = new Intent(this, MultiredditSelectionActivity.class);
startActivityForResult(intent, ADD_TO_MULTIREDDIT_REQUEST_CODE);
} else if (itemId == R.id.action_add_to_post_filter_view_subreddit_detail_activity) {
Intent intent = new Intent(this, PostFilterPreferenceActivity.class);
intent.putExtra(PostFilterPreferenceActivity.EXTRA_SUBREDDIT_NAME, communityName);
@@ -1179,23 +1219,59 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String baseURL = mRetrofit.getBaseURL().endsWith("/") ? mRetrofit.getBaseURL() : mRetrofit.getBaseURL() + "/";
shareIntent.putExtra(Intent.EXTRA_TEXT, baseURL + "/" + qualifiedName);
shareIntent.putExtra(Intent.EXTRA_TEXT, baseURL + "c/" + qualifiedName);
if (shareIntent.resolveActivity(getPackageManager()) != null) {
startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));
} else {
Toast.makeText(this, R.string.no_app, Toast.LENGTH_SHORT).show();
}
return true;
} else if (itemId == R.id.action_go_to_wiki_view_subreddit_detail_activity) {
Intent wikiIntent = new Intent(this, WikiActivity.class);
wikiIntent.putExtra(WikiActivity.EXTRA_SUBREDDIT_NAME, communityName);
wikiIntent.putExtra(WikiActivity.EXTRA_WIKI_PATH, "index");
startActivity(wikiIntent);
return true;
} else if (itemId == R.id.action_contact_mods_view_subreddit_detail_activity) {
Intent intent = new Intent(this, SendPrivateMessageActivity.class);
intent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, "r/" + communityName);
startActivity(intent);
/* Intent intent = new Intent(this, SendPrivateMessageActivity.class);
intent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, "r/" + communityName);*/
//startActivity(intent);
return true;
} else if (itemId == R.id.block_community_view_subreddit_detail_activity) {
if (mAccessToken == null) {
Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.block_community)
.setMessage(R.string.are_you_sure)
.setPositiveButton(R.string.yes, (dialogInterface, i)
-> BlockCommunity.INSTANCE.blockCommunity(mRetrofit.getRetrofit(), communityId, mAccessToken, new BlockCommunity.BlockCommunityListener() {
@Override
public void onBlockCommunitySuccess() {
communityData.setBlocked(true);
Toast.makeText(ViewSubredditDetailActivity.this, R.string.block_community_success, Toast.LENGTH_SHORT).show();
ViewSubredditDetailActivity.this.invalidateOptionsMenu();
sectionsPagerAdapter.refresh(false);
}
@Override
public void onBlockCommunityError() {
Toast.makeText(ViewSubredditDetailActivity.this, R.string.block_community_failed, Toast.LENGTH_SHORT).show();
}
}))
.setNegativeButton(R.string.no, null)
.show();
return true;
} else if (itemId == R.id.unblock_community_view_subreddit_detail_activity) {
BlockCommunity.INSTANCE.unBlockCommunity(mRetrofit.getRetrofit(), communityId, mAccessToken, new BlockCommunity.BlockCommunityListener() {
@Override
public void onBlockCommunitySuccess() {
communityData.setBlocked(false);
Toast.makeText(ViewSubredditDetailActivity.this, R.string.unblock_community_success, Toast.LENGTH_SHORT).show();
ViewSubredditDetailActivity.this.invalidateOptionsMenu();
sectionsPagerAdapter.refresh(false);
}
@Override
public void onBlockCommunityError() {
Toast.makeText(ViewSubredditDetailActivity.this, R.string.unblock_community_failed, Toast.LENGTH_SHORT).show();
}
});
return true;
}
return false;
@@ -1288,27 +1364,27 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
break;
case PostTypeBottomSheetFragment.TYPE_LINK:
intent = new Intent(this, PostLinkActivity.class);
intent.putExtra(PostLinkActivity.EXTRA_SUBREDDIT_NAME, communityName);
intent.putExtra(PostLinkActivity.EXTRA_SUBREDDIT_NAME, qualifiedName);
startActivity(intent);
break;
case PostTypeBottomSheetFragment.TYPE_IMAGE:
intent = new Intent(this, PostImageActivity.class);
intent.putExtra(PostImageActivity.EXTRA_SUBREDDIT_NAME, communityName);
intent.putExtra(PostImageActivity.EXTRA_SUBREDDIT_NAME, qualifiedName);
startActivity(intent);
break;
case PostTypeBottomSheetFragment.TYPE_VIDEO:
intent = new Intent(this, PostVideoActivity.class);
intent.putExtra(PostVideoActivity.EXTRA_SUBREDDIT_NAME, communityName);
intent.putExtra(PostVideoActivity.EXTRA_SUBREDDIT_NAME, qualifiedName);
startActivity(intent);
break;
case PostTypeBottomSheetFragment.TYPE_GALLERY:
intent = new Intent(this, PostGalleryActivity.class);
intent.putExtra(PostGalleryActivity.EXTRA_SUBREDDIT_NAME, communityName);
intent.putExtra(PostGalleryActivity.EXTRA_SUBREDDIT_NAME, qualifiedName);
startActivity(intent);
break;
case PostTypeBottomSheetFragment.TYPE_POLL:
intent = new Intent(this, PostPollActivity.class);
intent.putExtra(PostPollActivity.EXTRA_SUBREDDIT_NAME, communityName);
intent.putExtra(PostPollActivity.EXTRA_SUBREDDIT_NAME, qualifiedName);
startActivity(intent);
}
}
@@ -1402,10 +1478,6 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
goToUser();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_RANDOM: {
random();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_HIDE_READ_POSTS: {
if (sectionsPagerAdapter != null) {
sectionsPagerAdapter.hideReadPosts();

View File

@@ -4,6 +4,7 @@ import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
@@ -20,7 +21,9 @@ import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
@@ -52,6 +55,7 @@ import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.Executor;
@@ -71,11 +75,14 @@ import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.SortTypeSelectionCallback;
import eu.toldi.infinityforlemmy.account.FetchBlockedThings;
import eu.toldi.infinityforlemmy.adapters.SubredditAutocompleteRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.asynctasks.AddSubredditOrUserToMultiReddit;
import eu.toldi.infinityforlemmy.asynctasks.CheckIsFollowingUser;
import eu.toldi.infinityforlemmy.asynctasks.SwitchAccount;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
import eu.toldi.infinityforlemmy.bottomsheetfragments.CopyTextBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.FABMoreOptionsBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.PostLayoutBottomSheetFragment;
@@ -101,11 +108,13 @@ import eu.toldi.infinityforlemmy.post.PostPagingSource;
import eu.toldi.infinityforlemmy.readpost.InsertReadPost;
import eu.toldi.infinityforlemmy.subreddit.ParseSubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.user.BasicUserInfo;
import eu.toldi.infinityforlemmy.user.BlockUser;
import eu.toldi.infinityforlemmy.user.FetchUserData;
import eu.toldi.infinityforlemmy.user.UserDao;
import eu.toldi.infinityforlemmy.user.UserData;
import eu.toldi.infinityforlemmy.user.UserFollowing;
import eu.toldi.infinityforlemmy.user.UserStats;
import eu.toldi.infinityforlemmy.user.UserViewModel;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
@@ -141,6 +150,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
private static final String FETCH_USER_INFO_STATE = "FSIS";
private static final String MESSAGE_FULLNAME_STATE = "MFS";
private static final String NEW_ACCOUNT_NAME_STATE = "NANS";
private static final String NEW_ACCOUNT_QUALIFIED_NAME_STATE = "NAQNS";
@BindView(R.id.coordinator_layout_view_user_detail_activity)
CoordinatorLayout coordinatorLayout;
@@ -165,11 +175,32 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
@BindView(R.id.user_qualified_name_text_view_view_user_detail_activity)
TextView qualifiedNameTextView;
@BindView(R.id.loading_user_progress_indicator_view_user_detail_activity)
ProgressBar progressBar;
@BindView(R.id.subscribe_user_chip_view_user_detail_activity)
Chip subscribeUserChip;
@BindView(R.id.karma_text_view_view_user_detail_activity)
TextView karmaTextView;
@BindView(R.id.cakeday_text_view_view_user_detail_activity)
@BindView(R.id.post_count_text_view_view_user_detail_activity)
TextView postCountTextView;
@BindView(R.id.comment_count_text_view_view_user_detail_activity)
TextView commentCountTextView;
@BindView(R.id.upvote_count_post_text_view_view_user_detail_activity)
TextView upvoteCountPostTextView;
@BindView(R.id.upvote_count_comment_text_view_view_user_detail_activity)
TextView upvoteCountCommentTextView;
@BindView(R.id.posts_count_icon_image_view_view_user_detail_activity)
ImageView postsCountIconImageView;
@BindView(R.id.comments_count_icon_image_view_view_user_detail_activity)
ImageView commentsCountIconImageView;
@BindView(R.id.account_created_cake_icon_image_view_view_user_detail_activity)
ImageView accountCreatedCakeIconImageView;
@BindView(R.id.cake_day_text_view_view_user_detail_activity)
TextView cakedayTextView;
@BindView(R.id.description_text_view_view_user_detail_activity)
TextView descriptionTextView;
@@ -216,6 +247,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
private String mAccountName;
private String mAccountQualifiedName;
private String username;
private String qualifiedName;
private String description;
private boolean subscriptionReady = false;
@@ -238,6 +270,8 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
private UserData mUserData;
private boolean isBlocked;
//private MaterialAlertDialogBuilder nsfwWarningBuilder;
@Override
@@ -288,6 +322,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
mFetchUserInfoSuccess = savedInstanceState.getBoolean(FETCH_USER_INFO_STATE);
mMessageId = savedInstanceState.getInt(MESSAGE_FULLNAME_STATE);
mNewAccountName = savedInstanceState.getString(NEW_ACCOUNT_NAME_STATE);
qualifiedName = savedInstanceState.getString("qualified_name");
}
checkNewAccountAndInitializeViewPager();
@@ -299,9 +334,26 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
}
}
@Override
protected void onStart() {
super.onStart();
if (mUserData != null) {
setupVisibleElements();
} else {
fetchUserInfo();
}
}
@Override
protected void onStop() {
super.onStop();
mFetchUserInfoSuccess = false;
}
private void setupVisibleElements() {
Resources resources = getResources();
String title = username;
progressBar.setVisibility(View.GONE);
userNameTextView.setText(title);
qualifiedNameTextView.setText(qualifiedName);
toolbar.setTitle(title);
@@ -559,8 +611,15 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
getSupportActionBar().setTitle(userFullName);
}
String karma = "";//getString(R.string.karma_info_user_detail, userData.getTotalKarma(), userData.getLinkKarma(), userData.getCommentKarma());
karmaTextView.setText(karma);
cakedayTextView.setText(getString(R.string.cakeday_info, userData.getCakeday()));
cakedayTextView.setText((String) userData.getCakeday());
UserStats userStats = mUserData.getStats();
if (userStats != null) {
postCountTextView.setText(String.valueOf(userStats.getPostCount()));
commentCountTextView.setText(String.valueOf(userStats.getCommentCount()));
upvoteCountPostTextView.setText(String.valueOf(userStats.getPostScore()));
upvoteCountCommentTextView.setText(String.valueOf(userStats.getCommentScore()));
}
if (userData.getDescription() == null || userData.getDescription().equals("")) {
descriptionTextView.setVisibility(View.GONE);
@@ -628,7 +687,13 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
unsubscribedColor = mCustomThemeWrapper.getUnsubscribed();
subscribedColor = mCustomThemeWrapper.getSubscribed();
userNameTextView.setTextColor(mCustomThemeWrapper.getUsername());
karmaTextView.setTextColor(mCustomThemeWrapper.getPrimaryTextColor());
postCountTextView.setTextColor(mCustomThemeWrapper.getPrimaryTextColor());
upvoteCountPostTextView.setTextColor(mCustomThemeWrapper.getPrimaryTextColor());
commentCountTextView.setTextColor(mCustomThemeWrapper.getPrimaryTextColor());
upvoteCountCommentTextView.setTextColor(mCustomThemeWrapper.getPrimaryTextColor());
postsCountIconImageView.setColorFilter(mCustomThemeWrapper.getPrimaryTextColor(), PorterDuff.Mode.SRC_IN);
commentsCountIconImageView.setColorFilter(mCustomThemeWrapper.getPrimaryTextColor(), PorterDuff.Mode.SRC_IN);
accountCreatedCakeIconImageView.setColorFilter(mCustomThemeWrapper.getPrimaryTextColor(), PorterDuff.Mode.SRC_IN);
cakedayTextView.setTextColor(mCustomThemeWrapper.getPrimaryTextColor());
navigationWrapper.applyCustomTheme(mCustomThemeWrapper.getBottomAppBarIconColor(), mCustomThemeWrapper.getBottomAppBarBackgroundColor());
applyFABTheme(navigationWrapper.floatingActionButton, mSharedPreferences.getBoolean(SharedPreferencesUtils.USE_CIRCULAR_FAB, false));
@@ -637,7 +702,10 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
applyTabLayoutTheme(tabLayout);
if (typeface != null) {
userNameTextView.setTypeface(typeface);
karmaTextView.setTypeface(typeface);
postCountTextView.setTypeface(typeface);
upvoteCountPostTextView.setTypeface(typeface);
commentCountTextView.setTypeface(typeface);
upvoteCountCommentTextView.setTypeface(typeface);
cakedayTextView.setTypeface(typeface);
subscribeUserChip.setTypeface(typeface);
descriptionTextView.setTypeface(typeface);
@@ -929,6 +997,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
case SharedPreferencesUtils.OTHER_ACTIVITIES_BOTTOM_APP_BAR_OPTION_PROFILE: {
Intent intent = new Intent(this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName);
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY,mAccountQualifiedName);
startActivity(intent);
break;
}
@@ -1083,8 +1152,27 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
@Override
public void onFetchUserDataSuccess(UserData userData, int inboxCount) {
mUserData = userData;
username = userData.getName();
username = userData.getDisplayName();
setupVisibleElements();
FetchBlockedThings.fetchBlockedThings(mRetrofit.getRetrofit(), mAccessToken, mAccountQualifiedName, new FetchBlockedThings.FetchBlockedThingsListener() {
@Override
public void onFetchBlockedThingsSuccess(List<BlockedUserData> blockedUsers, List<BlockedCommunityData> blockedCommunities) {
for (BlockedUserData blockedUserData : blockedUsers) {
if (blockedUserData.getQualifiedName().equals(qualifiedName)) {
isBlocked = true;
invalidateOptionsMenu();
return;
}
}
isBlocked = false;
invalidateOptionsMenu();
}
@Override
public void onFetchBlockedThingsFailure() {
}
});
new ViewUserDetailActivity.InsertUserDataAsyncTask(mRedditDataRoomDatabase.userDao(), userData,
() -> mFetchUserInfoSuccess = true).execute();
}
@@ -1127,6 +1215,12 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
menu.findItem(R.id.action_block_user_view_user_detail_activity).setVisible(false);
} else {
menu.findItem(R.id.action_edit_profile_view_user_detail_activity).setVisible(false);
if (isBlocked) {
menu.findItem(R.id.action_block_user_view_user_detail_activity).setVisible(false);
menu.findItem(R.id.action_unblock_user_view_user_detail_activity).setVisible(true);
} else {
menu.findItem(R.id.action_unblock_user_view_user_detail_activity).setVisible(false);
}
}
applyMenuItemTheme(menu);
return true;
@@ -1161,7 +1255,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
String baseURL = mRetrofit.getBaseURL().endsWith("/") ? mRetrofit.getBaseURL() : mRetrofit.getBaseURL() + "/";
shareIntent.putExtra(Intent.EXTRA_TEXT, baseURL + qualifiedName);
shareIntent.putExtra(Intent.EXTRA_TEXT, baseURL + "u/" + qualifiedName);
if (shareIntent.resolveActivity(getPackageManager()) != null) {
startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));
} else {
@@ -1175,16 +1269,9 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
}
Intent pmIntent = new Intent(this, SendPrivateMessageActivity.class);
pmIntent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USERNAME, username);
pmIntent.putExtra(SendPrivateMessageActivity.EXTRA_RECIPIENT_USER_INFO, new BasicUserInfo(mUserData.getId(), username, qualifiedName, mUserData.getAvatar(), mUserData.getDisplayName()));
startActivity(pmIntent);
return true;
} else if (itemId == R.id.action_add_to_multireddit_view_user_detail_activity) {
if (mAccessToken == null) {
Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
Intent intent = new Intent(this, MultiredditSelectionActivity.class);
startActivityForResult(intent, ADD_TO_MULTIREDDIT_REQUEST_CODE);
} else if (itemId == R.id.action_add_to_post_filter_view_user_detail_activity) {
Intent intent = new Intent(this, PostFilterPreferenceActivity.class);
intent.putExtra(PostFilterPreferenceActivity.EXTRA_USER_NAME, username);
@@ -1205,10 +1292,13 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
.setTitle(R.string.block_user)
.setMessage(R.string.are_you_sure)
.setPositiveButton(R.string.yes, (dialogInterface, i)
-> BlockUser.blockUser(mOauthRetrofit, mAccessToken, username, new BlockUser.BlockUserListener() {
-> BlockUser.blockUser(mRetrofit.getRetrofit(), mAccessToken, mUserData.getId(), true, new BlockUser.BlockUserListener() {
@Override
public void success() {
Toast.makeText(ViewUserDetailActivity.this, R.string.block_user_success, Toast.LENGTH_SHORT).show();
isBlocked = true;
sectionsPagerAdapter.refresh();
invalidateOptionsMenu();
}
@Override
@@ -1222,6 +1312,25 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
} else if (itemId == R.id.action_edit_profile_view_user_detail_activity) {
startActivity(new Intent(this, EditProfileActivity.class));
return true;
} else if (itemId == R.id.action_unblock_user_view_user_detail_activity) {
if (mAccessToken == null) {
Toast.makeText(this, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
BlockUser.blockUser(mRetrofit.getRetrofit(), mAccessToken, mUserData.getId(), false, new BlockUser.BlockUserListener() {
@Override
public void success() {
isBlocked = false;
Toast.makeText(ViewUserDetailActivity.this, R.string.unblock_user_success, Toast.LENGTH_SHORT).show();
sectionsPagerAdapter.refresh();
invalidateOptionsMenu();
}
@Override
public void failed() {
Toast.makeText(ViewUserDetailActivity.this, R.string.unblock_user_failed, Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
@@ -1270,6 +1379,8 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
outState.putBoolean(FETCH_USER_INFO_STATE, mFetchUserInfoSuccess);
outState.putInt(MESSAGE_FULLNAME_STATE, mMessageId);
outState.putString(NEW_ACCOUNT_NAME_STATE, mNewAccountName);
outState.putString(NEW_ACCOUNT_QUALIFIED_NAME_STATE, mAccountQualifiedName);
outState.putString("qualified_name", qualifiedName);
}
@Override
@@ -1341,10 +1452,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
goToUser();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_RANDOM: {
random();
break;
}
case FABMoreOptionsBottomSheetFragment.FAB_HIDE_READ_POSTS: {
if (sectionsPagerAdapter != null) {
sectionsPagerAdapter.hideReadPosts();

View File

@@ -0,0 +1,377 @@
package eu.toldi.infinityforlemmy.adapters;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
import java.util.concurrent.Executor;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.ViewSubredditDetailActivity;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import me.zhanghai.android.fastscroll.PopupTextProvider;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
public class BlockedCommunitiesRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements PopupTextProvider {
private static final int VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER = 0;
private static final int VIEW_TYPE_FAVORITE_SUBREDDIT = 1;
private static final int VIEW_TYPE_SUBREDDIT_DIVIDER = 2;
private static final int VIEW_TYPE_SUBREDDIT = 3;
private BaseActivity mActivity;
private Executor mExecutor;
private Retrofit mOauthRetrofit;
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private List<BlockedCommunityData> mBlockedCommunityData;
private List<BlockedCommunityData> mFavoriteBlockedCommunityData;
private RequestManager glide;
private ItemClickListener itemClickListener;
private String accessToken;
private String username;
private String userIconUrl;
private boolean hasClearSelectionRow;
private int primaryTextColor;
private int secondaryTextColor;
public BlockedCommunitiesRecyclerViewAdapter(BaseActivity activity, Executor executor, Retrofit oauthRetrofit,
RedditDataRoomDatabase redditDataRoomDatabase,
CustomThemeWrapper customThemeWrapper,
String accessToken) {
mActivity = activity;
mExecutor = executor;
glide = Glide.with(activity);
mOauthRetrofit = oauthRetrofit;
mRedditDataRoomDatabase = redditDataRoomDatabase;
this.accessToken = accessToken;
primaryTextColor = customThemeWrapper.getPrimaryTextColor();
secondaryTextColor = customThemeWrapper.getSecondaryTextColor();
}
public BlockedCommunitiesRecyclerViewAdapter(BaseActivity activity, Executor executor, Retrofit oauthRetrofit,
RedditDataRoomDatabase redditDataRoomDatabase,
CustomThemeWrapper customThemeWrapper,
String accessToken, boolean hasClearSelectionRow,
ItemClickListener itemClickListener) {
this(activity, executor, oauthRetrofit, redditDataRoomDatabase, customThemeWrapper, accessToken);
this.hasClearSelectionRow = hasClearSelectionRow;
this.itemClickListener = itemClickListener;
}
@Override
public int getItemViewType(int position) {
if (mFavoriteBlockedCommunityData != null && mFavoriteBlockedCommunityData.size() > 0) {
if (itemClickListener != null && !hasClearSelectionRow) {
if (position == 0) {
return VIEW_TYPE_SUBREDDIT;
} else if (position == 1) {
return VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER;
} else if (position == mFavoriteBlockedCommunityData.size() + 2) {
return VIEW_TYPE_SUBREDDIT_DIVIDER;
} else if (position <= mFavoriteBlockedCommunityData.size() + 1) {
return VIEW_TYPE_FAVORITE_SUBREDDIT;
} else {
return VIEW_TYPE_SUBREDDIT;
}
} else if (hasClearSelectionRow) {
if (position == 0) {
return VIEW_TYPE_SUBREDDIT;
} else if (position == 1) {
return VIEW_TYPE_SUBREDDIT;
} else if (position == 2) {
return VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER;
} else if (position == mFavoriteBlockedCommunityData.size() + 3) {
return VIEW_TYPE_SUBREDDIT_DIVIDER;
} else if (position <= mFavoriteBlockedCommunityData.size() + 2) {
return VIEW_TYPE_FAVORITE_SUBREDDIT;
} else {
return VIEW_TYPE_SUBREDDIT;
}
} else {
if (position == 0) {
return VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER;
} else if (position == mFavoriteBlockedCommunityData.size() + 1) {
return VIEW_TYPE_SUBREDDIT_DIVIDER;
} else if (position <= mFavoriteBlockedCommunityData.size()) {
return VIEW_TYPE_FAVORITE_SUBREDDIT;
} else {
return VIEW_TYPE_SUBREDDIT;
}
}
} else {
return VIEW_TYPE_SUBREDDIT;
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
switch (i) {
case VIEW_TYPE_FAVORITE_SUBREDDIT_DIVIDER:
return new FavoriteSubredditsDividerViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_favorite_thing_divider, viewGroup, false));
case VIEW_TYPE_FAVORITE_SUBREDDIT:
return new FavoriteSubredditViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_subscribed_thing, viewGroup, false));
case VIEW_TYPE_SUBREDDIT_DIVIDER:
return new AllSubredditsDividerViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_favorite_thing_divider, viewGroup, false));
default:
return new SubredditViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_subscribed_thing, viewGroup, false));
}
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) {
if (viewHolder instanceof SubredditViewHolder) {
String name;
String fullname = "";
String iconUrl;
if (hasClearSelectionRow && viewHolder.getBindingAdapterPosition() == 0) {
((SubredditViewHolder) viewHolder).subredditNameTextView.setText(R.string.all_communities);
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(null));
return;
} else {
int offset = hasClearSelectionRow ? 1 : 0;
BlockedCommunityData communityData = mBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset);
name = mBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getName();
fullname = mBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getQualified_name();
iconUrl = mBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getIconUrl();
if (itemClickListener != null) {
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(communityData));
}
}
if (itemClickListener == null) {
String finalFullname = fullname;
viewHolder.itemView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, name);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_COMMUNITY_FULL_NAME_KEY,
finalFullname);
mActivity.startActivity(intent);
});
}
if (iconUrl != null && !iconUrl.equals("")) {
glide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((SubredditViewHolder) viewHolder).iconGifImageView);
} else {
glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((SubredditViewHolder) viewHolder).iconGifImageView);
}
((SubredditViewHolder) viewHolder).subredditNameTextView.setText(name);
} else if (viewHolder instanceof FavoriteSubredditViewHolder) {
int offset;
if (itemClickListener != null) {
if (hasClearSelectionRow) {
offset = 3;
} else {
offset = 2;
}
} else {
offset = 1;
}
BlockedCommunityData communityData = mFavoriteBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset);
String name = mFavoriteBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getName();
String iconUrl = mFavoriteBlockedCommunityData.get(viewHolder.getBindingAdapterPosition() - offset).getIconUrl();
if (itemClickListener != null) {
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(communityData));
} else {
viewHolder.itemView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, name);
mActivity.startActivity(intent);
});
}
if (iconUrl != null && !iconUrl.equals("")) {
glide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((FavoriteSubredditViewHolder) viewHolder).iconGifImageView);
} else {
glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((FavoriteSubredditViewHolder) viewHolder).iconGifImageView);
}
((FavoriteSubredditViewHolder) viewHolder).subredditNameTextView.setText(name);
}
}
@Override
public int getItemCount() {
if (mBlockedCommunityData != null) {
if (itemClickListener != null) {
return mBlockedCommunityData.size() > 0 ? mBlockedCommunityData.size() + ((hasClearSelectionRow) ? 1 : 0) : 0;
}
return mBlockedCommunityData.size();
}
return 0;
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if (holder instanceof SubredditViewHolder) {
glide.clear(((SubredditViewHolder) holder).iconGifImageView);
} else if (holder instanceof FavoriteSubredditViewHolder) {
glide.clear(((FavoriteSubredditViewHolder) holder).iconGifImageView);
}
}
public void setSubscribedSubreddits(List<BlockedCommunityData> subscribedSubreddits) {
mBlockedCommunityData = subscribedSubreddits;
notifyDataSetChanged();
}
public void setFavoriteSubscribedSubreddits(List<BlockedCommunityData> favoriteBlockedCommunityData) {
mFavoriteBlockedCommunityData = favoriteBlockedCommunityData;
notifyDataSetChanged();
}
public void addUser(String username, String userIconUrl) {
this.username = username;
this.userIconUrl = userIconUrl;
}
@NonNull
@Override
public String getPopupText(int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_SUBREDDIT:
if (hasClearSelectionRow && position == 0) {
return "";
} else if (itemClickListener != null && !hasClearSelectionRow && position == 0) {
return "";
} else if (hasClearSelectionRow && position == 1) {
return "";
} else {
int offset;
if (itemClickListener != null) {
if (hasClearSelectionRow) {
offset = (mFavoriteBlockedCommunityData != null && mFavoriteBlockedCommunityData.size() > 0) ?
mFavoriteBlockedCommunityData.size() + 4 : 0;
} else {
offset = (mFavoriteBlockedCommunityData != null && mFavoriteBlockedCommunityData.size() > 0) ?
mFavoriteBlockedCommunityData.size() + 3 : 0;
}
} else {
offset = (mFavoriteBlockedCommunityData != null && mFavoriteBlockedCommunityData.size() > 0) ?
mFavoriteBlockedCommunityData.size() + 2 : 0;
}
return mBlockedCommunityData.get(position - offset).getName().substring(0, 1).toUpperCase();
}
case VIEW_TYPE_FAVORITE_SUBREDDIT:
int offset;
if (itemClickListener != null) {
if (hasClearSelectionRow) {
offset = 3;
} else {
offset = 2;
}
} else {
offset = 1;
}
return mFavoriteBlockedCommunityData.get(position - offset).getName().substring(0, 1).toUpperCase();
default:
return "";
}
}
public interface ItemClickListener {
void onClick(BlockedCommunityData subredditData);
}
class SubredditViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.thing_icon_gif_image_view_item_subscribed_thing)
GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView subredditNameTextView;
SubredditViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
subredditNameTextView.setTypeface(mActivity.typeface);
}
subredditNameTextView.setTextColor(primaryTextColor);
}
}
class FavoriteSubredditViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.thing_icon_gif_image_view_item_subscribed_thing)
GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView subredditNameTextView;
FavoriteSubredditViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
subredditNameTextView.setTypeface(mActivity.typeface);
}
subredditNameTextView.setTextColor(primaryTextColor);
}
}
class FavoriteSubredditsDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
FavoriteSubredditsDividerViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
dividerTextView.setTypeface(mActivity.typeface);
}
dividerTextView.setText(R.string.favorites);
dividerTextView.setTextColor(secondaryTextColor);
}
}
class AllSubredditsDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
AllSubredditsDividerViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
dividerTextView.setTypeface(mActivity.typeface);
}
dividerTextView.setText(R.string.all);
dividerTextView.setTextColor(secondaryTextColor);
}
}
}

View File

@@ -0,0 +1,216 @@
package eu.toldi.infinityforlemmy.adapters;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import java.util.List;
import java.util.concurrent.Executor;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.ViewUserDetailActivity;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import me.zhanghai.android.fastscroll.PopupTextProvider;
import pl.droidsonroids.gif.GifImageView;
import retrofit2.Retrofit;
public class BlockedUsersRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements PopupTextProvider {
private static final int VIEW_TYPE_FAVORITE_USER_DIVIDER = 0;
private static final int VIEW_TYPE_FAVORITE_USER = 1;
private static final int VIEW_TYPE_USER_DIVIDER = 2;
private static final int VIEW_TYPE_USER = 3;
private List<BlockedUserData> mBlockedUserData;
private List<BlockedUserData> mFavoriteBlockedUserData;
private BaseActivity mActivity;
private Executor mExecutor;
private Retrofit mOauthRetrofit;
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private String mAccessToken;
private RequestManager glide;
private int mPrimaryTextColor;
private int mSecondaryTextColor;
public BlockedUsersRecyclerViewAdapter(BaseActivity activity, Executor executor, Retrofit oauthRetrofit,
RedditDataRoomDatabase redditDataRoomDatabase,
CustomThemeWrapper customThemeWrapper,
String accessToken) {
mActivity = activity;
mExecutor = executor;
mOauthRetrofit = oauthRetrofit;
mRedditDataRoomDatabase = redditDataRoomDatabase;
mAccessToken = accessToken;
glide = Glide.with(activity);
mPrimaryTextColor = customThemeWrapper.getPrimaryTextColor();
mSecondaryTextColor = customThemeWrapper.getSecondaryTextColor();
}
@Override
public int getItemViewType(int position) {
if (mFavoriteBlockedUserData != null && mFavoriteBlockedUserData.size() > 0) {
if (position == 0) {
return VIEW_TYPE_FAVORITE_USER_DIVIDER;
} else if (position == mFavoriteBlockedUserData.size() + 1) {
return VIEW_TYPE_USER_DIVIDER;
} else if (position <= mFavoriteBlockedUserData.size()) {
return VIEW_TYPE_FAVORITE_USER;
} else {
return VIEW_TYPE_USER;
}
} else {
return VIEW_TYPE_USER;
}
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
switch (i) {
case VIEW_TYPE_FAVORITE_USER_DIVIDER:
return new FavoriteUsersDividerViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_favorite_thing_divider, viewGroup, false));
case VIEW_TYPE_USER_DIVIDER:
return new AllUsersDividerViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_favorite_thing_divider, viewGroup, false));
default:
return new UserViewHolder(LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.item_subscribed_thing, viewGroup, false));
}
}
@Override
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) {
if (viewHolder instanceof UserViewHolder) {
int offset = 0;
if (!mBlockedUserData.get(viewHolder.getBindingAdapterPosition() - offset).getAvatar().equals("")) {
glide.load(mBlockedUserData.get(viewHolder.getBindingAdapterPosition() - offset).getAvatar())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((UserViewHolder) viewHolder).iconGifImageView);
} else {
glide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((UserViewHolder) viewHolder).iconGifImageView);
}
((UserViewHolder) viewHolder).userNameTextView.setText(mBlockedUserData.get(viewHolder.getBindingAdapterPosition() - offset).getName());
}
}
@Override
public int getItemCount() {
if (mBlockedUserData != null && mBlockedUserData.size() > 0) {
return mBlockedUserData.size();
}
return 0;
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if (holder instanceof UserViewHolder) {
glide.clear(((UserViewHolder) holder).iconGifImageView);
}
}
public void setSubscribedUsers(List<BlockedUserData> subscribedUsers) {
mBlockedUserData = subscribedUsers;
notifyDataSetChanged();
}
public void setFavoriteSubscribedUsers(List<BlockedUserData> favoriteSubscribedUsers) {
mFavoriteBlockedUserData = favoriteSubscribedUsers;
notifyDataSetChanged();
}
@NonNull
@Override
public String getPopupText(int position) {
switch (getItemViewType(position)) {
case VIEW_TYPE_USER:
int offset = (mFavoriteBlockedUserData != null && mFavoriteBlockedUserData.size() > 0) ?
mFavoriteBlockedUserData.size() + 2 : 0;
return mBlockedUserData.get(position - offset).getName().substring(0, 1).toUpperCase();
case VIEW_TYPE_FAVORITE_USER:
return mFavoriteBlockedUserData.get(position - 1).getName().substring(0, 1).toUpperCase();
default:
return "";
}
}
class UserViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.thing_icon_gif_image_view_item_subscribed_thing)
GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView userNameTextView;
UserViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
userNameTextView.setTypeface(mActivity.typeface);
}
userNameTextView.setTextColor(mPrimaryTextColor);
itemView.setOnClickListener(view -> {
int offset = (mFavoriteBlockedUserData != null && mFavoriteBlockedUserData.size() > 0) ?
mFavoriteBlockedUserData.size() + 2 : 0;
int position = getBindingAdapterPosition() - offset;
if (position >= 0 && mBlockedUserData.size() > position) {
Intent intent = new Intent(mActivity, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mBlockedUserData.get(position).getName());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mBlockedUserData.get(position).getQualifiedName());
mActivity.startActivity(intent);
}
});
}
}
class FavoriteUsersDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
FavoriteUsersDividerViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
dividerTextView.setTypeface(mActivity.typeface);
}
dividerTextView.setText(R.string.favorites);
dividerTextView.setTextColor(mSecondaryTextColor);
}
}
class AllUsersDividerViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.divider_text_view_item_favorite_thing_divider)
TextView dividerTextView;
AllUsersDividerViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
dividerTextView.setTypeface(mActivity.typeface);
}
dividerTextView.setText(R.string.all);
dividerTextView.setTextColor(mSecondaryTextColor);
}
}
}

View File

@@ -472,6 +472,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
Intent intent = new Intent(mActivity, ViewPostDetailActivity.class);
intent.putExtra(ViewPostDetailActivity.EXTRA_POST_ID, comment.getPostId());
intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_ID, comment.getId());
intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_PARENT_ID, comment.getParentId());
mActivity.startActivity(intent);
}
});

View File

@@ -10,6 +10,7 @@ import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spanned;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@@ -98,7 +99,8 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
private Retrofit mOauthRetrofit;
private Markwon mCommentMarkwon;
private String mAccessToken;
private String mAccountName;
private String mAccountQualifiedName;
private Post mPost;
private ArrayList<Comment> mVisibleComments;
@@ -124,6 +126,8 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
private boolean mShowAuthorAvatar;
private boolean mAlwaysShowChildCommentCount;
private boolean mHideTheNumberOfVotes;
private boolean mSeperateUpandDownvote;
private boolean mHideDownvotes;
private int mDepthThreshold;
private CommentRecyclerViewAdapterCallback mCommentRecyclerViewAdapterCallback;
private boolean isInitiallyLoading;
@@ -166,6 +170,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
Post post, Locale locale, Integer singleCommentId,
boolean isSingleCommentThreadMode,
SharedPreferences sharedPreferences,
SharedPreferences currentAccountSharedPreferences,
CommentRecyclerViewAdapterCallback commentRecyclerViewAdapterCallback) {
mActivity = activity;
mFragment = fragment;
@@ -213,7 +218,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
miscPlugin, mCommentTextColor, commentSpoilerBackgroundColor, onLinkLongClickListener);
recycledViewPool = new RecyclerView.RecycledViewPool();
mAccessToken = accessToken;
mAccountName = accountName;
mAccountQualifiedName = accountName;
mPost = post;
mVisibleComments = new ArrayList<>();
loadedComments = new HashSet<>();
@@ -237,6 +242,8 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
mShowAuthorAvatar = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_AUTHOR_AVATAR, false);
mAlwaysShowChildCommentCount = sharedPreferences.getBoolean(SharedPreferencesUtils.ALWAYS_SHOW_CHILD_COMMENT_COUNT, false);
mHideTheNumberOfVotes = sharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_VOTES_IN_COMMENTS, false);
mHideDownvotes = !currentAccountSharedPreferences.getBoolean(SharedPreferencesUtils.CAN_DOWNVOTE, true);
mSeperateUpandDownvote = sharedPreferences.getBoolean(SharedPreferencesUtils.COMMENT_SEPARATE_UP_AND_DOWN_VOTES, true) && !mHideDownvotes;
mDepthThreshold = sharedPreferences.getInt(SharedPreferencesUtils.SHOW_FEWER_TOOLBAR_OPTIONS_THRESHOLD, 5);
mCommentRecyclerViewAdapterCallback = commentRecyclerViewAdapterCallback;
@@ -383,7 +390,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
Drawable moderatorDrawable = Utils.getTintedDrawable(mActivity, R.drawable.ic_verified_user_14dp, mModeratorColor);
((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(
moderatorDrawable, null, null, null);
} else if (comment.getAuthor().equals(mAccountName)) {
} else if (comment.getAuthorQualifiedName().equals(mAccountQualifiedName)) {
((CommentViewHolder) holder).authorTextView.setTextColor(mCurrentUserColor);
Drawable currentUserDrawable = Utils.getTintedDrawable(mActivity, R.drawable.ic_current_user_14dp, mCurrentUserColor);
((CommentViewHolder) holder).authorTextView.setCompoundDrawablesWithIntrinsicBounds(
@@ -392,12 +399,12 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
if (comment.getAuthorIconUrl() == null) {
mFragment.loadIcon(comment.getAuthorQualifiedName(), (authorName, iconUrl) -> {
if (authorName.equals(comment.getAuthor())) {
if (authorName.equals(comment.getAuthorQualifiedName())) {
comment.setAuthorIconUrl(iconUrl);
}
Comment currentComment = getCurrentComment(holder);
if (currentComment != null && authorName.equals(currentComment.getAuthor())) {
if (currentComment != null && authorName.equals(currentComment.getAuthorQualifiedName())) {
mGlide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
@@ -434,6 +441,10 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
((CommentViewHolder) holder).mMarkwonAdapter.setMarkdown(mCommentMarkwon, comment.getCommentMarkdown());
// noinspection NotifyDataSetChanged
((CommentViewHolder) holder).mMarkwonAdapter.notifyDataSetChanged();
if (mHideDownvotes) {
((CommentViewHolder) holder).downvoteButton.setVisibility(View.GONE);
((CommentViewHolder) holder).downvoteTextView.setVisibility(View.GONE);
}
if (!mHideTheNumberOfVotes) {
String commentText = "";
@@ -445,7 +456,21 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType()));
((CommentViewHolder) holder).scoreTextView.setText(commentText);
if (mSeperateUpandDownvote) {
int upvotes = (comment.getVoteType() == 1) ? comment.getUpvotes() + 1 : comment.getUpvotes();
int downvotes = (comment.getVoteType() == -1) ? comment.getDownvotes() + 1 : comment.getDownvotes();
((CommentViewHolder) holder).downvoteTextView.setVisibility(View.VISIBLE);
((CommentViewHolder) holder).scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, upvotes));
((CommentViewHolder) holder).downvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
((CommentViewHolder) holder).scoreTextView.setGravity(Gravity.START);
((CommentViewHolder) holder).scoreTextView.getLayoutParams().width = (int) (32 * mActivity.getResources().getDisplayMetrics().density);
((CommentViewHolder) holder).scoreTextView.setPadding(0, 0, 6, 0);
((CommentViewHolder) holder).downvoteButton.setPadding(24, 0, 12, 0);
((CommentViewHolder) holder).upvoteButton.setPadding(24, 0, 12, 0);
} else {
((CommentViewHolder) holder).scoreTextView.setText(commentText);
}
((CommentViewHolder) holder).topScoreTextView.setText(topScoreText);
} else {
((CommentViewHolder) holder).scoreTextView.setText(mActivity.getString(R.string.vote));
@@ -485,13 +510,21 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN);
((CommentViewHolder) holder).scoreTextView.setTextColor(mUpvotedColor);
((CommentViewHolder) holder).topScoreTextView.setTextColor(mUpvotedColor);
((CommentViewHolder) holder).downvoteTextView.setTextColor(mCommentIconAndInfoColor);
break;
case Comment.VOTE_TYPE_DOWNVOTE:
((CommentViewHolder) holder).downvoteButton
.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
((CommentViewHolder) holder).scoreTextView.setTextColor(mDownvotedColor);
if(mSeperateUpandDownvote) {
((CommentViewHolder) holder).downvoteTextView.setTextColor(mDownvotedColor);
((CommentViewHolder) holder).scoreTextView.setTextColor(mCommentIconAndInfoColor);
} else {
((CommentViewHolder) holder).scoreTextView.setTextColor(mDownvotedColor);
}
((CommentViewHolder) holder).topScoreTextView.setTextColor(mDownvotedColor);
break;
default:
((CommentViewHolder) holder).downvoteTextView.setTextColor(mCommentIconAndInfoColor);
}
if (mPost.isArchived()) {
@@ -537,12 +570,12 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
if (comment.getAuthorIconUrl() == null) {
mFragment.loadIcon(comment.getAuthorQualifiedName(), (authorName, iconUrl) -> {
if (authorName.equals(comment.getAuthor())) {
if (authorName.equals(comment.getAuthorQualifiedName())) {
comment.setAuthorIconUrl(iconUrl);
}
Comment currentComment = getCurrentComment(holder);
if (currentComment != null && authorName.equals(currentComment.getAuthor())) {
if (currentComment != null && authorName.equals(currentComment.getAuthorQualifiedName())) {
mGlide.load(iconUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
@@ -1190,6 +1223,9 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
ImageView upvoteButton;
@BindView(R.id.score_text_view_item_post_comment)
TextView scoreTextView;
@BindView(R.id.downvote_text_view_item_post_comment)
TextView downvoteTextView;
@BindView(R.id.down_vote_button_item_post_comment)
ImageView downvoteButton;
@BindView(R.id.placeholder_item_post_comment)
@@ -1221,6 +1257,8 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
constraintSet.clear(scoreTextView.getId(), ConstraintSet.END);
constraintSet.clear(downvoteButton.getId(), ConstraintSet.START);
constraintSet.clear(downvoteButton.getId(), ConstraintSet.END);
constraintSet.clear(downvoteTextView.getId(), ConstraintSet.START);
constraintSet.clear(downvoteTextView.getId(), ConstraintSet.END);
constraintSet.clear(expandButton.getId(), ConstraintSet.START);
constraintSet.clear(expandButton.getId(), ConstraintSet.END);
constraintSet.clear(saveButton.getId(), ConstraintSet.START);
@@ -1233,8 +1271,15 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
constraintSet.connect(upvoteButton.getId(), ConstraintSet.START, placeholder.getId(), ConstraintSet.END);
constraintSet.connect(scoreTextView.getId(), ConstraintSet.END, downvoteButton.getId(), ConstraintSet.START);
constraintSet.connect(scoreTextView.getId(), ConstraintSet.START, upvoteButton.getId(), ConstraintSet.END);
constraintSet.connect(downvoteButton.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
constraintSet.connect(downvoteButton.getId(), ConstraintSet.START, scoreTextView.getId(), ConstraintSet.END);
if (!mSeperateUpandDownvote) {
constraintSet.connect(downvoteButton.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
constraintSet.connect(downvoteButton.getId(), ConstraintSet.START, scoreTextView.getId(), ConstraintSet.END);
} else {
constraintSet.connect(downvoteButton.getId(), ConstraintSet.END, downvoteTextView.getId(), ConstraintSet.START);
constraintSet.connect(downvoteButton.getId(), ConstraintSet.START, scoreTextView.getId(), ConstraintSet.END);
constraintSet.connect(downvoteTextView.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
constraintSet.connect(downvoteTextView.getId(), ConstraintSet.START, downvoteButton.getId(), ConstraintSet.END);
}
constraintSet.connect(placeholder.getId(), ConstraintSet.END, upvoteButton.getId(), ConstraintSet.START);
constraintSet.connect(placeholder.getId(), ConstraintSet.START, moreButton.getId(), ConstraintSet.END);
constraintSet.connect(moreButton.getId(), ConstraintSet.START, expandButton.getId(), ConstraintSet.END);
@@ -1267,6 +1312,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
editedTextView.setTypeface(mActivity.typeface);
awardsTextView.setTypeface(mActivity.typeface);
scoreTextView.setTypeface(mActivity.typeface);
downvoteTextView.setTypeface(mActivity.typeface);
expandButton.setTypeface(mActivity.typeface);
}
@@ -1298,11 +1344,13 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
commentTimeTextView.setTextColor(mSecondaryTextColor);
authorFlairTextView.setTextColor(mAuthorFlairTextColor);
topScoreTextView.setTextColor(mSecondaryTextColor);
downvoteTextView.setTextColor(mSecondaryTextColor);
editedTextView.setTextColor(mSecondaryTextColor);
awardsTextView.setTextColor(mSecondaryTextColor);
commentDivider.setBackgroundColor(mDividerColor);
upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mCommentIconAndInfoColor);
downvoteTextView.setTextColor(mCommentIconAndInfoColor);
downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
moreButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
expandButton.setTextColor(mCommentIconAndInfoColor);
@@ -1326,7 +1374,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
Comment comment = getCurrentComment(this);
if (comment != null) {
Bundle bundle = new Bundle();
if (!mPost.isArchived() && !mPost.isLocked() && comment.getAuthor().equals(mAccountName)) {
if (!mPost.isArchived() && !mPost.isLocked() && comment.getAuthorQualifiedName().equals(mAccountQualifiedName)) {
bundle.putBoolean(CommentMoreBottomSheetFragment.EXTRA_EDIT_AND_DELETE_AVAILABLE, true);
}
bundle.putString(CommentMoreBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
@@ -1409,12 +1457,22 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mCommentIconAndInfoColor);
downvoteTextView.setTextColor(mCommentIconAndInfoColor);
topScoreTextView.setTextColor(mSecondaryTextColor);
}
if (!mHideTheNumberOfVotes) {
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType()));
if(mSeperateUpandDownvote){
int upvoteCount = (comment.getVoteType() == 1) ? comment.getUpvotes() + 1 : comment.getUpvotes();
int downvoteCount = (comment.getVoteType() == -1) ? comment.getDownvotes() + 1 : comment.getDownvotes();
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
upvoteCount));
downvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
downvoteCount));
}else {
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType()));
}
topScoreTextView.setText(mActivity.getString(R.string.top_score,
Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType())));
@@ -1430,6 +1488,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
upvoteButton.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mUpvotedColor);
topScoreTextView.setTextColor(mUpvotedColor);
downvoteTextView.setTextColor(mCommentIconAndInfoColor);
}
} else {
comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
@@ -1437,14 +1496,24 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mCommentIconAndInfoColor);
topScoreTextView.setTextColor(mSecondaryTextColor);
downvoteTextView.setTextColor(mCommentIconAndInfoColor);
}
}
if (currentPosition == position) {
downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
if (!mHideTheNumberOfVotes) {
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType()));
if(mSeperateUpandDownvote){
int upvoteCount = (comment.getVoteType() == 1) ? comment.getUpvotes() + 1 : comment.getUpvotes();
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
upvoteCount));
int downvoteCount = (comment.getVoteType() == -1) ? comment.getDownvotes() + 1 : comment.getDownvotes();
downvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
downvoteCount));
} else {
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType()));
}
topScoreTextView.setText(mActivity.getString(R.string.top_score,
Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType())));
@@ -1482,20 +1551,34 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
newVoteType = Integer.parseInt(APIUtils.DIR_DOWNVOTE);
downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mDownvotedColor);
if(mSeperateUpandDownvote){
downvoteTextView.setTextColor(mDownvotedColor);
scoreTextView.setTextColor(mCommentIconAndInfoColor);
}else {
scoreTextView.setTextColor(mDownvotedColor);
}
topScoreTextView.setTextColor(mDownvotedColor);
} else {
//Downvoted before
comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
downvoteTextView.setTextColor(mCommentIconAndInfoColor);
scoreTextView.setTextColor(mCommentIconAndInfoColor);
topScoreTextView.setTextColor(mSecondaryTextColor);
}
if (!mHideTheNumberOfVotes) {
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType()));
if(mSeperateUpandDownvote){
int downvotes = (comment.getVoteType() == -1) ? comment.getDownvotes() +1 : comment.getDownvotes();
int upvotes = (comment.getVoteType() == 1) ? comment.getUpvotes() +1 : comment.getUpvotes();
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
upvotes));
downvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
} else {
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType()));
}
topScoreTextView.setText(mActivity.getString(R.string.top_score,
Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType())));
@@ -1510,7 +1593,11 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
if (currentPosition == position) {
downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mDownvotedColor);
if(mSeperateUpandDownvote){
downvoteTextView.setTextColor(mDownvotedColor);
}else {
scoreTextView.setTextColor(mDownvotedColor);
}
topScoreTextView.setTextColor(mDownvotedColor);
}
} else {
@@ -1518,6 +1605,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
if (currentPosition == position) {
downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mCommentIconAndInfoColor);
downvoteTextView.setTextColor(mCommentIconAndInfoColor);
topScoreTextView.setTextColor(mSecondaryTextColor);
}
}
@@ -1525,8 +1613,17 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
if (currentPosition == position) {
upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
if (!mHideTheNumberOfVotes) {
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType()));
if(mSeperateUpandDownvote){
int downvotes = (comment.getVoteType() == -1) ? comment.getDownvotes() +1 : comment.getDownvotes();
int upvotes = (comment.getVoteType() == 1) ? comment.getUpvotes() +1 : comment.getUpvotes();
downvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
upvotes));
} else {
scoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType()));
}
topScoreTextView.setText(mActivity.getString(R.string.top_score,
Utils.getNVotes(mShowAbsoluteNumberOfVotes,
comment.getScore() + comment.getVoteType())));
@@ -1548,7 +1645,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
SaveComment saveComment = new SaveComment();
if (comment.isSaved()) {
comment.setSaved(false);
saveComment.unsaveThing(mOauthRetrofit, mAccessToken, comment.getId(), new SaveThing.SaveThingListener() {
saveComment.unsaveThing(mRetrofit, mAccessToken, comment.getId(), new SaveThing.SaveThingListener() {
@Override
public void success() {
comment.setSaved(false);
@@ -1924,6 +2021,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
if (mActivity != null && mActivity instanceof ViewPostDetailActivity) {
mIsSingleCommentThreadMode = false;
mSingleCommentId = null;
loadedComments.clear();
notifyItemRemoved(0);
mFragment.changeToNormalThreadMode();
}

View File

@@ -554,9 +554,6 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
.into(((PostBaseViewHolder) holder).iconGifImageView);
}
if (holder.getBindingAdapterPosition() >= 0) {
post.setSubredditIconUrl(iconUrl);
}
}
});
} else if (!post.getSubredditIconUrl().equals("")) {
@@ -641,9 +638,12 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
break;
}
if (mPostType == PostPagingSource.TYPE_SUBREDDIT && !mDisplaySubredditName && post.isStickied()) {
if (mPostType == PostPagingSource.TYPE_SUBREDDIT && !mDisplaySubredditName && post.isFeaturedInCommunity() || post.isFeaturedOnInstance()) {
((PostBaseViewHolder) holder).stickiedPostImageView.setVisibility(View.VISIBLE);
mGlide.load(R.drawable.ic_thumbtack_24dp).into(((PostBaseViewHolder) holder).stickiedPostImageView);
if (post.isFeaturedOnInstance()) {
((PostBaseViewHolder) holder).stickiedPostImageView.setColorFilter(mModeratorColor, android.graphics.PorterDuff.Mode.SRC_IN);
}
}
if (post.isArchived()) {
@@ -1079,9 +1079,6 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
.into(((PostCompactBaseViewHolder) holder).iconGifImageView);
}
if (holder.getBindingAdapterPosition() >= 0) {
post.setSubredditIconUrl(iconUrl);
}
}
});
} else if (!post.getSubredditIconUrl().equals("")) {
@@ -1210,7 +1207,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
}
}
if (mPostType == PostPagingSource.TYPE_SUBREDDIT && !mDisplaySubredditName && post.isStickied()) {
if (mPostType == PostPagingSource.TYPE_SUBREDDIT && !mDisplaySubredditName && post.isFeaturedInCommunity()) {
((PostCompactBaseViewHolder) holder).stickiedPostImageView.setVisibility(View.VISIBLE);
mGlide.load(R.drawable.ic_thumbtack_24dp).into(((PostCompactBaseViewHolder) holder).stickiedPostImageView);
}

View File

@@ -42,7 +42,7 @@ import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration;
import io.noties.markwon.core.MarkwonTheme;
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin;
import io.noties.markwon.inlineparser.BangInlineProcessor;
import io.noties.markwon.image.glide.GlideImagesPlugin;
import io.noties.markwon.inlineparser.HtmlInlineProcessor;
import io.noties.markwon.inlineparser.MarkwonInlineParserPlugin;
import io.noties.markwon.linkify.LinkifyPlugin;
@@ -105,7 +105,6 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<CommentInteract
mMarkwon = Markwon.builder(mActivity)
.usePlugin(MarkwonInlineParserPlugin.create(plugin -> {
plugin.excludeInlineProcessor(HtmlInlineProcessor.class);
plugin.excludeInlineProcessor(BangInlineProcessor.class);
}))
.usePlugin(new AbstractMarkwonPlugin() {
@Override
@@ -129,6 +128,7 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<CommentInteract
.usePlugin(StrikethroughPlugin.create())
.usePlugin(MovementMethodPlugin.create(new SpoilerAwareMovementMethod()))
.usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
.usePlugin(GlideImagesPlugin.create(mActivity))
.build();
mAccessToken = accessToken;
if (where.equals(FetchMessage.WHERE_MESSAGES)) {
@@ -182,6 +182,9 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<CommentInteract
intent.putExtra(ViewPostDetailActivity.EXTRA_POST_ID, message.getComment().getPostId());
intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_ID, message.getComment().getId());
if(message.getComment().getDepth() > 0) {
intent.putExtra(ViewPostDetailActivity.EXTRA_SINGLE_COMMENT_PARENT_ID, message.getComment().getParentId());
}
mActivity.startActivity(intent);
} else if (mMessageType == FetchMessage.MESSAGE_TYPE_PRIVATE_MESSAGE) {
Intent intent = new Intent(mActivity, ViewPrivateMessagesActivity.class);
@@ -215,7 +218,7 @@ public class MessageRecyclerViewAdapter extends PagedListAdapter<CommentInteract
Intent intent = new Intent(mActivity, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, message.getComment().getAuthor());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, message.getComment().getCommunityQualifiedName());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, message.getComment().getAuthorQualifiedName());
mActivity.startActivity(intent);
});
}

View File

@@ -15,6 +15,7 @@ import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Spanned;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
@@ -56,6 +57,7 @@ import com.libRG.CustomTextView;
import java.util.ArrayList;
import java.util.Locale;
import java.util.concurrent.Executor;
import java.util.regex.Pattern;
import javax.inject.Provider;
@@ -170,9 +172,14 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
private boolean mHideUpvoteRatio;
private boolean mHideTheNumberOfAwards;
private boolean mHideSubredditAndUserPrefix;
private boolean mShowDisplayNames;
private boolean mHideTheNumberOfVotes;
private boolean mSeperateUpvoteAndDownvote;
private boolean mHideTheNumberOfComments;
private boolean mSeparatePostAndComments;
private boolean mHideDownvotes;
private boolean mLegacyAutoplayVideoControllerUI;
private boolean mEasierToWatchInFullScreen;
private PostDetailRecyclerViewAdapterCallback mPostDetailRecyclerViewAdapterCallback;
@@ -340,7 +347,10 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mHideUpvoteRatio = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_UPVOTE_RATIO, false);
mHideTheNumberOfAwards = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_AWARDS, false);
mHideSubredditAndUserPrefix = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_SUBREDDIT_AND_USER_PREFIX, false);
mShowDisplayNames = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.POST_DETAIL_DISPLAY_NAME_INSTEAD_OF_USERNAME, true);
mHideTheNumberOfVotes = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_VOTES, false);
mHideDownvotes = !currentAccountSharedPreferences.getBoolean(SharedPreferencesUtils.CAN_DOWNVOTE, true);
mSeperateUpvoteAndDownvote = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.POST_DETAIL_SEPARATE_UP_AND_DOWN_VOTES, true) && !mHideDownvotes;
mHideTheNumberOfComments = postDetailsSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_THE_NUMBER_OF_COMMENTS, false);
mPostDetailRecyclerViewAdapterCallback = postDetailRecyclerViewAdapterCallback;
@@ -438,7 +448,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
}
return new PostDetailVideoAutoplayViewHolder(LayoutInflater.from(parent.getContext()).inflate(mLegacyAutoplayVideoControllerUI ? R.layout.item_post_detail_video_autoplay_legacy_controller : R.layout.item_post_detail_video_autoplay, parent, false));
case VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW:
if (mDataSavingMode && (mDisableImagePreview || mOnlyDisablePreviewInVideoAndGifPosts)) {
if (mDataSavingMode && (mDisableImagePreview || mOnlyDisablePreviewInVideoAndGifPosts) || mPost.getPreviews().isEmpty()) {
return new PostDetailNoPreviewViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_detail_no_preview, parent, false));
}
return new PostDetailVideoAndGifPreviewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_post_detail_video_and_gif_preview, parent, false));
@@ -475,8 +485,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
((PostDetailBaseViewHolder) holder).mTitleTextView.setText(mPost.getTitle());
if (mPost.getSubredditNamePrefixed().startsWith("u/")) {
if (mPost.getAuthorIconUrl() == null) {
String authorName = mPost.isAuthorDeleted() ? mPost.getSubredditNamePrefixed().substring(2) : mPost.getAuthor();
LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, authorName, mOauthRetrofit, iconImageUrl -> {
LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase,mPost.getAuthorNamePrefixed(), mOauthRetrofit, iconImageUrl -> {
if (mActivity != null && getItemCount() > 0) {
if (iconImageUrl == null || iconImageUrl.equals("")) {
mGlide.load(R.drawable.subreddit_default_icon)
@@ -522,8 +531,6 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((PostDetailBaseViewHolder) holder).mIconGifImageView);
}
mPost.setSubredditIconUrl(iconImageUrl);
});
} else if (!mPost.getSubredditIconUrl().equals("")) {
mGlide.load(mPost.getSubredditIconUrl())
@@ -544,16 +551,23 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
//Upvote
((PostDetailBaseViewHolder) holder).mUpvoteButton.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN);
((PostDetailBaseViewHolder) holder).mScoreTextView.setTextColor(mUpvotedColor);
((PostDetailBaseViewHolder) holder).mDownvoteTextView.setTextColor(mPostIconAndInfoColor);
break;
case -1:
//Downvote
((PostDetailBaseViewHolder) holder).mDownvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
((PostDetailBaseViewHolder) holder).mScoreTextView.setTextColor(mDownvotedColor);
if(mSeperateUpvoteAndDownvote){
((PostDetailBaseViewHolder) holder).mDownvoteTextView.setTextColor(mDownvotedColor);
} else {
((PostDetailBaseViewHolder) holder).mScoreTextView.setTextColor(mDownvotedColor);
}
break;
default:
case 0:
((PostDetailBaseViewHolder) holder).mUpvoteButton.setColorFilter(mPostIconAndInfoColor, PorterDuff.Mode.SRC_IN);
((PostDetailBaseViewHolder) holder).mDownvoteButton.setColorFilter(mPostIconAndInfoColor, PorterDuff.Mode.SRC_IN);
((PostDetailBaseViewHolder) holder).mScoreTextView.setTextColor(mPostIconAndInfoColor);
((PostDetailBaseViewHolder) holder).mDownvoteTextView.setTextColor(mPostIconAndInfoColor);
}
if (mPost.isArchived()) {
@@ -567,15 +581,20 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
((PostDetailBaseViewHolder) holder).mCrosspostImageView.setVisibility(View.VISIBLE);
}
if (!mHideSubredditAndUserPrefix) {
((PostDetailBaseViewHolder) holder).mSubredditTextView.setText(mPost.getSubredditNamePrefixed());
((PostDetailBaseViewHolder) holder).mUserTextView.setText(mPost.getAuthorNamePrefixed());
((PostDetailBaseViewHolder) holder).mUserTextView.setText((mShowDisplayNames) ? mPost.getAuthor() : mPost.getAuthorInfo().getUsername());
((PostDetailBaseViewHolder) holder).mSubredditTextView.setText((mShowDisplayNames) ? mPost.getSubredditName() : mPost.getCommunityInfo().getName());
if (mHideSubredditAndUserPrefix) {
((PostDetailBaseViewHolder) holder).mUserTextView.setText((mShowDisplayNames) ? mPost.getAuthor() : mPost.getAuthorInfo().getUsername());
} else {
((PostDetailBaseViewHolder) holder).mSubredditTextView.setText(mPost.getSubredditName());
((PostDetailBaseViewHolder) holder).mUserTextView.setText(mPost.getAuthor());
((PostDetailBaseViewHolder) holder).mSubredditTextView.setText((mShowDisplayNames) ? mPost.getSubredditName() : mPost.getCommunityInfo().getName());
((PostDetailBaseViewHolder) holder).mCommunityInstanceTextView.setText('@' + mPost.getSubredditNamePrefixed().split(Pattern.quote("@"))[1]);
((PostDetailBaseViewHolder) holder).mUserInstanceTextView.setText('@' + mPost.getAuthorNamePrefixed().split(Pattern.quote("@"))[1]);
((PostDetailBaseViewHolder) holder).mCommunityInstanceTextView.setTextColor(CustomThemeWrapper.darkenColor(mSubredditColor, 0.7f));
((PostDetailBaseViewHolder) holder).mUserInstanceTextView.setTextColor(CustomThemeWrapper.darkenColor(mPost.isModerator() || mPost.isAdmin() ? mModeratorColor : mUsernameColor, 0.7f));
}
if (mPost.isModerator()) {
if (mPost.isModerator() || mPost.isAdmin()) {
((PostDetailBaseViewHolder) holder).mUserTextView.setTextColor(mModeratorColor);
Drawable moderatorDrawable = Utils.getTintedDrawable(mActivity, R.drawable.ic_verified_user_14dp, mModeratorColor);
((PostDetailBaseViewHolder) holder).mUserTextView.setCompoundDrawablesWithIntrinsicBounds(
@@ -611,7 +630,24 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
}
if (!mHideTheNumberOfVotes) {
((PostDetailBaseViewHolder) holder).mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, mPost.getScore() + mPost.getVoteType()));
if(mSeperateUpvoteAndDownvote){
int upvotes = (mPost.getVoteType() == 1) ? mPost.getUpvotes()+1 : mPost.getUpvotes();
int downvotes = (mPost.getVoteType() == -1) ? mPost.getDownvotes() +1 : Math.max(mPost.getDownvotes(),0);
((PostDetailBaseViewHolder) holder).mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, upvotes));
((PostDetailBaseViewHolder) holder).mDownvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
((PostDetailBaseViewHolder) holder).mDownvoteTextView.setVisibility(View.VISIBLE);
((PostDetailBaseViewHolder) holder).mDownvoteTextView.setGravity(Gravity.START);
((PostDetailBaseViewHolder) holder).mScoreTextView.setGravity(Gravity.START);
((PostDetailBaseViewHolder) holder).mScoreTextView.getLayoutParams().width = (int) (32 * mActivity.getResources().getDisplayMetrics().density);
((PostDetailBaseViewHolder) holder).mScoreTextView.setPadding(0, 0, 6, 0);
((PostDetailBaseViewHolder) holder).mDownvoteTextView.setPadding(0, 0, 12, 0);
((PostDetailBaseViewHolder) holder).mUpvoteButton.setPadding(24, 0, 12, 0);
} else {
((PostDetailBaseViewHolder) holder).mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, mPost.getScore() + mPost.getVoteType()));
}
} else {
((PostDetailBaseViewHolder) holder).mScoreTextView.setText(mActivity.getString(R.string.vote));
}
@@ -1146,7 +1182,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
public class PostDetailBaseViewHolder extends RecyclerView.ViewHolder {
AspectRatioGifImageView mIconGifImageView;
TextView mSubredditTextView;
TextView mCommunityInstanceTextView;
TextView mUserTextView;
TextView mUserInstanceTextView;
TextView mAuthorFlairTextView;
TextView mPostTimeTextView;
TextView mTitleTextView;
@@ -1163,6 +1201,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ConstraintLayout mBottomConstraintLayout;
ImageView mUpvoteButton;
TextView mScoreTextView;
TextView mDownvoteTextView;
ImageView mDownvoteButton;
TextView commentsCountTextView;
ImageView mSaveButton;
@@ -1174,7 +1213,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
void setBaseView(AspectRatioGifImageView mIconGifImageView,
TextView mSubredditTextView,
TextView mCommunityInstanceTextView,
TextView mUserTextView,
TextView mUserInstanceTextView,
TextView mAuthorFlairTextView,
TextView mPostTimeTextView,
TextView mTitleTextView,
@@ -1191,13 +1232,16 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ConstraintLayout mBottomConstraintLayout,
ImageView mUpvoteButton,
TextView mScoreTextView,
TextView mDownvoteTextView,
ImageView mDownvoteButton,
TextView commentsCountTextView,
ImageView mSaveButton,
ImageView mShareButton) {
this.mIconGifImageView = mIconGifImageView;
this.mSubredditTextView = mSubredditTextView;
this.mCommunityInstanceTextView = mCommunityInstanceTextView;
this.mUserTextView = mUserTextView;
this.mUserInstanceTextView = mUserInstanceTextView;
this.mAuthorFlairTextView = mAuthorFlairTextView;
this.mPostTimeTextView = mPostTimeTextView;
this.mTitleTextView = mTitleTextView;
@@ -1214,23 +1258,30 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
this.mBottomConstraintLayout = mBottomConstraintLayout;
this.mUpvoteButton = mUpvoteButton;
this.mScoreTextView = mScoreTextView;
this.mDownvoteTextView = mDownvoteTextView;
this.mDownvoteButton = mDownvoteButton;
this.commentsCountTextView = commentsCountTextView;
this.mSaveButton = mSaveButton;
this.mShareButton = mShareButton;
if(!mCurrentAccountSharedPreferences.getBoolean(SharedPreferencesUtils.CAN_DOWNVOTE,true)){
mDownvoteButton.setVisibility(View.GONE);
}
mIconGifImageView.setOnClickListener(view -> mSubredditTextView.performClick());
mSubredditTextView.setOnClickListener(view -> {
View.OnClickListener communityClickListener = view -> {
Intent intent;
intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY,
mPost.getSubredditName());
intent.putExtra(ViewSubredditDetailActivity.EXTRA_COMMUNITY_FULL_NAME_KEY, mPost.getSubredditNamePrefixed());
mActivity.startActivity(intent);
});
};
mSubredditTextView.setOnClickListener(communityClickListener);
mCommunityInstanceTextView.setOnClickListener(communityClickListener);
mUserTextView.setOnClickListener(view -> {
View.OnClickListener onUserClick = view -> {
if (mPost.isAuthorDeleted()) {
return;
}
@@ -1238,7 +1289,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mPost.getAuthor());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mPost.getAuthorNamePrefixed());
mActivity.startActivity(intent);
});
};
mUserTextView.setOnClickListener(onUserClick);
mUserInstanceTextView.setOnClickListener(onUserClick);
mAuthorFlairTextView.setOnClickListener(view -> mUserTextView.performClick());
@@ -1302,6 +1355,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
int newVoteType;
mDownvoteButton.setColorFilter(mPostIconAndInfoColor, PorterDuff.Mode.SRC_IN);
mDownvoteTextView.setTextColor(mPostIconAndInfoColor);
if (previousVoteType != 1) {
//Not upvoted before
@@ -1318,8 +1372,15 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
}
if (!mHideTheNumberOfVotes) {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + mPost.getVoteType()));
if(mSeperateUpvoteAndDownvote){
int upvotes = (mPost.getVoteType() == 1) ? mPost.getUpvotes() + 1 : mPost.getUpvotes();
int downvotes = (mPost.getVoteType() == -1) ? mPost.getDownvotes() + 1 : Math.max(mPost.getDownvotes(),0);;
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, upvotes));
mDownvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
} else {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + mPost.getVoteType()));
}
}
mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
@@ -1339,8 +1400,15 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mDownvoteButton.setColorFilter(mPostIconAndInfoColor, PorterDuff.Mode.SRC_IN);
if (!mHideTheNumberOfVotes) {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + mPost.getVoteType()));
if(mSeperateUpvoteAndDownvote){
int upvotes = (mPost.getVoteType() == 1) ? mPost.getUpvotes() + 1 : mPost.getUpvotes();
int downvotes = (mPost.getVoteType() == -1) ? mPost.getDownvotes() + 1 : Math.max(mPost.getDownvotes(),0);;
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, upvotes));
mDownvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
} else {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + mPost.getVoteType()));
}
}
mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
@@ -1351,8 +1419,15 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
Toast.makeText(mActivity, R.string.vote_failed, Toast.LENGTH_SHORT).show();
mPost.setVoteType(previousVoteType);
if (!mHideTheNumberOfVotes) {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + previousVoteType));
if(mSeperateUpvoteAndDownvote){
int upvotes = (previousVoteType == 1) ? mPost.getUpvotes() + 1 : mPost.getUpvotes();
int downvotes = (previousVoteType == -1) ? mPost.getDownvotes() - 1 : Math.max(mPost.getDownvotes(),0);;
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, upvotes));
mDownvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
} else {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + previousVoteType));
}
}
mUpvoteButton.setColorFilter(previousUpvoteButtonColorFilter);
mDownvoteButton.setColorFilter(previousDownvoteButtonColorFilter);
@@ -1382,24 +1457,36 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
int newVoteType;
mUpvoteButton.setColorFilter(mPostIconAndInfoColor, PorterDuff.Mode.SRC_IN);
mScoreTextView.setTextColor(mPostIconAndInfoColor);
if (previousVoteType != -1) {
//Not upvoted before
mPost.setVoteType(-1);
newVoteType = Integer.parseInt(APIUtils.DIR_DOWNVOTE);
mDownvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
mScoreTextView.setTextColor(mDownvotedColor);
if(mSeperateUpvoteAndDownvote){
mDownvoteTextView.setTextColor(mDownvotedColor);
} else {
mScoreTextView.setTextColor(mDownvotedColor);
}
} else {
//Upvoted before
mPost.setVoteType(0);
newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
mDownvoteButton.setColorFilter(mPostIconAndInfoColor, PorterDuff.Mode.SRC_IN);
mScoreTextView.setTextColor(mPostIconAndInfoColor);
mDownvoteTextView.setTextColor(mPostIconAndInfoColor);
}
if (!mHideTheNumberOfVotes) {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + mPost.getVoteType()));
if(mSeperateUpvoteAndDownvote){
int upvotes = (mPost.getVoteType() == 1) ? mPost.getUpvotes() + 1 : mPost.getUpvotes();
int downvotes = (mPost.getVoteType() == -1) ? mPost.getDownvotes() + 1 : Math.max(mPost.getDownvotes(),0);;
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, upvotes));
mDownvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
} else {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + mPost.getVoteType()));
}
}
mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
@@ -1410,17 +1497,29 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
if (newVoteType == Integer.parseInt(APIUtils.DIR_DOWNVOTE)) {
mPost.setVoteType(-1);
mDownvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
mScoreTextView.setTextColor(mDownvotedColor);
if(mSeperateUpvoteAndDownvote) {
mDownvoteTextView.setTextColor(mDownvotedColor);
} else {
mScoreTextView.setTextColor(mDownvotedColor);
}
} else {
mPost.setVoteType(0);
mDownvoteButton.setColorFilter(mPostIconAndInfoColor, PorterDuff.Mode.SRC_IN);
mScoreTextView.setTextColor(mPostIconAndInfoColor);
mDownvoteTextView.setTextColor(mPostIconAndInfoColor);
}
mUpvoteButton.setColorFilter(mPostIconAndInfoColor, PorterDuff.Mode.SRC_IN);
if (!mHideTheNumberOfVotes) {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + mPost.getVoteType()));
if(mSeperateUpvoteAndDownvote){
int upvotes = (mPost.getVoteType() == 1) ? mPost.getUpvotes() + 1 : mPost.getUpvotes();
int downvotes = (mPost.getVoteType() == -1) ? mPost.getDownvotes() + 1 : Math.max(mPost.getDownvotes(),0);;
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, upvotes));
mDownvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
} else {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + mPost.getVoteType()));
}
}
mPostDetailRecyclerViewAdapterCallback.updatePost(mPost);
@@ -1431,8 +1530,15 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
Toast.makeText(mActivity, R.string.vote_failed, Toast.LENGTH_SHORT).show();
mPost.setVoteType(previousVoteType);
if (!mHideTheNumberOfVotes) {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + previousVoteType));
if(mSeperateUpvoteAndDownvote) {
int upvotes = (previousVoteType == 1) ? mPost.getUpvotes() + 1 : mPost.getUpvotes();
int downvotes = (previousVoteType == -1) ? mPost.getDownvotes() + 1 : Math.max(mPost.getDownvotes(),0);
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, upvotes));
mDownvoteTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes, downvotes));
} else {
mScoreTextView.setText(Utils.getNVotes(mShowAbsoluteNumberOfVotes,
mPost.getScore() + previousVoteType));
}
}
mUpvoteButton.setColorFilter(previousUpvoteButtonColorFilter);
mDownvoteButton.setColorFilter(previousDownvoteButtonColorFilter);
@@ -1481,7 +1587,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
SavePost savePost = new SavePost();
if (mPost.isSaved()) {
mSaveButton.setImageResource(R.drawable.ic_bookmark_border_grey_24dp);
savePost.unsaveThing(mOauthRetrofit, mAccessToken, mPost.getId(),
savePost.unsaveThing(mRetrofit, mAccessToken, mPost.getId(),
new SaveThing.SaveThingListener() {
@Override
public void success() {
@@ -1555,11 +1661,18 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
constraintSet.clear(mUpvoteButton.getId(), ConstraintSet.START);
constraintSet.clear(mScoreTextView.getId(), ConstraintSet.START);
constraintSet.clear(mDownvoteButton.getId(), ConstraintSet.START);
constraintSet.clear(mDownvoteTextView.getId(), ConstraintSet.START);
constraintSet.clear(mSaveButton.getId(), ConstraintSet.END);
constraintSet.clear(mShareButton.getId(), ConstraintSet.END);
constraintSet.connect(mUpvoteButton.getId(), ConstraintSet.END, mScoreTextView.getId(), ConstraintSet.START);
constraintSet.connect(mScoreTextView.getId(), ConstraintSet.END, mDownvoteButton.getId(), ConstraintSet.START);
constraintSet.connect(mDownvoteButton.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
if (!mSeperateUpvoteAndDownvote) {
constraintSet.connect(mDownvoteButton.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
} else {
constraintSet.connect(mDownvoteButton.getId(), ConstraintSet.END, mDownvoteTextView.getId(), ConstraintSet.START);
constraintSet.connect(mDownvoteTextView.getId(), ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END);
}
constraintSet.connect(commentsCountTextView.getId(), ConstraintSet.START, mSaveButton.getId(), ConstraintSet.END);
constraintSet.connect(commentsCountTextView.getId(), ConstraintSet.END, mUpvoteButton.getId(), ConstraintSet.START);
constraintSet.connect(mSaveButton.getId(), ConstraintSet.START, mShareButton.getId(), ConstraintSet.END);
@@ -1627,8 +1740,14 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
AspectRatioGifImageView mIconGifImageView;
@BindView(R.id.subreddit_text_view_item_post_detail_video_autoplay)
TextView mSubredditTextView;
@BindView(R.id.community_instance_text_view_item_post_detail_video_autoplay)
TextView mCommunityInstanceTextView;
@BindView(R.id.user_text_view_item_post_detail_video_autoplay)
TextView mUserTextView;
@BindView(R.id.user_instance_text_view_item_post_detail_video_autoplay)
TextView mUserInstanceTextView;
@BindView(R.id.author_flair_text_view_item_post_detail_video_autoplay)
TextView mAuthorFlairTextView;
@BindView(R.id.post_time_text_view_item_post_detail_video_autoplay)
@@ -1679,6 +1798,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ImageView mUpvoteButton;
@BindView(R.id.score_text_view_item_post_detail_video_autoplay)
TextView mScoreTextView;
@BindView(R.id.downvote_text_view_item_post_detail_video_autoplay)
TextView mDownvoteTextView;
@BindView(R.id.minus_button_item_post_detail_video_autoplay)
ImageView mDownvoteButton;
@BindView(R.id.comments_count_item_post_detail_video_autoplay)
@@ -1700,7 +1822,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ButterKnife.bind(this, itemView);
setBaseView(mIconGifImageView,
mSubredditTextView,
mCommunityInstanceTextView,
mUserTextView,
mUserInstanceTextView,
mAuthorFlairTextView,
mPostTimeTextView,
mTitleTextView,
@@ -1717,6 +1841,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mBottomConstraintLayout,
mUpvoteButton,
mScoreTextView,
mDownvoteTextView,
mDownvoteButton,
commentsCountTextView,
mSaveButton,
@@ -1765,8 +1890,8 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
} else {
intent.setData(Uri.parse(mPost.getVideoUrl()));
intent.putExtra(ViewVideoActivity.EXTRA_VIDEO_DOWNLOAD_URL, mPost.getVideoDownloadUrl());
intent.putExtra(ViewVideoActivity.EXTRA_SUBREDDIT, mPost.getSubredditName());
intent.putExtra(ViewVideoActivity.EXTRA_ID, mPost.getId());
intent.putExtra(ViewVideoActivity.EXTRA_VIDEO_TYPE, ViewVideoActivity.VIDEO_TYPE_DIRECT);
}
intent.putExtra(ViewVideoActivity.EXTRA_POST_TITLE, mPost.getTitle());
if (helper != null) {
@@ -1934,8 +2059,12 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
AspectRatioGifImageView mIconGifImageView;
@BindView(R.id.subreddit_text_view_item_post_detail_video_and_gif_preview)
TextView mSubredditTextView;
@BindView(R.id.community_instance_text_view_item_post_detail_video_and_gif_preview)
TextView mCommunityInstanceTextView;
@BindView(R.id.user_text_view_item_post_detail_video_and_gif_preview)
TextView mUserTextView;
@BindView(R.id.user_instance_text_view_item_post_detail_video_and_gif_preview)
TextView mUserInstanceTextView;
@BindView(R.id.author_flair_text_view_item_post_detail_video_and_gif_preview)
TextView mAuthorFlairTextView;
@BindView(R.id.post_time_text_view_item_post_detail_video_and_gif_preview)
@@ -1978,6 +2107,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ImageView mUpvoteButton;
@BindView(R.id.score_text_view_item_post_detail_video_and_gif_preview)
TextView mScoreTextView;
@BindView(R.id.downvote_text_view_item_post_detail_video_and_gif_preview)
TextView mDownvoteTextView;
@BindView(R.id.minus_button_item_post_detail_video_and_gif_preview)
ImageView mDownvoteButton;
@BindView(R.id.comments_count_item_post_detail_video_and_gif_preview)
@@ -1992,7 +2124,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ButterKnife.bind(this, itemView);
setBaseView(mIconGifImageView,
mSubredditTextView,
mCommunityInstanceTextView,
mUserTextView,
mUserInstanceTextView,
mAuthorFlairTextView,
mPostTimeTextView,
mTitleTextView,
@@ -2009,6 +2143,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mBottomConstraintLayout,
mUpvoteButton,
mScoreTextView,
mDownvoteTextView,
mDownvoteButton,
commentsCountTextView,
mSaveButton,
@@ -2038,8 +2173,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
intent.putExtra(ViewVideoActivity.EXTRA_STREAMABLE_SHORT_CODE, mPost.getStreamableShortCode());
} else {
intent.setData(Uri.parse(mPost.getVideoUrl()));
intent.putExtra(ViewVideoActivity.EXTRA_SUBREDDIT, mPost.getSubredditName());
intent.putExtra(ViewVideoActivity.EXTRA_ID, mPost.getId());
intent.putExtra(ViewVideoActivity.EXTRA_VIDEO_TYPE, ViewVideoActivity.VIDEO_TYPE_DIRECT);
intent.putExtra(ViewVideoActivity.EXTRA_VIDEO_DOWNLOAD_URL, mPost.getVideoDownloadUrl());
}
intent.putExtra(ViewVideoActivity.EXTRA_POST_TITLE, mPost.getTitle());
@@ -2064,8 +2198,12 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
AspectRatioGifImageView mIconGifImageView;
@BindView(R.id.subreddit_text_view_item_post_detail_image_and_gif_autoplay)
TextView mSubredditTextView;
@BindView(R.id.community_instance_text_view_item_post_detail_image_and_gif_autoplay)
TextView mCommunityInstanceTextView;
@BindView(R.id.user_text_view_item_post_detail_image_and_gif_autoplay)
TextView mUserTextView;
@BindView(R.id.user_instance_text_view_item_post_detail_image_and_gif_autoplay)
TextView mUserInstanceTextView;
@BindView(R.id.author_flair_text_view_item_post_detail_image_and_gif_autoplay)
TextView mAuthorFlairTextView;
@BindView(R.id.post_time_text_view_item_post_detail_image_and_gif_autoplay)
@@ -2108,6 +2246,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ImageView mUpvoteButton;
@BindView(R.id.score_text_view_item_post_detail_image_and_gif_autoplay)
TextView mScoreTextView;
@BindView(R.id.downvote_text_view_item_post_detail_image_and_gif_autoplay)
TextView mDownvoteTextView;
@BindView(R.id.minus_button_item_post_detail_image_and_gif_autoplay)
ImageView mDownvoteButton;
@BindView(R.id.comments_count_item_post_detail_image_and_gif_autoplay)
@@ -2122,7 +2263,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ButterKnife.bind(this, itemView);
setBaseView(mIconGifImageView,
mSubredditTextView,
mCommunityInstanceTextView,
mUserTextView,
mUserInstanceTextView,
mAuthorFlairTextView,
mPostTimeTextView,
mTitleTextView,
@@ -2139,6 +2282,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mBottomConstraintLayout,
mUpvoteButton,
mScoreTextView,
mDownvoteTextView,
mDownvoteButton,
commentsCountTextView,
mSaveButton,
@@ -2177,8 +2321,12 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
AspectRatioGifImageView mIconGifImageView;
@BindView(R.id.subreddit_text_view_item_post_detail_link)
TextView mSubredditTextView;
@BindView(R.id.community_instance_text_view_item_post_detail_link)
TextView mCommunityInstanceTextView;
@BindView(R.id.user_text_view_item_post_detail_link)
TextView mUserTextView;
@BindView(R.id.user_instance_text_view_item_post_detail_link)
TextView mUserInstanceTextView;
@BindView(R.id.author_flair_text_view_item_post_detail_link)
TextView mAuthorFlairTextView;
@BindView(R.id.post_time_text_view_item_post_detail_link)
@@ -2223,6 +2371,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ImageView mUpvoteButton;
@BindView(R.id.score_text_view_item_post_detail_link)
TextView mScoreTextView;
@BindView(R.id.downvote_text_view_item_post_detail_link)
TextView mDownvoteTextView;
@BindView(R.id.minus_button_item_post_detail_link)
ImageView mDownvoteButton;
@BindView(R.id.comments_count_item_post_detail_link)
@@ -2237,7 +2388,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ButterKnife.bind(this, itemView);
setBaseView(mIconGifImageView,
mSubredditTextView,
mCommunityInstanceTextView,
mUserTextView,
mUserInstanceTextView,
mAuthorFlairTextView,
mPostTimeTextView,
mTitleTextView,
@@ -2254,6 +2407,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mBottomConstraintLayout,
mUpvoteButton,
mScoreTextView,
mDownvoteTextView,
mDownvoteButton,
commentsCountTextView,
mSaveButton,
@@ -2281,8 +2435,12 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
AspectRatioGifImageView mIconGifImageView;
@BindView(R.id.subreddit_text_view_item_post_detail_no_preview_link)
TextView mSubredditTextView;
@BindView(R.id.community_instance_text_view_item_post_detail_no_preview_link)
TextView mCommunityInstanceTextView;
@BindView(R.id.user_text_view_item_post_detail_no_preview_link)
TextView mUserTextView;
@BindView(R.id.user_instance_text_view_item_post_detail_no_preview_link)
TextView mUserInstanceTextView;
@BindView(R.id.author_flair_text_view_item_post_detail_no_preview_link)
TextView mAuthorFlairTextView;
@BindView(R.id.post_time_text_view_item_post_detail_no_preview_link)
@@ -2319,6 +2477,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ImageView mUpvoteButton;
@BindView(R.id.score_text_view_item_post_detail_no_preview_link)
TextView mScoreTextView;
@BindView(R.id.downvote_text_view_item_post_detail_no_preview_link)
TextView mDownvoteTextView;
@BindView(R.id.minus_button_item_post_detail_no_preview_link)
ImageView mDownvoteButton;
@BindView(R.id.comments_count_item_post_detail_no_preview_link)
@@ -2333,7 +2494,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ButterKnife.bind(this, itemView);
setBaseView(mIconGifImageView,
mSubredditTextView,
mCommunityInstanceTextView,
mUserTextView,
mUserInstanceTextView,
mAuthorFlairTextView,
mPostTimeTextView,
mTitleTextView,
@@ -2350,6 +2513,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mBottomConstraintLayout,
mUpvoteButton,
mScoreTextView,
mDownvoteTextView,
mDownvoteButton,
commentsCountTextView,
mSaveButton,
@@ -2377,7 +2541,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
intent.putExtra(ViewVideoActivity.EXTRA_STREAMABLE_SHORT_CODE, mPost.getStreamableShortCode());
} else {
intent.setData(Uri.parse(mPost.getVideoUrl()));
intent.putExtra(ViewVideoActivity.EXTRA_SUBREDDIT, mPost.getSubredditName());
intent.putExtra(ViewVideoActivity.EXTRA_VIDEO_TYPE, ViewVideoActivity.VIDEO_TYPE_DIRECT);
intent.putExtra(ViewVideoActivity.EXTRA_ID, mPost.getId());
intent.putExtra(ViewVideoActivity.EXTRA_VIDEO_DOWNLOAD_URL, mPost.getVideoDownloadUrl());
}
@@ -2422,8 +2586,12 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
AspectRatioGifImageView mIconGifImageView;
@BindView(R.id.subreddit_text_view_item_post_detail_gallery)
TextView mSubredditTextView;
@BindView(R.id.community_instance_text_view_item_post_detail_gallery)
TextView mCommunityInstanceTextView;
@BindView(R.id.user_text_view_item_post_detail_gallery)
TextView mUserTextView;
@BindView(R.id.user_instance_text_view_item_post_detail_gallery)
TextView mUserInstanceTextView;
@BindView(R.id.author_flair_text_view_item_post_detail_gallery)
TextView mAuthorFlairTextView;
@BindView(R.id.post_time_text_view_item_post_detail_gallery)
@@ -2464,6 +2632,8 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ImageView mUpvoteButton;
@BindView(R.id.score_text_view_item_post_detail_gallery)
TextView mScoreTextView;
@BindView(R.id.downvote_text_view_item_post_detail_gallery)
TextView mDownvoteTextView;
@BindView(R.id.minus_button_item_post_detail_gallery)
ImageView mDownvoteButton;
@BindView(R.id.comments_count_item_post_detail_gallery)
@@ -2479,7 +2649,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ButterKnife.bind(this, itemView);
setBaseView(mIconGifImageView,
mSubredditTextView,
mCommunityInstanceTextView,
mUserTextView,
mUserInstanceTextView,
mAuthorFlairTextView,
mPostTimeTextView,
mTitleTextView,
@@ -2496,6 +2668,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mBottomConstraintLayout,
mUpvoteButton,
mScoreTextView,
mDownvoteTextView,
mDownvoteButton,
commentsCountTextView,
mSaveButton,
@@ -2617,8 +2790,12 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
AspectRatioGifImageView mIconGifImageView;
@BindView(R.id.subreddit_text_view_item_post_detail_text)
TextView mSubredditTextView;
@BindView(R.id.community_instance_text_view_item_post_detail_text)
TextView mCommunityInstanceTextView;
@BindView(R.id.user_text_view_item_post_detail_text)
TextView mUserTextView;
@BindView(R.id.user_instance_text_view_item_post_detail_text)
TextView mUserInstanceTextView;
@BindView(R.id.author_flair_text_view_item_post_detail_text)
TextView mAuthorFlairTextView;
@BindView(R.id.post_time_text_view_item_post_detail_text)
@@ -2651,6 +2828,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ImageView mUpvoteButton;
@BindView(R.id.score_text_view_item_post_detail_text)
TextView mScoreTextView;
@BindView(R.id.downvote_text_view_item_post_detail_text)
TextView mDownvoteTextView;
@BindView(R.id.minus_button_item_post_detail_text)
ImageView mDownvoteButton;
@BindView(R.id.comments_count_item_post_detail_text)
@@ -2665,7 +2845,9 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
ButterKnife.bind(this, itemView);
setBaseView(mIconGifImageView,
mSubredditTextView,
mCommunityInstanceTextView,
mUserTextView,
mUserInstanceTextView,
mAuthorFlairTextView,
mPostTimeTextView,
mTitleTextView,
@@ -2682,6 +2864,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mBottomConstraintLayout,
mUpvoteButton,
mScoreTextView,
mDownvoteTextView,
mDownvoteButton,
commentsCountTextView,
mSaveButton,

View File

@@ -0,0 +1,343 @@
package eu.toldi.infinityforlemmy.adapters;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.net.Uri;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.view.LayoutInflater;
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.paging.PagedListAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.NetworkState;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.LinkResolverActivity;
import eu.toldi.infinityforlemmy.activities.ViewPrivateMessagesActivity;
import eu.toldi.infinityforlemmy.activities.ViewUserDetailActivity;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.markdown.RedditHeadingPlugin;
import eu.toldi.infinityforlemmy.markdown.SpoilerAwareMovementMethod;
import eu.toldi.infinityforlemmy.markdown.SpoilerParserPlugin;
import eu.toldi.infinityforlemmy.markdown.SuperscriptPlugin;
import eu.toldi.infinityforlemmy.privatemessage.LemmyPrivateMessageAPI;
import eu.toldi.infinityforlemmy.privatemessage.PrivateMessage;
import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration;
import io.noties.markwon.core.MarkwonTheme;
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin;
import io.noties.markwon.image.glide.GlideImagesPlugin;
import io.noties.markwon.inlineparser.HtmlInlineProcessor;
import io.noties.markwon.inlineparser.MarkwonInlineParserPlugin;
import io.noties.markwon.linkify.LinkifyPlugin;
import io.noties.markwon.movement.MovementMethodPlugin;
import retrofit2.Retrofit;
public class PrivateMessageRecycleViewAdapter extends PagedListAdapter<PrivateMessage, RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_DATA = 0;
private static final int VIEW_TYPE_ERROR = 1;
private static final int VIEW_TYPE_LOADING = 2;
private static final DiffUtil.ItemCallback<PrivateMessage> DIFF_CALLBACK = new DiffUtil.ItemCallback<>() {
@Override
public boolean areItemsTheSame(@NonNull PrivateMessage message, @NonNull PrivateMessage t1) {
return message.getId() == t1.getId();
}
@Override
public boolean areContentsTheSame(@NonNull PrivateMessage message, @NonNull PrivateMessage t1) {
return message.getContent().equals(t1.getContent());
}
};
private BaseActivity mActivity;
private Retrofit retrofit;
private Markwon mMarkwon;
private String mAccessToken;
private final LemmyPrivateMessageAPI lemmyPrivateMessageAPI;
private int mMessageType;
private NetworkState networkState;
private RetryLoadingMoreCallback mRetryLoadingMoreCallback;
private int mColorAccent;
private int mMessageBackgroundColor;
private int mUsernameColor;
private int mPrimaryTextColor;
private int mSecondaryTextColor;
private int mUnreadMessageBackgroundColor;
private int mColorPrimaryLightTheme;
private int mButtonTextColor;
private boolean markAllMessagesAsRead = false;
public PrivateMessageRecycleViewAdapter(BaseActivity activity, Retrofit oauthRetrofit,
CustomThemeWrapper customThemeWrapper,
String accessToken,
LemmyPrivateMessageAPI lemmyPrivateMessageAPI, RetryLoadingMoreCallback retryLoadingMoreCallback) {
super(DIFF_CALLBACK);
mActivity = activity;
retrofit = oauthRetrofit;
this.lemmyPrivateMessageAPI = lemmyPrivateMessageAPI;
mRetryLoadingMoreCallback = retryLoadingMoreCallback;
mColorAccent = customThemeWrapper.getColorAccent();
mMessageBackgroundColor = customThemeWrapper.getCardViewBackgroundColor();
mUsernameColor = customThemeWrapper.getUsername();
mPrimaryTextColor = customThemeWrapper.getPrimaryTextColor();
mSecondaryTextColor = customThemeWrapper.getSecondaryTextColor();
int spoilerBackgroundColor = mSecondaryTextColor | 0xFF000000;
mUnreadMessageBackgroundColor = customThemeWrapper.getUnreadMessageBackgroundColor();
mColorPrimaryLightTheme = customThemeWrapper.getColorPrimaryLightTheme();
mButtonTextColor = customThemeWrapper.getButtonTextColor();
// todo:https://github.com/Docile-Alligator/Infinity-For-Reddit/issues/1027
// add tables support and replace with MarkdownUtils#commonPostMarkwonBuilder
mMarkwon = Markwon.builder(mActivity)
.usePlugin(MarkwonInlineParserPlugin.create(plugin -> {
plugin.excludeInlineProcessor(HtmlInlineProcessor.class);
}))
.usePlugin(new AbstractMarkwonPlugin() {
@Override
public void configureConfiguration(@NonNull MarkwonConfiguration.Builder builder) {
builder.linkResolver((view, link) -> {
Intent intent = new Intent(mActivity, LinkResolverActivity.class);
Uri uri = Uri.parse(link);
intent.setData(uri);
mActivity.startActivity(intent);
});
}
@Override
public void configureTheme(@NonNull MarkwonTheme.Builder builder) {
builder.linkColor(customThemeWrapper.getLinkColor());
}
})
.usePlugin(SuperscriptPlugin.create())
.usePlugin(SpoilerParserPlugin.create(mSecondaryTextColor, spoilerBackgroundColor))
.usePlugin(RedditHeadingPlugin.create())
.usePlugin(StrikethroughPlugin.create())
.usePlugin(MovementMethodPlugin.create(new SpoilerAwareMovementMethod()))
.usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
.usePlugin(GlideImagesPlugin.create(mActivity))
.build();
mAccessToken = accessToken;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_DATA) {
return new DataViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_message, parent, false));
} else if (viewType == VIEW_TYPE_ERROR) {
return new ErrorViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer_error, parent, false));
} else {
return new LoadingViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_footer_loading, parent, false));
}
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder instanceof DataViewHolder) {
PrivateMessage message = getItem(holder.getBindingAdapterPosition());
if (message != null) {
if (!message.getRead()) {
if (markAllMessagesAsRead) {
message.setRead(true);
} else {
holder.itemView.setBackgroundColor(
mUnreadMessageBackgroundColor);
}
}
((DataViewHolder) holder).titleTextView.setVisibility(View.GONE);
((DataViewHolder) holder).authorTextView.setText(message.getCreatorQualifiedName());
String subject = message.getRecipientQualifiedName();
((DataViewHolder) holder).subjectTextView.setText(subject);
mMarkwon.setMarkdown(((DataViewHolder) holder).contentCustomMarkwonView, message.getContent());
holder.itemView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, ViewPrivateMessagesActivity.class);
intent.putExtra(ViewPrivateMessagesActivity.EXTRA_PRIVATE_MESSAGE, message);
mActivity.startActivity(intent);
if (message.getRead()) {
holder.itemView.setBackgroundColor(mMessageBackgroundColor);
lemmyPrivateMessageAPI.markPrivateMessageAsRead(mAccessToken, message.getId(), new LemmyPrivateMessageAPI.PrivateMessageMarkedAsReadListener() {
@Override
public void onPrivateMessageMarkedAsReadError() {
message.setRead(false);
}
@Override
public void onPrivateMessageMarkedAsReadSuccess() {
message.setRead(true);
}
});
}
});
((DataViewHolder) holder).authorTextView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, message.getCreatorName());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, message.getCreatorQualifiedName());
mActivity.startActivity(intent);
});
}
}
}
@Override
public int getItemViewType(int position) {
// Reached at the end
if (hasExtraRow() && position == getItemCount() - 1) {
if (networkState.getStatus() == NetworkState.Status.LOADING) {
return VIEW_TYPE_LOADING;
} else {
return VIEW_TYPE_ERROR;
}
} else {
return VIEW_TYPE_DATA;
}
}
@Override
public int getItemCount() {
if (hasExtraRow()) {
return super.getItemCount() + 1;
}
return super.getItemCount();
}
@Override
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
super.onViewRecycled(holder);
if (holder instanceof DataViewHolder) {
((DataViewHolder) holder).itemView.setBackgroundColor(mMessageBackgroundColor);
((DataViewHolder) holder).titleTextView.setVisibility(View.VISIBLE);
}
}
private boolean hasExtraRow() {
return networkState != null && networkState.getStatus() != NetworkState.Status.SUCCESS;
}
public void setNetworkState(NetworkState newNetworkState) {
NetworkState previousState = this.networkState;
boolean previousExtraRow = hasExtraRow();
this.networkState = newNetworkState;
boolean newExtraRow = hasExtraRow();
if (previousExtraRow != newExtraRow) {
if (previousExtraRow) {
notifyItemRemoved(super.getItemCount());
} else {
notifyItemInserted(super.getItemCount());
}
} else if (newExtraRow && !previousState.equals(newNetworkState)) {
notifyItemChanged(getItemCount() - 1);
}
}
public void updateMessageReply(PrivateMessage newReply, int position) {
if (position >= 0 && position < super.getItemCount()) {
PrivateMessage message = getItem(position);
if (message != null) {
notifyItemChanged(position);
}
}
}
public void setMarkAllMessagesAsRead(boolean markAllMessagesAsRead) {
this.markAllMessagesAsRead = markAllMessagesAsRead;
}
public interface RetryLoadingMoreCallback {
void retryLoadingMore();
}
class DataViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.author_text_view_item_message)
TextView authorTextView;
@BindView(R.id.subject_text_view_item_message)
TextView subjectTextView;
@BindView(R.id.title_text_view_item_message)
TextView titleTextView;
@BindView(R.id.content_custom_markwon_view_item_message)
TextView contentCustomMarkwonView;
DataViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
authorTextView.setTypeface(mActivity.typeface);
subjectTextView.setTypeface(mActivity.typeface);
titleTextView.setTypeface(mActivity.titleTypeface);
contentCustomMarkwonView.setTypeface(mActivity.contentTypeface);
}
itemView.setBackgroundColor(mMessageBackgroundColor);
authorTextView.setTextColor(mUsernameColor);
subjectTextView.setTextColor(mPrimaryTextColor);
titleTextView.setTextColor(mPrimaryTextColor);
contentCustomMarkwonView.setTextColor(mSecondaryTextColor);
contentCustomMarkwonView.setMovementMethod(LinkMovementMethod.getInstance());
contentCustomMarkwonView.setOnClickListener(view -> {
if (contentCustomMarkwonView.getSelectionStart() == -1 && contentCustomMarkwonView.getSelectionEnd() == -1) {
itemView.performClick();
}
});
}
}
class ErrorViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.error_text_view_item_footer_error)
TextView errorTextView;
@BindView(R.id.retry_button_item_footer_error)
Button retryButton;
ErrorViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
if (mActivity.typeface != null) {
errorTextView.setTypeface(mActivity.typeface);
retryButton.setTypeface(mActivity.typeface);
}
errorTextView.setText(R.string.load_comments_failed);
errorTextView.setTextColor(mSecondaryTextColor);
retryButton.setOnClickListener(view -> mRetryLoadingMoreCallback.retryLoadingMore());
retryButton.setBackgroundTintList(ColorStateList.valueOf(mColorPrimaryLightTheme));
retryButton.setTextColor(mButtonTextColor);
}
}
class LoadingViewHolder extends RecyclerView.ViewHolder {
@BindView(R.id.progress_bar_item_footer_loading)
ProgressBar progressBar;
LoadingViewHolder(@NonNull View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
progressBar.setIndeterminateTintList(ColorStateList.valueOf(mColorAccent));
}
}
}

View File

@@ -27,34 +27,35 @@ import java.util.Locale;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration;
import io.noties.markwon.core.MarkwonTheme;
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin;
import io.noties.markwon.inlineparser.BangInlineProcessor;
import io.noties.markwon.inlineparser.HtmlInlineProcessor;
import io.noties.markwon.inlineparser.MarkwonInlineParserPlugin;
import io.noties.markwon.linkify.LinkifyPlugin;
import io.noties.markwon.movement.MovementMethodPlugin;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.activities.LinkResolverActivity;
import eu.toldi.infinityforlemmy.activities.ViewPrivateMessagesActivity;
import eu.toldi.infinityforlemmy.activities.ViewUserDetailActivity;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.markdown.ClickableGlideImagesPlugin;
import eu.toldi.infinityforlemmy.markdown.RedditHeadingPlugin;
import eu.toldi.infinityforlemmy.markdown.SpoilerAwareMovementMethod;
import eu.toldi.infinityforlemmy.markdown.SpoilerParserPlugin;
import eu.toldi.infinityforlemmy.markdown.SuperscriptPlugin;
import eu.toldi.infinityforlemmy.message.Message;
import eu.toldi.infinityforlemmy.privatemessage.PrivateMessage;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration;
import io.noties.markwon.core.MarkwonTheme;
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin;
import io.noties.markwon.image.glide.GlideImagesPlugin;
import io.noties.markwon.inlineparser.HtmlInlineProcessor;
import io.noties.markwon.inlineparser.MarkwonInlineParserPlugin;
import io.noties.markwon.linkify.LinkifyPlugin;
import io.noties.markwon.movement.MovementMethodPlugin;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_MESSAGE_SENT = 0;
private static final int VIEW_TYPE_MESSAGE_RECEIVED = 1;
private Message mMessage;
private PrivateMessage mMessage;
private ViewPrivateMessagesActivity mViewPrivateMessagesActivity;
private RequestManager mGlide;
private Locale mLocale;
@@ -70,7 +71,7 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
public PrivateMessagesDetailRecyclerViewAdapter(ViewPrivateMessagesActivity viewPrivateMessagesActivity,
SharedPreferences sharedPreferences, Locale locale,
Message message, String accountName,
PrivateMessage message, String accountName,
CustomThemeWrapper customThemeWrapper) {
mMessage = message;
mViewPrivateMessagesActivity = viewPrivateMessagesActivity;
@@ -83,7 +84,6 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
mMarkwon = Markwon.builder(viewPrivateMessagesActivity)
.usePlugin(MarkwonInlineParserPlugin.create(plugin -> {
plugin.excludeInlineProcessor(HtmlInlineProcessor.class);
plugin.excludeInlineProcessor(BangInlineProcessor.class);
}))
.usePlugin(new AbstractMarkwonPlugin() {
@Override
@@ -108,6 +108,8 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
builder.linkColor(customThemeWrapper.getLinkColor());
}
})
.usePlugin(GlideImagesPlugin.create(viewPrivateMessagesActivity))
.usePlugin(ClickableGlideImagesPlugin.create(viewPrivateMessagesActivity))
.usePlugin(SuperscriptPlugin.create())
.usePlugin(StrikethroughPlugin.create())
.usePlugin(SpoilerParserPlugin.create(commentColor, commentColor | 0xFF000000))
@@ -127,9 +129,9 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
@Override
public int getItemViewType(int position) {
if (position == 0) {
return mMessage.getAuthor().equals(mAccountName) ? VIEW_TYPE_MESSAGE_SENT : VIEW_TYPE_MESSAGE_RECEIVED;
return mMessage.getCreatorQualifiedName().equals(mAccountName) ? VIEW_TYPE_MESSAGE_SENT : VIEW_TYPE_MESSAGE_RECEIVED;
} else {
return mMessage.getReplies().get(position - 1).getAuthor().equals(mAccountName) ? VIEW_TYPE_MESSAGE_SENT : VIEW_TYPE_MESSAGE_RECEIVED;
return mMessage.getReplies().get(position - 1).getCreatorQualifiedName().equals(mAccountName) ? VIEW_TYPE_MESSAGE_SENT : VIEW_TYPE_MESSAGE_RECEIVED;
}
}
@@ -145,7 +147,7 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Message message;
PrivateMessage message;
if (holder.getBindingAdapterPosition() == 0) {
message = mMessage;
} else {
@@ -153,12 +155,12 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
}
if (message != null) {
if (holder instanceof MessageViewHolder) {
mMarkwon.setMarkdown(((MessageViewHolder) holder).messageTextView, message.getBody());
mMarkwon.setMarkdown(((MessageViewHolder) holder).messageTextView, message.getContent());
if (mShowElapsedTime) {
((MessageViewHolder) holder).timeTextView.setText(Utils.getElapsedTime(mViewPrivateMessagesActivity, message.getTimeUTC()));
((MessageViewHolder) holder).timeTextView.setText(Utils.getElapsedTime(mViewPrivateMessagesActivity, message.getPublished()));
} else {
((MessageViewHolder) holder).timeTextView.setText(Utils.getFormattedTime(mLocale, message.getTimeUTC(), mTimeFormatPattern));
((MessageViewHolder) holder).timeTextView.setText(Utils.getFormattedTime(mLocale, message.getPublished(), mTimeFormatPattern));
}
}
@@ -166,26 +168,33 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
((SentMessageViewHolder) holder).messageTextView.setBackground(Utils.getTintedDrawable(mViewPrivateMessagesActivity,
R.drawable.private_message_ballon, mSentMessageBackgroundColor));
} else if (holder instanceof ReceivedMessageViewHolder) {
mViewPrivateMessagesActivity.fetchUserAvatar(message.getAuthor(), userAvatarUrl -> {
if (userAvatarUrl == null || userAvatarUrl.equals("")) {
mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((ReceivedMessageViewHolder) holder).userAvatarImageView);
} else {
mGlide.load(userAvatarUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((ReceivedMessageViewHolder) holder).userAvatarImageView);
}
});
if (!message.getCreatorAvatar().equals("")) {
mGlide.load(message.getCreatorAvatar())
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((ReceivedMessageViewHolder) holder).userAvatarImageView);
} else {
mViewPrivateMessagesActivity.fetchUserAvatar(message.getCreatorQualifiedName(), userAvatarUrl -> {
if (userAvatarUrl == null || userAvatarUrl.equals("")) {
mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(((ReceivedMessageViewHolder) holder).userAvatarImageView);
} else {
mGlide.load(userAvatarUrl)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.error(mGlide.load(R.drawable.subreddit_default_icon)
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))))
.into(((ReceivedMessageViewHolder) holder).userAvatarImageView);
}
});
}
((ReceivedMessageViewHolder) holder).userAvatarImageView.setOnClickListener(view -> {
if (message.isAuthorDeleted()) {
return;
}
Intent intent = new Intent(mViewPrivateMessagesActivity, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, message.getAuthor());
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, message.getCreatorName());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, message.getCreatorQualifiedName());
mViewPrivateMessagesActivity.startActivity(intent);
});
@@ -207,12 +216,12 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
}
}
public void setMessage(Message message) {
public void setMessage(PrivateMessage message) {
mMessage = message;
notifyDataSetChanged();
}
public void addReply(Message reply) {
public void addReply(PrivateMessage reply) {
int currentSize = getItemCount();
if (mMessage != null) {
@@ -273,7 +282,7 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
copyImageView.setColorFilter(mSecondaryTextColor, android.graphics.PorterDuff.Mode.SRC_IN);
copyImageView.setOnClickListener(view -> {
Message message;
PrivateMessage message;
if (getBindingAdapterPosition() == 0) {
message = mMessage;
} else {
@@ -282,7 +291,7 @@ public class PrivateMessagesDetailRecyclerViewAdapter extends RecyclerView.Adapt
if (message != null) {
ClipboardManager clipboard = (ClipboardManager) mViewPrivateMessagesActivity.getSystemService(Context.CLIPBOARD_SERVICE);
if (clipboard != null) {
ClipData clip = ClipData.newPlainText("simple text", message.getBody());
ClipData clip = ClipData.newPlainText("simple text", message.getContent());
clipboard.setPrimaryClip(clip);
if (android.os.Build.VERSION.SDK_INT < 33) {
Toast.makeText(mViewPrivateMessagesActivity, R.string.copy_success, Toast.LENGTH_SHORT).show();

View File

@@ -148,7 +148,7 @@ public class UserListingRecyclerViewAdapter extends PagedListAdapter<UserData, R
@Override
public void isNotSubscribed() {
((DataViewHolder) holder).subscribeButton.setVisibility(View.VISIBLE);
((DataViewHolder) holder).subscribeButton.setOnClickListener(view -> {
UserFollowing.followUser(oauthRetrofit, retrofit,
accessToken, userData.getName(), accountName, redditDataRoomDatabase,

View File

@@ -24,8 +24,8 @@ public class AccountSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recy
private static final int VIEW_TYPE_MENU_GROUP_TITLE = 1;
private static final int VIEW_TYPE_MENU_ITEM = 2;
private static final int ACCOUNT_SECTION_ITEMS = 5;
private static final int ANONYMOUS_ACCOUNT_SECTION_ITEMS = 3;
private static final int ACCOUNT_SECTION_ITEMS = 4;
private static final int ANONYMOUS_ACCOUNT_SECTION_ITEMS = 1;
private BaseActivity baseActivity;
private int inboxCount;
@@ -101,10 +101,6 @@ public class AccountSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recy
drawableId = R.drawable.ic_subscritptions_bottom_app_bar_24dp;
break;
case 3:
stringId = R.string.multi_reddit;
drawableId = R.drawable.ic_multi_reddit_24dp;
break;
case 4:
setOnClickListener = false;
if (inboxCount > 0) {
((MenuItemViewHolder) holder).menuTextView.setText(baseActivity.getString(R.string.inbox_with_count, inboxCount));
@@ -118,23 +114,21 @@ public class AccountSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recy
});
break;
default:
stringId = R.string.history;
drawableId = R.drawable.ic_history_24dp;
stringId = R.string.account_saved_thing_activity_label;
drawableId = R.drawable.ic_outline_bookmarks_24dp;
break;
}
} else {
switch (position) {
case 1:
stringId = R.string.subscriptions;
drawableId = R.drawable.ic_subscritptions_bottom_app_bar_24dp;
break;
case 2:
stringId = R.string.multi_reddit;
drawableId = R.drawable.ic_multi_reddit_24dp;
break;
default:
stringId = R.string.history;
drawableId = R.drawable.ic_history_24dp;
stringId = R.string.anonymous_account_instance;
drawableId = R.drawable.ic_account_circle_24dp;
break;
}
}

View File

@@ -39,6 +39,7 @@ public class HeaderSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
private Resources resources;
private RequestManager glide;
private String accountName;
private String accountQualifiedName;
private String profileImageUrl;
private String bannerImageUrl;
private int karma;
@@ -50,7 +51,7 @@ public class HeaderSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
private boolean hideKarma;
public HeaderSectionRecyclerViewAdapter(BaseActivity baseActivity, CustomThemeWrapper customThemeWrapper,
RequestManager glide, String accountName,
RequestManager glide, String accountName, String accountQualifiedName,
SharedPreferences sharedPreferences,
SharedPreferences navigationDrawerSharedPreferences,
SharedPreferences securitySharedPreferences,
@@ -62,6 +63,7 @@ public class HeaderSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
this.accountName = accountName;
isLoggedIn = accountName != null;
this.pageToggle = pageToggle;
this.accountQualifiedName = accountQualifiedName;
requireAuthToAccountSection = securitySharedPreferences.getBoolean(SharedPreferencesUtils.REQUIRE_AUTHENTICATION_TO_GO_TO_ACCOUNT_SECTION_IN_NAVIGATION_DRAWER, false);
showAvatarOnTheRightInTheNavigationDrawer = sharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_AVATAR_ON_THE_RIGHT, false);
showAvatarOnTheRightInTheNavigationDrawer = navigationDrawerSharedPreferences.getBoolean(SharedPreferencesUtils.SHOW_AVATAR_ON_THE_RIGHT, false);
@@ -86,15 +88,11 @@ public class HeaderSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
}
((NavHeaderViewHolder) holder).profileImageView.setLayoutParams(params);
if (isLoggedIn) {
if (hideKarma) {
int karmaTextHeight = ((NavHeaderViewHolder) holder).karmaTextView.getHeight();
((NavHeaderViewHolder) holder).karmaTextView.setVisibility(View.GONE);
((NavHeaderViewHolder) holder).accountNameTextView.setTranslationY(karmaTextHeight / 2);
} else {
((NavHeaderViewHolder) holder).karmaTextView.setVisibility(View.VISIBLE);
((NavHeaderViewHolder) holder).karmaTextView.setText(baseActivity.getString(R.string.karma_info, karma));
((NavHeaderViewHolder) holder).accountNameTextView.setTranslationY(0);
}
((NavHeaderViewHolder) holder).karmaTextView.setVisibility(View.VISIBLE);
((NavHeaderViewHolder) holder).karmaTextView.setText(accountQualifiedName);
((NavHeaderViewHolder) holder).accountNameTextView.setTranslationY(0);
((NavHeaderViewHolder) holder).accountNameTextView.setText(accountName);
if (profileImageUrl != null && !profileImageUrl.equals("")) {
glide.load(profileImageUrl)

View File

@@ -18,13 +18,13 @@ import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
public class LemmySectionRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int VIEW_TYPE_MENU_GROUP_TITLE = 1;
private static final int VIEW_TYPE_MENU_ITEM = 2;
private static final int REDDIT_SECTION_ITEMS = 1;
private static final int LEMMY_SECTION_ITEMS = 2;
private static final int REDDIT_SECTION_ANONYMOUS_ITEMS = 2;
private static final int LEMMY_SECTION_ANONYMOUS_ITEMS = 1;
private final boolean isLoggedIn;
private BaseActivity baseActivity;
@@ -34,9 +34,9 @@ public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
private boolean collapseRedditSection;
private NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener itemClickListener;
public RedditSectionRecyclerViewAdapter(BaseActivity baseActivity, CustomThemeWrapper customThemeWrapper,
SharedPreferences navigationDrawerSharedPreferences,
NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener itemClickListener, boolean isLoggedIn) {
public LemmySectionRecyclerViewAdapter(BaseActivity baseActivity, CustomThemeWrapper customThemeWrapper,
SharedPreferences navigationDrawerSharedPreferences,
NavigationDrawerRecyclerViewMergedAdapter.ItemClickListener itemClickListener, boolean isLoggedIn) {
this.baseActivity = baseActivity;
primaryTextColor = customThemeWrapper.getPrimaryTextColor();
secondaryTextColor = customThemeWrapper.getSecondaryTextColor();
@@ -76,10 +76,10 @@ public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
holder.itemView.setOnClickListener(view -> {
if (collapseRedditSection) {
collapseRedditSection = !collapseRedditSection;
notifyItemRangeInserted(holder.getBindingAdapterPosition() + 1, REDDIT_SECTION_ITEMS);
notifyItemRangeInserted(holder.getBindingAdapterPosition() + 1, isLoggedIn ? LEMMY_SECTION_ITEMS : LEMMY_SECTION_ANONYMOUS_ITEMS);
} else {
collapseRedditSection = !collapseRedditSection;
notifyItemRangeRemoved(holder.getBindingAdapterPosition() + 1, REDDIT_SECTION_ITEMS);
notifyItemRangeRemoved(holder.getBindingAdapterPosition() + 1, isLoggedIn ? LEMMY_SECTION_ITEMS : LEMMY_SECTION_ANONYMOUS_ITEMS);
}
notifyItemChanged(holder.getBindingAdapterPosition());
});
@@ -89,12 +89,13 @@ public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
switch (position) {
case 1:
stringId = R.string.trending;
drawableId = R.drawable.ic_trending_24dp;
stringId = R.string.instance_info;
drawableId = R.drawable.ic_baseline_info_24;
break;
case 2:
stringId = R.string.anonymous_account_instance;
drawableId = R.drawable.ic_account_circle_24dp;
stringId = R.string.blocks;
drawableId = R.drawable.ic_outline_lock_24dp;
break;
}
((MenuItemViewHolder) holder).menuTextView.setText(stringId);
@@ -106,7 +107,7 @@ public class RedditSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
@Override
public int getItemCount() {
return !collapseRedditSection ? (isLoggedIn ? REDDIT_SECTION_ITEMS + 1 : REDDIT_SECTION_ANONYMOUS_ITEMS + 1) : 1;
return !collapseRedditSection ? (isLoggedIn ? LEMMY_SECTION_ITEMS + 1 : LEMMY_SECTION_ANONYMOUS_ITEMS + 1) : 1;
}
class MenuGroupTitleViewHolder extends RecyclerView.ViewHolder {

View File

@@ -17,12 +17,11 @@ import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData;
public class NavigationDrawerRecyclerViewMergedAdapter {
private HeaderSectionRecyclerViewAdapter headerSectionRecyclerViewAdapter;
private AccountSectionRecyclerViewAdapter accountSectionRecyclerViewAdapter;
private RedditSectionRecyclerViewAdapter redditSectionRecyclerViewAdapter;
private PostSectionRecyclerViewAdapter postSectionRecyclerViewAdapter;
private PreferenceSectionRecyclerViewAdapter preferenceSectionRecyclerViewAdapter;
private FavoriteSubscribedSubredditsSectionRecyclerViewAdapter favoriteSubscribedSubredditsSectionRecyclerViewAdapter;
private SubscribedSubredditsRecyclerViewAdapter subscribedSubredditsRecyclerViewAdapter;
private AccountManagementSectionRecyclerViewAdapter accountManagementSectionRecyclerViewAdapter;
private LemmySectionRecyclerViewAdapter lemmySectionRecyclerViewAdapter;
private ConcatAdapter mainPageConcatAdapter;
public NavigationDrawerRecyclerViewMergedAdapter(BaseActivity baseActivity, SharedPreferences sharedPreferences,
@@ -30,12 +29,12 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
SharedPreferences navigationDrawerSharedPreferences,
SharedPreferences securitySharedPreferences,
CustomThemeWrapper customThemeWrapper,
String accountName,
String accountName, String accountQualifiedName,
ItemClickListener itemClickListener) {
RequestManager glide = Glide.with(baseActivity);
headerSectionRecyclerViewAdapter = new HeaderSectionRecyclerViewAdapter(baseActivity, customThemeWrapper,
glide, accountName, sharedPreferences, navigationDrawerSharedPreferences, securitySharedPreferences,
glide, accountName, accountQualifiedName, sharedPreferences, navigationDrawerSharedPreferences, securitySharedPreferences,
new HeaderSectionRecyclerViewAdapter.PageToggle() {
@Override
public void openAccountSection() {
@@ -49,10 +48,6 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
});
accountSectionRecyclerViewAdapter = new AccountSectionRecyclerViewAdapter(baseActivity, customThemeWrapper,
navigationDrawerSharedPreferences, accountName != null, itemClickListener);
redditSectionRecyclerViewAdapter = new RedditSectionRecyclerViewAdapter(baseActivity, customThemeWrapper,
navigationDrawerSharedPreferences, itemClickListener, accountName != null);
postSectionRecyclerViewAdapter = new PostSectionRecyclerViewAdapter(baseActivity, customThemeWrapper,
navigationDrawerSharedPreferences, accountName != null, itemClickListener);
preferenceSectionRecyclerViewAdapter = new PreferenceSectionRecyclerViewAdapter(baseActivity, customThemeWrapper,
accountName, nsfwAndSpoilerSharedPreferences, navigationDrawerSharedPreferences, itemClickListener);
favoriteSubscribedSubredditsSectionRecyclerViewAdapter = new FavoriteSubscribedSubredditsSectionRecyclerViewAdapter(
@@ -61,12 +56,13 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
customThemeWrapper, navigationDrawerSharedPreferences, itemClickListener);
accountManagementSectionRecyclerViewAdapter = new AccountManagementSectionRecyclerViewAdapter(baseActivity,
customThemeWrapper, glide, accountName != null, itemClickListener);
lemmySectionRecyclerViewAdapter = new LemmySectionRecyclerViewAdapter(baseActivity, customThemeWrapper,
navigationDrawerSharedPreferences, itemClickListener, accountName != null);
mainPageConcatAdapter = new ConcatAdapter(
headerSectionRecyclerViewAdapter,
accountSectionRecyclerViewAdapter,
redditSectionRecyclerViewAdapter,
postSectionRecyclerViewAdapter,
lemmySectionRecyclerViewAdapter,
preferenceSectionRecyclerViewAdapter,
favoriteSubscribedSubredditsSectionRecyclerViewAdapter,
subscribedSubredditsRecyclerViewAdapter);
@@ -78,8 +74,7 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
private void openAccountSection() {
mainPageConcatAdapter.removeAdapter(accountSectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(redditSectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(postSectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(lemmySectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(preferenceSectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(favoriteSubscribedSubredditsSectionRecyclerViewAdapter);
mainPageConcatAdapter.removeAdapter(subscribedSubredditsRecyclerViewAdapter);
@@ -91,8 +86,7 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
mainPageConcatAdapter.removeAdapter(accountManagementSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(accountSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(redditSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(postSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(lemmySectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(preferenceSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(favoriteSubscribedSubredditsSectionRecyclerViewAdapter);
mainPageConcatAdapter.addAdapter(subscribedSubredditsRecyclerViewAdapter);

View File

@@ -6,6 +6,7 @@ import com.google.common.util.concurrent.ListenableFuture;
import eu.toldi.infinityforlemmy.dto.AccountLoginDTO;
import eu.toldi.infinityforlemmy.dto.AuthDTO;
import eu.toldi.infinityforlemmy.dto.BlockCommunityDTO;
import eu.toldi.infinityforlemmy.dto.CommentDTO;
import eu.toldi.infinityforlemmy.dto.CommentVoteDTO;
import eu.toldi.infinityforlemmy.dto.DeleteCommentDTO;
@@ -14,12 +15,19 @@ import eu.toldi.infinityforlemmy.dto.EditCommentDTO;
import eu.toldi.infinityforlemmy.dto.EditPostDTO;
import eu.toldi.infinityforlemmy.dto.FollowCommunityDTO;
import eu.toldi.infinityforlemmy.dto.PostVoteDTO;
import eu.toldi.infinityforlemmy.dto.PrivateMessageDTO;
import eu.toldi.infinityforlemmy.dto.PrivateMessageReadDTO;
import eu.toldi.infinityforlemmy.dto.PrivateMessageReportDTO;
import eu.toldi.infinityforlemmy.dto.PrivateMessageUpdateDTO;
import eu.toldi.infinityforlemmy.dto.ReadCommentDTO;
import eu.toldi.infinityforlemmy.dto.ReadMessageDTO;
import eu.toldi.infinityforlemmy.dto.ReadPostDTO;
import eu.toldi.infinityforlemmy.dto.ReportCommentDTO;
import eu.toldi.infinityforlemmy.dto.ReportPostDTO;
import eu.toldi.infinityforlemmy.dto.SaveCommentDTO;
import eu.toldi.infinityforlemmy.dto.SavePostDTO;
import eu.toldi.infinityforlemmy.dto.SubmitPostDTO;
import eu.toldi.infinityforlemmy.dto.UserBlockDTO;
import eu.toldi.infinityforlemmy.message.MessageCount;
import okhttp3.MultipartBody;
import retrofit2.Call;
@@ -42,6 +50,10 @@ public interface LemmyAPI {
@GET("api/v3/user")
Call<String> userInfo(@Query("username") String username, @Query("auth") String access_token);
@Headers("Content-Type: application/json")
@POST("api/v3/user/block")
Call<String> userBlock(@Body UserBlockDTO params);
@GET("api/v3/user/mention")
Call<String> userMentions(@Query("sort") String sort, @Query("page") Integer page, @Query("limit") Integer limit, @Query("unread_only") boolean unread_only, @Query("auth") String access_token);
@@ -76,6 +88,10 @@ public interface LemmyAPI {
@POST("api/v3/post")
Call<String> postCreate(@Body SubmitPostDTO params);
@Headers("Content-Type: application/json")
@POST("api/v3/post/report")
Call<String> postReport(@Body ReportPostDTO params);
@Headers("Content-Type: application/json")
@PUT("api/v3/post")
Call<String> postUpdate(@Body EditPostDTO params);
@@ -132,10 +148,18 @@ public interface LemmyAPI {
@POST("api/v3/comment/like")
Call<String> commentLike(@Body CommentVoteDTO params);
@Headers("Content-Type: application/json")
@POST("api/v3/comment/report")
Call<String> commentReport(@Body ReportCommentDTO params);
@Headers("Content-Type: application/json")
@POST("api/v3/community/follow")
Call<String> communityFollow(@Body FollowCommunityDTO params);
@Headers("Content-Type: application/json")
@POST("api/v3/community/block")
Call<String> communityBlock(@Body BlockCommunityDTO params);
@Headers("Content-Type: application/json")
@PUT("api/v3/post/save")
Call<String> postSave(@Body SavePostDTO params);
@@ -221,4 +245,42 @@ public interface LemmyAPI {
@Query("id") int commentId,
@Query("auth") String auth
);
@GET("api/v3/site")
Call<String> getSiteInfo(
@Query("auth") String auth
);
@GET("api/v3/private_message/list")
Call<String> privateMessagesList(
@Query("page") Integer page,
@Query("limit") Integer limit,
@Query("unread_only") Boolean unread_only,
@NonNull @Query("auth") String auth
);
@POST("api/v3/private_message")
Call<String> privateMessageSend(
@Body PrivateMessageDTO params
);
@PUT("api/v3/private_message")
Call<String> privateMessageEdit(
@Body PrivateMessageUpdateDTO params
);
@POST("api/v3/private_message/delete")
Call<String> privateMessageDelete(
@Body PrivateMessageUpdateDTO params
);
@POST("api/v3/private_message/mark_as_read")
Call<String> privateMessageMarkAsRead(
@Body PrivateMessageReadDTO params
);
@POST("api/v3/private_message/report")
Call<String> privateMessageReport(
@Body PrivateMessageReportDTO params
);
}

View File

@@ -0,0 +1,130 @@
package eu.toldi.infinityforlemmy.asynctasks;
import android.os.Handler;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Executor;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityDao;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityData;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserDao;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserData;
public class InsertBlockedThings {
public static void insertBlockedThings(Executor executor, Handler handler,
RedditDataRoomDatabase redditDataRoomDatabase, @Nullable String accountName,
List<BlockedCommunityData> blockedCommunityDataList,
List<BlockedUserData> blockedUserDataDataList,
InsertBlockedThingListener insertSubscribedThingListener) {
executor.execute(() -> {
if (accountName != null && redditDataRoomDatabase.accountDao().getAccountData(accountName) == null) {
handler.post(insertSubscribedThingListener::insertSuccess);
return;
}
BlockedUserDao blockedUserDao = redditDataRoomDatabase.blockedUserDao();
BlockedCommunityDao blockedCommunityDao = redditDataRoomDatabase.blockedCommunityDao();
if (blockedCommunityDataList != null) {
List<BlockedCommunityData> existingBlockedCommunityDaoList =
blockedCommunityDao.getAllBlockedCommunitiesList(accountName);
Collections.sort(blockedCommunityDataList, (subscribedSubredditData, t1) -> subscribedSubredditData.getName().compareToIgnoreCase(t1.getName()));
List<String> unsubscribedSubreddits = new ArrayList<>();
compareTwoSubscribedSubredditList(blockedCommunityDataList, existingBlockedCommunityDaoList,
unsubscribedSubreddits);
for (String unsubscribed : unsubscribedSubreddits) {
blockedCommunityDao.deleteBlockedCommunity(unsubscribed, accountName);
}
for (BlockedCommunityData s : blockedCommunityDataList) {
blockedCommunityDao.insert(s);
}
}
if (blockedUserDataDataList != null) {
List<BlockedUserData> existingBlockedUserDataList =
blockedUserDao.getAllBlockedUsersList(accountName);
Collections.sort(blockedUserDataDataList, (subscribedUserData, t1) -> subscribedUserData.getName().compareToIgnoreCase(t1.getName()));
List<String> unsubscribedUsers = new ArrayList<>();
compareTwoSubscribedUserList(blockedUserDataDataList, existingBlockedUserDataList,
unsubscribedUsers);
for (String unsubscribed : unsubscribedUsers) {
blockedUserDao.deleteBlockedUser(unsubscribed, accountName);
}
for (BlockedUserData s : blockedUserDataDataList) {
blockedUserDao.insert(s);
}
}
handler.post(insertSubscribedThingListener::insertSuccess);
});
}
private static void compareTwoSubscribedSubredditList(List<BlockedCommunityData> newSubscribedSubreddits,
List<BlockedCommunityData> oldSubscribedSubreddits,
List<String> unsubscribedSubredditNames) {
int newIndex = 0;
for (int oldIndex = 0; oldIndex < oldSubscribedSubreddits.size(); oldIndex++) {
if (newIndex >= newSubscribedSubreddits.size()) {
for (; oldIndex < oldSubscribedSubreddits.size(); oldIndex++) {
unsubscribedSubredditNames.add(oldSubscribedSubreddits.get(oldIndex).getQualified_name());
}
return;
}
BlockedCommunityData old = oldSubscribedSubreddits.get(oldIndex);
for (; newIndex < newSubscribedSubreddits.size(); newIndex++) {
if (newSubscribedSubreddits.get(newIndex).getQualified_name().compareToIgnoreCase(old.getQualified_name()) == 0) {
newIndex++;
break;
}
if (newSubscribedSubreddits.get(newIndex).getQualified_name().compareToIgnoreCase(old.getQualified_name()) > 0) {
unsubscribedSubredditNames.add(old.getQualified_name());
break;
}
}
}
}
private static void compareTwoSubscribedUserList(List<BlockedUserData> newSubscribedUsers,
List<BlockedUserData> oldSubscribedUsers,
List<String> unsubscribedUserNames) {
int newIndex = 0;
for (int oldIndex = 0; oldIndex < oldSubscribedUsers.size(); oldIndex++) {
if (newIndex >= newSubscribedUsers.size()) {
for (; oldIndex < oldSubscribedUsers.size(); oldIndex++) {
unsubscribedUserNames.add(oldSubscribedUsers.get(oldIndex).getQualifiedName());
}
return;
}
BlockedUserData old = oldSubscribedUsers.get(oldIndex);
for (; newIndex < newSubscribedUsers.size(); newIndex++) {
if (newSubscribedUsers.get(newIndex).getName().compareToIgnoreCase(old.getName()) == 0) {
newIndex++;
break;
}
if (newSubscribedUsers.get(newIndex).getName().compareToIgnoreCase(old.getName()) > 0) {
unsubscribedUserNames.add(old.getQualifiedName());
break;
}
}
}
}
public interface InsertBlockedThingListener {
void insertSuccess();
}
}

View File

@@ -9,6 +9,7 @@ import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.subreddit.FetchSubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditDao;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import retrofit2.Retrofit;
public class LoadSubredditIcon {
@@ -18,9 +19,9 @@ public class LoadSubredditIcon {
LoadSubredditIconAsyncTaskListener loadSubredditIconAsyncTaskListener) {
executor.execute(() -> {
SubredditDao subredditDao = redditDataRoomDatabase.subredditDao();
SubredditData subredditData = subredditDao.getSubredditData(subredditName);
SubredditData subredditData = subredditDao.getSubredditDataByActorId(LemmyUtils.qualifiedCommunityName2ActorId(subredditName));
if (subredditData != null) {
String iconImageUrl = subredditDao.getSubredditData(subredditName).getIconUrl();
String iconImageUrl = subredditDao.getSubredditDataByActorId(LemmyUtils.qualifiedCommunityName2ActorId(subredditName)).getIconUrl();
handler.post(() -> loadSubredditIconAsyncTaskListener.loadIconSuccess(iconImageUrl));
} else {
handler.post(() -> FetchSubredditData.fetchSubredditData(retrofit, subredditName, accessToken, new FetchSubredditData.FetchSubredditDataListener() {

View File

@@ -8,6 +8,7 @@ import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.user.FetchUserData;
import eu.toldi.infinityforlemmy.user.UserDao;
import eu.toldi.infinityforlemmy.user.UserData;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import retrofit2.Retrofit;
public class LoadUserData {
@@ -16,8 +17,9 @@ public class LoadUserData {
Retrofit retrofit, LoadUserDataAsyncTaskListener loadUserDataAsyncTaskListener) {
executor.execute(() -> {
UserDao userDao = redditDataRoomDatabase.userDao();
if (userDao.getUserData(userName) != null) {
String iconImageUrl = userDao.getUserData(userName).getIconUrl();
UserData userData= userDao.getUserDataByActorId(LemmyUtils.qualifiedUserName2ActorId(userName));
if (userData != null) {
String iconImageUrl = userData.getIconUrl();
handler.post(() -> loadUserDataAsyncTaskListener.loadUserDataSuccess(iconImageUrl));
} else {
handler.post(() -> FetchUserData.fetchUserData(retrofit, userName, new FetchUserData.FetchUserDataListener() {

View File

@@ -11,11 +11,11 @@ public class ParseAndInsertNewAccount {
public static void parseAndInsertNewAccount(Executor executor, Handler handler, String username,
String display_name,String accessToken, String profileImageUrl,
String bannerImageUrl, String code,String instance, AccountDao accountDao,
String bannerImageUrl, String code,String instance,boolean can_downvote, AccountDao accountDao,
ParseAndInsertAccountListener parseAndInsertAccountListener) {
executor.execute(() -> {
Account account = new Account(username,display_name, accessToken, code, profileImageUrl,
bannerImageUrl, true,instance);
bannerImageUrl, true,instance,true);
accountDao.markAllAccountsNonCurrent();
accountDao.insert(account);

View File

@@ -8,6 +8,8 @@ import java.util.concurrent.Executor;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.account.Account;
import eu.toldi.infinityforlemmy.site.FetchSiteInfo;
import eu.toldi.infinityforlemmy.site.SiteInfo;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
public class SwitchAccount {
@@ -26,6 +28,18 @@ public class SwitchAccount {
.putString(SharedPreferencesUtils.ACCOUNT_INSTANCE,account.getInstance_url())
.putString(SharedPreferencesUtils.ACCOUNT_IMAGE_URL, account.getProfileImageUrl()).apply();
retrofitHolder.setBaseURL(account.getInstance_url());
FetchSiteInfo.fetchSiteInfo(retrofitHolder.getRetrofit(), account.getAccessToken(), new FetchSiteInfo.FetchSiteInfoListener() {
@Override
public void onFetchSiteInfoSuccess(SiteInfo siteInfo) {
boolean canDownvote = siteInfo.isEnable_downvotes();
currentAccountSharedPreferences.edit().putBoolean(SharedPreferencesUtils.CAN_DOWNVOTE, canDownvote).apply();
}
@Override
public void onFetchSiteInfoFailed() {
currentAccountSharedPreferences.edit().putBoolean(SharedPreferencesUtils.CAN_DOWNVOTE, true).apply();
}
});
handler.post(() -> switchAccountListener.switched(account));
});

View File

@@ -0,0 +1,30 @@
package eu.toldi.infinityforlemmy.blockedcommunity;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
@Dao
public interface BlockedCommunityDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(BlockedCommunityData communityData);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<BlockedCommunityData> blockedCommunityDataList);
@Query("SELECT * FROM blocked_communities WHERE account_name = :accountName AND name LIKE '%' || :searchQuery || '%' COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC")
LiveData<List<BlockedCommunityData>> getAllBlockedCommunitiesWithSearchQuery(String accountName, String searchQuery);
@Query("SELECT * FROM blocked_communities WHERE account_name = :accountName COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC")
List<BlockedCommunityData> getAllBlockedCommunitiesList(String accountName);
@Query("SELECT * FROM blocked_communities WHERE name = :name COLLATE NOCASE AND account_name = :accountName COLLATE NOCASE LIMIT 1")
BlockedCommunityData getBlockedCommunity(String name, String accountName);
@Query("DELETE FROM blocked_communities WHERE qualified_name = :name COLLATE NOCASE AND account_name = :accountName COLLATE NOCASE")
void deleteBlockedCommunity(String name, String accountName);
}

View File

@@ -0,0 +1,80 @@
package eu.toldi.infinityforlemmy.blockedcommunity;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
@Entity(tableName = "blocked_communities", primaryKeys = {"id", "account_name"})
public class BlockedCommunityData {
@ColumnInfo(name = "id")
private final int id;
@ColumnInfo(name = "name")
private String name;
@ColumnInfo(name = "qualified_name")
private String qualified_name;
@ColumnInfo(name = "icon")
private String iconUrl;
@NonNull
@ColumnInfo(name = "account_name")
private String accountName;
public BlockedCommunityData(int id, String name, String qualified_name, String iconUrl, @NonNull String accountName) {
this.id = id;
this.name = name;
this.qualified_name = qualified_name;
this.iconUrl = iconUrl;
this.accountName = accountName;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getQualified_name() {
return qualified_name;
}
public String getIconUrl() {
return iconUrl;
}
@NonNull
public String getAccountName() {
return accountName;
}
public void setName(String name) {
this.name = name;
}
public void setQualified_name(String qualified_name) {
this.qualified_name = qualified_name;
}
public void setIconUrl(String iconUrl) {
this.iconUrl = iconUrl;
}
public void setAccountName(@NonNull String accountName) {
this.accountName = accountName;
}
public BlockedCommunityData(SubredditData subredditData, @NonNull String accountName) {
this.id = subredditData.getId();
this.name = subredditData.getName();
this.qualified_name = LemmyUtils.actorID2FullName(subredditData.getActorId());
this.iconUrl = subredditData.getIconUrl();
this.accountName = accountName;
}
}

View File

@@ -0,0 +1,42 @@
package eu.toldi.infinityforlemmy.blockedcommunity;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import java.util.List;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class BlockedCommunityRepository {
private BlockedCommunityDao blockedCommunityDao;
private String mAccountName;
BlockedCommunityRepository(RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
mAccountName = accountName;
blockedCommunityDao = redditDataRoomDatabase.blockedCommunityDao();
}
LiveData<List<BlockedCommunityData>> getAllSubscribedSubredditsWithSearchQuery(String searchQuery) {
return blockedCommunityDao.getAllBlockedCommunitiesWithSearchQuery(mAccountName, searchQuery);
}
public void insert(BlockedCommunityData subscribedSubredditData) {
new insertAsyncTask(blockedCommunityDao).execute(subscribedSubredditData);
}
private static class insertAsyncTask extends AsyncTask<BlockedCommunityData, Void, Void> {
private BlockedCommunityDao mAsyncTaskDao;
insertAsyncTask(BlockedCommunityDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final BlockedCommunityData... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
}
}

View File

@@ -0,0 +1,60 @@
package eu.toldi.infinityforlemmy.blockedcommunity;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import java.util.List;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class BlockedCommunityViewModel extends AndroidViewModel {
private BlockedCommunityRepository blockedCommunityRepository;
private LiveData<List<BlockedCommunityData>> mAllBlockedCommunities;
private MutableLiveData<String> searchQueryLiveData;
public BlockedCommunityViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
super(application);
blockedCommunityRepository = new BlockedCommunityRepository(redditDataRoomDatabase, accountName);
searchQueryLiveData = new MutableLiveData<>();
searchQueryLiveData.postValue("");
mAllBlockedCommunities = Transformations.switchMap(searchQueryLiveData, searchQuery -> blockedCommunityRepository.getAllSubscribedSubredditsWithSearchQuery(searchQuery));
}
public LiveData<List<BlockedCommunityData>> getAllBlockedCommunities() {
return mAllBlockedCommunities;
}
public void insert(BlockedCommunityData subscribedSubredditData) {
blockedCommunityRepository.insert(subscribedSubredditData);
}
public void setSearchQuery(String searchQuery) {
searchQueryLiveData.postValue(searchQuery);
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private Application mApplication;
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private String mAccountName;
public Factory(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
this.mApplication = application;
this.mRedditDataRoomDatabase = redditDataRoomDatabase;
this.mAccountName = accountName;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new BlockedCommunityViewModel(mApplication, mRedditDataRoomDatabase, mAccountName);
}
}
}

View File

@@ -0,0 +1,31 @@
package eu.toldi.infinityforlemmy.blockeduser;
import androidx.lifecycle.LiveData;
import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.OnConflictStrategy;
import androidx.room.Query;
import java.util.List;
@Dao
public interface BlockedUserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(BlockedUserData userData);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<BlockedUserData> blockedUserDataDataList);
@Query("SELECT * FROM blocked_users WHERE account_name = :accountName AND name LIKE '%' || :searchQuery || '%' COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC")
LiveData<List<BlockedUserData>> getAllBlockedUsersWithSearchQuery(String accountName, String searchQuery);
@Query("SELECT * FROM blocked_users WHERE account_name = :accountName COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC")
List<BlockedUserData> getAllBlockedUsersList(String accountName);
@Query("SELECT * FROM blocked_users WHERE name = :name COLLATE NOCASE AND account_name = :accountName COLLATE NOCASE LIMIT 1")
BlockedUserData getBlockedUser(String name, String accountName);
@Query("DELETE FROM blocked_users WHERE qualified_name = :name COLLATE NOCASE AND account_name = :accountName COLLATE NOCASE")
void deleteBlockedUser(String name, String accountName);
}

View File

@@ -0,0 +1,80 @@
package eu.toldi.infinityforlemmy.blockeduser;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import eu.toldi.infinityforlemmy.user.UserData;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
@Entity(tableName = "blocked_users", primaryKeys = {"id", "account_name"})
public class BlockedUserData {
@ColumnInfo(name = "id")
private final int id;
@ColumnInfo(name = "name")
private String name;
@ColumnInfo(name = "avatar")
private String avatar;
@ColumnInfo(name = "qualified_name")
private String qualifiedName;
@NonNull
@ColumnInfo(name = "account_name")
private String accountName;
public BlockedUserData(int id, String name, String avatar, String qualifiedName, String accountName) {
this.id = id;
this.name = name;
this.avatar = avatar;
this.qualifiedName = qualifiedName;
this.accountName = accountName;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getQualifiedName() {
return qualifiedName;
}
public void setQualifiedName(String qualifiedName) {
this.qualifiedName = qualifiedName;
}
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public BlockedUserData(UserData userData, @NonNull String accountName) {
this.id = userData.getId();
this.name = userData.getName();
this.avatar = userData.getAvatar();
this.qualifiedName = LemmyUtils.actorID2FullName(userData.getActorId());
this.accountName = accountName;
}
}

View File

@@ -0,0 +1,47 @@
package eu.toldi.infinityforlemmy.blockeduser;
import android.os.AsyncTask;
import androidx.lifecycle.LiveData;
import java.util.List;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class BlockedUserRepository {
private BlockedUserDao mBlockedUserDao;
private String mAccountName;
BlockedUserRepository(RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
mBlockedUserDao = redditDataRoomDatabase.blockedUserDao();
mAccountName = accountName;
}
LiveData<List<BlockedUserData>> getAllBlockedUsersWithSearchQuery(String searchQuery) {
return mBlockedUserDao.getAllBlockedUsersWithSearchQuery(mAccountName, searchQuery);
}
LiveData<List<BlockedUserData>> getAllFavoriteSubscribedUsersWithSearchQuery(String searchQuery) {
return mBlockedUserDao.getAllBlockedUsersWithSearchQuery(mAccountName, searchQuery);
}
public void insert(BlockedUserData BlockedUserData) {
new BlockedUserRepository.insertAsyncTask(mBlockedUserDao).execute(BlockedUserData);
}
private static class insertAsyncTask extends AsyncTask<BlockedUserData, Void, Void> {
private BlockedUserDao mAsyncTaskDao;
insertAsyncTask(BlockedUserDao dao) {
mAsyncTaskDao = dao;
}
@Override
protected Void doInBackground(final BlockedUserData... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
}
}

View File

@@ -0,0 +1,61 @@
package eu.toldi.infinityforlemmy.blockeduser;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider;
import java.util.List;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class BlockedUserViewModel extends AndroidViewModel {
private BlockedUserRepository blockedUserRepository;
private LiveData<List<BlockedUserData>> mAllSubscribedUsers;
private MutableLiveData<String> searchQueryLiveData;
public BlockedUserViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
super(application);
blockedUserRepository = new BlockedUserRepository(redditDataRoomDatabase, accountName);
searchQueryLiveData = new MutableLiveData<>();
searchQueryLiveData.postValue("");
mAllSubscribedUsers = Transformations.switchMap(searchQueryLiveData, searchQuery -> blockedUserRepository.getAllFavoriteSubscribedUsersWithSearchQuery(searchQuery));
}
public LiveData<List<BlockedUserData>> getAllSubscribedUsers() {
return mAllSubscribedUsers;
}
public void insert(BlockedUserData BlockedUserData) {
blockedUserRepository.insert(BlockedUserData);
}
public void setSearchQuery(String searchQuery) {
searchQueryLiveData.postValue(searchQuery);
}
public static class Factory extends ViewModelProvider.NewInstanceFactory {
private Application mApplication;
private RedditDataRoomDatabase mRedditDataRoomDatabase;
private String mAccountName;
public Factory(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
mApplication = application;
mRedditDataRoomDatabase = redditDataRoomDatabase;
mAccountName = accountName;
}
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
return (T) new BlockedUserViewModel(mApplication, mRedditDataRoomDatabase, mAccountName);
}
}
}

View File

@@ -10,24 +10,32 @@ import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
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 com.google.android.material.dialog.MaterialAlertDialogBuilder;
import javax.inject.Inject;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.CommentActivity;
import eu.toldi.infinityforlemmy.activities.EditCommentActivity;
import eu.toldi.infinityforlemmy.activities.GiveAwardActivity;
import eu.toldi.infinityforlemmy.activities.ReportActivity;
import eu.toldi.infinityforlemmy.activities.ViewPostDetailActivity;
import eu.toldi.infinityforlemmy.activities.ViewUserDetailActivity;
import eu.toldi.infinityforlemmy.comment.Comment;
import eu.toldi.infinityforlemmy.comment.LemmyCommentAPI;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.LandscapeExpandedRoundedBottomSheetDialogFragment;
import eu.toldi.infinityforlemmy.utils.Utils;
@@ -55,12 +63,15 @@ public class CommentMoreBottomSheetFragment extends LandscapeExpandedRoundedBott
TextView shareTextView;
@BindView(R.id.copy_text_view_comment_more_bottom_sheet_fragment)
TextView copyTextView;
@BindView(R.id.give_award_text_view_comment_more_bottom_sheet_fragment)
TextView giveAwardTextView;
@BindView(R.id.report_view_comment_more_bottom_sheet_fragment)
TextView reportTextView;
@BindView(R.id.see_removed_view_comment_more_bottom_sheet_fragment)
TextView seeRemovedTextView;
@Inject
LemmyCommentAPI lemmyCommentAPI;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
private BaseActivity activity;
public CommentMoreBottomSheetFragment() {
@@ -70,6 +81,7 @@ public class CommentMoreBottomSheetFragment extends LandscapeExpandedRoundedBott
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((Infinity) activity.getApplication()).getAppComponent().inject(this);
View rootView = inflater.inflate(R.layout.fragment_comment_more_bottom_sheet, container, false);
ButterKnife.bind(this, rootView);
@@ -93,18 +105,6 @@ public class CommentMoreBottomSheetFragment extends LandscapeExpandedRoundedBott
boolean showReplyAndSaveOption = bundle.getBoolean(EXTRA_SHOW_REPLY_AND_SAVE_OPTION, false);
if (accessToken != null && !accessToken.equals("")) {
giveAwardTextView.setVisibility(View.VISIBLE);
giveAwardTextView.setOnClickListener(view -> {
Intent intent = new Intent(activity, GiveAwardActivity.class);
intent.putExtra(GiveAwardActivity.EXTRA_THING_FULLNAME, comment.getFullName());
intent.putExtra(GiveAwardActivity.EXTRA_ITEM_POSITION, bundle.getInt(EXTRA_POSITION));
if (activity instanceof ViewPostDetailActivity) {
activity.startActivityForResult(intent, ViewPostDetailActivity.GIVE_AWARD_REQUEST_CODE);
} else if (activity instanceof ViewUserDetailActivity) {
activity.startActivityForResult(intent, ViewUserDetailActivity.GIVE_AWARD_REQUEST_CODE);
}
dismiss();
});
if (editAndDeleteAvailable) {
editTextView.setVisibility(View.VISIBLE);
@@ -193,27 +193,47 @@ public class CommentMoreBottomSheetFragment extends LandscapeExpandedRoundedBott
});
reportTextView.setOnClickListener(view -> {
Intent intent = new Intent(activity, ReportActivity.class);
intent.putExtra(ReportActivity.EXTRA_SUBREDDIT_NAME, comment.getCommunityName());
intent.putExtra(ReportActivity.EXTRA_THING_FULLNAME, comment.getFullName());
activity.startActivity(intent);
if (accessToken == null) {
Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show();
dismiss();
return;
}
LayoutInflater dialog_inflater = LayoutInflater.from(activity);
View dialog_view = dialog_inflater.inflate(R.layout.dialog_report, null);
EditText reasonEditText = dialog_view.findViewById(R.id.reasonEditText);
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(activity)
.setTitle(R.string.report_post)
.setView(dialog_view)
.setNegativeButton(R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss())
.setPositiveButton(R.string.send_report, (dialogInterface, i) -> {
String reason = reasonEditText.getText().toString();
if (reason.isEmpty()) {
Toast.makeText(activity, "A report reason must be provided", Toast.LENGTH_SHORT).show();
return;
}
lemmyCommentAPI.reportComment(comment.getId(), reason, accessToken, new LemmyCommentAPI.ReportCommentCallback() {
@Override
public void onSuccess() {
Toast.makeText(activity, R.string.report_successful, Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure() {
Toast.makeText(activity, R.string.report_failed, Toast.LENGTH_SHORT).show();
}
});
});
AlertDialog dialog = builder.create();
dialog.show();
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
positiveButton.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
negativeButton.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
dismiss();
});
if ("[deleted]".equals(comment.getAuthor()) ||
"[deleted]".equals(comment.getCommentRawText()) ||
"[removed]".equals(comment.getCommentRawText())
) {
seeRemovedTextView.setVisibility(View.VISIBLE);
seeRemovedTextView.setOnClickListener(view -> {
dismiss();
if (activity instanceof ViewPostDetailActivity) {
((ViewPostDetailActivity) activity).showRemovedComment(comment, bundle.getInt(EXTRA_POSITION));
}
});
}
if (activity.typeface != null) {
Utils.setFontToAllTextViews(rootView, activity.typeface);

View File

@@ -24,7 +24,6 @@ public class FABMoreOptionsBottomSheetFragment extends LandscapeExpandedRoundedB
public static final int FAB_OPTION_SEARCH = 4;
public static final int FAB_OPTION_GO_TO_SUBREDDIT = 5;
public static final int FAB_OPTION_GO_TO_USER = 6;
public static final int FAB_RANDOM = 7;
public static final int FAB_HIDE_READ_POSTS = 8;
public static final int FAB_FILTER_POSTS = 9;
public static final int FAB_GO_TO_TOP = 10;
@@ -86,10 +85,6 @@ public class FABMoreOptionsBottomSheetFragment extends LandscapeExpandedRoundedB
dismiss();
});
binding.randomTextViewFabMoreOptionsBottomSheetFragment.setOnClickListener(view -> {
activity.fabOptionSelected(FAB_RANDOM);
dismiss();
});
binding.filterPostsTextViewFabMoreOptionsBottomSheetFragment.setOnClickListener(view -> {
activity.fabOptionSelected(FAB_FILTER_POSTS);

View File

@@ -31,16 +31,12 @@ public class SearchPostSortTypeBottomSheetFragment extends LandscapeExpandedRoun
public static final String EXTRA_CURRENT_SORT_TYPE = "ECST";
@BindView(R.id.relevance_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView relevanceTypeTextView;
@BindView(R.id.hot_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView hotTypeTextView;
@BindView(R.id.top_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView topTypeTextView;
@BindView(R.id.new_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView newTypeTextView;
@BindView(R.id.comments_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView commentsTypeTextView;
@BindView(R.id.old_type_text_view_search_sort_type_bottom_sheet_fragment)
TextView oldTypeTextView;
private BaseActivity activity;
public SearchPostSortTypeBottomSheetFragment() {
// Required empty public constructor
@@ -61,14 +57,12 @@ public class SearchPostSortTypeBottomSheetFragment extends LandscapeExpandedRoun
ButterKnife.bind(this, rootView);
String currentSortType = getArguments().getString(EXTRA_CURRENT_SORT_TYPE);
if (currentSortType.equals(SortType.Type.HOT.fullName)) {
hotTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(hotTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
} else if (currentSortType.equals(SortType.Type.TOP.fullName)) {
if (currentSortType.equals(SortType.Type.TOP.fullName)) {
topTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(topTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
} else if (currentSortType.equals(SortType.Type.NEW.fullName)) {
newTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(newTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
} else if (currentSortType.equals(SortType.Type.OLD.fullName)) {
commentsTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(commentsTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
oldTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(oldTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
@@ -76,15 +70,6 @@ public class SearchPostSortTypeBottomSheetFragment extends LandscapeExpandedRoun
rootView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
}
/*relevanceTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(SortType.Type.RELEVANCE.name());
dismiss();
});*/
hotTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(SortType.Type.HOT.name());
dismiss();
});
topTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(SortType.Type.TOP.name());
@@ -92,12 +77,12 @@ public class SearchPostSortTypeBottomSheetFragment extends LandscapeExpandedRoun
});
newTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(new SortType(SortType.Type.NEW));
((SortTypeSelectionCallback) activity).sortTypeSelected(new SortType(SortType.Type.NEW,null));
dismiss();
});
commentsTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(SortType.Type.MOST_COMMENTS.name());
oldTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(new SortType(SortType.Type.OLD,null));
dismiss();
});

View File

@@ -41,7 +41,8 @@ public class Comment implements Parcelable {
private String communityQualifiedName;
private Integer parentId;
private int score;
private int downvotes;
private int upvotes;
private int voteType;
private boolean isSubmitter;
private String distinguished;
@@ -67,7 +68,7 @@ public class Comment implements Parcelable {
public Comment(int id, int postId, String fullName, String author, String authorQualifiedName, String linkAuthor,
long commentTimeMillis, String commentMarkdown, String commentRawText,
String linkId, String communityName, String communityQualifiedName, Integer parentId, int score,
String linkId, String communityName, String communityQualifiedName, Integer parentId, int downvotes,int upvotes,
int voteType, boolean isSubmitter, String distinguished, String permalink,
int depth, boolean collapsed, boolean hasReply, boolean saved, boolean deleted, long edited, String[] path) {
this.id = id;
@@ -83,7 +84,8 @@ public class Comment implements Parcelable {
this.communityName = communityName;
this.communityQualifiedName = communityQualifiedName;
this.parentId = parentId;
this.score = score;
this.downvotes = downvotes;
this.upvotes = upvotes;
this.voteType = voteType;
this.isSubmitter = isSubmitter;
this.distinguished = distinguished;
@@ -132,7 +134,8 @@ public class Comment implements Parcelable {
communityName = in.readString();
communityQualifiedName = in.readString();
parentId = in.readInt();
score = in.readInt();
downvotes = in.readInt();
upvotes = in.readInt();
voteType = in.readInt();
isSubmitter = in.readByte() != 0;
distinguished = in.readString();
@@ -228,11 +231,23 @@ public class Comment implements Parcelable {
}
public int getScore() {
return score;
return upvotes-downvotes;
}
public void setScore(int score) {
this.score = score;
public int getDownvotes() {
return downvotes;
}
public void setDownvotes(int downvotes) {
this.downvotes = downvotes;
}
public int getUpvotes() {
return upvotes;
}
public void setUpvotes(int upvotes) {
this.upvotes = upvotes;
}
public boolean isSubmitter() {
@@ -432,7 +447,8 @@ public class Comment implements Parcelable {
parcel.writeString(communityName);
parcel.writeString(communityQualifiedName);
parcel.writeInt(parentId == null ? 0 : parentId);
parcel.writeInt(score);
parcel.writeInt(downvotes);
parcel.writeInt(upvotes);
parcel.writeInt(voteType);
parcel.writeByte((byte) (isSubmitter ? 1 : 0));
parcel.writeString(distinguished);

View File

@@ -24,7 +24,6 @@ import java.util.TimeZone;
import java.util.concurrent.Executor;
import java.util.regex.Pattern;
import eu.toldi.infinityforlemmy.markdown.MarkdownUtils;
import eu.toldi.infinityforlemmy.utils.JSONUtils;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
@@ -285,6 +284,12 @@ public class ParseComment {
String author = creatorObj.getString("name");
String authorQualifiedName = LemmyUtils.actorID2FullName(creatorObj.getString("actor_id"));
String linkAuthor = creatorObj.getString("actor_id");
String authorAvatar = null;
if(creatorObj.has("avatar")){
authorAvatar = creatorObj.getString("avatar");
}
long commentTimeMillis = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
commentTimeMillis = ZonedDateTime.parse(commentObj.getString("published"),
@@ -304,17 +309,23 @@ public class ParseComment {
e.printStackTrace();
}
}
String content = MarkdownUtils.processImageCaptions(commentObj.getString("content"), "Image");
String content = commentObj.getString("content");
String commentMarkdown = content;
String commentRawText = content;
String linkId = postObj.getString("id");
String communityName = communityObj.getString("name");
String communityQualifiedName = LemmyUtils.actorID2FullName(communityObj.getString("actor_id"));
int score = countsObj.getInt("score");
int upvotes = countsObj.getInt("upvotes");
int downvotes = countsObj.getInt("downvotes");
int voteType = (jsonObject.isNull("my_vote")) ? 0 : jsonObject.getInt("my_vote");
if (voteType != 0)
score -= 1;
if (voteType != 0) {
if(voteType == 1) {
upvotes--;
} else {
downvotes--;
}
}
boolean isSubmitter = creatorObj.getInt("id") == postObj.getInt("creator_id");
String distinguished = commentObj.getString("distinguished");
String permalink = commentObj.getString("ap_id");
@@ -332,9 +343,10 @@ public class ParseComment {
Comment comment = new Comment(id, postID, fullName, author, authorQualifiedName, linkAuthor, commentTimeMillis,
commentMarkdown, commentRawText, linkId, communityName, communityQualifiedName, parentId,
score, voteType, isSubmitter, distinguished, permalink, depth, collapsed, hasReply, saved, deleted, edited, path);
downvotes,upvotes, voteType, isSubmitter, distinguished, permalink, depth, collapsed, hasReply, saved, deleted, edited, path);
int child_count = countsObj.getInt("child_count");
comment.setChildCount(child_count);
comment.setAuthorIconUrl(authorAvatar);
return comment;
}

View File

@@ -54,22 +54,22 @@ public class CustomThemeWrapper {
public int getColorPrimary() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COLOR_PRIMARY,
getDefaultColor("#0336FF", "#242424", "#000000"));
getDefaultColor("#0336FF", "#393A59", "#000000"));
}
public int getColorPrimaryDark() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COLOR_PRIMARY_DARK,
getDefaultColor("#002BF0", "#121212", "#000000"));
getDefaultColor("#002BF0", "#393A59", "#000000"));
}
public int getColorAccent() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COLOR_ACCENT,
getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
getDefaultColor("#FF1868", "#F8F8F2", "#FF1868"));
}
public int getColorPrimaryLightTheme() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COLOR_PRIMARY_LIGHT_THEME,
getDefaultColor("#0336FF", "#0336FF", "#0336FF"));
getDefaultColor("#0336FF", "#393A59", "#0336FF"));
}
public int getPrimaryTextColor() {
@@ -94,12 +94,12 @@ public class CustomThemeWrapper {
public int getReadPostTitleColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.READ_POST_TITLE_COLOR,
getDefaultColor("#9D9D9D", "#979797", "#979797"));
getDefaultColor("#9D9D9D", "#9D9D9D", "#979797"));
}
public int getReadPostContentColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.READ_POST_CONTENT_COLOR,
getDefaultColor("#9D9D9D", "#979797", "#979797"));
getDefaultColor("#9D9D9D", "#9D9D9D", "#979797"));
}
public int getCommentColor() {
@@ -114,27 +114,27 @@ public class CustomThemeWrapper {
public int getBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.BACKGROUND_COLOR,
getDefaultColor("#FFFFFF", "#121212", "#000000"));
getDefaultColor("#FFFFFF", "#282A36", "#000000"));
}
public int getCardViewBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.CARD_VIEW_BACKGROUND_COLOR,
getDefaultColor("#FFFFFF", "#242424", "#000000"));
getDefaultColor("#FFFFFF", "#393A59", "#000000"));
}
public int getReadPostCardViewBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.READ_POST_CARD_VIEW_BACKGROUND_COLOR,
getDefaultColor("#F5F5F5", "#101010", "#000000"));
getDefaultColor("#F5F5F5", "#1C1F3D", "#000000"));
}
public int getCommentBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COMMENT_BACKGROUND_COLOR,
getDefaultColor("#FFFFFF", "#242424", "#000000"));
getDefaultColor("#FFFFFF", "#393A59", "#000000"));
}
public int getBottomAppBarBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.BOTTOM_APP_BAR_BACKGROUND_COLOR,
getDefaultColor("#FFFFFF", "#121212", "#000000"));
getDefaultColor("#FFFFFF", "#393A59", "#000000"));
}
public int getPrimaryIconColor() {
@@ -169,22 +169,22 @@ public class CustomThemeWrapper {
public int getCircularProgressBarBackground() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.CIRCULAR_PROGRESS_BAR_BACKGROUND,
getDefaultColor("#FFFFFF", "#242424", "#000000"));
getDefaultColor("#FFFFFF", "#393A59", "#000000"));
}
public int getMediaIndicatorIconColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.MEDIA_INDICATOR_ICON_COLOR,
getDefaultColor("#FFFFFF", "#000000", "#000000"));
getDefaultColor("#FFFFFF", "#FFFFFF", "#000000"));
}
public int getMediaIndicatorBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.MEDIA_INDICATOR_BACKGROUND_COLOR,
getDefaultColor("#000000", "#FFFFFF", "#FFFFFF"));
getDefaultColor("#000000", "#000000", "#FFFFFF"));
}
public int getTabLayoutWithExpandedCollapsingToolbarTabBackground() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.TAB_LAYOUT_WITH_EXPANDED_COLLAPSING_TOOLBAR_TAB_BACKGROUND,
getDefaultColor("#FFFFFF", "#242424", "#000000"));
getDefaultColor("#FFFFFF", "#393A59", "#000000"));
}
public int getTabLayoutWithExpandedCollapsingToolbarTextColor() {
@@ -199,7 +199,7 @@ public class CustomThemeWrapper {
public int getTabLayoutWithCollapsedCollapsingToolbarTabBackground() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.TAB_LAYOUT_WITH_COLLAPSED_COLLAPSING_TOOLBAR_TAB_BACKGROUND,
getDefaultColor("#0336FF", "#242424", "#000000"));
getDefaultColor("#0336FF", "#393A59", "#000000"));
}
public int getTabLayoutWithCollapsedCollapsingToolbarTextColor() {
@@ -214,7 +214,7 @@ public class CustomThemeWrapper {
public int getUpvoted() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.UPVOTED,
getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
getDefaultColor("#FF1868", "#FF008C", "#FF1868"));
}
public int getDownvoted() {
@@ -294,12 +294,12 @@ public class CustomThemeWrapper {
public int getStickiedPostIconTint() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.STICKIED_POST_ICON_TINT,
getDefaultColor("#002BF0", "#0336FF", "#0336FF"));
getDefaultColor("#002BF0", "#02ABEE", "#0336FF"));
}
public int getNoPreviewPostTypeIconTint() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.NO_PREVIEW_POST_TYPE_ICON_TINT,
getDefaultColor("#808080", "#808080", "#808080"));
getDefaultColor("#808080", "#FFFFFF", "#808080"));
}
public int getSubscribed() {
@@ -309,7 +309,7 @@ public class CustomThemeWrapper {
public int getUnsubscribed() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.UNSUBSCRIBED,
getDefaultColor("#002BF0", "#0336FF", "#0336FF"));
getDefaultColor("#002BF0", "#002BF0", "#0336FF"));
}
public int getUsername() {
@@ -319,7 +319,7 @@ public class CustomThemeWrapper {
public int getSubreddit() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.SUBREDDIT,
getDefaultColor("#FF1868", "#FF1868", "#FF1868"));
getDefaultColor("#FF1868", "#FF4B9C", "#FF1868"));
}
public int getAuthorFlairTextColor() {
@@ -344,12 +344,12 @@ public class CustomThemeWrapper {
public int getSingleCommentThreadBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.SINGLE_COMMENT_THREAD_BACKGROUND_COLOR,
getDefaultColor("#B3E5F9", "#123E77", "#123E77"));
getDefaultColor("#B3E5F9", "#5F5B85", "#123E77"));
}
public int getUnreadMessageBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.UNREAD_MESSAGE_BACKGROUND_COLOR,
getDefaultColor("#B3E5F9", "#123E77", "#123E77"));
getDefaultColor("#B3E5F9", "#5F5B85", "#123E77"));
}
public int getDividerColor() {
@@ -359,52 +359,52 @@ public class CustomThemeWrapper {
public int getNoPreviewPostTypeBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.NO_PREVIEW_POST_TYPE_BACKGROUND_COLOR,
getDefaultColor("#E0E0E0", "#424242", "#424242"));
getDefaultColor("#E0E0E0", "#6272A4", "#424242"));
}
public int getVoteAndReplyUnavailableButtonColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.VOTE_AND_REPLY_UNAVAILABLE_BUTTON_COLOR,
getDefaultColor("#F0F0F0", "#3C3C3C", "#3C3C3C"));
getDefaultColor("#F0F0F0", "#777C82", "#3C3C3C"));
}
public int getCommentVerticalBarColor1() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COMMENT_VERTICAL_BAR_COLOR_1,
getDefaultColor("#0336FF", "#0336FF", "#0336FF"));
getDefaultColor("#0336FF", "#8BE9FD", "#0336FF"));
}
public int getCommentVerticalBarColor2() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COMMENT_VERTICAL_BAR_COLOR_2,
getDefaultColor("#EE02BE", "#C300B3", "#C300B3"));
getDefaultColor("#EE02BE", "#50FA7B", "#C300B3"));
}
public int getCommentVerticalBarColor3() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COMMENT_VERTICAL_BAR_COLOR_3,
getDefaultColor("#02DFEE", "#00B8DA", "#00B8DA"));
getDefaultColor("#02DFEE", "#FFB86C", "#00B8DA"));
}
public int getCommentVerticalBarColor4() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COMMENT_VERTICAL_BAR_COLOR_4,
getDefaultColor("#EED502", "#EDCA00", "#EDCA00"));
getDefaultColor("#EED502", "#FF79C6", "#EDCA00"));
}
public int getCommentVerticalBarColor5() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COMMENT_VERTICAL_BAR_COLOR_5,
getDefaultColor("#EE0220", "#EE0219", "#EE0219"));
getDefaultColor("#EE0220", "#BD93F9", "#EE0219"));
}
public int getCommentVerticalBarColor6() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COMMENT_VERTICAL_BAR_COLOR_6,
getDefaultColor("#02EE6E", "#00B925", "#00B925"));
getDefaultColor("#02EE6E", "#FF5555", "#00B925"));
}
public int getCommentVerticalBarColor7() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.COMMENT_VERTICAL_BAR_COLOR_7,
getDefaultColor("#EE4602", "#EE4602", "#EE4602"));
getDefaultColor("#EE4602", "#F1FA8C", "#EE4602"));
}
public int getFABIconColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.FAB_ICON_COLOR,
getDefaultColor("#FFFFFF", "#FFFFFF", "#FFFFFF"));
getDefaultColor("#FFFFFF", "#000000", "#FFFFFF"));
}
public int getChipTextColor() {
@@ -449,12 +449,12 @@ public class CustomThemeWrapper {
public int getAwardedCommentBackgroundColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.AWARDED_COMMENT_BACKGROUND_COLOR,
getDefaultColor("#FFFFFF", "#242424", "#000000"));
getDefaultColor("#FFFFFF", "#393A59", "#000000"));
}
public int getNavBarColor() {
return getThemeSharedPreferences().getInt(CustomThemeSharedPreferencesUtils.NAV_BAR_COLOR,
getDefaultColor("#FFFFFF", "#121212", "#000000"));
getDefaultColor("#FFFFFF", "#393A59", "#000000"));
}
public boolean isLightStatusBar() {
@@ -1536,4 +1536,17 @@ public class CustomThemeWrapper {
return customTheme;
}
public static int darkenColor(int color, float factor) {
int a = Color.alpha(color);
int r = Math.round(Color.red(color) * factor);
int g = Math.round(Color.green(color) * factor);
int b = Math.round(Color.blue(color) * factor);
return Color.argb(a,
Math.min(r, 255),
Math.min(g, 255),
Math.min(b, 255));
}
}

View File

@@ -1,12 +1,12 @@
package eu.toldi.infinityforlemmy.events;
import eu.toldi.infinityforlemmy.message.Message;
import eu.toldi.infinityforlemmy.privatemessage.PrivateMessage;
public class RepliedToPrivateMessageEvent {
public Message newReply;
public PrivateMessage newReply;
public int messagePosition;
public RepliedToPrivateMessageEvent(Message newReply, int messagePosition) {
public RepliedToPrivateMessageEvent(PrivateMessage newReply, int messagePosition) {
this.newReply = newReply;
this.messagePosition = messagePosition;
}

View File

@@ -0,0 +1,202 @@
package eu.toldi.infinityforlemmy.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.SubscribedThingListingActivity;
import eu.toldi.infinityforlemmy.adapters.BlockedCommunitiesRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.blockedcommunity.BlockedCommunityViewModel;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import me.zhanghai.android.fastscroll.FastScrollerBuilder;
import retrofit2.Retrofit;
/**
* A simple {@link Fragment} subclass.
*/
public class BlockedCommunitiesListingFragment extends Fragment implements FragmentCommunicator {
public static final String EXTRA_ACCOUNT_NAME = "EAN";
public static final String EXTRA_ACCESS_TOKEN = "EAT";
public static final String EXTRA_ACCOUNT_PROFILE_IMAGE_URL = "EAPIU";
public static final String EXTRA_IS_SUBREDDIT_SELECTION = "EISS";
public static final String EXTRA_EXTRA_CLEAR_SELECTION = "EECS";
public static final String EXTRA_ACCOUNT_QUALIFIED_NAME = "EAQN";
@BindView(R.id.swipe_refresh_layout_subscribed_subreddits_listing_fragment)
SwipeRefreshLayout mSwipeRefreshLayout;
@BindView(R.id.recycler_view_subscribed_subreddits_listing_fragment)
RecyclerView mRecyclerView;
@BindView(R.id.no_subscriptions_linear_layout_subreddits_listing_fragment)
LinearLayout mLinearLayout;
@BindView(R.id.no_subscriptions_image_view_subreddits_listing_fragment)
ImageView mImageView;
@BindView(R.id.error_text_view_subscribed_subreddits_listing_fragment)
TextView mErrorTextView;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
public BlockedCommunityViewModel mSubscribedSubredditViewModel;
private BaseActivity mActivity;
private RequestManager mGlide;
private LinearLayoutManagerBugFixed mLinearLayoutManager;
public BlockedCommunitiesListingFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_subscribed_subreddits_listing, container, false);
ButterKnife.bind(this, rootView);
((Infinity) mActivity.getApplication()).getAppComponent().inject(this);
applyTheme();
if ((mActivity instanceof BaseActivity && ((BaseActivity) mActivity).isImmersiveInterface())) {
mRecyclerView.setPadding(0, 0, 0, ((BaseActivity) mActivity).getNavBarHeight());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& mSharedPreferences.getBoolean(SharedPreferencesUtils.IMMERSIVE_INTERFACE_KEY, true)) {
Resources resources = getResources();
int navBarResourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (navBarResourceId > 0) {
mRecyclerView.setPadding(0, 0, 0, resources.getDimensionPixelSize(navBarResourceId));
}
}
String accountName = getArguments().getString(EXTRA_ACCOUNT_NAME, "-");
String accountQualifiedName = getArguments().getString(EXTRA_ACCOUNT_QUALIFIED_NAME, "-");
String accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
if (accessToken == null) {
mSwipeRefreshLayout.setEnabled(false);
}
mGlide = Glide.with(this);
mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
BlockedCommunitiesRecyclerViewAdapter adapter = new BlockedCommunitiesRecyclerViewAdapter(mActivity, mExecutor, mOauthRetrofit, mRedditDataRoomDatabase,
mCustomThemeWrapper, accessToken);
mRecyclerView.setAdapter(adapter);
new FastScrollerBuilder(mRecyclerView).useMd2Style().build();
mSubscribedSubredditViewModel = new ViewModelProvider(this,
new BlockedCommunityViewModel.Factory(mActivity.getApplication(), mRedditDataRoomDatabase, accountQualifiedName))
.get(BlockedCommunityViewModel.class);
mSubscribedSubredditViewModel.getAllBlockedCommunities().observe(getViewLifecycleOwner(), subscribedSubredditData -> {
mSwipeRefreshLayout.setRefreshing(false);
if (subscribedSubredditData == null || subscribedSubredditData.size() == 0) {
mRecyclerView.setVisibility(View.GONE);
mLinearLayout.setVisibility(View.VISIBLE);
mGlide.load(R.drawable.error_image).into(mImageView);
} else {
mLinearLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mGlide.clear(mImageView);
}
if (accessToken != null) {
adapter.addUser(accountName, getArguments().getString(EXTRA_ACCOUNT_PROFILE_IMAGE_URL));
}
adapter.setSubscribedSubreddits(subscribedSubredditData);
});
/* mSubscribedSubredditViewModel.getAllFavoriteSubscribedSubreddits().observe(getViewLifecycleOwner(), favoriteSubscribedSubredditData -> {
mSwipeRefreshLayout.setRefreshing(false);
if (favoriteSubscribedSubredditData != null && favoriteSubscribedSubredditData.size() > 0) {
mLinearLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mGlide.clear(mImageView);
}
adapter.setFavoriteSubscribedSubreddits(favoriteSubscribedSubredditData);
});*/
return rootView;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mActivity = (BaseActivity) context;
}
@Override
public void stopRefreshProgressbar() {
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void applyTheme() {
if (mActivity instanceof SubscribedThingListingActivity) {
mSwipeRefreshLayout.setOnRefreshListener(() -> ((SubscribedThingListingActivity) mActivity).loadSubscriptions(true));
mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground());
mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent());
} else {
mSwipeRefreshLayout.setEnabled(false);
}
mErrorTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
if (mActivity.typeface != null) {
mErrorTextView.setTypeface(mActivity.contentTypeface);
}
}
public void goBackToTop() {
if (mLinearLayoutManager != null) {
mLinearLayoutManager.scrollToPositionWithOffset(0, 0);
}
}
public void changeSearchQuery(String searchQuery) {
mSubscribedSubredditViewModel.setSearchQuery(searchQuery);
}
}

View File

@@ -0,0 +1,172 @@
package eu.toldi.infinityforlemmy.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import java.util.concurrent.Executor;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.BlockedThingListingActivity;
import eu.toldi.infinityforlemmy.adapters.BlockedUsersRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.blockeduser.BlockedUserViewModel;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import me.zhanghai.android.fastscroll.FastScrollerBuilder;
import retrofit2.Retrofit;
public class BlockedUsersListingFragment extends Fragment implements FragmentCommunicator {
public static final String EXTRA_ACCOUNT_NAME = "EAN";
public static final String EXTRA_ACCESS_TOKEN = "EAT";
@BindView(R.id.swipe_refresh_layout_followed_users_listing_fragment)
SwipeRefreshLayout mSwipeRefreshLayout;
@BindView(R.id.recycler_view_followed_users_listing_fragment)
RecyclerView mRecyclerView;
@BindView(R.id.no_subscriptions_linear_layout_followed_users_listing_fragment)
LinearLayout mLinearLayout;
@BindView(R.id.no_subscriptions_image_view_followed_users_listing_fragment)
ImageView mImageView;
@BindView(R.id.error_text_view_followed_users_listing_fragment)
TextView mErrorTextView;
@Inject
@Named("oauth")
Retrofit mOauthRetrofit;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
Executor mExecutor;
BlockedUserViewModel blockedUserViewModel;
private BaseActivity mActivity;
private RequestManager mGlide;
private LinearLayoutManagerBugFixed mLinearLayoutManager;
public BlockedUsersListingFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_followed_users_listing, container, false);
ButterKnife.bind(this, rootView);
((Infinity) mActivity.getApplication()).getAppComponent().inject(this);
applyTheme();
Resources resources = getResources();
if ((mActivity instanceof BaseActivity && ((BaseActivity) mActivity).isImmersiveInterface())) {
mRecyclerView.setPadding(0, 0, 0, ((BaseActivity) mActivity).getNavBarHeight());
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
&& mSharedPreferences.getBoolean(SharedPreferencesUtils.IMMERSIVE_INTERFACE_KEY, true)) {
int navBarResourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (navBarResourceId > 0) {
mRecyclerView.setPadding(0, 0, 0, resources.getDimensionPixelSize(navBarResourceId));
}
}
mGlide = Glide.with(this);
String accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
if (accessToken == null) {
mSwipeRefreshLayout.setEnabled(false);
}
mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
BlockedUsersRecyclerViewAdapter adapter = new BlockedUsersRecyclerViewAdapter(mActivity,
mExecutor, mOauthRetrofit, mRedditDataRoomDatabase, mCustomThemeWrapper, accessToken);
mRecyclerView.setAdapter(adapter);
new FastScrollerBuilder(mRecyclerView).useMd2Style().build();
blockedUserViewModel = new ViewModelProvider(this,
new BlockedUserViewModel.Factory(mActivity.getApplication(), mRedditDataRoomDatabase, getArguments().getString(EXTRA_ACCOUNT_NAME)))
.get(BlockedUserViewModel.class);
blockedUserViewModel.getAllSubscribedUsers().observe(getViewLifecycleOwner(), subscribedUserData -> {
mSwipeRefreshLayout.setRefreshing(false);
if (subscribedUserData == null || subscribedUserData.size() == 0) {
mRecyclerView.setVisibility(View.GONE);
mLinearLayout.setVisibility(View.VISIBLE);
mGlide.load(R.drawable.error_image).into(mImageView);
} else {
mLinearLayout.setVisibility(View.GONE);
mRecyclerView.setVisibility(View.VISIBLE);
mGlide.clear(mImageView);
}
adapter.setSubscribedUsers(subscribedUserData);
});
return rootView;
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mActivity = (BaseActivity) context;
}
@Override
public void stopRefreshProgressbar() {
mSwipeRefreshLayout.setRefreshing(false);
}
@Override
public void applyTheme() {
if (mActivity instanceof BlockedThingListingActivity) {
mSwipeRefreshLayout.setOnRefreshListener(() -> ((BlockedThingListingActivity) mActivity).loadBlocks(true));
mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground());
mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent());
} else {
mSwipeRefreshLayout.setEnabled(false);
}
mErrorTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
if (mActivity.typeface != null) {
mErrorTextView.setTypeface(mActivity.typeface);
}
}
public void goBackToTop() {
if (mLinearLayoutManager != null) {
mLinearLayoutManager.scrollToPositionWithOffset(0, 0);
}
}
public void changeSearchQuery(String searchQuery) {
blockedUserViewModel.setSearchQuery(searchQuery);
}
}

View File

@@ -1033,7 +1033,8 @@ public class HistoryPostFragment extends Fragment implements FragmentCommunicato
if (post != null && post.getFullName().equals(event.post.getFullName())) {
post.setTitle(event.post.getTitle());
post.setVoteType(event.post.getVoteType());
post.setScore(event.post.getScore());
post.setDownvotes(event.post.getDownvotes());
post.setUpvotes(event.post.getUpvotes());
post.setNComments(event.post.getNComments());
post.setNSFW(event.post.isNSFW());
post.setHidden(event.post.isHidden());

View File

@@ -460,9 +460,9 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
nameOfUsage = PostFilterUsage.NO_USAGE;
String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_SEARCH_POST, SortType.Type.TOP_ALL.value);
String sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_SEARCH_POST, SortType.Time.ALL.name());
String sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_SEARCH_POST, sort.equalsIgnoreCase(SortType.Type.TOP.value) ? SortType.Time.ALL.name() : null);
SortType.Type st = SortType.Type.fromValue(sort);
sortType = new SortType(st == null ? SortType.Type.TOP_ALL : st, SortType.Time.valueOf(sortTime));
sortType = new SortType(st == null ? SortType.Type.TOP_ALL : st,sortTime != null ? SortType.Time.valueOf(sortTime) : null);
postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_SEARCH_POST, defaultPostLayout);
mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mRetrofit.getRetrofit(), mGfycatRetrofit,
@@ -529,7 +529,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_SUBREDDIT_POST_BASE + subredditName,
mSharedPreferences.getString(SharedPreferencesUtils.SUBREDDIT_DEFAULT_SORT_TYPE, SortType.Type.HOT.name()));
if (sort.equals(sort.equals(SortType.Type.TOP.name()))) {
if (sort.equalsIgnoreCase(SortType.Type.TOP.value)) {
sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_SUBREDDIT_POST_BASE + subredditName,
mSharedPreferences.getString(SharedPreferencesUtils.SUBREDDIT_DEFAULT_SORT_TIME, SortType.Time.ALL.name()));
}
@@ -537,7 +537,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_SUBREDDIT_POST_BASE + subredditName, defaultPostLayout);
if (sortTime != null) {
sortType = new SortType(SortType.Type.valueOf(sort), SortType.Time.valueOf(sortTime));
sortType = new SortType(SortType.Type.fromValue(sortTime));
} else {
sortType = new SortType(SortType.Type.valueOf(sort));
}
@@ -669,10 +669,10 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_USER_POST_BASE + username,
mSharedPreferences.getString(SharedPreferencesUtils.USER_DEFAULT_SORT_TYPE, SortType.Type.NEW.name()));
if (sort.equals(SortType.Type.TOP.name())) {
if (sort.equalsIgnoreCase(SortType.Type.TOP.value)) {
String sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_USER_POST_BASE + username,
mSharedPreferences.getString(SharedPreferencesUtils.USER_DEFAULT_SORT_TIME, SortType.Time.ALL.name()));
sortType = new SortType(SortType.Type.valueOf(sort), SortType.Time.valueOf(sortTime));
sortType = new SortType(SortType.Type.fromValue(sortTime));
} else {
sortType = new SortType(SortType.Type.valueOf(sort));
}
@@ -1385,6 +1385,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
mSortTypeSharedPreferences.edit().putString(SharedPreferencesUtils.SORT_TYPE_SEARCH_POST, sortType.getType().name()).apply();
if (sortType.getTime() != null) {
mSortTypeSharedPreferences.edit().putString(SharedPreferencesUtils.SORT_TIME_SEARCH_POST, sortType.getTime().name()).apply();
}else {
mSortTypeSharedPreferences.edit().remove(SharedPreferencesUtils.SORT_TIME_SEARCH_POST).apply();
}
break;
case PostPagingSource.TYPE_MULTI_REDDIT:
@@ -1778,7 +1780,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
if (post != null && post.getFullName().equals(event.post.getFullName())) {
post.setTitle(event.post.getTitle());
post.setVoteType(event.post.getVoteType());
post.setScore(event.post.getScore());
post.setDownvotes(event.post.getDownvotes());
post.setUpvotes(event.post.getUpvotes());
post.setNComments(event.post.getNComments());
post.setNSFW(event.post.isNSFW());
post.setHidden(event.post.isHidden());

View File

@@ -0,0 +1,243 @@
package eu.toldi.infinityforlemmy.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.paging.PagedList;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import javax.inject.Inject;
import javax.inject.Named;
import butterknife.BindView;
import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.NetworkState;
import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.adapters.PrivateMessageRecycleViewAdapter;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
import eu.toldi.infinityforlemmy.events.RepliedToPrivateMessageEvent;
import eu.toldi.infinityforlemmy.privatemessage.LemmyPrivateMessageAPI;
import eu.toldi.infinityforlemmy.privatemessage.PrivateMessage;
import eu.toldi.infinityforlemmy.privatemessage.PrivateMessageViewModel;
public class PrivateMessageFragment extends Fragment implements FragmentCommunicator {
public static final String EXTRA_ACCESS_TOKEN = "EAT";
public static final String EXTRA_MESSAGE_WHERE = "EMT";
@BindView(R.id.swipe_refresh_layout_inbox_fragment)
SwipeRefreshLayout mSwipeRefreshLayout;
@BindView(R.id.recycler_view_inbox_fragment)
RecyclerView mRecyclerView;
@BindView(R.id.fetch_messages_info_linear_layout_inbox_fragment)
LinearLayout mFetchMessageInfoLinearLayout;
@BindView(R.id.fetch_messages_info_image_view_inbox_fragment)
ImageView mFetchMessageInfoImageView;
@BindView(R.id.fetch_messages_info_text_view_inbox_fragment)
TextView mFetchMessageInfoTextView;
PrivateMessageViewModel mMessageViewModel;
@Inject
@Named("no_oauth")
RetrofitHolder mRetrofit;
@Inject
RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject
@Named("default")
SharedPreferences mSharedPreferences;
@Inject
CustomThemeWrapper mCustomThemeWrapper;
@Inject
LemmyPrivateMessageAPI mLemmyPrivateMessageAPI;
private String mAccessToken;
private PrivateMessageRecycleViewAdapter mAdapter;
private RequestManager mGlide;
private LinearLayoutManagerBugFixed mLinearLayoutManager;
private BaseActivity mActivity;
public PrivateMessageFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("PrivateMessageFragment", "onCreateView");
View rootView = inflater.inflate(R.layout.fragment_inbox, container, false);
((Infinity) mActivity.getApplication()).getAppComponent().inject(this);
ButterKnife.bind(this, rootView);
EventBus.getDefault().register(this);
applyTheme();
Bundle arguments = getArguments();
if (arguments == null) {
return rootView;
}
mAccessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
mGlide = Glide.with(this);
if (mActivity.isImmersiveInterface()) {
mRecyclerView.setPadding(0, 0, 0, mActivity.getNavBarHeight());
}
mAdapter = new PrivateMessageRecycleViewAdapter(mActivity, mRetrofit.getRetrofit(), mCustomThemeWrapper, mAccessToken, mLemmyPrivateMessageAPI, () -> mMessageViewModel.refresh());
mLinearLayoutManager = new LinearLayoutManagerBugFixed(mActivity);
mRecyclerView.setLayoutManager(mLinearLayoutManager);
mRecyclerView.setAdapter(mAdapter);
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mActivity, mLinearLayoutManager.getOrientation());
mRecyclerView.addItemDecoration(dividerItemDecoration);
if (mActivity instanceof RecyclerViewContentScrollingInterface) {
mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) {
((RecyclerViewContentScrollingInterface) mActivity).contentScrollDown();
} else if (dy < 0) {
((RecyclerViewContentScrollingInterface) mActivity).contentScrollUp();
}
}
});
}
PrivateMessageViewModel.Factory factory = new PrivateMessageViewModel.Factory(mRetrofit.getRetrofit(),
getResources().getConfiguration().locale, mAccessToken, mLemmyPrivateMessageAPI);
mMessageViewModel = new ViewModelProvider(this, factory).get(PrivateMessageViewModel.class);
mMessageViewModel.getPrivateMessages().observe(getViewLifecycleOwner(), messages -> mAdapter.submitList(messages));
mMessageViewModel.getInitialLoadState().observe(getViewLifecycleOwner(), networkState -> {
if (networkState.getStatus().equals(NetworkState.Status.SUCCESS)) {
mSwipeRefreshLayout.setRefreshing(false);
} else if (networkState.getStatus().equals(NetworkState.Status.FAILED)) {
mSwipeRefreshLayout.setRefreshing(false);
mFetchMessageInfoLinearLayout.setOnClickListener(view -> {
mFetchMessageInfoLinearLayout.setVisibility(View.GONE);
mMessageViewModel.refresh();
mAdapter.setNetworkState(null);
});
showErrorView(R.string.load_messages_failed);
} else {
mSwipeRefreshLayout.setRefreshing(true);
}
});
mSwipeRefreshLayout.setOnRefreshListener(this::onRefresh);
return rootView;
}
private void showErrorView(int stringResId) {
mSwipeRefreshLayout.setRefreshing(false);
mFetchMessageInfoLinearLayout.setVisibility(View.VISIBLE);
mFetchMessageInfoTextView.setText(stringResId);
mGlide.load(R.drawable.error_image).into(mFetchMessageInfoImageView);
}
@Override
public void applyTheme() {
mSwipeRefreshLayout.setProgressBackgroundColorSchemeColor(mCustomThemeWrapper.getCircularProgressBarBackground());
mSwipeRefreshLayout.setColorSchemeColors(mCustomThemeWrapper.getColorAccent());
mFetchMessageInfoTextView.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
if (mActivity.typeface != null) {
mFetchMessageInfoTextView.setTypeface(mActivity.typeface);
}
}
public void goBackToTop() {
if (mLinearLayoutManager != null) {
mLinearLayoutManager.scrollToPositionWithOffset(0, 0);
}
}
public void markAllMessagesRead() {
if (mAdapter != null) {
mAdapter.setMarkAllMessagesAsRead(true);
int previousPosition = -1;
if (mLinearLayoutManager != null) {
previousPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
}
RecyclerView.LayoutManager layoutManager = mRecyclerView.getLayoutManager();
mRecyclerView.setAdapter(null);
mRecyclerView.setLayoutManager(null);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.setLayoutManager(layoutManager);
if (previousPosition > 0) {
mRecyclerView.scrollToPosition(previousPosition);
}
}
}
private void onRefresh() {
mMessageViewModel.refresh();
mSwipeRefreshLayout.setRefreshing(false);
}
public PrivateMessage getMessageByIndex(int index) {
if (mMessageViewModel == null || index < 0) {
return null;
}
PagedList<PrivateMessage> messages = mMessageViewModel.getPrivateMessages().getValue();
if (messages == null) {
return null;
}
if (index >= messages.size()) {
return null;
}
return messages.get(index);
}
@Override
public void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
mActivity = (BaseActivity) context;
}
@Subscribe
public void onRepliedToPrivateMessageEvent(RepliedToPrivateMessageEvent repliedToPrivateMessageEvent) {
/* if (mAdapter != null && mWhere.equals(FetchMessage.WHERE_MESSAGES)) {
mAdapter.updateMessageReply(repliedToPrivateMessageEvent.newReply, repliedToPrivateMessageEvent.messagePosition);
}*/
}
}

View File

@@ -40,6 +40,7 @@ import eu.toldi.infinityforlemmy.markdown.MarkdownUtils;
import eu.toldi.infinityforlemmy.subreddit.FetchSubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditViewModel;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration;
@@ -97,7 +98,7 @@ public class SidebarFragment extends Fragment {
mAccessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
subredditName = getArguments().getString(EXTRA_SUBREDDIT_NAME);
communityQualifiedName = getArguments().getString(EXTRA_COMMUNITY_QUALIFIED_NAME);
if (subredditName == null) {
if (communityQualifiedName == null) {
Toast.makeText(activity, R.string.error_getting_community_name, Toast.LENGTH_SHORT).show();
return rootView;
}
@@ -166,7 +167,7 @@ public class SidebarFragment extends Fragment {
});
mSubredditViewModel = new ViewModelProvider(activity,
new SubredditViewModel.Factory(activity.getApplication(), mRedditDataRoomDatabase, communityQualifiedName))
new SubredditViewModel.Factory(activity.getApplication(), mRedditDataRoomDatabase, LemmyUtils.qualifiedCommunityName2ActorId(communityQualifiedName)))
.get(SubredditViewModel.class);
mSubredditViewModel.getSubredditLiveData().observe(getViewLifecycleOwner(), subredditData -> {
if (subredditData != null) {

View File

@@ -61,6 +61,7 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
public static final String EXTRA_IS_GETTING_SUBREDDIT_INFO = "EIGSI";
public static final String EXTRA_ACCESS_TOKEN = "EAT";
public static final String EXTRA_ACCOUNT_NAME = "EAN";
public static final String EXTRA_ACCOUNT_QUALIFIED_NAME = "EAQN";
public static final String EXTRA_IS_MULTI_SELECTION = "EIMS";
@BindView(R.id.coordinator_layout_subreddit_listing_fragment)
@@ -135,13 +136,14 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
boolean isGettingSubredditInfo = getArguments().getBoolean(EXTRA_IS_GETTING_SUBREDDIT_INFO);
String accessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
String accountName = getArguments().getString(EXTRA_ACCOUNT_NAME);
String accountQualifiedName = getArguments().getString(EXTRA_ACCOUNT_QUALIFIED_NAME);
String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_SEARCH_SUBREDDIT, SortType.Type.TOP_ALL.value);
sortType = new SortType(SortType.Type.fromValue(sort));
boolean nsfw = !mSharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_NSFW_FOREVER, false) && mNsfwAndSpoilerSharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.NSFW_BASE, false);
mAdapter = new SubredditListingRecyclerViewAdapter(mActivity, mExecutor, mRetrofit.getRetrofit(), mRetrofit.getRetrofit(),
mCustomThemeWrapper, accessToken, accountName,
mCustomThemeWrapper, accessToken, accountQualifiedName,
mRedditDataRoomDatabase, getArguments().getBoolean(EXTRA_IS_MULTI_SELECTION, false),
new SubredditListingRecyclerViewAdapter.Callback() {
@Override

View File

@@ -24,6 +24,8 @@ import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
@@ -31,6 +33,7 @@ import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.view.menu.MenuItemImpl;
import androidx.core.content.res.ResourcesCompat;
@@ -78,9 +81,7 @@ import eu.toldi.infinityforlemmy.SaveThing;
import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.activities.CommentActivity;
import eu.toldi.infinityforlemmy.activities.EditPostActivity;
import eu.toldi.infinityforlemmy.activities.GiveAwardActivity;
import eu.toldi.infinityforlemmy.activities.PostFilterPreferenceActivity;
import eu.toldi.infinityforlemmy.activities.ReportActivity;
import eu.toldi.infinityforlemmy.activities.SubmitCrosspostActivity;
import eu.toldi.infinityforlemmy.activities.ViewPostDetailActivity;
import eu.toldi.infinityforlemmy.adapters.CommentsRecyclerViewAdapter;
@@ -88,12 +89,12 @@ import eu.toldi.infinityforlemmy.adapters.PostDetailRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.apis.StreamableAPI;
import eu.toldi.infinityforlemmy.asynctasks.LoadUserData;
import eu.toldi.infinityforlemmy.bottomsheetfragments.FlairBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.PostCommentSortTypeBottomSheetFragment;
import eu.toldi.infinityforlemmy.comment.Comment;
import eu.toldi.infinityforlemmy.comment.FetchComment;
import eu.toldi.infinityforlemmy.comment.FetchRemovedComment;
import eu.toldi.infinityforlemmy.comment.FetchRemovedCommentReveddit;
import eu.toldi.infinityforlemmy.community.BlockCommunity;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.CustomToroContainer;
import eu.toldi.infinityforlemmy.customviews.LinearLayoutManagerBugFixed;
@@ -108,11 +109,15 @@ import eu.toldi.infinityforlemmy.message.ReadMessage;
import eu.toldi.infinityforlemmy.post.FetchPost;
import eu.toldi.infinityforlemmy.post.FetchRemovedPost;
import eu.toldi.infinityforlemmy.post.HidePost;
import eu.toldi.infinityforlemmy.post.LemmyPostAPI;
import eu.toldi.infinityforlemmy.post.MarkPostAsRead;
import eu.toldi.infinityforlemmy.post.Post;
import eu.toldi.infinityforlemmy.readpost.InsertReadPost;
import eu.toldi.infinityforlemmy.subreddit.FetchSubredditData;
import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.user.BlockUser;
import eu.toldi.infinityforlemmy.user.FetchUserData;
import eu.toldi.infinityforlemmy.user.UserData;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
@@ -129,6 +134,8 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
public static final String EXTRA_POST_DATA = "EPD";
public static final String EXTRA_POST_ID = "EPI";
public static final String EXTRA_SINGLE_COMMENT_ID = "ESCI";
public static final String EXTRA_SINGLE_COMMENT_PARENT_ID = "ESCPID";
public static final String EXTRA_CONTEXT_NUMBER = "ECN";
public static final String EXTRA_MESSAGE_FULLNAME = "EMF";
public static final String EXTRA_POST_LIST_POSITION = "EPLP";
@@ -191,6 +198,8 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
Executor mExecutor;
@Inject
MarkPostAsRead markPostAsRead;
@Inject
LemmyPostAPI mLemmyPostAPI;
@State
Post mPost;
@State
@@ -220,6 +229,10 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
boolean mRespectSubredditRecommendedSortType;
@State
long viewPostDetailFragmentId;
@State
boolean isCommunityBlocked;
private ViewPostDetailActivity activity;
private RequestManager mGlide;
private Locale mLocale;
@@ -229,6 +242,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
private String mAccountQualifiedName;
private int postListPosition = -1;
private Integer mSingleCommentId;
private Integer mSingleCommentParentId;
private String mContextNumber;
private boolean showToast = false;
private boolean mIsSmoothScrolling = false;
@@ -547,6 +561,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
};
mSingleCommentId = getArguments().getInt(EXTRA_SINGLE_COMMENT_ID, 0);
mSingleCommentParentId = getArguments().getInt(EXTRA_SINGLE_COMMENT_PARENT_ID, 0);
mContextNumber = getArguments().getString(EXTRA_CONTEXT_NUMBER, "8");
if (savedInstanceState == null) {
@@ -606,8 +621,8 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
mExoCreator, post -> EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)));
mCommentsAdapter = new CommentsRecyclerViewAdapter(activity,
this, mCustomThemeWrapper, mExecutor, mRetrofit.getRetrofit(),
mAccessToken, mAccountName, mPost, mLocale, mSingleCommentId,
isSingleCommentThreadMode, mSharedPreferences,
mAccessToken, mAccountQualifiedName, mPost, mLocale, mSingleCommentId
, isSingleCommentThreadMode, mSharedPreferences, mCurrentAccountSharedPreferences,
new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() {
@Override
public void retryFetchingComments() {
@@ -626,7 +641,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
public SortType.Type getSortType() {
return sortType;
}
});
} );
if (mCommentsRecyclerView != null) {
mRecyclerView.setAdapter(mPostAdapter);
mCommentsRecyclerView.setAdapter(mCommentsAdapter);
@@ -704,7 +719,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
MenuItem spoilerItem = mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment);
spoilerItem.setVisible(true);
mMenu.findItem(R.id.action_edit_flair_view_post_detail_fragment).setVisible(true);
mMenu.findItem(R.id.action_block_user_view_post_detail_fragment).setVisible(false);
}
mMenu.findItem(R.id.action_view_crosspost_parent_view_post_detail_fragment).setVisible(mPost.getCrosspostParentId() != null);
@@ -782,6 +797,8 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
mGlide.clear(mFetchPostInfoImageView);
if (children != null) {
children.clear();
pages_loaded = 0;
mCommentsAdapter.clearLoadedComments();
}
this.sortType = sortType.getType();
if (mSharedPreferences.getBoolean(SharedPreferencesUtils.SAVE_SORT_TYPE, true)) {
@@ -1067,35 +1084,118 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
return true;
} else if (itemId == R.id.action_spoiler_view_post_detail_fragment) {
return true;
} else if (itemId == R.id.action_edit_flair_view_post_detail_fragment) {
FlairBottomSheetFragment flairBottomSheetFragment = new FlairBottomSheetFragment();
Bundle bundle = new Bundle();
bundle.putString(FlairBottomSheetFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(FlairBottomSheetFragment.EXTRA_SUBREDDIT_NAME, mPost.getSubredditName());
bundle.putLong(FlairBottomSheetFragment.EXTRA_VIEW_POST_DETAIL_FRAGMENT_ID, viewPostDetailFragmentId);
flairBottomSheetFragment.setArguments(bundle);
flairBottomSheetFragment.show(activity.getSupportFragmentManager(), flairBottomSheetFragment.getTag());
return true;
} else if (itemId == R.id.action_give_award_view_post_detail_fragment) {
} else if (itemId == R.id.action_block_user_view_post_detail_fragment) {
if (mAccessToken == null) {
Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.block_user)
.setMessage(R.string.are_you_sure)
.setPositiveButton(R.string.yes, (dialogInterface, i)
-> FetchUserData.fetchUserData(mRetrofit.getRetrofit(), mPost.getAuthorNamePrefixed(), new FetchUserData.FetchUserDataListener() {
Intent giveAwardIntent = new Intent(activity, GiveAwardActivity.class);
giveAwardIntent.putExtra(GiveAwardActivity.EXTRA_THING_FULLNAME, mPost.getFullName());
giveAwardIntent.putExtra(GiveAwardActivity.EXTRA_ITEM_POSITION, 0);
activity.startActivityForResult(giveAwardIntent, ViewPostDetailActivity.GIVE_AWARD_REQUEST_CODE);
@Override
public void onFetchUserDataSuccess(UserData userData, int inboxCount) {
BlockUser.blockUser(mRetrofit.getRetrofit(), mAccessToken, userData.getId(), true, new BlockUser.BlockUserListener() {
@Override
public void success() {
Toast.makeText(activity, R.string.block_user_success, Toast.LENGTH_SHORT).show();
activity.finish();
}
@Override
public void failed() {
Toast.makeText(activity, R.string.block_user_failed, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onFetchUserDataFailed() {
Toast.makeText(activity, R.string.block_user_failed, Toast.LENGTH_SHORT).show();
}
}))
.setNegativeButton(R.string.no, null)
.show();
return true;
} else if (itemId == R.id.action_block_community_view_post_detail_fragment) {
if (mAccessToken == null) {
Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
new MaterialAlertDialogBuilder(activity, R.style.MaterialAlertDialogTheme)
.setTitle(R.string.block_community)
.setMessage(R.string.are_you_sure)
.setPositiveButton(R.string.yes, (dialogInterface, i)
-> FetchSubredditData.fetchSubredditData(mRetrofit.getRetrofit(), mPost.getSubredditNamePrefixed(), mAccessToken, new FetchSubredditData.FetchSubredditDataListener() {
@Override
public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) {
BlockCommunity.INSTANCE.blockCommunity(mRetrofit.getRetrofit(), subredditData.getId(), mAccessToken, new BlockCommunity.BlockCommunityListener() {
@Override
public void onBlockCommunitySuccess() {
Toast.makeText(activity, R.string.block_community_success, Toast.LENGTH_SHORT).show();
activity.finish();
}
@Override
public void onBlockCommunityError() {
Toast.makeText(activity, R.string.block_community_failed, Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onFetchSubredditDataFail(boolean isQuarantined) {
Toast.makeText(activity, R.string.block_community_failed, Toast.LENGTH_SHORT).show();
}
}))
.setNegativeButton(R.string.no, null)
.show();
return true;
} else if (itemId == R.id.action_report_view_post_detail_fragment) {
if (mAccessToken == null) {
Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
Intent intent = new Intent(activity, ReportActivity.class);
intent.putExtra(ReportActivity.EXTRA_SUBREDDIT_NAME, mPost.getSubredditName());
intent.putExtra(ReportActivity.EXTRA_THING_FULLNAME, mPost.getFullName());
startActivity(intent);
if (mAccessToken == null) {
Toast.makeText(activity, R.string.login_first, Toast.LENGTH_SHORT).show();
return true;
}
LayoutInflater inflater = LayoutInflater.from(activity);
View view = inflater.inflate(R.layout.dialog_report, null);
EditText reasonEditText = view.findViewById(R.id.reasonEditText);
MaterialAlertDialogBuilder builder = new MaterialAlertDialogBuilder(activity)
.setTitle(R.string.report_post)
.setView(view)
.setNegativeButton(R.string.cancel, (dialogInterface, i) -> dialogInterface.dismiss())
.setPositiveButton(R.string.send_report, (dialogInterface, i) -> {
String reason = reasonEditText.getText().toString();
if (reason.isEmpty()) {
Toast.makeText(activity, "A report reason must be provided", Toast.LENGTH_SHORT).show();
return;
}
mLemmyPostAPI.reportPost(mPost.getId(), reason, mAccessToken, new LemmyPostAPI.ReportPostCallback() {
@Override
public void onSuccess() {
Toast.makeText(activity, R.string.report_successful, Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure() {
Toast.makeText(activity, R.string.report_failed, Toast.LENGTH_SHORT).show();
}
});
});
AlertDialog dialog = builder.create();
dialog.show();
Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
Button negativeButton = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
positiveButton.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
negativeButton.setTextColor(mCustomThemeWrapper.getSecondaryTextColor());
return true;
} else if (itemId == R.id.action_see_removed_view_post_detail_fragment) {
showRemovedPost();
@@ -1185,7 +1285,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
if (mCommentsRecyclerView != null) {
LinearLayoutManager myLayoutManager = (LinearLayoutManager) mCommentsRecyclerView.getLayoutManager();
scrollPosition = myLayoutManager != null ? myLayoutManager.findFirstVisibleItemPosition() : 0;
} else {
LinearLayoutManager myLayoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
scrollPosition = myLayoutManager != null ? myLayoutManager.findFirstVisibleItemPosition() : 0;
@@ -1245,14 +1345,14 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
mPostDetailsSharedPreferences, mExoCreator,
post1 -> EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)));
mSwipeRefreshLayout.setRefreshing(false);
FetchComment.fetchComments(mExecutor, new Handler(), mRetrofit.getRetrofit(), mAccessToken, post.getId(), mSingleCommentId == 0 ? null : mSingleCommentId, sortType, mExpandChildren, 1, new FetchComment.FetchCommentListener() {
FetchComment.fetchComments(mExecutor, new Handler(), mRetrofit.getRetrofit(), mAccessToken, post.getId(), mSingleCommentId == null || mSingleCommentId == 0 ? null : mSingleCommentParentId == 0 ? mSingleCommentId : mSingleCommentParentId, sortType, mExpandChildren, 1, new FetchComment.FetchCommentListener() {
@Override
public void onFetchCommentSuccess(ArrayList<Comment> expandedComments, Integer parentId, ArrayList<Integer> children) {
pages_loaded++;
mCommentsAdapter = new CommentsRecyclerViewAdapter(activity,
ViewPostDetailFragment.this, mCustomThemeWrapper, mExecutor,
mRetrofit.getRetrofit(), mAccessToken, mAccountName, mPost, mLocale,
mSingleCommentId, isSingleCommentThreadMode, mSharedPreferences,
mRetrofit.getRetrofit(), mAccessToken, mAccountQualifiedName, mPost, mLocale,
mSingleCommentId, isSingleCommentThreadMode, mSharedPreferences, mCurrentAccountSharedPreferences,
new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() {
@Override
public void retryFetchingComments() {
@@ -1364,7 +1464,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
}
FetchComment.fetchComments(mExecutor, new Handler(), mRetrofit.getRetrofit(), mAccessToken, mPost.getId(), commentId, sortType, mExpandChildren, pages_loaded + 1,
FetchComment.fetchComments(mExecutor, new Handler(), mRetrofit.getRetrofit(), mAccessToken, mPost.getId(), mSingleCommentId == null || mSingleCommentId == 0 ? null : mSingleCommentParentId == 0 ? mSingleCommentId : mSingleCommentParentId, sortType, mExpandChildren, pages_loaded + 1,
new FetchComment.FetchCommentListener() {
@Override
public void onFetchCommentSuccess(ArrayList<Comment> expandedComments,
@@ -1433,8 +1533,8 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Override
public void onFetchCommentFailed() {
isFetchingComments = false;
mCommentsAdapter.initiallyLoadCommentsFailed();
if(pages_loaded == 0)
mCommentsAdapter.initiallyLoadCommentsFailed();
if (changeRefreshState) {
isRefreshing = false;
}
@@ -1454,7 +1554,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
isLoadingMoreChildren = true;
FetchComment.fetchComments(mExecutor, new Handler(), mRetrofit.getRetrofit(), mAccessToken,
mPost.getId(), null, sortType, mExpandChildren, pages_loaded + 1, new FetchComment.FetchCommentListener() {
mPost.getId(), (mSingleCommentId == null || mSingleCommentId == 0) ? null : (mSingleCommentParentId == null || mSingleCommentParentId == 0 ? mSingleCommentId : mSingleCommentParentId), sortType, mExpandChildren, pages_loaded + 1, new FetchComment.FetchCommentListener() {
@Override
public void onFetchCommentSuccess(ArrayList<Comment> expandedComments, Integer parentId, ArrayList<Integer> children) {
pages_loaded++;
@@ -1666,6 +1766,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
public void changeToNormalThreadMode() {
isSingleCommentThreadMode = false;
mSingleCommentId = null;
mSingleCommentParentId = null;
mRespectSubredditRecommendedSortType = mSharedPreferences.getBoolean(SharedPreferencesUtils.RESPECT_SUBREDDIT_RECOMMENDED_COMMENT_SORT_TYPE, false);
refresh(false, true);
}

View File

@@ -0,0 +1,59 @@
package eu.toldi.infinityforlemmy.markdown;
import android.content.Context;
import android.content.Intent;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import org.commonmark.node.Image;
import eu.toldi.infinityforlemmy.activities.ViewImageOrGifActivity;
import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.MarkwonConfiguration;
import io.noties.markwon.MarkwonSpansFactory;
import io.noties.markwon.RenderProps;
import io.noties.markwon.image.AsyncDrawableSpan;
import io.noties.markwon.image.ImageSpanFactory;
public class ClickableGlideImagesPlugin extends AbstractMarkwonPlugin {
public static Context context;
public ClickableGlideImagesPlugin(Context context) {
this.context = context;
}
public static ClickableGlideImagesPlugin create(Context context) {
return new ClickableGlideImagesPlugin(context);
}
@Override
public void configureSpansFactory(@NonNull MarkwonSpansFactory.Builder builder) {
builder.setFactory(Image.class, new ClickableImageFactory());
}
class ClickableImageFactory extends ImageSpanFactory {
@Override
public Object getSpans(@NonNull MarkwonConfiguration configuration, @NonNull RenderProps props) {
AsyncDrawableSpan image = (AsyncDrawableSpan) super.getSpans(configuration, props);
ClickableSpan clickableSpan = new ClickableSpan() {
@Override
public void onClick(@NonNull View widget) {
Intent intent = new Intent(context, ViewImageOrGifActivity.class);
intent.putExtra(ViewImageOrGifActivity.EXTRA_IMAGE_URL_KEY, image.getDrawable().getDestination());
intent.putExtra(ViewImageOrGifActivity.EXTRA_FILE_NAME_KEY, image.getDrawable().getDestination());
context.startActivity(intent);
}
};
Object[] objects = new Object[2];
objects[0] = image;
objects[1] = clickableSpan;
return objects;
}
}
}

View File

@@ -8,7 +8,6 @@ import androidx.annotation.Nullable;
import org.commonmark.ext.gfm.tables.TableBlock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import eu.toldi.infinityforlemmy.R;
@@ -16,6 +15,7 @@ import eu.toldi.infinityforlemmy.customviews.CustomMarkwonAdapter;
import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonPlugin;
import io.noties.markwon.ext.strikethrough.StrikethroughPlugin;
import io.noties.markwon.image.glide.GlideImagesPlugin;
import io.noties.markwon.inlineparser.BangInlineProcessor;
import io.noties.markwon.inlineparser.HtmlInlineProcessor;
import io.noties.markwon.inlineparser.MarkwonInlineParserPlugin;
@@ -38,9 +38,9 @@ public class MarkdownUtils {
int spoilerBackgroundColor,
@Nullable BetterLinkMovementMethod.OnLinkLongClickListener onLinkLongClickListener) {
return Markwon.builder(context)
.usePlugin(GlideImagesPlugin.create(context))
.usePlugin(MarkwonInlineParserPlugin.create(plugin -> {
plugin.excludeInlineProcessor(HtmlInlineProcessor.class);
plugin.excludeInlineProcessor(BangInlineProcessor.class);
}))
.usePlugin(miscPlugin)
.usePlugin(SuperscriptPlugin.create())
@@ -51,6 +51,8 @@ public class MarkdownUtils {
.setOnLinkLongClickListener(onLinkLongClickListener)))
.usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
.usePlugin(TableEntryPlugin.create(context))
.usePlugin(ClickableGlideImagesPlugin.create(context))
.usePlugin(new MarkwonLemmyLinkPlugin())
.build();
}
@@ -60,7 +62,6 @@ public class MarkdownUtils {
return Markwon.builder(context)
.usePlugin(MarkwonInlineParserPlugin.create(plugin -> {
plugin.excludeInlineProcessor(HtmlInlineProcessor.class);
plugin.excludeInlineProcessor(BangInlineProcessor.class);
}))
.usePlugin(miscPlugin)
.usePlugin(SuperscriptPlugin.create())
@@ -70,6 +71,8 @@ public class MarkdownUtils {
.setOnLinkLongClickListener(onLinkLongClickListener)))
.usePlugin(LinkifyPlugin.create(Linkify.WEB_URLS))
.usePlugin(TableEntryPlugin.create(context))
.usePlugin(GlideImagesPlugin.create(context))
.usePlugin(new MarkwonLemmyLinkPlugin())
.build();
}
@@ -104,6 +107,15 @@ public class MarkdownUtils {
.build();
}
@NonNull
public static MarkwonAdapter createTablesAndImagesAdapter(@NonNull Context context) {
return MarkwonAdapter.builder(R.layout.adapter_default_entry, R.id.text)
.include(TableBlock.class, TableEntry.create(builder -> builder
.tableLayout(R.layout.adapter_table_block, R.id.table_layout)
.textLayoutIsRoot(R.layout.view_table_entry_cell)))
.build();
}
/**
* Creates a CustomMarkwonAdapter configured with support for tables.
*/
@@ -119,35 +131,4 @@ public class MarkdownUtils {
private static final Pattern emptyPattern = Pattern.compile("!\\[\\]\\((.*?)\\)");
private static final Pattern nonEmptyPattern = Pattern.compile("!\\[(.*?)\\]\\((.*?)\\)");
public static String processImageCaptions(String markdown, String replacementCaption) {
// Pattern for Markdown images with empty captions
// Pattern for Markdown images with non-empty captions
Matcher emptyMatcher = emptyPattern.matcher(markdown);
StringBuffer sb = new StringBuffer();
while (emptyMatcher.find()) {
// Replace the matched pattern with the same URL, but with a caption
emptyMatcher.appendReplacement(sb, "[" + replacementCaption + "](" + emptyMatcher.group(1) + ")");
}
// Append the rest of the content
emptyMatcher.appendTail(sb);
// Now process non-empty captions
Matcher nonEmptyMatcher = nonEmptyPattern.matcher(sb.toString());
StringBuffer finalSb = new StringBuffer();
while (nonEmptyMatcher.find()) {
// Replace the matched pattern with the same URL and caption, but without the "!"
nonEmptyMatcher.appendReplacement(finalSb, "[" + nonEmptyMatcher.group(1) + "](" + nonEmptyMatcher.group(2) + ")");
}
// Append the rest of the content
nonEmptyMatcher.appendTail(finalSb);
return finalSb.toString();
}
}

View File

@@ -33,8 +33,9 @@ import java.util.concurrent.Executor;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import eu.toldi.infinityforlemmy.markdown.MarkdownUtils;
import eu.toldi.infinityforlemmy.community.BasicCommunityInfo;
import eu.toldi.infinityforlemmy.postfilter.PostFilter;
import eu.toldi.infinityforlemmy.user.BasicUserInfo;
import eu.toldi.infinityforlemmy.utils.JSONUtils;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import eu.toldi.infinityforlemmy.utils.Utils;
@@ -175,9 +176,11 @@ public class ParsePost {
}
}
String title = post.getString("name");
String title = post.getString("name").replace("&amp;", "&");
String permalink = post.getString("ap_id");
int score = counts.getInt("score");
int upvotes = counts.getInt("upvotes");
int downvotes = counts.getInt("downvotes");
int voteType = 0;
int nComments = counts.getInt("comments");
int upvoteRatio = 100 * counts.getInt("upvotes") / max(counts.getInt("upvotes") + counts.getInt("downvotes"), 1);
@@ -185,43 +188,47 @@ public class ParsePost {
boolean nsfw = post.getBoolean("nsfw");
boolean locked = post.getBoolean("locked");
boolean saved = data.getBoolean("saved");
String distinguished = "";
String distinguished = (creator.getBoolean("admin") ? "admin" : "");
String suggestedSort = "";
ArrayList <Post.Preview> previews = new ArrayList<>();
if(!post.isNull("thumbnail_url")) {
ArrayList<Post.Preview> previews = new ArrayList<>();
if (!post.isNull("thumbnail_url")) {
String thumbnail = post.getString("thumbnail_url");
//int[] wh_array = getImageDimension(thumbnail);
previews.add(new Post.Preview(thumbnail, 0, 0, "", ""));
}
BasicUserInfo authorInfo = new BasicUserInfo(creator.getInt("id"), author, authorFull, creator.optString("avatar", ""), creator.optString("display_name", author));
BasicCommunityInfo communityInfo = new BasicCommunityInfo(community.getInt("id"), subredditName, subredditNamePrefixed, community.optString("icon", ""), community.optString("title", subredditName));
return parseData(data, permalink, id, fullName, subredditName, subredditNamePrefixed,
author,authorFull, postTimeMillis, title, previews,
score, voteType, nComments, upvoteRatio, nsfw, locked, saved,
distinguished, suggestedSort);
return parseData(data, permalink, id, communityInfo,
authorInfo, postTimeMillis, title, previews,
downvotes, upvotes, voteType, nComments, upvoteRatio, nsfw, locked, saved,
distinguished, suggestedSort);
}
private static Post parseData(JSONObject data, String permalink, int id, String fullName,
String subredditName, String subredditNamePrefixed, String author, String authorFull,
private static Post parseData(JSONObject data, String permalink, int id, BasicCommunityInfo communityInfo, BasicUserInfo author,
long postTimeMillis, String title, ArrayList<Post.Preview> previews,
int score, int voteType, int nComments, int upvoteRatio,
int downvotes, int upvotes, int voteType, int nComments, int upvoteRatio,
boolean nsfw, boolean locked,
boolean saved,
String distinguished, String suggestedSort) throws JSONException {
Post post;
boolean isVideo = false;
String url = (!data.getJSONObject("post").isNull("url")) ? data.getJSONObject("post").getString("url") : "";
String communityURL = (!data.getJSONObject("community").isNull("icon")) ? data.getJSONObject("community").getString("icon") : "";
String authorAvatar = (!data.getJSONObject("creator").isNull("avatar")) ? data.getJSONObject("creator").getString("avatar") : null;
Uri uri = Uri.parse(url);
String path = uri.getPath();
boolean isVideo = path.endsWith(".mp4") || path.endsWith(".webm") || path.endsWith(".gifv");
if (!data.getJSONObject("post").has("thumbnail_url") && previews.isEmpty()) {
if (!data.getJSONObject("post").isNull("body") && url.equals("")) {
//Text post
int postType = Post.TEXT_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
postTimeMillis, title, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw,
locked, saved, distinguished, suggestedSort);
String body = data.getJSONObject("post").getString("body");
@@ -233,9 +240,9 @@ public class ParsePost {
//Image post
int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
if (previews.isEmpty()) {
previews.add(new Post.Preview(url, 0, 0, "", ""));
@@ -244,21 +251,18 @@ public class ParsePost {
} else {
if (isVideo) {
//No preview video post
JSONObject redditVideoObject = data.getJSONObject(JSONUtils.MEDIA_KEY).getJSONObject(JSONUtils.REDDIT_VIDEO_KEY);
int postType = Post.VIDEO_TYPE;
String videoUrl = Html.fromHtml(redditVideoObject.getString(JSONUtils.HLS_URL_KEY)).toString();
String videoDownloadUrl = redditVideoObject.getString(JSONUtils.FALLBACK_URL_KEY);
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull, postTimeMillis, title, permalink, score, postType, voteType,
post = new Post(id, communityInfo, author, postTimeMillis, title, permalink, downvotes, upvotes, postType, voteType,
nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
post.setVideoUrl(videoUrl);
post.setVideoDownloadUrl(videoDownloadUrl);
post.setVideoUrl(url);
post.setVideoDownloadUrl(url);
} else if (!url.equals("")) {
//No preview link post
int postType = Post.NO_PREVIEW_LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
postTimeMillis, title, url, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
@@ -291,8 +295,8 @@ public class ParsePost {
}
} else {
int postType = Post.TEXT_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
postTimeMillis, title, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw,
locked, saved, distinguished, suggestedSort);
String body = "";
@@ -330,7 +334,7 @@ public class ParsePost {
String videoUrl = Html.fromHtml(redditVideoObject.getString(JSONUtils.HLS_URL_KEY)).toString();
String videoDownloadUrl = redditVideoObject.getString(JSONUtils.FALLBACK_URL_KEY);
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull, postTimeMillis, title, permalink, score, postType, voteType,
post = new Post(id, communityInfo, author, postTimeMillis, title, permalink, downvotes, upvotes, postType, voteType,
nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
post.setPreviews(previews);
@@ -341,8 +345,8 @@ public class ParsePost {
//Image post
int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
authorFull, postTimeMillis, title, url, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved,
distinguished, suggestedSort);
@@ -353,15 +357,15 @@ public class ParsePost {
} else if (path.endsWith(".gif")) {
//Gif post
int postType = Post.GIF_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
postTimeMillis, title, url, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio,
nsfw, locked, saved,
distinguished, suggestedSort);
post.setPreviews(previews);
post.setVideoUrl(url);
} else if (uri.getAuthority().contains("imgur.com") && (path.endsWith(".gifv") || path.endsWith(".mp4"))) {
} else if (uri.getAuthority() != null && uri.getAuthority().contains("imgur.com") && (path.endsWith(".gifv") || path.endsWith(".mp4"))) {
// Imgur gifv/mp4
int postType = Post.VIDEO_TYPE;
@@ -369,8 +373,8 @@ public class ParsePost {
url = url.substring(0, url.length() - 5) + ".mp4";
}
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
postTimeMillis, title, url, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio,
nsfw, locked, saved,
distinguished, suggestedSort);
@@ -382,8 +386,8 @@ public class ParsePost {
//Video post
int postType = Post.VIDEO_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
postTimeMillis, title, url, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved,
distinguished, suggestedSort);
post.setPreviews(previews);
@@ -393,8 +397,8 @@ public class ParsePost {
//Link post
int postType = Post.LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
postTimeMillis, title, url, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved,
distinguished, suggestedSort);
if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
@@ -434,8 +438,8 @@ public class ParsePost {
//Image post
int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
postTimeMillis, title, url, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
if (previews.isEmpty()) {
@@ -446,8 +450,8 @@ public class ParsePost {
//Video post
int postType = Post.VIDEO_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
postTimeMillis, title, url, permalink, score,
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
post.setPreviews(previews);
post.setVideoUrl(url);
@@ -456,9 +460,9 @@ public class ParsePost {
//CP No Preview Link post
int postType = Post.NO_PREVIEW_LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
post = new Post(id, communityInfo, author,
postTimeMillis, title, url, permalink, downvotes, upvotes,
postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
//Need attention
if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText("");
@@ -574,7 +578,7 @@ public class ParsePost {
singleGalleryObject.getJSONObject(JSONUtils.S_KEY).getInt(JSONUtils.Y_KEY), galleryItemCaption, galleryItemCaptionUrl));
}
Post.Gallery postGalleryItem = new Post.Gallery(mimeType, galleryItemUrl, "", subredditName + "-" + galleryId + "." + mimeType.substring(mimeType.lastIndexOf("/") + 1), galleryItemCaption, galleryItemCaptionUrl);
Post.Gallery postGalleryItem = new Post.Gallery(mimeType, galleryItemUrl, "", communityInfo.getDisplayName() + "-" + galleryId + "." + mimeType.substring(mimeType.lastIndexOf("/") + 1), galleryItemCaption, galleryItemCaptionUrl);
// For issue #558
// Construct a fallback image url
@@ -652,16 +656,26 @@ public class ParsePost {
}
if (!data.isNull("my_vote")) {
post.setVoteType(data.getInt("my_vote"));
post.setScore(post.getScore() - 1);
if(post.getVoteType() == 1)
post.setUpvotes(post.getUpvotes() - 1);
else if (post.getVoteType() == -1)
post.setDownvotes(post.getDownvotes() - 1);
}
if (!data.getJSONObject("post").isNull("body")) {
String body = MarkdownUtils.processImageCaptions(data.getJSONObject("post").getString("body"), "Image");
String body = data.getJSONObject("post").getString("body");
post.setSelfText(body);
post.setSelfTextPlain(body);
post.setSelfTextPlainTrimmed(body.trim());
}
if (data.getJSONObject("post").getBoolean("featured_community")) {
post.setFeaturedInCommunity(true);
}
if (data.getJSONObject("post").getBoolean("featured_local")) {
post.setFeaturedOnInstance(true);
}
return post;
}

View File

@@ -8,6 +8,9 @@ import androidx.annotation.Nullable;
import java.util.ArrayList;
import eu.toldi.infinityforlemmy.community.BasicCommunityInfo;
import eu.toldi.infinityforlemmy.user.BasicUserInfo;
/**
* Created by alex on 3/1/18.
*/
@@ -33,13 +36,8 @@ public class Post implements Parcelable {
}
};
private int id;
private String fullName;
private String subredditName;
private String subredditNamePrefixed;
private String subredditIconUrl;
private String author;
private String authorNamePrefixed;
private String authorIconUrl;
private BasicCommunityInfo communityInfo;
private BasicUserInfo author;
private String title;
private String selfText;
private String selfTextPlain;
@@ -56,14 +54,19 @@ public class Post implements Parcelable {
private boolean loadGfyOrStreamableVideoSuccess;
private String permalink;
private long postTimeMillis;
private int score;
private int downvotes;
private int upvotes;
private int postType;
private int voteType;
private int nComments;
private int upvoteRatio;
private boolean hidden;
private boolean nsfw;
private boolean stickied;
private boolean featuredInCommunity;
private boolean featuredOnInstance;
private boolean archived;
private boolean locked;
private boolean saved;
@@ -75,29 +78,26 @@ public class Post implements Parcelable {
private ArrayList<Preview> previews = new ArrayList<>();
private ArrayList<Gallery> gallery = new ArrayList<>();
public Post(int id, String fullName, String subredditName, String subredditNamePrefixed,
String author,String authorNamePrefixed, long postTimeMillis,
String title, String permalink, int score, int postType, int voteType, int nComments,
public Post(int id, BasicCommunityInfo communityInfo,
BasicUserInfo userInfo, long postTimeMillis,
String title, String permalink, int downvotes, int upvotes, int postType, int voteType, int nComments,
int upvoteRatio,
boolean nsfw, boolean locked, boolean saved,
String distinguished, String suggestedSort) {
this.id = id;
this.fullName = fullName;
this.subredditName = subredditName;
this.subredditNamePrefixed = subredditNamePrefixed;
this.author = author;
this.authorNamePrefixed = authorNamePrefixed;
this.communityInfo = communityInfo;
this.author = userInfo;
this.postTimeMillis = postTimeMillis;
this.title = title;
this.permalink = permalink;
this.score = score;
this.upvotes = upvotes;
this.downvotes = downvotes;
this.postType = postType;
this.voteType = voteType;
this.nComments = nComments;
this.upvoteRatio = upvoteRatio;
this.hidden = hidden;
this.nsfw = nsfw;
this.stickied = stickied;
this.archived = archived;
this.locked = locked;
this.saved = saved;
@@ -107,29 +107,26 @@ public class Post implements Parcelable {
isRead = false;
}
public Post(int id, String fullName, String subredditName, String subredditNamePrefixed,
String author, String authorNamePrefixed, long postTimeMillis, String title,
String url, String permalink, int score, int postType, int voteType, int nComments,
public Post(int id, BasicCommunityInfo communityInfo,
BasicUserInfo author, long postTimeMillis, String title,
String url, String permalink, int downvotes, int upvotes, int postType, int voteType, int nComments,
int upvoteRatio,
boolean nsfw, boolean locked, boolean saved, String distinguished, String suggestedSort) {
boolean nsfw, boolean locked, boolean saved, String distinguished, String suggestedSort) {
this.id = id;
this.fullName = fullName;
this.subredditName = subredditName;
this.subredditNamePrefixed = subredditNamePrefixed;
this.communityInfo = communityInfo;
this.author = author;
this.authorNamePrefixed = authorNamePrefixed;
this.postTimeMillis = postTimeMillis;
this.title = title;
this.url = url;
this.permalink = permalink;
this.score = score;
this.downvotes = downvotes;
this.upvotes = upvotes;
this.postType = postType;
this.voteType = voteType;
this.nComments = nComments;
this.upvoteRatio = upvoteRatio;
this.hidden = hidden;
this.nsfw = nsfw;
this.stickied = stickied;
this.archived = archived;
this.locked = locked;
this.saved = saved;
@@ -141,13 +138,8 @@ public class Post implements Parcelable {
protected Post(Parcel in) {
id = in.readInt();
fullName = in.readString();
subredditName = in.readString();
subredditNamePrefixed = in.readString();
subredditIconUrl = in.readString();
author = in.readString();
authorNamePrefixed = in.readString();
authorIconUrl = in.readString();
communityInfo = in.readParcelable(BasicCommunityInfo.class.getClassLoader());
author = in.readParcelable(BasicUserInfo.class.getClassLoader());
postTimeMillis = in.readLong();
title = in.readString();
selfText = in.readString();
@@ -164,14 +156,15 @@ public class Post implements Parcelable {
isStreamable = in.readByte() != 0;
loadGfyOrStreamableVideoSuccess = in.readByte() != 0;
permalink = in.readString();
score = in.readInt();
downvotes = in.readInt();
upvotes = in.readInt();
postType = in.readInt();
voteType = in.readInt();
nComments = in.readInt();
upvoteRatio = in.readInt();
hidden = in.readByte() != 0;
nsfw = in.readByte() != 0;
stickied = in.readByte() != 0;
featuredInCommunity = in.readByte() != 0;
archived = in.readByte() != 0;
locked = in.readByte() != 0;
saved = in.readByte() != 0;
@@ -189,27 +182,24 @@ public class Post implements Parcelable {
}
public String getFullName() {
return fullName;
return communityInfo.getQualifiedName();
}
public String getSubredditName() {
return subredditName;
return communityInfo.getDisplayName();
}
public String getSubredditNamePrefixed() {
return subredditNamePrefixed;
return communityInfo.getQualifiedName();
}
public String getSubredditIconUrl() {
return subredditIconUrl;
return communityInfo.getIcon();
}
public void setSubredditIconUrl(String subredditIconUrl) {
this.subredditIconUrl = subredditIconUrl;
}
public String getAuthor() {
return author;
return author.getDisplayName();
}
public boolean isAuthorDeleted() {
@@ -217,20 +207,19 @@ public class Post implements Parcelable {
}
public void setAuthor(String author) {
this.author = author;
this.authorNamePrefixed = "u/" + author;
}
public String getAuthorNamePrefixed() {
return authorNamePrefixed;
return author.getQualifiedName();
}
public String getAuthorIconUrl() {
return authorIconUrl;
return (author.getAvatar() == null) ? "" : author.getAvatar();
}
public void setAuthorIconUrl(String authorIconUrl) {
this.authorIconUrl = authorIconUrl;
}
public long getPostTimeMillis() {
@@ -269,6 +258,22 @@ public class Post implements Parcelable {
this.selfTextPlainTrimmed = selfTextPlainTrimmed;
}
public int getDownvotes() {
return downvotes;
}
public void setDownvotes(int downvotes) {
this.downvotes = downvotes;
}
public int getUpvotes() {
return upvotes;
}
public void setUpvotes(int upvotes) {
this.upvotes = upvotes;
}
public String getUrl() {
return url;
}
@@ -366,11 +371,7 @@ public class Post implements Parcelable {
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
return upvotes- downvotes;
}
public int getPostType() {
@@ -426,8 +427,20 @@ public class Post implements Parcelable {
return 0;
}
public boolean isStickied() {
return stickied;
public boolean isFeaturedInCommunity() {
return featuredInCommunity;
}
public void setFeaturedInCommunity(boolean featuredInCommunity) {
this.featuredInCommunity = featuredInCommunity;
}
public boolean isFeaturedOnInstance() {
return featuredOnInstance;
}
public void setFeaturedOnInstance(boolean featuredOnInstance) {
this.featuredOnInstance = featuredOnInstance;
}
public boolean isArchived() {
@@ -482,16 +495,19 @@ public class Post implements Parcelable {
this.gallery = gallery;
}
public BasicCommunityInfo getCommunityInfo() {
return communityInfo;
}
public BasicUserInfo getAuthorInfo() {
return author;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeInt(id);
parcel.writeString(fullName);
parcel.writeString(subredditName);
parcel.writeString(subredditNamePrefixed);
parcel.writeString(subredditIconUrl);
parcel.writeString(author);
parcel.writeString(authorNamePrefixed);
parcel.writeString(authorIconUrl);
parcel.writeParcelable(communityInfo, i);
parcel.writeParcelable(author, i);
parcel.writeLong(postTimeMillis);
parcel.writeString(title);
parcel.writeString(selfText);
@@ -508,14 +524,15 @@ public class Post implements Parcelable {
parcel.writeByte((byte) (isStreamable ? 1 : 0));
parcel.writeByte((byte) (loadGfyOrStreamableVideoSuccess ? 1 : 0));
parcel.writeString(permalink);
parcel.writeInt(score);
parcel.writeInt(downvotes);
parcel.writeInt(upvotes);
parcel.writeInt(postType);
parcel.writeInt(voteType);
parcel.writeInt(nComments);
parcel.writeInt(upvoteRatio);
parcel.writeByte((byte) (hidden ? 1 : 0));
parcel.writeByte((byte) (nsfw ? 1 : 0));
parcel.writeByte((byte) (stickied ? 1 : 0));
parcel.writeByte((byte) (featuredInCommunity ? 1 : 0));
parcel.writeByte((byte) (archived ? 1 : 0));
parcel.writeByte((byte) (locked ? 1 : 0));
parcel.writeByte((byte) (saved ? 1 : 0));

View File

@@ -251,7 +251,7 @@ public class PostPagingSource extends ListenableFuturePagingSource<Integer, Post
private ListenableFuture<LoadResult<Integer, Post>> loadSubredditPosts(@NonNull LoadParams<Integer> loadParams, LemmyAPI api) {
ListenableFuture<Response<String>> subredditPost;
subredditPost = api.getPosts(null,sortType.getType().value,loadParams.getKey(),25,null,subredditOrUserName,false,null);
subredditPost = api.getPosts(null,sortType.getType().value,loadParams.getKey(),25,null,subredditOrUserName,false,accessToken);
ListenableFuture<LoadResult<Integer, Post>> pageFuture = Futures.transform(subredditPost, this::transformData, executor);

View File

@@ -105,7 +105,7 @@ public class CrashReportsFragment extends Fragment {
} catch (UnsupportedEncodingException e) {
return false;
}
Uri githubIssueUri = Uri.parse(String.format("https://github.com/Docile-Alligator/Infinity-For-Reddit/issues/new?labels=possible-bug&device=%s&version=%s&android_version=%s&logs=%s&&template=BUG_REPORT.yml", model, appVersion, androidVersion, logs));
Uri githubIssueUri = Uri.parse(String.format("https://codeberg.org/Bazsalanszky/Infinity-For-Lemmy/issues/new?template=.gitea/issue_template/bug_report.md&body=%s", logs));
intent.setData(githubIssueUri);
startActivity(intent);
return true;

View File

@@ -224,7 +224,7 @@ public class CustomizeMainPageTabsFragment extends Fragment {
showTabNamesSwitch.setOnCheckedChangeListener((compoundButton, b) -> mainActivityTabsSharedPreferences.edit().putBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_SHOW_TAB_NAMES, b).apply());
showTabNamesLinearLayout.setOnClickListener(view -> showTabNamesSwitch.performClick());
tab1CurrentTitle = mainActivityTabsSharedPreferences.getString((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_1_TITLE, getString(R.string.home));
tab1CurrentTitle = mainActivityTabsSharedPreferences.getString((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_1_TITLE, getString(R.string.subscribed_feed));
tab1CurrentPostType = mainActivityTabsSharedPreferences.getInt((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_1_POST_TYPE, SharedPreferencesUtils.MAIN_PAGE_TAB_POST_TYPE_HOME);
tab1CurrentName = mainActivityTabsSharedPreferences.getString((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_1_NAME, "");
tab1TypeSummaryTextView.setText(typeValues[tab1CurrentPostType]);

View File

@@ -0,0 +1,34 @@
package eu.toldi.infinityforlemmy.site;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import retrofit2.Retrofit;
public class FetchSiteInfo {
public static void fetchSiteInfo(Retrofit retrofit, String accesToken, FetchSiteInfoListener fetchSiteInfoListener) {
retrofit.create(LemmyAPI.class).getSiteInfo(accesToken).enqueue(
new retrofit2.Callback<String>() {
@Override
public void onResponse(retrofit2.Call<String> call, retrofit2.Response<String> response) {
if (response.isSuccessful()) {
String siteInfoJson = response.body();
SiteInfo siteInfo = SiteInfo.parseSiteInfo(siteInfoJson);
fetchSiteInfoListener.onFetchSiteInfoSuccess(siteInfo);
} else {
fetchSiteInfoListener.onFetchSiteInfoFailed();
}
}
@Override
public void onFailure(retrofit2.Call<String> call, Throwable t) {
fetchSiteInfoListener.onFetchSiteInfoFailed();
}
}
);
}
public interface FetchSiteInfoListener {
void onFetchSiteInfoSuccess(SiteInfo siteInfo);
void onFetchSiteInfoFailed();
}
}

View File

@@ -0,0 +1,83 @@
package eu.toldi.infinityforlemmy.site;
import org.json.JSONException;
import org.json.JSONObject;
public class SiteInfo {
private int id;
private String name;
private String sidebar;
private String description;
private boolean enable_downvotes;
private boolean enable_nsfw;
private boolean community_creation_admin_only;
public SiteInfo(int id, String name, String sidebar, String description, boolean enable_downvotes, boolean enable_nsfw, boolean community_creation_admin_only) {
this.id = id;
this.name = name;
this.sidebar = sidebar;
this.description = description;
this.enable_downvotes = enable_downvotes;
this.enable_nsfw = enable_nsfw;
this.community_creation_admin_only = community_creation_admin_only;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getSidebar() {
return sidebar;
}
public String getDescription() {
return description;
}
public boolean isEnable_downvotes() {
return enable_downvotes;
}
public boolean isEnable_nsfw() {
return enable_nsfw;
}
public boolean isCommunity_creation_admin_only() {
return community_creation_admin_only;
}
public static SiteInfo parseSiteInfo(String siteInfoJson) {
try {
JSONObject siteInfo = new JSONObject(siteInfoJson);
JSONObject siteView = siteInfo.getJSONObject("site_view");
JSONObject site = siteView.getJSONObject("site");
JSONObject localSite = siteView.getJSONObject("local_site");
int id = site.getInt("id");
String name = site.getString("name");
String sidebar = null;
if (site.has("sidebar"))
sidebar = site.getString("sidebar");
String description = null;
if (site.has("description"))
description = site.getString("description");
boolean enable_downvotes = localSite.getBoolean("enable_downvotes");
boolean enable_nsfw = localSite.getBoolean("enable_nsfw");
boolean community_creation_admin_only = localSite.getBoolean("community_creation_admin_only");
SiteInfo si = new SiteInfo(id, name, sidebar, description, enable_downvotes, enable_nsfw, community_creation_admin_only);
return si;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}

View File

@@ -8,8 +8,14 @@ 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.Locale;
import java.util.TimeZone;
import eu.toldi.infinityforlemmy.community.CommunityStats;
import eu.toldi.infinityforlemmy.utils.JSONUtils;
public class ParseSubredditData {
@@ -22,14 +28,14 @@ public class ParseSubredditData {
}
@Nullable
private static SubredditData parseSubredditData(JSONObject subredditDataJsonObject, boolean nsfw) throws JSONException {
public static SubredditData parseSubredditData(JSONObject subredditDataJsonObject, boolean nsfw) throws JSONException {
JSONObject community = subredditDataJsonObject.getJSONObject("community");
boolean isNSFW = community.getBoolean("nsfw");
if (!nsfw && isNSFW) {
return null;
}
String title = community.getString(JSONUtils.TITLE_KEY);
String title = community.getString(JSONUtils.TITLE_KEY).replace("&amp;", "&");
String bannerImageUrl = "";
if (!community.isNull("banner")) {
bannerImageUrl = community.getString("banner");
@@ -47,7 +53,11 @@ public class ParseSubredditData {
}
boolean removed = community.getBoolean("removed");
String published = community.getString("published");
String published_raw = community.getString("published");
String published = formatISOTime(published_raw);
if(published == null){
published = published_raw;
}
String updated = "";
if (!community.isNull("updated")) {
updated = community.getString("updated");
@@ -60,9 +70,18 @@ public class ParseSubredditData {
boolean hidden = community.getBoolean("hidden");
boolean postingRestrictedToMods = community.getBoolean("posting_restricted_to_mods");
int instanceId = community.getInt("instance_id");
int subscribers = subredditDataJsonObject.getJSONObject("counts").getInt("subscribers");
int subscribers = (subredditDataJsonObject.has("counts")) ? subredditDataJsonObject.getJSONObject("counts").getInt("subscribers") : 0;
boolean blocked = (subredditDataJsonObject.has("blocked")) ? subredditDataJsonObject.getBoolean("blocked") : true;
CommunityStats stats = null;
if (subredditDataJsonObject.has("counts")) {
JSONObject counts = subredditDataJsonObject.getJSONObject("counts");
int activeUserCount = counts.getInt("users_active_month");
int postCount = counts.getInt("posts");
int commentCount = counts.getInt("comments");
stats = new CommunityStats(subscribers, activeUserCount, postCount, commentCount);
}
return new SubredditData(id,name,title,description,removed,published,updated,deleted,isNSFW,actorId,local,iconUrl,bannerImageUrl,hidden,postingRestrictedToMods,instanceId,subscribers);
return new SubredditData(id, name, title, description, removed, published, updated, deleted, isNSFW, actorId, local, iconUrl, bannerImageUrl, hidden, postingRestrictedToMods, instanceId, subscribers, blocked, stats);
}
interface ParseSubredditDataListener {
@@ -170,4 +189,25 @@ public class ParseSubredditData {
}
}
}
public static String formatISOTime(String isoTime) {
// Truncate the time to millisecond precision
//String truncatedTime = isoTime.substring(0, 23);
SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
isoFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date date = isoFormat.parse(isoTime);
// Set your desired output format here
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss", Locale.US);
outputFormat.setTimeZone(TimeZone.getDefault()); // Set to device's default timezone
return outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
}

View File

@@ -22,4 +22,7 @@ public interface SubredditDao {
@Query("SELECT * from subreddits WHERE name = :namePrefixed COLLATE NOCASE LIMIT 1")
SubredditData getSubredditData(String namePrefixed);
@Query("SELECT * from subreddits WHERE actor_id = :actorId COLLATE NOCASE LIMIT 1")
SubredditData getSubredditDataByActorId(String actorId);
}

View File

@@ -1,13 +1,18 @@
package eu.toldi.infinityforlemmy.subreddit;
import android.os.Parcel;
import android.os.Parcelable;
import androidx.annotation.NonNull;
import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.Ignore;
import androidx.room.PrimaryKey;
import eu.toldi.infinityforlemmy.community.CommunityStats;
@Entity(tableName = "subreddits")
public class SubredditData {
public class SubredditData implements Parcelable {
@PrimaryKey
@NonNull
@ColumnInfo(name = "id")
@@ -61,10 +66,80 @@ public class SubredditData {
@ColumnInfo(name = "subscribers")
private int subscribers;
@ColumnInfo(name = "blocked")
private boolean blocked;
@Ignore
private boolean isSelected;
@Ignore
private CommunityStats communityStats;
protected SubredditData(Parcel in) {
id = in.readInt();
name = in.readString();
title = in.readString();
description = in.readString();
removed = in.readByte() != 0;
published = in.readString();
updated = in.readString();
deleted = in.readByte() != 0;
nsfw = in.readByte() != 0;
actorId = in.readString();
local = in.readByte() != 0;
icon = in.readString();
banner = in.readString();
hidden = in.readByte() != 0;
postingRestrictedToMods = in.readByte() != 0;
instanceId = in.readInt();
subscribers = in.readInt();
blocked = in.readByte() != 0;
isSelected = in.readByte() != 0;
communityStats = in.readParcelable(CommunityStats.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(name);
dest.writeString(title);
dest.writeString(description);
dest.writeByte((byte) (removed ? 1 : 0));
dest.writeString(published);
dest.writeString(updated);
dest.writeByte((byte) (deleted ? 1 : 0));
dest.writeByte((byte) (nsfw ? 1 : 0));
dest.writeString(actorId);
dest.writeByte((byte) (local ? 1 : 0));
dest.writeString(icon);
dest.writeString(banner);
dest.writeByte((byte) (hidden ? 1 : 0));
dest.writeByte((byte) (postingRestrictedToMods ? 1 : 0));
dest.writeInt(instanceId);
dest.writeInt(subscribers);
dest.writeByte((byte) (blocked ? 1 : 0));
dest.writeByte((byte) (isSelected ? 1 : 0));
dest.writeParcelable(communityStats, flags);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<SubredditData> CREATOR = new Creator<SubredditData>() {
@Override
public SubredditData createFromParcel(Parcel in) {
return new SubredditData(in);
}
@Override
public SubredditData[] newArray(int size) {
return new SubredditData[size];
}
};
public int getId() {
return id;
}
@@ -201,7 +276,7 @@ public class SubredditData {
this.subscribers = subscribers;
}
public SubredditData(int id, String name, String title, String description, boolean removed, String published, String updated, boolean deleted, boolean nsfw, String actorId, boolean local, String icon, String banner, boolean hidden, boolean postingRestrictedToMods, int instanceId, int subscribers) {
public SubredditData(int id, String name, String title, String description, boolean removed, String published, String updated, boolean deleted, boolean nsfw, String actorId, boolean local, String icon, String banner, boolean hidden, boolean postingRestrictedToMods, int instanceId, int subscribers, boolean blocked) {
this.id = id;
this.name = name;
this.title = title;
@@ -219,6 +294,29 @@ public class SubredditData {
this.postingRestrictedToMods = postingRestrictedToMods;
this.instanceId = instanceId;
this.subscribers = subscribers;
this.blocked = blocked;
}
public SubredditData(int id, String name, String title, String description, boolean removed, String published, String updated, boolean deleted, boolean nsfw, String actorId, boolean local, String icon, String banner, boolean hidden, boolean postingRestrictedToMods, int instanceId, int subscribers, boolean blocked, CommunityStats communityStats) {
this.id = id;
this.name = name;
this.title = title;
this.description = description;
this.removed = removed;
this.published = published;
this.updated = updated;
this.deleted = deleted;
this.nsfw = nsfw;
this.actorId = actorId;
this.local = local;
this.icon = icon;
this.banner = banner;
this.hidden = hidden;
this.postingRestrictedToMods = postingRestrictedToMods;
this.instanceId = instanceId;
this.subscribers = subscribers;
this.blocked = blocked;
this.communityStats = communityStats;
}
public boolean isNSFW() {
@@ -250,6 +348,22 @@ public class SubredditData {
}
public void setSelected(boolean b) {
isSelected =b;
isSelected = b;
}
public boolean isBlocked() {
return blocked;
}
public void setBlocked(boolean blocked) {
this.blocked = blocked;
}
public CommunityStats getCommunityStats() {
return communityStats;
}
public void setCommunityStats(CommunityStats communityStats) {
this.communityStats = communityStats;
}
}

View File

@@ -2,11 +2,8 @@ package eu.toldi.infinityforlemmy.user;
import androidx.annotation.NonNull;
import java.util.HashMap;
import java.util.Map;
import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.dto.UserBlockDTO;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
@@ -15,13 +12,13 @@ import retrofit2.Retrofit;
public class BlockUser {
public interface BlockUserListener {
void success();
void failed();
}
public static void blockUser(Retrofit oauthRetrofit, String accessToken, String username, BlockUserListener blockUserListener) {
Map<String, String> params = new HashMap<>();
params.put(APIUtils.NAME_KEY, username);
oauthRetrofit.create(RedditAPI.class).blockUser(APIUtils.getOAuthHeader(accessToken), params).enqueue(new Callback<String>() {
public static void blockUser(Retrofit retrofit, String accessToken, int userID, boolean block, BlockUserListener blockUserListener) {
LemmyAPI api = retrofit.create(LemmyAPI.class);
api.userBlock(new UserBlockDTO(userID, block, accessToken)).enqueue(new Callback<>() {
@Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) {

View File

@@ -21,13 +21,14 @@ public class ParseUserData {
new ParseUserListingDataAsyncTask(response, parseUserListingDataListener).execute();
}
private static UserData parseUserDataBase(JSONObject userDataJson, boolean parseFullKarma) throws JSONException {
public static UserData parseUserDataBase(JSONObject userDataJson, boolean parseFullKarma) throws JSONException {
if (userDataJson == null) {
return null;
}
JSONObject personJson = (userDataJson.has("person_view")) ? userDataJson.getJSONObject("person_view").getJSONObject("person") : userDataJson.getJSONObject("person");
JSONObject countsJson = (userDataJson.has("person_view")) ? userDataJson.getJSONObject("person_view").getJSONObject("counts") : userDataJson.getJSONObject("counts");
String userName = personJson.getString(JSONUtils.NAME_KEY);
String actor_id = personJson.getString("actor_id");
String iconImageUrl = "";
@@ -38,14 +39,12 @@ public class ParseUserData {
if (!personJson.isNull("banner")) {
bannerImageUrl = personJson.getString("banner");
}
JSONObject countsJson = (userDataJson.has("person_view")) ? userDataJson.getJSONObject("person_view").getJSONObject("counts") : userDataJson.getJSONObject("counts");
int linkKarma = countsJson.getInt(JSONUtils.POST_SCORE_KEY);
int commentKarma = countsJson.getInt(JSONUtils.COMMENT_SCORE_KEY);
int account_id = personJson.getInt("id");
int instance_id = personJson.getInt("instance_id");
String cakeday = personJson.getString(JSONUtils.PUBLISHED);
cakeday = cakeday.substring(0, cakeday.indexOf("T"));
boolean isBot = personJson.getBoolean("bot_account");
boolean isBanned = personJson.getBoolean("banned");
boolean isLocal = personJson.getBoolean("local");
@@ -61,9 +60,13 @@ public class ParseUserData {
if (!personJson.isNull("display_name")) {
title = personJson.getString("display_name");
}
int postCount = countsJson.optInt("post_count", 0);
int commentCount = countsJson.optInt("comment_count", 0);
int postScore = countsJson.optInt("post_score", 0);
int commentScore = countsJson.optInt("comment_score", 0);
UserStats userStats = new UserStats(postCount, postScore, commentCount, commentScore);
return new UserData(account_id,userName,title, iconImageUrl,isBanned,cakeday,actor_id,isLocal,isDeleted,isAdmin,isBot,instance_id);
return new UserData(account_id, userName, title, iconImageUrl, isBanned, cakeday, actor_id, isLocal, isDeleted, isAdmin, isBot, instance_id, userStats);
}
interface ParseUserDataListener {

View File

@@ -25,4 +25,7 @@ public interface UserDao {
@Query("SELECT * FROM users WHERE name = :userName COLLATE NOCASE LIMIT 1")
UserData getUserData(String userName);
@Query("SELECT * FROM users WHERE actor_id = :actorId COLLATE NOCASE LIMIT 1")
UserData getUserDataByActorId(String actorId);
}

View File

@@ -49,6 +49,9 @@ public class UserData {
@Ignore
private boolean isSelected;
@Ignore
private UserStats stats;
public boolean isSelected() {
return isSelected;
}
@@ -157,6 +160,10 @@ public class UserData {
this.instanceId = instanceId;
}
public UserStats getStats() {
return stats;
}
public UserData(int id, String name, String displayName, String avatar, boolean banned, String published, String actorId, boolean local, boolean deleted, boolean admin, boolean botAccount, int instanceId) {
this.id = id;
this.name = name;
@@ -172,6 +179,23 @@ public class UserData {
this.instanceId = instanceId;
}
public UserData(int id, String name, String displayName, String avatar, boolean banned, String published, String actorId, boolean local, boolean deleted, boolean admin, boolean botAccount, int instanceId, UserStats stats) {
this.id = id;
this.name = name;
this.displayName = displayName;
this.avatar = avatar;
this.banned = banned;
this.published = published;
this.actorId = actorId;
this.local = local;
this.deleted = deleted;
this.admin = admin;
this.botAccount = botAccount;
this.instanceId = instanceId;
this.stats = stats;
}
public boolean isCanBeFollowed() {
return false;
}

View File

@@ -1,11 +1,20 @@
package eu.toldi.infinityforlemmy.utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class LemmyUtils {
public static String actorID2FullName(String url) {
String[] splitURL = url.split("/");
String userName = splitURL[splitURL.length - 1];
String domain = splitURL[2];
return userName + "@" + domain;
return (userName.contains("@")) ? userName : userName + "@" + domain;
}
public static String qualifiedCommunityName2ActorId(String qualifiedName) {
@@ -21,4 +30,25 @@ public class LemmyUtils {
String domain = splitQualifiedName[1];
return "https://" + domain + "/u/" + userName;
}
public static Long dateStringToMills(String dateStr) {
long postTimeMillis = 0;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
postTimeMillis = ZonedDateTime.parse(dateStr,
DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.of("Z"))).toInstant().toEpochMilli();
} else {
dateStr = dateStr.substring(0, dateStr.lastIndexOf(".") + 4) + 'Z';
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date date = sdf.parse(dateStr);
if (date != null) {
postTimeMillis = date.getTime();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return postTimeMillis;
}
}

View File

@@ -48,6 +48,16 @@ public class SharedPreferencesUtils {
public static final String USE_CIRCULAR_FAB = "use_circular_fab";
public static final String POST_SEPARATE_UP_AND_DOWN_VOTES = "post_separate_down_and_up_votes";
public static final String POST_DETAIL_SEPARATE_UP_AND_DOWN_VOTES = "post_detail_separate_down_and_up_votes";
public static final String COMMENT_SEPARATE_UP_AND_DOWN_VOTES = "comment_separate_down_and_up_votes";
public static final String POST_DISPLAY_NAME_INSTEAD_OF_USERNAME = "post_display_name_instead_of_user_name";
public static final String POST_DETAIL_DISPLAY_NAME_INSTEAD_OF_USERNAME = "post_detail_display_name_instead_of_user_name";
public static final String SORT_TYPE_SHARED_PREFERENCES_FILE = "eu.toldi.infinityforlemmy.sort_type";
public static final String SORT_TYPE_BEST_POST = "sort_type_best_post";
public static final String SORT_TIME_BEST_POST = "sort_time_best_post";
@@ -400,4 +410,5 @@ public class SharedPreferencesUtils {
public static final String OPEN_LINK_IN_APP_LEGACY = "open_link_in_app";
public static final String ACCOUNT_INSTANCE = "account_instance";
public static final String ACCOUNT_QUALIFIED_NAME = "account_qualified_name";
public static final String CAN_DOWNVOTE = "can_downvote";
}

Some files were not shown because too many files have changed in this diff Show More