Basic browsing functionality

This commit is contained in:
Balazs Toldi 2023-07-20 15:58:52 +02:00
parent fd499edccf
commit d78b12f78d
No known key found for this signature in database
GPG Key ID: 6C7D440036F99D58
128 changed files with 1613 additions and 1873 deletions

View File

@ -100,6 +100,7 @@ dependencies {
implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion"
implementation "com.squareup.retrofit2:adapter-guava:$retrofitVersion" implementation "com.squareup.retrofit2:adapter-guava:$retrofitVersion"
implementation "com.squareup.retrofit2:converter-gson:$retrofitVersion"
implementation 'com.squareup.okhttp3:okhttp:4.9.1' implementation 'com.squareup.okhttp3:okhttp:4.9.1'
// Dependency injection // Dependency injection

View File

@ -51,53 +51,10 @@ class AccessTokenAuthenticator implements Authenticator {
return null; return null;
} }
String accessTokenFromDatabase = account.getAccessToken(); String accessTokenFromDatabase = account.getAccessToken();
if (accessToken.equals(accessTokenFromDatabase)) {
String newAccessToken = refreshAccessToken(account);
if (!newAccessToken.equals("")) {
return response.request().newBuilder().headers(Headers.of(APIUtils.getOAuthHeader(newAccessToken))).build();
} else {
return null;
}
} else {
return response.request().newBuilder().headers(Headers.of(APIUtils.getOAuthHeader(accessTokenFromDatabase))).build(); return response.request().newBuilder().headers(Headers.of(APIUtils.getOAuthHeader(accessTokenFromDatabase))).build();
} }
} }
}
return null; return null;
} }
private String refreshAccessToken(Account account) {
String refreshToken = mRedditDataRoomDatabase.accountDao().getCurrentAccount().getRefreshToken();
RedditAPI api = mRetrofit.create(RedditAPI.class);
Map<String, String> params = new HashMap<>();
params.put(APIUtils.GRANT_TYPE_KEY, APIUtils.GRANT_TYPE_REFRESH_TOKEN);
params.put(APIUtils.REFRESH_TOKEN_KEY, refreshToken);
Call<String> accessTokenCall = api.getAccessToken(APIUtils.getHttpBasicAuthHeader(), params);
try {
retrofit2.Response<String> response = accessTokenCall.execute();
if (response.isSuccessful() && response.body() != null) {
JSONObject jsonObject = new JSONObject(response.body());
String newAccessToken = jsonObject.getString(APIUtils.ACCESS_TOKEN_KEY);
String newRefreshToken = jsonObject.has(APIUtils.REFRESH_TOKEN_KEY) ? jsonObject.getString(APIUtils.REFRESH_TOKEN_KEY) : null;
if (newRefreshToken == null) {
mRedditDataRoomDatabase.accountDao().updateAccessToken(account.getAccountName(), newAccessToken);
} else {
mRedditDataRoomDatabase.accountDao().updateAccessTokenAndRefreshToken(account.getAccountName(), newAccessToken, newRefreshToken);
}
if (mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, "").equals(account.getAccountName())) {
mCurrentAccountSharedPreferences.edit().putString(SharedPreferencesUtils.ACCESS_TOKEN, newAccessToken).apply();
}
return newAccessToken;
}
return "";
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return "";
}
} }

View File

@ -54,12 +54,9 @@ public class AnyAccountAccessTokenAuthenticator implements Authenticator {
} }
String accessTokenFromDatabase = mAccount.getAccessToken(); String accessTokenFromDatabase = mAccount.getAccessToken();
if (accessToken.equals(accessTokenFromDatabase)) { if (accessToken.equals(accessTokenFromDatabase)) {
String newAccessToken = refreshAccessToken(mAccount);
if (!newAccessToken.equals("")) {
return response.request().newBuilder().headers(Headers.of(APIUtils.getOAuthHeader(newAccessToken))).build();
} else {
return null; return null;
}
} else { } else {
return response.request().newBuilder().headers(Headers.of(APIUtils.getOAuthHeader(accessTokenFromDatabase))).build(); return response.request().newBuilder().headers(Headers.of(APIUtils.getOAuthHeader(accessTokenFromDatabase))).build();
} }
@ -68,39 +65,4 @@ public class AnyAccountAccessTokenAuthenticator implements Authenticator {
return null; return null;
} }
private String refreshAccessToken(Account account) {
String refreshToken = account.getRefreshToken();
RedditAPI api = mRetrofit.create(RedditAPI.class);
Map<String, String> params = new HashMap<>();
params.put(APIUtils.GRANT_TYPE_KEY, APIUtils.GRANT_TYPE_REFRESH_TOKEN);
params.put(APIUtils.REFRESH_TOKEN_KEY, refreshToken);
Call<String> accessTokenCall = api.getAccessToken(APIUtils.getHttpBasicAuthHeader(), params);
try {
retrofit2.Response<String> response = accessTokenCall.execute();
if (response.isSuccessful() && response.body() != null) {
JSONObject jsonObject = new JSONObject(response.body());
String newAccessToken = jsonObject.getString(APIUtils.ACCESS_TOKEN_KEY);
String newRefreshToken = jsonObject.has(APIUtils.REFRESH_TOKEN_KEY) ? jsonObject.getString(APIUtils.REFRESH_TOKEN_KEY) : null;
if (newRefreshToken == null) {
mRedditDataRoomDatabase.accountDao().updateAccessToken(account.getAccountName(), newAccessToken);
} else {
mRedditDataRoomDatabase.accountDao().updateAccessTokenAndRefreshToken(account.getAccountName(), newAccessToken, newRefreshToken);
}
Account currentAccount = mRedditDataRoomDatabase.accountDao().getCurrentAccount();
if (currentAccount != null && mAccount.getAccountName().equals(currentAccount.getAccountName()) && mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, "").equals(account.getAccountName())) {
mCurrentAccountSharedPreferences.edit().putString(SharedPreferencesUtils.ACCESS_TOKEN, newAccessToken).apply();
}
return newAccessToken;
}
return "";
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return "";
}
} }

View File

@ -8,9 +8,11 @@ import androidx.annotation.NonNull;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.utils.APIUtils; import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.JSONUtils; import eu.toldi.infinityforlemmy.utils.JSONUtils;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Retrofit; import retrofit2.Retrofit;
@ -18,10 +20,10 @@ import retrofit2.Retrofit;
public class FetchMyInfo { public class FetchMyInfo {
public static void fetchAccountInfo(final Retrofit retrofit, RedditDataRoomDatabase redditDataRoomDatabase, public static void fetchAccountInfo(final Retrofit retrofit, RedditDataRoomDatabase redditDataRoomDatabase,
String accessToken, final FetchMyInfoListener fetchMyInfoListener) { String username,String accessToken, final FetchMyInfoListener fetchMyInfoListener) {
RedditAPI api = retrofit.create(RedditAPI.class); LemmyAPI api = retrofit.create(LemmyAPI.class);
Call<String> userInfo = api.getMyInfo(APIUtils.getOAuthHeader(accessToken)); Call<String> userInfo = api.userInfo(username,accessToken);
userInfo.enqueue(new Callback<String>() { userInfo.enqueue(new Callback<String>() {
@Override @Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) { public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
@ -40,7 +42,7 @@ public class FetchMyInfo {
} }
public interface FetchMyInfoListener { public interface FetchMyInfoListener {
void onFetchMyInfoSuccess(String name, String profileImageUrl, String bannerImageUrl, int karma); void onFetchMyInfoSuccess(String name, String display_name,String profileImageUrl, String bannerImageUrl);
void onFetchMyInfoFailed(boolean parseFailed); void onFetchMyInfoFailed(boolean parseFailed);
} }
@ -54,7 +56,8 @@ public class FetchMyInfo {
private String name; private String name;
private String profileImageUrl; private String profileImageUrl;
private String bannerImageUrl; private String bannerImageUrl;
private int karma;
private String display_name;
ParseAndSaveAccountInfoAsyncTask(String response, RedditDataRoomDatabase redditDataRoomDatabase, ParseAndSaveAccountInfoAsyncTask(String response, RedditDataRoomDatabase redditDataRoomDatabase,
FetchMyInfoListener fetchMyInfoListener) { FetchMyInfoListener fetchMyInfoListener) {
@ -71,14 +74,17 @@ public class FetchMyInfo {
@Override @Override
protected Void doInBackground(Void... voids) { protected Void doInBackground(Void... voids) {
try { try {
name = jsonResponse.getString(JSONUtils.NAME_KEY); JSONObject person = jsonResponse.getJSONObject("person_view").getJSONObject("person");
profileImageUrl = Html.fromHtml(jsonResponse.getString(JSONUtils.ICON_IMG_KEY)).toString();
if (!jsonResponse.isNull(JSONUtils.SUBREDDIT_KEY)) {
bannerImageUrl = Html.fromHtml(jsonResponse.getJSONObject(JSONUtils.SUBREDDIT_KEY).getString(JSONUtils.BANNER_IMG_KEY)).toString();
}
karma = jsonResponse.getInt(JSONUtils.TOTAL_KARMA_KEY);
redditDataRoomDatabase.accountDao().updateAccountInfo(name, profileImageUrl, bannerImageUrl, karma); name = LemmyUtils.actorID2FullName(person.getString("actor_id"));
if (!person.isNull("avatar")) {
profileImageUrl = person.getString("avatar");
}
if (!person.isNull("banner")) {
bannerImageUrl = person.getString("banner");
}
display_name = person.getString("name");
redditDataRoomDatabase.accountDao().updateAccountInfo(name, profileImageUrl, bannerImageUrl);
} catch (JSONException e) { } catch (JSONException e) {
parseFailed = true; parseFailed = true;
} }
@ -88,7 +94,7 @@ public class FetchMyInfo {
@Override @Override
protected void onPostExecute(Void aVoid) { protected void onPostExecute(Void aVoid) {
if (!parseFailed) { if (!parseFailed) {
fetchMyInfoListener.onFetchMyInfoSuccess(name, profileImageUrl, bannerImageUrl, karma); fetchMyInfoListener.onFetchMyInfoSuccess(name,display_name, profileImageUrl, bannerImageUrl);
} else { } else {
fetchMyInfoListener.onFetchMyInfoFailed(true); fetchMyInfoListener.onFetchMyInfoFailed(true);
} }

View File

@ -4,25 +4,24 @@ import androidx.annotation.NonNull;
import java.util.ArrayList; import java.util.ArrayList;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.subreddit.SubredditData; import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData; import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData;
import eu.toldi.infinityforlemmy.subscribeduser.SubscribedUserData; import eu.toldi.infinityforlemmy.subscribeduser.SubscribedUserData;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Response; import retrofit2.Response;
import retrofit2.Retrofit; import retrofit2.Retrofit;
public class FetchSubscribedThing { public class FetchSubscribedThing {
public static void fetchSubscribedThing(final Retrofit oauthRetrofit, String accessToken, String accountName, public static void fetchSubscribedThing(final Retrofit retrofit, String accessToken, String accountName,
final String lastItem, final ArrayList<SubscribedSubredditData> subscribedSubredditData, final Integer page, final ArrayList<SubscribedSubredditData> subscribedSubredditData,
final ArrayList<SubscribedUserData> subscribedUserData, final ArrayList<SubscribedUserData> subscribedUserData,
final ArrayList<SubredditData> subredditData, final ArrayList<SubredditData> subredditData,
final FetchSubscribedThingListener fetchSubscribedThingListener) { final FetchSubscribedThingListener fetchSubscribedThingListener) {
RedditAPI api = oauthRetrofit.create(RedditAPI.class); LemmyAPI api = retrofit.create(LemmyAPI.class);
Call<String> subredditDataCall = api.getSubscribedThing(lastItem, APIUtils.getOAuthHeader(accessToken)); Call<String> subredditDataCall = api.listCommunities("Subscribed",null,page,null,accessToken);
subredditDataCall.enqueue(new Callback<String>() { subredditDataCall.enqueue(new Callback<String>() {
@Override @Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
@ -35,12 +34,12 @@ public class FetchSubscribedThing {
public void onParseSubscribedSubredditsSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData, public void onParseSubscribedSubredditsSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData,
ArrayList<SubscribedUserData> subscribedUserData, ArrayList<SubscribedUserData> subscribedUserData,
ArrayList<SubredditData> subredditData, ArrayList<SubredditData> subredditData,
String lastItem) { boolean lastItem) {
if (lastItem.equals("null")) { if (lastItem) {
fetchSubscribedThingListener.onFetchSubscribedThingSuccess( fetchSubscribedThingListener.onFetchSubscribedThingSuccess(
subscribedSubredditData, subscribedUserData, subredditData); subscribedSubredditData, subscribedUserData, subredditData);
} else { } else {
fetchSubscribedThing(oauthRetrofit, accessToken, accountName, lastItem, fetchSubscribedThing(retrofit, accessToken, accountName, (page == null) ? 2 : page+1,
subscribedSubredditData, subscribedUserData, subredditData, subscribedSubredditData, subscribedUserData, subredditData,
fetchSubscribedThingListener); fetchSubscribedThingListener);
} }

View File

@ -17,11 +17,13 @@ import okhttp3.Interceptor;
import okhttp3.OkHttpClient; import okhttp3.OkHttpClient;
import retrofit2.Retrofit; import retrofit2.Retrofit;
import retrofit2.adapter.guava.GuavaCallAdapterFactory; import retrofit2.adapter.guava.GuavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory;
@Module(includes = AppModule.class) @Module(includes = AppModule.class)
abstract class NetworkModule { abstract class NetworkModule {
@Provides @Provides
@Named("base") @Named("base")
@Singleton @Singleton
@ -33,9 +35,17 @@ abstract class NetworkModule {
.build(); .build();
} }
@Provides @Provides
@Named("base") @Named("base")
@Singleton @Singleton
static RetrofitHolder provideBaseRetrofitHolder(@Named("base") OkHttpClient okHttpClient) {
return new RetrofitHolder(okHttpClient);
}
/*@Provides
@Named("base")
@Singleton
static Retrofit provideBaseRetrofit(@Named("base") OkHttpClient okHttpClient) { static Retrofit provideBaseRetrofit(@Named("base") OkHttpClient okHttpClient) {
return new Retrofit.Builder() return new Retrofit.Builder()
.baseUrl(APIUtils.API_BASE_URI) .baseUrl(APIUtils.API_BASE_URI)
@ -43,8 +53,9 @@ abstract class NetworkModule {
.addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(SortTypeConverterFactory.create()) .addConverterFactory(SortTypeConverterFactory.create())
.addCallAdapterFactory(GuavaCallAdapterFactory.create()) .addCallAdapterFactory(GuavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build(); .build();
} }*/
@Provides @Provides
static ConnectionPool provideConnectionPool() { static ConnectionPool provideConnectionPool() {
@ -53,15 +64,15 @@ abstract class NetworkModule {
@Provides @Provides
@Named("no_oauth") @Named("no_oauth")
static Retrofit provideRetrofit(@Named("base") Retrofit retrofit) { static RetrofitHolder provideRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit; return retrofit;
} }
@Provides @Provides
@Named("oauth") @Named("oauth")
static Retrofit provideOAuthRetrofit(@Named("base") Retrofit retrofit, static Retrofit provideOAuthRetrofit(@Named("base") RetrofitHolder retrofit,
@Named("default") OkHttpClient okHttpClient) { @Named("default") OkHttpClient okHttpClient) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.OAUTH_API_BASE_URI) .baseUrl(APIUtils.OAUTH_API_BASE_URI)
.client(okHttpClient) .client(okHttpClient)
.build(); .build();
@ -71,12 +82,12 @@ abstract class NetworkModule {
@Named("default") @Named("default")
@Singleton @Singleton
static OkHttpClient provideOkHttpClient(@Named("base") OkHttpClient httpClient, static OkHttpClient provideOkHttpClient(@Named("base") OkHttpClient httpClient,
@Named("base") Retrofit retrofit, @Named("base") RetrofitHolder retrofit,
RedditDataRoomDatabase accountRoomDatabase, RedditDataRoomDatabase accountRoomDatabase,
@Named("current_account") SharedPreferences currentAccountSharedPreferences, @Named("current_account") SharedPreferences currentAccountSharedPreferences,
ConnectionPool connectionPool) { ConnectionPool connectionPool) {
return httpClient.newBuilder() return httpClient.newBuilder()
.authenticator(new AccessTokenAuthenticator(retrofit, accountRoomDatabase, currentAccountSharedPreferences)) .authenticator(new AccessTokenAuthenticator(retrofit.getRetrofit(), accountRoomDatabase, currentAccountSharedPreferences))
.connectionPool(connectionPool) .connectionPool(connectionPool)
.build(); .build();
} }
@ -84,8 +95,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("oauth_without_authenticator") @Named("oauth_without_authenticator")
@Singleton @Singleton
static Retrofit provideOauthWithoutAuthenticatorRetrofit(@Named("base") Retrofit retrofit) { static Retrofit provideOauthWithoutAuthenticatorRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.OAUTH_API_BASE_URI) .baseUrl(APIUtils.OAUTH_API_BASE_URI)
.build(); .build();
} }
@ -93,8 +104,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("upload_media") @Named("upload_media")
@Singleton @Singleton
static Retrofit provideUploadMediaRetrofit(@Named("base") Retrofit retrofit) { static Retrofit provideUploadMediaRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.API_UPLOAD_MEDIA_URI) .baseUrl(APIUtils.API_UPLOAD_MEDIA_URI)
.build(); .build();
} }
@ -102,8 +113,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("upload_video") @Named("upload_video")
@Singleton @Singleton
static Retrofit provideUploadVideoRetrofit(@Named("base") Retrofit retrofit) { static Retrofit provideUploadVideoRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.API_UPLOAD_VIDEO_URI) .baseUrl(APIUtils.API_UPLOAD_VIDEO_URI)
.build(); .build();
} }
@ -111,8 +122,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("download_media") @Named("download_media")
@Singleton @Singleton
static Retrofit provideDownloadRedditVideoRetrofit(@Named("base") Retrofit retrofit) { static Retrofit provideDownloadRedditVideoRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl("http://localhost/") .baseUrl("http://localhost/")
.build(); .build();
} }
@ -120,8 +131,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("gfycat") @Named("gfycat")
@Singleton @Singleton
static Retrofit provideGfycatRetrofit(@Named("base") Retrofit retrofit) { static Retrofit provideGfycatRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.GFYCAT_API_BASE_URI) .baseUrl(APIUtils.GFYCAT_API_BASE_URI)
.build(); .build();
} }
@ -137,7 +148,7 @@ abstract class NetworkModule {
@Singleton @Singleton
static Retrofit provideRedgifsRetrofit(@Named("RedgifsAccessTokenAuthenticator") Interceptor accessTokenAuthenticator, static Retrofit provideRedgifsRetrofit(@Named("RedgifsAccessTokenAuthenticator") Interceptor accessTokenAuthenticator,
@Named("base") OkHttpClient httpClient, @Named("base") OkHttpClient httpClient,
@Named("base") Retrofit retrofit, @Named("base") RetrofitHolder retrofit,
ConnectionPool connectionPool) { ConnectionPool connectionPool) {
OkHttpClient.Builder okHttpClientBuilder = httpClient.newBuilder() OkHttpClient.Builder okHttpClientBuilder = httpClient.newBuilder()
.addInterceptor(chain -> chain.proceed( .addInterceptor(chain -> chain.proceed(
@ -149,7 +160,7 @@ abstract class NetworkModule {
.addInterceptor(accessTokenAuthenticator) .addInterceptor(accessTokenAuthenticator)
.connectionPool(connectionPool); .connectionPool(connectionPool);
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.REDGIFS_API_BASE_URI) .baseUrl(APIUtils.REDGIFS_API_BASE_URI)
.client(okHttpClientBuilder.build()) .client(okHttpClientBuilder.build())
.build(); .build();
@ -158,8 +169,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("imgur") @Named("imgur")
@Singleton @Singleton
static Retrofit provideImgurRetrofit(@Named("base") Retrofit retrofit) { static Retrofit provideImgurRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.IMGUR_API_BASE_URI) .baseUrl(APIUtils.IMGUR_API_BASE_URI)
.build(); .build();
} }
@ -167,8 +178,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("pushshift") @Named("pushshift")
@Singleton @Singleton
static Retrofit providePushshiftRetrofit(@Named("base") Retrofit retrofit) { static Retrofit providePushshiftRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.PUSHSHIFT_API_BASE_URI) .baseUrl(APIUtils.PUSHSHIFT_API_BASE_URI)
.build(); .build();
} }
@ -176,8 +187,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("reveddit") @Named("reveddit")
@Singleton @Singleton
static Retrofit provideRevedditRetrofit(@Named("base") Retrofit retrofit) { static Retrofit provideRevedditRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.REVEDDIT_API_BASE_URI) .baseUrl(APIUtils.REVEDDIT_API_BASE_URI)
.build(); .build();
} }
@ -185,8 +196,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("vReddIt") @Named("vReddIt")
@Singleton @Singleton
static Retrofit provideVReddItRetrofit(@Named("base") Retrofit retrofit) { static Retrofit provideVReddItRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl("http://localhost/") .baseUrl("http://localhost/")
.build(); .build();
} }
@ -194,8 +205,8 @@ abstract class NetworkModule {
@Provides @Provides
@Named("streamable") @Named("streamable")
@Singleton @Singleton
static Retrofit provideStreamableRetrofit(@Named("base") Retrofit retrofit) { static Retrofit provideStreamableRetrofit(@Named("base") RetrofitHolder retrofit) {
return retrofit.newBuilder() return retrofit.getRetrofit().newBuilder()
.baseUrl(APIUtils.STREAMABLE_API_BASE_URI) .baseUrl(APIUtils.STREAMABLE_API_BASE_URI)
.build(); .build();
} }

View File

@ -12,7 +12,7 @@ import eu.toldi.infinityforlemmy.subreddit.SubredditData;
import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData; import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData;
import eu.toldi.infinityforlemmy.subscribeduser.SubscribedUserData; import eu.toldi.infinityforlemmy.subscribeduser.SubscribedUserData;
import eu.toldi.infinityforlemmy.utils.JSONUtils; import eu.toldi.infinityforlemmy.utils.JSONUtils;
import eu.toldi.infinityforlemmy.utils.Utils; import eu.toldi.infinityforlemmy.utils.LemmyUtils;
class ParseSubscribedThing { class ParseSubscribedThing {
static void parseSubscribedSubreddits(String response, String accountName, static void parseSubscribedSubreddits(String response, String accountName,
@ -28,7 +28,7 @@ class ParseSubscribedThing {
void onParseSubscribedSubredditsSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData, void onParseSubscribedSubredditsSuccess(ArrayList<SubscribedSubredditData> subscribedSubredditData,
ArrayList<SubscribedUserData> subscribedUserData, ArrayList<SubscribedUserData> subscribedUserData,
ArrayList<SubredditData> subredditData, ArrayList<SubredditData> subredditData,
String lastItem); boolean lastItem);
void onParseSubscribedSubredditsFail(); void onParseSubscribedSubredditsFail();
} }
@ -37,7 +37,7 @@ class ParseSubscribedThing {
private JSONObject jsonResponse; private JSONObject jsonResponse;
private String accountName; private String accountName;
private boolean parseFailed; private boolean parseFailed;
private String lastItem; private boolean lastItem;
private ArrayList<SubscribedSubredditData> subscribedSubredditData; private ArrayList<SubscribedSubredditData> subscribedSubredditData;
private ArrayList<SubscribedUserData> subscribedUserData; private ArrayList<SubscribedUserData> subscribedUserData;
private ArrayList<SubredditData> subredditData; private ArrayList<SubredditData> subredditData;
@ -73,46 +73,48 @@ class ParseSubscribedThing {
parseFailed = true; parseFailed = true;
return null; return null;
} }
JSONArray children = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY); JSONArray children = jsonResponse.getJSONArray("communities");
if(children.length() ==0){
lastItem = true;
}
for (int i = 0; i < children.length(); i++) { for (int i = 0; i < children.length(); i++) {
JSONObject data = children.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY); JSONObject data = children.getJSONObject(i);
String name = data.getString(JSONUtils.DISPLAY_NAME_KEY); JSONObject community = data.getJSONObject("community");
String bannerImageUrl = data.getString(JSONUtils.BANNER_BACKGROUND_IMAGE_KEY); String title = community.getString(JSONUtils.TITLE_KEY);
if (bannerImageUrl.equals("") || bannerImageUrl.equals("null")) { String bannerImageUrl = "";
bannerImageUrl = data.getString(JSONUtils.BANNER_IMG_KEY); if(!community.isNull("banner")){
if (bannerImageUrl.equals("null")) { bannerImageUrl = community.getString("banner");
bannerImageUrl = "";
} }
}
String iconUrl = data.getString(JSONUtils.COMMUNITY_ICON_KEY);
if (iconUrl.equals("") || iconUrl.equals("null")) {
iconUrl = data.getString(JSONUtils.ICON_IMG_KEY);
if (iconUrl.equals("null")) {
iconUrl = "";
}
}
String id = data.getString(JSONUtils.NAME_KEY);
boolean isFavorite = data.getBoolean(JSONUtils.USER_HAS_FAVORITED_KEY);
if (data.getString(JSONUtils.SUBREDDIT_TYPE_KEY) String iconUrl = "";
.equals(JSONUtils.SUBREDDIT_TYPE_VALUE_USER)) { if(!community.isNull("icon")){
//It's a user iconUrl = community.getString("icon");
newSubscribedUserData.add(new SubscribedUserData(name.substring(2), iconUrl, accountName, isFavorite));
} else {
String subredditFullName = data.getString(JSONUtils.DISPLAY_NAME_KEY);
String description = data.getString(JSONUtils.PUBLIC_DESCRIPTION_KEY).trim();
String sidebarDescription = Utils.modifyMarkdown(data.getString(JSONUtils.DESCRIPTION_KEY).trim());
int nSubscribers = data.getInt(JSONUtils.SUBSCRIBERS_KEY);
long createdUTC = data.getLong(JSONUtils.CREATED_UTC_KEY) * 1000;
String suggestedCommentSort = data.getString(JSONUtils.SUGGESTED_COMMENT_SORT_KEY);
boolean isNSFW = data.getBoolean(JSONUtils.OVER18_KEY);
newSubscribedSubredditData.add(new SubscribedSubredditData(id, name, iconUrl, accountName, isFavorite));
newSubredditData.add(new SubredditData(id, subredditFullName, iconUrl,
bannerImageUrl, description, sidebarDescription, nSubscribers, createdUTC,
suggestedCommentSort, isNSFW));
} }
int id = community.getInt("id");
String name = community.getString("name");
String description = "";
if(!community.isNull("description")) {
description = community.getString("description");
}
boolean removed = community.getBoolean("removed");
String published = community.getString("published");
String updated = "";
if(!community.isNull("updated")) {
updated = community.getString("updated");
}
boolean deleted = community.getBoolean("deleted");
boolean nsfw = community.getBoolean("nsfw");
String actorId = community.getString("actor_id");
boolean local = community.getBoolean("local");
boolean hidden = community.getBoolean("hidden");
boolean postingRestrictedToMods = community.getBoolean("posting_restricted_to_mods");
int instanceId = community.getInt("instance_id");
int subscribers = data.getJSONObject("counts").getInt("subscribers");
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));
} }
lastItem = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getString(JSONUtils.AFTER_KEY);
} catch (JSONException e) { } catch (JSONException e) {
parseFailed = true; parseFailed = true;
e.printStackTrace(); e.printStackTrace();

View File

@ -50,7 +50,7 @@ public class PullNotificationWorker extends Worker {
Retrofit mOauthWithoutAuthenticatorRetrofit; Retrofit mOauthWithoutAuthenticatorRetrofit;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
RedditDataRoomDatabase mRedditDataRoomDatabase; RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject @Inject
@ -227,49 +227,7 @@ public class PullNotificationWorker extends Worker {
if (response.isSuccessful()) { if (response.isSuccessful()) {
return response; return response;
} else { } else {
if (response.code() == 401) {
String accessToken = refreshAccessToken(account);
if (!accessToken.equals("")) {
account.setAccessToken(accessToken);
return fetchMessages(account, retryCount - 1);
}
}
return null; return null;
} }
} }
private String refreshAccessToken(Account account) {
String refreshToken = account.getRefreshToken();
RedditAPI api = mRetrofit.create(RedditAPI.class);
Map<String, String> params = new HashMap<>();
params.put(APIUtils.GRANT_TYPE_KEY, APIUtils.GRANT_TYPE_REFRESH_TOKEN);
params.put(APIUtils.REFRESH_TOKEN_KEY, refreshToken);
Call<String> accessTokenCall = api.getAccessToken(APIUtils.getHttpBasicAuthHeader(), params);
try {
Response<String> response = accessTokenCall.execute();
if (response.isSuccessful() && response.body() != null) {
JSONObject jsonObject = new JSONObject(response.body());
String newAccessToken = jsonObject.getString(APIUtils.ACCESS_TOKEN_KEY);
String newRefreshToken = jsonObject.has(APIUtils.REFRESH_TOKEN_KEY) ? jsonObject.getString(APIUtils.REFRESH_TOKEN_KEY) : null;
if (newRefreshToken == null) {
mRedditDataRoomDatabase.accountDao().updateAccessToken(account.getAccountName(), newAccessToken);
} else {
mRedditDataRoomDatabase.accountDao().updateAccessTokenAndRefreshToken(account.getAccountName(), newAccessToken, newRefreshToken);
}
if (mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, "").equals(account.getAccountName())) {
mCurrentAccountSharedPreferences.edit().putString(SharedPreferencesUtils.ACCESS_TOKEN, newAccessToken).apply();
}
return newAccessToken;
}
return "";
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return "";
}
} }

View File

@ -0,0 +1,39 @@
package eu.toldi.infinityforlemmy;
import eu.toldi.infinityforlemmy.network.SortTypeConverterFactory;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.guava.GuavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
public class RetrofitHolder {
private Retrofit retrofit;
private OkHttpClient okHttpClient;
public Retrofit getRetrofit() {
return retrofit;
}
public void setBaseURL(String baseURL){
retrofit = createRetrofit(okHttpClient,baseURL);
}
public RetrofitHolder(OkHttpClient okHttpClient) {
this.okHttpClient = okHttpClient;
this.retrofit = createRetrofit(okHttpClient, APIUtils.API_BASE_URI);
}
private static Retrofit createRetrofit(OkHttpClient okHttpClient, String baseUrl) {
return new Retrofit.Builder()
.baseUrl(baseUrl)
.client(okHttpClient)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(SortTypeConverterFactory.create())
.addCallAdapterFactory(GuavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
}

View File

@ -30,9 +30,9 @@ public class SortType {
} }
public enum Type { public enum Type {
BEST("best", "Best"), ACTIVE("Active", "Active"),
HOT("hot", "Hot"), HOT("Hot", "Hot"),
NEW("new", "New"), NEW("New", "New"),
RANDOM("random", "Random"), RANDOM("random", "Random"),
RISING("rising", "Rising"), RISING("rising", "Rising"),
TOP("top", "Top"), TOP("top", "Top"),

View File

@ -8,7 +8,9 @@ import androidx.annotation.NonNull;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.dto.VoteDTO;
import eu.toldi.infinityforlemmy.utils.APIUtils; import eu.toldi.infinityforlemmy.utils.APIUtils;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
@ -21,16 +23,13 @@ import retrofit2.Retrofit;
public class VoteThing { public class VoteThing {
public static void voteThing(Context context, final Retrofit retrofit, String accessToken, public static void voteThing(Context context, final Retrofit retrofit, String accessToken,
final VoteThingListener voteThingListener, final String fullName, final VoteThingListener voteThingListener, final int postID,
final String point, final int position) { final int point, final int position) {
RedditAPI api = retrofit.create(RedditAPI.class); LemmyAPI api = retrofit.create(LemmyAPI.class);
Map<String, String> params = new HashMap<>();
params.put(APIUtils.DIR_KEY, point);
params.put(APIUtils.ID_KEY, fullName);
params.put(APIUtils.RANK_KEY, APIUtils.RANK);
Call<String> voteThingCall = api.voteThing(APIUtils.getOAuthHeader(accessToken), params);
Call<String> voteThingCall = api.postLike(new VoteDTO(postID,point,accessToken));
voteThingCall.enqueue(new Callback<String>() { voteThingCall.enqueue(new Callback<String>() {
@Override @Override
public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) { public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {

View File

@ -15,31 +15,33 @@ public class Account implements Parcelable {
@NonNull @NonNull
@ColumnInfo(name = "username") @ColumnInfo(name = "username")
private String accountName; private String accountName;
@ColumnInfo(name = "display_name")
private String display_name;
@ColumnInfo(name = "profile_image_url") @ColumnInfo(name = "profile_image_url")
private String profileImageUrl; private String profileImageUrl;
@ColumnInfo(name = "banner_image_url") @ColumnInfo(name = "banner_image_url")
private String bannerImageUrl; private String bannerImageUrl;
@ColumnInfo(name = "karma")
private int karma;
@ColumnInfo(name = "access_token") @ColumnInfo(name = "access_token")
private String accessToken; private String accessToken;
@ColumnInfo(name = "refresh_token")
private String refreshToken;
@ColumnInfo(name = "code") @ColumnInfo(name = "code")
private String code; private String code;
@ColumnInfo(name = "is_current_user") @ColumnInfo(name = "is_current_user")
private boolean isCurrentUser; private boolean isCurrentUser;
@ColumnInfo(name = "instance_url")
private String instance_url;
@Ignore @Ignore
protected Account(Parcel in) { protected Account(Parcel in) {
accountName = in.readString(); accountName = in.readString();
display_name = in.readString();
profileImageUrl = in.readString(); profileImageUrl = in.readString();
bannerImageUrl = in.readString(); bannerImageUrl = in.readString();
karma = in.readInt();
accessToken = in.readString(); accessToken = in.readString();
refreshToken = in.readString();
code = in.readString(); code = in.readString();
isCurrentUser = in.readByte() != 0; isCurrentUser = in.readByte() != 0;
instance_url = in.readString();
} }
public static final Creator<Account> CREATOR = new Creator<Account>() { public static final Creator<Account> CREATOR = new Creator<Account>() {
@ -56,19 +58,19 @@ public class Account implements Parcelable {
@Ignore @Ignore
public static Account getAnonymousAccount() { public static Account getAnonymousAccount() {
return new Account("-", null, null, null, null, null, 0, false); return new Account("-",null, null, null, null, null, false,null);
} }
public Account(@NonNull String accountName, String accessToken, String refreshToken, String code, public Account(@NonNull String accountName, String display_name, String accessToken, String code,
String profileImageUrl, String bannerImageUrl, int karma, boolean isCurrentUser) { String profileImageUrl, String bannerImageUrl, boolean isCurrentUser,String instance_url) {
this.accountName = accountName; this.accountName = accountName;
this.display_name = display_name;
this.accessToken = accessToken; this.accessToken = accessToken;
this.refreshToken = refreshToken;
this.code = code; this.code = code;
this.profileImageUrl = profileImageUrl; this.profileImageUrl = profileImageUrl;
this.bannerImageUrl = bannerImageUrl; this.bannerImageUrl = bannerImageUrl;
this.karma = karma;
this.isCurrentUser = isCurrentUser; this.isCurrentUser = isCurrentUser;
this.instance_url = instance_url;
} }
@NonNull @NonNull
@ -76,6 +78,10 @@ public class Account implements Parcelable {
return accountName; return accountName;
} }
public String getDisplay_name() {
return display_name;
}
public String getProfileImageUrl() { public String getProfileImageUrl() {
return profileImageUrl; return profileImageUrl;
} }
@ -84,9 +90,6 @@ public class Account implements Parcelable {
return bannerImageUrl; return bannerImageUrl;
} }
public int getKarma() {
return karma;
}
public String getAccessToken() { public String getAccessToken() {
return accessToken; return accessToken;
@ -96,10 +99,6 @@ public class Account implements Parcelable {
this.accessToken = accessToken; this.accessToken = accessToken;
} }
public String getRefreshToken() {
return refreshToken;
}
public String getCode() { public String getCode() {
return code; return code;
} }
@ -113,15 +112,19 @@ public class Account implements Parcelable {
return 0; return 0;
} }
public String getInstance_url() {
return instance_url;
}
@Override @Override
public void writeToParcel(Parcel dest, int flags) { public void writeToParcel(Parcel dest, int flags) {
dest.writeString(accountName); dest.writeString(accountName);
dest.writeString(display_name);
dest.writeString(profileImageUrl); dest.writeString(profileImageUrl);
dest.writeString(bannerImageUrl); dest.writeString(bannerImageUrl);
dest.writeInt(karma);
dest.writeString(accessToken); dest.writeString(accessToken);
dest.writeString(refreshToken);
dest.writeString(code); dest.writeString(code);
dest.writeByte((byte) (isCurrentUser ? 1 : 0)); dest.writeByte((byte) (isCurrentUser ? 1 : 0));
dest.writeString(instance_url);
} }
} }

View File

@ -46,9 +46,8 @@ public interface AccountDao {
@Query("SELECT * FROM accounts WHERE is_current_user = 1 AND username != '-' LIMIT 1") @Query("SELECT * FROM accounts WHERE is_current_user = 1 AND username != '-' LIMIT 1")
LiveData<Account> getCurrentAccountLiveData(); LiveData<Account> getCurrentAccountLiveData();
@Query("UPDATE accounts SET profile_image_url = :profileImageUrl, banner_image_url = :bannerImageUrl, " + @Query("UPDATE accounts SET profile_image_url = :profileImageUrl, banner_image_url = :bannerImageUrl WHERE username = :username")
"karma = :karma WHERE username = :username") void updateAccountInfo(String username, String profileImageUrl, String bannerImageUrl);
void updateAccountInfo(String username, String profileImageUrl, String bannerImageUrl, int karma);
@Query("SELECT * FROM accounts WHERE is_current_user = 0 AND username != '-' ORDER BY username COLLATE NOCASE ASC") @Query("SELECT * FROM accounts WHERE is_current_user = 0 AND username != '-' ORDER BY username COLLATE NOCASE ASC")
LiveData<List<Account>> getAccountsExceptCurrentAccountLiveData(); LiveData<List<Account>> getAccountsExceptCurrentAccountLiveData();
@ -56,8 +55,8 @@ public interface AccountDao {
@Query("UPDATE accounts SET is_current_user = 1 WHERE username = :username") @Query("UPDATE accounts SET is_current_user = 1 WHERE username = :username")
void markAccountCurrent(String username); void markAccountCurrent(String username);
@Query("UPDATE accounts SET access_token = :accessToken, refresh_token = :refreshToken WHERE username = :username") @Query("UPDATE accounts SET access_token = :accessToken WHERE username = :username")
void updateAccessTokenAndRefreshToken(String username, String accessToken, String refreshToken); void updateAccessTokenAndRefreshToken(String username, String accessToken);
@Query("UPDATE accounts SET access_token = :accessToken WHERE username = :username") @Query("UPDATE accounts SET access_token = :accessToken WHERE username = :username")
void updateAccessToken(String username, String accessToken); void updateAccessToken(String username, String accessToken);

View File

@ -23,6 +23,7 @@ import android.view.MenuItem;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.view.Window; import android.view.Window;
import android.widget.Button;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
@ -371,6 +372,11 @@ public abstract class BaseActivity extends AppCompatActivity implements CustomFo
customThemeWrapper.getTabLayoutWithCollapsedCollapsingToolbarTextColor()); customThemeWrapper.getTabLayoutWithCollapsedCollapsingToolbarTextColor());
} }
protected void applyButtonTheme(Button button){
button.setBackgroundTintList(ColorStateList.valueOf(customThemeWrapper.getColorAccent()));
button.setTextColor(customThemeWrapper.getFABIconColor());
}
protected void applyFABTheme(FloatingActionButton fab) { protected void applyFABTheme(FloatingActionButton fab) {
fab.setBackgroundTintList(ColorStateList.valueOf(customThemeWrapper.getColorAccent())); fab.setBackgroundTintList(ColorStateList.valueOf(customThemeWrapper.getColorAccent()));
fab.setImageTintList(ColorStateList.valueOf(customThemeWrapper.getFABIconColor())); fab.setImageTintList(ColorStateList.valueOf(customThemeWrapper.getFABIconColor()));

View File

@ -40,6 +40,7 @@ import java.util.concurrent.TimeUnit;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Named; import javax.inject.Named;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import io.noties.markwon.AbstractMarkwonPlugin; import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon; import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration; import io.noties.markwon.MarkwonConfiguration;
@ -91,7 +92,7 @@ public class CommentActivity extends BaseActivity implements UploadImageEnabledA
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -387,7 +388,7 @@ public class CommentActivity extends BaseActivity implements UploadImageEnabledA
Snackbar sendingSnackbar = Snackbar.make(binding.commentCoordinatorLayout, R.string.sending_comment, Snackbar.LENGTH_INDEFINITE); Snackbar sendingSnackbar = Snackbar.make(binding.commentCoordinatorLayout, R.string.sending_comment, Snackbar.LENGTH_INDEFINITE);
sendingSnackbar.show(); sendingSnackbar.show();
Retrofit newAuthenticatorOauthRetrofit = mOauthRetrofit.newBuilder().client(new OkHttpClient.Builder().authenticator(new AnyAccountAccessTokenAuthenticator(mRetrofit, mRedditDataRoomDatabase, selectedAccount, mCurrentAccountSharedPreferences)) Retrofit newAuthenticatorOauthRetrofit = mOauthRetrofit.newBuilder().client(new OkHttpClient.Builder().authenticator(new AnyAccountAccessTokenAuthenticator(mRetrofit.getRetrofit(), mRedditDataRoomDatabase, selectedAccount, mCurrentAccountSharedPreferences))
.connectTimeout(30, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS)

View File

@ -16,6 +16,7 @@ import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.bottomsheetfragments.RandomBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.RandomBottomSheetFragment;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.post.FetchPost; import eu.toldi.infinityforlemmy.post.FetchPost;
@ -29,7 +30,7 @@ public class FetchRandomSubredditOrPostActivity extends BaseActivity {
RelativeLayout relativeLayout; RelativeLayout relativeLayout;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("default") @Named("default")
SharedPreferences mSharedPreferences; SharedPreferences mSharedPreferences;
@ -49,7 +50,7 @@ public class FetchRandomSubredditOrPostActivity extends BaseActivity {
int option = getIntent().getIntExtra(EXTRA_RANDOM_OPTION, RandomBottomSheetFragment.RANDOM_SUBREDDIT); int option = getIntent().getIntExtra(EXTRA_RANDOM_OPTION, RandomBottomSheetFragment.RANDOM_SUBREDDIT);
FetchPost.fetchRandomPost(mExecutor, new Handler(), mRetrofit, option == RandomBottomSheetFragment.RANDOM_NSFW_SUBREDDIT FetchPost.fetchRandomPost(mExecutor, new Handler(), mRetrofit.getRetrofit(), option == RandomBottomSheetFragment.RANDOM_NSFW_SUBREDDIT
|| option == RandomBottomSheetFragment.RANDOM_NSFW_POST, new FetchPost.FetchRandomPostListener() { || option == RandomBottomSheetFragment.RANDOM_NSFW_POST, new FetchPost.FetchRandomPostListener() {
@Override @Override
public void fetchRandomPostSuccess(String postId, String subredditName) { public void fetchRandomPostSuccess(String postId, String subredditName) {

View File

@ -275,7 +275,7 @@ public class FilteredPostsActivity extends BaseActivity implements SortTypeSelec
getSupportActionBar().setTitle(R.string.search); getSupportActionBar().setTitle(R.string.search);
break; break;
case PostPagingSource.TYPE_SUBREDDIT: case PostPagingSource.TYPE_SUBREDDIT:
if (name.equals("popular") || name.equals("all")) { if (name.equals("local") || name.equals("all")) {
getSupportActionBar().setTitle(name.substring(0, 1).toUpperCase() + name.substring(1)); getSupportActionBar().setTitle(name.substring(0, 1).toUpperCase() + name.substring(1));
} else { } else {
String subredditNamePrefixed = "r/" + name; String subredditNamePrefixed = "r/" + name;

View File

@ -46,6 +46,7 @@ import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface; import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.asynctasks.SwitchAccount; import eu.toldi.infinityforlemmy.asynctasks.SwitchAccount;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
@ -87,6 +88,11 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
ViewPager2 viewPager2; ViewPager2 viewPager2;
@BindView(R.id.fab_inbox_activity) @BindView(R.id.fab_inbox_activity)
FloatingActionButton fab; FloatingActionButton fab;
@Inject
@Named("base")
RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -233,7 +239,7 @@ public class InboxActivity extends BaseActivity implements ActivityToolbarInterf
private void getCurrentAccountAndFetchMessage(Bundle savedInstanceState) { private void getCurrentAccountAndFetchMessage(Bundle savedInstanceState) {
if (mNewAccountName != null) { if (mNewAccountName != null) {
if (mAccountName == null || !mAccountName.equals(mNewAccountName)) { if (mAccountName == null || !mAccountName.equals(mNewAccountName)) {
SwitchAccount.switchAccount(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, SwitchAccount.switchAccount(mRedditDataRoomDatabase,mRetrofit, mCurrentAccountSharedPreferences,
mExecutor, new Handler(), mNewAccountName, newAccount -> { mExecutor, new Handler(), mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName())); EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();

View File

@ -3,37 +3,26 @@ package eu.toldi.infinityforlemmy.activities;
import android.app.Activity; import android.app.Activity;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
import android.text.SpannableString;
import android.text.util.Linkify;
import android.util.Log; import android.util.Log;
import android.view.InflateException; import android.view.InflateException;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.widget.Button;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar; import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import com.google.android.material.appbar.AppBarLayout; import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.dialog.MaterialAlertDialogBuilder; import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import javax.inject.Inject; import javax.inject.Inject;
@ -41,16 +30,16 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import me.saket.bettermovementmethod.BetterLinkMovementMethod; import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.dto.AccountLoginDTO;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.FetchMyInfo; import eu.toldi.infinityforlemmy.FetchMyInfo;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.asynctasks.ParseAndInsertNewAccount; import eu.toldi.infinityforlemmy.asynctasks.ParseAndInsertNewAccount;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
import eu.toldi.infinityforlemmy.customviews.slidr.Slidr; import eu.toldi.infinityforlemmy.customviews.slidr.Slidr;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils; import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import eu.toldi.infinityforlemmy.utils.Utils; import eu.toldi.infinityforlemmy.utils.Utils;
import retrofit2.Call; import retrofit2.Call;
@ -71,13 +60,22 @@ public class LoginActivity extends BaseActivity {
Toolbar toolbar; Toolbar toolbar;
@BindView(R.id.two_fa_infO_text_view_login_activity) @BindView(R.id.two_fa_infO_text_view_login_activity)
TextView twoFAInfoTextView; TextView twoFAInfoTextView;
@BindView(R.id.webview_login_activity)
WebView webView; @BindView(R.id.instance_url_input)
@BindView(R.id.fab_login_activity) TextInputEditText instance_input;
FloatingActionButton fab; @BindView(R.id.username_input)
TextInputEditText username_input;
@BindView(R.id.user_password_input)
TextInputEditText password_input;
@BindView(R.id.user_2fa_token_input)
TextInputEditText token_2fa_input;
@BindView(R.id.user_login_button)
Button loginButton;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -131,80 +129,38 @@ public class LoginActivity extends BaseActivity {
isAgreeToUserAgreement = savedInstanceState.getBoolean(IS_AGREE_TO_USER_AGGREMENT_STATE); isAgreeToUserAgreement = savedInstanceState.getBoolean(IS_AGREE_TO_USER_AGGREMENT_STATE);
} }
fab.setOnClickListener(view -> { loginButton.setOnClickListener(view -> {
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme) String username = username_input.getText().toString();
.setTitle(R.string.have_trouble_login_title) String instance = instance_input.getText().toString();
.setMessage(R.string.have_trouble_login_message) AccountLoginDTO accountLoginDTO = new AccountLoginDTO(username,password_input.getText().toString(),token_2fa_input.getText().toString());
.setPositiveButton(R.string.yes, (dialogInterface, i) -> { mRetrofit.setBaseURL(instance);
enableDom = !enableDom; LemmyAPI api = mRetrofit.getRetrofit().create(LemmyAPI.class);
ActivityCompat.recreate(this); Call<String> accessTokenCall = api.userLogin(accountLoginDTO);
})
.setNegativeButton(R.string.no, null)
.show();
});
if (enableDom) {
twoFAInfoTextView.setVisibility(View.GONE);
}
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(enableDom);
Uri baseUri = Uri.parse(APIUtils.OAUTH_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter(APIUtils.CLIENT_ID_KEY, APIUtils.CLIENT_ID);
uriBuilder.appendQueryParameter(APIUtils.RESPONSE_TYPE_KEY, APIUtils.RESPONSE_TYPE);
uriBuilder.appendQueryParameter(APIUtils.STATE_KEY, APIUtils.STATE);
uriBuilder.appendQueryParameter(APIUtils.REDIRECT_URI_KEY, APIUtils.REDIRECT_URI);
uriBuilder.appendQueryParameter(APIUtils.DURATION_KEY, APIUtils.DURATION);
uriBuilder.appendQueryParameter(APIUtils.SCOPE_KEY, APIUtils.SCOPE);
String url = uriBuilder.toString();
CookieManager.getInstance().removeAllCookies(aBoolean -> {
});
webView.loadUrl(url);
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("&code=") || url.contains("?code=")) {
Uri uri = Uri.parse(url);
String state = uri.getQueryParameter("state");
if (state.equals(APIUtils.STATE)) {
authCode = uri.getQueryParameter("code");
Map<String, String> params = new HashMap<>();
params.put(APIUtils.GRANT_TYPE_KEY, "authorization_code");
params.put("code", authCode);
params.put("redirect_uri", APIUtils.REDIRECT_URI);
RedditAPI api = mRetrofit.create(RedditAPI.class);
Call<String> accessTokenCall = api.getAccessToken(APIUtils.getHttpBasicAuthHeader(), params);
accessTokenCall.enqueue(new Callback<String>() { accessTokenCall.enqueue(new Callback<String>() {
@Override @Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
try { Log.i("test", "WIN");
String accountResponse = response.body(); String accountResponse = response.body();
if (accountResponse == null) { if (accountResponse == null) {
//Handle error //Handle error
return; return;
} }
Log.i("test", accountResponse);
try {
JSONObject responseJSON = new JSONObject(accountResponse); JSONObject responseJSON = new JSONObject(accountResponse);
String accessToken = responseJSON.getString(APIUtils.ACCESS_TOKEN_KEY); String accessToken = responseJSON.getString("jwt");
String refreshToken = responseJSON.getString(APIUtils.REFRESH_TOKEN_KEY);
FetchMyInfo.fetchAccountInfo(mOauthRetrofit, mRedditDataRoomDatabase, FetchMyInfo.fetchAccountInfo(mRetrofit.getRetrofit(), mRedditDataRoomDatabase, username,
accessToken, new FetchMyInfo.FetchMyInfoListener() { accessToken, new FetchMyInfo.FetchMyInfoListener() {
@Override @Override
public void onFetchMyInfoSuccess(String name, String profileImageUrl, String bannerImageUrl, int karma) { public void onFetchMyInfoSuccess(String name,String display_name, String profileImageUrl, String bannerImageUrl) {
mCurrentAccountSharedPreferences.edit().putString(SharedPreferencesUtils.ACCESS_TOKEN, accessToken) mCurrentAccountSharedPreferences.edit().putString(SharedPreferencesUtils.ACCESS_TOKEN, accessToken)
.putString(SharedPreferencesUtils.ACCOUNT_NAME, name) .putString(SharedPreferencesUtils.ACCOUNT_NAME, name)
.putString(SharedPreferencesUtils.ACCOUNT_INSTANCE,instance)
.putString(SharedPreferencesUtils.ACCOUNT_IMAGE_URL, profileImageUrl).apply(); .putString(SharedPreferencesUtils.ACCOUNT_IMAGE_URL, profileImageUrl).apply();
ParseAndInsertNewAccount.parseAndInsertNewAccount(mExecutor, new Handler(), name, accessToken, refreshToken, profileImageUrl, bannerImageUrl, ParseAndInsertNewAccount.parseAndInsertNewAccount(mExecutor, new Handler(), name,display_name, accessToken, profileImageUrl, bannerImageUrl, authCode,instance, mRedditDataRoomDatabase.accountDao(),
karma, authCode, mRedditDataRoomDatabase.accountDao(),
() -> { () -> {
Intent resultIntent = new Intent(); Intent resultIntent = new Intent();
setResult(Activity.RESULT_OK, resultIntent); setResult(Activity.RESULT_OK, resultIntent);
@ -224,74 +180,27 @@ public class LoginActivity extends BaseActivity {
} }
}); });
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); throw new RuntimeException(e);
Toast.makeText(LoginActivity.this, R.string.parse_json_response_error, Toast.LENGTH_SHORT).show();
finish();
} }
} else {
Toast.makeText(LoginActivity.this, R.string.retrieve_token_error, Toast.LENGTH_SHORT).show(); return;
finish();
} }
String accountResponse = response.body();
if (accountResponse == null) {
//Handle error
return;
}
Log.i("test", accountResponse);
} }
@Override @Override
public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) { public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(LoginActivity.this, R.string.retrieve_token_error, Toast.LENGTH_SHORT).show(); Log.i("test", "LOSE");
t.printStackTrace();
finish();
} }
}); });
} else {
Toast.makeText(LoginActivity.this, R.string.something_went_wrong, Toast.LENGTH_SHORT).show();
finish();
}
} else if (url.contains("error=access_denied")) {
Toast.makeText(LoginActivity.this, R.string.access_denied, Toast.LENGTH_SHORT).show();
finish();
} else {
view.loadUrl(url);
}
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}); });
if (!isAgreeToUserAgreement) {
TextView messageTextView = new TextView(this);
int padding = (int) Utils.convertDpToPixel(24, this);
messageTextView.setPaddingRelative(padding, padding, padding, padding);
SpannableString message = new SpannableString(getString(R.string.user_agreement_message, "https://www.redditinc.com/policies/user-agreement-september-12-2021", "https://docile-alligator.github.io"));
Linkify.addLinks(message, Linkify.WEB_URLS);
messageTextView.setMovementMethod(BetterLinkMovementMethod.newInstance().setOnLinkClickListener(new BetterLinkMovementMethod.OnLinkClickListener() {
@Override
public boolean onClick(TextView textView, String url) {
Intent intent = new Intent(LoginActivity.this, LinkResolverActivity.class);
intent.setData(Uri.parse(url));
startActivity(intent);
return true;
}
}));
messageTextView.setLinkTextColor(getResources().getColor(R.color.colorAccent));
messageTextView.setText(message);
new MaterialAlertDialogBuilder(this, R.style.MaterialAlertDialogTheme)
.setTitle(getString(R.string.user_agreement_dialog_title))
.setView(messageTextView)
.setPositiveButton(R.string.agree, (dialogInterface, i) -> isAgreeToUserAgreement = true)
.setNegativeButton(R.string.do_not_agree, (dialogInterface, i) -> finish())
.setCancelable(false)
.show();
}
} }
@Override @Override
@ -318,7 +227,7 @@ public class LoginActivity extends BaseActivity {
twoFAInfoTextView.setTextColor(mCustomThemeWrapper.getPrimaryTextColor()); twoFAInfoTextView.setTextColor(mCustomThemeWrapper.getPrimaryTextColor());
Drawable infoDrawable = Utils.getTintedDrawable(this, R.drawable.ic_info_preference_24dp, mCustomThemeWrapper.getPrimaryIconColor()); Drawable infoDrawable = Utils.getTintedDrawable(this, R.drawable.ic_info_preference_24dp, mCustomThemeWrapper.getPrimaryIconColor());
twoFAInfoTextView.setCompoundDrawablesWithIntrinsicBounds(infoDrawable, null, null, null); twoFAInfoTextView.setCompoundDrawablesWithIntrinsicBounds(infoDrawable, null, null, null);
applyFABTheme(fab); applyButtonTheme(loginButton);
if (typeface != null) { if (typeface != null) {
twoFAInfoTextView.setTypeface(typeface); twoFAInfoTextView.setTypeface(typeface);
} }

View File

@ -78,6 +78,7 @@ import eu.toldi.infinityforlemmy.PullNotificationWorker;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface; import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.SortTypeSelectionCallback; import eu.toldi.infinityforlemmy.SortTypeSelectionCallback;
import eu.toldi.infinityforlemmy.account.AccountViewModel; import eu.toldi.infinityforlemmy.account.AccountViewModel;
@ -91,7 +92,6 @@ import eu.toldi.infinityforlemmy.bottomsheetfragments.FABMoreOptionsBottomSheetF
import eu.toldi.infinityforlemmy.bottomsheetfragments.PostLayoutBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.PostLayoutBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.PostTypeBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.PostTypeBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.RandomBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.RandomBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.RedditAPIInfoBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTimeBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTimeBottomSheetFragment;
import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTypeBottomSheetFragment; import eu.toldi.infinityforlemmy.bottomsheetfragments.SortTypeBottomSheetFragment;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
@ -170,7 +170,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
AccountViewModel accountViewModel; AccountViewModel accountViewModel;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -323,6 +323,10 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null); mAccessToken = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCESS_TOKEN, null);
mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null); mAccountName = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_NAME, null);
String instance = mCurrentAccountSharedPreferences.getString(SharedPreferencesUtils.ACCOUNT_INSTANCE, null);
if(instance != null) {
mRetrofit.setBaseURL(instance);
}
if (savedInstanceState != null) { if (savedInstanceState != null) {
mFetchUserInfoSuccess = savedInstanceState.getBoolean(FETCH_USER_INFO_STATE); mFetchUserInfoSuccess = savedInstanceState.getBoolean(FETCH_USER_INFO_STATE);
@ -336,11 +340,6 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
mNewAccountName = getIntent().getStringExtra(EXTRA_NEW_ACCOUNT_NAME); mNewAccountName = getIntent().getStringExtra(EXTRA_NEW_ACCOUNT_NAME);
} }
if (!mInternalSharedPreferences.getBoolean(SharedPreferencesUtils.DO_NOT_SHOW_REDDIT_API_INFO_AGAIN, false)) {
RedditAPIInfoBottomSheetFragment fragment = new RedditAPIInfoBottomSheetFragment();
fragment.setCancelable(false);
fragment.show(getSupportFragmentManager(), fragment.getTag());
}
initializeNotificationAndBindView(); initializeNotificationAndBindView();
} }
@ -385,7 +384,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
if (mNewAccountName != null) { if (mNewAccountName != null) {
if (mAccountName == null || !mAccountName.equals(mNewAccountName)) { if (mAccountName == null || !mAccountName.equals(mNewAccountName)) {
SwitchAccount.switchAccount(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, SwitchAccount.switchAccount(mRedditDataRoomDatabase,mRetrofit, mCurrentAccountSharedPreferences,
mExecutor, new Handler(), mNewAccountName, newAccount -> { mExecutor, new Handler(), mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName())); EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();
@ -453,6 +452,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_PROFILE: { case SharedPreferencesUtils.MAIN_ACTIVITY_BOTTOM_APP_BAR_OPTION_PROFILE: {
Intent intent = new Intent(this, ViewUserDetailActivity.class); Intent intent = new Intent(this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName); intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName);
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mAccountName);
startActivity(intent); startActivity(intent);
break; break;
} }
@ -786,6 +786,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
if (stringId == R.string.profile) { if (stringId == R.string.profile) {
intent = new Intent(MainActivity.this, ViewUserDetailActivity.class); intent = new Intent(MainActivity.this, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName); intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, mAccountName);
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, mAccountName);
} else if (stringId == R.string.subscriptions) { } else if (stringId == R.string.subscriptions) {
intent = new Intent(MainActivity.this, SubscribedThingListingActivity.class); intent = new Intent(MainActivity.this, SubscribedThingListingActivity.class);
} else if (stringId == R.string.multi_reddit) { } else if (stringId == R.string.multi_reddit) {
@ -867,7 +868,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
@Override @Override
public void onAccountClick(String accountName) { public void onAccountClick(String accountName) {
SwitchAccount.switchAccount(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, SwitchAccount.switchAccount(mRedditDataRoomDatabase,mRetrofit, mCurrentAccountSharedPreferences,
mExecutor, new Handler(), accountName, newAccount -> { mExecutor, new Handler(), accountName, newAccount -> {
Intent intent = new Intent(MainActivity.this, MainActivity.class); Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent); startActivity(intent);
@ -901,7 +902,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
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.home)));
break; break;
case 1: case 1:
Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_TITLE, getString(R.string.popular))); Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_TITLE, getString(R.string.local)));
break; break;
case 2: case 2:
Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_3_TITLE, getString(R.string.all))); Utils.setTitleWithCustomFontToTab(typeface, tab, mMainActivityTabsSharedPreferences.getString((mAccountName == null ? "" : mAccountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_3_TITLE, getString(R.string.all)));
@ -977,20 +978,19 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
sectionsPagerAdapter.setSubscribedSubreddits(subscribedSubredditData); sectionsPagerAdapter.setSubscribedSubreddits(subscribedSubredditData);
} }
}); });
subscribedSubredditViewModel.getAllFavoriteSubscribedSubreddits().observe(this, subscribedSubredditData -> { /*subscribedSubredditViewModel.getAllFavoriteSubscribedSubreddits().observe(this, subscribedSubredditData -> {
adapter.setFavoriteSubscribedSubreddits(subscribedSubredditData); adapter.setFavoriteSubscribedSubreddits(subscribedSubredditData);
if (mShowFavoriteSubscribedSubreddits && sectionsPagerAdapter != null) { if (mShowFavoriteSubscribedSubreddits && sectionsPagerAdapter != null) {
sectionsPagerAdapter.setFavoriteSubscribedSubreddits(subscribedSubredditData); sectionsPagerAdapter.setFavoriteSubscribedSubreddits(subscribedSubredditData);
} }
}); });*/
accountViewModel = new ViewModelProvider(this, accountViewModel = new ViewModelProvider(this,
new AccountViewModel.Factory(mRedditDataRoomDatabase)).get(AccountViewModel.class); new AccountViewModel.Factory(mRedditDataRoomDatabase)).get(AccountViewModel.class);
accountViewModel.getAccountsExceptCurrentAccountLiveData().observe(this, adapter::changeAccountsDataset); accountViewModel.getAccountsExceptCurrentAccountLiveData().observe(this, adapter::changeAccountsDataset);
accountViewModel.getCurrentAccountLiveData().observe(this, account -> { accountViewModel.getCurrentAccountLiveData().observe(this, account -> {
if (account != null) { if (account != null) {
adapter.updateAccountInfo(account.getProfileImageUrl(), account.getBannerImageUrl(), adapter.updateAccountInfo(account.getProfileImageUrl(), account.getBannerImageUrl());
account.getKarma());
} }
}); });
@ -1015,7 +1015,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
private void loadSubscriptions() { private void loadSubscriptions() {
if (mAccessToken != null && !mFetchSubscriptionsSuccess) { if (mAccessToken != null && !mFetchSubscriptionsSuccess) {
FetchSubscribedThing.fetchSubscribedThing(mOauthRetrofit, mAccessToken, mAccountName, null, FetchSubscribedThing.fetchSubscribedThing(mRetrofit.getRetrofit(), mAccessToken, mAccountName, null,
new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>(),
new ArrayList<>(), new ArrayList<>(),
new FetchSubscribedThing.FetchSubscribedThingListener() { new FetchSubscribedThing.FetchSubscribedThingListener() {
@ -1653,7 +1653,7 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
} else if (postType == SharedPreferencesUtils.MAIN_PAGE_TAB_POST_TYPE_ALL) { } else if (postType == SharedPreferencesUtils.MAIN_PAGE_TAB_POST_TYPE_ALL) {
PostFragment fragment = new PostFragment(); PostFragment fragment = new PostFragment();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostPagingSource.TYPE_SUBREDDIT); bundle.putInt(PostFragment.EXTRA_POST_TYPE, mAccessToken == null ? PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE : PostPagingSource.TYPE_FRONT_PAGE);
bundle.putString(PostFragment.EXTRA_NAME, "all"); bundle.putString(PostFragment.EXTRA_NAME, "all");
bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(PostFragment.EXTRA_ACCOUNT_NAME, mAccountName); bundle.putString(PostFragment.EXTRA_ACCOUNT_NAME, mAccountName);
@ -1717,8 +1717,8 @@ public class MainActivity extends BaseActivity implements SortTypeSelectionCallb
} else { } else {
PostFragment fragment = new PostFragment(); PostFragment fragment = new PostFragment();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostPagingSource.TYPE_SUBREDDIT); bundle.putInt(PostFragment.EXTRA_POST_TYPE, mAccessToken == null ? PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE : PostPagingSource.TYPE_FRONT_PAGE);
bundle.putString(PostFragment.EXTRA_NAME, "popular"); bundle.putString(PostFragment.EXTRA_NAME, "local");
bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(PostFragment.EXTRA_ACCOUNT_NAME, mAccountName); bundle.putString(PostFragment.EXTRA_ACCOUNT_NAME, mAccountName);
fragment.setArguments(bundle); fragment.setArguments(bundle);

View File

@ -143,12 +143,6 @@ public class PostFilterPreferenceActivity extends BaseActivity {
case 1: case 1:
intent.putExtra(CustomizePostFilterActivity.EXTRA_EXCLUDE_USER, post.getAuthor()); intent.putExtra(CustomizePostFilterActivity.EXTRA_EXCLUDE_USER, post.getAuthor());
break; break;
case 2:
intent.putExtra(CustomizePostFilterActivity.EXTRA_EXCLUDE_FLAIR, post.getFlair());
break;
case 3:
intent.putExtra(CustomizePostFilterActivity.EXTRA_CONTAIN_FLAIR, post.getFlair());
break;
case 4: case 4:
intent.putExtra(CustomizePostFilterActivity.EXTRA_EXCLUDE_DOMAIN, post.getUrl()); intent.putExtra(CustomizePostFilterActivity.EXTRA_EXCLUDE_DOMAIN, post.getUrl());
break; break;

View File

@ -58,6 +58,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.Flair; import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
@ -142,7 +143,7 @@ public class PostGalleryActivity extends BaseActivity implements FlairBottomShee
RecyclerView imagesRecyclerView; RecyclerView imagesRecyclerView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -530,7 +531,7 @@ public class PostGalleryActivity extends BaseActivity implements FlairBottomShee
} }
private void loadSubredditIcon() { private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, mAccessToken, mOauthRetrofit, mRetrofit, iconImageUrl -> { LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl; iconUrl = iconImageUrl;
displaySubredditIcon(); displaySubredditIcon();
loadSubredditIconSuccessful = true; loadSubredditIconSuccessful = true;

View File

@ -50,6 +50,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.Flair; import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
@ -137,7 +138,7 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
ImageView imageView; ImageView imageView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -492,7 +493,7 @@ public class PostImageActivity extends BaseActivity implements FlairBottomSheetF
} }
private void loadSubredditIcon() { private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, mAccessToken, mOauthRetrofit, mRetrofit, iconImageUrl -> { LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl; iconUrl = iconImageUrl;
displaySubredditIcon(); displaySubredditIcon();
loadSubredditIconSuccessful = true; loadSubredditIconSuccessful = true;

View File

@ -42,6 +42,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.Flair; import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
@ -126,7 +127,7 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
EditText linkEditText; EditText linkEditText;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -355,7 +356,7 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
if (!URLUtil.isHttpsUrl(url) && !URLUtil.isHttpUrl(url)) { if (!URLUtil.isHttpsUrl(url) && !URLUtil.isHttpUrl(url)) {
url = "https://" + url; url = "https://" + url;
} }
mRetrofit.newBuilder() mRetrofit.getRetrofit().newBuilder()
.baseUrl("http://localhost/") .baseUrl("http://localhost/")
.addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(ScalarsConverterFactory.create())
.build().create(TitleSuggestion.class).getHtml(url).enqueue(new Callback<String>() { .build().create(TitleSuggestion.class).getHtml(url).enqueue(new Callback<String>() {
@ -465,7 +466,7 @@ public class PostLinkActivity extends BaseActivity implements FlairBottomSheetFr
private void loadSubredditIcon() { private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName,
mAccessToken, mOauthRetrofit, mRetrofit, iconImageUrl -> { mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl; iconUrl = iconImageUrl;
displaySubredditIcon(); displaySubredditIcon();
loadSubredditIconSuccessful = true; loadSubredditIconSuccessful = true;

View File

@ -50,6 +50,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.Flair; import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
@ -155,7 +156,7 @@ public class PostPollActivity extends BaseActivity implements FlairBottomSheetFr
TextInputEditText option6TextInputEditText; TextInputEditText option6TextInputEditText;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -528,7 +529,7 @@ public class PostPollActivity extends BaseActivity implements FlairBottomSheetFr
} }
private void loadSubredditIcon() { private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, mAccessToken, mOauthRetrofit, mRetrofit, iconImageUrl -> { LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl; iconUrl = iconImageUrl;
displaySubredditIcon(); displaySubredditIcon();
loadSubredditIconSuccessful = true; loadSubredditIconSuccessful = true;

View File

@ -51,6 +51,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.Flair; import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
@ -140,7 +141,7 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
RecyclerView markdownBottomBarRecyclerView; RecyclerView markdownBottomBarRecyclerView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -484,7 +485,7 @@ public class PostTextActivity extends BaseActivity implements FlairBottomSheetFr
private void loadSubredditIcon() { private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName,
mAccessToken, mOauthRetrofit, mRetrofit, iconImageUrl -> { mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl; iconUrl = iconImageUrl;
displaySubredditIcon(); displaySubredditIcon();
loadSubredditIconSuccessful = true; loadSubredditIconSuccessful = true;

View File

@ -54,6 +54,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.Flair; import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
@ -140,7 +141,7 @@ public class PostVideoActivity extends BaseActivity implements FlairBottomSheetF
PlayerView videoPlayerView; PlayerView videoPlayerView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -512,7 +513,7 @@ public class PostVideoActivity extends BaseActivity implements FlairBottomSheetF
private void loadSubredditIcon() { private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName,
mAccessToken, mOauthRetrofit, mRetrofit, iconImageUrl -> { mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl; iconUrl = iconImageUrl;
displaySubredditIcon(); displaySubredditIcon();
loadSubredditIconSuccessful = true; loadSubredditIconSuccessful = true;

View File

@ -30,6 +30,7 @@ import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.ReportReason; import eu.toldi.infinityforlemmy.ReportReason;
import eu.toldi.infinityforlemmy.ReportThing; import eu.toldi.infinityforlemmy.ReportThing;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.Rule; import eu.toldi.infinityforlemmy.Rule;
import eu.toldi.infinityforlemmy.adapters.ReportReasonRecyclerViewAdapter; import eu.toldi.infinityforlemmy.adapters.ReportReasonRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
@ -57,7 +58,7 @@ public class ReportActivity extends BaseActivity {
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("default") @Named("default")
SharedPreferences mSharedPreferences; SharedPreferences mSharedPreferences;
@ -119,7 +120,7 @@ public class ReportActivity extends BaseActivity {
recyclerView.setAdapter(mAdapter); recyclerView.setAdapter(mAdapter);
if (rulesReasons == null) { if (rulesReasons == null) {
FetchRules.fetchRules(mExecutor, new Handler(), mAccessToken == null ? mRetrofit : mOauthRetrofit, mAccessToken, mSubredditName, new FetchRules.FetchRulesListener() { FetchRules.fetchRules(mExecutor, new Handler(), mAccessToken == null ? mRetrofit.getRetrofit() : mOauthRetrofit, mAccessToken, mSubredditName, new FetchRules.FetchRulesListener() {
@Override @Override
public void success(ArrayList<Rule> rules) { public void success(ArrayList<Rule> rules) {
mAdapter.setRules(ReportReason.convertRulesToReasons(rules)); mAdapter.setRules(ReportReason.convertRulesToReasons(rules));

View File

@ -34,6 +34,7 @@ import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.FetchRules; import eu.toldi.infinityforlemmy.FetchRules;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.Rule; import eu.toldi.infinityforlemmy.Rule;
import eu.toldi.infinityforlemmy.adapters.RulesRecyclerViewAdapter; import eu.toldi.infinityforlemmy.adapters.RulesRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
@ -63,7 +64,7 @@ public class RulesActivity extends BaseActivity {
TextView errorTextView; TextView errorTextView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -134,7 +135,7 @@ public class RulesActivity extends BaseActivity {
mAdapter = new RulesRecyclerViewAdapter(this, mCustomThemeWrapper, sliderPanel); mAdapter = new RulesRecyclerViewAdapter(this, mCustomThemeWrapper, sliderPanel);
recyclerView.setAdapter(mAdapter); recyclerView.setAdapter(mAdapter);
FetchRules.fetchRules(mExecutor, new Handler(), mAccessToken == null ? mRetrofit : mOauthRetrofit, mAccessToken, mSubredditName, new FetchRules.FetchRulesListener() { FetchRules.fetchRules(mExecutor, new Handler(), mAccessToken == null ? mRetrofit.getRetrofit() : mOauthRetrofit, mAccessToken, mSubredditName, new FetchRules.FetchRulesListener() {
@Override @Override
public void success(ArrayList<Rule> rules) { public void success(ArrayList<Rule> rules) {
progressBar.setVisibility(View.GONE); progressBar.setVisibility(View.GONE);
@ -183,7 +184,7 @@ public class RulesActivity extends BaseActivity {
errorTextView.setOnClickListener(view -> { errorTextView.setOnClickListener(view -> {
progressBar.setVisibility(View.VISIBLE); progressBar.setVisibility(View.VISIBLE);
errorTextView.setVisibility(View.GONE); errorTextView.setVisibility(View.GONE);
FetchRules.fetchRules(mExecutor, new Handler(), mAccessToken == null ? mRetrofit : mOauthRetrofit, mAccessToken, mSubredditName, new FetchRules.FetchRulesListener() { FetchRules.fetchRules(mExecutor, new Handler(), mAccessToken == null ? mRetrofit.getRetrofit() : mOauthRetrofit, mAccessToken, mSubredditName, new FetchRules.FetchRulesListener() {
@Override @Override
public void success(ArrayList<Rule> rules) { public void success(ArrayList<Rule> rules) {
progressBar.setVisibility(View.GONE); progressBar.setVisibility(View.GONE);

View File

@ -50,6 +50,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.Flair; import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
@ -137,7 +138,7 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
ImageView playButton; ImageView playButton;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -273,11 +274,6 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
.apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0))) .apply(RequestOptions.bitmapTransform(new RoundedCornersTransformation(72, 0)))
.into(iconGifImageView); .into(iconGifImageView);
if (post.isSpoiler()) {
spoilerTextView.setBackgroundColor(spoilerBackgroundColor);
spoilerTextView.setBorderColor(spoilerBackgroundColor);
spoilerTextView.setTextColor(spoilerTextColor);
}
if (post.isNSFW()) { if (post.isNSFW()) {
nsfwTextView.setBackgroundColor(nsfwBackgroundColor); nsfwTextView.setBackgroundColor(nsfwBackgroundColor);
nsfwTextView.setBorderColor(nsfwBackgroundColor); nsfwTextView.setBorderColor(nsfwBackgroundColor);
@ -499,7 +495,7 @@ public class SubmitCrosspostActivity extends BaseActivity implements FlairBottom
private void loadSubredditIcon() { private void loadSubredditIcon() {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName, LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditName,
mAccessToken, mOauthRetrofit, mRetrofit, iconImageUrl -> { mAccessToken, mOauthRetrofit, mRetrofit.getRetrofit(), iconImageUrl -> {
iconUrl = iconImageUrl; iconUrl = iconImageUrl;
displaySubredditIcon(); displaySubredditIcon();
loadSubredditIconSuccessful = true; loadSubredditIconSuccessful = true;

View File

@ -38,6 +38,7 @@ import eu.toldi.infinityforlemmy.FetchSubscribedThing;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.account.Account; import eu.toldi.infinityforlemmy.account.Account;
import eu.toldi.infinityforlemmy.asynctasks.InsertSubscribedThings; import eu.toldi.infinityforlemmy.asynctasks.InsertSubscribedThings;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
@ -74,7 +75,7 @@ public class SubredditSelectionActivity extends BaseActivity implements Activity
Toolbar toolbar; Toolbar toolbar;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -141,7 +142,7 @@ public class SubredditSelectionActivity extends BaseActivity implements Activity
mAccountName = specifiedAccount.getAccountName(); mAccountName = specifiedAccount.getAccountName();
mAccountProfileImageUrl = specifiedAccount.getProfileImageUrl(); mAccountProfileImageUrl = specifiedAccount.getProfileImageUrl();
mOauthRetrofit = mOauthRetrofit.newBuilder().client(new OkHttpClient.Builder().authenticator(new AnyAccountAccessTokenAuthenticator(mRetrofit, mRedditDataRoomDatabase, specifiedAccount, mCurrentAccountSharedPreferences)) mOauthRetrofit = mOauthRetrofit.newBuilder().client(new OkHttpClient.Builder().authenticator(new AnyAccountAccessTokenAuthenticator(mRetrofit.getRetrofit(), mRedditDataRoomDatabase, specifiedAccount, mCurrentAccountSharedPreferences))
.connectTimeout(30, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS)
@ -211,7 +212,7 @@ public class SubredditSelectionActivity extends BaseActivity implements Activity
private void loadSubscriptions() { private void loadSubscriptions() {
if (!mInsertSuccess) { if (!mInsertSuccess) {
FetchSubscribedThing.fetchSubscribedThing(mOauthRetrofit, mAccessToken, mAccountName, null, FetchSubscribedThing.fetchSubscribedThing(mRetrofit.getRetrofit(), mAccessToken, mAccountName, null,
new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>(),
new ArrayList<>(), new ArrayList<>(),
new FetchSubscribedThing.FetchSubscribedThingListener() { new FetchSubscribedThing.FetchSubscribedThingListener() {

View File

@ -50,6 +50,7 @@ import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.asynctasks.DeleteMultiredditInDatabase; import eu.toldi.infinityforlemmy.asynctasks.DeleteMultiredditInDatabase;
import eu.toldi.infinityforlemmy.asynctasks.InsertMultireddit; import eu.toldi.infinityforlemmy.asynctasks.InsertMultireddit;
import eu.toldi.infinityforlemmy.asynctasks.InsertSubscribedThings; import eu.toldi.infinityforlemmy.asynctasks.InsertSubscribedThings;
@ -99,6 +100,10 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@Inject
@Named("no_oauth")
RetrofitHolder mRetrofit;
@Inject @Inject
RedditDataRoomDatabase mRedditDataRoomDatabase; RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject @Inject
@ -317,7 +322,7 @@ public class SubscribedThingListingActivity extends BaseActivity implements Acti
public void loadSubscriptions(boolean forceLoad) { public void loadSubscriptions(boolean forceLoad) {
if (mAccessToken != null && !(!forceLoad && mInsertSuccess)) { if (mAccessToken != null && !(!forceLoad && mInsertSuccess)) {
FetchSubscribedThing.fetchSubscribedThing(mOauthRetrofit, mAccessToken, mAccountName, null, FetchSubscribedThing.fetchSubscribedThing(mRetrofit.getRetrofit(), mAccessToken, mAccountName, null,
new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>(),
new ArrayList<>(), new ArrayList<>(),
new FetchSubscribedThing.FetchSubscribedThingListener() { new FetchSubscribedThing.FetchSubscribedThingListener() {

View File

@ -42,6 +42,7 @@ import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.TrendingSearch; import eu.toldi.infinityforlemmy.TrendingSearch;
import eu.toldi.infinityforlemmy.adapters.TrendingSearchRecyclerViewAdapter; import eu.toldi.infinityforlemmy.adapters.TrendingSearchRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.RedditAPI;
@ -83,7 +84,7 @@ public class TrendingActivity extends BaseActivity {
TextView errorTextView; TextView errorTextView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -207,7 +208,7 @@ public class TrendingActivity extends BaseActivity {
Handler handler = new Handler(); Handler handler = new Handler();
Call<String> trendingCall; Call<String> trendingCall;
if (mAccessToken == null) { if (mAccessToken == null) {
trendingCall = mRetrofit.create(RedditAPI.class).getTrendingSearches(); trendingCall = mRetrofit.getRetrofit().create(RedditAPI.class).getTrendingSearches();
} else { } else {
trendingCall = mOauthRetrofit.create(RedditAPI.class).getTrendingSearchesOauth(APIUtils.getOAuthHeader(mAccessToken)); trendingCall = mOauthRetrofit.create(RedditAPI.class).getTrendingSearchesOauth(APIUtils.getOAuthHeader(mAccessToken));
} }

View File

@ -46,6 +46,7 @@ import eu.toldi.infinityforlemmy.MarkPostAsReadInterface;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface; import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.SortTypeSelectionCallback; import eu.toldi.infinityforlemmy.SortTypeSelectionCallback;
import eu.toldi.infinityforlemmy.adapters.SubredditAutocompleteRecyclerViewAdapter; import eu.toldi.infinityforlemmy.adapters.SubredditAutocompleteRecyclerViewAdapter;
@ -99,7 +100,7 @@ public class ViewMultiRedditDetailActivity extends BaseActivity implements SortT
Toolbar toolbar; Toolbar toolbar;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;

View File

@ -62,6 +62,7 @@ import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.LoadingMorePostsStatus; import eu.toldi.infinityforlemmy.LoadingMorePostsStatus;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SaveThing; import eu.toldi.infinityforlemmy.SaveThing;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.SortTypeSelectionCallback; import eu.toldi.infinityforlemmy.SortTypeSelectionCallback;
@ -128,7 +129,7 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
ImageView closeSearchPanelImageView; ImageView closeSearchPanelImageView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -351,7 +352,7 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
private void checkNewAccountAndBindView(Bundle savedInstanceState) { private void checkNewAccountAndBindView(Bundle savedInstanceState) {
if (mNewAccountName != null) { if (mNewAccountName != null) {
if (mAccountName == null || !mAccountName.equals(mNewAccountName)) { if (mAccountName == null || !mAccountName.equals(mNewAccountName)) {
SwitchAccount.switchAccount(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, SwitchAccount.switchAccount(mRedditDataRoomDatabase,mRetrofit, mCurrentAccountSharedPreferences,
mExecutor, new Handler(), mNewAccountName, newAccount -> { mExecutor, new Handler(), mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName())); EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();
@ -528,7 +529,7 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
if (postType != HistoryPostPagingSource.TYPE_READ_POSTS) { if (postType != HistoryPostPagingSource.TYPE_READ_POSTS) {
mExecutor.execute(() -> { mExecutor.execute(() -> {
RedditAPI api = (mAccessToken == null ? mRetrofit : mOauthRetrofit).create(RedditAPI.class); RedditAPI api = (mAccessToken == null ? mRetrofit.getRetrofit() : mOauthRetrofit).create(RedditAPI.class);
Call<String> call; Call<String> call;
String afterKey = posts.isEmpty() ? null : posts.get(posts.size() - 1).getFullName(); String afterKey = posts.isEmpty() ? null : posts.get(posts.size() - 1).getFullName();
switch (postType) { switch (postType) {
@ -649,7 +650,7 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
mExecutor.execute((Runnable) () -> { mExecutor.execute((Runnable) () -> {
long lastItem = 0; long lastItem = 0;
if (!posts.isEmpty()) { if (!posts.isEmpty()) {
lastItem = mRedditDataRoomDatabase.readPostDao().getReadPost(posts.get(posts.size() - 1).getId()).getTime(); lastItem = mRedditDataRoomDatabase.readPostDao().getReadPost(String.valueOf(posts.get(posts.size() - 1).getId())).getTime();
} }
List<ReadPost> readPosts = mRedditDataRoomDatabase.readPostDao().getAllReadPosts(mAccountName, lastItem); List<ReadPost> readPosts = mRedditDataRoomDatabase.readPostDao().getAllReadPosts(mAccountName, lastItem);
StringBuilder ids = new StringBuilder(); StringBuilder ids = new StringBuilder();
@ -664,7 +665,7 @@ public class ViewPostDetailActivity extends BaseActivity implements SortTypeSele
if (mAccessToken != null && !mAccessToken.isEmpty()) { if (mAccessToken != null && !mAccessToken.isEmpty()) {
historyPosts = mOauthRetrofit.create(RedditAPI.class).getInfoOauth(ids.toString(), APIUtils.getOAuthHeader(mAccessToken)); historyPosts = mOauthRetrofit.create(RedditAPI.class).getInfoOauth(ids.toString(), APIUtils.getOAuthHeader(mAccessToken));
} else { } else {
historyPosts = mRetrofit.create(RedditAPI.class).getInfo(ids.toString()); historyPosts = mRetrofit.getRetrofit().create(RedditAPI.class).getInfo(ids.toString());
} }
try { try {

View File

@ -38,6 +38,7 @@ import eu.toldi.infinityforlemmy.ActivityToolbarInterface;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.adapters.PrivateMessagesDetailRecyclerViewAdapter; import eu.toldi.infinityforlemmy.adapters.PrivateMessagesDetailRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.asynctasks.LoadUserData; import eu.toldi.infinityforlemmy.asynctasks.LoadUserData;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
@ -77,7 +78,7 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
RedditDataRoomDatabase mRedditDataRoomDatabase; RedditDataRoomDatabase mRedditDataRoomDatabase;
@Inject @Inject
@ -248,7 +249,7 @@ public class ViewPrivateMessagesActivity extends BaseActivity implements Activit
mProvideUserAvatarCallbacks.add(provideUserAvatarCallback); mProvideUserAvatarCallbacks.add(provideUserAvatarCallback);
if (!isLoadingUserAvatar) { if (!isLoadingUserAvatar) {
LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase,
username, mRetrofit, iconImageUrl -> { username, mRetrofit.getRetrofit(), iconImageUrl -> {
isLoadingUserAvatar = false; isLoadingUserAvatar = false;
mUserAvatar = iconImageUrl == null ? "" : iconImageUrl; mUserAvatar = iconImageUrl == null ? "" : iconImageUrl;
for (ProvideUserAvatarCallback provideUserAvatarCallbackInArrayList : mProvideUserAvatarCallbacks) { for (ProvideUserAvatarCallback provideUserAvatarCallbackInArrayList : mProvideUserAvatarCallbacks) {

View File

@ -49,7 +49,6 @@ import com.google.android.material.textfield.TextInputEditText;
import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.Subscribe;
import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Locale; import java.util.Locale;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
@ -59,6 +58,8 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import io.noties.markwon.AbstractMarkwonPlugin; import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon; import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration; import io.noties.markwon.MarkwonConfiguration;
@ -126,6 +127,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
public static final String EXTRA_MESSAGE_FULLNAME = "ENF"; public static final String EXTRA_MESSAGE_FULLNAME = "ENF";
public static final String EXTRA_NEW_ACCOUNT_NAME = "ENAN"; public static final String EXTRA_NEW_ACCOUNT_NAME = "ENAN";
public static final String EXTRA_VIEW_SIDEBAR = "EVSB"; public static final String EXTRA_VIEW_SIDEBAR = "EVSB";
public static final String EXTRA_COMMUNITY_FULL_NAME_KEY = "ECFNK";
private static final String FETCH_SUBREDDIT_INFO_STATE = "FSIS"; private static final String FETCH_SUBREDDIT_INFO_STATE = "FSIS";
private static final String CURRENT_ONLINE_SUBSCRIBERS_STATE = "COSS"; private static final String CURRENT_ONLINE_SUBSCRIBERS_STATE = "COSS";
@ -155,6 +157,9 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
Chip subscribeSubredditChip; Chip subscribeSubredditChip;
@BindView(R.id.subreddit_name_text_view_view_subreddit_detail_activity) @BindView(R.id.subreddit_name_text_view_view_subreddit_detail_activity)
TextView subredditNameTextView; TextView subredditNameTextView;
@BindView(R.id.community_fulname_text_view_view_subreddit_detail_activity)
TextView communityFullNameTextView;
@BindView(R.id.subscriber_count_text_view_view_subreddit_detail_activity) @BindView(R.id.subscriber_count_text_view_view_subreddit_detail_activity)
TextView nSubscribersTextView; TextView nSubscribersTextView;
@BindView(R.id.online_subscriber_count_text_view_view_subreddit_detail_activity) @BindView(R.id.online_subscriber_count_text_view_view_subreddit_detail_activity)
@ -167,7 +172,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
TextView descriptionTextView; TextView descriptionTextView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -203,6 +208,8 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
private String mAccountName; private String mAccountName;
private String subredditName; private String subredditName;
private String description; private String description;
private String qualifiedName;
private boolean mFetchSubredditInfoSuccess = false; private boolean mFetchSubredditInfoSuccess = false;
private int mNCurrentOnlineSubscribers = 0; private int mNCurrentOnlineSubscribers = 0;
private boolean isNsfwSubreddit = false; private boolean isNsfwSubreddit = false;
@ -331,6 +338,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
boolean hideSubredditDescription = mSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_SUBREDDIT_DESCRIPTION, false); boolean hideSubredditDescription = mSharedPreferences.getBoolean(SharedPreferencesUtils.HIDE_SUBREDDIT_DESCRIPTION, false);
subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME_KEY); subredditName = getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME_KEY);
qualifiedName = getIntent().getStringExtra(EXTRA_COMMUNITY_FULL_NAME_KEY);
fragmentManager = getSupportFragmentManager(); fragmentManager = getSupportFragmentManager();
@ -355,10 +363,11 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
fetchSubredditData(); fetchSubredditData();
String title = "r/" + subredditName;
subredditNameTextView.setText(title);
toolbar.setTitle(title); subredditNameTextView.setText(subredditName);
communityFullNameTextView.setText(qualifiedName);
toolbar.setTitle(subredditName);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
setToolbarGoToTop(toolbar); setToolbarGoToTop(toolbar);
@ -438,16 +447,18 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
}); });
} }
String subredditFullName = "r/" + subredditData.getName(); String subredditFullName = subredditData.getTitle();
if (!title.equals(subredditFullName)) { if (!subredditName.equals(subredditFullName)) {
getSupportActionBar().setTitle(subredditFullName); getSupportActionBar().setTitle(subredditFullName);
} }
subredditNameTextView.setText(subredditFullName); subredditNameTextView.setText(subredditFullName);
qualifiedName = LemmyUtils.actorID2FullName(subredditData.getActorId());
communityFullNameTextView.setText(qualifiedName);
String nSubscribers = getString(R.string.subscribers_number_detail, subredditData.getNSubscribers()); String nSubscribers = getString(R.string.subscribers_number_detail, subredditData.getNSubscribers());
nSubscribersTextView.setText(nSubscribers); nSubscribersTextView.setText(nSubscribers);
creationTimeTextView.setText(new SimpleDateFormat("MMM d, yyyy", creationTimeTextView.setText(subredditData.getCreatedUTC());
locale).format(subredditData.getCreatedUTC()));
description = subredditData.getDescription(); description = subredditData.getDescription();
if (hideSubredditDescription || description.equals("")) { if (hideSubredditDescription || description.equals("")) {
descriptionTextView.setVisibility(View.GONE); descriptionTextView.setVisibility(View.GONE);
} else { } else {
@ -537,7 +548,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
private void checkNewAccountAndBindView() { private void checkNewAccountAndBindView() {
if (mNewAccountName != null) { if (mNewAccountName != null) {
if (mAccountName == null || !mAccountName.equals(mNewAccountName)) { if (mAccountName == null || !mAccountName.equals(mNewAccountName)) {
SwitchAccount.switchAccount(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, SwitchAccount.switchAccount(mRedditDataRoomDatabase,mRetrofit, mCurrentAccountSharedPreferences,
mExecutor, new Handler(), mNewAccountName, newAccount -> { mExecutor, new Handler(), mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName())); EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();
@ -560,9 +571,10 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
private void fetchSubredditData() { private void fetchSubredditData() {
if (!mFetchSubredditInfoSuccess) { if (!mFetchSubredditInfoSuccess) {
FetchSubredditData.fetchSubredditData(mOauthRetrofit, mRetrofit, subredditName, mAccessToken, new FetchSubredditData.FetchSubredditDataListener() { FetchSubredditData.fetchSubredditData(mOauthRetrofit, mRetrofit.getRetrofit(), qualifiedName, mAccessToken, new FetchSubredditData.FetchSubredditDataListener() {
@Override @Override
public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) {
qualifiedName = LemmyUtils.actorID2FullName(subredditData.getActorId());
mNCurrentOnlineSubscribers = nCurrentOnlineSubscribers; mNCurrentOnlineSubscribers = nCurrentOnlineSubscribers;
nOnlineSubscribersTextView.setText(getString(R.string.online_subscribers_number_detail, nCurrentOnlineSubscribers)); nOnlineSubscribersTextView.setText(getString(R.string.online_subscribers_number_detail, nCurrentOnlineSubscribers));
InsertSubredditData.insertSubredditData(mExecutor, new Handler(), mRedditDataRoomDatabase, InsertSubredditData.insertSubredditData(mExecutor, new Handler(), mRedditDataRoomDatabase,
@ -945,7 +957,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
subscriptionReady = false; subscriptionReady = false;
if (getResources().getString(R.string.subscribe).contentEquals(subscribeSubredditChip.getText())) { if (getResources().getString(R.string.subscribe).contentEquals(subscribeSubredditChip.getText())) {
SubredditSubscription.anonymousSubscribeToSubreddit(mExecutor, new Handler(), SubredditSubscription.anonymousSubscribeToSubreddit(mExecutor, new Handler(),
mRetrofit, mRedditDataRoomDatabase, subredditName, mRetrofit.getRetrofit(), mRedditDataRoomDatabase, subredditName,
new SubredditSubscription.SubredditSubscriptionListener() { new SubredditSubscription.SubredditSubscriptionListener() {
@Override @Override
public void onSubredditSubscriptionSuccess() { public void onSubredditSubscriptionSuccess() {
@ -986,7 +998,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
subscriptionReady = false; subscriptionReady = false;
if (getResources().getString(R.string.subscribe).contentEquals(subscribeSubredditChip.getText())) { if (getResources().getString(R.string.subscribe).contentEquals(subscribeSubredditChip.getText())) {
SubredditSubscription.subscribeToSubreddit(mExecutor, new Handler(), mOauthRetrofit, SubredditSubscription.subscribeToSubreddit(mExecutor, new Handler(), mOauthRetrofit,
mRetrofit, mAccessToken, subredditName, mAccountName, mRedditDataRoomDatabase, mRetrofit.getRetrofit(), mAccessToken, subredditName, mAccountName, mRedditDataRoomDatabase,
new SubredditSubscription.SubredditSubscriptionListener() { new SubredditSubscription.SubredditSubscriptionListener() {
@Override @Override
public void onSubredditSubscriptionSuccess() { public void onSubredditSubscriptionSuccess() {
@ -1144,7 +1156,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
} else if (itemId == R.id.action_share_view_subreddit_detail_activity) { } else if (itemId == R.id.action_share_view_subreddit_detail_activity) {
Intent shareIntent = new Intent(Intent.ACTION_SEND); Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain"); shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "https://www.reddit.com/r/" + subredditName); shareIntent.putExtra(Intent.EXTRA_TEXT, qualifiedName);
if (shareIntent.resolveActivity(getPackageManager()) != null) { if (shareIntent.resolveActivity(getPackageManager()) != null) {
startActivity(Intent.createChooser(shareIntent, getString(R.string.share))); startActivity(Intent.createChooser(shareIntent, getString(R.string.share)));
} else { } else {
@ -1560,7 +1572,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
if (position == 0) { if (position == 0) {
PostFragment fragment = new PostFragment(); PostFragment fragment = new PostFragment();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString(PostFragment.EXTRA_NAME, subredditName); bundle.putString(PostFragment.EXTRA_NAME, qualifiedName);
bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostPagingSource.TYPE_SUBREDDIT); bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostPagingSource.TYPE_SUBREDDIT);
bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(PostFragment.EXTRA_ACCOUNT_NAME, mAccountName); bundle.putString(PostFragment.EXTRA_ACCOUNT_NAME, mAccountName);
@ -1571,6 +1583,7 @@ public class ViewSubredditDetailActivity extends BaseActivity implements SortTyp
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString(SidebarFragment.EXTRA_ACCESS_TOKEN, mAccessToken); bundle.putString(SidebarFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(SidebarFragment.EXTRA_SUBREDDIT_NAME, subredditName); bundle.putString(SidebarFragment.EXTRA_SUBREDDIT_NAME, subredditName);
bundle.putString(SidebarFragment.EXTRA_COMMUNITY_QUALIFIED_NAME, qualifiedName);
fragment.setArguments(bundle); fragment.setArguments(bundle);
return fragment; return fragment;
} }

View File

@ -61,6 +61,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import io.noties.markwon.AbstractMarkwonPlugin; import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon; import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration; import io.noties.markwon.MarkwonConfiguration;
@ -131,6 +132,8 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
public static final String EXTRA_USER_NAME_KEY = "EUNK"; public static final String EXTRA_USER_NAME_KEY = "EUNK";
public static final String EXTRA_MESSAGE_FULLNAME = "ENF"; public static final String EXTRA_MESSAGE_FULLNAME = "ENF";
public static final String EXTRA_NEW_ACCOUNT_NAME = "ENAN"; public static final String EXTRA_NEW_ACCOUNT_NAME = "ENAN";
public static final String EXTRA_QUALIFIED_USER_NAME_KEY = "EQUNK";
public static final int GIVE_AWARD_REQUEST_CODE = 200; public static final int GIVE_AWARD_REQUEST_CODE = 200;
public static final int EDIT_COMMENT_REQUEST_CODE = 300; public static final int EDIT_COMMENT_REQUEST_CODE = 300;
public static final int ADD_TO_MULTIREDDIT_REQUEST_CODE = 400; public static final int ADD_TO_MULTIREDDIT_REQUEST_CODE = 400;
@ -159,6 +162,9 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
GifImageView iconGifImageView; GifImageView iconGifImageView;
@BindView(R.id.user_name_text_view_view_user_detail_activity) @BindView(R.id.user_name_text_view_view_user_detail_activity)
TextView userNameTextView; TextView userNameTextView;
@BindView(R.id.user_qualified_name_text_view_view_user_detail_activity)
TextView qualifiedNameTextView;
@BindView(R.id.subscribe_user_chip_view_user_detail_activity) @BindView(R.id.subscribe_user_chip_view_user_detail_activity)
Chip subscribeUserChip; Chip subscribeUserChip;
@BindView(R.id.karma_text_view_view_user_detail_activity) @BindView(R.id.karma_text_view_view_user_detail_activity)
@ -169,7 +175,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
TextView descriptionTextView; TextView descriptionTextView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -206,6 +212,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
private String mAccessToken; private String mAccessToken;
private String mAccountName; private String mAccountName;
private String username; private String username;
private String qualifiedName;
private String description; private String description;
private boolean subscriptionReady = false; private boolean subscriptionReady = false;
private boolean mFetchUserInfoSuccess = false; private boolean mFetchUserInfoSuccess = false;
@ -224,6 +231,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
private boolean lockBottomAppBar; private boolean lockBottomAppBar;
private String mMessageFullname; private String mMessageFullname;
private String mNewAccountName; private String mNewAccountName;
//private MaterialAlertDialogBuilder nsfwWarningBuilder; //private MaterialAlertDialogBuilder nsfwWarningBuilder;
@Override @Override
@ -257,6 +265,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
mViewPager2 = viewPager2; mViewPager2 = viewPager2;
username = getIntent().getStringExtra(EXTRA_USER_NAME_KEY); username = getIntent().getStringExtra(EXTRA_USER_NAME_KEY);
qualifiedName = getIntent().getStringExtra(EXTRA_QUALIFIED_USER_NAME_KEY);
fragmentManager = getSupportFragmentManager(); fragmentManager = getSupportFragmentManager();
@ -283,8 +292,9 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
Resources resources = getResources(); Resources resources = getResources();
String title = "u/" + username; String title = username;
userNameTextView.setText(title); userNameTextView.setText(title);
qualifiedNameTextView.setText(qualifiedName);
toolbar.setTitle(title); toolbar.setTitle(title);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
@ -441,7 +451,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
subscriptionReady = false; subscriptionReady = false;
if (resources.getString(R.string.follow).contentEquals(subscribeUserChip.getText())) { if (resources.getString(R.string.follow).contentEquals(subscribeUserChip.getText())) {
if (mAccessToken == null) { if (mAccessToken == null) {
UserFollowing.anonymousFollowUser(mExecutor, new Handler(), mRetrofit, UserFollowing.anonymousFollowUser(mExecutor, new Handler(), mRetrofit.getRetrofit(),
username, mRedditDataRoomDatabase, new UserFollowing.UserFollowingListener() { username, mRedditDataRoomDatabase, new UserFollowing.UserFollowingListener() {
@Override @Override
public void onUserFollowingSuccess() { public void onUserFollowingSuccess() {
@ -458,7 +468,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
} }
}); });
} else { } else {
UserFollowing.followUser(mOauthRetrofit, mRetrofit, mAccessToken, UserFollowing.followUser(mOauthRetrofit, mRetrofit.getRetrofit(), mAccessToken,
username, mAccountName, mRedditDataRoomDatabase, new UserFollowing.UserFollowingListener() { username, mAccountName, mRedditDataRoomDatabase, new UserFollowing.UserFollowingListener() {
@Override @Override
public void onUserFollowingSuccess() { public void onUserFollowingSuccess() {
@ -493,7 +503,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
} }
}); });
} else { } else {
UserFollowing.unfollowUser(mOauthRetrofit, mRetrofit, mAccessToken, UserFollowing.unfollowUser(mOauthRetrofit, mRetrofit.getRetrofit(), mAccessToken,
username, mAccountName, mRedditDataRoomDatabase, new UserFollowing.UserFollowingListener() { username, mAccountName, mRedditDataRoomDatabase, new UserFollowing.UserFollowingListener() {
@Override @Override
public void onUserFollowingSuccess() { public void onUserFollowingSuccess() {
@ -534,15 +544,14 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
subscribeUserChip.setVisibility(View.GONE); subscribeUserChip.setVisibility(View.GONE);
} }
String userFullName = "u/" + userData.getName(); String userFullName = userData.getName();
userNameTextView.setText(userFullName); userNameTextView.setText(userFullName);
if (!title.equals(userFullName)) { if (!title.equals(userFullName)) {
getSupportActionBar().setTitle(userFullName); getSupportActionBar().setTitle(userFullName);
} }
String karma = getString(R.string.karma_info_user_detail, userData.getTotalKarma(), userData.getLinkKarma(), userData.getCommentKarma()); String karma = "";//getString(R.string.karma_info_user_detail, userData.getTotalKarma(), userData.getLinkKarma(), userData.getCommentKarma());
karmaTextView.setText(karma); karmaTextView.setText(karma);
cakedayTextView.setText(getString(R.string.cakeday_info, new SimpleDateFormat("MMM d, yyyy", cakedayTextView.setText(getString(R.string.cakeday_info, userData.getCakeday()));
locale).format(userData.getCakeday())));
if (userData.getDescription() == null || userData.getDescription().equals("")) { if (userData.getDescription() == null || userData.getDescription().equals("")) {
descriptionTextView.setVisibility(View.GONE); descriptionTextView.setVisibility(View.GONE);
@ -568,16 +577,6 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
}*/ }*/
} }
}); });
karmaTextView.setOnClickListener(view -> {
UserData userData = userViewModel.getUserLiveData().getValue();
if (userData != null) {
KarmaInfoBottomSheetFragment karmaInfoBottomSheetFragment = KarmaInfoBottomSheetFragment.newInstance(
userData.getLinkKarma(), userData.getCommentKarma(), userData.getAwarderKarma(), userData.getAwardeeKarma()
);
karmaInfoBottomSheetFragment.show(getSupportFragmentManager(), karmaInfoBottomSheetFragment.getTag());
}
});
} }
@Override @Override
@ -639,7 +638,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
private void checkNewAccountAndInitializeViewPager() { private void checkNewAccountAndInitializeViewPager() {
if (mNewAccountName != null) { if (mNewAccountName != null) {
if (mAccountName == null || !mAccountName.equals(mNewAccountName)) { if (mAccountName == null || !mAccountName.equals(mNewAccountName)) {
SwitchAccount.switchAccount(mRedditDataRoomDatabase, mCurrentAccountSharedPreferences, SwitchAccount.switchAccount(mRedditDataRoomDatabase,mRetrofit, mCurrentAccountSharedPreferences,
mExecutor, new Handler(), mNewAccountName, newAccount -> { mExecutor, new Handler(), mNewAccountName, newAccount -> {
EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName())); EventBus.getDefault().post(new SwitchAccountEvent(getClass().getName()));
Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show(); Toast.makeText(this, R.string.account_switched, Toast.LENGTH_SHORT).show();
@ -1071,7 +1070,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
private void fetchUserInfo() { private void fetchUserInfo() {
if (!mFetchUserInfoSuccess) { if (!mFetchUserInfoSuccess) {
FetchUserData.fetchUserData(mRetrofit, username, new FetchUserData.FetchUserDataListener() { FetchUserData.fetchUserData(mRetrofit.getRetrofit(), qualifiedName, new FetchUserData.FetchUserDataListener() {
@Override @Override
public void onFetchUserDataSuccess(UserData userData, int inboxCount) { public void onFetchUserDataSuccess(UserData userData, int inboxCount) {
new ViewUserDetailActivity.InsertUserDataAsyncTask(mRedditDataRoomDatabase.userDao(), userData, new ViewUserDetailActivity.InsertUserDataAsyncTask(mRedditDataRoomDatabase.userDao(), userData,
@ -1624,7 +1623,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
PostFragment fragment = new PostFragment(); PostFragment fragment = new PostFragment();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostPagingSource.TYPE_USER); bundle.putInt(PostFragment.EXTRA_POST_TYPE, PostPagingSource.TYPE_USER);
bundle.putString(PostFragment.EXTRA_USER_NAME, username); bundle.putString(PostFragment.EXTRA_USER_NAME, qualifiedName);
bundle.putString(PostFragment.EXTRA_USER_WHERE, PostPagingSource.USER_WHERE_SUBMITTED); bundle.putString(PostFragment.EXTRA_USER_WHERE, PostPagingSource.USER_WHERE_SUBMITTED);
bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken); bundle.putString(PostFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(PostFragment.EXTRA_ACCOUNT_NAME, mAccountName); bundle.putString(PostFragment.EXTRA_ACCOUNT_NAME, mAccountName);
@ -1633,7 +1632,7 @@ public class ViewUserDetailActivity extends BaseActivity implements SortTypeSele
} }
CommentsListingFragment fragment = new CommentsListingFragment(); CommentsListingFragment fragment = new CommentsListingFragment();
Bundle bundle = new Bundle(); Bundle bundle = new Bundle();
bundle.putString(CommentsListingFragment.EXTRA_USERNAME, username); bundle.putString(CommentsListingFragment.EXTRA_USERNAME, qualifiedName);
bundle.putString(CommentsListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken); bundle.putString(CommentsListingFragment.EXTRA_ACCESS_TOKEN, mAccessToken);
bundle.putString(CommentsListingFragment.EXTRA_ACCOUNT_NAME, mAccountName); bundle.putString(CommentsListingFragment.EXTRA_ACCOUNT_NAME, mAccountName);
bundle.putBoolean(CommentsListingFragment.EXTRA_ARE_SAVED_COMMENTS, false); bundle.putBoolean(CommentsListingFragment.EXTRA_ARE_SAVED_COMMENTS, false);

View File

@ -94,6 +94,7 @@ import eu.toldi.infinityforlemmy.FetchGfycatOrRedgifsVideoLinks;
import eu.toldi.infinityforlemmy.FetchStreamableVideo; import eu.toldi.infinityforlemmy.FetchStreamableVideo;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.StreamableVideo; import eu.toldi.infinityforlemmy.StreamableVideo;
import eu.toldi.infinityforlemmy.apis.StreamableAPI; import eu.toldi.infinityforlemmy.apis.StreamableAPI;
import eu.toldi.infinityforlemmy.apis.VReddIt; import eu.toldi.infinityforlemmy.apis.VReddIt;
@ -200,7 +201,7 @@ public class ViewVideoActivity extends AppCompatActivity implements CustomFontRe
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit retrofit; RetrofitHolder retrofit;
@Inject @Inject
@Named("gfycat") @Named("gfycat")
@ -789,7 +790,7 @@ public class ViewVideoActivity extends AppCompatActivity implements CustomFontRe
List<String> segments = redirectUri.getPathSegments(); List<String> segments = redirectUri.getPathSegments();
int commentsIndex = segments.lastIndexOf("comments"); int commentsIndex = segments.lastIndexOf("comments");
String postId = segments.get(commentsIndex + 1); String postId = segments.get(commentsIndex + 1);
FetchPost.fetchPost(mExecutor, new Handler(), retrofit, postId, null, FetchPost.fetchPost(mExecutor, new Handler(), retrofit.getRetrofit(), postId, null,
new FetchPost.FetchPostListener() { new FetchPost.FetchPostListener() {
@Override @Override
public void fetchPostSuccess(Post post) { public void fetchPostSuccess(Post post) {
@ -839,7 +840,7 @@ public class ViewVideoActivity extends AppCompatActivity implements CustomFontRe
if (post.getVideoUrl() != null) { if (post.getVideoUrl() != null) {
mVideoUri = Uri.parse(post.getVideoUrl()); mVideoUri = Uri.parse(post.getVideoUrl());
subredditName = post.getSubredditName(); subredditName = post.getSubredditName();
id = post.getId(); id = String.valueOf(post.getId());
videoDownloadUrl = post.getVideoDownloadUrl(); videoDownloadUrl = post.getVideoDownloadUrl();
videoFileName = subredditName + "-" + id + ".mp4"; videoFileName = subredditName + "-" + id + ".mp4";

View File

@ -35,6 +35,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import io.noties.markwon.AbstractMarkwonPlugin; import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon; import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration; import io.noties.markwon.MarkwonConfiguration;
@ -88,7 +89,7 @@ public class WikiActivity extends BaseActivity {
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit retrofit; RetrofitHolder retrofit;
@Inject @Inject
@Named("default") @Named("default")
SharedPreferences mSharedPreferences; SharedPreferences mSharedPreferences;
@ -221,7 +222,7 @@ public class WikiActivity extends BaseActivity {
Glide.with(this).clear(mFetchWikiInfoImageView); Glide.with(this).clear(mFetchWikiInfoImageView);
mFetchWikiInfoLinearLayout.setVisibility(View.GONE); mFetchWikiInfoLinearLayout.setVisibility(View.GONE);
retrofit.create(RedditAPI.class).getWikiPage(getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME), getIntent().getStringExtra(EXTRA_WIKI_PATH)).enqueue(new Callback<String>() { retrofit.getRetrofit().create(RedditAPI.class).getWikiPage(getIntent().getStringExtra(EXTRA_SUBREDDIT_NAME), getIntent().getStringExtra(EXTRA_WIKI_PATH)).enqueue(new Callback<String>() {
@Override @Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
if (response.isSuccessful()) { if (response.isSuccessful()) {

View File

@ -67,7 +67,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
private static final DiffUtil.ItemCallback<Comment> DIFF_CALLBACK = new DiffUtil.ItemCallback<Comment>() { private static final DiffUtil.ItemCallback<Comment> DIFF_CALLBACK = new DiffUtil.ItemCallback<Comment>() {
@Override @Override
public boolean areItemsTheSame(@NonNull Comment comment, @NonNull Comment t1) { public boolean areItemsTheSame(@NonNull Comment comment, @NonNull Comment t1) {
return comment.getId().equals(t1.getId()); return comment.getId() == t1.getId();
} }
@Override @Override
@ -538,21 +538,21 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
Comment comment = getItem(getBindingAdapterPosition()); Comment comment = getItem(getBindingAdapterPosition());
if (comment != null) { if (comment != null) {
int previousVoteType = comment.getVoteType(); int previousVoteType = comment.getVoteType();
String newVoteType; int newVoteType;
downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
if (previousVoteType != Comment.VOTE_TYPE_UPVOTE) { if (previousVoteType != Comment.VOTE_TYPE_UPVOTE) {
//Not upvoted before //Not upvoted before
comment.setVoteType(Comment.VOTE_TYPE_UPVOTE); comment.setVoteType(Comment.VOTE_TYPE_UPVOTE);
newVoteType = APIUtils.DIR_UPVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UPVOTE);
upvoteButton upvoteButton
.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN); .setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mUpvotedColor); scoreTextView.setTextColor(mUpvotedColor);
} else { } else {
//Upvoted before //Upvoted before
comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE); comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mCommentIconAndInfoColor); scoreTextView.setTextColor(mCommentIconAndInfoColor);
} }
@ -566,7 +566,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_UPVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_UPVOTE)) {
comment.setVoteType(Comment.VOTE_TYPE_UPVOTE); comment.setVoteType(Comment.VOTE_TYPE_UPVOTE);
if (currentPosition == position) { if (currentPosition == position) {
upvoteButton.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN);
@ -592,7 +592,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
@Override @Override
public void onVoteThingFail(int position) { public void onVoteThingFail(int position) {
} }
}, comment.getFullName(), newVoteType, getBindingAdapterPosition()); }, comment.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });
@ -609,20 +609,20 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
Comment comment = getItem(getBindingAdapterPosition()); Comment comment = getItem(getBindingAdapterPosition());
if (comment != null) { if (comment != null) {
int previousVoteType = comment.getVoteType(); int previousVoteType = comment.getVoteType();
String newVoteType; int newVoteType;
upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
if (previousVoteType != Comment.VOTE_TYPE_DOWNVOTE) { if (previousVoteType != Comment.VOTE_TYPE_DOWNVOTE) {
//Not downvoted before //Not downvoted before
comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE); comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
newVoteType = APIUtils.DIR_DOWNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_DOWNVOTE);
downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mDownvotedColor); scoreTextView.setTextColor(mDownvotedColor);
} else { } else {
//Downvoted before //Downvoted before
comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE); comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mCommentIconAndInfoColor); scoreTextView.setTextColor(mCommentIconAndInfoColor);
} }
@ -636,7 +636,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_DOWNVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_DOWNVOTE)) {
comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE); comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
if (currentPosition == position) { if (currentPosition == position) {
downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
@ -662,7 +662,7 @@ public class CommentsListingRecyclerViewAdapter extends PagedListAdapter<Comment
@Override @Override
public void onVoteThingFail(int position1) { public void onVoteThingFail(int position1) {
} }
}, comment.getFullName(), newVoteType, getBindingAdapterPosition()); }, comment.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });

View File

@ -359,7 +359,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
if (holder instanceof CommentViewHolder) { if (holder instanceof CommentViewHolder) {
Comment comment = getCurrentComment(position); Comment comment = getCurrentComment(position);
if (comment != null) { if (comment != null) {
if (mIsSingleCommentThreadMode && comment.getId().equals(mSingleCommentId)) { if (mIsSingleCommentThreadMode && String.valueOf(comment.getId()).equals(mSingleCommentId)) {
holder.itemView.setBackgroundColor(mSingleCommentThreadBackgroundColor); holder.itemView.setBackgroundColor(mSingleCommentThreadBackgroundColor);
} else if (comment.getAwards() != null && !comment.getAwards().equals("")) { } else if (comment.getAwards() != null && !comment.getAwards().equals("")) {
holder.itemView.setBackgroundColor(mAwardedCommentBackgroundColor); holder.itemView.setBackgroundColor(mAwardedCommentBackgroundColor);
@ -1396,21 +1396,21 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
Comment comment = getCurrentComment(this); Comment comment = getCurrentComment(this);
if (comment != null) { if (comment != null) {
int previousVoteType = comment.getVoteType(); int previousVoteType = comment.getVoteType();
String newVoteType; int newVoteType;
downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
if (previousVoteType != Comment.VOTE_TYPE_UPVOTE) { if (previousVoteType != Comment.VOTE_TYPE_UPVOTE) {
//Not upvoted before //Not upvoted before
comment.setVoteType(Comment.VOTE_TYPE_UPVOTE); comment.setVoteType(Comment.VOTE_TYPE_UPVOTE);
newVoteType = APIUtils.DIR_UPVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UPVOTE);
upvoteButton.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mUpvotedColor); scoreTextView.setTextColor(mUpvotedColor);
topScoreTextView.setTextColor(mUpvotedColor); topScoreTextView.setTextColor(mUpvotedColor);
} else { } else {
//Upvoted before //Upvoted before
comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE); comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mCommentIconAndInfoColor); scoreTextView.setTextColor(mCommentIconAndInfoColor);
topScoreTextView.setTextColor(mSecondaryTextColor); topScoreTextView.setTextColor(mSecondaryTextColor);
@ -1428,7 +1428,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
@Override @Override
public void onVoteThingSuccess(int position) { public void onVoteThingSuccess(int position) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_UPVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_UPVOTE)) {
comment.setVoteType(Comment.VOTE_TYPE_UPVOTE); comment.setVoteType(Comment.VOTE_TYPE_UPVOTE);
if (currentPosition == position) { if (currentPosition == position) {
upvoteButton.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mUpvotedColor, PorterDuff.Mode.SRC_IN);
@ -1459,7 +1459,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
@Override @Override
public void onVoteThingFail(int position) { public void onVoteThingFail(int position) {
} }
}, comment.getFullName(), newVoteType, getBindingAdapterPosition()); }, comment.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });
@ -1477,21 +1477,21 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
Comment comment = getCurrentComment(this); Comment comment = getCurrentComment(this);
if (comment != null) { if (comment != null) {
int previousVoteType = comment.getVoteType(); int previousVoteType = comment.getVoteType();
String newVoteType; int newVoteType;
upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
if (previousVoteType != Comment.VOTE_TYPE_DOWNVOTE) { if (previousVoteType != Comment.VOTE_TYPE_DOWNVOTE) {
//Not downvoted before //Not downvoted before
comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE); comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
newVoteType = APIUtils.DIR_DOWNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_DOWNVOTE);
downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mDownvotedColor); scoreTextView.setTextColor(mDownvotedColor);
topScoreTextView.setTextColor(mDownvotedColor); topScoreTextView.setTextColor(mDownvotedColor);
} else { } else {
//Downvoted before //Downvoted before
comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE); comment.setVoteType(Comment.VOTE_TYPE_NO_VOTE);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mCommentIconAndInfoColor, PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mCommentIconAndInfoColor); scoreTextView.setTextColor(mCommentIconAndInfoColor);
topScoreTextView.setTextColor(mSecondaryTextColor); topScoreTextView.setTextColor(mSecondaryTextColor);
@ -1510,7 +1510,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_DOWNVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_DOWNVOTE)) {
comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE); comment.setVoteType(Comment.VOTE_TYPE_DOWNVOTE);
if (currentPosition == position) { if (currentPosition == position) {
downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mDownvotedColor, PorterDuff.Mode.SRC_IN);
@ -1541,7 +1541,7 @@ public class CommentsRecyclerViewAdapter extends RecyclerView.Adapter<RecyclerVi
@Override @Override
public void onVoteThingFail(int position1) { public void onVoteThingFail(int position1) {
} }
}, comment.getFullName(), newVoteType, getBindingAdapterPosition()); }, comment.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });

View File

@ -119,11 +119,6 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
} }
((UserViewHolder) viewHolder).userNameTextView.setText(mSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - offset).getName()); ((UserViewHolder) viewHolder).userNameTextView.setText(mSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - offset).getName());
if(mSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - offset).isFavorite()) {
((UserViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
} else {
((UserViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
} else if (viewHolder instanceof FavoriteUserViewHolder) { } else if (viewHolder instanceof FavoriteUserViewHolder) {
if (!mFavoriteSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - 1).getIconUrl().equals("")) { if (!mFavoriteSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - 1).getIconUrl().equals("")) {
glide.load(mFavoriteSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - 1).getIconUrl()) glide.load(mFavoriteSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - 1).getIconUrl())
@ -138,11 +133,6 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
} }
((FavoriteUserViewHolder) viewHolder).userNameTextView.setText(mFavoriteSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - 1).getName()); ((FavoriteUserViewHolder) viewHolder).userNameTextView.setText(mFavoriteSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - 1).getName());
if(mFavoriteSubscribedUserData.get(viewHolder.getBindingAdapterPosition() - 1).isFavorite()) {
((FavoriteUserViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
} else {
((FavoriteUserViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
} }
} }
@ -196,8 +186,6 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
GifImageView iconGifImageView; GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing) @BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView userNameTextView; TextView userNameTextView;
@BindView(R.id.favorite_image_view_item_subscribed_thing)
ImageView favoriteImageView;
FavoriteUserViewHolder(View itemView) { FavoriteUserViewHolder(View itemView) {
super(itemView); super(itemView);
@ -216,64 +204,6 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
} }
}); });
favoriteImageView.setOnClickListener(view -> {
int position = getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteSubscribedUserData.size() > position) {
if(mFavoriteSubscribedUserData.get(position).isFavorite()) {
favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
mFavoriteSubscribedUserData.get(position).setFavorite(false);
FavoriteThing.unfavoriteUser(mExecutor, new Handler(), mOauthRetrofit,
mRedditDataRoomDatabase, mAccessToken,
mFavoriteSubscribedUserData.get(position),
new FavoriteThing.FavoriteThingListener() {
@Override
public void success() {
int position = getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteSubscribedUserData.size() > position) {
mFavoriteSubscribedUserData.get(position).setFavorite(false);
}
favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_unfavorite_failed, Toast.LENGTH_SHORT).show();
int position = getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteSubscribedUserData.size() > position) {
mFavoriteSubscribedUserData.get(position).setFavorite(true);
}
favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
});
} else {
favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
mFavoriteSubscribedUserData.get(position).setFavorite(true);
FavoriteThing.favoriteUser(mExecutor, new Handler(), mOauthRetrofit,
mRedditDataRoomDatabase, mAccessToken,
mFavoriteSubscribedUserData.get(position),
new FavoriteThing.FavoriteThingListener() {
@Override
public void success() {
int position = getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteSubscribedUserData.size() > position) {
mFavoriteSubscribedUserData.get(position).setFavorite(true);
}
favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_favorite_failed, Toast.LENGTH_SHORT).show();
int position = getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteSubscribedUserData.size() > position) {
mFavoriteSubscribedUserData.get(position).setFavorite(false);
}
favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
});
}
}
});
} }
} }
@ -282,8 +212,6 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
GifImageView iconGifImageView; GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing) @BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView userNameTextView; TextView userNameTextView;
@BindView(R.id.favorite_image_view_item_subscribed_thing)
ImageView favoriteImageView;
UserViewHolder(View itemView) { UserViewHolder(View itemView) {
super(itemView); super(itemView);
@ -304,67 +232,6 @@ public class FollowedUsersRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
} }
}); });
favoriteImageView.setOnClickListener(view -> {
int offset = (mFavoriteSubscribedUserData != null && mFavoriteSubscribedUserData.size() > 0) ?
mFavoriteSubscribedUserData.size() + 2 : 0;
int position = getBindingAdapterPosition() - offset;
if(position >= 0 && mSubscribedUserData.size() > position) {
if(mSubscribedUserData.get(position).isFavorite()) {
favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
mSubscribedUserData.get(position).setFavorite(false);
FavoriteThing.unfavoriteUser(mExecutor, new Handler(), mOauthRetrofit,
mRedditDataRoomDatabase, mAccessToken,
mSubscribedUserData.get(position),
new FavoriteThing.FavoriteThingListener() {
@Override
public void success() {
int position = getBindingAdapterPosition() - offset;
if(position >= 0 && mSubscribedUserData.size() > position) {
mSubscribedUserData.get(position).setFavorite(false);
}
favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_unfavorite_failed, Toast.LENGTH_SHORT).show();
int position = getBindingAdapterPosition() - offset;
if(position >= 0 && mSubscribedUserData.size() > position) {
mSubscribedUserData.get(position).setFavorite(true);
}
favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
});
} else {
favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
mSubscribedUserData.get(position).setFavorite(true);
FavoriteThing.favoriteUser(mExecutor, new Handler(), mOauthRetrofit,
mRedditDataRoomDatabase, mAccessToken,
mSubscribedUserData.get(position),
new FavoriteThing.FavoriteThingListener() {
@Override
public void success() {
int position = getBindingAdapterPosition() - offset;
if(position >= 0 && mSubscribedUserData.size() > position) {
mSubscribedUserData.get(position).setFavorite(true);
}
favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_favorite_failed, Toast.LENGTH_SHORT).show();
int position = getBindingAdapterPosition() - offset;
if(position >= 0 && mSubscribedUserData.size() > position) {
mSubscribedUserData.get(position).setFavorite(false);
}
favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
});
}
}
});
} }
} }

View File

@ -126,7 +126,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
private static final DiffUtil.ItemCallback<Post> DIFF_CALLBACK = new DiffUtil.ItemCallback<Post>() { private static final DiffUtil.ItemCallback<Post> DIFF_CALLBACK = new DiffUtil.ItemCallback<Post>() {
@Override @Override
public boolean areItemsTheSame(@NonNull Post post, @NonNull Post t1) { public boolean areItemsTheSame(@NonNull Post post, @NonNull Post t1) {
return post.getId().equals(t1.getId()); return post.getId() == t1.getId();
} }
@Override @Override
@ -357,7 +357,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
switch (post.getPostType()) { switch (post.getPostType()) {
case Post.VIDEO_TYPE: case Post.VIDEO_TYPE:
if (mAutoplay) { if (mAutoplay) {
if ((!mAutoplayNsfwVideos && post.isNSFW()) || post.isSpoiler()) { if ((!mAutoplayNsfwVideos && post.isNSFW())) {
return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE; return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE;
} }
return VIEW_TYPE_POST_CARD_VIDEO_AUTOPLAY_TYPE; return VIEW_TYPE_POST_CARD_VIDEO_AUTOPLAY_TYPE;
@ -416,7 +416,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
switch (post.getPostType()) { switch (post.getPostType()) {
case Post.VIDEO_TYPE: case Post.VIDEO_TYPE:
if (mAutoplay) { if (mAutoplay) {
if ((!mAutoplayNsfwVideos && post.isNSFW()) || post.isSpoiler()) { if ((!mAutoplayNsfwVideos && post.isNSFW())) {
return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE; return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE;
} }
return VIEW_TYPE_POST_CARD_2_VIDEO_AUTOPLAY_TYPE; return VIEW_TYPE_POST_CARD_2_VIDEO_AUTOPLAY_TYPE;
@ -627,28 +627,6 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
((PostBaseViewHolder) holder).nsfwTextView.setVisibility(View.VISIBLE); ((PostBaseViewHolder) holder).nsfwTextView.setVisibility(View.VISIBLE);
} }
if (post.isSpoiler()) {
((PostBaseViewHolder) holder).spoilerTextView.setVisibility(View.VISIBLE);
}
if (post.getFlair() != null && !post.getFlair().equals("")) {
if (mHidePostFlair) {
((PostBaseViewHolder) holder).flairTextView.setVisibility(View.GONE);
} else {
((PostBaseViewHolder) holder).flairTextView.setVisibility(View.VISIBLE);
Utils.setHTMLWithImageToTextView(((PostBaseViewHolder) holder).flairTextView, post.getFlair(), false);
}
}
if (post.getNAwards() > 0 && !mHideTheNumberOfAwards) {
((PostBaseViewHolder) holder).awardsTextView.setVisibility(View.VISIBLE);
if (post.getNAwards() == 1) {
((PostBaseViewHolder) holder).awardsTextView.setText(mActivity.getString(R.string.one_award));
} else {
((PostBaseViewHolder) holder).awardsTextView.setText(mActivity.getString(R.string.n_awards, post.getNAwards()));
}
}
switch (post.getVoteType()) { switch (post.getVoteType()) {
case 1: case 1:
//Upvoted //Upvoted
@ -812,7 +790,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_outline_video_24dp); ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_outline_video_24dp);
((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE); ((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
} else { } else {
if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler))) { if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mAutoplay && mAutoplayNsfwVideos)))) {
((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE); ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE);
((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_image_24dp); ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_image_24dp);
((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE); ((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
@ -869,10 +847,10 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
} }
((PostBaseGalleryTypeViewHolder) holder).adapter.setGalleryImages(post.getGallery()); ((PostBaseGalleryTypeViewHolder) holder).adapter.setGalleryImages(post.getGallery());
((PostBaseGalleryTypeViewHolder) holder).adapter.setBlurImage( ((PostBaseGalleryTypeViewHolder) holder).adapter.setBlurImage(
(post.isNSFW() && mNeedBlurNsfw) || (post.isSpoiler() && mNeedBlurSpoiler)); (post.isNSFW() && mNeedBlurNsfw) );
} }
} else if (holder instanceof PostTextTypeViewHolder) { } else if (holder instanceof PostTextTypeViewHolder) {
if (!mHideTextPostContent && !post.isSpoiler() && post.getSelfTextPlainTrimmed() != null && !post.getSelfTextPlainTrimmed().equals("")) { if (!mHideTextPostContent && post.getSelfTextPlainTrimmed() != null && !post.getSelfTextPlainTrimmed().equals("")) {
((PostTextTypeViewHolder) holder).contentTextView.setVisibility(View.VISIBLE); ((PostTextTypeViewHolder) holder).contentTextView.setVisibility(View.VISIBLE);
((PostTextTypeViewHolder) holder).contentTextView.setText(post.getSelfTextPlainTrimmed()); ((PostTextTypeViewHolder) holder).contentTextView.setText(post.getSelfTextPlainTrimmed());
} }
@ -991,7 +969,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_outline_video_24dp); ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_outline_video_24dp);
((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE); ((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
} else { } else {
if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler))) { if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mAutoplay && mAutoplayNsfwVideos)))) {
((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setVisibility(View.VISIBLE); ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setVisibility(View.VISIBLE);
((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_image_24dp); ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_image_24dp);
((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE); ((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
@ -1032,7 +1010,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
} }
} else if (holder instanceof PostCard2TextTypeViewHolder) { } else if (holder instanceof PostCard2TextTypeViewHolder) {
if (!mHideTextPostContent && !post.isSpoiler() && post.getSelfTextPlainTrimmed() != null && !post.getSelfTextPlainTrimmed().equals("")) { if (!mHideTextPostContent && post.getSelfTextPlainTrimmed() != null && !post.getSelfTextPlainTrimmed().equals("")) {
((PostCard2TextTypeViewHolder) holder).contentTextView.setVisibility(View.VISIBLE); ((PostCard2TextTypeViewHolder) holder).contentTextView.setVisibility(View.VISIBLE);
((PostCard2TextTypeViewHolder) holder).contentTextView.setText(post.getSelfTextPlainTrimmed()); ((PostCard2TextTypeViewHolder) holder).contentTextView.setText(post.getSelfTextPlainTrimmed());
} }
@ -1049,9 +1027,6 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
final String title = post.getTitle(); final String title = post.getTitle();
int voteType = post.getVoteType(); int voteType = post.getVoteType();
boolean nsfw = post.isNSFW(); boolean nsfw = post.isNSFW();
boolean spoiler = post.isSpoiler();
String flair = post.getFlair();
int nAwards = post.getNAwards();
boolean isArchived = post.isArchived(); boolean isArchived = post.isArchived();
if (mDisplaySubredditName) { if (mDisplaySubredditName) {
@ -1208,28 +1183,6 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
((PostCompactBaseViewHolder) holder).nsfwTextView.setVisibility(View.VISIBLE); ((PostCompactBaseViewHolder) holder).nsfwTextView.setVisibility(View.VISIBLE);
} }
if (spoiler) {
((PostCompactBaseViewHolder) holder).spoilerTextView.setVisibility(View.VISIBLE);
}
if (flair != null && !flair.equals("")) {
if (mHidePostFlair) {
((PostCompactBaseViewHolder) holder).flairTextView.setVisibility(View.GONE);
} else {
((PostCompactBaseViewHolder) holder).flairTextView.setVisibility(View.VISIBLE);
Utils.setHTMLWithImageToTextView(((PostCompactBaseViewHolder) holder).flairTextView, flair, false);
}
}
if (nAwards > 0 && !mHideTheNumberOfAwards) {
((PostCompactBaseViewHolder) holder).awardsTextView.setVisibility(View.VISIBLE);
if (nAwards == 1) {
((PostCompactBaseViewHolder) holder).awardsTextView.setText(mActivity.getString(R.string.one_award));
} else {
((PostCompactBaseViewHolder) holder).awardsTextView.setText(mActivity.getString(R.string.n_awards, nAwards));
}
}
switch (voteType) { switch (voteType) {
case 1: case 1:
//Upvoted //Upvoted
@ -1402,7 +1355,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
break; break;
} }
case Post.GIF_TYPE: { case Post.GIF_TYPE: {
if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler))) { if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mAutoplay && mAutoplayNsfwVideos)))) {
((PostGalleryViewHolder) holder).noPreviewImageView.setVisibility(View.VISIBLE); ((PostGalleryViewHolder) holder).noPreviewImageView.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_image_24dp); ((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_image_24dp);
} else { } else {
@ -1534,7 +1487,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
} }
((PostGalleryBaseGalleryTypeViewHolder) holder).adapter.setGalleryImages(post.getGallery()); ((PostGalleryBaseGalleryTypeViewHolder) holder).adapter.setGalleryImages(post.getGallery());
((PostGalleryBaseGalleryTypeViewHolder) holder).adapter.setBlurImage( ((PostGalleryBaseGalleryTypeViewHolder) holder).adapter.setBlurImage(
(post.isNSFW() && mNeedBlurNsfw) || (post.isSpoiler() && mNeedBlurSpoiler)); (post.isNSFW() && mNeedBlurNsfw) );
} }
} }
} }
@ -1571,7 +1524,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
Post.Preview preview = ((PostWithPreviewTypeViewHolder) holder).preview; Post.Preview preview = ((PostWithPreviewTypeViewHolder) holder).preview;
if (preview != null) { if (preview != null) {
String url; String url;
boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler); boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos));
if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) { if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) {
url = post.getUrl(); url = post.getUrl();
} else { } else {
@ -1598,7 +1551,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
RequestBuilder<Drawable> imageRequestBuilder = mGlide.load(postCompactThumbnailPreviewUrl) RequestBuilder<Drawable> imageRequestBuilder = mGlide.load(postCompactThumbnailPreviewUrl)
.error(R.drawable.ic_error_outline_black_24dp).listener(((PostCompactBaseViewHolder) holder).requestListener); .error(R.drawable.ic_error_outline_black_24dp).listener(((PostCompactBaseViewHolder) holder).requestListener);
if ((post.isNSFW() && mNeedBlurNsfw) || (post.isSpoiler() && mNeedBlurSpoiler)) { if ((post.isNSFW() && mNeedBlurNsfw)) {
imageRequestBuilder imageRequestBuilder
.transform(new BlurTransformation(50, 2)).into(((PostCompactBaseViewHolder) holder).imageView); .transform(new BlurTransformation(50, 2)).into(((PostCompactBaseViewHolder) holder).imageView);
} else { } else {
@ -1610,7 +1563,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
Post.Preview preview = ((PostGalleryViewHolder) holder).preview; Post.Preview preview = ((PostGalleryViewHolder) holder).preview;
if (preview != null) { if (preview != null) {
String url; String url;
boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos)) || post.isSpoiler() && mNeedBlurSpoiler; boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos));
if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) { if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) {
url = post.getUrl(); url = post.getUrl();
} else { } else {
@ -1630,7 +1583,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
Post.Preview preview = ((PostCard2WithPreviewViewHolder) holder).preview; Post.Preview preview = ((PostCard2WithPreviewViewHolder) holder).preview;
if (preview != null) { if (preview != null) {
String url; String url;
boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler); boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos));
if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) { if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) {
url = post.getUrl(); url = post.getUrl();
} else { } else {
@ -2325,9 +2278,6 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
return; return;
} }
Post post = getItem(position); Post post = getItem(position);
if (post != null) {
mCallback.flairChipClicked(post.getFlair());
}
}); });
} }
@ -2353,21 +2303,21 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
int previousScoreTextViewColor = scoreTextView.getCurrentTextColor(); int previousScoreTextViewColor = scoreTextView.getCurrentTextColor();
int previousVoteType = post.getVoteType(); int previousVoteType = post.getVoteType();
String newVoteType; int newVoteType;
downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
if (previousVoteType != 1) { if (previousVoteType != 1) {
//Not upvoted before //Not upvoted before
post.setVoteType(1); post.setVoteType(1);
newVoteType = APIUtils.DIR_UPVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UPVOTE);
upvoteButton upvoteButton
.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); .setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mUpvotedColor); scoreTextView.setTextColor(mUpvotedColor);
} else { } else {
//Upvoted before //Upvoted before
post.setVoteType(0); post.setVoteType(0);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mPostIconAndInfoColor); scoreTextView.setTextColor(mPostIconAndInfoColor);
} }
@ -2380,7 +2330,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_UPVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_UPVOTE)) {
post.setVoteType(1); post.setVoteType(1);
if (currentPosition == position) { if (currentPosition == position) {
upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
@ -2419,7 +2369,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post)); EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post));
} }
}, post.getFullName(), newVoteType, getBindingAdapterPosition()); }, post.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });
@ -2445,21 +2395,21 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
int previousScoreTextViewColor = scoreTextView.getCurrentTextColor(); int previousScoreTextViewColor = scoreTextView.getCurrentTextColor();
int previousVoteType = post.getVoteType(); int previousVoteType = post.getVoteType();
String newVoteType; int newVoteType;
upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
if (previousVoteType != -1) { if (previousVoteType != -1) {
//Not downvoted before //Not downvoted before
post.setVoteType(-1); post.setVoteType(-1);
newVoteType = APIUtils.DIR_DOWNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_DOWNVOTE);
downvoteButton downvoteButton
.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); .setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mDownvotedColor); scoreTextView.setTextColor(mDownvotedColor);
} else { } else {
//Downvoted before //Downvoted before
post.setVoteType(0); post.setVoteType(0);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mPostIconAndInfoColor); scoreTextView.setTextColor(mPostIconAndInfoColor);
} }
@ -2472,7 +2422,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_DOWNVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_DOWNVOTE)) {
post.setVoteType(-1); post.setVoteType(-1);
if (currentPosition == position) { if (currentPosition == position) {
downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
@ -2511,7 +2461,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post)); EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post));
} }
}, post.getFullName(), newVoteType, getBindingAdapterPosition()); }, post.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });
@ -3640,9 +3590,6 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
return; return;
} }
Post post = getItem(position); Post post = getItem(position);
if (post != null && !(mActivity instanceof FilteredPostsActivity)) {
mCallback.flairChipClicked(post.getFlair());
}
}); });
imageView.setOnClickListener(view -> { imageView.setOnClickListener(view -> {
@ -3682,21 +3629,21 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
int previousScoreTextViewColor = scoreTextView.getCurrentTextColor(); int previousScoreTextViewColor = scoreTextView.getCurrentTextColor();
int previousVoteType = post.getVoteType(); int previousVoteType = post.getVoteType();
String newVoteType; int newVoteType;
downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
if (previousVoteType != 1) { if (previousVoteType != 1) {
//Not upvoted before //Not upvoted before
post.setVoteType(1); post.setVoteType(1);
newVoteType = APIUtils.DIR_UPVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UPVOTE);
upvoteButton upvoteButton
.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); .setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mUpvotedColor); scoreTextView.setTextColor(mUpvotedColor);
} else { } else {
//Upvoted before //Upvoted before
post.setVoteType(0); post.setVoteType(0);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mPostIconAndInfoColor); scoreTextView.setTextColor(mPostIconAndInfoColor);
} }
@ -3709,7 +3656,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_UPVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_UPVOTE)) {
post.setVoteType(1); post.setVoteType(1);
if (currentPosition == position) { if (currentPosition == position) {
upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
@ -3748,7 +3695,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post)); EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post));
} }
}, post.getFullName(), newVoteType, getBindingAdapterPosition()); }, post.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });
@ -3774,21 +3721,21 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
int previousScoreTextViewColor = scoreTextView.getCurrentTextColor(); int previousScoreTextViewColor = scoreTextView.getCurrentTextColor();
int previousVoteType = post.getVoteType(); int previousVoteType = post.getVoteType();
String newVoteType; int newVoteType;
upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
if (previousVoteType != -1) { if (previousVoteType != -1) {
//Not downvoted before //Not downvoted before
post.setVoteType(-1); post.setVoteType(-1);
newVoteType = APIUtils.DIR_DOWNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_DOWNVOTE);
downvoteButton downvoteButton
.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); .setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mDownvotedColor); scoreTextView.setTextColor(mDownvotedColor);
} else { } else {
//Downvoted before //Downvoted before
post.setVoteType(0); post.setVoteType(0);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mPostIconAndInfoColor); scoreTextView.setTextColor(mPostIconAndInfoColor);
} }
@ -3801,7 +3748,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_DOWNVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_DOWNVOTE)) {
post.setVoteType(-1); post.setVoteType(-1);
if (currentPosition == position) { if (currentPosition == position) {
downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
@ -3841,7 +3788,7 @@ public class HistoryPostRecyclerViewAdapter extends PagingDataAdapter<Post, Recy
EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post)); EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post));
} }
}, post.getFullName(), newVoteType, getBindingAdapterPosition()); }, post.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });

View File

@ -391,7 +391,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
switch (mPost.getPostType()) { switch (mPost.getPostType()) {
case Post.VIDEO_TYPE: case Post.VIDEO_TYPE:
if (mAutoplay && !mSeparatePostAndComments) { if (mAutoplay && !mSeparatePostAndComments) {
if ((!mAutoplayNsfwVideos && mPost.isNSFW()) || mPost.isSpoiler()) { if ((!mAutoplayNsfwVideos && mPost.isNSFW()) ) {
return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW; return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW;
} }
return VIEW_TYPE_POST_DETAIL_VIDEO_AUTOPLAY; return VIEW_TYPE_POST_DETAIL_VIDEO_AUTOPLAY;
@ -400,12 +400,12 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
} }
case Post.GIF_TYPE: case Post.GIF_TYPE:
if (mAutoplay) { if (mAutoplay) {
if ((!mAutoplayNsfwVideos && mPost.isNSFW()) || mPost.isSpoiler()) { if ((!mAutoplayNsfwVideos && mPost.isNSFW()) ) {
return VIEW_TYPE_POST_DETAIL_NO_PREVIEW_LINK; return VIEW_TYPE_POST_DETAIL_NO_PREVIEW_LINK;
} }
return VIEW_TYPE_POST_DETAIL_GIF_AUTOPLAY; return VIEW_TYPE_POST_DETAIL_GIF_AUTOPLAY;
} else { } else {
if ((mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())) || (mPost.isSpoiler() && mNeedBlurSpoiler)) { if ((mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()))) {
return VIEW_TYPE_POST_DETAIL_NO_PREVIEW_LINK; return VIEW_TYPE_POST_DETAIL_NO_PREVIEW_LINK;
} }
return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW; return VIEW_TYPE_POST_DETAIL_VIDEO_AND_GIF_PREVIEW;
@ -536,13 +536,6 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
} }
} }
if (mPost.getAuthorFlairHTML() != null && !mPost.getAuthorFlairHTML().equals("")) {
((PostDetailBaseViewHolder) holder).mAuthorFlairTextView.setVisibility(View.VISIBLE);
Utils.setHTMLWithImageToTextView(((PostDetailBaseViewHolder) holder).mAuthorFlairTextView, mPost.getAuthorFlairHTML(), true);
} else if (mPost.getAuthorFlair() != null && !mPost.getAuthorFlair().equals("")) {
((PostDetailBaseViewHolder) holder).mAuthorFlairTextView.setVisibility(View.VISIBLE);
((PostDetailBaseViewHolder) holder).mAuthorFlairTextView.setText(mPost.getAuthorFlair());
}
switch (mPost.getVoteType()) { switch (mPost.getVoteType()) {
case 1: case 1:
@ -573,7 +566,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
} }
if (!mHideSubredditAndUserPrefix) { if (!mHideSubredditAndUserPrefix) {
((PostDetailBaseViewHolder) holder).mSubredditTextView.setText("r/" + mPost.getSubredditName()); ((PostDetailBaseViewHolder) holder).mSubredditTextView.setText(mPost.getSubredditNamePrefixed());
((PostDetailBaseViewHolder) holder).mUserTextView.setText(mPost.getAuthorNamePrefixed()); ((PostDetailBaseViewHolder) holder).mUserTextView.setText(mPost.getAuthorNamePrefixed());
} else { } else {
((PostDetailBaseViewHolder) holder).mSubredditTextView.setText(mPost.getSubredditName()); ((PostDetailBaseViewHolder) holder).mSubredditTextView.setText(mPost.getSubredditName());
@ -602,19 +595,6 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
((PostDetailBaseViewHolder) holder).mLockedImageView.setVisibility(View.VISIBLE); ((PostDetailBaseViewHolder) holder).mLockedImageView.setVisibility(View.VISIBLE);
} }
if (mPost.isSpoiler()) {
((PostDetailBaseViewHolder) holder).mSpoilerTextView.setVisibility(View.VISIBLE);
}
if (!mHidePostFlair && mPost.getFlair() != null && !mPost.getFlair().equals("")) {
((PostDetailBaseViewHolder) holder).mFlairTextView.setVisibility(View.VISIBLE);
Utils.setHTMLWithImageToTextView(((PostDetailBaseViewHolder) holder).mFlairTextView, mPost.getFlair(), false);
}
if (!mHideTheNumberOfAwards && mPost.getAwards() != null && !mPost.getAwards().equals("")) {
((PostDetailBaseViewHolder) holder).mAwardsTextView.setVisibility(View.VISIBLE);
Utils.setHTMLWithImageToTextView(((PostDetailBaseViewHolder) holder).mAwardsTextView, mPost.getAwards(), true);
}
if (mHideUpvoteRatio) { if (mHideUpvoteRatio) {
((PostDetailBaseViewHolder) holder).mUpvoteRatioTextView.setVisibility(View.GONE); ((PostDetailBaseViewHolder) holder).mUpvoteRatioTextView.setVisibility(View.GONE);
@ -805,7 +785,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
} }
((PostDetailGalleryViewHolder) holder).adapter.setGalleryImages(mPost.getGallery()); ((PostDetailGalleryViewHolder) holder).adapter.setGalleryImages(mPost.getGallery());
((PostDetailGalleryViewHolder) holder).adapter.setBlurImage( ((PostDetailGalleryViewHolder) holder).adapter.setBlurImage(
(mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())) || (mPost.isSpoiler() && mNeedBlurSpoiler)); (mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())) );
} }
} }
} }
@ -839,7 +819,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
private void loadImage(PostDetailBaseViewHolder holder, @NonNull Post.Preview preview) { private void loadImage(PostDetailBaseViewHolder holder, @NonNull Post.Preview preview) {
if (holder instanceof PostDetailImageAndGifAutoplayViewHolder) { if (holder instanceof PostDetailImageAndGifAutoplayViewHolder) {
boolean blurImage = (mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mPost.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos)) || (mPost.isSpoiler() && mNeedBlurSpoiler); boolean blurImage = (mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mPost.getPostType() == Post.GIF_TYPE && mAutoplayNsfwVideos));
String url = mPost.getPostType() == Post.IMAGE_TYPE || blurImage ? preview.getPreviewUrl() : mPost.getUrl(); String url = mPost.getPostType() == Post.IMAGE_TYPE || blurImage ? preview.getPreviewUrl() : mPost.getUrl();
RequestBuilder<Drawable> imageRequestBuilder = mGlide.load(url) RequestBuilder<Drawable> imageRequestBuilder = mGlide.load(url)
.listener(new RequestListener<>() { .listener(new RequestListener<>() {
@ -889,7 +869,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
} }
}); });
if ((mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())) || (mPost.isSpoiler() && mNeedBlurSpoiler)) { if ((mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()))) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 10))) imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 10)))
.into(((PostDetailVideoAndGifPreviewHolder) holder).mImageView); .into(((PostDetailVideoAndGifPreviewHolder) holder).mImageView);
} else { } else {
@ -917,7 +897,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
} }
}); });
if ((mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())) || (mPost.isSpoiler() && mNeedBlurSpoiler)) { if ((mPost.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()))) {
imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 10))) imageRequestBuilder.apply(RequestOptions.bitmapTransform(new BlurTransformation(50, 10)))
.into(((PostDetailLinkViewHolder) holder).mImageView); .into(((PostDetailLinkViewHolder) holder).mImageView);
} else { } else {
@ -966,13 +946,6 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
} }
} }
public void giveAward(String awardsHTML, int awardCount) {
if (mPost != null) {
mPost.addAwards(awardsHTML);
mPost.addAwards(awardCount);
notifyItemChanged(0);
}
}
public void addOneComment() { public void addOneComment() {
if (mPost != null) { if (mPost != null) {
@ -1157,17 +1130,8 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
mTypeTextView.setVisibility(View.GONE); mTypeTextView.setVisibility(View.GONE);
} }
if (!mHidePostFlair) {
mFlairTextView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, FilteredPostsActivity.class);
intent.putExtra(FilteredPostsActivity.EXTRA_NAME, mSubredditNamePrefixed.substring(2));
intent.putExtra(FilteredPostsActivity.EXTRA_POST_TYPE, PostPagingSource.TYPE_SUBREDDIT);
intent.putExtra(FilteredPostsActivity.EXTRA_CONTAIN_FLAIR, mPost.getFlair());
mActivity.startActivity(intent);
});
} else {
mFlairTextView.setVisibility(View.GONE); mFlairTextView.setVisibility(View.GONE);
}
mNSFWTextView.setOnClickListener(view -> { mNSFWTextView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, FilteredPostsActivity.class); Intent intent = new Intent(mActivity, FilteredPostsActivity.class);
@ -2060,7 +2024,7 @@ public class PostDetailRecyclerViewAdapter extends RecyclerView.Adapter<Recycler
Intent intent = new Intent(mActivity, ViewImageOrGifActivity.class); Intent intent = new Intent(mActivity, ViewImageOrGifActivity.class);
intent.putExtra(ViewImageOrGifActivity.EXTRA_IMAGE_URL_KEY, mPost.getUrl()); intent.putExtra(ViewImageOrGifActivity.EXTRA_IMAGE_URL_KEY, mPost.getUrl());
intent.putExtra(ViewImageOrGifActivity.EXTRA_FILE_NAME_KEY, mPost.getSubredditNamePrefixed().substring(2) intent.putExtra(ViewImageOrGifActivity.EXTRA_FILE_NAME_KEY, mPost.getSubredditNamePrefixed().substring(2)
+ "-" + mPost.getId().substring(3) + ".jpg"); + "-" + mPost.getId() + ".jpg");
intent.putExtra(ViewImageOrGifActivity.EXTRA_POST_TITLE_KEY, mPost.getTitle()); intent.putExtra(ViewImageOrGifActivity.EXTRA_POST_TITLE_KEY, mPost.getTitle());
intent.putExtra(ViewImageOrGifActivity.EXTRA_SUBREDDIT_OR_USERNAME_KEY, mPost.getSubredditName()); intent.putExtra(ViewImageOrGifActivity.EXTRA_SUBREDDIT_OR_USERNAME_KEY, mPost.getSubredditName());
mActivity.startActivity(intent); mActivity.startActivity(intent);

View File

@ -131,7 +131,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
private static final DiffUtil.ItemCallback<Post> DIFF_CALLBACK = new DiffUtil.ItemCallback<Post>() { private static final DiffUtil.ItemCallback<Post> DIFF_CALLBACK = new DiffUtil.ItemCallback<Post>() {
@Override @Override
public boolean areItemsTheSame(@NonNull Post post, @NonNull Post t1) { public boolean areItemsTheSame(@NonNull Post post, @NonNull Post t1) {
return post.getId().equals(t1.getId()); return post.getId() == t1.getId();
} }
@Override @Override
@ -379,7 +379,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
switch (post.getPostType()) { switch (post.getPostType()) {
case Post.VIDEO_TYPE: case Post.VIDEO_TYPE:
if (mAutoplay) { if (mAutoplay) {
if ((!mAutoplayNsfwVideos && post.isNSFW()) || post.isSpoiler()) { if ((!mAutoplayNsfwVideos && post.isNSFW())) {
return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE; return VIEW_TYPE_POST_CARD_WITH_PREVIEW_TYPE;
} }
return VIEW_TYPE_POST_CARD_VIDEO_AUTOPLAY_TYPE; return VIEW_TYPE_POST_CARD_VIDEO_AUTOPLAY_TYPE;
@ -438,7 +438,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
switch (post.getPostType()) { switch (post.getPostType()) {
case Post.VIDEO_TYPE: case Post.VIDEO_TYPE:
if (mAutoplay) { if (mAutoplay) {
if ((!mAutoplayNsfwVideos && post.isNSFW()) || post.isSpoiler()) { if ((!mAutoplayNsfwVideos && post.isNSFW()) ) {
return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE; return VIEW_TYPE_POST_CARD_2_WITH_PREVIEW_TYPE;
} }
return VIEW_TYPE_POST_CARD_2_VIDEO_AUTOPLAY_TYPE; return VIEW_TYPE_POST_CARD_2_VIDEO_AUTOPLAY_TYPE;
@ -523,13 +523,13 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
((PostBaseViewHolder) holder).titleTextView.setTextColor(mReadPostTitleColor); ((PostBaseViewHolder) holder).titleTextView.setTextColor(mReadPostTitleColor);
} }
String authorPrefixed = "u/" + post.getAuthor(); String authorPrefixed = post.getAuthorNamePrefixed();
if (mHideSubredditAndUserPrefix) { if (mHideSubredditAndUserPrefix) {
((PostBaseViewHolder) holder).subredditTextView.setText(post.getSubredditName()); ((PostBaseViewHolder) holder).subredditTextView.setText(post.getSubredditName());
((PostBaseViewHolder) holder).userTextView.setText(post.getAuthor()); ((PostBaseViewHolder) holder).userTextView.setText(post.getAuthor());
} else { } else {
((PostBaseViewHolder) holder).subredditTextView.setText("r/" + post.getSubredditName()); ((PostBaseViewHolder) holder).subredditTextView.setText(post.getSubredditNamePrefixed());
((PostBaseViewHolder) holder).userTextView.setText(authorPrefixed); ((PostBaseViewHolder) holder).userTextView.setText(authorPrefixed);
} }
@ -659,28 +659,6 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
((PostBaseViewHolder) holder).nsfwTextView.setVisibility(View.VISIBLE); ((PostBaseViewHolder) holder).nsfwTextView.setVisibility(View.VISIBLE);
} }
if (post.isSpoiler()) {
((PostBaseViewHolder) holder).spoilerTextView.setVisibility(View.VISIBLE);
}
if (post.getFlair() != null && !post.getFlair().equals("")) {
if (mHidePostFlair) {
((PostBaseViewHolder) holder).flairTextView.setVisibility(View.GONE);
} else {
((PostBaseViewHolder) holder).flairTextView.setVisibility(View.VISIBLE);
Utils.setHTMLWithImageToTextView(((PostBaseViewHolder) holder).flairTextView, post.getFlair(), false);
}
}
if (post.getNAwards() > 0 && !mHideTheNumberOfAwards) {
((PostBaseViewHolder) holder).awardsTextView.setVisibility(View.VISIBLE);
if (post.getNAwards() == 1) {
((PostBaseViewHolder) holder).awardsTextView.setText(mActivity.getString(R.string.one_award));
} else {
((PostBaseViewHolder) holder).awardsTextView.setText(mActivity.getString(R.string.n_awards, post.getNAwards()));
}
}
switch (post.getVoteType()) { switch (post.getVoteType()) {
case 1: case 1:
//Upvoted //Upvoted
@ -844,7 +822,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_outline_video_24dp); ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_outline_video_24dp);
((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE); ((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
} else { } else {
if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler))) { if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mAutoplay && mAutoplayNsfwVideos)))) {
((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE); ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setVisibility(View.VISIBLE);
((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_image_24dp); ((PostWithPreviewTypeViewHolder) holder).noPreviewLinkImageView.setImageResource(R.drawable.ic_image_24dp);
((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE); ((PostWithPreviewTypeViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
@ -904,10 +882,10 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
} }
((PostBaseGalleryTypeViewHolder) holder).adapter.setGalleryImages(post.getGallery()); ((PostBaseGalleryTypeViewHolder) holder).adapter.setGalleryImages(post.getGallery());
((PostBaseGalleryTypeViewHolder) holder).adapter.setBlurImage( ((PostBaseGalleryTypeViewHolder) holder).adapter.setBlurImage(
(post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())) || (post.isSpoiler() && mNeedBlurSpoiler)); (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())));
} }
} else if (holder instanceof PostTextTypeViewHolder) { } else if (holder instanceof PostTextTypeViewHolder) {
if (!mHideTextPostContent && !post.isSpoiler() && post.getSelfTextPlainTrimmed() != null && !post.getSelfTextPlainTrimmed().equals("")) { if (!mHideTextPostContent && post.getSelfTextPlainTrimmed() != null && !post.getSelfTextPlainTrimmed().equals("")) {
((PostTextTypeViewHolder) holder).contentTextView.setVisibility(View.VISIBLE); ((PostTextTypeViewHolder) holder).contentTextView.setVisibility(View.VISIBLE);
if (post.isRead()) { if (post.isRead()) {
((PostTextTypeViewHolder) holder).contentTextView.setTextColor(mReadPostContentColor); ((PostTextTypeViewHolder) holder).contentTextView.setTextColor(mReadPostContentColor);
@ -1035,7 +1013,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_outline_video_24dp); ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_outline_video_24dp);
((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE); ((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
} else { } else {
if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler))) { if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mAutoplay && mAutoplayNsfwVideos)))) {
((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setVisibility(View.VISIBLE); ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setVisibility(View.VISIBLE);
((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_image_24dp); ((PostCard2WithPreviewViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_image_24dp);
((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE); ((PostCard2WithPreviewViewHolder) holder).videoOrGifIndicatorImageView.setVisibility(View.GONE);
@ -1078,7 +1056,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
} }
} else if (holder instanceof PostCard2TextTypeViewHolder) { } else if (holder instanceof PostCard2TextTypeViewHolder) {
if (!mHideTextPostContent && !post.isSpoiler() && post.getSelfTextPlainTrimmed() != null && !post.getSelfTextPlainTrimmed().equals("")) { if (!mHideTextPostContent && post.getSelfTextPlainTrimmed() != null && !post.getSelfTextPlainTrimmed().equals("")) {
((PostCard2TextTypeViewHolder) holder).contentTextView.setVisibility(View.VISIBLE); ((PostCard2TextTypeViewHolder) holder).contentTextView.setVisibility(View.VISIBLE);
if (post.isRead()) { if (post.isRead()) {
((PostCard2TextTypeViewHolder) holder).contentTextView.setTextColor(mReadPostContentColor); ((PostCard2TextTypeViewHolder) holder).contentTextView.setTextColor(mReadPostContentColor);
@ -1099,13 +1077,10 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
} }
final String subredditNamePrefixed = post.getSubredditNamePrefixed(); final String subredditNamePrefixed = post.getSubredditNamePrefixed();
String subredditName = subredditNamePrefixed.substring(2); String subredditName = subredditNamePrefixed.substring(2);
String authorPrefixed = "u/" + post.getAuthor(); String authorPrefixed = post.getAuthorNamePrefixed();
final String title = post.getTitle(); final String title = post.getTitle();
int voteType = post.getVoteType(); int voteType = post.getVoteType();
boolean nsfw = post.isNSFW(); boolean nsfw = post.isNSFW();
boolean spoiler = post.isSpoiler();
String flair = post.getFlair();
int nAwards = post.getNAwards();
boolean isArchived = post.isArchived(); boolean isArchived = post.isArchived();
if (mDisplaySubredditName) { if (mDisplaySubredditName) {
@ -1263,28 +1238,6 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
((PostCompactBaseViewHolder) holder).nsfwTextView.setVisibility(View.VISIBLE); ((PostCompactBaseViewHolder) holder).nsfwTextView.setVisibility(View.VISIBLE);
} }
if (spoiler) {
((PostCompactBaseViewHolder) holder).spoilerTextView.setVisibility(View.VISIBLE);
}
if (flair != null && !flair.equals("")) {
if (mHidePostFlair) {
((PostCompactBaseViewHolder) holder).flairTextView.setVisibility(View.GONE);
} else {
((PostCompactBaseViewHolder) holder).flairTextView.setVisibility(View.VISIBLE);
Utils.setHTMLWithImageToTextView(((PostCompactBaseViewHolder) holder).flairTextView, flair, false);
}
}
if (nAwards > 0 && !mHideTheNumberOfAwards) {
((PostCompactBaseViewHolder) holder).awardsTextView.setVisibility(View.VISIBLE);
if (nAwards == 1) {
((PostCompactBaseViewHolder) holder).awardsTextView.setText(mActivity.getString(R.string.one_award));
} else {
((PostCompactBaseViewHolder) holder).awardsTextView.setText(mActivity.getString(R.string.n_awards, nAwards));
}
}
switch (voteType) { switch (voteType) {
case 1: case 1:
//Upvoted //Upvoted
@ -1469,7 +1422,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
break; break;
} }
case Post.GIF_TYPE: { case Post.GIF_TYPE: {
if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler))) { if (post.getPostType() == Post.GIF_TYPE && ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(mAutoplay && mAutoplayNsfwVideos)) )) {
((PostGalleryViewHolder) holder).noPreviewImageView.setVisibility(View.VISIBLE); ((PostGalleryViewHolder) holder).noPreviewImageView.setVisibility(View.VISIBLE);
((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_image_24dp); ((PostGalleryViewHolder) holder).noPreviewImageView.setImageResource(R.drawable.ic_image_24dp);
} else { } else {
@ -1605,7 +1558,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
} }
((PostGalleryBaseGalleryTypeViewHolder) holder).adapter.setGalleryImages(post.getGallery()); ((PostGalleryBaseGalleryTypeViewHolder) holder).adapter.setGalleryImages(post.getGallery());
((PostGalleryBaseGalleryTypeViewHolder) holder).adapter.setBlurImage( ((PostGalleryBaseGalleryTypeViewHolder) holder).adapter.setBlurImage(
(post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())) || (post.isSpoiler() && mNeedBlurSpoiler)); (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())));
} }
} }
} }
@ -1642,7 +1595,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
Post.Preview preview = ((PostWithPreviewTypeViewHolder) holder).preview; Post.Preview preview = ((PostWithPreviewTypeViewHolder) holder).preview;
if (preview != null) { if (preview != null) {
String url; String url;
boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler); boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos));
if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) { if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) {
url = post.getUrl(); url = post.getUrl();
} else { } else {
@ -1669,7 +1622,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
RequestBuilder<Drawable> imageRequestBuilder = mGlide.load(postCompactThumbnailPreviewUrl) RequestBuilder<Drawable> imageRequestBuilder = mGlide.load(postCompactThumbnailPreviewUrl)
.error(R.drawable.ic_error_outline_black_24dp).listener(((PostCompactBaseViewHolder) holder).requestListener); .error(R.drawable.ic_error_outline_black_24dp).listener(((PostCompactBaseViewHolder) holder).requestListener);
if ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit())) || (post.isSpoiler() && mNeedBlurSpoiler)) { if ((post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()))) {
imageRequestBuilder imageRequestBuilder
.transform(new BlurTransformation(50, 2)).into(((PostCompactBaseViewHolder) holder).imageView); .transform(new BlurTransformation(50, 2)).into(((PostCompactBaseViewHolder) holder).imageView);
} else { } else {
@ -1681,7 +1634,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
Post.Preview preview = ((PostGalleryViewHolder) holder).preview; Post.Preview preview = ((PostGalleryViewHolder) holder).preview;
if (preview != null) { if (preview != null) {
String url; String url;
boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos)) || post.isSpoiler() && mNeedBlurSpoiler; boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos));
if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) { if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) {
url = post.getUrl(); url = post.getUrl();
} else { } else {
@ -1701,7 +1654,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
Post.Preview preview = ((PostCard2WithPreviewViewHolder) holder).preview; Post.Preview preview = ((PostCard2WithPreviewViewHolder) holder).preview;
if (preview != null) { if (preview != null) {
String url; String url;
boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos)) || (post.isSpoiler() && mNeedBlurSpoiler); boolean blurImage = (post.isNSFW() && mNeedBlurNsfw && !(mDoNotBlurNsfwInNsfwSubreddits && mFragment != null && mFragment.getIsNsfwSubreddit()) && !(post.getPostType() == Post.GIF_TYPE && mAutoplay && mAutoplayNsfwVideos));
if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) { if (post.getPostType() == Post.GIF_TYPE && mAutoplay && !blurImage) {
url = post.getUrl(); url = post.getUrl();
} else { } else {
@ -2360,6 +2313,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
canStartActivity = false; canStartActivity = false;
Intent intent = new Intent(mActivity, ViewUserDetailActivity.class); Intent intent = new Intent(mActivity, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, post.getAuthor()); intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, post.getAuthor());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, post.getAuthorNamePrefixed());
mActivity.startActivity(intent); mActivity.startActivity(intent);
}); });
@ -2376,6 +2330,8 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class); Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY,
post.getSubredditName()); post.getSubredditName());
intent.putExtra(ViewSubredditDetailActivity.EXTRA_COMMUNITY_FULL_NAME_KEY,
post.getSubredditNamePrefixed());
mActivity.startActivity(intent); mActivity.startActivity(intent);
} }
} }
@ -2395,6 +2351,8 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class); Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY,
post.getSubredditName()); post.getSubredditName());
intent.putExtra(ViewSubredditDetailActivity.EXTRA_COMMUNITY_FULL_NAME_KEY,
post.getSubredditNamePrefixed());
mActivity.startActivity(intent); mActivity.startActivity(intent);
} }
} }
@ -2424,17 +2382,6 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
mCallback.typeChipClicked(post.getPostType()); mCallback.typeChipClicked(post.getPostType());
} }
}); });
flairTextView.setOnClickListener(view -> {
int position = getBindingAdapterPosition();
if (position < 0) {
return;
}
Post post = getItem(position);
if (post != null) {
mCallback.flairChipClicked(post.getFlair());
}
});
} }
upvoteButton.setOnClickListener(view -> { upvoteButton.setOnClickListener(view -> {
@ -2463,21 +2410,21 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
int previousScoreTextViewColor = scoreTextView.getCurrentTextColor(); int previousScoreTextViewColor = scoreTextView.getCurrentTextColor();
int previousVoteType = post.getVoteType(); int previousVoteType = post.getVoteType();
String newVoteType; int newVoteType;
downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
if (previousVoteType != 1) { if (previousVoteType != 1) {
//Not upvoted before //Not upvoted before
post.setVoteType(1); post.setVoteType(1);
newVoteType = APIUtils.DIR_UPVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UPVOTE);
upvoteButton upvoteButton
.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); .setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mUpvotedColor); scoreTextView.setTextColor(mUpvotedColor);
} else { } else {
//Upvoted before //Upvoted before
post.setVoteType(0); post.setVoteType(0);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mPostIconAndInfoColor); scoreTextView.setTextColor(mPostIconAndInfoColor);
} }
@ -2490,7 +2437,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_UPVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_UPVOTE)) {
post.setVoteType(1); post.setVoteType(1);
if (currentPosition == position) { if (currentPosition == position) {
upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
@ -2529,7 +2476,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post)); EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post));
} }
}, post.getFullName(), newVoteType, getBindingAdapterPosition()); }, post.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });
@ -2559,21 +2506,21 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
int previousScoreTextViewColor = scoreTextView.getCurrentTextColor(); int previousScoreTextViewColor = scoreTextView.getCurrentTextColor();
int previousVoteType = post.getVoteType(); int previousVoteType = post.getVoteType();
String newVoteType; int newVoteType;
upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
if (previousVoteType != -1) { if (previousVoteType != -1) {
//Not downvoted before //Not downvoted before
post.setVoteType(-1); post.setVoteType(-1);
newVoteType = APIUtils.DIR_DOWNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_DOWNVOTE);
downvoteButton downvoteButton
.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); .setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mDownvotedColor); scoreTextView.setTextColor(mDownvotedColor);
} else { } else {
//Downvoted before //Downvoted before
post.setVoteType(0); post.setVoteType(0);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mPostIconAndInfoColor); scoreTextView.setTextColor(mPostIconAndInfoColor);
} }
@ -2586,7 +2533,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_DOWNVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_DOWNVOTE)) {
post.setVoteType(-1); post.setVoteType(-1);
if (currentPosition == position) { if (currentPosition == position) {
downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
@ -2625,7 +2572,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post)); EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post));
} }
}, post.getFullName(), newVoteType, getBindingAdapterPosition()); }, post.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });
@ -3743,10 +3690,13 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class); Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY,
post.getSubredditName()); post.getSubredditName());
intent.putExtra(ViewSubredditDetailActivity.EXTRA_COMMUNITY_FULL_NAME_KEY,
post.getSubredditNamePrefixed());
mActivity.startActivity(intent); mActivity.startActivity(intent);
} else if (!post.isAuthorDeleted()) { } else if (!post.isAuthorDeleted()) {
Intent intent = new Intent(mActivity, ViewUserDetailActivity.class); Intent intent = new Intent(mActivity, ViewUserDetailActivity.class);
intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, post.getAuthor()); intent.putExtra(ViewUserDetailActivity.EXTRA_USER_NAME_KEY, post.getAuthor());
intent.putExtra(ViewUserDetailActivity.EXTRA_QUALIFIED_USER_NAME_KEY, post.getAuthorNamePrefixed());
mActivity.startActivity(intent); mActivity.startActivity(intent);
} }
} }
@ -3776,16 +3726,6 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
} }
}); });
flairTextView.setOnClickListener(view -> {
int position = getBindingAdapterPosition();
if (position < 0) {
return;
}
Post post = getItem(position);
if (post != null && !(mActivity instanceof FilteredPostsActivity)) {
mCallback.flairChipClicked(post.getFlair());
}
});
imageView.setOnClickListener(view -> { imageView.setOnClickListener(view -> {
int position = getBindingAdapterPosition(); int position = getBindingAdapterPosition();
@ -3829,21 +3769,21 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
int previousScoreTextViewColor = scoreTextView.getCurrentTextColor(); int previousScoreTextViewColor = scoreTextView.getCurrentTextColor();
int previousVoteType = post.getVoteType(); int previousVoteType = post.getVoteType();
String newVoteType; int newVoteType;
downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
if (previousVoteType != 1) { if (previousVoteType != 1) {
//Not upvoted before //Not upvoted before
post.setVoteType(1); post.setVoteType(1);
newVoteType = APIUtils.DIR_UPVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UPVOTE);
upvoteButton upvoteButton
.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); .setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mUpvotedColor); scoreTextView.setTextColor(mUpvotedColor);
} else { } else {
//Upvoted before //Upvoted before
post.setVoteType(0); post.setVoteType(0);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mPostIconAndInfoColor); scoreTextView.setTextColor(mPostIconAndInfoColor);
} }
@ -3856,7 +3796,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_UPVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_UPVOTE)) {
post.setVoteType(1); post.setVoteType(1);
if (currentPosition == position) { if (currentPosition == position) {
upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mUpvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
@ -3895,7 +3835,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post)); EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post));
} }
}, post.getFullName(), newVoteType, getBindingAdapterPosition()); }, post.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });
@ -3925,21 +3865,21 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
int previousScoreTextViewColor = scoreTextView.getCurrentTextColor(); int previousScoreTextViewColor = scoreTextView.getCurrentTextColor();
int previousVoteType = post.getVoteType(); int previousVoteType = post.getVoteType();
String newVoteType; int newVoteType;
upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); upvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
if (previousVoteType != -1) { if (previousVoteType != -1) {
//Not downvoted before //Not downvoted before
post.setVoteType(-1); post.setVoteType(-1);
newVoteType = APIUtils.DIR_DOWNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_DOWNVOTE);
downvoteButton downvoteButton
.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); .setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mDownvotedColor); scoreTextView.setTextColor(mDownvotedColor);
} else { } else {
//Downvoted before //Downvoted before
post.setVoteType(0); post.setVoteType(0);
newVoteType = APIUtils.DIR_UNVOTE; newVoteType = Integer.parseInt(APIUtils.DIR_UNVOTE);
downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mPostIconAndInfoColor, android.graphics.PorterDuff.Mode.SRC_IN);
scoreTextView.setTextColor(mPostIconAndInfoColor); scoreTextView.setTextColor(mPostIconAndInfoColor);
} }
@ -3952,7 +3892,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
@Override @Override
public void onVoteThingSuccess(int position1) { public void onVoteThingSuccess(int position1) {
int currentPosition = getBindingAdapterPosition(); int currentPosition = getBindingAdapterPosition();
if (newVoteType.equals(APIUtils.DIR_DOWNVOTE)) { if (newVoteType == Integer.parseInt(APIUtils.DIR_DOWNVOTE)) {
post.setVoteType(-1); post.setVoteType(-1);
if (currentPosition == position) { if (currentPosition == position) {
downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN); downvoteButton.setColorFilter(mDownvotedColor, android.graphics.PorterDuff.Mode.SRC_IN);
@ -3992,7 +3932,7 @@ public class PostRecyclerViewAdapter extends PagingDataAdapter<Post, RecyclerVie
EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post)); EventBus.getDefault().post(new PostUpdateEventToPostDetailFragment(post));
} }
}, post.getFullName(), newVoteType, getBindingAdapterPosition()); }, post.getId(), newVoteType, getBindingAdapterPosition());
} }
}); });

View File

@ -27,6 +27,7 @@ import java.util.concurrent.Executor;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation; import jp.wasabeef.glide.transformations.RoundedCornersTransformation;
import eu.toldi.infinityforlemmy.NetworkState; import eu.toldi.infinityforlemmy.NetworkState;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
@ -46,7 +47,7 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
private static final DiffUtil.ItemCallback<SubredditData> DIFF_CALLBACK = new DiffUtil.ItemCallback<SubredditData>() { private static final DiffUtil.ItemCallback<SubredditData> DIFF_CALLBACK = new DiffUtil.ItemCallback<SubredditData>() {
@Override @Override
public boolean areItemsTheSame(@NonNull SubredditData oldItem, @NonNull SubredditData newItem) { public boolean areItemsTheSame(@NonNull SubredditData oldItem, @NonNull SubredditData newItem) {
return oldItem.getId().equals(newItem.getId()); return oldItem.getId() == newItem.getId();
} }
@Override @Override
@ -124,7 +125,7 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
if (isMultiSelection) { if (isMultiSelection) {
((DataViewHolder) holder).checkBox.performClick(); ((DataViewHolder) holder).checkBox.performClick();
} else { } else {
callback.subredditSelected(subredditData.getName(), subredditData.getIconUrl()); callback.subredditSelected(subredditData.getName(), LemmyUtils.actorID2FullName(subredditData.getActorId()), subredditData.getIconUrl());
} }
}); });
@ -251,7 +252,7 @@ public class SubredditListingRecyclerViewAdapter extends PagedListAdapter<Subred
public interface Callback { public interface Callback {
void retryLoadingMore(); void retryLoadingMore();
void subredditSelected(String subredditName, String iconUrl); void subredditSelected(String subredditName, String communityFullName,String iconUrl);
} }
class DataViewHolder extends RecyclerView.ViewHolder { class DataViewHolder extends RecyclerView.ViewHolder {

View File

@ -148,20 +148,18 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) { public void onBindViewHolder(@NonNull final RecyclerView.ViewHolder viewHolder, int i) {
if (viewHolder instanceof SubredditViewHolder) { if (viewHolder instanceof SubredditViewHolder) {
String name; String name;
String fullname = "";
String iconUrl; String iconUrl;
if (hasClearSelectionRow && viewHolder.getBindingAdapterPosition() == 0) { if (hasClearSelectionRow && viewHolder.getBindingAdapterPosition() == 0) {
((SubredditViewHolder) viewHolder).subredditNameTextView.setText(R.string.all_subreddits); ((SubredditViewHolder) viewHolder).subredditNameTextView.setText(R.string.all_subreddits);
((SubredditViewHolder) viewHolder).favoriteImageView.setVisibility(View.GONE);
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(null, null, false)); viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(null, null, false));
return; return;
} else if (itemClickListener != null && !hasClearSelectionRow && viewHolder.getBindingAdapterPosition() == 0) { } else if (itemClickListener != null && !hasClearSelectionRow && viewHolder.getBindingAdapterPosition() == 0) {
((SubredditViewHolder) viewHolder).favoriteImageView.setVisibility(View.GONE);
name = username; name = username;
iconUrl = userIconUrl; iconUrl = userIconUrl;
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(name, iconUrl, true)); viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(name, iconUrl, true));
} else if (hasClearSelectionRow && viewHolder.getBindingAdapterPosition() == 1) { } else if (hasClearSelectionRow && viewHolder.getBindingAdapterPosition() == 1) {
((SubredditViewHolder) viewHolder).favoriteImageView.setVisibility(View.GONE);
name = username; name = username;
iconUrl = userIconUrl; iconUrl = userIconUrl;
if (itemClickListener != null) { if (itemClickListener != null) {
@ -183,67 +181,8 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
} }
name = mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).getName(); name = mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).getName();
fullname = mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).getQualified_name();
iconUrl = mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).getIconUrl(); iconUrl = mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).getIconUrl();
if(mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).isFavorite()) {
((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
} else {
((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
((SubredditViewHolder) viewHolder).favoriteImageView.setOnClickListener(view -> {
if(mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).isFavorite()) {
((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).setFavorite(false);
FavoriteThing.unfavoriteSubreddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, accessToken,
mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset),
new FavoriteThing.FavoriteThingListener() {
@Override
public void success() {
int position = viewHolder.getBindingAdapterPosition() - offset;
if(position >= 0 && mSubscribedSubredditData.size() > position) {
mSubscribedSubredditData.get(position).setFavorite(false);
}
((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_unfavorite_failed, Toast.LENGTH_SHORT).show();
int position = viewHolder.getBindingAdapterPosition() - offset;
if(position >= 0 && mSubscribedSubredditData.size() > position) {
mSubscribedSubredditData.get(position).setFavorite(true);
}
((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
});
} else {
((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).setFavorite(true);
FavoriteThing.favoriteSubreddit(mExecutor, new Handler(), mOauthRetrofit,
mRedditDataRoomDatabase, accessToken,
mSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset),
new FavoriteThing.FavoriteThingListener() {
@Override
public void success() {
int position = viewHolder.getBindingAdapterPosition() - offset;
if(position >= 0 && mSubscribedSubredditData.size() > position) {
mSubscribedSubredditData.get(position).setFavorite(true);
}
((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_favorite_failed, Toast.LENGTH_SHORT).show();
int position = viewHolder.getBindingAdapterPosition() - offset;
if(position >= 0 && mSubscribedSubredditData.size() > position) {
mSubscribedSubredditData.get(position).setFavorite(false);
}
((SubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
});
}
});
if (itemClickListener != null) { if (itemClickListener != null) {
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(name, iconUrl, false)); viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(name, iconUrl, false));
@ -251,9 +190,12 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
} }
if (itemClickListener == null) { if (itemClickListener == null) {
String finalFullname = fullname;
viewHolder.itemView.setOnClickListener(view -> { viewHolder.itemView.setOnClickListener(view -> {
Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class); Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, name); intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, name);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_COMMUNITY_FULL_NAME_KEY,
finalFullname);
mActivity.startActivity(intent); mActivity.startActivity(intent);
}); });
} }
@ -283,65 +225,6 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
} }
String name = mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).getName(); String name = mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).getName();
String iconUrl = mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).getIconUrl(); String iconUrl = mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).getIconUrl();
if(mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).isFavorite()) {
((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
} else {
((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setOnClickListener(view -> {
if(mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).isFavorite()) {
((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).setFavorite(false);
FavoriteThing.unfavoriteSubreddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, accessToken,
mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset),
new FavoriteThing.FavoriteThingListener() {
@Override
public void success() {
int position = viewHolder.getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteSubscribedSubredditData.size() > position) {
mFavoriteSubscribedSubredditData.get(position).setFavorite(false);
}
((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_unfavorite_failed, Toast.LENGTH_SHORT).show();
int position = viewHolder.getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteSubscribedSubredditData.size() > position) {
mFavoriteSubscribedSubredditData.get(position).setFavorite(true);
}
((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
});
} else {
((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset).setFavorite(true);
FavoriteThing.favoriteSubreddit(mExecutor, new Handler(), mOauthRetrofit, mRedditDataRoomDatabase, accessToken,
mFavoriteSubscribedSubredditData.get(viewHolder.getBindingAdapterPosition() - offset),
new FavoriteThing.FavoriteThingListener() {
@Override
public void success() {
int position = viewHolder.getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteSubscribedSubredditData.size() > position) {
mFavoriteSubscribedSubredditData.get(position).setFavorite(true);
}
((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_24dp);
}
@Override
public void failed() {
Toast.makeText(mActivity, R.string.thing_favorite_failed, Toast.LENGTH_SHORT).show();
int position = viewHolder.getBindingAdapterPosition() - 1;
if(position >= 0 && mFavoriteSubscribedSubredditData.size() > position) {
mFavoriteSubscribedSubredditData.get(position).setFavorite(false);
}
((FavoriteSubredditViewHolder) viewHolder).favoriteImageView.setImageResource(R.drawable.ic_favorite_border_24dp);
}
});
}
});
if (itemClickListener != null) { if (itemClickListener != null) {
viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(name, iconUrl, false)); viewHolder.itemView.setOnClickListener(view -> itemClickListener.onClick(name, iconUrl, false));
@ -402,7 +285,6 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) { public void onViewRecycled(@NonNull RecyclerView.ViewHolder holder) {
if(holder instanceof SubredditViewHolder) { if(holder instanceof SubredditViewHolder) {
glide.clear(((SubredditViewHolder) holder).iconGifImageView); glide.clear(((SubredditViewHolder) holder).iconGifImageView);
((SubredditViewHolder) holder).favoriteImageView.setVisibility(View.VISIBLE);
} else if (holder instanceof FavoriteSubredditViewHolder) { } else if (holder instanceof FavoriteSubredditViewHolder) {
glide.clear(((FavoriteSubredditViewHolder) holder).iconGifImageView); glide.clear(((FavoriteSubredditViewHolder) holder).iconGifImageView);
} }
@ -477,8 +359,6 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
GifImageView iconGifImageView; GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing) @BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView subredditNameTextView; TextView subredditNameTextView;
@BindView(R.id.favorite_image_view_item_subscribed_thing)
ImageView favoriteImageView;
SubredditViewHolder(View itemView) { SubredditViewHolder(View itemView) {
super(itemView); super(itemView);
@ -495,8 +375,6 @@ public class SubscribedSubredditsRecyclerViewAdapter extends RecyclerView.Adapte
GifImageView iconGifImageView; GifImageView iconGifImageView;
@BindView(R.id.thing_name_text_view_item_subscribed_thing) @BindView(R.id.thing_name_text_view_item_subscribed_thing)
TextView subredditNameTextView; TextView subredditNameTextView;
@BindView(R.id.favorite_image_view_item_subscribed_thing)
ImageView favoriteImageView;
FavoriteSubredditViewHolder(View itemView) { FavoriteSubredditViewHolder(View itemView) {
super(itemView); super(itemView);

View File

@ -185,10 +185,9 @@ public class HeaderSectionRecyclerViewAdapter extends RecyclerView.Adapter<Recyc
return false; return false;
} }
public void updateAccountInfo(String profileImageUrl, String bannerImageUrl, int karma) { public void updateAccountInfo(String profileImageUrl, String bannerImageUrl) {
this.profileImageUrl = profileImageUrl; this.profileImageUrl = profileImageUrl;
this.bannerImageUrl = bannerImageUrl; this.bannerImageUrl = bannerImageUrl;
this.karma = karma;
notifyItemChanged(0); notifyItemChanged(0);
} }

View File

@ -103,8 +103,8 @@ public class NavigationDrawerRecyclerViewMergedAdapter {
headerSectionRecyclerViewAdapter.closeAccountSectionWithoutChangeIconResource(checkIsInMainPage); headerSectionRecyclerViewAdapter.closeAccountSectionWithoutChangeIconResource(checkIsInMainPage);
} }
public void updateAccountInfo(String profileImageUrl, String bannerImageUrl, int karma) { public void updateAccountInfo(String profileImageUrl, String bannerImageUrl) {
headerSectionRecyclerViewAdapter.updateAccountInfo(profileImageUrl, bannerImageUrl, karma); headerSectionRecyclerViewAdapter.updateAccountInfo(profileImageUrl, bannerImageUrl);
} }
public void setRequireAuthToAccountSection(boolean requireAuthToAccountSection) { public void setRequireAuthToAccountSection(boolean requireAuthToAccountSection) {

View File

@ -0,0 +1,58 @@
package eu.toldi.infinityforlemmy.apis;
import com.google.common.util.concurrent.ListenableFuture;
import eu.toldi.infinityforlemmy.dto.AccountLoginDTO;
import eu.toldi.infinityforlemmy.dto.VoteDTO;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.Query;
public interface LemmyAPI {
@Headers("Content-Type: application/json")
@POST("api/v3/user/login")
Call<String> userLogin(@Body AccountLoginDTO params);
@GET("api/v3/user")
Call<String> userInfo(@Query("username") String username,@Query("auth") String access_token);
@GET("api/v3/community")
Call<String> communityInfo(@Query("name") String name,@Query("auth") String access_token);
@GET("api/v3/user")
ListenableFuture<Response<String>> getUserPosts(
@Query("username") String username,
@Query("sort") String sort,
@Query("page") Integer page,
@Query("limit") Integer limit,
@Query("auth") String access_token);
@GET("api/v3/community/list")
Call<String> listCommunities(
@Query("type_") String type_,
@Query("sort") String sort,
@Query("page") Integer page,
@Query("limit") Integer limit,
@Query("auth") String auth
);
@GET("api/v3/post/list")
ListenableFuture<Response<String>> getPosts(
@Query("type_") String type_,
@Query("sort") String sort,
@Query("page") Integer page,
@Query("limit") Integer limit,
@Query("community_id") Integer community_id,
@Query("community_name") String community_name,
@Query("saved_only") Boolean saved_only,
@Query("auth") String auth
);
@Headers("Content-Type: application/json")
@POST("api/v3/post/like")
Call<String> postLike(@Body VoteDTO params);
}

View File

@ -10,12 +10,12 @@ import eu.toldi.infinityforlemmy.account.AccountDao;
public class ParseAndInsertNewAccount { public class ParseAndInsertNewAccount {
public static void parseAndInsertNewAccount(Executor executor, Handler handler, String username, public static void parseAndInsertNewAccount(Executor executor, Handler handler, String username,
String accessToken, String refreshToken, String profileImageUrl, String display_name,String accessToken, String profileImageUrl,
String bannerImageUrl, int karma, String code, AccountDao accountDao, String bannerImageUrl, String code,String instance, AccountDao accountDao,
ParseAndInsertAccountListener parseAndInsertAccountListener) { ParseAndInsertAccountListener parseAndInsertAccountListener) {
executor.execute(() -> { executor.execute(() -> {
Account account = new Account(username, accessToken, refreshToken, code, profileImageUrl, Account account = new Account(username,display_name, accessToken, code, profileImageUrl,
bannerImageUrl, karma, true); bannerImageUrl, true,instance);
accountDao.markAllAccountsNonCurrent(); accountDao.markAllAccountsNonCurrent();
accountDao.insert(account); accountDao.insert(account);

View File

@ -5,12 +5,13 @@ import android.os.Handler;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.account.Account; import eu.toldi.infinityforlemmy.account.Account;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils; import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
public class SwitchAccount { public class SwitchAccount {
public static void switchAccount(RedditDataRoomDatabase redditDataRoomDatabase, public static void switchAccount(RedditDataRoomDatabase redditDataRoomDatabase,RetrofitHolder retrofitHolder,
SharedPreferences currentAccountSharedPreferences, Executor executor, SharedPreferences currentAccountSharedPreferences, Executor executor,
Handler handler, String newAccountName, Handler handler, String newAccountName,
SwitchAccountListener switchAccountListener) { SwitchAccountListener switchAccountListener) {
@ -21,7 +22,9 @@ public class SwitchAccount {
currentAccountSharedPreferences.edit() currentAccountSharedPreferences.edit()
.putString(SharedPreferencesUtils.ACCESS_TOKEN, account.getAccessToken()) .putString(SharedPreferencesUtils.ACCESS_TOKEN, account.getAccessToken())
.putString(SharedPreferencesUtils.ACCOUNT_NAME, account.getAccountName()) .putString(SharedPreferencesUtils.ACCOUNT_NAME, account.getAccountName())
.putString(SharedPreferencesUtils.ACCOUNT_INSTANCE,account.getInstance_url())
.putString(SharedPreferencesUtils.ACCOUNT_IMAGE_URL, account.getProfileImageUrl()).apply(); .putString(SharedPreferencesUtils.ACCOUNT_IMAGE_URL, account.getProfileImageUrl()).apply();
retrofitHolder.setBaseURL(account.getInstance_url());
handler.post(() -> switchAccountListener.switched(account)); handler.post(() -> switchAccountListener.switched(account));
}); });

View File

@ -28,6 +28,7 @@ import eu.toldi.infinityforlemmy.FetchFlairs;
import eu.toldi.infinityforlemmy.Flair; import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.activities.BaseActivity; import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.adapters.FlairBottomSheetRecyclerViewAdapter; import eu.toldi.infinityforlemmy.adapters.FlairBottomSheetRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
@ -56,7 +57,7 @@ public class FlairBottomSheetFragment extends LandscapeExpandedBottomSheetDialog
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
CustomThemeWrapper mCustomThemeWrapper; CustomThemeWrapper mCustomThemeWrapper;
private String mAccessToken; private String mAccessToken;

View File

@ -69,7 +69,7 @@ public class PostCommentSortTypeBottomSheetFragment extends LandscapeExpandedRou
ButterKnife.bind(this, rootView); ButterKnife.bind(this, rootView);
SortType.Type currentSortType = (SortType.Type) getArguments().getSerializable(EXTRA_CURRENT_SORT_TYPE); SortType.Type currentSortType = (SortType.Type) getArguments().getSerializable(EXTRA_CURRENT_SORT_TYPE);
if (currentSortType.equals(SortType.Type.BEST) || currentSortType.equals(SortType.Type.CONFIDENCE)) { if (currentSortType.equals(SortType.Type.ACTIVE) || currentSortType.equals(SortType.Type.CONFIDENCE)) {
confidenceTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(confidenceTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null); confidenceTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(confidenceTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
} else if (currentSortType.equals(SortType.Type.TOP)) { } else if (currentSortType.equals(SortType.Type.TOP)) {
topTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(topTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null); topTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(topTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);

View File

@ -73,13 +73,13 @@ public class SortTypeBottomSheetFragment extends LandscapeExpandedRoundedBottomS
bestTypeTextView.setVisibility(View.GONE); bestTypeTextView.setVisibility(View.GONE);
} else { } else {
bestTypeTextView.setOnClickListener(view -> { bestTypeTextView.setOnClickListener(view -> {
((SortTypeSelectionCallback) activity).sortTypeSelected(new SortType(SortType.Type.BEST)); ((SortTypeSelectionCallback) activity).sortTypeSelected(new SortType(SortType.Type.ACTIVE));
dismiss(); dismiss();
}); });
} }
String currentSortType = getArguments().getString(EXTRA_CURRENT_SORT_TYPE); String currentSortType = getArguments().getString(EXTRA_CURRENT_SORT_TYPE);
if (currentSortType.equals(SortType.Type.BEST.fullName)) { if (currentSortType.equals(SortType.Type.ACTIVE.fullName)) {
bestTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(bestTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null); bestTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(bestTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);
} else if (currentSortType.equals(SortType.Type.HOT.fullName)) { } else 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); hotTypeTextView.setCompoundDrawablesRelativeWithIntrinsicBounds(hotTypeTextView.getCompoundDrawablesRelative()[0], null, AppCompatResources.getDrawable(activity, R.drawable.ic_round_check_circle_day_night_24dp), null);

View File

@ -26,7 +26,7 @@ public class Comment implements Parcelable {
return new Comment[size]; return new Comment[size];
} }
}; };
private String id; private int id;
private String fullName; private String fullName;
private String author; private String author;
private String authorFlair; private String authorFlair;
@ -60,7 +60,7 @@ public class Comment implements Parcelable {
private boolean loadMoreChildrenFailed; private boolean loadMoreChildrenFailed;
private long editedTimeMillis; private long editedTimeMillis;
public Comment(String id, String fullName, String author, String authorFlair, public Comment(int id, String fullName, String author, String authorFlair,
String authorFlairHTML, String linkAuthor, String authorFlairHTML, String linkAuthor,
long commentTimeMillis, String commentMarkdown, String commentRawText, long commentTimeMillis, String commentMarkdown, String commentRawText,
String linkId, String subredditName, String parentId, int score, String linkId, String subredditName, String parentId, int score,
@ -114,7 +114,7 @@ public class Comment implements Parcelable {
} }
protected Comment(Parcel in) { protected Comment(Parcel in) {
id = in.readString(); id = in.readInt();
fullName = in.readString(); fullName = in.readString();
author = in.readString(); author = in.readString();
authorFlair = in.readString(); authorFlair = in.readString();
@ -149,7 +149,7 @@ public class Comment implements Parcelable {
loadMoreChildrenFailed = in.readByte() != 0; loadMoreChildrenFailed = in.readByte() != 0;
} }
public String getId() { public int getId() {
return id; return id;
} }
@ -405,7 +405,7 @@ public class Comment implements Parcelable {
@Override @Override
public void writeToParcel(Parcel parcel, int i) { public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(id); parcel.writeInt(id);
parcel.writeString(fullName); parcel.writeString(fullName);
parcel.writeString(author); parcel.writeString(author);
parcel.writeString(authorFlair); parcel.writeString(authorFlair);

View File

@ -24,7 +24,7 @@ public class FetchRemovedComment {
FetchRemovedCommentListener listener) { FetchRemovedCommentListener listener) {
executor.execute(() -> { executor.execute(() -> {
try { try {
Response<String> response = retrofit.create(PushshiftAPI.class).getRemovedComment(comment.getId()).execute(); Response<String> response = retrofit.create(PushshiftAPI.class).getRemovedComment(String.valueOf(comment.getId())).execute();
if (response.isSuccessful()) { if (response.isSuccessful()) {
Comment removedComment = parseComment(response.body(), comment); Comment removedComment = parseComment(response.body(), comment);
handler.post(() -> { handler.post(() -> {

View File

@ -21,19 +21,19 @@ public class FetchRemovedCommentReveddit {
long postCreatedUtc, int nComments, FetchRemovedCommentListener listener) { long postCreatedUtc, int nComments, FetchRemovedCommentListener listener) {
executor.execute(() -> { executor.execute(() -> {
String parentIdWithoutPrefix = comment.getParentId().substring(3); String parentIdWithoutPrefix = comment.getParentId().substring(3);
String rootCommentId = parentIdWithoutPrefix.equals(comment.getLinkId()) ? comment.getId() : parentIdWithoutPrefix; String rootCommentId = parentIdWithoutPrefix.equals(comment.getLinkId()) ? String.valueOf(comment.getId()) : parentIdWithoutPrefix;
try { try {
Response<String> response = retrofit.create(RevedditAPI.class).getRemovedComments( Response<String> response = retrofit.create(RevedditAPI.class).getRemovedComments(
APIUtils.getRevedditHeader(), APIUtils.getRevedditHeader(),
comment.getLinkId(), comment.getLinkId(),
(comment.getCommentTimeMillis() / 1000) - 1, (comment.getCommentTimeMillis() / 1000) - 1,
rootCommentId, rootCommentId,
comment.getId(), String.valueOf(comment.getId()),
nComments, nComments,
postCreatedUtc / 1000, postCreatedUtc / 1000,
true).execute(); true).execute();
if (response.isSuccessful()) { if (response.isSuccessful()) {
Comment removedComment = parseRemovedComment(new JSONObject(response.body()).getJSONObject(comment.getId()), comment); Comment removedComment = parseRemovedComment(new JSONObject(response.body()).getJSONObject(String.valueOf(comment.getId())), comment);
handler.post(() -> { handler.post(() -> {
if (removedComment != null) { if (removedComment != null) {
listener.fetchSuccess(removedComment, comment); listener.fetchSuccess(removedComment, comment);

View File

@ -292,7 +292,7 @@ public class ParseComment {
voteType = singleCommentData.getBoolean(JSONUtils.LIKES_KEY) ? VOTE_TYPE_UPVOTE : VOTE_TYPE_DOWNVOTE; voteType = singleCommentData.getBoolean(JSONUtils.LIKES_KEY) ? VOTE_TYPE_UPVOTE : VOTE_TYPE_DOWNVOTE;
score -= voteType; score -= voteType;
} }
long submitTime = singleCommentData.getLong(JSONUtils.CREATED_UTC_KEY) * 1000; long submitTime = singleCommentData.getLong(JSONUtils.PUBLISHED) * 1000;
boolean scoreHidden = singleCommentData.getBoolean(JSONUtils.SCORE_HIDDEN_KEY); boolean scoreHidden = singleCommentData.getBoolean(JSONUtils.SCORE_HIDDEN_KEY);
boolean saved = singleCommentData.getBoolean(JSONUtils.SAVED_KEY); boolean saved = singleCommentData.getBoolean(JSONUtils.SAVED_KEY);
@ -306,7 +306,7 @@ public class ParseComment {
// this key can either be a bool (false) or a long (edited timestamp) // this key can either be a bool (false) or a long (edited timestamp)
long edited = singleCommentData.optLong(JSONUtils.EDITED_KEY) * 1000; long edited = singleCommentData.optLong(JSONUtils.EDITED_KEY) * 1000;
return new Comment(id, fullName, author, authorFlair, authorFlairHTMLBuilder.toString(), return new Comment(Integer.parseInt(id), fullName, author, authorFlair, authorFlairHTMLBuilder.toString(),
linkAuthor, submitTime, commentMarkdown, commentRawText, linkAuthor, submitTime, commentMarkdown, commentRawText,
linkId, subredditName, parentId, score, voteType, isSubmitter, distinguished, linkId, subredditName, parentId, score, voteType, isSubmitter, distinguished,
permalink, awardingsBuilder.toString(), depth, collapsed, hasReply, scoreHidden, saved, edited); permalink, awardingsBuilder.toString(), depth, collapsed, hasReply, scoreHidden, saved, edited);

View File

@ -0,0 +1,37 @@
package eu.toldi.infinityforlemmy.dto;
public class AccountLoginDTO {
private String username_or_email;
private String password;
private String totp_2fa_token;
public AccountLoginDTO(String username_or_email, String password, String totp_2fa_token) {
this.username_or_email = username_or_email;
this.password = password;
this.totp_2fa_token = totp_2fa_token;
}
public String getUsername_or_email() {
return username_or_email;
}
public void setUsername_or_email(String username_or_email) {
this.username_or_email = username_or_email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getTotp_2fa_token() {
return totp_2fa_token;
}
public void setTotp_2fa_token(String totp_2fa_token) {
this.totp_2fa_token = totp_2fa_token;
}
}

View File

@ -0,0 +1,26 @@
package eu.toldi.infinityforlemmy.dto;
public class VoteDTO {
private final int post_id;
private final int score;
private final String auth;
public VoteDTO(int post_id, int vote, String auth) {
this.post_id = post_id;
this.score = vote;
this.auth = auth;
}
public int getPost_id() {
return post_id;
}
public int getScore() {
return score;
}
public String getAccess_token() {
return auth;
}
}

View File

@ -43,6 +43,7 @@ import eu.toldi.infinityforlemmy.NetworkState;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface; import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.activities.BaseActivity; import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.adapters.CommentsListingRecyclerViewAdapter; import eu.toldi.infinityforlemmy.adapters.CommentsListingRecyclerViewAdapter;
@ -79,7 +80,7 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
CommentViewModel mCommentViewModel; CommentViewModel mCommentViewModel;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -294,7 +295,7 @@ public class CommentsListingFragment extends Fragment implements FragmentCommuni
CommentViewModel.Factory factory; CommentViewModel.Factory factory;
if (mAccessToken == null) { if (mAccessToken == null) {
factory = new CommentViewModel.Factory(mRetrofit, factory = new CommentViewModel.Factory(mRetrofit.getRetrofit(),
resources.getConfiguration().locale, null, username, sortType, resources.getConfiguration().locale, null, username, sortType,
getArguments().getBoolean(EXTRA_ARE_SAVED_COMMENTS)); getArguments().getBoolean(EXTRA_ARE_SAVED_COMMENTS));
} else { } else {

View File

@ -70,6 +70,7 @@ import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface; import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.activities.BaseActivity; import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.adapters.HistoryPostRecyclerViewAdapter; import eu.toldi.infinityforlemmy.adapters.HistoryPostRecyclerViewAdapter;
import eu.toldi.infinityforlemmy.adapters.Paging3LoadingStateAdapter; import eu.toldi.infinityforlemmy.adapters.Paging3LoadingStateAdapter;
@ -159,7 +160,7 @@ public class HistoryPostFragment extends Fragment implements FragmentCommunicato
HistoryPostViewModel mHistoryPostViewModel; HistoryPostViewModel mHistoryPostViewModel;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -655,11 +656,11 @@ public class HistoryPostFragment extends Fragment implements FragmentCommunicato
private void initializeAndBindPostViewModel(String accessToken) { private void initializeAndBindPostViewModel(String accessToken) {
if (postType == HistoryPostPagingSource.TYPE_READ_POSTS) { if (postType == HistoryPostPagingSource.TYPE_READ_POSTS) {
mHistoryPostViewModel = new ViewModelProvider(HistoryPostFragment.this, new HistoryPostViewModel.Factory(mExecutor, mHistoryPostViewModel = new ViewModelProvider(HistoryPostFragment.this, new HistoryPostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, mRedditDataRoomDatabase, accessToken, accessToken == null ? mRetrofit.getRetrofit() : mOauthRetrofit, mRedditDataRoomDatabase, accessToken,
accountName, mSharedPreferences, HistoryPostPagingSource.TYPE_READ_POSTS, postFilter)).get(HistoryPostViewModel.class); accountName, mSharedPreferences, HistoryPostPagingSource.TYPE_READ_POSTS, postFilter)).get(HistoryPostViewModel.class);
} else { } else {
mHistoryPostViewModel = new ViewModelProvider(HistoryPostFragment.this, new HistoryPostViewModel.Factory(mExecutor, mHistoryPostViewModel = new ViewModelProvider(HistoryPostFragment.this, new HistoryPostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, mRedditDataRoomDatabase, accessToken, accessToken == null ? mRetrofit.getRetrofit() : mOauthRetrofit, mRedditDataRoomDatabase, accessToken,
accountName, mSharedPreferences, HistoryPostPagingSource.TYPE_READ_POSTS, postFilter)).get(HistoryPostViewModel.class); accountName, mSharedPreferences, HistoryPostPagingSource.TYPE_READ_POSTS, postFilter)).get(HistoryPostViewModel.class);
} }
@ -932,14 +933,14 @@ public class HistoryPostFragment extends Fragment implements FragmentCommunicato
} else { } else {
if (isSubreddit) { if (isSubreddit) {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase,
subredditOrUserName, accessToken, mOauthRetrofit, mRetrofit, subredditOrUserName, accessToken, mOauthRetrofit, mRetrofit.getRetrofit(),
iconImageUrl -> { iconImageUrl -> {
subredditOrUserIcons.put(subredditOrUserName, iconImageUrl); subredditOrUserIcons.put(subredditOrUserName, iconImageUrl);
loadIconListener.loadIconSuccess(subredditOrUserName, iconImageUrl); loadIconListener.loadIconSuccess(subredditOrUserName, iconImageUrl);
}); });
} else { } else {
LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditOrUserName, LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditOrUserName,
mRetrofit, iconImageUrl -> { mRetrofit.getRetrofit(), iconImageUrl -> {
subredditOrUserIcons.put(subredditOrUserName, iconImageUrl); subredditOrUserIcons.put(subredditOrUserName, iconImageUrl);
loadIconListener.loadIconSuccess(subredditOrUserName, iconImageUrl); loadIconListener.loadIconSuccess(subredditOrUserName, iconImageUrl);
}); });
@ -1036,8 +1037,6 @@ public class HistoryPostFragment extends Fragment implements FragmentCommunicato
post.setNComments(event.post.getNComments()); post.setNComments(event.post.getNComments());
post.setNSFW(event.post.isNSFW()); post.setNSFW(event.post.isNSFW());
post.setHidden(event.post.isHidden()); post.setHidden(event.post.isHidden());
post.setSpoiler(event.post.isSpoiler());
post.setFlair(event.post.getFlair());
post.setSaved(event.post.isSaved()); post.setSaved(event.post.isSaved());
if (event.post.isRead()) { if (event.post.isRead()) {
post.markAsRead(); post.markAsRead();

View File

@ -74,6 +74,7 @@ import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface; import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.activities.AccountPostsActivity; import eu.toldi.infinityforlemmy.activities.AccountPostsActivity;
import eu.toldi.infinityforlemmy.activities.AccountSavedThingActivity; import eu.toldi.infinityforlemmy.activities.AccountSavedThingActivity;
@ -180,7 +181,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
PostViewModel mPostViewModel; PostViewModel mPostViewModel;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -462,7 +463,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
sortType = new SortType(SortType.Type.valueOf(sort), SortType.Time.valueOf(sortTime)); sortType = new SortType(SortType.Type.valueOf(sort), SortType.Time.valueOf(sortTime));
postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_SEARCH_POST, defaultPostLayout); postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_SEARCH_POST, defaultPostLayout);
mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mGfycatRetrofit, mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mRetrofit.getRetrofit(), mGfycatRetrofit,
mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale, mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale,
accessToken, accountName, postType, postLayout, true, accessToken, accountName, postType, postLayout, true,
mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences,
@ -530,7 +531,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_SUBREDDIT_POST_BASE + subredditName, sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_SUBREDDIT_POST_BASE + subredditName,
mSharedPreferences.getString(SharedPreferencesUtils.SUBREDDIT_DEFAULT_SORT_TIME, SortType.Time.ALL.name())); mSharedPreferences.getString(SharedPreferencesUtils.SUBREDDIT_DEFAULT_SORT_TIME, SortType.Time.ALL.name()));
} }
boolean displaySubredditName = subredditName != null && (subredditName.equals("popular") || subredditName.equals("all")); boolean displaySubredditName = subredditName != null && (subredditName.equals("local") || subredditName.equals("all"));
postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_SUBREDDIT_POST_BASE + subredditName, defaultPostLayout); postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_SUBREDDIT_POST_BASE + subredditName, defaultPostLayout);
if (sortTime != null) { if (sortTime != null) {
@ -539,7 +540,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
sortType = new SortType(SortType.Type.valueOf(sort)); sortType = new SortType(SortType.Type.valueOf(sort));
} }
mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mGfycatRetrofit, mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mRetrofit.getRetrofit(), mGfycatRetrofit,
mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale, mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale,
accessToken, accountName, postType, postLayout, displaySubredditName, accessToken, accountName, postType, postLayout, displaySubredditName,
mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences,
@ -610,7 +611,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
sortType = new SortType(SortType.Type.valueOf(sort)); sortType = new SortType(SortType.Type.valueOf(sort));
} }
mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mGfycatRetrofit, mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mRetrofit.getRetrofit(), mGfycatRetrofit,
mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale, mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale,
accessToken, accountName, postType, postLayout, true, accessToken, accountName, postType, postLayout, true,
mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences,
@ -675,7 +676,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
} }
postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_USER_POST_BASE + username, defaultPostLayout); postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_USER_POST_BASE + username, defaultPostLayout);
mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mGfycatRetrofit, mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mRetrofit.getRetrofit(), mGfycatRetrofit,
mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale, mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale,
accessToken, accountName, postType, postLayout, true, accessToken, accountName, postType, postLayout, true,
mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences,
@ -725,6 +726,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
} else if (postType == PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE) { } else if (postType == PostPagingSource.TYPE_ANONYMOUS_FRONT_PAGE) {
usage = PostFilterUsage.HOME_TYPE; usage = PostFilterUsage.HOME_TYPE;
nameOfUsage = PostFilterUsage.NO_USAGE; nameOfUsage = PostFilterUsage.NO_USAGE;
subredditName = getArguments().getString(EXTRA_NAME);
String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_SUBREDDIT_POST_BASE + "-", SortType.Type.HOT.name()); String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_SUBREDDIT_POST_BASE + "-", SortType.Type.HOT.name());
if (sort.equals(SortType.Type.CONTROVERSIAL.name()) || sort.equals(SortType.Type.TOP.name())) { if (sort.equals(SortType.Type.CONTROVERSIAL.name()) || sort.equals(SortType.Type.TOP.name())) {
@ -736,7 +738,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_FRONT_PAGE_POST, defaultPostLayout); postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_FRONT_PAGE_POST, defaultPostLayout);
mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mGfycatRetrofit, mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mRetrofit.getRetrofit(), mGfycatRetrofit,
mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale, mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale,
accessToken, accountName, postType, postLayout, true, accessToken, accountName, postType, postLayout, true,
mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences,
@ -796,7 +798,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_MULTI_REDDIT_POST_BASE + multiRedditPath, defaultPostLayout); postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_MULTI_REDDIT_POST_BASE + multiRedditPath, defaultPostLayout);
mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mGfycatRetrofit, mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mRetrofit.getRetrofit(), mGfycatRetrofit,
mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale, mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale,
accessToken, accountName, postType, postLayout, true, accessToken, accountName, postType, postLayout, true,
mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences,
@ -843,8 +845,8 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
} else { } else {
usage = PostFilterUsage.HOME_TYPE; usage = PostFilterUsage.HOME_TYPE;
nameOfUsage = PostFilterUsage.NO_USAGE; nameOfUsage = PostFilterUsage.NO_USAGE;
subredditName = getArguments().getString(EXTRA_NAME);
String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_BEST_POST, SortType.Type.BEST.name()); String sort = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_BEST_POST, SortType.Type.ACTIVE.name());
if (sort.equals(SortType.Type.CONTROVERSIAL.name()) || sort.equals(SortType.Type.TOP.name())) { if (sort.equals(SortType.Type.CONTROVERSIAL.name()) || sort.equals(SortType.Type.TOP.name())) {
String sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_BEST_POST, SortType.Time.ALL.name()); String sortTime = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TIME_BEST_POST, SortType.Time.ALL.name());
sortType = new SortType(SortType.Type.valueOf(sort), SortType.Time.valueOf(sortTime)); sortType = new SortType(SortType.Type.valueOf(sort), SortType.Time.valueOf(sortTime));
@ -853,7 +855,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
} }
postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_FRONT_PAGE_POST, defaultPostLayout); postLayout = mPostLayoutSharedPreferences.getInt(SharedPreferencesUtils.POST_LAYOUT_FRONT_PAGE_POST, defaultPostLayout);
mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mOauthRetrofit, mGfycatRetrofit, mAdapter = new PostRecyclerViewAdapter(activity, this, mExecutor, mRetrofit.getRetrofit(), mGfycatRetrofit,
mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale, mRedgifsRetrofit, mStreamableApiProvider, mCustomThemeWrapper, locale,
accessToken, accountName, postType, postLayout, true, accessToken, accountName, postType, postLayout, true,
mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences, mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostHistorySharedPreferences,
@ -1206,33 +1208,33 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
private void initializeAndBindPostViewModel(String accessToken) { private void initializeAndBindPostViewModel(String accessToken) {
if (postType == PostPagingSource.TYPE_SEARCH) { if (postType == PostPagingSource.TYPE_SEARCH) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, accessToken, mRetrofit.getRetrofit() , accessToken,
accountName, mSharedPreferences, accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, mPostHistorySharedPreferences, subredditName, mPostFeedScrolledPositionSharedPreferences, mPostHistorySharedPreferences, subredditName,
query, trendingSource, postType, sortType, postFilter, readPosts)).get(PostViewModel.class); query, trendingSource, postType, sortType, postFilter, readPosts)).get(PostViewModel.class);
} else if (postType == PostPagingSource.TYPE_SUBREDDIT) { } else if (postType == PostPagingSource.TYPE_SUBREDDIT) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, accessToken, mRetrofit.getRetrofit() , accessToken,
accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences, accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences,
mPostHistorySharedPreferences, subredditName, postType, sortType, postFilter, readPosts)) mPostHistorySharedPreferences, subredditName, postType, sortType, postFilter, readPosts))
.get(PostViewModel.class); .get(PostViewModel.class);
} else if (postType == PostPagingSource.TYPE_MULTI_REDDIT) { } else if (postType == PostPagingSource.TYPE_MULTI_REDDIT) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, accessToken, mRetrofit.getRetrofit(), accessToken,
accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences, accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences,
mPostHistorySharedPreferences, multiRedditPath, postType, sortType, postFilter, readPosts)) mPostHistorySharedPreferences, multiRedditPath, postType, sortType, postFilter, readPosts))
.get(PostViewModel.class); .get(PostViewModel.class);
} else if (postType == PostPagingSource.TYPE_USER) { } else if (postType == PostPagingSource.TYPE_USER) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
accessToken == null ? mRetrofit : mOauthRetrofit, accessToken, mRetrofit.getRetrofit(), accessToken,
accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences, accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences,
mPostHistorySharedPreferences, username, postType, sortType, postFilter, where, readPosts)) mPostHistorySharedPreferences, username, postType, sortType, postFilter, where, readPosts))
.get(PostViewModel.class); .get(PostViewModel.class);
} else { } else {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
mOauthRetrofit, accessToken, mRetrofit.getRetrofit(), accessToken,
accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences, accountName, mSharedPreferences, mPostFeedScrolledPositionSharedPreferences,
mPostHistorySharedPreferences, postType, sortType, postFilter, readPosts)).get(PostViewModel.class); mPostHistorySharedPreferences, postType, sortType, postFilter, readPosts,subredditName)).get(PostViewModel.class);
} }
bindPostViewModel(); bindPostViewModel();
@ -1242,28 +1244,28 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
//For anonymous user //For anonymous user
if (postType == PostPagingSource.TYPE_SEARCH) { if (postType == PostPagingSource.TYPE_SEARCH) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
mRetrofit, null, accountName, mSharedPreferences, mRetrofit.getRetrofit(), null, accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, null, subredditName, query, trendingSource, mPostFeedScrolledPositionSharedPreferences, null, subredditName, query, trendingSource,
postType, sortType, postFilter, readPosts)).get(PostViewModel.class); postType, sortType, postFilter, readPosts)).get(PostViewModel.class);
} else if (postType == PostPagingSource.TYPE_SUBREDDIT) { } else if (postType == PostPagingSource.TYPE_SUBREDDIT) {
mPostViewModel = new ViewModelProvider(this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(this, new PostViewModel.Factory(mExecutor,
mRetrofit, null, accountName, mSharedPreferences, mRetrofit.getRetrofit(), null, accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, null, subredditName, postType, sortType, mPostFeedScrolledPositionSharedPreferences, null, subredditName, postType, sortType,
postFilter, readPosts)).get(PostViewModel.class); postFilter, readPosts)).get(PostViewModel.class);
} else if (postType == PostPagingSource.TYPE_MULTI_REDDIT) { } else if (postType == PostPagingSource.TYPE_MULTI_REDDIT) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
mRetrofit, null, accountName, mSharedPreferences, mRetrofit.getRetrofit(), null, accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, null, multiRedditPath, mPostFeedScrolledPositionSharedPreferences, null, multiRedditPath,
postType, sortType, postFilter, readPosts)).get(PostViewModel.class); postType, sortType, postFilter, readPosts)).get(PostViewModel.class);
} else if (postType == PostPagingSource.TYPE_USER) { } else if (postType == PostPagingSource.TYPE_USER) {
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
mRetrofit, null, accountName, mSharedPreferences, mRetrofit.getRetrofit(), null, accountName, mSharedPreferences,
mPostFeedScrolledPositionSharedPreferences, null, username, postType, sortType, postFilter, mPostFeedScrolledPositionSharedPreferences, null, username, postType, sortType, postFilter,
where, readPosts)).get(PostViewModel.class); where, readPosts)).get(PostViewModel.class);
} else { } else {
//Anonymous Front Page //Anonymous Front Page
mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor, mPostViewModel = new ViewModelProvider(PostFragment.this, new PostViewModel.Factory(mExecutor,
mRetrofit, mSharedPreferences, concatenatedSubredditNames, postType, sortType, postFilter)) mRetrofit.getRetrofit(), mSharedPreferences, concatenatedSubredditNames, postType, sortType, postFilter,subredditName))
.get(PostViewModel.class); .get(PostViewModel.class);
} }
@ -1468,7 +1470,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
} }
private void saveCache() { private void saveCache() {
if (savePostFeedScrolledPosition && postType == PostPagingSource.TYPE_FRONT_PAGE && sortType != null && sortType.getType() == SortType.Type.BEST && mAdapter != null) { if (savePostFeedScrolledPosition && postType == PostPagingSource.TYPE_FRONT_PAGE && sortType != null && sortType.getType() == SortType.Type.ACTIVE && mAdapter != null) {
Post currentPost = mAdapter.getItemByPosition(maxPosition); Post currentPost = mAdapter.getItemByPosition(maxPosition);
if (currentPost != null) { if (currentPost != null) {
String accountNameForCache = accountName == null ? SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_ANONYMOUS : accountName; String accountNameForCache = accountName == null ? SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_ANONYMOUS : accountName;
@ -1746,14 +1748,14 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
} else { } else {
if (isSubreddit) { if (isSubreddit) {
LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase, LoadSubredditIcon.loadSubredditIcon(mExecutor, new Handler(), mRedditDataRoomDatabase,
subredditOrUserName, accessToken, mOauthRetrofit, mRetrofit, subredditOrUserName, accessToken, mRetrofit.getRetrofit(), mRetrofit.getRetrofit(),
iconImageUrl -> { iconImageUrl -> {
subredditOrUserIcons.put(subredditOrUserName, iconImageUrl); subredditOrUserIcons.put(subredditOrUserName, iconImageUrl);
loadIconListener.loadIconSuccess(subredditOrUserName, iconImageUrl); loadIconListener.loadIconSuccess(subredditOrUserName, iconImageUrl);
}); });
} else { } else {
LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditOrUserName, LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, subredditOrUserName,
mRetrofit, iconImageUrl -> { mRetrofit.getRetrofit(), iconImageUrl -> {
subredditOrUserIcons.put(subredditOrUserName, iconImageUrl); subredditOrUserIcons.put(subredditOrUserName, iconImageUrl);
loadIconListener.loadIconSuccess(subredditOrUserName, iconImageUrl); loadIconListener.loadIconSuccess(subredditOrUserName, iconImageUrl);
}); });
@ -1765,7 +1767,7 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
if (readPosts == null) { if (readPosts == null) {
readPosts = new ArrayList<>(); readPosts = new ArrayList<>();
} }
readPosts.add(post.getId()); readPosts.add(String.valueOf(post.getId()));
} }
@Subscribe @Subscribe
@ -1780,8 +1782,6 @@ public class PostFragment extends Fragment implements FragmentCommunicator {
post.setNComments(event.post.getNComments()); post.setNComments(event.post.getNComments());
post.setNSFW(event.post.isNSFW()); post.setNSFW(event.post.isNSFW());
post.setHidden(event.post.isHidden()); post.setHidden(event.post.isHidden());
post.setSpoiler(event.post.isSpoiler());
post.setFlair(event.post.getFlair());
post.setSaved(event.post.isSaved()); post.setSaved(event.post.isSaved());
if (event.post.isRead()) { if (event.post.isRead()) {
post.markAsRead(); post.markAsRead();

View File

@ -25,6 +25,7 @@ import javax.inject.Named;
import butterknife.BindView; import butterknife.BindView;
import butterknife.ButterKnife; import butterknife.ButterKnife;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import io.noties.markwon.AbstractMarkwonPlugin; import io.noties.markwon.AbstractMarkwonPlugin;
import io.noties.markwon.Markwon; import io.noties.markwon.Markwon;
import io.noties.markwon.MarkwonConfiguration; import io.noties.markwon.MarkwonConfiguration;
@ -52,6 +53,7 @@ public class SidebarFragment extends Fragment {
public static final String EXTRA_SUBREDDIT_NAME = "ESN"; public static final String EXTRA_SUBREDDIT_NAME = "ESN";
public static final String EXTRA_ACCESS_TOKEN = "EAT"; public static final String EXTRA_ACCESS_TOKEN = "EAT";
public static final String EXTRA_COMMUNITY_QUALIFIED_NAME = "ECQN";
public SubredditViewModel mSubredditViewModel; public SubredditViewModel mSubredditViewModel;
@BindView(R.id.swipe_refresh_layout_sidebar_fragment) @BindView(R.id.swipe_refresh_layout_sidebar_fragment)
SwipeRefreshLayout swipeRefreshLayout; SwipeRefreshLayout swipeRefreshLayout;
@ -59,7 +61,7 @@ public class SidebarFragment extends Fragment {
RecyclerView recyclerView; RecyclerView recyclerView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -72,6 +74,8 @@ public class SidebarFragment extends Fragment {
private ViewSubredditDetailActivity activity; private ViewSubredditDetailActivity activity;
private String mAccessToken; private String mAccessToken;
private String subredditName; private String subredditName;
private String communityQualifiedName;
private LinearLayoutManagerBugFixed linearLayoutManager; private LinearLayoutManagerBugFixed linearLayoutManager;
private int markdownColor; private int markdownColor;
private String sidebarDescription; private String sidebarDescription;
@ -92,6 +96,7 @@ public class SidebarFragment extends Fragment {
mAccessToken = getArguments().getString(EXTRA_ACCESS_TOKEN); mAccessToken = getArguments().getString(EXTRA_ACCESS_TOKEN);
subredditName = getArguments().getString(EXTRA_SUBREDDIT_NAME); subredditName = getArguments().getString(EXTRA_SUBREDDIT_NAME);
communityQualifiedName = getArguments().getString(EXTRA_COMMUNITY_QUALIFIED_NAME);
if (subredditName == null) { if (subredditName == null) {
Toast.makeText(activity, R.string.error_getting_subreddit_name, Toast.LENGTH_SHORT).show(); Toast.makeText(activity, R.string.error_getting_subreddit_name, Toast.LENGTH_SHORT).show();
return rootView; return rootView;
@ -161,7 +166,7 @@ public class SidebarFragment extends Fragment {
}); });
mSubredditViewModel = new ViewModelProvider(activity, mSubredditViewModel = new ViewModelProvider(activity,
new SubredditViewModel.Factory(activity.getApplication(), mRedditDataRoomDatabase, subredditName)) new SubredditViewModel.Factory(activity.getApplication(), mRedditDataRoomDatabase, communityQualifiedName))
.get(SubredditViewModel.class); .get(SubredditViewModel.class);
mSubredditViewModel.getSubredditLiveData().observe(getViewLifecycleOwner(), subredditData -> { mSubredditViewModel.getSubredditLiveData().observe(getViewLifecycleOwner(), subredditData -> {
if (subredditData != null) { if (subredditData != null) {
@ -189,7 +194,7 @@ public class SidebarFragment extends Fragment {
public void fetchSubredditData() { public void fetchSubredditData() {
swipeRefreshLayout.setRefreshing(true); swipeRefreshLayout.setRefreshing(true);
FetchSubredditData.fetchSubredditData(mOauthRetrofit, mRetrofit, subredditName, mAccessToken, new FetchSubredditData.FetchSubredditDataListener() { FetchSubredditData.fetchSubredditData(mOauthRetrofit, mRetrofit.getRetrofit(), communityQualifiedName, mAccessToken, new FetchSubredditData.FetchSubredditDataListener() {
@Override @Override
public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) {
swipeRefreshLayout.setRefreshing(false); swipeRefreshLayout.setRefreshing(false);

View File

@ -38,6 +38,7 @@ import eu.toldi.infinityforlemmy.NetworkState;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface; import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.activities.BaseActivity; import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.SearchSubredditsResultActivity; import eu.toldi.infinityforlemmy.activities.SearchSubredditsResultActivity;
@ -77,7 +78,7 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
SubredditListingViewModel mSubredditListingViewModel; SubredditListingViewModel mSubredditListingViewModel;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -142,7 +143,7 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
sortType = new SortType(SortType.Type.valueOf(sort.toUpperCase())); sortType = new SortType(SortType.Type.valueOf(sort.toUpperCase()));
boolean nsfw = !mSharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_NSFW_FOREVER, false) && mNsfwAndSpoilerSharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.NSFW_BASE, false); boolean nsfw = !mSharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_NSFW_FOREVER, false) && mNsfwAndSpoilerSharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.NSFW_BASE, false);
mAdapter = new SubredditListingRecyclerViewAdapter(mActivity, mExecutor, mOauthRetrofit, mRetrofit, mAdapter = new SubredditListingRecyclerViewAdapter(mActivity, mExecutor, mOauthRetrofit, mRetrofit.getRetrofit(),
mCustomThemeWrapper, accessToken, accountName, mCustomThemeWrapper, accessToken, accountName,
mRedditDataRoomDatabase, getArguments().getBoolean(EXTRA_IS_MULTI_SELECTION, false), mRedditDataRoomDatabase, getArguments().getBoolean(EXTRA_IS_MULTI_SELECTION, false),
new SubredditListingRecyclerViewAdapter.Callback() { new SubredditListingRecyclerViewAdapter.Callback() {
@ -152,12 +153,13 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
} }
@Override @Override
public void subredditSelected(String subredditName, String iconUrl) { public void subredditSelected(String subredditName, String communityFullName,String iconUrl) {
if (isGettingSubredditInfo) { if (isGettingSubredditInfo) {
((SearchSubredditsResultActivity) mActivity).getSelectedSubreddit(subredditName, iconUrl); ((SearchSubredditsResultActivity) mActivity).getSelectedSubreddit(subredditName, iconUrl);
} else { } else {
Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class); Intent intent = new Intent(mActivity, ViewSubredditDetailActivity.class);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, subredditName); intent.putExtra(ViewSubredditDetailActivity.EXTRA_SUBREDDIT_NAME_KEY, subredditName);
intent.putExtra(ViewSubredditDetailActivity.EXTRA_COMMUNITY_FULL_NAME_KEY, communityFullName);
mActivity.startActivity(intent); mActivity.startActivity(intent);
} }
} }
@ -179,7 +181,7 @@ public class SubredditListingFragment extends Fragment implements FragmentCommun
} }
SubredditListingViewModel.Factory factory = new SubredditListingViewModel.Factory( SubredditListingViewModel.Factory factory = new SubredditListingViewModel.Factory(
accessToken == null ? mRetrofit : mOauthRetrofit, query, sortType, accessToken, nsfw); accessToken == null ? mRetrofit.getRetrofit() : mOauthRetrofit, query, sortType, accessToken, nsfw);
mSubredditListingViewModel = new ViewModelProvider(this, factory).get(SubredditListingViewModel.class); mSubredditListingViewModel = new ViewModelProvider(this, factory).get(SubredditListingViewModel.class);
mSubredditListingViewModel.getSubreddits().observe(getViewLifecycleOwner(), subredditData -> mAdapter.submitList(subredditData)); mSubredditListingViewModel.getSubreddits().observe(getViewLifecycleOwner(), subredditData -> mAdapter.submitList(subredditData));

View File

@ -155,7 +155,7 @@ public class SubscribedSubredditsListingFragment extends Fragment implements Fra
adapter.setSubscribedSubreddits(subscribedSubredditData); adapter.setSubscribedSubreddits(subscribedSubredditData);
}); });
mSubscribedSubredditViewModel.getAllFavoriteSubscribedSubreddits().observe(getViewLifecycleOwner(), favoriteSubscribedSubredditData -> { /* mSubscribedSubredditViewModel.getAllFavoriteSubscribedSubreddits().observe(getViewLifecycleOwner(), favoriteSubscribedSubredditData -> {
mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setRefreshing(false);
if (favoriteSubscribedSubredditData != null && favoriteSubscribedSubredditData.size() > 0) { if (favoriteSubscribedSubredditData != null && favoriteSubscribedSubredditData.size() > 0) {
mLinearLayout.setVisibility(View.GONE); mLinearLayout.setVisibility(View.GONE);
@ -164,7 +164,7 @@ public class SubscribedSubredditsListingFragment extends Fragment implements Fra
} }
adapter.setFavoriteSubscribedSubreddits(favoriteSubscribedSubredditData); adapter.setFavoriteSubscribedSubreddits(favoriteSubscribedSubredditData);
}); });*/
return rootView; return rootView;
} }

View File

@ -38,6 +38,7 @@ import eu.toldi.infinityforlemmy.NetworkState;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface; import eu.toldi.infinityforlemmy.RecyclerViewContentScrollingInterface;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.activities.BaseActivity; import eu.toldi.infinityforlemmy.activities.BaseActivity;
import eu.toldi.infinityforlemmy.activities.SearchUsersResultActivity; import eu.toldi.infinityforlemmy.activities.SearchUsersResultActivity;
@ -77,7 +78,7 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato
UserListingViewModel mUserListingViewModel; UserListingViewModel mUserListingViewModel;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -142,7 +143,7 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato
sortType = new SortType(SortType.Type.valueOf(sort.toUpperCase())); sortType = new SortType(SortType.Type.valueOf(sort.toUpperCase()));
boolean nsfw = !mSharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_NSFW_FOREVER, false) && mNsfwAndSpoilerSharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.NSFW_BASE, false); boolean nsfw = !mSharedPreferences.getBoolean(SharedPreferencesUtils.DISABLE_NSFW_FOREVER, false) && mNsfwAndSpoilerSharedPreferences.getBoolean((accountName == null ? "" : accountName) + SharedPreferencesUtils.NSFW_BASE, false);
mAdapter = new UserListingRecyclerViewAdapter(mActivity, mExecutor, mOauthRetrofit, mRetrofit, mAdapter = new UserListingRecyclerViewAdapter(mActivity, mExecutor, mOauthRetrofit, mRetrofit.getRetrofit(),
mCustomThemeWrapper, accessToken, accountName, mRedditDataRoomDatabase, mCustomThemeWrapper, accessToken, accountName, mRedditDataRoomDatabase,
getArguments().getBoolean(EXTRA_IS_MULTI_SELECTION, false), getArguments().getBoolean(EXTRA_IS_MULTI_SELECTION, false),
new UserListingRecyclerViewAdapter.Callback() { new UserListingRecyclerViewAdapter.Callback() {
@ -178,7 +179,7 @@ public class UserListingFragment extends Fragment implements FragmentCommunicato
}); });
} }
UserListingViewModel.Factory factory = new UserListingViewModel.Factory(mRetrofit, mQuery, UserListingViewModel.Factory factory = new UserListingViewModel.Factory(mRetrofit.getRetrofit(), mQuery,
sortType, nsfw); sortType, nsfw);
mUserListingViewModel = new ViewModelProvider(this, factory).get(UserListingViewModel.class); mUserListingViewModel = new ViewModelProvider(this, factory).get(UserListingViewModel.class);
mUserListingViewModel.getUsers().observe(getViewLifecycleOwner(), UserData -> mAdapter.submitList(UserData)); mUserListingViewModel.getUsers().observe(getViewLifecycleOwner(), UserData -> mAdapter.submitList(UserData));

View File

@ -72,6 +72,7 @@ import eu.toldi.infinityforlemmy.FragmentCommunicator;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.SaveThing; import eu.toldi.infinityforlemmy.SaveThing;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.activities.CommentActivity; import eu.toldi.infinityforlemmy.activities.CommentActivity;
@ -146,7 +147,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
TextView mFetchPostInfoTextView; TextView mFetchPostInfoTextView;
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("pushshift") @Named("pushshift")
Retrofit pushshiftRetrofit; Retrofit pushshiftRetrofit;
@ -593,13 +594,13 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
setupMenu(); setupMenu();
mPostAdapter = new PostDetailRecyclerViewAdapter(activity, mPostAdapter = new PostDetailRecyclerViewAdapter(activity,
this, mExecutor, mCustomThemeWrapper, mRetrofit, mOauthRetrofit, mGfycatRetrofit, this, mExecutor, mCustomThemeWrapper, mRetrofit.getRetrofit(), mOauthRetrofit, mGfycatRetrofit,
mRedgifsRetrofit, mStreamableApiProvider, mRedditDataRoomDatabase, mGlide, mRedgifsRetrofit, mStreamableApiProvider, mRedditDataRoomDatabase, mGlide,
mSeparatePostAndComments, mAccessToken, mAccountName, mPost, mLocale, mSeparatePostAndComments, mAccessToken, mAccountName, mPost, mLocale,
mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostDetailsSharedPreferences, mSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mPostDetailsSharedPreferences,
mExoCreator, post -> EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition))); mExoCreator, post -> EventBus.getDefault().post(new PostUpdateEventToPostList(mPost, postListPosition)));
mCommentsAdapter = new CommentsRecyclerViewAdapter(activity, mCommentsAdapter = new CommentsRecyclerViewAdapter(activity,
this, mCustomThemeWrapper, mExecutor, mRetrofit, mOauthRetrofit, this, mCustomThemeWrapper, mExecutor, mRetrofit.getRetrofit(), mOauthRetrofit,
mAccessToken, mAccountName, mPost, mLocale, mSingleCommentId, mAccessToken, mAccountName, mPost, mLocale, mSingleCommentId,
isSingleCommentThreadMode, mSharedPreferences, isSingleCommentThreadMode, mSharedPreferences,
new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() { new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() {
@ -699,11 +700,6 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
MenuItem spoilerItem = mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment); MenuItem spoilerItem = mMenu.findItem(R.id.action_spoiler_view_post_detail_fragment);
spoilerItem.setVisible(true); spoilerItem.setVisible(true);
if (mPost.isSpoiler()) {
Utils.setTitleWithCustomFontToMenuItem(activity.typeface, spoilerItem, activity.getString(R.string.action_unmark_spoiler));
} else {
Utils.setTitleWithCustomFontToMenuItem(activity.typeface, spoilerItem, activity.getString(R.string.action_mark_spoiler));
}
mMenu.findItem(R.id.action_edit_flair_view_post_detail_fragment).setVisible(true); mMenu.findItem(R.id.action_edit_flair_view_post_detail_fragment).setVisible(true);
} }
@ -823,7 +819,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@NonNull @NonNull
private SortType.Type loadSortType() { private SortType.Type loadSortType() {
String sortTypeName = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, SortType.Type.CONFIDENCE.name()); String sortTypeName = mSortTypeSharedPreferences.getString(SharedPreferencesUtils.SORT_TYPE_POST_COMMENT, SortType.Type.CONFIDENCE.name());
if (SortType.Type.BEST.name().equals(sortTypeName)) { if (SortType.Type.ACTIVE.name().equals(sortTypeName)) {
// migrate from BEST to CONFIDENCE // migrate from BEST to CONFIDENCE
// key guaranteed to exist because got non-default value // key guaranteed to exist because got non-default value
mSortTypeSharedPreferences.edit() mSortTypeSharedPreferences.edit()
@ -906,7 +902,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
loadIconListener.loadIconSuccess(authorName, activity.authorIcons.get(authorName)); loadIconListener.loadIconSuccess(authorName, activity.authorIcons.get(authorName));
} else { } else {
LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, authorName, LoadUserData.loadUserData(mExecutor, new Handler(), mRedditDataRoomDatabase, authorName,
mRetrofit, iconImageUrl -> { mRetrofit.getRetrofit(), iconImageUrl -> {
activity.authorIcons.put(authorName, iconImageUrl); activity.authorIcons.put(authorName, iconImageUrl);
loadIconListener.loadIconSuccess(authorName, iconImageUrl); loadIconListener.loadIconSuccess(authorName, iconImageUrl);
}); });
@ -1104,11 +1100,6 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
} }
return true; return true;
} else if (itemId == R.id.action_spoiler_view_post_detail_fragment) { } else if (itemId == R.id.action_spoiler_view_post_detail_fragment) {
if (mPost.isSpoiler()) {
unmarkSpoiler();
} else {
markSpoiler();
}
return true; return true;
} else if (itemId == R.id.action_edit_flair_view_post_detail_fragment) { } else if (itemId == R.id.action_edit_flair_view_post_detail_fragment) {
FlairBottomSheetFragment flairBottomSheetFragment = new FlairBottomSheetFragment(); FlairBottomSheetFragment flairBottomSheetFragment = new FlairBottomSheetFragment();
@ -1265,10 +1256,10 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
Call<String> postAndComments; Call<String> postAndComments;
if (mAccessToken == null) { if (mAccessToken == null) {
if (isSingleCommentThreadMode && mSingleCommentId != null) { if (isSingleCommentThreadMode && mSingleCommentId != null) {
postAndComments = mRetrofit.create(RedditAPI.class).getPostAndCommentsSingleThreadById( postAndComments = mRetrofit.getRetrofit().create(RedditAPI.class).getPostAndCommentsSingleThreadById(
subredditId, mSingleCommentId, sortType, mContextNumber); subredditId, mSingleCommentId, sortType, mContextNumber);
} else { } else {
postAndComments = mRetrofit.create(RedditAPI.class).getPostAndCommentsById(subredditId, postAndComments = mRetrofit.getRetrofit().create(RedditAPI.class).getPostAndCommentsById(subredditId,
sortType); sortType);
} }
} else { } else {
@ -1299,7 +1290,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
mPostAdapter = new PostDetailRecyclerViewAdapter(activity, mPostAdapter = new PostDetailRecyclerViewAdapter(activity,
ViewPostDetailFragment.this, mExecutor, mCustomThemeWrapper, ViewPostDetailFragment.this, mExecutor, mCustomThemeWrapper,
mRetrofit, mOauthRetrofit, mGfycatRetrofit, mRedgifsRetrofit, mRetrofit.getRetrofit(), mOauthRetrofit, mGfycatRetrofit, mRedgifsRetrofit,
mStreamableApiProvider, mRedditDataRoomDatabase, mGlide, mSeparatePostAndComments, mStreamableApiProvider, mRedditDataRoomDatabase, mGlide, mSeparatePostAndComments,
mAccessToken, mAccountName, mPost, mLocale, mSharedPreferences, mAccessToken, mAccountName, mPost, mLocale, mSharedPreferences,
mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences, mCurrentAccountSharedPreferences, mNsfwAndSpoilerSharedPreferences,
@ -1308,7 +1299,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
mCommentsAdapter = new CommentsRecyclerViewAdapter(activity, mCommentsAdapter = new CommentsRecyclerViewAdapter(activity,
ViewPostDetailFragment.this, mCustomThemeWrapper, mExecutor, ViewPostDetailFragment.this, mCustomThemeWrapper, mExecutor,
mRetrofit, mOauthRetrofit, mAccessToken, mAccountName, mPost, mLocale, mRetrofit.getRetrofit(), mOauthRetrofit, mAccessToken, mAccountName, mPost, mLocale,
mSingleCommentId, isSingleCommentThreadMode, mSharedPreferences, mSingleCommentId, isSingleCommentThreadMode, mSharedPreferences,
new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() { new CommentsRecyclerViewAdapter.CommentRecyclerViewAdapterCallback() {
@Override @Override
@ -1436,11 +1427,11 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
e.printStackTrace(); e.printStackTrace();
} }
} }
FetchSubredditData.fetchSubredditData(mOauthRetrofit, mRetrofit, mPost.getSubredditName(), mAccessToken, FetchSubredditData.fetchSubredditData(mOauthRetrofit, mRetrofit.getRetrofit(), mPost.getSubredditNamePrefixed(), mAccessToken,
new FetchSubredditData.FetchSubredditDataListener() { new FetchSubredditData.FetchSubredditDataListener() {
@Override @Override
public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) { public void onFetchSubredditDataSuccess(SubredditData subredditData, int nCurrentOnlineSubscribers) {
String suggestedCommentSort = subredditData.getSuggestedCommentSort(); String suggestedCommentSort = "top";
SortType.Type sortTypeType; SortType.Type sortTypeType;
if (suggestedCommentSort == null || suggestedCommentSort.equals("null") || suggestedCommentSort.equals("")) { if (suggestedCommentSort == null || suggestedCommentSort.equals("null") || suggestedCommentSort.equals("")) {
mRespectSubredditRecommendedSortType = false; mRespectSubredditRecommendedSortType = false;
@ -1480,8 +1471,8 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
commentId = mSingleCommentId; commentId = mSingleCommentId;
} }
Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit; Retrofit retrofit = mAccessToken == null ? mRetrofit.getRetrofit() : mOauthRetrofit;
FetchComment.fetchComments(mExecutor, new Handler(), retrofit, mAccessToken, mPost.getId(), commentId, sortType, FetchComment.fetchComments(mExecutor, new Handler(), retrofit, mAccessToken, String.valueOf(mPost.getId()), commentId, sortType,
mContextNumber, mExpandChildren, mLocale, new FetchComment.FetchCommentListener() { mContextNumber, mExpandChildren, mLocale, new FetchComment.FetchCommentListener() {
@Override @Override
public void onFetchCommentSuccess(ArrayList<Comment> expandedComments, public void onFetchCommentSuccess(ArrayList<Comment> expandedComments,
@ -1567,7 +1558,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
isLoadingMoreChildren = true; isLoadingMoreChildren = true;
Retrofit retrofit = mAccessToken == null ? mRetrofit : mOauthRetrofit; Retrofit retrofit = mAccessToken == null ? mRetrofit.getRetrofit() : mOauthRetrofit;
FetchComment.fetchMoreComment(mExecutor, new Handler(), retrofit, mAccessToken, children, FetchComment.fetchMoreComment(mExecutor, new Handler(), retrofit, mAccessToken, children,
mExpandChildren, mPost.getFullName(), sortType, new FetchComment.FetchMoreCommentListener() { mExpandChildren, mPost.getFullName(), sortType, new FetchComment.FetchMoreCommentListener() {
@Override @Override
@ -1604,11 +1595,11 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
if (fetchPost) { if (fetchPost) {
Retrofit retrofit; Retrofit retrofit;
if (mAccessToken == null) { if (mAccessToken == null) {
retrofit = mRetrofit; retrofit = mRetrofit.getRetrofit();
} else { } else {
retrofit = mOauthRetrofit; retrofit = mOauthRetrofit;
} }
FetchPost.fetchPost(mExecutor, new Handler(), retrofit, mPost.getId(), mAccessToken, FetchPost.fetchPost(mExecutor, new Handler(), retrofit, String.valueOf(mPost.getId()), mAccessToken,
new FetchPost.FetchPostListener() { new FetchPost.FetchPostListener() {
@Override @Override
public void fetchPostSuccess(Post post) { public void fetchPostSuccess(Post post) {
@ -1930,7 +1921,7 @@ public class ViewPostDetailFragment extends Fragment implements FragmentCommunic
@Subscribe @Subscribe
public void onPostUpdateEvent(PostUpdateEventToPostDetailFragment event) { public void onPostUpdateEvent(PostUpdateEventToPostDetailFragment event) {
if (mPost.getId().equals(event.post.getId())) { if (mPost.getId() == event.post.getId()) {
mPost.setVoteType(event.post.getVoteType()); mPost.setVoteType(event.post.getVoteType());
mPost.setSaved(event.post.isSaved()); mPost.setSaved(event.post.isSaved());
if (mMenu != null) { if (mMenu != null) {

View File

@ -70,7 +70,7 @@ public class ParseMessage {
boolean isNew = rawMessageJSON.getBoolean(JSONUtils.NEW_KEY); boolean isNew = rawMessageJSON.getBoolean(JSONUtils.NEW_KEY);
int score = rawMessageJSON.getInt(JSONUtils.SCORE_KEY); int score = rawMessageJSON.getInt(JSONUtils.SCORE_KEY);
int nComments = rawMessageJSON.isNull(JSONUtils.NUM_COMMENTS_KEY) ? -1 : rawMessageJSON.getInt(JSONUtils.NUM_COMMENTS_KEY); int nComments = rawMessageJSON.isNull(JSONUtils.NUM_COMMENTS_KEY) ? -1 : rawMessageJSON.getInt(JSONUtils.NUM_COMMENTS_KEY);
long timeUTC = rawMessageJSON.getLong(JSONUtils.CREATED_UTC_KEY) * 1000; long timeUTC = rawMessageJSON.getLong(JSONUtils.PUBLISHED) * 1000;
Calendar submitTimeCalendar = Calendar.getInstance(); Calendar submitTimeCalendar = Calendar.getInstance();
submitTimeCalendar.setTimeInMillis(timeUTC); submitTimeCalendar.setTimeInMillis(timeUTC);

View File

@ -89,7 +89,7 @@ public class FetchMultiRedditInfo {
String visibility = object.getString(JSONUtils.VISIBILITY_KEY); String visibility = object.getString(JSONUtils.VISIBILITY_KEY);
String owner = object.getString(JSONUtils.OWNER_KEY); String owner = object.getString(JSONUtils.OWNER_KEY);
int nSubscribers = object.getInt(JSONUtils.NUM_SUBSCRIBERS_KEY); int nSubscribers = object.getInt(JSONUtils.NUM_SUBSCRIBERS_KEY);
long createdUTC = object.getLong(JSONUtils.CREATED_UTC_KEY); long createdUTC = object.getLong(JSONUtils.PUBLISHED);
boolean over18 = object.getBoolean(JSONUtils.OVER_18_KEY); boolean over18 = object.getBoolean(JSONUtils.OVER_18_KEY);
boolean isSubscriber = object.getBoolean(JSONUtils.IS_SUBSCRIBER_KEY); boolean isSubscriber = object.getBoolean(JSONUtils.IS_SUBSCRIBER_KEY);
boolean isFavorite = object.getBoolean(JSONUtils.IS_FAVORITED_KEY); boolean isFavorite = object.getBoolean(JSONUtils.IS_FAVORITED_KEY);

View File

@ -38,7 +38,7 @@ public class ParseMultiReddit {
int nSubscribers = singleMultiRedditJSON.getInt(JSONUtils.NUM_SUBSCRIBERS_KEY); int nSubscribers = singleMultiRedditJSON.getInt(JSONUtils.NUM_SUBSCRIBERS_KEY);
String copiedFrom = singleMultiRedditJSON.getString(JSONUtils.COPIED_FROM_KEY); String copiedFrom = singleMultiRedditJSON.getString(JSONUtils.COPIED_FROM_KEY);
String iconUrl = singleMultiRedditJSON.getString(JSONUtils.ICON_URL_KEY); String iconUrl = singleMultiRedditJSON.getString(JSONUtils.ICON_URL_KEY);
long createdUTC = singleMultiRedditJSON.getLong(JSONUtils.CREATED_UTC_KEY); long createdUTC = singleMultiRedditJSON.getLong(JSONUtils.PUBLISHED);
String visibility = singleMultiRedditJSON.getString(JSONUtils.VISIBILITY_KEY); String visibility = singleMultiRedditJSON.getString(JSONUtils.VISIBILITY_KEY);
boolean over18 = singleMultiRedditJSON.getBoolean(JSONUtils.OVER_18_KEY); boolean over18 = singleMultiRedditJSON.getBoolean(JSONUtils.OVER_18_KEY);
String path = singleMultiRedditJSON.getString(JSONUtils.PATH_KEY); String path = singleMultiRedditJSON.getString(JSONUtils.PATH_KEY);

View File

@ -22,7 +22,7 @@ import retrofit2.Retrofit;
public class FetchRemovedPost { public class FetchRemovedPost {
public static void fetchRemovedPost(Retrofit retrofit, Post post, FetchRemovedPostListener listener) { public static void fetchRemovedPost(Retrofit retrofit, Post post, FetchRemovedPostListener listener) {
retrofit.create(PushshiftAPI.class).getRemovedPost(post.getId()) retrofit.create(PushshiftAPI.class).getRemovedPost(String.valueOf(post.getId()))
.enqueue(new Callback<String>() { .enqueue(new Callback<String>() {
@Override @Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {

View File

@ -1,5 +1,7 @@
package eu.toldi.infinityforlemmy.post; package eu.toldi.infinityforlemmy.post;
import static java.lang.Integer.max;
import android.net.Uri; import android.net.Uri;
import android.os.Handler; import android.os.Handler;
import android.text.Html; import android.text.Html;
@ -9,6 +11,9 @@ import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
@ -19,6 +24,7 @@ import java.util.regex.Pattern;
import eu.toldi.infinityforlemmy.postfilter.PostFilter; import eu.toldi.infinityforlemmy.postfilter.PostFilter;
import eu.toldi.infinityforlemmy.utils.JSONUtils; import eu.toldi.infinityforlemmy.utils.JSONUtils;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import eu.toldi.infinityforlemmy.utils.Utils; import eu.toldi.infinityforlemmy.utils.Utils;
/** /**
@ -30,12 +36,12 @@ public class ParsePost {
LinkedHashSet<Post> newPosts = new LinkedHashSet<>(); LinkedHashSet<Post> newPosts = new LinkedHashSet<>();
try { try {
JSONObject jsonResponse = new JSONObject(response); JSONObject jsonResponse = new JSONObject(response);
JSONArray allData = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getJSONArray(JSONUtils.CHILDREN_KEY); JSONArray allPosts = jsonResponse.getJSONArray("posts");
//Posts listing //Posts listing
int size; int size;
if (nPosts < 0 || nPosts > allData.length()) { if (nPosts < 0 || nPosts > allPosts.length()) {
size = allData.length(); size = allPosts.length();
} else { } else {
size = nPosts; size = nPosts;
} }
@ -46,16 +52,16 @@ public class ParsePost {
} }
for (int i = 0; i < size; i++) { for (int i = 0; i < size; i++) {
try { try {
if (allData.getJSONObject(i).getString(JSONUtils.KIND_KEY).equals("t3")) {
JSONObject data = allData.getJSONObject(i).getJSONObject(JSONUtils.DATA_KEY); JSONObject data = allPosts.getJSONObject(i);
Post post = parseBasicData(data); Post post = parseBasicData(data);
if (readPostHashSet != null && readPostHashSet.contains(post.getId())) { if (readPostHashSet != null && readPostHashSet.contains(String.valueOf(post.getId()))) {
post.markAsRead(); post.markAsRead();
} }
if (PostFilter.isPostAllowed(post, postFilter)) { if (PostFilter.isPostAllowed(post, postFilter)) {
newPosts.add(post); newPosts.add(post);
} }
}
} catch (JSONException e) { } catch (JSONException e) {
e.printStackTrace(); e.printStackTrace();
} }
@ -126,162 +132,81 @@ public class ParsePost {
} }
public static Post parseBasicData(JSONObject data) throws JSONException { public static Post parseBasicData(JSONObject data) throws JSONException {
String id = data.getString(JSONUtils.ID_KEY); JSONObject post = data.getJSONObject("post");
String fullName = data.getString(JSONUtils.NAME_KEY); JSONObject creator = data.getJSONObject("creator");
String subredditName = data.getString(JSONUtils.SUBREDDIT_KEY); JSONObject community = data.getJSONObject("community");
String subredditNamePrefixed = data.getString(JSONUtils.SUBREDDIT_NAME_PREFIX_KEY); JSONObject counts = data.getJSONObject("counts");
String author = data.getString(JSONUtils.AUTHOR_KEY);
StringBuilder authorFlairHTMLBuilder = new StringBuilder(); int id = post.getInt("id");
if (data.has(JSONUtils.AUTHOR_FLAIR_RICHTEXT_KEY)) { String fullName = post.getString("name");
JSONArray flairArray = data.getJSONArray(JSONUtils.AUTHOR_FLAIR_RICHTEXT_KEY); String subredditName = community.getString("name");
for (int i = 0; i < flairArray.length(); i++) { String subredditNamePrefixed = LemmyUtils.actorID2FullName(community.getString("actor_id"));
JSONObject flairObject = flairArray.getJSONObject(i); String author = creator.getString("name");
String e = flairObject.getString(JSONUtils.E_KEY); String authorFull = LemmyUtils.actorID2FullName(creator.getString("actor_id"));
if (e.equals("text")) { long postTimeMillis = 0;
authorFlairHTMLBuilder.append(flairObject.getString(JSONUtils.T_KEY)); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
} else if (e.equals("emoji")) { postTimeMillis = ZonedDateTime.parse(post.getString("published"),
authorFlairHTMLBuilder.append("<img src=\"").append(Html.escapeHtml(flairObject.getString(JSONUtils.U_KEY))).append("\">"); DateTimeFormatter.ISO_DATE_TIME.withZone(ZoneId.of("Z"))).toInstant().toEpochMilli();
} }
} String title = post.getString("name");
} String permalink = post.getString("ap_id");
String authorFlair = data.isNull(JSONUtils.AUTHOR_FLAIR_TEXT_KEY) ? "" : data.getString(JSONUtils.AUTHOR_FLAIR_TEXT_KEY); int score = counts.getInt("score");
String distinguished = data.getString(JSONUtils.DISTINGUISHED_KEY); int voteType = 0;
String suggestedSort = data.has(JSONUtils.SUGGESTED_SORT_KEY) ? data.getString(JSONUtils.SUGGESTED_SORT_KEY) : null; int nComments = counts.getInt("comments");
long postTime = data.getLong(JSONUtils.CREATED_UTC_KEY) * 1000; int upvoteRatio = 100 * counts.getInt("upvotes") / max(counts.getInt("upvotes") + counts.getInt("downvotes"),1);
String title = data.getString(JSONUtils.TITLE_KEY); boolean hidden = community.getBoolean("hidden");
int score = data.getInt(JSONUtils.SCORE_KEY); boolean nsfw = post.getBoolean("nsfw");
int voteType; boolean locked = post.getBoolean("locked");
int nComments = data.getInt(JSONUtils.NUM_COMMENTS_KEY); boolean saved = data.getBoolean("saved");
int upvoteRatio = (int) (data.getDouble(JSONUtils.UPVOTE_RATIO_KEY) * 100); String distinguished = "";
boolean hidden = data.getBoolean(JSONUtils.HIDDEN_KEY); String suggestedSort = "";
boolean spoiler = data.getBoolean(JSONUtils.SPOILER_KEY); ArrayList <Post.Preview> previews = new ArrayList<>();
boolean nsfw = data.getBoolean(JSONUtils.NSFW_KEY); if(!post.isNull("thumbnail_url")){
boolean stickied = data.getBoolean(JSONUtils.STICKIED_KEY); previews.add(new Post.Preview(post.getString("thumbnail_url"),0,0,"",""));
boolean archived = data.getBoolean(JSONUtils.ARCHIVED_KEY);
boolean locked = data.getBoolean(JSONUtils.LOCKED_KEY);
boolean saved = data.getBoolean(JSONUtils.SAVED_KEY);
boolean deleted = !data.isNull(JSONUtils.REMOVED_BY_CATEGORY_KEY) && data.getString(JSONUtils.REMOVED_BY_CATEGORY_KEY).equals("deleted");
boolean removed = !data.isNull(JSONUtils.REMOVED_BY_CATEGORY_KEY) && data.getString(JSONUtils.REMOVED_BY_CATEGORY_KEY).equals("moderator");
StringBuilder postFlairHTMLBuilder = new StringBuilder();
String flair = "";
if (data.has(JSONUtils.LINK_FLAIR_RICHTEXT_KEY)) {
JSONArray flairArray = data.getJSONArray(JSONUtils.LINK_FLAIR_RICHTEXT_KEY);
for (int i = 0; i < flairArray.length(); i++) {
JSONObject flairObject = flairArray.getJSONObject(i);
String e = flairObject.getString(JSONUtils.E_KEY);
if (e.equals("text")) {
postFlairHTMLBuilder.append(Html.escapeHtml(flairObject.getString(JSONUtils.T_KEY)));
} else if (e.equals("emoji")) {
postFlairHTMLBuilder.append("<img src=\"").append(Html.escapeHtml(flairObject.getString(JSONUtils.U_KEY))).append("\">");
}
}
flair = postFlairHTMLBuilder.toString();
} }
if (flair.equals("") && data.has(JSONUtils.LINK_FLAIR_TEXT_KEY) && !data.isNull(JSONUtils.LINK_FLAIR_TEXT_KEY)) {
flair = data.getString(JSONUtils.LINK_FLAIR_TEXT_KEY);
}
StringBuilder awardingsBuilder = new StringBuilder();
JSONArray awardingsArray = data.getJSONArray(JSONUtils.ALL_AWARDINGS_KEY);
int nAwards = 0;
for (int i = 0; i < awardingsArray.length(); i++) {
JSONObject award = awardingsArray.getJSONObject(i);
int count = award.getInt(JSONUtils.COUNT_KEY);
nAwards += count;
JSONArray icons = award.getJSONArray(JSONUtils.RESIZED_ICONS_KEY);
if (icons.length() > 4) {
String iconUrl = icons.getJSONObject(3).getString(JSONUtils.URL_KEY);
awardingsBuilder.append("<img src=\"").append(Html.escapeHtml(iconUrl)).append("\"> ").append("x").append(count).append(" ");
} else if (icons.length() > 0) {
String iconUrl = icons.getJSONObject(icons.length() - 1).getString(JSONUtils.URL_KEY);
awardingsBuilder.append("<img src=\"").append(Html.escapeHtml(iconUrl)).append("\"> ").append("x").append(count).append(" ");
}
}
if (data.isNull(JSONUtils.LIKES_KEY)) {
voteType = 0;
} else {
voteType = data.getBoolean(JSONUtils.LIKES_KEY) ? 1 : -1;
score -= voteType;
}
String permalink = Html.fromHtml(data.getString(JSONUtils.PERMALINK_KEY)).toString();
ArrayList<Post.Preview> previews = new ArrayList<>();
if (data.has(JSONUtils.PREVIEW_KEY)) {
JSONObject images = data.getJSONObject(JSONUtils.PREVIEW_KEY).getJSONArray(JSONUtils.IMAGES_KEY).getJSONObject(0);
String previewUrl = images.getJSONObject(JSONUtils.SOURCE_KEY).getString(JSONUtils.URL_KEY);
int previewWidth = images.getJSONObject(JSONUtils.SOURCE_KEY).getInt(JSONUtils.WIDTH_KEY);
int previewHeight = images.getJSONObject(JSONUtils.SOURCE_KEY).getInt(JSONUtils.HEIGHT_KEY);
previews.add(new Post.Preview(previewUrl, previewWidth, previewHeight, "", ""));
JSONArray thumbnailPreviews = images.getJSONArray(JSONUtils.RESOLUTIONS_KEY);
for (int i = 0; i < thumbnailPreviews.length(); i++) {
JSONObject thumbnailPreview = thumbnailPreviews.getJSONObject(i);
String thumbnailPreviewUrl = thumbnailPreview.getString(JSONUtils.URL_KEY);
int thumbnailPreviewWidth = thumbnailPreview.getInt(JSONUtils.WIDTH_KEY);
int thumbnailPreviewHeight = thumbnailPreview.getInt(JSONUtils.HEIGHT_KEY);
previews.add(new Post.Preview(thumbnailPreviewUrl, thumbnailPreviewWidth, thumbnailPreviewHeight, "", ""));
}
}
if (data.has(JSONUtils.CROSSPOST_PARENT_LIST)) {
//Cross post
//data.getJSONArray(JSONUtils.CROSSPOST_PARENT_LIST).getJSONObject(0) out of bounds????????????
data = data.getJSONArray(JSONUtils.CROSSPOST_PARENT_LIST).getJSONObject(0);
Post crosspostParent = parseBasicData(data);
Post post = parseData(data, permalink, id, fullName, subredditName, subredditNamePrefixed,
author, authorFlair, authorFlairHTMLBuilder.toString(),
postTime, title, previews,
score, voteType, nComments, upvoteRatio, flair, awardingsBuilder.toString(), nAwards, hidden,
spoiler, nsfw, stickied, archived, locked, saved, deleted, removed, true,
distinguished, suggestedSort);
post.setCrosspostParentId(crosspostParent.getId());
return post;
} else {
return parseData(data, permalink, id, fullName, subredditName, subredditNamePrefixed, return parseData(data, permalink, id, fullName, subredditName, subredditNamePrefixed,
author, authorFlair, authorFlairHTMLBuilder.toString(), author,authorFull, postTimeMillis, title, previews,
postTime, title, previews, score, voteType, nComments, upvoteRatio, nsfw, locked, saved,
score, voteType, nComments, upvoteRatio, flair, awardingsBuilder.toString(), nAwards, hidden,
spoiler, nsfw, stickied, archived, locked, saved, deleted, removed, false,
distinguished, suggestedSort); distinguished, suggestedSort);
}
} }
private static Post parseData(JSONObject data, String permalink, String id, String fullName, private static Post parseData(JSONObject data, String permalink, int id, String fullName,
String subredditName, String subredditNamePrefixed, String author, String subredditName, String subredditNamePrefixed, String author, String authorFull,
String authorFlair, String authorFlairHTML,
long postTimeMillis, String title, ArrayList<Post.Preview> previews, long postTimeMillis, String title, ArrayList<Post.Preview> previews,
int score, int voteType, int nComments, int upvoteRatio, String flair, int score, int voteType, int nComments, int upvoteRatio,
String awards, int nAwards, boolean hidden, boolean spoiler, boolean nsfw, boolean locked,
boolean nsfw, boolean stickied, boolean archived, boolean locked, boolean saved,
boolean saved, boolean deleted, boolean removed, boolean isCrosspost,
String distinguished, String suggestedSort) throws JSONException { String distinguished, String suggestedSort) throws JSONException {
Post post; Post post;
boolean isVideo = data.getBoolean(JSONUtils.IS_VIDEO_KEY); boolean isVideo = false;
String url = Html.fromHtml(data.getString(JSONUtils.URL_KEY)).toString(); String url = (!data.getJSONObject("post").isNull("url")) ? data.getJSONObject("post").getString("url") : "";
Uri uri = Uri.parse(url); Uri uri = Uri.parse(url);
String path = uri.getPath(); String path = uri.getPath();
if (!data.has(JSONUtils.PREVIEW_KEY) && previews.isEmpty()) { if (!data.has(JSONUtils.PREVIEW_KEY) && previews.isEmpty()) {
if (url.contains(permalink)) { if (!data.getJSONObject("post").isNull("body")) {
//Text post //Text post
int postType = Post.TEXT_TYPE; int postType = Post.TEXT_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, permalink, score, postType, postTimeMillis, title, permalink, score,
voteType, nComments, upvoteRatio, flair, awards, nAwards, hidden, spoiler, nsfw, postType, voteType, nComments, upvoteRatio, nsfw,
stickied, archived, locked, saved, isCrosspost, distinguished, suggestedSort); locked, saved, distinguished, suggestedSort);
String body = data.getJSONObject("post").getString("body");
post.setSelfText(body);
post.setSelfTextPlain(body);
post.setSelfTextPlainTrimmed(body.trim());
} else { } else {
if (path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".jpeg")) { if (path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".jpeg") || path.endsWith(".webp")) {
//Image post //Image post
int postType = Post.IMAGE_TYPE; int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, hidden, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
spoiler, nsfw, stickied, archived, locked, saved, isCrosspost, distinguished, suggestedSort);
if (previews.isEmpty()) { if (previews.isEmpty()) {
previews.add(new Post.Preview(url, 0, 0, "", "")); previews.add(new Post.Preview(url, 0, 0, "", ""));
@ -295,20 +220,17 @@ public class ParsePost {
String videoUrl = Html.fromHtml(redditVideoObject.getString(JSONUtils.HLS_URL_KEY)).toString(); String videoUrl = Html.fromHtml(redditVideoObject.getString(JSONUtils.HLS_URL_KEY)).toString();
String videoDownloadUrl = redditVideoObject.getString(JSONUtils.FALLBACK_URL_KEY); String videoDownloadUrl = redditVideoObject.getString(JSONUtils.FALLBACK_URL_KEY);
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFlair, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull, postTimeMillis, title, permalink, score, postType, voteType,
authorFlairHTML, postTimeMillis, title, permalink, score, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
nComments, upvoteRatio, flair, awards, nAwards, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost, distinguished, suggestedSort);
post.setVideoUrl(videoUrl); post.setVideoUrl(videoUrl);
post.setVideoDownloadUrl(videoDownloadUrl); post.setVideoDownloadUrl(videoDownloadUrl);
} else { } else {
//No preview link post //No preview link post
int postType = Post.NO_PREVIEW_LINK_TYPE; int postType = Post.NO_PREVIEW_LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, hidden, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
spoiler, nsfw, stickied, archived, locked, saved, isCrosspost, distinguished, suggestedSort);
if (data.isNull(JSONUtils.SELFTEXT_KEY)) { if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText(""); post.setSelfText("");
} else { } else {
@ -369,10 +291,8 @@ public class ParsePost {
String videoUrl = Html.fromHtml(redditVideoObject.getString(JSONUtils.HLS_URL_KEY)).toString(); String videoUrl = Html.fromHtml(redditVideoObject.getString(JSONUtils.HLS_URL_KEY)).toString();
String videoDownloadUrl = redditVideoObject.getString(JSONUtils.FALLBACK_URL_KEY); String videoDownloadUrl = redditVideoObject.getString(JSONUtils.FALLBACK_URL_KEY);
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFlair, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull, postTimeMillis, title, permalink, score, postType, voteType,
authorFlairHTML, postTimeMillis, title, permalink, score, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
nComments, upvoteRatio, flair, awards, nAwards, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost, distinguished, suggestedSort);
post.setPreviews(previews); post.setPreviews(previews);
post.setVideoUrl(videoUrl); post.setVideoUrl(videoUrl);
@ -387,10 +307,8 @@ public class ParsePost {
url = url.substring(0, url.length() - 5) + ".mp4"; url = url.substring(0, url.length() - 5) + ".mp4";
} }
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFlair, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFull,postTimeMillis, title, permalink, score, postType, voteType,
authorFlairHTML, postTimeMillis, title, permalink, score, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
nComments, upvoteRatio, flair, awards, nAwards, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost, distinguished, suggestedSort);
post.setPreviews(previews); post.setPreviews(previews);
post.setVideoUrl(url); post.setVideoUrl(url);
post.setVideoDownloadUrl(url); post.setVideoDownloadUrl(url);
@ -403,23 +321,20 @@ public class ParsePost {
String videoDownloadUrl = data.getJSONObject(JSONUtils.PREVIEW_KEY) String videoDownloadUrl = data.getJSONObject(JSONUtils.PREVIEW_KEY)
.getJSONObject(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY).getString(JSONUtils.FALLBACK_URL_KEY); .getJSONObject(JSONUtils.REDDIT_VIDEO_PREVIEW_KEY).getString(JSONUtils.FALLBACK_URL_KEY);
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, authorFlair, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull, postTimeMillis, title, permalink, score, postType, voteType,
authorFlairHTML, postTimeMillis, title, permalink, score, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
nComments, upvoteRatio, flair, awards, nAwards, hidden, spoiler, nsfw, stickied,
archived, locked, saved, isCrosspost, distinguished, suggestedSort);
post.setPreviews(previews); post.setPreviews(previews);
post.setVideoUrl(videoUrl); post.setVideoUrl(videoUrl);
post.setVideoDownloadUrl(videoDownloadUrl); post.setVideoDownloadUrl(videoDownloadUrl);
} }
} else { } else {
if (path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".jpeg")) { if (path.endsWith(".jpg") || path.endsWith(".png") || path.endsWith(".jpeg")|| path.endsWith(".webp")) {
//Image post //Image post
int postType = Post.IMAGE_TYPE; int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, authorFull,postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved,
hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost,
distinguished, suggestedSort); distinguished, suggestedSort);
if (previews.isEmpty()) { if (previews.isEmpty()) {
@ -429,10 +344,10 @@ public class ParsePost {
} else if (path.endsWith(".gif")) { } else if (path.endsWith(".gif")) {
//Gif post //Gif post
int postType = Post.GIF_TYPE; int postType = Post.GIF_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, postType, voteType, nComments, upvoteRatio,
hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost, nsfw, locked, saved,
distinguished, suggestedSort); distinguished, suggestedSort);
post.setPreviews(previews); post.setPreviews(previews);
@ -445,10 +360,10 @@ public class ParsePost {
url = url.substring(0, url.length() - 5) + ".mp4"; url = url.substring(0, url.length() - 5) + ".mp4";
} }
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, postType, voteType, nComments, upvoteRatio,
hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost, nsfw, locked, saved,
distinguished, suggestedSort); distinguished, suggestedSort);
post.setPreviews(previews); post.setPreviews(previews);
post.setVideoUrl(url); post.setVideoUrl(url);
@ -458,10 +373,9 @@ public class ParsePost {
//Video post //Video post
int postType = Post.VIDEO_TYPE; int postType = Post.VIDEO_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved,
hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost,
distinguished, suggestedSort); distinguished, suggestedSort);
post.setPreviews(previews); post.setPreviews(previews);
post.setVideoUrl(url); post.setVideoUrl(url);
@ -471,10 +385,9 @@ public class ParsePost {
//Text post but with a preview //Text post but with a preview
int postType = Post.TEXT_TYPE; int postType = Post.TEXT_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, permalink, score, postTimeMillis, title, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved,
hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost,
distinguished, suggestedSort); distinguished, suggestedSort);
//Need attention //Need attention
@ -483,10 +396,9 @@ public class ParsePost {
//Link post //Link post
int postType = Post.LINK_TYPE; int postType = Post.LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved,
hidden, spoiler, nsfw, stickied, archived, locked, saved, isCrosspost,
distinguished, suggestedSort); distinguished, suggestedSort);
if (data.isNull(JSONUtils.SELFTEXT_KEY)) { if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText(""); post.setSelfText("");
@ -527,10 +439,9 @@ public class ParsePost {
//Image post //Image post
int postType = Post.IMAGE_TYPE; int postType = Post.IMAGE_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, hidden, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
spoiler, nsfw, stickied, archived, locked, saved, isCrosspost, distinguished, suggestedSort);
if (previews.isEmpty()) { if (previews.isEmpty()) {
previews.add(new Post.Preview(url, 0, 0, "", "")); previews.add(new Post.Preview(url, 0, 0, "", ""));
@ -540,10 +451,9 @@ public class ParsePost {
//Video post //Video post
int postType = Post.VIDEO_TYPE; int postType = Post.VIDEO_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, hidden, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
spoiler, nsfw, stickied, archived, locked, saved, isCrosspost, distinguished, suggestedSort);
post.setPreviews(previews); post.setPreviews(previews);
post.setVideoUrl(url); post.setVideoUrl(url);
post.setVideoDownloadUrl(url); post.setVideoDownloadUrl(url);
@ -551,10 +461,9 @@ public class ParsePost {
//CP No Preview Link post //CP No Preview Link post
int postType = Post.NO_PREVIEW_LINK_TYPE; int postType = Post.NO_PREVIEW_LINK_TYPE;
post = new Post(id, fullName, subredditName, subredditNamePrefixed, author, post = new Post(id, fullName, subredditName, subredditNamePrefixed, author,authorFull,
authorFlair, authorFlairHTML, postTimeMillis, title, url, permalink, score, postTimeMillis, title, url, permalink, score,
postType, voteType, nComments, upvoteRatio, flair, awards, nAwards, hidden, postType, voteType, nComments, upvoteRatio, nsfw, locked, saved, distinguished, suggestedSort);
spoiler, nsfw, stickied, archived, locked, saved, isCrosspost, distinguished, suggestedSort);
//Need attention //Need attention
if (data.isNull(JSONUtils.SELFTEXT_KEY)) { if (data.isNull(JSONUtils.SELFTEXT_KEY)) {
post.setSelfText(""); post.setSelfText("");
@ -728,7 +637,21 @@ public class ParsePost {
} }
} }
} }
if(data.getBoolean("read")){
post.markAsRead();
}
if(!data.isNull("my_vote")){
post.setVoteType(data.getInt("my_vote"));
post.setScore(post.getScore()-1);
}
if (!data.getJSONObject("post").isNull("body")) {
String body = data.getJSONObject("post").getString("body");
post.setSelfText(body);
post.setSelfTextPlain(body);
post.setSelfTextPlainTrimmed(body.trim());
}
return post; return post;
} }

View File

@ -33,7 +33,7 @@ public class Post implements Parcelable {
return new Post[size]; return new Post[size];
} }
}; };
private String id; private int id;
private String fullName; private String fullName;
private String subredditName; private String subredditName;
private String subredditNamePrefixed; private String subredditNamePrefixed;
@ -41,8 +41,6 @@ public class Post implements Parcelable {
private String author; private String author;
private String authorNamePrefixed; private String authorNamePrefixed;
private String authorIconUrl; private String authorIconUrl;
private String authorFlair;
private String authorFlairHTML;
private String title; private String title;
private String selfText; private String selfText;
private String selfTextPlain; private String selfTextPlain;
@ -58,9 +56,6 @@ public class Post implements Parcelable {
private boolean isStreamable; private boolean isStreamable;
private boolean loadGfyOrStreamableVideoSuccess; private boolean loadGfyOrStreamableVideoSuccess;
private String permalink; private String permalink;
private String flair;
private String awards;
private int nAwards;
private long postTimeMillis; private long postTimeMillis;
private int score; private int score;
private int postType; private int postType;
@ -68,7 +63,6 @@ public class Post implements Parcelable {
private int nComments; private int nComments;
private int upvoteRatio; private int upvoteRatio;
private boolean hidden; private boolean hidden;
private boolean spoiler;
private boolean nsfw; private boolean nsfw;
private boolean stickied; private boolean stickied;
private boolean archived; private boolean archived;
@ -82,20 +76,18 @@ public class Post implements Parcelable {
private ArrayList<Preview> previews = new ArrayList<>(); private ArrayList<Preview> previews = new ArrayList<>();
private ArrayList<Gallery> gallery = new ArrayList<>(); private ArrayList<Gallery> gallery = new ArrayList<>();
public Post(String id, String fullName, String subredditName, String subredditNamePrefixed, public Post(int id, String fullName, String subredditName, String subredditNamePrefixed,
String author, String authorFlair, String authorFlairHTML, long postTimeMillis, String author,String authorNamePrefixed, long postTimeMillis,
String title, String permalink, int score, int postType, int voteType, int nComments, String title, String permalink, int score, int postType, int voteType, int nComments,
int upvoteRatio, String flair, String awards, int nAwards, boolean hidden, boolean spoiler, int upvoteRatio,
boolean nsfw, boolean stickied, boolean archived, boolean locked, boolean saved, boolean nsfw, boolean locked, boolean saved,
boolean isCrosspost, String distinguished, String suggestedSort) { String distinguished, String suggestedSort) {
this.id = id; this.id = id;
this.fullName = fullName; this.fullName = fullName;
this.subredditName = subredditName; this.subredditName = subredditName;
this.subredditNamePrefixed = subredditNamePrefixed; this.subredditNamePrefixed = subredditNamePrefixed;
this.author = author; this.author = author;
this.authorNamePrefixed = "u/" + author; this.authorNamePrefixed = authorNamePrefixed;
this.authorFlair = authorFlair;
this.authorFlairHTML = authorFlairHTML;
this.postTimeMillis = postTimeMillis; this.postTimeMillis = postTimeMillis;
this.title = title; this.title = title;
this.permalink = APIUtils.API_BASE_URI + permalink; this.permalink = APIUtils.API_BASE_URI + permalink;
@ -104,11 +96,7 @@ public class Post implements Parcelable {
this.voteType = voteType; this.voteType = voteType;
this.nComments = nComments; this.nComments = nComments;
this.upvoteRatio = upvoteRatio; this.upvoteRatio = upvoteRatio;
this.flair = flair;
this.awards = awards;
this.nAwards = nAwards;
this.hidden = hidden; this.hidden = hidden;
this.spoiler = spoiler;
this.nsfw = nsfw; this.nsfw = nsfw;
this.stickied = stickied; this.stickied = stickied;
this.archived = archived; this.archived = archived;
@ -120,20 +108,17 @@ public class Post implements Parcelable {
isRead = false; isRead = false;
} }
public Post(String id, String fullName, String subredditName, String subredditNamePrefixed, public Post(int id, String fullName, String subredditName, String subredditNamePrefixed,
String author, String authorFlair, String authorFlairHTML, long postTimeMillis, String title, String author, String authorNamePrefixed, long postTimeMillis, String title,
String url, String permalink, int score, int postType, int voteType, int nComments, String url, String permalink, int score, int postType, int voteType, int nComments,
int upvoteRatio, String flair, String awards, int nAwards, boolean hidden, boolean spoiler, int upvoteRatio,
boolean nsfw, boolean stickied, boolean archived, boolean locked, boolean saved, boolean nsfw, boolean locked, boolean saved, String distinguished, String suggestedSort) {
boolean isCrosspost, String distinguished, String suggestedSort) {
this.id = id; this.id = id;
this.fullName = fullName; this.fullName = fullName;
this.subredditName = subredditName; this.subredditName = subredditName;
this.subredditNamePrefixed = subredditNamePrefixed; this.subredditNamePrefixed = subredditNamePrefixed;
this.author = author; this.author = author;
this.authorNamePrefixed = "u/" + author; this.authorNamePrefixed = authorNamePrefixed;
this.authorFlair = authorFlair;
this.authorFlairHTML = authorFlairHTML;
this.postTimeMillis = postTimeMillis; this.postTimeMillis = postTimeMillis;
this.title = title; this.title = title;
this.url = url; this.url = url;
@ -143,11 +128,7 @@ public class Post implements Parcelable {
this.voteType = voteType; this.voteType = voteType;
this.nComments = nComments; this.nComments = nComments;
this.upvoteRatio = upvoteRatio; this.upvoteRatio = upvoteRatio;
this.flair = flair;
this.awards = awards;
this.nAwards = nAwards;
this.hidden = hidden; this.hidden = hidden;
this.spoiler = spoiler;
this.nsfw = nsfw; this.nsfw = nsfw;
this.stickied = stickied; this.stickied = stickied;
this.archived = archived; this.archived = archived;
@ -160,15 +141,13 @@ public class Post implements Parcelable {
} }
protected Post(Parcel in) { protected Post(Parcel in) {
id = in.readString(); id = in.readInt();
fullName = in.readString(); fullName = in.readString();
subredditName = in.readString(); subredditName = in.readString();
subredditNamePrefixed = in.readString(); subredditNamePrefixed = in.readString();
subredditIconUrl = in.readString(); subredditIconUrl = in.readString();
author = in.readString(); author = in.readString();
authorNamePrefixed = in.readString(); authorNamePrefixed = in.readString();
authorFlair = in.readString();
authorFlairHTML = in.readString();
authorIconUrl = in.readString(); authorIconUrl = in.readString();
postTimeMillis = in.readLong(); postTimeMillis = in.readLong();
title = in.readString(); title = in.readString();
@ -186,16 +165,12 @@ public class Post implements Parcelable {
isStreamable = in.readByte() != 0; isStreamable = in.readByte() != 0;
loadGfyOrStreamableVideoSuccess = in.readByte() != 0; loadGfyOrStreamableVideoSuccess = in.readByte() != 0;
permalink = in.readString(); permalink = in.readString();
flair = in.readString();
awards = in.readString();
nAwards = in.readInt();
score = in.readInt(); score = in.readInt();
postType = in.readInt(); postType = in.readInt();
voteType = in.readInt(); voteType = in.readInt();
nComments = in.readInt(); nComments = in.readInt();
upvoteRatio = in.readInt(); upvoteRatio = in.readInt();
hidden = in.readByte() != 0; hidden = in.readByte() != 0;
spoiler = in.readByte() != 0;
nsfw = in.readByte() != 0; nsfw = in.readByte() != 0;
stickied = in.readByte() != 0; stickied = in.readByte() != 0;
archived = in.readByte() != 0; archived = in.readByte() != 0;
@ -210,7 +185,7 @@ public class Post implements Parcelable {
in.readTypedList(gallery, Gallery.CREATOR); in.readTypedList(gallery, Gallery.CREATOR);
} }
public String getId() { public int getId() {
return id; return id;
} }
@ -251,14 +226,6 @@ public class Post implements Parcelable {
return authorNamePrefixed; return authorNamePrefixed;
} }
public String getAuthorFlair() {
return authorFlair;
}
public String getAuthorFlairHTML() {
return authorFlairHTML;
}
public String getAuthorIconUrl() { public String getAuthorIconUrl() {
return authorIconUrl; return authorIconUrl;
} }
@ -387,14 +354,6 @@ public class Post implements Parcelable {
return permalink; return permalink;
} }
public String getFlair() {
return flair;
}
public void setFlair(String flair) {
this.flair = flair;
}
public boolean isModerator() { public boolean isModerator() {
return distinguished != null && distinguished.equals("moderator"); return distinguished != null && distinguished.equals("moderator");
} }
@ -407,22 +366,6 @@ public class Post implements Parcelable {
return suggestedSort; return suggestedSort;
} }
public String getAwards() {
return awards;
}
public void addAwards(String newAwardsHTML) {
awards += newAwardsHTML;
}
public int getNAwards() {
return nAwards;
}
public void addAwards(int newNAwards) {
nAwards += newNAwards;
}
public int getScore() { public int getScore() {
return score; return score;
} }
@ -471,14 +414,6 @@ public class Post implements Parcelable {
this.hidden = hidden; this.hidden = hidden;
} }
public boolean isSpoiler() {
return spoiler;
}
public void setSpoiler(boolean spoiler) {
this.spoiler = spoiler;
}
public boolean isNSFW() { public boolean isNSFW() {
return nsfw; return nsfw;
} }
@ -550,15 +485,13 @@ public class Post implements Parcelable {
@Override @Override
public void writeToParcel(Parcel parcel, int i) { public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(id); parcel.writeInt(id);
parcel.writeString(fullName); parcel.writeString(fullName);
parcel.writeString(subredditName); parcel.writeString(subredditName);
parcel.writeString(subredditNamePrefixed); parcel.writeString(subredditNamePrefixed);
parcel.writeString(subredditIconUrl); parcel.writeString(subredditIconUrl);
parcel.writeString(author); parcel.writeString(author);
parcel.writeString(authorNamePrefixed); parcel.writeString(authorNamePrefixed);
parcel.writeString(authorFlair);
parcel.writeString(authorFlairHTML);
parcel.writeString(authorIconUrl); parcel.writeString(authorIconUrl);
parcel.writeLong(postTimeMillis); parcel.writeLong(postTimeMillis);
parcel.writeString(title); parcel.writeString(title);
@ -576,16 +509,12 @@ public class Post implements Parcelable {
parcel.writeByte((byte) (isStreamable ? 1 : 0)); parcel.writeByte((byte) (isStreamable ? 1 : 0));
parcel.writeByte((byte) (loadGfyOrStreamableVideoSuccess ? 1 : 0)); parcel.writeByte((byte) (loadGfyOrStreamableVideoSuccess ? 1 : 0));
parcel.writeString(permalink); parcel.writeString(permalink);
parcel.writeString(flair);
parcel.writeString(awards);
parcel.writeInt(nAwards);
parcel.writeInt(score); parcel.writeInt(score);
parcel.writeInt(postType); parcel.writeInt(postType);
parcel.writeInt(voteType); parcel.writeInt(voteType);
parcel.writeInt(nComments); parcel.writeInt(nComments);
parcel.writeInt(upvoteRatio); parcel.writeInt(upvoteRatio);
parcel.writeByte((byte) (hidden ? 1 : 0)); parcel.writeByte((byte) (hidden ? 1 : 0));
parcel.writeByte((byte) (spoiler ? 1 : 0));
parcel.writeByte((byte) (nsfw ? 1 : 0)); parcel.writeByte((byte) (nsfw ? 1 : 0));
parcel.writeByte((byte) (stickied ? 1 : 0)); parcel.writeByte((byte) (stickied ? 1 : 0));
parcel.writeByte((byte) (archived ? 1 : 0)); parcel.writeByte((byte) (archived ? 1 : 0));
@ -605,12 +534,12 @@ public class Post implements Parcelable {
if (!(obj instanceof Post)) { if (!(obj instanceof Post)) {
return false; return false;
} }
return ((Post) obj).id.equals(id); return ((Post) obj).id == id;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return id.hashCode(); return Integer.valueOf(id).hashCode();
} }
public static class Gallery implements Parcelable { public static class Gallery implements Parcelable {

View File

@ -15,18 +15,18 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.LinkedHashSet; import java.util.LinkedHashSet;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.postfilter.PostFilter; import eu.toldi.infinityforlemmy.postfilter.PostFilter;
import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils; import eu.toldi.infinityforlemmy.utils.SharedPreferencesUtils;
import retrofit2.HttpException; import retrofit2.HttpException;
import retrofit2.Response; import retrofit2.Response;
import retrofit2.Retrofit; import retrofit2.Retrofit;
public class PostPagingSource extends ListenableFuturePagingSource<String, Post> { public class PostPagingSource extends ListenableFuturePagingSource<Integer, Post> {
public static final int TYPE_FRONT_PAGE = 0; public static final int TYPE_FRONT_PAGE = 0;
public static final int TYPE_SUBREDDIT = 1; public static final int TYPE_SUBREDDIT = 1;
public static final int TYPE_USER = 2; public static final int TYPE_USER = 2;
@ -59,18 +59,21 @@ public class PostPagingSource extends ListenableFuturePagingSource<String, Post>
private String multiRedditPath; private String multiRedditPath;
private LinkedHashSet<Post> postLinkedHashSet; private LinkedHashSet<Post> postLinkedHashSet;
private int page = 1;
PostPagingSource(Executor executor, Retrofit retrofit, String accessToken, String accountName, PostPagingSource(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences sharedPreferences,
SharedPreferences postFeedScrolledPositionSharedPreferences, int postType, SharedPreferences postFeedScrolledPositionSharedPreferences, int postType,
SortType sortType, PostFilter postFilter, List<String> readPostList) { SortType sortType, PostFilter postFilter, List<String> readPostList,String option) {
this.executor = executor; this.executor = executor;
this.retrofit = retrofit; this.retrofit = retrofit;
this.accessToken = accessToken; this.accessToken = accessToken;
this.accountName = accountName; this.accountName = accountName;
this.subredditOrUserName = option;
this.sharedPreferences = sharedPreferences; this.sharedPreferences = sharedPreferences;
this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences; this.postFeedScrolledPositionSharedPreferences = postFeedScrolledPositionSharedPreferences;
this.postType = postType; this.postType = postType;
this.sortType = sortType == null ? new SortType(SortType.Type.BEST) : sortType; this.sortType = sortType == null ? new SortType(SortType.Type.ACTIVE) : sortType;
this.postFilter = postFilter; this.postFilter = postFilter;
this.readPostList = readPostList; this.readPostList = readPostList;
postLinkedHashSet = new LinkedHashSet<>(); postLinkedHashSet = new LinkedHashSet<>();
@ -101,10 +104,10 @@ public class PostPagingSource extends ListenableFuturePagingSource<String, Post>
} }
this.postType = postType; this.postType = postType;
if (sortType == null) { if (sortType == null) {
if (path.equals("popular") || path.equals("all")) { if (path.equals("local") || path.equals("all")) {
this.sortType = new SortType(SortType.Type.HOT); this.sortType = new SortType(SortType.Type.HOT);
} else { } else {
this.sortType = new SortType(SortType.Type.BEST); this.sortType = new SortType(SortType.Type.ACTIVE);
} }
} else { } else {
this.sortType = sortType; this.sortType = sortType;
@ -155,44 +158,46 @@ public class PostPagingSource extends ListenableFuturePagingSource<String, Post>
@Nullable @Nullable
@Override @Override
public String getRefreshKey(@NonNull PagingState<String, Post> pagingState) { public Integer getRefreshKey(@NonNull PagingState<Integer, Post> pagingState) {
return null; return null;
} }
@NonNull @NonNull
@Override @Override
public ListenableFuture<LoadResult<String, Post>> loadFuture(@NonNull LoadParams<String> loadParams) { public ListenableFuture<LoadResult<Integer, Post>> loadFuture(@NonNull LoadParams<Integer> loadParams) {
RedditAPI api = retrofit.create(RedditAPI.class); LemmyAPI api = retrofit.create(LemmyAPI.class);
switch (postType) { switch (postType) {
default:
case TYPE_FRONT_PAGE: case TYPE_FRONT_PAGE:
return loadHomePosts(loadParams, api); return loadHomePosts(loadParams, api);
case TYPE_SUBREDDIT: case TYPE_SUBREDDIT:
return loadSubredditPosts(loadParams, api); return loadSubredditPosts(loadParams, api);
case TYPE_USER: case TYPE_USER:
return loadUserPosts(loadParams, api); return loadUserPosts(loadParams, api);
case TYPE_SEARCH: /* case TYPE_SEARCH:
return loadSearchPosts(loadParams, api); return loadSearchPosts(loadParams, api);
case TYPE_MULTI_REDDIT: case TYPE_MULTI_REDDIT:
return loadMultiRedditPosts(loadParams, api); return loadMultiRedditPosts(loadParams, api);
default: default:
return loadAnonymousHomePosts(loadParams, api); return loadAnonymousHomePosts(loadParams, api);*/
} }
} }
public LoadResult<String, Post> transformData(Response<String> response) { public LoadResult<Integer, Post> transformData(Response<String> response) {
if (response.isSuccessful()) { if (response.isSuccessful()) {
String responseString = response.body(); String responseString = response.body();
LinkedHashSet<Post> newPosts = ParsePost.parsePostsSync(responseString, -1, postFilter, readPostList); LinkedHashSet<Post> newPosts = ParsePost.parsePostsSync(responseString, -1, postFilter, readPostList);
String lastItem = ParsePost.getLastItem(responseString);
if (newPosts == null) { if (newPosts == null) {
return new LoadResult.Error<>(new Exception("Error parsing posts")); return new LoadResult.Error<>(new Exception("Error parsing posts"));
} else { } else {
int currentPostsSize = postLinkedHashSet.size(); int currentPostsSize = postLinkedHashSet.size();
postLinkedHashSet.addAll(newPosts); postLinkedHashSet.addAll(newPosts);
int nextKey = (postLinkedHashSet.size()+1) / 25+1;
if (currentPostsSize == postLinkedHashSet.size()) { if (currentPostsSize == postLinkedHashSet.size()) {
return new LoadResult.Page<>(new ArrayList<>(), null, lastItem); return new LoadResult.Page<>(new ArrayList<>(), null, nextKey);
} else { } else {
return new LoadResult.Page<>(new ArrayList<>(postLinkedHashSet).subList(currentPostsSize, postLinkedHashSet.size()), null, lastItem); return new LoadResult.Page<>(new ArrayList<>(postLinkedHashSet).subList(currentPostsSize, postLinkedHashSet.size()), null, nextKey);
} }
} }
} else { } else {
@ -200,26 +205,28 @@ public class PostPagingSource extends ListenableFuturePagingSource<String, Post>
} }
} }
private ListenableFuture<LoadResult<String, Post>> loadHomePosts(@NonNull LoadParams<String> loadParams, RedditAPI api) { private ListenableFuture<LoadResult<Integer, Post>> loadHomePosts(@NonNull LoadParams<Integer> loadParams, LemmyAPI api) {
ListenableFuture<Response<String>> bestPost; ListenableFuture<Response<String>> bestPost;
String afterKey; Integer page;
if (loadParams.getKey() == null) { if (loadParams.getKey() == null) {
boolean savePostFeedScrolledPosition = sortType != null && sortType.getType() == SortType.Type.BEST && sharedPreferences.getBoolean(SharedPreferencesUtils.SAVE_FRONT_PAGE_SCROLLED_POSITION, false); boolean savePostFeedScrolledPosition = sortType != null && sortType.getType() == SortType.Type.ACTIVE && sharedPreferences.getBoolean(SharedPreferencesUtils.SAVE_FRONT_PAGE_SCROLLED_POSITION, false);
if (savePostFeedScrolledPosition) { if (savePostFeedScrolledPosition) {
String accountNameForCache = accountName == null ? SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_ANONYMOUS : accountName; String accountNameForCache = accountName == null ? SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_ANONYMOUS : accountName;
afterKey = postFeedScrolledPositionSharedPreferences.getString(accountNameForCache + SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_FRONT_PAGE_BASE, null); // TODO: Fix this. Save the page number?
page = null ; // postFeedScrolledPositionSharedPreferences.getString(accountNameForCache + SharedPreferencesUtils.FRONT_PAGE_SCROLLED_POSITION_FRONT_PAGE_BASE, null);
} else { } else {
afterKey = null; page = null;
} }
} else { } else {
afterKey = loadParams.getKey(); page = loadParams.getKey();
} }
bestPost = api.getBestPostsListenableFuture(sortType.getType(), sortType.getTime(), afterKey, String feed_type = Objects.equals(subredditOrUserName, "all") ? "All" : Objects.equals(subredditOrUserName, "local") ? "Local" : "Subscribed";
APIUtils.getOAuthHeader(accessToken));
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(bestPost, this::transformData, executor); bestPost = api.getPosts(feed_type,sortType.getType().value,page,25,null,null,false,accessToken);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture = ListenableFuture<LoadResult<Integer, Post>> pageFuture = Futures.transform(bestPost, this::transformData, executor);
ListenableFuture<LoadResult<Integer, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class, Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor); LoadResult.Error::new, executor);
@ -227,18 +234,15 @@ public class PostPagingSource extends ListenableFuturePagingSource<String, Post>
IOException.class, LoadResult.Error::new, executor); IOException.class, LoadResult.Error::new, executor);
} }
private ListenableFuture<LoadResult<String, Post>> loadSubredditPosts(@NonNull LoadParams<String> loadParams, RedditAPI api) { private ListenableFuture<LoadResult<Integer, Post>> loadSubredditPosts(@NonNull LoadParams<Integer> loadParams, LemmyAPI api) {
ListenableFuture<Response<String>> subredditPost; ListenableFuture<Response<String>> subredditPost;
if (accessToken == null) {
subredditPost = api.getSubredditBestPostsListenableFuture(subredditOrUserName, sortType.getType(), sortType.getTime(), loadParams.getKey());
} else {
subredditPost = api.getSubredditBestPostsOauthListenableFuture(subredditOrUserName, sortType.getType(),
sortType.getTime(), loadParams.getKey(), APIUtils.getOAuthHeader(accessToken));
}
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(subredditPost, this::transformData, executor); subredditPost = api.getPosts(null,sortType.getType().value,loadParams.getKey(),25,null,subredditOrUserName,false,null);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture =
ListenableFuture<LoadResult<Integer, Post>> pageFuture = Futures.transform(subredditPost, this::transformData, executor);
ListenableFuture<LoadResult<Integer, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class, Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor); LoadResult.Error::new, executor);
@ -246,27 +250,22 @@ public class PostPagingSource extends ListenableFuturePagingSource<String, Post>
IOException.class, LoadResult.Error::new, executor); IOException.class, LoadResult.Error::new, executor);
} }
private ListenableFuture<LoadResult<String, Post>> loadUserPosts(@NonNull LoadParams<String> loadParams, RedditAPI api) { private ListenableFuture<LoadResult<Integer, Post>> loadUserPosts(@NonNull LoadParams<Integer> loadParams, LemmyAPI api) {
ListenableFuture<Response<String>> userPosts; ListenableFuture<Response<String>> userPosts;
if (accessToken == null) { userPosts = api.getUserPosts(subredditOrUserName, sortType.getType().value,loadParams.getKey(),25,accessToken);
userPosts = api.getUserPostsListenableFuture(subredditOrUserName, loadParams.getKey(), sortType.getType(),
sortType.getTime());
} else {
userPosts = api.getUserPostsOauthListenableFuture(subredditOrUserName, userWhere, loadParams.getKey(), sortType.getType(),
sortType.getTime(), APIUtils.getOAuthHeader(accessToken));
}
ListenableFuture<LoadResult<String, Post>> pageFuture = Futures.transform(userPosts, this::transformData, executor);
ListenableFuture<LoadResult<String, Post>> partialLoadResultFuture = ListenableFuture<LoadResult<Integer, Post>> pageFuture = Futures.transform(userPosts, this::transformData, executor);
ListenableFuture<LoadResult<Integer, Post>> partialLoadResultFuture =
Futures.catching(pageFuture, HttpException.class, Futures.catching(pageFuture, HttpException.class,
LoadResult.Error::new, executor); LoadResult.Error::new, executor);
return Futures.catching(partialLoadResultFuture, return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor); IOException.class, LoadResult.Error::new, executor);
} }
/*
private ListenableFuture<LoadResult<String, Post>> loadSearchPosts(@NonNull LoadParams<String> loadParams, RedditAPI api) { private ListenableFuture<LoadResult<String, Post>> loadSearchPosts(@NonNull LoadParams<String> loadParams, LemmyAPI api) {
ListenableFuture<Response<String>> searchPosts; ListenableFuture<Response<String>> searchPosts;
if (subredditOrUserName == null) { if (subredditOrUserName == null) {
if (accessToken == null) { if (accessToken == null) {
@ -297,7 +296,7 @@ public class PostPagingSource extends ListenableFuturePagingSource<String, Post>
IOException.class, LoadResult.Error::new, executor); IOException.class, LoadResult.Error::new, executor);
} }
private ListenableFuture<LoadResult<String, Post>> loadMultiRedditPosts(@NonNull LoadParams<String> loadParams, RedditAPI api) { private ListenableFuture<LoadResult<String, Post>> loadMultiRedditPosts(@NonNull LoadParams<String> loadParams, LemmyAPI api) {
ListenableFuture<Response<String>> multiRedditPosts; ListenableFuture<Response<String>> multiRedditPosts;
if (accessToken == null) { if (accessToken == null) {
multiRedditPosts = api.getMultiRedditPostsListenableFuture(multiRedditPath, loadParams.getKey(), sortType.getTime()); multiRedditPosts = api.getMultiRedditPostsListenableFuture(multiRedditPath, loadParams.getKey(), sortType.getTime());
@ -316,7 +315,7 @@ public class PostPagingSource extends ListenableFuturePagingSource<String, Post>
IOException.class, LoadResult.Error::new, executor); IOException.class, LoadResult.Error::new, executor);
} }
private ListenableFuture<LoadResult<String, Post>> loadAnonymousHomePosts(@NonNull LoadParams<String> loadParams, RedditAPI api) { private ListenableFuture<LoadResult<String, Post>> loadAnonymousHomePosts(@NonNull LoadParams<String> loadParams, LemmyAPI api) {
ListenableFuture<Response<String>> anonymousHomePosts; ListenableFuture<Response<String>> anonymousHomePosts;
anonymousHomePosts = api.getSubredditBestPostsListenableFuture(subredditOrUserName, sortType.getType(), sortType.getTime(), loadParams.getKey()); anonymousHomePosts = api.getSubredditBestPostsListenableFuture(subredditOrUserName, sortType.getType(), sortType.getTime(), loadParams.getKey());
@ -328,5 +327,11 @@ public class PostPagingSource extends ListenableFuturePagingSource<String, Post>
return Futures.catching(partialLoadResultFuture, return Futures.catching(partialLoadResultFuture,
IOException.class, LoadResult.Error::new, executor); IOException.class, LoadResult.Error::new, executor);
}*/
@Override
public boolean getKeyReuseSupported() {
//TODO: Figure out why this is needed
return true;
} }
} }

View File

@ -53,7 +53,7 @@ public class PostViewModel extends ViewModel {
public PostViewModel(Executor executor, Retrofit retrofit, String accessToken, String accountName, public PostViewModel(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences, SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
@Nullable SharedPreferences postHistorySharedPreferences, int postType, @Nullable SharedPreferences postHistorySharedPreferences, int postType,
SortType sortType, PostFilter postFilter, List<String> readPostList) { SortType sortType, PostFilter postFilter, List<String> readPostList,String option) {
this.executor = executor; this.executor = executor;
this.retrofit = retrofit; this.retrofit = retrofit;
this.accessToken = accessToken; this.accessToken = accessToken;
@ -64,6 +64,7 @@ public class PostViewModel extends ViewModel {
this.sortType = sortType; this.sortType = sortType;
this.postFilter = postFilter; this.postFilter = postFilter;
this.readPostList = readPostList; this.readPostList = readPostList;
this.name = option;
sortTypeLiveData = new MutableLiveData<>(); sortTypeLiveData = new MutableLiveData<>();
sortTypeLiveData.postValue(sortType); sortTypeLiveData.postValue(sortType);
@ -72,7 +73,7 @@ public class PostViewModel extends ViewModel {
sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData); sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData);
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce); Pager<Integer, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> { posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> {
changeSortTypeAndPostFilter( changeSortTypeAndPostFilter(
@ -114,7 +115,7 @@ public class PostViewModel extends ViewModel {
sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData); sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData);
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce); Pager<Integer, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> { posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> {
changeSortTypeAndPostFilter( changeSortTypeAndPostFilter(
@ -159,7 +160,7 @@ public class PostViewModel extends ViewModel {
sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData); sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData);
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce); Pager<Integer, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> { posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> {
changeSortTypeAndPostFilter( changeSortTypeAndPostFilter(
@ -204,7 +205,7 @@ public class PostViewModel extends ViewModel {
sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData); sortTypeAndPostFilterLiveData = new SortTypeAndPostFilterLiveData(sortTypeLiveData, postFilterLiveData);
Pager<String, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce); Pager<Integer, Post> pager = new Pager<>(new PagingConfig(25, 25, false), this::returnPagingSoruce);
posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> { posts = Transformations.switchMap(sortTypeAndPostFilterLiveData, sortAndPostFilter -> {
changeSortTypeAndPostFilter( changeSortTypeAndPostFilter(
@ -237,7 +238,7 @@ public class PostViewModel extends ViewModel {
case PostPagingSource.TYPE_FRONT_PAGE: case PostPagingSource.TYPE_FRONT_PAGE:
paging3PagingSource = new PostPagingSource(executor, retrofit, accessToken, accountName, paging3PagingSource = new PostPagingSource(executor, retrofit, accessToken, accountName,
sharedPreferences, postFeedScrolledPositionSharedPreferences, postType, sortType, sharedPreferences, postFeedScrolledPositionSharedPreferences, postType, sortType,
postFilter, readPostList); postFilter, readPostList,name);
break; break;
case PostPagingSource.TYPE_SUBREDDIT: case PostPagingSource.TYPE_SUBREDDIT:
case PostPagingSource.TYPE_MULTI_REDDIT: case PostPagingSource.TYPE_MULTI_REDDIT:
@ -294,7 +295,7 @@ public class PostViewModel extends ViewModel {
public Factory(Executor executor, Retrofit retrofit, String accessToken, String accountName, public Factory(Executor executor, Retrofit retrofit, String accessToken, String accountName,
SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences, SharedPreferences sharedPreferences, SharedPreferences postFeedScrolledPositionSharedPreferences,
SharedPreferences postHistorySharedPreferences, int postType, SortType sortType, SharedPreferences postHistorySharedPreferences, int postType, SortType sortType,
PostFilter postFilter, List<String> readPostList) { PostFilter postFilter, List<String> readPostList, String option) {
this.executor = executor; this.executor = executor;
this.retrofit = retrofit; this.retrofit = retrofit;
this.accessToken = accessToken; this.accessToken = accessToken;
@ -306,6 +307,7 @@ public class PostViewModel extends ViewModel {
this.sortType = sortType; this.sortType = sortType;
this.postFilter = postFilter; this.postFilter = postFilter;
this.readPostList = readPostList; this.readPostList = readPostList;
this.name = option;
} }
public Factory(Executor executor, Retrofit retrofit, String accessToken, String accountName, public Factory(Executor executor, Retrofit retrofit, String accessToken, String accountName,
@ -368,7 +370,7 @@ public class PostViewModel extends ViewModel {
//Anonymous Front Page //Anonymous Front Page
public Factory(Executor executor, Retrofit retrofit, SharedPreferences sharedPreferences, public Factory(Executor executor, Retrofit retrofit, SharedPreferences sharedPreferences,
String concatenatedSubredditNames, int postType, SortType sortType, PostFilter postFilter) { String concatenatedSubredditNames, int postType, SortType sortType, PostFilter postFilter, String opt) {
this.executor = executor; this.executor = executor;
this.retrofit = retrofit; this.retrofit = retrofit;
this.sharedPreferences = sharedPreferences; this.sharedPreferences = sharedPreferences;
@ -376,6 +378,7 @@ public class PostViewModel extends ViewModel {
this.postType = postType; this.postType = postType;
this.sortType = sortType; this.sortType = sortType;
this.postFilter = postFilter; this.postFilter = postFilter;
this.name = opt;
} }
@NonNull @NonNull
@ -384,7 +387,7 @@ public class PostViewModel extends ViewModel {
if (postType == PostPagingSource.TYPE_FRONT_PAGE) { if (postType == PostPagingSource.TYPE_FRONT_PAGE) {
return (T) new PostViewModel(executor, retrofit, accessToken, accountName, sharedPreferences, return (T) new PostViewModel(executor, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, postHistorySharedPreferences, postType, postFeedScrolledPositionSharedPreferences, postHistorySharedPreferences, postType,
sortType, postFilter, readPostList); sortType, postFilter, readPostList,name);
} else if (postType == PostPagingSource.TYPE_SEARCH) { } else if (postType == PostPagingSource.TYPE_SEARCH) {
return (T) new PostViewModel(executor, retrofit, accessToken, accountName, sharedPreferences, return (T) new PostViewModel(executor, retrofit, accessToken, accountName, sharedPreferences,
postFeedScrolledPositionSharedPreferences, postHistorySharedPreferences, name, query, postFeedScrolledPositionSharedPreferences, postHistorySharedPreferences, name, query,

View File

@ -137,22 +137,13 @@ public class PostFilter implements Parcelable {
if (postFilter.minComments > 0 && post.getNComments() < postFilter.minComments) { if (postFilter.minComments > 0 && post.getNComments() < postFilter.minComments) {
return false; return false;
} }
if (postFilter.maxAwards > 0 && post.getNAwards() > postFilter.maxAwards) {
return false;
}
if (postFilter.minAwards > 0 && post.getNAwards() < postFilter.minAwards) {
return false;
}
if (postFilter.onlyNSFW && !post.isNSFW()) { if (postFilter.onlyNSFW && !post.isNSFW()) {
if (postFilter.onlySpoiler) {
return post.isSpoiler();
}
return false; return false;
} }
if (postFilter.onlySpoiler && !post.isSpoiler()) { if (postFilter.onlySpoiler /*&& !post.isSpoiler()*/) {
if (postFilter.onlyNSFW) { /*if (postFilter.onlyNSFW) {
return post.isNSFW(); return post.isNSFW();
} }*/
return false; return false;
} }
if (!postFilter.containTextType && post.getPostType() == Post.TEXT_TYPE) { if (!postFilter.containTextType && post.getPostType() == Post.TEXT_TYPE) {
@ -230,14 +221,7 @@ public class PostFilter implements Parcelable {
} }
} }
} }
if (postFilter.excludeFlairs != null && !postFilter.excludeFlairs.equals("")) {
String[] flairs = postFilter.excludeFlairs.split(",", 0);
for (String f : flairs) {
if (!f.trim().equals("") && post.getFlair().equalsIgnoreCase(f.trim())) {
return false;
}
}
}
if (post.getUrl() != null && postFilter.excludeDomains != null && !postFilter.excludeDomains.equals("")) { if (post.getUrl() != null && postFilter.excludeDomains != null && !postFilter.excludeDomains.equals("")) {
String[] domains = postFilter.excludeDomains.split(",", 0); String[] domains = postFilter.excludeDomains.split(",", 0);
String url = post.getUrl().toLowerCase(); String url = post.getUrl().toLowerCase();
@ -261,24 +245,6 @@ public class PostFilter implements Parcelable {
return false; return false;
} }
} }
if (postFilter.containFlairs != null && !postFilter.containFlairs.equals("")) {
String[] flairs = postFilter.containFlairs.split(",", 0);
if (flairs.length > 0) {
boolean match = false;
for (int i = 0; i < flairs.length; i++) {
String flair = flairs[i].trim();
if (flair.equals("") && i == flairs.length - 1) {
return false;
}
if (!flair.equals("") && post.getFlair().equalsIgnoreCase(flair)) {
match = true;
break;
}
}
return match;
}
}
return true; return true;
} }

View File

@ -6,14 +6,14 @@ import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class InsertReadPost { public class InsertReadPost {
public static void insertReadPost(RedditDataRoomDatabase redditDataRoomDatabase, Executor executor, public static void insertReadPost(RedditDataRoomDatabase redditDataRoomDatabase, Executor executor,
String username, String postId) { String username, int postId) {
executor.execute(() -> { executor.execute(() -> {
ReadPostDao readPostDao = redditDataRoomDatabase.readPostDao(); ReadPostDao readPostDao = redditDataRoomDatabase.readPostDao();
if (readPostDao.getReadPostsCount() > 500) { if (readPostDao.getReadPostsCount() > 500) {
readPostDao.deleteOldestReadPosts(username); readPostDao.deleteOldestReadPosts(username);
} }
if (username != null && !username.equals("")) { if (username != null && !username.equals("")) {
readPostDao.insert(new ReadPost(username, postId)); readPostDao.insert(new ReadPost(username, String.valueOf(postId)));
} }
}); });
} }

View File

@ -46,6 +46,7 @@ import eu.toldi.infinityforlemmy.Flair;
import eu.toldi.infinityforlemmy.Infinity; import eu.toldi.infinityforlemmy.Infinity;
import eu.toldi.infinityforlemmy.R; import eu.toldi.infinityforlemmy.R;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.RetrofitHolder;
import eu.toldi.infinityforlemmy.account.Account; import eu.toldi.infinityforlemmy.account.Account;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper; import eu.toldi.infinityforlemmy.customtheme.CustomThemeWrapper;
@ -88,7 +89,7 @@ public class SubmitPostService extends Service {
private static final String EXTRA_MEDIA_URI = "EU"; private static final String EXTRA_MEDIA_URI = "EU";
@Inject @Inject
@Named("no_oauth") @Named("no_oauth")
Retrofit mRetrofit; RetrofitHolder mRetrofit;
@Inject @Inject
@Named("oauth") @Named("oauth")
Retrofit mOauthRetrofit; Retrofit mOauthRetrofit;
@ -137,7 +138,7 @@ public class SubmitPostService extends Service {
boolean receivePostReplyNotifications = bundle.getBoolean(EXTRA_RECEIVE_POST_REPLY_NOTIFICATIONS, true); boolean receivePostReplyNotifications = bundle.getBoolean(EXTRA_RECEIVE_POST_REPLY_NOTIFICATIONS, true);
int postType = bundle.getInt(EXTRA_POST_TYPE, EXTRA_POST_TEXT_OR_LINK); int postType = bundle.getInt(EXTRA_POST_TYPE, EXTRA_POST_TEXT_OR_LINK);
Retrofit newAuthenticatorOauthRetrofit = mOauthRetrofit.newBuilder().client(new OkHttpClient.Builder().authenticator(new AnyAccountAccessTokenAuthenticator(mRetrofit, mRedditDataRoomDatabase, account, mCurrentAccountSharedPreferences)) Retrofit newAuthenticatorOauthRetrofit = mOauthRetrofit.newBuilder().client(new OkHttpClient.Builder().authenticator(new AnyAccountAccessTokenAuthenticator(mRetrofit.getRetrofit(), mRedditDataRoomDatabase, account, mCurrentAccountSharedPreferences))
.connectTimeout(30, TimeUnit.SECONDS) .connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS)

View File

@ -312,7 +312,7 @@ public class CustomizeMainPageTabsFragment extends Fragment {
tab1AddImageView.setOnClickListener(view -> selectName(0)); tab1AddImageView.setOnClickListener(view -> selectName(0));
tab2CurrentTitle = mainActivityTabsSharedPreferences.getString((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_TITLE, getString(R.string.popular)); tab2CurrentTitle = mainActivityTabsSharedPreferences.getString((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_TITLE, getString(R.string.local));
tab2CurrentPostType = mainActivityTabsSharedPreferences.getInt((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_POST_TYPE, SharedPreferencesUtils.MAIN_PAGE_TAB_POST_TYPE_POPULAR); tab2CurrentPostType = mainActivityTabsSharedPreferences.getInt((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_POST_TYPE, SharedPreferencesUtils.MAIN_PAGE_TAB_POST_TYPE_POPULAR);
tab2CurrentName = mainActivityTabsSharedPreferences.getString((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_NAME, ""); tab2CurrentName = mainActivityTabsSharedPreferences.getString((accountName == null ? "" : accountName) + SharedPreferencesUtils.MAIN_PAGE_TAB_2_NAME, "");
tab2TypeSummaryTextView.setText(typeValues[tab2CurrentPostType]); tab2TypeSummaryTextView.setText(typeValues[tab2CurrentPostType]);

View File

@ -10,6 +10,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.utils.APIUtils; import eu.toldi.infinityforlemmy.utils.APIUtils;
import retrofit2.Call; import retrofit2.Call;
@ -19,15 +20,11 @@ import retrofit2.Retrofit;
public class FetchSubredditData { public class FetchSubredditData {
public static void fetchSubredditData(Retrofit oauthRetrofit, Retrofit retrofit, String subredditName, String accessToken, final FetchSubredditDataListener fetchSubredditDataListener) { public static void fetchSubredditData(Retrofit oauthRetrofit, Retrofit retrofit, String subredditName, String accessToken, final FetchSubredditDataListener fetchSubredditDataListener) {
RedditAPI api = retrofit.create(RedditAPI.class); LemmyAPI api = retrofit.create(LemmyAPI.class);
Call<String> subredditData; Call<String> subredditData;
if (oauthRetrofit == null || TextUtils.isEmpty(accessToken)) { subredditData = api.communityInfo(subredditName,accessToken);
subredditData = api.getSubredditData(subredditName);
} else {
RedditAPI oauthApi = oauthRetrofit.create(RedditAPI.class);
subredditData = oauthApi.getSubredditDataOauth(subredditName, APIUtils.getOAuthHeader(accessToken));
}
subredditData.enqueue(new Callback<>() { subredditData.enqueue(new Callback<>() {
@Override @Override
public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) { public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {

View File

@ -24,44 +24,40 @@ public class ParseSubredditData {
@Nullable @Nullable
private static SubredditData parseSubredditData(JSONObject subredditDataJsonObject, boolean nsfw) throws JSONException { private static SubredditData parseSubredditData(JSONObject subredditDataJsonObject, boolean nsfw) throws JSONException {
boolean isNSFW = !subredditDataJsonObject.isNull(JSONUtils.OVER18_KEY) && subredditDataJsonObject.getBoolean(JSONUtils.OVER18_KEY); JSONObject community = subredditDataJsonObject.getJSONObject("community");
boolean isNSFW = community.getBoolean("nsfw");
if (!nsfw && isNSFW) { if (!nsfw && isNSFW) {
return null; return null;
} }
String id = subredditDataJsonObject.getString(JSONUtils.NAME_KEY);
String subredditFullName = subredditDataJsonObject.getString(JSONUtils.DISPLAY_NAME_KEY);
String description = subredditDataJsonObject.getString(JSONUtils.PUBLIC_DESCRIPTION_KEY).trim();
String sidebarDescription = Utils.modifyMarkdown(subredditDataJsonObject.getString(JSONUtils.DESCRIPTION_KEY).trim());
long createdUTC = subredditDataJsonObject.getLong(JSONUtils.CREATED_UTC_KEY) * 1000;
String suggestedCommentSort = subredditDataJsonObject.getString(JSONUtils.SUGGESTED_COMMENT_SORT_KEY);
String bannerImageUrl; String title = community.getString(JSONUtils.TITLE_KEY);
if (subredditDataJsonObject.isNull(JSONUtils.BANNER_BACKGROUND_IMAGE_KEY)) { String bannerImageUrl = "";
bannerImageUrl = ""; if(!community.isNull("banner")){
} else { bannerImageUrl = community.getString("banner");
bannerImageUrl = subredditDataJsonObject.getString(JSONUtils.BANNER_BACKGROUND_IMAGE_KEY);
}
if (bannerImageUrl.equals("") && !subredditDataJsonObject.isNull(JSONUtils.BANNER_IMG_KEY)) {
bannerImageUrl = subredditDataJsonObject.getString(JSONUtils.BANNER_IMG_KEY);
} }
String iconUrl; String iconUrl = "";
if (subredditDataJsonObject.isNull(JSONUtils.COMMUNITY_ICON_KEY)) { if(!community.isNull("banner")){
iconUrl = ""; bannerImageUrl = community.getString("icon");
} else {
iconUrl = subredditDataJsonObject.getString(JSONUtils.COMMUNITY_ICON_KEY);
}
if (iconUrl.equals("") && !subredditDataJsonObject.isNull(JSONUtils.ICON_IMG_KEY)) {
iconUrl = subredditDataJsonObject.getString(JSONUtils.ICON_IMG_KEY);
} }
int id = community.getInt("id");
String name = community.getString("name");
String description = community.getString("description");
boolean removed = community.getBoolean("removed");
String published = community.getString("published");
String updated = community.getString("updated");
boolean deleted = community.getBoolean("deleted");
int nSubscribers = 0; String actorId = community.getString("actor_id");
if (!subredditDataJsonObject.isNull(JSONUtils.SUBSCRIBERS_KEY)) { boolean local = community.getBoolean("local");
nSubscribers = subredditDataJsonObject.getInt(JSONUtils.SUBSCRIBERS_KEY); String icon = community.getString("icon");
} String banner = community.getString("banner");
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");
return new SubredditData(id, subredditFullName, iconUrl, bannerImageUrl, description, return new SubredditData(id,name,title,description,removed,published,updated,deleted,nsfw,actorId,local,iconUrl,bannerImageUrl,hidden,postingRestrictedToMods,instanceId,subscribers);
sidebarDescription, nSubscribers, createdUTC, suggestedCommentSort, isNSFW);
} }
interface ParseSubredditDataListener { interface ParseSubredditDataListener {
@ -97,8 +93,8 @@ public class ParseSubredditData {
@Override @Override
protected Void doInBackground(Void... voids) { protected Void doInBackground(Void... voids) {
try { try {
JSONObject data = jsonResponse.getJSONObject(JSONUtils.DATA_KEY); JSONObject data = jsonResponse.getJSONObject("community_view");
mNCurrentOnlineSubscribers = data.getInt(JSONUtils.ACTIVE_USER_COUNT_KEY); mNCurrentOnlineSubscribers = 0;// data.getInt(JSONUtils.ACTIVE_USER_COUNT_KEY);
subredditData = parseSubredditData(data, true); subredditData = parseSubredditData(data, true);
} catch (JSONException e) { } catch (JSONException e) {
parseFailed = true; parseFailed = true;

View File

@ -11,90 +11,245 @@ public class SubredditData {
@PrimaryKey @PrimaryKey
@NonNull @NonNull
@ColumnInfo(name = "id") @ColumnInfo(name = "id")
private String id; private int id;
@ColumnInfo(name = "name") @ColumnInfo(name = "name")
private String name; private String name;
@ColumnInfo(name = "icon")
private String iconUrl; @ColumnInfo(name = "title")
@ColumnInfo(name = "banner") private String title;
private String bannerUrl;
@ColumnInfo(name = "description") @ColumnInfo(name = "description")
private String description; private String description;
@ColumnInfo(name = "sidebar_description")
private String sidebarDescription; @ColumnInfo(name = "removed")
@ColumnInfo(name = "subscribers_count") private boolean removed;
private int nSubscribers;
@ColumnInfo(name = "created_utc") @ColumnInfo(name = "published")
private long createdUTC; private String published; // Consider using a converter if you want to store it as a different type
@ColumnInfo(name = "suggested_comment_sort")
private String suggestedCommentSort; @ColumnInfo(name = "updated")
@ColumnInfo(name = "over18") private String updated; // Consider using a converter if you want to store it as a different type
private boolean isNSFW;
@ColumnInfo(name = "deleted")
private boolean deleted;
@ColumnInfo(name = "nsfw")
private boolean nsfw;
@ColumnInfo(name = "actor_id")
private String actorId;
@ColumnInfo(name = "local")
private boolean local;
@ColumnInfo(name = "icon")
private String icon;
@ColumnInfo(name = "banner")
private String banner;
@ColumnInfo(name = "hidden")
private boolean hidden;
@ColumnInfo(name = "posting_restricted_to_mods")
private boolean postingRestrictedToMods;
@ColumnInfo(name = "instance_id")
private int instanceId;
@ColumnInfo(name = "subscribers")
private int subscribers;
@Ignore @Ignore
private boolean isSelected; private boolean isSelected;
public SubredditData(@NonNull String id, String name, String iconUrl, String bannerUrl, public int getId() {
String description, String sidebarDescription, int nSubscribers, long createdUTC, return id;
String suggestedCommentSort, boolean isNSFW) {
this.id = id;
this.name = name;
this.iconUrl = iconUrl;
this.bannerUrl = bannerUrl;
this.description = description;
this.sidebarDescription = sidebarDescription;
this.nSubscribers = nSubscribers;
this.createdUTC = createdUTC;
this.suggestedCommentSort = suggestedCommentSort;
this.isNSFW = isNSFW;
this.isSelected = false;
} }
@NonNull public void setId(int id) {
public String getId() { this.id = id;
return id;
} }
public String getName() { public String getName() {
return name; return name;
} }
public String getIconUrl() { public void setName(String name) {
return iconUrl; this.name = name;
} }
public String getBannerUrl() { public String getTitle() {
return bannerUrl; return title;
}
public void setTitle(String title) {
this.title = title;
} }
public String getDescription() { public String getDescription() {
return description; return description;
} }
public String getSidebarDescription() { public void setDescription(String description) {
return sidebarDescription; this.description = description;
} }
public int getNSubscribers() { public boolean isRemoved() {
return nSubscribers; return removed;
} }
public long getCreatedUTC() { public void setRemoved(boolean removed) {
return createdUTC; this.removed = removed;
} }
public String getSuggestedCommentSort() { public String getPublished() {
return suggestedCommentSort; return published;
}
public void setPublished(String published) {
this.published = published;
}
public String getUpdated() {
return updated;
}
public void setUpdated(String updated) {
this.updated = updated;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public boolean isNsfw() {
return nsfw;
}
public void setNsfw(boolean nsfw) {
this.nsfw = nsfw;
}
public String getActorId() {
return actorId;
}
public void setActorId(String actorId) {
this.actorId = actorId;
}
public boolean isLocal() {
return local;
}
public void setLocal(boolean local) {
this.local = local;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getBanner() {
return banner;
}
public void setBanner(String banner) {
this.banner = banner;
}
public boolean isHidden() {
return hidden;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
public boolean isPostingRestrictedToMods() {
return postingRestrictedToMods;
}
public void setPostingRestrictedToMods(boolean postingRestrictedToMods) {
this.postingRestrictedToMods = postingRestrictedToMods;
}
public int getInstanceId() {
return instanceId;
}
public void setInstanceId(int instanceId) {
this.instanceId = instanceId;
}
public int getSubscribers() {
return subscribers;
}
public void setSubscribers(int subscribers) {
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) {
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;
} }
public boolean isNSFW() { public boolean isNSFW() {
return isNSFW; return nsfw;
}
public String getBannerUrl() {
return banner;
}
public String getIconUrl() {
return icon;
}
public int getNSubscribers() {
return subscribers;
}
public String getCreatedUTC() {
return published;
}
public String getSidebarDescription() {
return description;
} }
public boolean isSelected() { public boolean isSelected() {
return isSelected; return isSelected;
} }
public void setSelected(boolean selected) { public void setSelected(boolean b) {
isSelected = selected; isSelected =b;
} }
} }

View File

@ -13,6 +13,7 @@ import eu.toldi.infinityforlemmy.account.Account;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData; import eu.toldi.infinityforlemmy.subscribedsubreddit.SubscribedSubredditData;
import eu.toldi.infinityforlemmy.utils.APIUtils; import eu.toldi.infinityforlemmy.utils.APIUtils;
import eu.toldi.infinityforlemmy.utils.LemmyUtils;
import retrofit2.Call; import retrofit2.Call;
import retrofit2.Callback; import retrofit2.Callback;
import retrofit2.Retrofit; import retrofit2.Retrofit;
@ -115,8 +116,8 @@ public class SubredditSubscription {
SubredditData subredditData, String accountName, SubredditData subredditData, String accountName,
SubredditSubscriptionListener subredditSubscriptionListener) { SubredditSubscriptionListener subredditSubscriptionListener) {
executor.execute(() -> { executor.execute(() -> {
SubscribedSubredditData subscribedSubredditData = new SubscribedSubredditData(subredditData.getId(), subredditData.getName(), SubscribedSubredditData subscribedSubredditData = new SubscribedSubredditData(subredditData.getId(), LemmyUtils.actorID2FullName(subredditData.getActorId()), subredditData.getName(),
subredditData.getIconUrl(), accountName, false); subredditData.getIconUrl(), accountName);
if (accountName.equals("-")) { if (accountName.equals("-")) {
if (!redditDataRoomDatabase.accountDao().isAnonymousAccountInserted()) { if (!redditDataRoomDatabase.accountDao().isAnonymousAccountInserted()) {
redditDataRoomDatabase.accountDao().insert(Account.getAnonymousAccount()); redditDataRoomDatabase.accountDao().insert(Account.getAnonymousAccount());

View File

@ -25,9 +25,6 @@ public interface SubscribedSubredditDao {
@Query("SELECT * from subscribed_subreddits WHERE username = :accountName COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC") @Query("SELECT * from subscribed_subreddits WHERE username = :accountName COLLATE NOCASE ORDER BY name COLLATE NOCASE ASC")
List<SubscribedSubredditData> getAllSubscribedSubredditsList(String accountName); List<SubscribedSubredditData> getAllSubscribedSubredditsList(String accountName);
@Query("SELECT * from subscribed_subreddits WHERE username = :accountName AND name LIKE '%' || :searchQuery || '%' COLLATE NOCASE AND is_favorite = 1 ORDER BY name COLLATE NOCASE ASC")
LiveData<List<SubscribedSubredditData>> getAllFavoriteSubscribedSubredditsWithSearchQuery(String accountName, String searchQuery);
@Query("SELECT * from subscribed_subreddits WHERE name = :subredditName COLLATE NOCASE AND username = :accountName COLLATE NOCASE LIMIT 1") @Query("SELECT * from subscribed_subreddits WHERE name = :subredditName COLLATE NOCASE AND username = :accountName COLLATE NOCASE LIMIT 1")
SubscribedSubredditData getSubscribedSubreddit(String subredditName, String accountName); SubscribedSubredditData getSubscribedSubreddit(String subredditName, String accountName);

View File

@ -13,28 +13,28 @@ import eu.toldi.infinityforlemmy.account.Account;
public class SubscribedSubredditData { public class SubscribedSubredditData {
@NonNull @NonNull
@ColumnInfo(name = "id") @ColumnInfo(name = "id")
private String id; private int id;
@ColumnInfo(name = "name") @ColumnInfo(name = "name")
private String name; private String name;
@ColumnInfo(name = "qualified_name")
private String qualified_name;
@ColumnInfo(name = "icon") @ColumnInfo(name = "icon")
private String iconUrl; private String iconUrl;
@NonNull @NonNull
@ColumnInfo(name = "username") @ColumnInfo(name = "username")
private String username; private String username;
@ColumnInfo(name = "is_favorite")
private boolean favorite;
public SubscribedSubredditData(@NonNull String id, String name, String iconUrl, @NonNull String username, public SubscribedSubredditData(@NonNull int id, String name,@NonNull String qualified_name, String iconUrl, @NonNull String username) {
boolean favorite) {
this.id = id; this.id = id;
this.name = name; this.name = name;
this.iconUrl = iconUrl; this.iconUrl = iconUrl;
this.username = username; this.username = username;
this.favorite = favorite; this.qualified_name =qualified_name;
} }
@NonNull @NonNull
public String getId() { public int getId() {
return id; return id;
} }
@ -51,15 +51,16 @@ public class SubscribedSubredditData {
return username; return username;
} }
@NonNull
public String getQualified_name() {
return qualified_name;
}
public void setQualified_name(String qualified_name) {
this.qualified_name = qualified_name;
}
public void setUsername(@NonNull String username) { public void setUsername(@NonNull String username) {
this.username = username; this.username = username;
} }
public boolean isFavorite() {
return favorite;
}
public void setFavorite(boolean favorite) {
this.favorite = favorite;
}
} }

View File

@ -21,10 +21,6 @@ public class SubscribedSubredditRepository {
return mSubscribedSubredditDao.getAllSubscribedSubredditsWithSearchQuery(mAccountName, searchQuery); return mSubscribedSubredditDao.getAllSubscribedSubredditsWithSearchQuery(mAccountName, searchQuery);
} }
public LiveData<List<SubscribedSubredditData>> getAllFavoriteSubscribedSubredditsWithSearchQuery(String searchQuery) {
return mSubscribedSubredditDao.getAllFavoriteSubscribedSubredditsWithSearchQuery(mAccountName, searchQuery);
}
public void insert(SubscribedSubredditData subscribedSubredditData) { public void insert(SubscribedSubredditData subscribedSubredditData) {
new insertAsyncTask(mSubscribedSubredditDao).execute(subscribedSubredditData); new insertAsyncTask(mSubscribedSubredditDao).execute(subscribedSubredditData);
} }

View File

@ -17,7 +17,6 @@ import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
public class SubscribedSubredditViewModel extends AndroidViewModel { public class SubscribedSubredditViewModel extends AndroidViewModel {
private SubscribedSubredditRepository mSubscribedSubredditRepository; private SubscribedSubredditRepository mSubscribedSubredditRepository;
private LiveData<List<SubscribedSubredditData>> mAllSubscribedSubreddits; private LiveData<List<SubscribedSubredditData>> mAllSubscribedSubreddits;
private LiveData<List<SubscribedSubredditData>> mAllFavoriteSubscribedSubreddits;
private MutableLiveData<String> searchQueryLiveData; private MutableLiveData<String> searchQueryLiveData;
public SubscribedSubredditViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) { public SubscribedSubredditViewModel(Application application, RedditDataRoomDatabase redditDataRoomDatabase, String accountName) {
@ -27,17 +26,12 @@ public class SubscribedSubredditViewModel extends AndroidViewModel {
searchQueryLiveData.postValue(""); searchQueryLiveData.postValue("");
mAllSubscribedSubreddits = Transformations.switchMap(searchQueryLiveData, searchQuery -> mSubscribedSubredditRepository.getAllSubscribedSubredditsWithSearchQuery(searchQuery)); mAllSubscribedSubreddits = Transformations.switchMap(searchQueryLiveData, searchQuery -> mSubscribedSubredditRepository.getAllSubscribedSubredditsWithSearchQuery(searchQuery));
mAllFavoriteSubscribedSubreddits = Transformations.switchMap(searchQueryLiveData, searchQuery -> mSubscribedSubredditRepository.getAllFavoriteSubscribedSubredditsWithSearchQuery(searchQuery));
} }
public LiveData<List<SubscribedSubredditData>> getAllSubscribedSubreddits() { public LiveData<List<SubscribedSubredditData>> getAllSubscribedSubreddits() {
return mAllSubscribedSubreddits; return mAllSubscribedSubreddits;
} }
public LiveData<List<SubscribedSubredditData>> getAllFavoriteSubscribedSubreddits() {
return mAllFavoriteSubscribedSubreddits;
}
public void insert(SubscribedSubredditData subscribedSubredditData) { public void insert(SubscribedSubredditData subscribedSubredditData) {
mSubscribedSubredditRepository.insert(subscribedSubredditData); mSubscribedSubredditRepository.insert(subscribedSubredditData);
} }

View File

@ -6,6 +6,7 @@ import java.util.ArrayList;
import eu.toldi.infinityforlemmy.RedditDataRoomDatabase; import eu.toldi.infinityforlemmy.RedditDataRoomDatabase;
import eu.toldi.infinityforlemmy.SortType; import eu.toldi.infinityforlemmy.SortType;
import eu.toldi.infinityforlemmy.apis.LemmyAPI;
import eu.toldi.infinityforlemmy.apis.RedditAPI; import eu.toldi.infinityforlemmy.apis.RedditAPI;
import eu.toldi.infinityforlemmy.utils.APIUtils; import eu.toldi.infinityforlemmy.utils.APIUtils;
import retrofit2.Call; import retrofit2.Call;
@ -19,13 +20,13 @@ public class FetchUserData {
public static void fetchUserData(RedditDataRoomDatabase redditDataRoomDatabase, Retrofit retrofit, public static void fetchUserData(RedditDataRoomDatabase redditDataRoomDatabase, Retrofit retrofit,
String accessToken, String userName, FetchUserDataListener fetchUserDataListener) { String accessToken, String userName, FetchUserDataListener fetchUserDataListener) {
RedditAPI api = retrofit.create(RedditAPI.class); LemmyAPI api = retrofit.create(LemmyAPI.class);
Call<String> userInfo; Call<String> userInfo;
if (redditDataRoomDatabase == null) { if (redditDataRoomDatabase == null) {
userInfo = api.getUserData(userName); userInfo = api.userInfo(userName,null);
} else { } else {
userInfo = api.getUserDataOauth(APIUtils.getOAuthHeader(accessToken), userName); userInfo = api.userInfo(userName,accessToken);
} }
userInfo.enqueue(new Callback<>() { userInfo.enqueue(new Callback<>() {
@Override @Override

View File

@ -26,36 +26,44 @@ public class ParseUserData {
return null; return null;
} }
userDataJson = userDataJson.getJSONObject(JSONUtils.DATA_KEY);
String userName = userDataJson.getString(JSONUtils.NAME_KEY);
String iconImageUrl = userDataJson.getString(JSONUtils.ICON_IMG_KEY);
String bannerImageUrl = "";
boolean canBeFollowed;
if (userDataJson.has(JSONUtils.SUBREDDIT_KEY) && !userDataJson.isNull(JSONUtils.SUBREDDIT_KEY)) {
bannerImageUrl = userDataJson.getJSONObject(JSONUtils.SUBREDDIT_KEY).getString(JSONUtils.BANNER_IMG_KEY);
canBeFollowed = true;
} else {
canBeFollowed = false;
}
int linkKarma = userDataJson.getInt(JSONUtils.LINK_KARMA_KEY);
int commentKarma = userDataJson.getInt(JSONUtils.COMMENT_KARMA_KEY);
int awarderKarma = 0;
int awardeeKarma = 0;
int totalKarma = linkKarma + commentKarma;
if (parseFullKarma) {
awarderKarma = userDataJson.getInt(JSONUtils.AWARDER_KARMA_KEY);
awardeeKarma = userDataJson.getInt(JSONUtils.AWARDEE_KARMA_KEY);
totalKarma = userDataJson.getInt(JSONUtils.TOTAL_KARMA_KEY);
}
long cakeday = userDataJson.getLong(JSONUtils.CREATED_UTC_KEY) * 1000;
boolean isGold = userDataJson.getBoolean(JSONUtils.IS_GOLD_KEY);
boolean isFriend = userDataJson.getBoolean(JSONUtils.IS_FRIEND_KEY);
boolean isNsfw = userDataJson.getJSONObject(JSONUtils.SUBREDDIT_KEY).getBoolean(JSONUtils.OVER_18_KEY);
String description = userDataJson.getJSONObject(JSONUtils.SUBREDDIT_KEY).getString(JSONUtils.PUBLIC_DESCRIPTION_KEY);
String title = userDataJson.getJSONObject(JSONUtils.SUBREDDIT_KEY).getString(JSONUtils.TITLE_KEY);
return new UserData(userName, iconImageUrl, bannerImageUrl, linkKarma, commentKarma, awarderKarma, JSONObject personJson = userDataJson.getJSONObject("person_view").getJSONObject("person");
awardeeKarma, totalKarma, cakeday, isGold, isFriend, canBeFollowed, isNsfw, description, title); String userName = personJson.getString(JSONUtils.NAME_KEY);
String actor_id = personJson.getString("actor_id");
String iconImageUrl = "";
String bannerImageUrl = "";
if (!personJson.isNull("avatar")) {
iconImageUrl = personJson.getString("avatar");
}
if (!personJson.isNull("banner")) {
bannerImageUrl = personJson.getString("banner");
}
JSONObject countsJson = userDataJson.getJSONObject("person_view").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);
boolean isBot = personJson.getBoolean("bot_account");
boolean isBanned = personJson.getBoolean("banned");
boolean isLocal = personJson.getBoolean("local");
boolean isAdmin = personJson.getBoolean("admin");
boolean isDeleted = personJson.getBoolean("deleted");
String description = "";
if (!personJson.isNull("bio")) {
description = personJson.getString("bio");
}
String title = "";
if (!personJson.isNull("display_name")) {
title = personJson.getString("display_name");
}
return new UserData(account_id,userName,title, iconImageUrl,isBanned,cakeday,actor_id,isLocal,isDeleted,isAdmin,isBot,instance_id);
} }
interface ParseUserDataListener { interface ParseUserDataListener {
@ -96,10 +104,7 @@ public class ParseUserData {
try { try {
userData = parseUserDataBase(jsonResponse, true); userData = parseUserDataBase(jsonResponse, true);
if (redditDataRoomDatabase != null) { if (redditDataRoomDatabase != null) {
redditDataRoomDatabase.accountDao().updateAccountInfo(userData.getName(), userData.getIconUrl(), userData.getBanner(), userData.getTotalKarma()); redditDataRoomDatabase.accountDao().updateAccountInfo(userData.getName(), userData.getIconUrl(), userData.getBanner());
}
if (jsonResponse.getJSONObject(JSONUtils.DATA_KEY).has(JSONUtils.INBOX_COUNT_KEY)) {
inboxCount = jsonResponse.getJSONObject(JSONUtils.DATA_KEY).getInt(JSONUtils.INBOX_COUNT_KEY);
} }
} catch (JSONException e) { } catch (JSONException e) {
parseFailed = true; parseFailed = true;

View File

@ -10,121 +10,45 @@ import androidx.room.PrimaryKey;
public class UserData { public class UserData {
@PrimaryKey @PrimaryKey
@NonNull @NonNull
@ColumnInfo(name = "id")
private int id;
@ColumnInfo(name = "name") @ColumnInfo(name = "name")
private String name; private String name;
@ColumnInfo(name = "icon")
private String iconUrl; @ColumnInfo(name = "display_name")
@ColumnInfo(name = "banner") private String displayName;
private String banner;
@ColumnInfo(name = "link_karma") @ColumnInfo(name = "avatar")
private int linkKarma; private String avatar;
@ColumnInfo(name = "comment_karma")
private int commentKarma; @ColumnInfo(name = "banned")
@ColumnInfo(name = "awarder_karma") private boolean banned;
private int awarderKarma;
@ColumnInfo(name = "awardee_karma") @ColumnInfo(name = "published")
private int awardeeKarma; private String published; // Consider using a converter if you want to store it as a different type
@ColumnInfo(name = "total_karma")
private int totalKarma; @ColumnInfo(name = "actor_id")
@ColumnInfo(name = "created_utc") private String actorId;
private long cakeday;
@ColumnInfo(name = "is_gold") @ColumnInfo(name = "local")
private boolean isGold; private boolean local;
@ColumnInfo(name = "is_friend")
private boolean isFriend; @ColumnInfo(name = "deleted")
@ColumnInfo(name = "can_be_followed") private boolean deleted;
private boolean canBeFollowed;
@ColumnInfo(name = "over_18") @ColumnInfo(name = "admin")
private boolean isNSFW; private boolean admin;
@ColumnInfo(name = "description")
private String description; @ColumnInfo(name = "bot_account")
@ColumnInfo(name = "title") private boolean botAccount;
private String title;
@ColumnInfo(name = "instance_id")
private int instanceId;
@Ignore @Ignore
private boolean isSelected; private boolean isSelected;
public UserData(@NonNull String name, String iconUrl, String banner, int linkKarma, int commentKarma,
int awarderKarma, int awardeeKarma, int totalKarma, long cakeday, boolean isGold,
boolean isFriend, boolean canBeFollowed, boolean isNSFW, String description, String title) {
this.name = name;
this.iconUrl = iconUrl;
this.banner = banner;
this.commentKarma = commentKarma;
this.linkKarma = linkKarma;
this.awarderKarma = awarderKarma;
this.awardeeKarma = awardeeKarma;
this.totalKarma = totalKarma;
this.cakeday = cakeday;
this.isGold = isGold;
this.isFriend = isFriend;
this.canBeFollowed = canBeFollowed;
this.isNSFW = isNSFW;
this.description = description;
this.title = title;
this.isSelected = false;
}
@NonNull
public String getName() {
return name;
}
public String getIconUrl() {
return iconUrl;
}
public String getBanner() {
return banner;
}
public int getLinkKarma() {
return linkKarma;
}
public int getCommentKarma() {
return commentKarma;
}
public int getAwarderKarma() {
return awarderKarma;
}
public int getAwardeeKarma() {
return awardeeKarma;
}
public int getTotalKarma() {
return totalKarma;
}
public long getCakeday() {
return cakeday;
}
public boolean isGold() {
return isGold;
}
public boolean isFriend() {
return isFriend;
}
public boolean isCanBeFollowed() {
return canBeFollowed;
}
public boolean isNSFW() {
return isNSFW;
}
public String getDescription() {
return description;
}
public String getTitle() {
return title;
}
public boolean isSelected() { public boolean isSelected() {
return isSelected; return isSelected;
} }
@ -132,4 +56,140 @@ public class UserData {
public void setSelected(boolean selected) { public void setSelected(boolean selected) {
isSelected = selected; isSelected = selected;
} }
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getAvatar() {
return avatar;
}
public String getIconUrl() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public boolean isBanned() {
return banned;
}
public void setBanned(boolean banned) {
this.banned = banned;
}
public String getPublished() {
return published;
}
public void setPublished(String published) {
this.published = published;
}
public String getActorId() {
return actorId;
}
public void setActorId(String actorId) {
this.actorId = actorId;
}
public boolean isLocal() {
return local;
}
public void setLocal(boolean local) {
this.local = local;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public boolean isBotAccount() {
return botAccount;
}
public void setBotAccount(boolean botAccount) {
this.botAccount = botAccount;
}
public int getInstanceId() {
return instanceId;
}
public void setInstanceId(int instanceId) {
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) {
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;
}
public boolean isCanBeFollowed() {
return false;
}
public String getBanner() {
return "";
}
public Object getCakeday() {
return published;
}
public String getDescription() {
return null;
}
public String getTitle() {
return displayName;
}
} }

View File

@ -15,7 +15,7 @@ import okhttp3.RequestBody;
public class APIUtils { public class APIUtils {
public static final String OAUTH_URL = "https://www.reddit.com/api/v1/authorize.compact"; public static final String OAUTH_URL = "https://www.reddit.com/api/v1/authorize.compact";
public static final String OAUTH_API_BASE_URI = "https://oauth.reddit.com"; public static final String OAUTH_API_BASE_URI = "https://oauth.reddit.com";
public static final String API_BASE_URI = "https://www.reddit.com"; public static final String API_BASE_URI = "https://lemmy.toldi.eu";
public static final String API_UPLOAD_MEDIA_URI = "https://reddit-uploaded-media.s3-accelerate.amazonaws.com"; public static final String API_UPLOAD_MEDIA_URI = "https://reddit-uploaded-media.s3-accelerate.amazonaws.com";
public static final String API_UPLOAD_VIDEO_URI = "https://reddit-uploaded-video.s3-accelerate.amazonaws.com"; public static final String API_UPLOAD_VIDEO_URI = "https://reddit-uploaded-video.s3-accelerate.amazonaws.com";
public static final String GFYCAT_API_BASE_URI = "https://api.gfycat.com/v1/gfycats/"; public static final String GFYCAT_API_BASE_URI = "https://api.gfycat.com/v1/gfycats/";
@ -128,6 +128,13 @@ public class APIUtils {
return params; return params;
} }
public static Map<String, String> getHttpJsonHeader() {
Map<String, String> params = new HashMap<>();
params.put("accept", "application/json");
params.put("Content-Type","application/json");
return params;
}
public static Map<String, String> getOAuthHeader(String accessToken) { public static Map<String, String> getOAuthHeader(String accessToken) {
Map<String, String> params = new HashMap<>(); Map<String, String> params = new HashMap<>();
params.put(APIUtils.AUTHORIZATION_KEY, APIUtils.AUTHORIZATION_BASE + accessToken); params.put(APIUtils.AUTHORIZATION_KEY, APIUtils.AUTHORIZATION_BASE + accessToken);

View File

@ -30,7 +30,7 @@ public class JSONUtils {
public static final String LIKES_KEY = "likes"; public static final String LIKES_KEY = "likes";
public static final String NSFW_KEY = "over_18"; public static final String NSFW_KEY = "over_18";
public static final String PERMALINK_KEY = "permalink"; public static final String PERMALINK_KEY = "permalink";
public static final String CREATED_UTC_KEY = "created_utc"; public static final String PUBLISHED = "published";
public static final String PREVIEW_KEY = "preview"; public static final String PREVIEW_KEY = "preview";
public static final String IMAGES_KEY = "images"; public static final String IMAGES_KEY = "images";
public static final String WIDTH_KEY = "width"; public static final String WIDTH_KEY = "width";
@ -59,8 +59,8 @@ public class JSONUtils {
public static final String ICON_IMG_KEY = "icon_img"; public static final String ICON_IMG_KEY = "icon_img";
public static final String ICON_URL_KEY = "icon_url"; public static final String ICON_URL_KEY = "icon_url";
public static final String COMMUNITY_ICON_KEY = "community_icon"; public static final String COMMUNITY_ICON_KEY = "community_icon";
public static final String LINK_KARMA_KEY = "link_karma"; public static final String POST_SCORE_KEY = "post_score";
public static final String COMMENT_KARMA_KEY = "comment_karma"; public static final String COMMENT_SCORE_KEY = "comment_score";
public static final String DISPLAY_NAME_KEY = "display_name"; public static final String DISPLAY_NAME_KEY = "display_name";
public static final String SUBREDDIT_TYPE_KEY = "subreddit_type"; public static final String SUBREDDIT_TYPE_KEY = "subreddit_type";
public static final String SUBREDDIT_TYPE_VALUE_USER = "user"; public static final String SUBREDDIT_TYPE_VALUE_USER = "user";

View File

@ -0,0 +1,10 @@
package eu.toldi.infinityforlemmy.utils;
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;
}
}

View File

@ -394,4 +394,5 @@ public class SharedPreferencesUtils {
public static final String BLUR_SPOILER_KEY_LEGACY = "blur_spoiler"; public static final String BLUR_SPOILER_KEY_LEGACY = "blur_spoiler";
public static final String CONFIRM_TO_EXIT_LEGACY = "confirm_to_exit"; public static final String CONFIRM_TO_EXIT_LEGACY = "confirm_to_exit";
public static final String OPEN_LINK_IN_APP_LEGACY = "open_link_in_app"; public static final String OPEN_LINK_IN_APP_LEGACY = "open_link_in_app";
public static final String ACCOUNT_INSTANCE = "account_instance";
} }

View File

@ -61,6 +61,13 @@
android:layout_gravity="center_horizontal" android:layout_gravity="center_horizontal"
android:fontFamily="?attr/font_family" /> android:fontFamily="?attr/font_family" />
<TextView
android:id="@+id/community_fulname_text_view_view_subreddit_detail_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="TextView" />
<com.google.android.material.chip.Chip <com.google.android.material.chip.Chip
android:id="@+id/subscribe_subreddit_chip_view_subreddit_detail_activity" android:id="@+id/subscribe_subreddit_chip_view_subreddit_detail_activity"
android:layout_width="wrap_content" android:layout_width="wrap_content"

View File

@ -56,11 +56,19 @@
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="16dp" android:layout_marginTop="16dp"
android:layout_marginBottom="16dp" android:layout_marginBottom="4dp"
android:textSize="?attr/font_18" android:textSize="?attr/font_18"
android:fontFamily="?attr/font_family" android:fontFamily="?attr/font_family"
android:layout_gravity="center_horizontal"/> android:layout_gravity="center_horizontal"/>
<TextView
android:id="@+id/user_qualified_name_text_view_view_user_detail_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="16dp"
android:text="TextView" />
<com.google.android.material.chip.Chip <com.google.android.material.chip.Chip
android:id="@+id/subscribe_user_chip_view_user_detail_activity" android:id="@+id/subscribe_user_chip_view_user_detail_activity"
android:layout_width="wrap_content" android:layout_width="wrap_content"

View File

@ -61,6 +61,13 @@
android:layout_gravity="center_horizontal" android:layout_gravity="center_horizontal"
android:fontFamily="?attr/font_family" /> android:fontFamily="?attr/font_family" />
<TextView
android:id="@+id/community_fulname_text_view_view_subreddit_detail_activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="TextView" />
<com.google.android.material.chip.Chip <com.google.android.material.chip.Chip
android:id="@+id/subscribe_subreddit_chip_view_subreddit_detail_activity" android:id="@+id/subscribe_subreddit_chip_view_subreddit_detail_activity"
android:layout_width="wrap_content" android:layout_width="wrap_content"

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