Search in sources :

Example 1 with RedditAPI

use of ml.docilealligator.infinityforreddit.apis.RedditAPI in project Infinity-For-Reddit by Docile-Alligator.

the class CommentDataSource method loadInitial.

@Override
public void loadInitial(@NonNull LoadInitialParams<String> params, @NonNull LoadInitialCallback<String, Comment> callback) {
    initialLoadStateLiveData.postValue(NetworkState.LOADING);
    RedditAPI api = retrofit.create(RedditAPI.class);
    Call<String> commentsCall;
    if (areSavedComments) {
        if (sortType.getTime() != null) {
            commentsCall = api.getUserSavedCommentsOauth(username, PostPagingSource.USER_WHERE_SAVED, null, sortType.getType().value, sortType.getTime().value, APIUtils.getOAuthHeader(accessToken));
        } else {
            commentsCall = api.getUserSavedCommentsOauth(username, PostPagingSource.USER_WHERE_SAVED, null, sortType.getType().value, APIUtils.getOAuthHeader(accessToken));
        }
    } else {
        if (accessToken == null) {
            if (sortType.getTime() != null) {
                commentsCall = api.getUserComments(username, null, sortType.getType().value, sortType.getTime().value);
            } else {
                commentsCall = api.getUserComments(username, null, sortType.getType().value);
            }
        } else {
            if (sortType.getTime() != null) {
                commentsCall = api.getUserCommentsOauth(APIUtils.getOAuthHeader(accessToken), username, null, sortType.getType().value, sortType.getTime().value);
            } else {
                commentsCall = api.getUserCommentsOauth(APIUtils.getOAuthHeader(accessToken), username, null, sortType.getType().value);
            }
        }
    }
    commentsCall.enqueue(new Callback<String>() {

        @Override
        public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
            if (response.isSuccessful()) {
                new ParseCommentAsyncTask(response.body(), locale, new ParseCommentAsyncTask.ParseCommentAsyncTaskListener() {

                    @Override
                    public void parseSuccessful(ArrayList<Comment> comments, String after) {
                        if (comments.size() == 0) {
                            hasPostLiveData.postValue(false);
                        } else {
                            hasPostLiveData.postValue(true);
                        }
                        if (after == null || after.equals("") || after.equals("null")) {
                            callback.onResult(comments, null, null);
                        } else {
                            callback.onResult(comments, null, after);
                        }
                        initialLoadStateLiveData.postValue(NetworkState.LOADED);
                    }

                    @Override
                    public void parseFailed() {
                        initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
                    }
                }).execute();
            } else {
                initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
            }
        }

        @Override
        public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
            initialLoadStateLiveData.postValue(new NetworkState(NetworkState.Status.FAILED, "Error parsing data"));
        }
    });
}
Also used : NetworkState(ml.docilealligator.infinityforreddit.NetworkState) RedditAPI(ml.docilealligator.infinityforreddit.apis.RedditAPI)

Example 2 with RedditAPI

use of ml.docilealligator.infinityforreddit.apis.RedditAPI in project Infinity-For-Reddit by Docile-Alligator.

the class FetchComment method fetchMoreComment.

public static void fetchMoreComment(Executor executor, Handler handler, Retrofit retrofit, @Nullable String accessToken, ArrayList<String> allChildren, int startingIndex, int depth, boolean expandChildren, FetchMoreCommentListener fetchMoreCommentListener) {
    if (allChildren == null) {
        return;
    }
    StringBuilder stringBuilder = new StringBuilder();
    for (int i = 0; i < 100; i++) {
        if (allChildren.size() <= startingIndex + i) {
            break;
        }
        stringBuilder.append(allChildren.get(startingIndex + i)).append(",");
    }
    if (stringBuilder.length() == 0) {
        return;
    }
    stringBuilder.deleteCharAt(stringBuilder.length() - 1);
    RedditAPI api = retrofit.create(RedditAPI.class);
    Call<String> moreComments;
    if (accessToken == null) {
        moreComments = api.getInfo(stringBuilder.toString());
    } else {
        moreComments = api.getInfoOauth(stringBuilder.toString(), APIUtils.getOAuthHeader(accessToken));
    }
    moreComments.enqueue(new Callback<String>() {

        @Override
        public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
            if (response.isSuccessful()) {
                ParseComment.parseMoreComment(executor, handler, response.body(), new ArrayList<>(), depth, expandChildren, new ParseComment.ParseCommentListener() {

                    @Override
                    public void onParseCommentSuccess(ArrayList<Comment> expandedComments, String parentId, ArrayList<String> moreChildrenFullnames) {
                        fetchMoreCommentListener.onFetchMoreCommentSuccess(expandedComments, startingIndex + 100);
                    }

                    @Override
                    public void onParseCommentFailed() {
                        fetchMoreCommentListener.onFetchMoreCommentFailed();
                    }
                });
            } else {
                fetchMoreCommentListener.onFetchMoreCommentFailed();
            }
        }

        @Override
        public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
            fetchMoreCommentListener.onFetchMoreCommentFailed();
        }
    });
}
Also used : ArrayList(java.util.ArrayList) RedditAPI(ml.docilealligator.infinityforreddit.apis.RedditAPI)

Example 3 with RedditAPI

use of ml.docilealligator.infinityforreddit.apis.RedditAPI in project Infinity-For-Reddit by Docile-Alligator.

the class EditProfileUtils method updateProfile.

public static void updateProfile(Retrofit oauthRetrofit, String accessToken, String accountName, String displayName, String publicDesc, EditProfileUtilsListener listener) {
    final Map<String, String> oauthHeader = APIUtils.getOAuthHeader(accessToken);
    final RedditAPI api = oauthRetrofit.create(RedditAPI.class);
    final String name = "u_" + accountName;
    api.getSubredditSetting(oauthHeader, name).enqueue(new Callback<>() {

        @Override
        public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
            if (response.isSuccessful()) {
                try {
                    final String json = response.body();
                    if (json == null) {
                        listener.failed("Something happen.");
                        return;
                    }
                    final JSONObject resBody = new JSONObject(json);
                    final SubredditSettingData data = new Gson().fromJson(resBody.getString("data"), SubredditSettingData.class);
                    if (data.getPublicDescription().equals(publicDesc) && data.getTitle().equals(displayName)) {
                        // no-op
                        listener.success();
                        return;
                    }
                    final Map<String, String> params = new HashMap<>();
                    params.put("api_type", "json");
                    params.put("sr", data.getSubredditId());
                    params.put("name", name);
                    params.put("type", data.getSubredditType());
                    // Only this 2 param
                    params.put("public_description", publicDesc);
                    params.put("title", displayName);
                    // Official Reddit app have this 2 params
                    // 1 = disable; 0 = enable || Active in communities visibility || Show which communities I am active in on my profile.
                    params.put("toxicity_threshold_chat_level", String.valueOf(data.getToxicityThresholdChatLevel()));
                    // Content visibility || Posts to this profile can appear in r/all and your profile can be discovered in /users
                    params.put("default_set", String.valueOf(data.isDefaultSet()));
                    // Allow people to follow you || Followers will be notified about posts you make to your profile and see them in their home feed.
                    params.put("accept_followers", String.valueOf(data.isAcceptFollowers()));
                    // 
                    params.put("allow_top", String.valueOf(data.isPublicTraffic()));
                    // 
                    params.put("link_type", String.valueOf(data.getContentOptions()));
                    // 
                    params.put("original_content_tag_enabled", String.valueOf(data.isOriginalContentTagEnabled()));
                    params.put("new_pinned_post_pns_enabled", String.valueOf(data.isNewPinnedPostPnsEnabled()));
                    params.put("prediction_leaderboard_entry_type", String.valueOf(data.getPredictionLeaderboardEntryType()));
                    params.put("restrict_commenting", String.valueOf(data.isRestrictCommenting()));
                    params.put("restrict_posting", String.valueOf(data.isRestrictPosting()));
                    params.put("should_archive_posts", String.valueOf(data.isShouldArchivePosts()));
                    params.put("show_media", String.valueOf(data.isShowMedia()));
                    params.put("show_media_preview", String.valueOf(data.isShowMediaPreview()));
                    params.put("spam_comments", data.getSpamComments());
                    params.put("spam_links", data.getSpamLinks());
                    params.put("spam_selfposts", data.getSpamSelfPosts());
                    params.put("spoilers_enabled", String.valueOf(data.isSpoilersEnabled()));
                    params.put("submit_link_label", data.getSubmitLinkLabel());
                    params.put("submit_text", data.getSubmitText());
                    params.put("submit_text_label", data.getSubmitTextLabel());
                    params.put("user_flair_pns_enabled", String.valueOf(data.isUserFlairPnsEnabled()));
                    params.put("all_original_content", String.valueOf(data.isAllOriginalContent()));
                    params.put("allow_chat_post_creation", String.valueOf(data.isAllowChatPostCreation()));
                    params.put("allow_discovery", String.valueOf(data.isAllowDiscovery()));
                    params.put("allow_galleries", String.valueOf(data.isAllowGalleries()));
                    params.put("allow_images", String.valueOf(data.isAllowImages()));
                    params.put("allow_polls", String.valueOf(data.isAllowPolls()));
                    params.put("allow_post_crossposts", String.valueOf(data.isAllowPostCrossPosts()));
                    params.put("allow_prediction_contributors", String.valueOf(data.isAllowPredictionContributors()));
                    params.put("allow_predictions", String.valueOf(data.isAllowPredictions()));
                    params.put("allow_predictions_tournament", String.valueOf(data.isAllowPredictionsTournament()));
                    params.put("allow_videos", String.valueOf(data.isAllowVideos()));
                    params.put("collapse_deleted_comments", String.valueOf(data.isCollapseDeletedComments()));
                    params.put("comment_score_hide_mins", String.valueOf(data.getCommentScoreHideMins()));
                    params.put("crowd_control_chat_level", String.valueOf(data.getCrowdControlChatLevel()));
                    params.put("crowd_control_filter", String.valueOf(data.getCrowdControlChatLevel()));
                    params.put("crowd_control_level", String.valueOf(data.getCrowdControlLevel()));
                    params.put("crowd_control_mode", String.valueOf(data.isCrowdControlMode()));
                    params.put("description", data.getDescription());
                    params.put("disable_contributor_requests", String.valueOf(data.isDisableContributorRequests()));
                    params.put("exclude_banned_modqueue", String.valueOf(data.isExcludeBannedModQueue()));
                    params.put("free_form_reports", String.valueOf(data.isFreeFormReports()));
                    params.put("header-title", data.getHeaderHoverText());
                    params.put("hide_ads", String.valueOf(data.isHideAds()));
                    params.put("key_color", data.getKeyColor());
                    params.put("lang", data.getLanguage());
                    params.put("over_18", String.valueOf(data.isOver18()));
                    params.put("suggested_comment_sort", data.getSuggestedCommentSort());
                    params.put("welcome_message_enabled", String.valueOf(data.isWelcomeMessageEnabled()));
                    params.put("welcome_message_text", String.valueOf(data.getWelcomeMessageText()));
                    params.put("wiki_edit_age", String.valueOf(data.getWikiEditAge()));
                    params.put("wiki_edit_karma", String.valueOf(data.getWikiEditKarma()));
                    params.put("wikimode", data.getWikiMode());
                    api.postSiteAdmin(oauthHeader, params).enqueue(new Callback<>() {

                        @Override
                        public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                            if (response.isSuccessful())
                                listener.success();
                            else
                                listener.failed(response.message());
                        }

                        @Override
                        public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                            t.printStackTrace();
                            listener.failed(t.getLocalizedMessage());
                        }
                    });
                } catch (JSONException e) {
                    listener.failed(e.getLocalizedMessage());
                }
            } else {
                listener.failed(response.message());
            }
        }

        @Override
        public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
            t.printStackTrace();
            listener.failed(t.getLocalizedMessage());
        }
    });
}
Also used : Call(retrofit2.Call) Gson(com.google.gson.Gson) JSONException(org.json.JSONException) RedditAPI(ml.docilealligator.infinityforreddit.apis.RedditAPI) Response(retrofit2.Response) SubredditSettingData(ml.docilealligator.infinityforreddit.subreddit.SubredditSettingData) Callback(retrofit2.Callback) JSONObject(org.json.JSONObject) NonNull(androidx.annotation.NonNull) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with RedditAPI

use of ml.docilealligator.infinityforreddit.apis.RedditAPI in project Infinity-For-Reddit by Docile-Alligator.

the class UserFollowing method userFollowing.

private static void userFollowing(Retrofit oauthRetrofit, Retrofit retrofit, String accessToken, String username, String accountName, String action, SubscribedUserDao subscribedUserDao, UserFollowingListener userFollowingListener) {
    RedditAPI api = oauthRetrofit.create(RedditAPI.class);
    Map<String, String> params = new HashMap<>();
    params.put(APIUtils.ACTION_KEY, action);
    params.put(APIUtils.SR_NAME_KEY, "u_" + username);
    Call<String> subredditSubscriptionCall = api.subredditSubscription(APIUtils.getOAuthHeader(accessToken), params);
    subredditSubscriptionCall.enqueue(new Callback<String>() {

        @Override
        public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
            if (response.isSuccessful()) {
                if (action.equals("sub")) {
                    FetchUserData.fetchUserData(retrofit, username, new FetchUserData.FetchUserDataListener() {

                        @Override
                        public void onFetchUserDataSuccess(UserData userData, int inboxCount) {
                            new UpdateSubscriptionAsyncTask(subscribedUserDao, userData, accountName, true).execute();
                        }

                        @Override
                        public void onFetchUserDataFailed() {
                        }
                    });
                } else {
                    new UpdateSubscriptionAsyncTask(subscribedUserDao, username, accountName, false).execute();
                }
                userFollowingListener.onUserFollowingSuccess();
            } else {
                userFollowingListener.onUserFollowingFail();
            }
        }

        @Override
        public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
            userFollowingListener.onUserFollowingFail();
        }
    });
}
Also used : HashMap(java.util.HashMap) SubscribedUserData(ml.docilealligator.infinityforreddit.subscribeduser.SubscribedUserData) RedditAPI(ml.docilealligator.infinityforreddit.apis.RedditAPI)

Example 5 with RedditAPI

use of ml.docilealligator.infinityforreddit.apis.RedditAPI in project Infinity-For-Reddit by Docile-Alligator.

the class VoteThing method voteThing.

public static void voteThing(Context context, final Retrofit retrofit, String accessToken, final VoteThingWithoutPositionListener voteThingWithoutPositionListener, final String fullName, final String point) {
    RedditAPI api = retrofit.create(RedditAPI.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);
    voteThingCall.enqueue(new Callback<String>() {

        @Override
        public void onResponse(@NonNull Call<String> call, @NonNull retrofit2.Response<String> response) {
            if (response.isSuccessful()) {
                voteThingWithoutPositionListener.onVoteThingSuccess();
            } else {
                voteThingWithoutPositionListener.onVoteThingFail();
                Toast.makeText(context, "Code " + response.code() + " Body: " + response.body(), Toast.LENGTH_LONG).show();
            }
        }

        @Override
        public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
            voteThingWithoutPositionListener.onVoteThingFail();
            Toast.makeText(context, "Network error " + "Body: " + t.getMessage(), Toast.LENGTH_LONG).show();
        }
    });
}
Also used : HashMap(java.util.HashMap) RedditAPI(ml.docilealligator.infinityforreddit.apis.RedditAPI)

Aggregations

RedditAPI (ml.docilealligator.infinityforreddit.apis.RedditAPI)25 HashMap (java.util.HashMap)12 ArrayList (java.util.ArrayList)6 JSONException (org.json.JSONException)6 JSONObject (org.json.JSONObject)5 IOException (java.io.IOException)4 NonNull (androidx.annotation.NonNull)2 Map (java.util.Map)2 Activity (android.app.Activity)1 Intent (android.content.Intent)1 SharedPreferences (android.content.SharedPreferences)1 Bitmap (android.graphics.Bitmap)1 Drawable (android.graphics.drawable.Drawable)1 Uri (android.net.Uri)1 Bundle (android.os.Bundle)1 Handler (android.os.Handler)1 SpannableString (android.text.SpannableString)1 Linkify (android.text.util.Linkify)1 Log (android.util.Log)1 InflateException (android.view.InflateException)1