Search in sources :

Example 11 with AccountManager

use of net.dean.jraw.managers.AccountManager in project Slide by ccrama.

the class NewsActivity method onPause.

@Override
public void onPause() {
    super.onPause();
    changed = false;
    if (!SettingValues.synccitName.isEmpty()) {
        new MySynccitUpdateTask().execute(SynccitRead.newVisited.toArray(new String[SynccitRead.newVisited.size()]));
    }
    if (Authentication.isLoggedIn && Authentication.me != null && Authentication.me.hasGold() && !SynccitRead.newVisited.isEmpty()) {
        new AsyncTask<Void, Void, Void>() {

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    String[] returned = new String[SynccitRead.newVisited.size()];
                    int i = 0;
                    for (String s : SynccitRead.newVisited) {
                        if (!s.contains("t3_")) {
                            s = "t3_" + s;
                        }
                        returned[i] = s;
                        i++;
                    }
                    new AccountManager(Authentication.reddit).storeVisits(returned);
                    SynccitRead.newVisited = new ArrayList<>();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }
    // Upon leaving MainActivity--hide the toolbar search if it is visible
    if (findViewById(R.id.toolbar_search).getVisibility() == View.VISIBLE) {
        findViewById(R.id.close_search_toolbar).performClick();
    }
}
Also used : CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) ArrayList(java.util.ArrayList) MySynccitUpdateTask(me.ccrama.redditslide.Synccit.MySynccitUpdateTask) AccountManager(net.dean.jraw.managers.AccountManager)

Example 12 with AccountManager

use of net.dean.jraw.managers.AccountManager in project Slide by ccrama.

the class PopulateNewsViewHolder method showBottomSheet.

public <T extends Contribution> void showBottomSheet(final Activity mContext, final Submission submission, final NewsViewHolder holder, final List<T> posts, final String baseSub, final RecyclerView recyclerview, final boolean full) {
    int[] attrs = new int[] { R.attr.tintColor };
    TypedArray ta = mContext.obtainStyledAttributes(attrs);
    int color = ta.getColor(0, Color.WHITE);
    Drawable profile = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.profile, null);
    final Drawable sub = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.sub, null);
    Drawable saved = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.iconstarfilled, null);
    Drawable hide = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.hide, null);
    final Drawable report = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.report, null);
    Drawable copy = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_content_copy, null);
    final Drawable readLater = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.save, null);
    Drawable open = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.openexternal, null);
    Drawable link = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.link, null);
    Drawable reddit = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.commentchange, null);
    Drawable filter = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.filter, null);
    profile.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    sub.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    saved.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    hide.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    report.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    copy.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    open.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    link.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    reddit.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    readLater.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    filter.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    ta.recycle();
    final BottomSheet.Builder b = new BottomSheet.Builder(mContext).title(Html.fromHtml(submission.getTitle()));
    final boolean isReadLater = mContext instanceof PostReadLater;
    final boolean isAddedToReadLaterList = ReadLater.isToBeReadLater(submission);
    if (Authentication.didOnline) {
        b.sheet(1, profile, "/u/" + submission.getAuthor()).sheet(2, sub, "/r/" + submission.getSubredditName());
        String save = mContext.getString(R.string.btn_save);
        if (ActionStates.isSaved(submission)) {
            save = mContext.getString(R.string.comment_unsave);
        }
        if (Authentication.isLoggedIn) {
            b.sheet(3, saved, save);
        }
    }
    if (isAddedToReadLaterList) {
        b.sheet(28, readLater, "Mark As Read");
    } else {
        b.sheet(28, readLater, "Read later");
    }
    if (Authentication.didOnline) {
        if (Authentication.isLoggedIn) {
            b.sheet(12, report, mContext.getString(R.string.btn_report));
        }
    }
    if (submission.getSelftext() != null && !submission.getSelftext().isEmpty() && full) {
        b.sheet(25, copy, mContext.getString(R.string.submission_copy_text));
    }
    boolean hidden = submission.isHidden();
    if (!full && Authentication.didOnline) {
        if (!hidden) {
            b.sheet(5, hide, mContext.getString(R.string.submission_hide));
        } else {
            b.sheet(5, hide, mContext.getString(R.string.submission_unhide));
        }
    }
    b.sheet(7, open, mContext.getString(R.string.submission_link_extern));
    b.sheet(4, link, mContext.getString(R.string.submission_share_permalink)).sheet(8, reddit, mContext.getString(R.string.submission_share_reddit_url));
    if ((mContext instanceof MainActivity) || (mContext instanceof SubredditView)) {
        b.sheet(10, filter, mContext.getString(R.string.filter_content));
    }
    b.listener(new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch(which) {
                case 1:
                    {
                        Intent i = new Intent(mContext, Profile.class);
                        i.putExtra(Profile.EXTRA_PROFILE, submission.getAuthor());
                        mContext.startActivity(i);
                    }
                    break;
                case 2:
                    {
                        Intent i = new Intent(mContext, SubredditView.class);
                        i.putExtra(SubredditView.EXTRA_SUBREDDIT, submission.getSubredditName());
                        mContext.startActivityForResult(i, 14);
                    }
                    break;
                case 10:
                    String[] choices;
                    final String flair = submission.getSubmissionFlair().getText() != null ? submission.getSubmissionFlair().getText() : "";
                    if (flair.isEmpty()) {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()) };
                        chosen = new boolean[] { Arrays.asList(SettingValues.subredditFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.userFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.domainFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.alwaysExternal.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getDomain().toLowerCase(Locale.ENGLISH)) };
                        oldChosen = chosen.clone();
                    } else {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()), mContext.getString(R.string.filter_posts_flair, flair, baseSub) };
                    }
                    ;
                    chosen = new boolean[] { Arrays.asList(SettingValues.subredditFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.userFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.domainFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.alwaysExternal.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.flairFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(baseSub + ":" + flair) };
                    oldChosen = chosen.clone();
                    new AlertDialogWrapper.Builder(mContext).setTitle(R.string.filter_title).alwaysCallMultiChoiceCallback().setMultiChoiceItems(choices, chosen, new DialogInterface.OnMultiChoiceClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            chosen[which] = isChecked;
                        }
                    }).setPositiveButton(R.string.filter_btn, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            boolean filtered = false;
                            SharedPreferences.Editor e = SettingValues.prefs.edit();
                            if (chosen[0] && chosen[0] != oldChosen[0]) {
                                SettingValues.subredditFilters = SettingValues.subredditFilters + ((SettingValues.subredditFilters.isEmpty() || SettingValues.subredditFilters.endsWith(",")) ? "" : ",") + submission.getSubredditName();
                                filtered = true;
                                e.putString(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                                PostMatch.subreddits = null;
                            } else if (!chosen[0] && chosen[0] != oldChosen[0]) {
                                SettingValues.subredditFilters = SettingValues.subredditFilters.replace(submission.getSubredditName(), "");
                                filtered = false;
                                e.putString(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                                e.apply();
                                PostMatch.subreddits = null;
                            }
                            if (chosen[1] && chosen[1] != oldChosen[1]) {
                                SettingValues.userFilters = SettingValues.userFilters + ((SettingValues.userFilters.isEmpty() || SettingValues.userFilters.endsWith(",")) ? "" : ",") + submission.getAuthor();
                                filtered = true;
                                e.putString(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                                PostMatch.users = null;
                            } else if (!chosen[1] && chosen[1] != oldChosen[1]) {
                                SettingValues.userFilters = SettingValues.userFilters.replace(submission.getAuthor(), "");
                                filtered = false;
                                e.putString(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                                e.apply();
                                PostMatch.users = null;
                            }
                            if (chosen[2] && chosen[2] != oldChosen[2]) {
                                SettingValues.domainFilters = SettingValues.domainFilters + ((SettingValues.domainFilters.isEmpty() || SettingValues.domainFilters.endsWith(",")) ? "" : ",") + submission.getDomain();
                                filtered = true;
                                e.putString(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                                PostMatch.domains = null;
                            } else if (!chosen[2] && chosen[2] != oldChosen[2]) {
                                SettingValues.domainFilters = SettingValues.domainFilters.replace(submission.getDomain(), "");
                                filtered = false;
                                e.putString(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                                e.apply();
                                PostMatch.domains = null;
                            }
                            if (chosen[3] && chosen[3] != oldChosen[3]) {
                                SettingValues.alwaysExternal = SettingValues.alwaysExternal + ((SettingValues.alwaysExternal.isEmpty() || SettingValues.alwaysExternal.endsWith(",")) ? "" : ",") + submission.getDomain();
                                e.putString(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                                e.apply();
                            } else if (!chosen[3] && chosen[3] != oldChosen[3]) {
                                SettingValues.alwaysExternal = SettingValues.alwaysExternal.replace(submission.getDomain(), "");
                                e.putString(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                                e.apply();
                            }
                            if (chosen.length > 4) {
                                if (chosen[4] && chosen[4] != oldChosen[4]) {
                                    SettingValues.flairFilters = SettingValues.flairFilters + ((SettingValues.flairFilters.isEmpty() || SettingValues.flairFilters.endsWith(",")) ? "" : ",") + (baseSub + ":" + flair);
                                    e.putString(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                    e.apply();
                                    PostMatch.flairs = null;
                                    filtered = true;
                                } else if (!chosen[4] && chosen[4] != oldChosen[4]) {
                                    SettingValues.flairFilters = SettingValues.flairFilters.toLowerCase(Locale.ENGLISH).replace((baseSub + ":" + flair).toLowerCase(Locale.ENGLISH), "");
                                    e.putString(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                    e.apply();
                                    PostMatch.flairs = null;
                                }
                            }
                            if (filtered) {
                                e.apply();
                                PostMatch.domains = null;
                                PostMatch.subreddits = null;
                                PostMatch.users = null;
                                ArrayList<Contribution> toRemove = new ArrayList<>();
                                for (Contribution s : posts) {
                                    if (s instanceof Submission && PostMatch.doesMatch((Submission) s)) {
                                        toRemove.add(s);
                                    }
                                }
                                OfflineSubreddit s = OfflineSubreddit.getSubreddit(baseSub, false, mContext);
                                for (Contribution remove : toRemove) {
                                    final int pos = posts.indexOf(remove);
                                    posts.remove(pos);
                                    if (baseSub != null) {
                                        s.hideMulti(pos);
                                    }
                                }
                                s.writeToMemoryNoStorage();
                                recyclerview.getAdapter().notifyDataSetChanged();
                            }
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                    break;
                case 5:
                    {
                        hideSubmission(submission, posts, baseSub, recyclerview, mContext);
                    }
                    break;
                case 7:
                    LinkUtil.openExternally(submission.getUrl(), mContext);
                    if (submission.isNsfw() && !SettingValues.storeNSFWHistory) {
                    // Do nothing if the post is NSFW and storeNSFWHistory is not enabled
                    } else if (SettingValues.storeHistory) {
                        HasSeen.addSeen(submission.getFullName());
                    }
                    break;
                case 28:
                    if (!isAddedToReadLaterList) {
                        ReadLater.setReadLater(submission, true);
                        Snackbar s = Snackbar.make(holder.itemView, "Added to read later!", Snackbar.LENGTH_SHORT);
                        View view = s.getView();
                        TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                        tv.setTextColor(Color.WHITE);
                        s.setAction(R.string.btn_undo, new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                ReadLater.setReadLater(submission, false);
                                Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                                View view2 = s2.getView();
                                TextView tv2 = (TextView) view2.findViewById(android.support.design.R.id.snackbar_text);
                                tv2.setTextColor(Color.WHITE);
                                s2.show();
                            }
                        });
                        if (NetworkUtil.isConnected(mContext)) {
                            new CommentCacheAsync(Arrays.asList(submission), mContext, CommentCacheAsync.SAVED_SUBMISSIONS, new boolean[] { true, true }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                        s.show();
                    } else {
                        ReadLater.setReadLater(submission, false);
                        if (isReadLater || !Authentication.didOnline) {
                            final int pos = posts.indexOf(submission);
                            posts.remove(submission);
                            recyclerview.getAdapter().notifyItemRemoved(holder.getAdapterPosition());
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = (TextView) view2.findViewById(android.support.design.R.id.snackbar_text);
                            tv2.setTextColor(Color.WHITE);
                            s2.setAction(R.string.btn_undo, new View.OnClickListener() {

                                @Override
                                public void onClick(View view) {
                                    posts.add(pos, (T) submission);
                                    recyclerview.getAdapter().notifyDataSetChanged();
                                }
                            });
                        } else {
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = (TextView) view2.findViewById(android.support.design.R.id.snackbar_text);
                            s2.show();
                        }
                        OfflineSubreddit.newSubreddit(CommentCacheAsync.SAVED_SUBMISSIONS).deleteFromMemory(submission.getFullName());
                    }
                    break;
                case 4:
                    Reddit.defaultShareText(Html.fromHtml(submission.getTitle()).toString(), StringEscapeUtils.escapeHtml4(submission.getUrl()), mContext);
                    break;
                case 12:
                    reportReason = "";
                    new MaterialDialog.Builder(mContext).input(mContext.getString(R.string.input_reason_for_report), null, true, new MaterialDialog.InputCallback() {

                        @Override
                        public void onInput(MaterialDialog dialog, CharSequence input) {
                            reportReason = input.toString();
                        }
                    }).title(R.string.report_post).alwaysCallInputCallback().inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES).positiveText(R.string.btn_report).negativeText(R.string.btn_cancel).onNegative(null).onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            new AsyncTask<Void, Void, Void>() {

                                @Override
                                protected Void doInBackground(Void... params) {
                                    try {
                                        new AccountManager(Authentication.reddit).report(submission, reportReason);
                                    } catch (ApiException e) {
                                        e.printStackTrace();
                                    }
                                    return null;
                                }

                                @Override
                                protected void onPostExecute(Void aVoid) {
                                    if (holder.itemView != null) {
                                        try {
                                            Snackbar s = Snackbar.make(holder.itemView, R.string.msg_report_sent, Snackbar.LENGTH_SHORT);
                                            View view = s.getView();
                                            TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                            tv.setTextColor(Color.WHITE);
                                            s.show();
                                        } catch (Exception ignored) {
                                        }
                                    }
                                }
                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    }).show();
                    break;
                case 8:
                    Reddit.defaultShareText(Html.fromHtml(submission.getTitle()).toString(), "https://reddit.com" + submission.getPermalink(), mContext);
                    break;
                case 6:
                    {
                        ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Link", submission.getUrl());
                        clipboard.setPrimaryClip(clip);
                        Toast.makeText(mContext, R.string.submission_link_copied, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 25:
                    final TextView showText = new TextView(mContext);
                    showText.setText(StringEscapeUtils.unescapeHtml4(submission.getTitle() + "\n\n" + submission.getSelftext()));
                    showText.setTextIsSelectable(true);
                    int sixteen = Reddit.dpToPxVertical(24);
                    showText.setPadding(sixteen, 0, sixteen, 0);
                    AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(mContext);
                    builder.setView(showText).setTitle("Select text to copy").setCancelable(true).setPositiveButton("COPY SELECTED", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String selected = showText.getText().toString().substring(showText.getSelectionStart(), showText.getSelectionEnd());
                            if (!selected.isEmpty()) {
                                ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                                ClipData clip = ClipData.newPlainText("Selftext", selected);
                                clipboard.setPrimaryClip(clip);
                                Toast.makeText(mContext, R.string.submission_comment_copied, Toast.LENGTH_SHORT).show();
                            } else {
                                ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                                ClipData clip = ClipData.newPlainText("Selftext", Html.fromHtml(submission.getTitle() + "\n\n" + submission.getSelftext()));
                                clipboard.setPrimaryClip(clip);
                                Toast.makeText(mContext, R.string.submission_comment_copied, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).setNeutralButton("COPY ALL", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                            ClipData clip = ClipData.newPlainText("Selftext", Html.fromHtml(submission.getTitle() + "\n\n" + submission.getSelftext()));
                            clipboard.setPrimaryClip(clip);
                            Toast.makeText(mContext, R.string.submission_comment_copied, Toast.LENGTH_SHORT).show();
                        }
                    }).show();
                    break;
            }
        }
    });
    b.show();
}
Also used : DialogInterface(android.content.DialogInterface) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) PostReadLater(me.ccrama.redditslide.Activities.PostReadLater) SubredditView(me.ccrama.redditslide.Activities.SubredditView) MainActivity(me.ccrama.redditslide.Activities.MainActivity) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) TypedArray(android.content.res.TypedArray) TextView(android.widget.TextView) ClipboardManager(android.content.ClipboardManager) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Submission(net.dean.jraw.models.Submission) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) SharedPreferences(android.content.SharedPreferences) Drawable(android.graphics.drawable.Drawable) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) MediaView(me.ccrama.redditslide.Activities.MediaView) ImageView(android.widget.ImageView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) View(android.view.View) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) RecyclerView(android.support.v7.widget.RecyclerView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) ApiException(net.dean.jraw.ApiException) DialogAction(com.afollestad.materialdialogs.DialogAction) AccountManager(net.dean.jraw.managers.AccountManager) BottomSheet(com.cocosw.bottomsheet.BottomSheet) ClipData(android.content.ClipData) Contribution(net.dean.jraw.models.Contribution) Snackbar(android.support.design.widget.Snackbar) ApiException(net.dean.jraw.ApiException)

Example 13 with AccountManager

use of net.dean.jraw.managers.AccountManager in project Slide by ccrama.

the class PopulateShadowboxInfo method doActionbar.

public static void doActionbar(final Submission s, final View rootView, final Activity c, boolean extras) {
    TextView title = (TextView) rootView.findViewById(R.id.title);
    TextView desc = (TextView) rootView.findViewById(R.id.desc);
    String distingush = "";
    if (s != null) {
        if (s.getDistinguishedStatus() == DistinguishedStatus.MODERATOR)
            distingush = "[M]";
        else if (s.getDistinguishedStatus() == DistinguishedStatus.ADMIN)
            distingush = "[A]";
        title.setText(Html.fromHtml(s.getTitle()));
        String spacer = c.getString(R.string.submission_properties_seperator);
        SpannableStringBuilder titleString = new SpannableStringBuilder();
        SpannableStringBuilder subreddit = new SpannableStringBuilder(" /r/" + s.getSubredditName() + " ");
        String subname = s.getSubredditName().toLowerCase(Locale.ENGLISH);
        if ((SettingValues.colorSubName && Palette.getColor(subname) != Palette.getDefaultColor())) {
            subreddit.setSpan(new ForegroundColorSpan(Palette.getColor(subname)), 0, subreddit.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            subreddit.setSpan(new StyleSpan(Typeface.BOLD), 0, subreddit.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        titleString.append(subreddit);
        titleString.append(distingush);
        titleString.append(spacer);
        titleString.append(TimeUtils.getTimeAgo(s.getCreated().getTime(), c));
        desc.setText(titleString);
        ((TextView) rootView.findViewById(R.id.comments)).setText(String.format(Locale.getDefault(), "%d", s.getCommentCount()));
        ((TextView) rootView.findViewById(R.id.score)).setText(String.format(Locale.getDefault(), "%d", s.getScore()));
        if (extras) {
            final ImageView downvotebutton = (ImageView) rootView.findViewById(R.id.downvote);
            final ImageView upvotebutton = (ImageView) rootView.findViewById(R.id.upvote);
            if (s.isArchived() || s.isLocked()) {
                downvotebutton.setVisibility(View.GONE);
                upvotebutton.setVisibility(View.GONE);
            } else if (Authentication.isLoggedIn && Authentication.didOnline) {
                if (SettingValues.actionbarVisible && downvotebutton.getVisibility() != View.VISIBLE) {
                    downvotebutton.setVisibility(View.VISIBLE);
                    upvotebutton.setVisibility(View.VISIBLE);
                }
                switch(ActionStates.getVoteDirection(s)) {
                    case UPVOTE:
                        {
                            ((TextView) rootView.findViewById(R.id.score)).setTextColor(ContextCompat.getColor(c, R.color.md_orange_500));
                            upvotebutton.setColorFilter(ContextCompat.getColor(c, R.color.md_orange_500), PorterDuff.Mode.SRC_ATOP);
                            ((TextView) rootView.findViewById(R.id.score)).setTypeface(null, Typeface.BOLD);
                            ((TextView) rootView.findViewById(R.id.score)).setText(String.format(Locale.getDefault(), "%d", (s.getScore() + ((s.getAuthor().equals(Authentication.name)) ? 0 : 1))));
                            downvotebutton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                            break;
                        }
                    case DOWNVOTE:
                        {
                            ((TextView) rootView.findViewById(R.id.score)).setTextColor(ContextCompat.getColor(c, R.color.md_blue_500));
                            downvotebutton.setColorFilter(ContextCompat.getColor(c, R.color.md_blue_500), PorterDuff.Mode.SRC_ATOP);
                            ((TextView) rootView.findViewById(R.id.score)).setTypeface(null, Typeface.BOLD);
                            ((TextView) rootView.findViewById(R.id.score)).setText(String.format(Locale.getDefault(), "%d", (s.getScore() + ((s.getAuthor().equals(Authentication.name)) ? 0 : -1))));
                            upvotebutton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                            break;
                        }
                    case NO_VOTE:
                        {
                            ((TextView) rootView.findViewById(R.id.score)).setTextColor(((TextView) rootView.findViewById(R.id.comments)).getCurrentTextColor());
                            ((TextView) rootView.findViewById(R.id.score)).setText(String.format(Locale.getDefault(), "%d", s.getScore()));
                            ((TextView) rootView.findViewById(R.id.score)).setTypeface(null, Typeface.NORMAL);
                            downvotebutton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                            upvotebutton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                            break;
                        }
                }
            }
            if (Authentication.isLoggedIn && Authentication.didOnline) {
                if (ActionStates.isSaved(s)) {
                    ((ImageView) rootView.findViewById(R.id.save)).setColorFilter(ContextCompat.getColor(c, R.color.md_amber_500), PorterDuff.Mode.SRC_ATOP);
                } else {
                    ((ImageView) rootView.findViewById(R.id.save)).setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                }
                rootView.findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        new AsyncTask<Void, Void, Void>() {

                            @Override
                            protected Void doInBackground(Void... params) {
                                try {
                                    if (ActionStates.isSaved(s)) {
                                        new AccountManager(Authentication.reddit).unsave(s);
                                        ActionStates.setSaved(s, false);
                                    } else {
                                        new AccountManager(Authentication.reddit).save(s);
                                        ActionStates.setSaved(s, true);
                                    }
                                } catch (ApiException e) {
                                    e.printStackTrace();
                                }
                                return null;
                            }

                            @Override
                            protected void onPostExecute(Void aVoid) {
                                ((SlidingUpPanelLayout) rootView.findViewById(R.id.sliding_layout)).setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
                                if (ActionStates.isSaved(s)) {
                                    ((ImageView) rootView.findViewById(R.id.save)).setColorFilter(ContextCompat.getColor(c, R.color.md_amber_500), PorterDuff.Mode.SRC_ATOP);
                                    AnimateHelper.setFlashAnimation(rootView, rootView.findViewById(R.id.save), ContextCompat.getColor(c, R.color.md_amber_500));
                                } else {
                                    ((ImageView) rootView.findViewById(R.id.save)).setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                                }
                            }
                        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                    }
                });
            }
            if (!Authentication.isLoggedIn || !Authentication.didOnline) {
                rootView.findViewById(R.id.save).setVisibility(View.GONE);
            }
            try {
                final TextView points = ((TextView) rootView.findViewById(R.id.score));
                final TextView comments = ((TextView) rootView.findViewById(R.id.comments));
                if (Authentication.isLoggedIn && Authentication.didOnline) {
                    {
                        downvotebutton.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                ((SlidingUpPanelLayout) rootView.findViewById(R.id.sliding_layout)).setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
                                if (SettingValues.storeHistory) {
                                    if (!s.isNsfw() || SettingValues.storeNSFWHistory) {
                                        HasSeen.addSeen(s.getFullName());
                                    }
                                }
                                if (ActionStates.getVoteDirection(s) != VoteDirection.DOWNVOTE) {
                                    // has not been downvoted
                                    points.setTextColor(ContextCompat.getColor(c, R.color.md_blue_500));
                                    downvotebutton.setColorFilter(ContextCompat.getColor(c, R.color.md_blue_500), PorterDuff.Mode.SRC_ATOP);
                                    upvotebutton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                                    AnimateHelper.setFlashAnimation(rootView, downvotebutton, ContextCompat.getColor(c, R.color.md_blue_500));
                                    ((TextView) rootView.findViewById(R.id.score)).setTypeface(null, Typeface.BOLD);
                                    // if a post is at 0 votes, keep it at 0 when downvoting
                                    final int downvoteScore = (s.getScore() == 0) ? 0 : s.getScore() - 1;
                                    ((TextView) rootView.findViewById(R.id.score)).setText(String.format(Locale.getDefault(), "%d", downvoteScore));
                                    new Vote(false, points, c).execute(s);
                                    ActionStates.setVoteDirection(s, VoteDirection.DOWNVOTE);
                                } else {
                                    points.setTextColor(comments.getCurrentTextColor());
                                    new Vote(points, c).execute(s);
                                    ((TextView) rootView.findViewById(R.id.score)).setTypeface(null, Typeface.NORMAL);
                                    ((TextView) rootView.findViewById(R.id.score)).setText(String.format(Locale.getDefault(), "%d", s.getScore()));
                                    ActionStates.setVoteDirection(s, VoteDirection.NO_VOTE);
                                    downvotebutton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                                }
                            }
                        });
                    }
                    {
                        upvotebutton.setOnClickListener(new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                ((SlidingUpPanelLayout) rootView.findViewById(R.id.sliding_layout)).setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
                                if (SettingValues.storeHistory) {
                                    if (!s.isNsfw() || SettingValues.storeNSFWHistory) {
                                        HasSeen.addSeen(s.getFullName());
                                    }
                                }
                                if (ActionStates.getVoteDirection(s) != VoteDirection.UPVOTE) {
                                    // has not been upvoted
                                    points.setTextColor(ContextCompat.getColor(c, R.color.md_orange_500));
                                    upvotebutton.setColorFilter(ContextCompat.getColor(c, R.color.md_orange_500), PorterDuff.Mode.SRC_ATOP);
                                    downvotebutton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                                    AnimateHelper.setFlashAnimation(rootView, upvotebutton, ContextCompat.getColor(c, R.color.md_orange_500));
                                    ((TextView) rootView.findViewById(R.id.score)).setTypeface(null, Typeface.BOLD);
                                    ((TextView) rootView.findViewById(R.id.score)).setText(String.format(Locale.getDefault(), "%d", s.getScore() + 1));
                                    new Vote(true, points, c).execute(s);
                                    ActionStates.setVoteDirection(s, VoteDirection.UPVOTE);
                                } else {
                                    points.setTextColor(comments.getCurrentTextColor());
                                    new Vote(points, c).execute(s);
                                    ((TextView) rootView.findViewById(R.id.score)).setTypeface(null, Typeface.NORMAL);
                                    ((TextView) rootView.findViewById(R.id.score)).setText(String.format(Locale.getDefault(), "%d", s.getScore()));
                                    ActionStates.setVoteDirection(s, VoteDirection.NO_VOTE);
                                    upvotebutton.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
                                }
                            }
                        });
                    }
                } else {
                    upvotebutton.setVisibility(View.GONE);
                    downvotebutton.setVisibility(View.GONE);
                }
            } catch (Exception ignored) {
                ignored.printStackTrace();
            }
            rootView.findViewById(R.id.menu).setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    showBottomSheet(c, s, rootView);
                }
            });
        }
    }
}
Also used : Vote(me.ccrama.redditslide.Vote) SlidingUpPanelLayout(com.sothree.slidinguppanel.SlidingUpPanelLayout) ForegroundColorSpan(android.text.style.ForegroundColorSpan) AsyncTask(android.os.AsyncTask) ImageView(android.widget.ImageView) TitleTextView(me.ccrama.redditslide.Views.TitleTextView) View(android.view.View) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) ApiException(net.dean.jraw.ApiException) StyleSpan(android.text.style.StyleSpan) TitleTextView(me.ccrama.redditslide.Views.TitleTextView) TextView(android.widget.TextView) AccountManager(net.dean.jraw.managers.AccountManager) ImageView(android.widget.ImageView) SpannableStringBuilder(android.text.SpannableStringBuilder) ApiException(net.dean.jraw.ApiException)

Example 14 with AccountManager

use of net.dean.jraw.managers.AccountManager in project Slide by ccrama.

the class PopulateSubmissionViewHolder method populateSubmissionViewHolder.

public <T extends Contribution> void populateSubmissionViewHolder(final SubmissionViewHolder holder, final Submission submission, final Activity mContext, boolean fullscreen, final boolean full, final List<T> posts, final RecyclerView recyclerview, final boolean same, final boolean offline, final String baseSub, @Nullable final CommentAdapter adapter) {
    holder.itemView.findViewById(R.id.vote).setVisibility(View.GONE);
    if (!offline && UserSubscriptions.modOf != null && submission.getSubredditName() != null && UserSubscriptions.modOf.contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH))) {
        holder.mod.setVisibility(View.VISIBLE);
        final Map<String, Integer> reports = submission.getUserReports();
        final Map<String, String> reports2 = submission.getModeratorReports();
        if (reports.size() + reports2.size() > 0) {
            ((ImageView) holder.mod).setColorFilter(ContextCompat.getColor(mContext, R.color.md_red_300), PorterDuff.Mode.SRC_ATOP);
        } else {
            ((ImageView) holder.mod).setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
        }
        holder.mod.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                showModBottomSheet(mContext, submission, posts, holder, recyclerview, reports, reports2);
            }
        });
    } else {
        holder.mod.setVisibility(View.GONE);
    }
    holder.menu.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            showBottomSheet(mContext, submission, holder, posts, baseSub, recyclerview, full);
        }
    });
    // Use this to offset the submission score
    int submissionScore = submission.getScore();
    final int commentCount = submission.getCommentCount();
    final int more = LastComments.commentsSince(submission);
    holder.comments.setText(String.format(Locale.getDefault(), "%d %s", commentCount, ((more > 0 && SettingValues.commentLastVisit) ? "(+" + more + ")" : "")));
    String scoreRatio = (SettingValues.upvotePercentage && full && submission.getUpvoteRatio() != null) ? "(" + (int) (submission.getUpvoteRatio() * 100) + "%)" : "";
    if (!scoreRatio.isEmpty()) {
        TextView percent = holder.itemView.findViewById(R.id.percent);
        percent.setVisibility(View.VISIBLE);
        percent.setText(scoreRatio);
        final double numb = (submission.getUpvoteRatio());
        if (numb <= .5) {
            if (numb <= .1) {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_500));
            } else if (numb <= .3) {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_400));
            } else {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_300));
            }
        } else {
            if (numb >= .9) {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_500));
            } else if (numb >= .7) {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_400));
            } else {
                percent.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_300));
            }
        }
    }
    final ImageView downvotebutton = (ImageView) holder.downvote;
    final ImageView upvotebutton = (ImageView) holder.upvote;
    if (submission.isArchived()) {
        downvotebutton.setVisibility(View.GONE);
        upvotebutton.setVisibility(View.GONE);
    } else if (Authentication.isLoggedIn && Authentication.didOnline) {
        if (SettingValues.actionbarVisible && downvotebutton.getVisibility() != View.VISIBLE) {
            downvotebutton.setVisibility(View.VISIBLE);
            upvotebutton.setVisibility(View.VISIBLE);
        }
    }
    // Set the colors and styles for the score text depending on what state it is in
    switch(ActionStates.getVoteDirection(submission)) {
        case UPVOTE:
            {
                holder.score.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_500));
                upvotebutton.setColorFilter(ContextCompat.getColor(mContext, R.color.md_orange_500), PorterDuff.Mode.SRC_ATOP);
                holder.score.setTypeface(null, Typeface.BOLD);
                downvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                if (submission.getVote() != VoteDirection.UPVOTE) {
                    if (submission.getVote() == VoteDirection.DOWNVOTE)
                        ++submissionScore;
                    // offset the score by +1
                    ++submissionScore;
                }
                break;
            }
        case DOWNVOTE:
            {
                holder.score.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_500));
                downvotebutton.setColorFilter(ContextCompat.getColor(mContext, R.color.md_blue_500), PorterDuff.Mode.SRC_ATOP);
                holder.score.setTypeface(null, Typeface.BOLD);
                upvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                if (submission.getVote() != VoteDirection.DOWNVOTE) {
                    if (submission.getVote() == VoteDirection.UPVOTE)
                        --submissionScore;
                    // offset the score by +1
                    --submissionScore;
                }
                break;
            }
        case NO_VOTE:
            {
                holder.score.setTextColor(holder.comments.getCurrentTextColor());
                holder.score.setTypeface(null, Typeface.NORMAL);
                downvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                upvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                break;
            }
    }
    // if the submission is already at 0pts, keep it at 0pts
    submissionScore = ((submissionScore < 0) ? 0 : submissionScore);
    if (submissionScore >= 10000 && SettingValues.abbreviateScores) {
        holder.score.setText(String.format(Locale.getDefault(), "%.1fk", (((double) submissionScore) / 1000)));
    } else {
        holder.score.setText(String.format(Locale.getDefault(), "%d", submissionScore));
    }
    // Save the score so we can use it in the OnClickListeners for the vote buttons
    final int SUBMISSION_SCORE = submissionScore;
    final ImageView hideButton = (ImageView) holder.hide;
    if (hideButton != null) {
        if (SettingValues.hideButton && Authentication.isLoggedIn) {
            hideButton.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    hideSubmission(submission, posts, baseSub, recyclerview, mContext);
                }
            });
        } else {
            hideButton.setVisibility(View.GONE);
        }
    }
    if (Authentication.isLoggedIn && Authentication.didOnline) {
        if (ActionStates.isSaved(submission)) {
            ((ImageView) holder.save).setColorFilter(ContextCompat.getColor(mContext, R.color.md_amber_500), PorterDuff.Mode.SRC_ATOP);
        } else {
            ((ImageView) holder.save).setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
        }
        holder.save.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                saveSubmission(submission, mContext, holder, full);
            }
        });
    }
    if (!SettingValues.saveButton && !full || !Authentication.isLoggedIn || !Authentication.didOnline) {
        holder.save.setVisibility(View.GONE);
    }
    ImageView thumbImage2 = ((ImageView) holder.thumbimage);
    if (holder.leadImage.thumbImage2 == null) {
        holder.leadImage.setThumbnail(thumbImage2);
    }
    final ContentType.Type type = ContentType.getContentType(submission);
    addClickFunctions(holder.leadImage, type, mContext, submission, holder, full);
    if (thumbImage2 != null) {
        addClickFunctions(thumbImage2, type, mContext, submission, holder, full);
    }
    if (full) {
        addClickFunctions(holder.itemView.findViewById(R.id.wraparea), type, mContext, submission, holder, full);
    }
    if (full) {
        holder.leadImage.setWrapArea(holder.itemView.findViewById(R.id.wraparea));
    }
    boolean crosspost = submission.getDataNode().has("crosspost_parent_list");
    if (full && crosspost) {
        holder.itemView.findViewById(R.id.crosspost).setVisibility(View.VISIBLE);
        ((TextView) holder.itemView.findViewById(R.id.crossinfo)).setText(SubmissionCache.getCrosspostLine(submission, mContext));
        ((Reddit) mContext.getApplicationContext()).getImageLoader().displayImage(submission.getDataNode().get("crosspost_parent_list").get(0).get("thumbnail").asText(), ((ImageView) holder.itemView.findViewById(R.id.crossthumb)));
        holder.itemView.findViewById(R.id.crosspost).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                OpenRedditLink.openUrl(mContext, submission.getDataNode().get("crosspost_parent_list").get(0).get("permalink").asText(), true);
            }
        });
    }
    holder.leadImage.setSubmission(submission, full, baseSub, type);
    holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {
            if (offline) {
                Snackbar s = Snackbar.make(holder.itemView, mContext.getString(R.string.offline_msg), Snackbar.LENGTH_SHORT);
                View view = s.getView();
                TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                tv.setTextColor(Color.WHITE);
                s.show();
            } else {
                if (SettingValues.actionbarTap && !full) {
                    CreateCardView.toggleActionbar(holder.itemView);
                } else {
                    holder.itemView.findViewById(R.id.menu).callOnClick();
                }
            }
            return true;
        }
    });
    doText(holder, submission, mContext, baseSub, full);
    if (!full && SettingValues.isSelftextEnabled(baseSub) && submission.isSelfPost() && !submission.getSelftext().isEmpty() && !submission.isNsfw() && !submission.getDataNode().get("spoiler").asBoolean() && !submission.getDataNode().get("selftext_html").asText().trim().isEmpty()) {
        holder.body.setVisibility(View.VISIBLE);
        String text = submission.getDataNode().get("selftext_html").asText();
        int typef = new FontPreferences(mContext).getFontTypeComment().getTypeface();
        Typeface typeface;
        if (typef >= 0) {
            typeface = RobotoTypefaces.obtainTypeface(mContext, typef);
        } else {
            typeface = Typeface.DEFAULT;
        }
        holder.body.setTypeface(typeface);
        holder.body.setTextHtml(Html.fromHtml(text.substring(0, text.contains("\n") ? text.indexOf("\n") : text.length())).toString().replace("<sup>", "<sup><small>").replace("</sup>", "</small></sup>"), "none ");
        holder.body.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                holder.itemView.callOnClick();
            }
        });
        holder.body.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                holder.menu.callOnClick();
                return true;
            }
        });
    } else if (!full) {
        holder.body.setVisibility(View.GONE);
    }
    if (full) {
        if (!submission.getSelftext().isEmpty()) {
            int typef = new FontPreferences(mContext).getFontTypeComment().getTypeface();
            Typeface typeface;
            if (typef >= 0) {
                typeface = RobotoTypefaces.obtainTypeface(mContext, typef);
            } else {
                typeface = Typeface.DEFAULT;
            }
            holder.firstTextView.setTypeface(typeface);
            setViews(submission.getDataNode().get("selftext_html").asText(), submission.getSubredditName() == null ? "all" : submission.getSubredditName(), holder);
            holder.itemView.findViewById(R.id.body_area).setVisibility(View.VISIBLE);
        } else {
            holder.itemView.findViewById(R.id.body_area).setVisibility(View.GONE);
        }
    }
    try {
        final TextView points = holder.score;
        final TextView comments = holder.comments;
        if (Authentication.isLoggedIn && !offline && Authentication.didOnline) {
            {
                downvotebutton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        if (SettingValues.storeHistory && !full) {
                            if (!submission.isNsfw() || SettingValues.storeNSFWHistory) {
                                HasSeen.addSeen(submission.getFullName());
                                if (mContext instanceof MainActivity) {
                                    holder.title.setAlpha(0.54f);
                                    holder.body.setAlpha(0.54f);
                                }
                            }
                        }
                        if (ActionStates.getVoteDirection(submission) != VoteDirection.DOWNVOTE) {
                            // has not been downvoted
                            points.setTextColor(ContextCompat.getColor(mContext, R.color.md_blue_500));
                            downvotebutton.setColorFilter(ContextCompat.getColor(mContext, R.color.md_blue_500), PorterDuff.Mode.SRC_ATOP);
                            upvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                            AnimateHelper.setFlashAnimation(holder.itemView, downvotebutton, ContextCompat.getColor(mContext, R.color.md_blue_500));
                            holder.score.setTypeface(null, Typeface.BOLD);
                            final int DOWNVOTE_SCORE = (SUBMISSION_SCORE == 0) ? 0 : SUBMISSION_SCORE - // if a post is at 0 votes, keep it at 0 when downvoting
                            1;
                            new Vote(false, points, mContext).execute(submission);
                            ActionStates.setVoteDirection(submission, VoteDirection.DOWNVOTE);
                            setSubmissionScoreText(submission, holder);
                        } else {
                            // un-downvoted a post
                            points.setTextColor(comments.getCurrentTextColor());
                            new Vote(points, mContext).execute(submission);
                            holder.score.setTypeface(null, Typeface.NORMAL);
                            ActionStates.setVoteDirection(submission, VoteDirection.NO_VOTE);
                            downvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                            setSubmissionScoreText(submission, holder);
                        }
                        if (!full && !SettingValues.actionbarVisible && SettingValues.defaultCardView != CreateCardView.CardEnum.DESKTOP) {
                            CreateCardView.toggleActionbar(holder.itemView);
                        }
                    }
                });
            }
            {
                upvotebutton.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        if (SettingValues.storeHistory && !full) {
                            if (!submission.isNsfw() || SettingValues.storeNSFWHistory) {
                                HasSeen.addSeen(submission.getFullName());
                                if (mContext instanceof MainActivity) {
                                    holder.title.setAlpha(0.54f);
                                    holder.body.setAlpha(0.54f);
                                }
                            }
                        }
                        if (ActionStates.getVoteDirection(submission) != VoteDirection.UPVOTE) {
                            // has not been upvoted
                            points.setTextColor(ContextCompat.getColor(mContext, R.color.md_orange_500));
                            upvotebutton.setColorFilter(ContextCompat.getColor(mContext, R.color.md_orange_500), PorterDuff.Mode.SRC_ATOP);
                            downvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                            AnimateHelper.setFlashAnimation(holder.itemView, upvotebutton, ContextCompat.getColor(mContext, R.color.md_orange_500));
                            holder.score.setTypeface(null, Typeface.BOLD);
                            new Vote(true, points, mContext).execute(submission);
                            ActionStates.setVoteDirection(submission, VoteDirection.UPVOTE);
                            setSubmissionScoreText(submission, holder);
                        } else {
                            // un-upvoted a post
                            points.setTextColor(comments.getCurrentTextColor());
                            new Vote(points, mContext).execute(submission);
                            holder.score.setTypeface(null, Typeface.NORMAL);
                            ActionStates.setVoteDirection(submission, VoteDirection.NO_VOTE);
                            upvotebutton.setColorFilter((((holder.itemView.getTag(holder.itemView.getId())) != null && holder.itemView.getTag(holder.itemView.getId()).equals("none") || full)) ? getCurrentTintColor(mContext) : getWhiteTintColor(), PorterDuff.Mode.SRC_ATOP);
                            setSubmissionScoreText(submission, holder);
                        }
                        if (!full && !SettingValues.actionbarVisible && SettingValues.defaultCardView != CreateCardView.CardEnum.DESKTOP) {
                            CreateCardView.toggleActionbar(holder.itemView);
                        }
                    }
                });
            }
        } else {
            upvotebutton.setVisibility(View.GONE);
            downvotebutton.setVisibility(View.GONE);
        }
    } catch (Exception ignored) {
        ignored.printStackTrace();
    }
    final View edit = holder.edit;
    if (Authentication.name != null && Authentication.name.toLowerCase(Locale.ENGLISH).equals(submission.getAuthor().toLowerCase(Locale.ENGLISH)) && Authentication.didOnline) {
        edit.setVisibility(View.VISIBLE);
        edit.setOnClickListener(new OnSingleClickListener() {

            @Override
            public void onSingleClick(View v) {
                new AsyncTask<Void, Void, ArrayList<String>>() {

                    List<FlairTemplate> flairlist;

                    @Override
                    protected ArrayList<String> doInBackground(Void... params) {
                        FlairReference allFlairs = new FluentRedditClient(Authentication.reddit).subreddit(submission.getSubredditName()).flair();
                        try {
                            flairlist = allFlairs.options(submission);
                            final ArrayList<String> finalFlairs = new ArrayList<>();
                            for (FlairTemplate temp : flairlist) {
                                finalFlairs.add(temp.getText());
                            }
                            return finalFlairs;
                        } catch (Exception e) {
                            e.printStackTrace();
                        // sub probably has no flairs?
                        }
                        return null;
                    }

                    @Override
                    public void onPostExecute(final ArrayList<String> data) {
                        final boolean flair = (data != null && !data.isEmpty());
                        int[] attrs = new int[] { R.attr.tintColor };
                        TypedArray ta = mContext.obtainStyledAttributes(attrs);
                        final int color2 = ta.getColor(0, Color.WHITE);
                        Drawable edit_drawable = mContext.getResources().getDrawable(R.drawable.edit);
                        Drawable nsfw_drawable = mContext.getResources().getDrawable(R.drawable.hide);
                        Drawable delete_drawable = mContext.getResources().getDrawable(R.drawable.delete);
                        Drawable flair_drawable = mContext.getResources().getDrawable(R.drawable.fontsizedarker);
                        edit_drawable.setColorFilter(color2, PorterDuff.Mode.SRC_ATOP);
                        nsfw_drawable.setColorFilter(color2, PorterDuff.Mode.SRC_ATOP);
                        delete_drawable.setColorFilter(color2, PorterDuff.Mode.SRC_ATOP);
                        flair_drawable.setColorFilter(color2, PorterDuff.Mode.SRC_ATOP);
                        ta.recycle();
                        BottomSheet.Builder b = new BottomSheet.Builder(mContext).title(Html.fromHtml(submission.getTitle()));
                        if (submission.isSelfPost()) {
                            b.sheet(1, edit_drawable, mContext.getString(R.string.edit_selftext));
                        }
                        if (submission.isNsfw()) {
                            b.sheet(4, nsfw_drawable, mContext.getString(R.string.mod_btn_unmark_nsfw));
                        } else {
                            b.sheet(4, nsfw_drawable, mContext.getString(R.string.mod_btn_mark_nsfw));
                        }
                        b.sheet(2, delete_drawable, mContext.getString(R.string.delete_submission));
                        if (flair) {
                            b.sheet(3, flair_drawable, mContext.getString(R.string.set_submission_flair));
                        }
                        b.listener(new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                switch(which) {
                                    case 1:
                                        {
                                            LayoutInflater inflater = mContext.getLayoutInflater();
                                            final View dialoglayout = inflater.inflate(R.layout.edit_comment, null);
                                            final AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(mContext);
                                            final EditText e = dialoglayout.findViewById(R.id.entry);
                                            e.setText(StringEscapeUtils.unescapeHtml4(submission.getSelftext()));
                                            DoEditorActions.doActions(e, dialoglayout, ((AppCompatActivity) mContext).getSupportFragmentManager(), mContext, null, null);
                                            builder.setCancelable(false).setView(dialoglayout);
                                            final Dialog d = builder.create();
                                            d.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                                            d.show();
                                            dialoglayout.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    d.dismiss();
                                                }
                                            });
                                            dialoglayout.findViewById(R.id.submit).setOnClickListener(new View.OnClickListener() {

                                                @Override
                                                public void onClick(View v) {
                                                    final String text = e.getText().toString();
                                                    new AsyncTask<Void, Void, Void>() {

                                                        @Override
                                                        protected Void doInBackground(Void... params) {
                                                            try {
                                                                new AccountManager(Authentication.reddit).updateContribution(submission, text);
                                                                if (adapter != null) {
                                                                    adapter.dataSet.reloadSubmission(adapter);
                                                                }
                                                                d.dismiss();
                                                            } catch (Exception e) {
                                                                (mContext).runOnUiThread(new Runnable() {

                                                                    @Override
                                                                    public void run() {
                                                                        new AlertDialogWrapper.Builder(mContext).setTitle(R.string.comment_delete_err).setMessage(R.string.comment_delete_err_msg).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                                                            @Override
                                                                            public void onClick(DialogInterface dialog, int which) {
                                                                                dialog.dismiss();
                                                                                doInBackground();
                                                                            }
                                                                        }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                                                            @Override
                                                                            public void onClick(DialogInterface dialog, int which) {
                                                                                dialog.dismiss();
                                                                            }
                                                                        }).show();
                                                                    }
                                                                });
                                                            }
                                                            return null;
                                                        }

                                                        @Override
                                                        protected void onPostExecute(Void aVoid) {
                                                            if (adapter != null) {
                                                                adapter.notifyItemChanged(1);
                                                            }
                                                        }
                                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                                }
                                            });
                                        }
                                        break;
                                    case 2:
                                        {
                                            new AlertDialogWrapper.Builder(mContext).setTitle(R.string.really_delete_submission).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    new AsyncTask<Void, Void, Void>() {

                                                        @Override
                                                        protected Void doInBackground(Void... params) {
                                                            try {
                                                                new ModerationManager(Authentication.reddit).delete(submission);
                                                            } catch (ApiException e) {
                                                                e.printStackTrace();
                                                            }
                                                            return null;
                                                        }

                                                        @Override
                                                        protected void onPostExecute(Void aVoid) {
                                                            (mContext).runOnUiThread(new Runnable() {

                                                                @Override
                                                                public void run() {
                                                                    (holder.title).setTextHtml(mContext.getString(R.string.content_deleted));
                                                                    if (holder.firstTextView != null) {
                                                                        holder.firstTextView.setText(R.string.content_deleted);
                                                                        holder.commentOverflow.setVisibility(View.GONE);
                                                                    } else {
                                                                        if (holder.itemView.findViewById(R.id.body) != null) {
                                                                            ((TextView) holder.itemView.findViewById(R.id.body)).setText(R.string.content_deleted);
                                                                        }
                                                                    }
                                                                }
                                                            });
                                                        }
                                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                                }
                                            }).setNegativeButton(R.string.btn_cancel, null).show();
                                        }
                                        break;
                                    case 3:
                                        {
                                            new MaterialDialog.Builder(mContext).items(data).title(R.string.sidebar_select_flair).itemsCallback(new MaterialDialog.ListCallback() {

                                                @Override
                                                public void onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                                    final FlairTemplate t = flairlist.get(which);
                                                    if (t.isTextEditable()) {
                                                        new MaterialDialog.Builder(mContext).title(R.string.mod_btn_submission_flair_text).input(mContext.getString(R.string.mod_flair_hint), t.getText(), true, new MaterialDialog.InputCallback() {

                                                            @Override
                                                            public void onInput(MaterialDialog dialog, CharSequence input) {
                                                            }
                                                        }).positiveText(R.string.btn_set).onPositive(new MaterialDialog.SingleButtonCallback() {

                                                            @Override
                                                            public void onClick(MaterialDialog dialog, DialogAction which) {
                                                                final String flair = dialog.getInputEditText().getText().toString();
                                                                new AsyncTask<Void, Void, Boolean>() {

                                                                    @Override
                                                                    protected Boolean doInBackground(Void... params) {
                                                                        try {
                                                                            new ModerationManager(Authentication.reddit).setFlair(submission.getSubredditName(), t, flair, submission);
                                                                            return true;
                                                                        } catch (ApiException e) {
                                                                            e.printStackTrace();
                                                                            return false;
                                                                        }
                                                                    }

                                                                    @Override
                                                                    protected void onPostExecute(Boolean done) {
                                                                        Snackbar s = null;
                                                                        if (done) {
                                                                            if (holder.itemView != null) {
                                                                                s = Snackbar.make(holder.itemView, R.string.snackbar_flair_success, Snackbar.LENGTH_SHORT);
                                                                                SubmissionCache.updateTitleFlair(submission, flair, mContext);
                                                                                holder.title.setText(SubmissionCache.getTitleLine(submission, mContext));
                                                                            }
                                                                        } else {
                                                                            if (holder.itemView != null) {
                                                                                s = Snackbar.make(holder.itemView, R.string.snackbar_flair_error, Snackbar.LENGTH_SHORT);
                                                                            }
                                                                        }
                                                                        if (s != null) {
                                                                            View view = s.getView();
                                                                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                                            tv.setTextColor(Color.WHITE);
                                                                            s.show();
                                                                        }
                                                                    }
                                                                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                                            }
                                                        }).negativeText(R.string.btn_cancel).show();
                                                    } else {
                                                        new AsyncTask<Void, Void, Boolean>() {

                                                            @Override
                                                            protected Boolean doInBackground(Void... params) {
                                                                try {
                                                                    new ModerationManager(Authentication.reddit).setFlair(submission.getSubredditName(), t, null, submission);
                                                                    return true;
                                                                } catch (ApiException e) {
                                                                    e.printStackTrace();
                                                                    return false;
                                                                }
                                                            }

                                                            @Override
                                                            protected void onPostExecute(Boolean done) {
                                                                Snackbar s = null;
                                                                if (done) {
                                                                    if (holder.itemView != null) {
                                                                        s = Snackbar.make(holder.itemView, R.string.snackbar_flair_success, Snackbar.LENGTH_SHORT);
                                                                        SubmissionCache.updateTitleFlair(submission, t.getCssClass(), mContext);
                                                                        holder.title.setText(SubmissionCache.getTitleLine(submission, mContext));
                                                                    }
                                                                } else {
                                                                    if (holder.itemView != null) {
                                                                        s = Snackbar.make(holder.itemView, R.string.snackbar_flair_error, Snackbar.LENGTH_SHORT);
                                                                    }
                                                                }
                                                                if (s != null) {
                                                                    View view = s.getView();
                                                                    TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                                    tv.setTextColor(Color.WHITE);
                                                                    s.show();
                                                                }
                                                            }
                                                        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                                    }
                                                }
                                            }).show();
                                        }
                                        break;
                                    case 4:
                                        if (submission.isNsfw()) {
                                            unNsfwSubmission(mContext, submission, holder);
                                        } else {
                                            setPostNsfw(mContext, submission, holder);
                                        }
                                        break;
                                }
                            }
                        }).show();
                    }
                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        });
    } else {
        edit.setVisibility(View.GONE);
    }
    if (HasSeen.getSeen(submission) && !full) {
        holder.title.setAlpha(0.54f);
        holder.body.setAlpha(0.54f);
    } else {
        holder.title.setAlpha(1f);
        if (!full) {
            holder.body.setAlpha(1f);
        }
    }
}
Also used : FluentRedditClient(net.dean.jraw.fluent.FluentRedditClient) ContentType(me.ccrama.redditslide.ContentType) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) FlairReference(net.dean.jraw.fluent.FlairReference) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) Dialog(android.app.Dialog) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) TypedArray(android.content.res.TypedArray) TextView(android.widget.TextView) ArrayList(java.util.ArrayList) List(java.util.List) ImageView(android.widget.ImageView) EditText(android.widget.EditText) Vote(me.ccrama.redditslide.Vote) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Typeface(android.graphics.Typeface) FlairTemplate(net.dean.jraw.models.FlairTemplate) AsyncTask(android.os.AsyncTask) Drawable(android.graphics.drawable.Drawable) DialogAction(com.afollestad.materialdialogs.DialogAction) LayoutInflater(android.view.LayoutInflater) AccountManager(net.dean.jraw.managers.AccountManager) BottomSheet(com.cocosw.bottomsheet.BottomSheet) Snackbar(android.support.design.widget.Snackbar) DialogInterface(android.content.DialogInterface) OnSingleClickListener(me.ccrama.redditslide.util.OnSingleClickListener) MainActivity(me.ccrama.redditslide.Activities.MainActivity) ModerationManager(net.dean.jraw.managers.ModerationManager) AppCompatActivity(android.support.v7.app.AppCompatActivity) MediaView(me.ccrama.redditslide.Activities.MediaView) ImageView(android.widget.ImageView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) RecyclerView(android.support.v7.widget.RecyclerView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) View(android.view.View) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) InvalidScopeException(net.dean.jraw.http.oauth.InvalidScopeException) ApiException(net.dean.jraw.ApiException) FontPreferences(me.ccrama.redditslide.Visuals.FontPreferences) ApiException(net.dean.jraw.ApiException)

Example 15 with AccountManager

use of net.dean.jraw.managers.AccountManager in project Slide by ccrama.

the class PopulateSubmissionViewHolder method showBottomSheet.

public <T extends Contribution> void showBottomSheet(final Activity mContext, final Submission submission, final SubmissionViewHolder holder, final List<T> posts, final String baseSub, final RecyclerView recyclerview, final boolean full) {
    int[] attrs = new int[] { R.attr.tintColor };
    TypedArray ta = mContext.obtainStyledAttributes(attrs);
    int color = ta.getColor(0, Color.WHITE);
    Drawable profile = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.profile, null);
    final Drawable sub = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.sub, null);
    Drawable saved = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.iconstarfilled, null);
    Drawable hide = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.hide, null);
    final Drawable report = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.report, null);
    Drawable copy = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.ic_content_copy, null);
    final Drawable readLater = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.save, null);
    Drawable open = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.openexternal, null);
    Drawable link = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.link, null);
    Drawable reddit = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.commentchange, null);
    Drawable filter = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.filter, null);
    Drawable crosspost = ResourcesCompat.getDrawable(mContext.getResources(), R.drawable.forward, null);
    profile.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    sub.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    saved.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    hide.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    report.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    copy.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    open.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    link.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    reddit.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    readLater.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    filter.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    crosspost.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    ta.recycle();
    final BottomSheet.Builder b = new BottomSheet.Builder(mContext).title(Html.fromHtml(submission.getTitle()));
    final boolean isReadLater = mContext instanceof PostReadLater;
    final boolean isAddedToReadLaterList = ReadLater.isToBeReadLater(submission);
    if (Authentication.didOnline) {
        b.sheet(1, profile, "/u/" + submission.getAuthor()).sheet(2, sub, "/r/" + submission.getSubredditName());
        String save = mContext.getString(R.string.btn_save);
        if (ActionStates.isSaved(submission)) {
            save = mContext.getString(R.string.comment_unsave);
        }
        if (Authentication.isLoggedIn) {
            b.sheet(3, saved, save);
        }
    }
    if (isAddedToReadLaterList) {
        b.sheet(28, readLater, "Mark As Read");
    } else {
        b.sheet(28, readLater, "Read later");
    }
    if (Authentication.didOnline) {
        if (Authentication.isLoggedIn) {
            b.sheet(12, report, mContext.getString(R.string.btn_report));
            b.sheet(13, crosspost, mContext.getString(R.string.btn_crosspost));
        }
    }
    if (submission.getSelftext() != null && !submission.getSelftext().isEmpty() && full) {
        b.sheet(25, copy, mContext.getString(R.string.submission_copy_text));
    }
    boolean hidden = submission.isHidden();
    if (!full && Authentication.didOnline) {
        if (!hidden) {
            b.sheet(5, hide, mContext.getString(R.string.submission_hide));
        } else {
            b.sheet(5, hide, mContext.getString(R.string.submission_unhide));
        }
    }
    b.sheet(7, open, mContext.getString(R.string.submission_link_extern));
    b.sheet(4, link, mContext.getString(R.string.submission_share_permalink)).sheet(8, reddit, mContext.getString(R.string.submission_share_reddit_url));
    if ((mContext instanceof MainActivity) || (mContext instanceof SubredditView)) {
        b.sheet(10, filter, mContext.getString(R.string.filter_content));
    }
    b.listener(new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch(which) {
                case 1:
                    {
                        Intent i = new Intent(mContext, Profile.class);
                        i.putExtra(Profile.EXTRA_PROFILE, submission.getAuthor());
                        mContext.startActivity(i);
                    }
                    break;
                case 2:
                    {
                        Intent i = new Intent(mContext, SubredditView.class);
                        i.putExtra(SubredditView.EXTRA_SUBREDDIT, submission.getSubredditName());
                        mContext.startActivityForResult(i, 14);
                    }
                    break;
                case 10:
                    String[] choices;
                    final String flair = submission.getSubmissionFlair().getText() != null ? submission.getSubmissionFlair().getText() : "";
                    if (flair.isEmpty()) {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()) };
                        chosen = new boolean[] { Arrays.asList(SettingValues.subredditFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.userFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.domainFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.alwaysExternal.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getDomain().toLowerCase(Locale.ENGLISH)) };
                        oldChosen = chosen.clone();
                    } else {
                        choices = new String[] { mContext.getString(R.string.filter_posts_sub, submission.getSubredditName()), mContext.getString(R.string.filter_posts_user, submission.getAuthor()), mContext.getString(R.string.filter_posts_urls, submission.getDomain()), mContext.getString(R.string.filter_open_externally, submission.getDomain()), mContext.getString(R.string.filter_posts_flair, flair, baseSub) };
                    }
                    chosen = new boolean[] { Arrays.asList(SettingValues.subredditFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getSubredditName().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.userFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getAuthor().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.domainFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.alwaysExternal.toLowerCase(Locale.ENGLISH).split(",")).contains(submission.getDomain().toLowerCase(Locale.ENGLISH)), Arrays.asList(SettingValues.flairFilters.toLowerCase(Locale.ENGLISH).split(",")).contains(baseSub + ":" + flair) };
                    oldChosen = chosen.clone();
                    new AlertDialogWrapper.Builder(mContext).setTitle(R.string.filter_title).alwaysCallMultiChoiceCallback().setMultiChoiceItems(choices, chosen, new DialogInterface.OnMultiChoiceClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            chosen[which] = isChecked;
                        }
                    }).setPositiveButton(R.string.filter_btn, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            boolean filtered = false;
                            SharedPreferences.Editor e = SettingValues.prefs.edit();
                            if (chosen[0] && chosen[0] != oldChosen[0]) {
                                SettingValues.subredditFilters = SettingValues.subredditFilters + ((SettingValues.subredditFilters.isEmpty() || SettingValues.subredditFilters.endsWith(",")) ? "" : ",") + submission.getSubredditName();
                                filtered = true;
                                e.putString(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                                PostMatch.subreddits = null;
                            } else if (!chosen[0] && chosen[0] != oldChosen[0]) {
                                SettingValues.subredditFilters = SettingValues.subredditFilters.replace(submission.getSubredditName(), "");
                                filtered = false;
                                e.putString(SettingValues.PREF_SUBREDDIT_FILTERS, SettingValues.subredditFilters);
                                e.apply();
                                PostMatch.subreddits = null;
                            }
                            if (chosen[1] && chosen[1] != oldChosen[1]) {
                                SettingValues.userFilters = SettingValues.userFilters + ((SettingValues.userFilters.isEmpty() || SettingValues.userFilters.endsWith(",")) ? "" : ",") + submission.getAuthor();
                                filtered = true;
                                e.putString(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                                PostMatch.users = null;
                            } else if (!chosen[1] && chosen[1] != oldChosen[1]) {
                                SettingValues.userFilters = SettingValues.userFilters.replace(submission.getAuthor(), "");
                                filtered = false;
                                e.putString(SettingValues.PREF_USER_FILTERS, SettingValues.userFilters);
                                e.apply();
                                PostMatch.users = null;
                            }
                            if (chosen[2] && chosen[2] != oldChosen[2]) {
                                SettingValues.domainFilters = SettingValues.domainFilters + ((SettingValues.domainFilters.isEmpty() || SettingValues.domainFilters.endsWith(",")) ? "" : ",") + submission.getDomain();
                                filtered = true;
                                e.putString(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                                PostMatch.domains = null;
                            } else if (!chosen[2] && chosen[2] != oldChosen[2]) {
                                SettingValues.domainFilters = SettingValues.domainFilters.replace(submission.getDomain(), "");
                                filtered = false;
                                e.putString(SettingValues.PREF_DOMAIN_FILTERS, SettingValues.domainFilters);
                                e.apply();
                                PostMatch.domains = null;
                            }
                            if (chosen[3] && chosen[3] != oldChosen[3]) {
                                SettingValues.alwaysExternal = SettingValues.alwaysExternal + ((SettingValues.alwaysExternal.isEmpty() || SettingValues.alwaysExternal.endsWith(",")) ? "" : ",") + submission.getDomain();
                                e.putString(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                                e.apply();
                            } else if (!chosen[3] && chosen[3] != oldChosen[3]) {
                                SettingValues.alwaysExternal = SettingValues.alwaysExternal.replace(submission.getDomain(), "");
                                e.putString(SettingValues.PREF_ALWAYS_EXTERNAL, SettingValues.alwaysExternal);
                                e.apply();
                            }
                            if (chosen.length > 4) {
                                if (chosen[4] && chosen[4] != oldChosen[4]) {
                                    SettingValues.flairFilters = SettingValues.flairFilters + ((SettingValues.flairFilters.isEmpty() || SettingValues.flairFilters.endsWith(",")) ? "" : ",") + (baseSub + ":" + flair);
                                    e.putString(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                    e.apply();
                                    PostMatch.flairs = null;
                                    filtered = true;
                                } else if (!chosen[4] && chosen[4] != oldChosen[4]) {
                                    SettingValues.flairFilters = SettingValues.flairFilters.toLowerCase(Locale.ENGLISH).replace((baseSub + ":" + flair).toLowerCase(Locale.ENGLISH), "");
                                    e.putString(SettingValues.PREF_FLAIR_FILTERS, SettingValues.flairFilters);
                                    e.apply();
                                    PostMatch.flairs = null;
                                }
                            }
                            if (filtered) {
                                e.apply();
                                PostMatch.domains = null;
                                PostMatch.subreddits = null;
                                PostMatch.users = null;
                                ArrayList<Contribution> toRemove = new ArrayList<>();
                                for (Contribution s : posts) {
                                    if (s instanceof Submission && PostMatch.doesMatch((Submission) s)) {
                                        toRemove.add(s);
                                    }
                                }
                                OfflineSubreddit s = OfflineSubreddit.getSubreddit(baseSub, false, mContext);
                                for (Contribution remove : toRemove) {
                                    final int pos = posts.indexOf(remove);
                                    posts.remove(pos);
                                    if (baseSub != null) {
                                        s.hideMulti(pos);
                                    }
                                }
                                s.writeToMemoryNoStorage();
                                recyclerview.getAdapter().notifyDataSetChanged();
                            }
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                    break;
                case 3:
                    saveSubmission(submission, mContext, holder, full);
                    break;
                case 5:
                    {
                        hideSubmission(submission, posts, baseSub, recyclerview, mContext);
                    }
                    break;
                case 7:
                    LinkUtil.openExternally(submission.getUrl(), mContext);
                    if (submission.isNsfw() && !SettingValues.storeNSFWHistory) {
                    // Do nothing if the post is NSFW and storeNSFWHistory is not enabled
                    } else if (SettingValues.storeHistory) {
                        HasSeen.addSeen(submission.getFullName());
                    }
                    break;
                case 13:
                    LinkUtil.crosspost(submission, mContext);
                    break;
                case 28:
                    if (!isAddedToReadLaterList) {
                        ReadLater.setReadLater(submission, true);
                        Snackbar s = Snackbar.make(holder.itemView, "Added to read later!", Snackbar.LENGTH_SHORT);
                        View view = s.getView();
                        TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                        tv.setTextColor(Color.WHITE);
                        s.setAction(R.string.btn_undo, new View.OnClickListener() {

                            @Override
                            public void onClick(View view) {
                                ReadLater.setReadLater(submission, false);
                                Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                                View view2 = s2.getView();
                                TextView tv2 = view2.findViewById(android.support.design.R.id.snackbar_text);
                                tv2.setTextColor(Color.WHITE);
                                s2.show();
                            }
                        });
                        if (NetworkUtil.isConnected(mContext)) {
                            new CommentCacheAsync(Arrays.asList(submission), mContext, CommentCacheAsync.SAVED_SUBMISSIONS, new boolean[] { true, true }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                        s.show();
                    } else {
                        ReadLater.setReadLater(submission, false);
                        if (isReadLater || !Authentication.didOnline) {
                            final int pos = posts.indexOf(submission);
                            posts.remove(submission);
                            recyclerview.getAdapter().notifyItemRemoved(holder.getAdapterPosition());
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = view2.findViewById(android.support.design.R.id.snackbar_text);
                            tv2.setTextColor(Color.WHITE);
                            s2.setAction(R.string.btn_undo, new View.OnClickListener() {

                                @Override
                                public void onClick(View view) {
                                    posts.add(pos, (T) submission);
                                    recyclerview.getAdapter().notifyDataSetChanged();
                                }
                            });
                        } else {
                            Snackbar s2 = Snackbar.make(holder.itemView, "Removed from read later", Snackbar.LENGTH_SHORT);
                            View view2 = s2.getView();
                            TextView tv2 = view2.findViewById(android.support.design.R.id.snackbar_text);
                            s2.show();
                        }
                        OfflineSubreddit.newSubreddit(CommentCacheAsync.SAVED_SUBMISSIONS).deleteFromMemory(submission.getFullName());
                    }
                    break;
                case 4:
                    Reddit.defaultShareText(Html.fromHtml(submission.getTitle()).toString(), StringEscapeUtils.escapeHtml4(submission.getUrl()), mContext);
                    break;
                case 12:
                    reportReason = "";
                    new MaterialDialog.Builder(mContext).input(mContext.getString(R.string.input_reason_for_report), null, true, new MaterialDialog.InputCallback() {

                        @Override
                        public void onInput(MaterialDialog dialog, CharSequence input) {
                            reportReason = input.toString();
                        }
                    }).title(R.string.report_post).alwaysCallInputCallback().inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE | InputType.TYPE_TEXT_FLAG_AUTO_CORRECT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES).positiveText(R.string.btn_report).negativeText(R.string.btn_cancel).onNegative(null).onPositive(new MaterialDialog.SingleButtonCallback() {

                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            new AsyncTask<Void, Void, Void>() {

                                @Override
                                protected Void doInBackground(Void... params) {
                                    try {
                                        new AccountManager(Authentication.reddit).report(submission, reportReason);
                                    } catch (ApiException e) {
                                        e.printStackTrace();
                                    }
                                    return null;
                                }

                                @Override
                                protected void onPostExecute(Void aVoid) {
                                    if (holder.itemView != null) {
                                        try {
                                            Snackbar s = Snackbar.make(holder.itemView, R.string.msg_report_sent, Snackbar.LENGTH_SHORT);
                                            View view = s.getView();
                                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                            tv.setTextColor(Color.WHITE);
                                            s.show();
                                        } catch (Exception ignored) {
                                        }
                                    }
                                }
                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    }).show();
                    break;
                case 8:
                    if (SettingValues.shareLongLink) {
                        Reddit.defaultShareText(submission.getTitle(), "htts://reddit.com" + submission.getPermalink(), mContext);
                    } else {
                        Reddit.defaultShareText(submission.getTitle(), "https://redd.it/" + submission.getId(), mContext);
                    }
                    break;
                case 6:
                    {
                        ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("Link", submission.getUrl());
                        clipboard.setPrimaryClip(clip);
                        Toast.makeText(mContext, R.string.submission_link_copied, Toast.LENGTH_SHORT).show();
                    }
                    break;
                case 25:
                    final TextView showText = new TextView(mContext);
                    showText.setText(StringEscapeUtils.unescapeHtml4(submission.getTitle() + "\n\n" + submission.getSelftext()));
                    showText.setTextIsSelectable(true);
                    int sixteen = Reddit.dpToPxVertical(24);
                    showText.setPadding(sixteen, 0, sixteen, 0);
                    AlertDialogWrapper.Builder builder = new AlertDialogWrapper.Builder(mContext);
                    builder.setView(showText).setTitle("Select text to copy").setCancelable(true).setPositiveButton("COPY SELECTED", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String selected = showText.getText().toString().substring(showText.getSelectionStart(), showText.getSelectionEnd());
                            if (!selected.isEmpty()) {
                                ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                                ClipData clip = ClipData.newPlainText("Selftext", selected);
                                clipboard.setPrimaryClip(clip);
                                Toast.makeText(mContext, R.string.submission_comment_copied, Toast.LENGTH_SHORT).show();
                            } else {
                                ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                                ClipData clip = ClipData.newPlainText("Selftext", Html.fromHtml(submission.getTitle() + "\n\n" + submission.getSelftext()));
                                clipboard.setPrimaryClip(clip);
                                Toast.makeText(mContext, R.string.submission_comment_copied, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).setNeutralButton("COPY ALL", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
                            ClipData clip = ClipData.newPlainText("Selftext", Html.fromHtml(submission.getTitle() + "\n\n" + submission.getSelftext()));
                            clipboard.setPrimaryClip(clip);
                            Toast.makeText(mContext, R.string.submission_comment_copied, Toast.LENGTH_SHORT).show();
                        }
                    }).show();
                    break;
            }
        }
    });
    b.show();
}
Also used : DialogInterface(android.content.DialogInterface) SpannableStringBuilder(android.text.SpannableStringBuilder) ArrayList(java.util.ArrayList) PostReadLater(me.ccrama.redditslide.Activities.PostReadLater) SubredditView(me.ccrama.redditslide.Activities.SubredditView) MainActivity(me.ccrama.redditslide.Activities.MainActivity) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) TypedArray(android.content.res.TypedArray) TextView(android.widget.TextView) ClipboardManager(android.content.ClipboardManager) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) Submission(net.dean.jraw.models.Submission) CommentCacheAsync(me.ccrama.redditslide.CommentCacheAsync) SharedPreferences(android.content.SharedPreferences) Drawable(android.graphics.drawable.Drawable) OfflineSubreddit(me.ccrama.redditslide.OfflineSubreddit) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) MediaView(me.ccrama.redditslide.Activities.MediaView) ImageView(android.widget.ImageView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) RecyclerView(android.support.v7.widget.RecyclerView) CreateCardView(me.ccrama.redditslide.Views.CreateCardView) View(android.view.View) TextView(android.widget.TextView) SubredditView(me.ccrama.redditslide.Activities.SubredditView) InvalidScopeException(net.dean.jraw.http.oauth.InvalidScopeException) ApiException(net.dean.jraw.ApiException) DialogAction(com.afollestad.materialdialogs.DialogAction) AccountManager(net.dean.jraw.managers.AccountManager) BottomSheet(com.cocosw.bottomsheet.BottomSheet) ClipData(android.content.ClipData) Contribution(net.dean.jraw.models.Contribution) Snackbar(android.support.design.widget.Snackbar) ApiException(net.dean.jraw.ApiException)

Aggregations

AccountManager (net.dean.jraw.managers.AccountManager)16 View (android.view.View)14 TextView (android.widget.TextView)14 ApiException (net.dean.jraw.ApiException)14 AsyncTask (android.os.AsyncTask)13 ImageView (android.widget.ImageView)12 ArrayList (java.util.ArrayList)12 Snackbar (android.support.design.widget.Snackbar)11 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)11 DialogInterface (android.content.DialogInterface)9 DialogAction (com.afollestad.materialdialogs.DialogAction)9 Intent (android.content.Intent)8 SpannableStringBuilder (android.text.SpannableStringBuilder)8 AlertDialogWrapper (com.afollestad.materialdialogs.AlertDialogWrapper)8 SubmissionsView (me.ccrama.redditslide.Fragments.SubmissionsView)8 SubredditView (me.ccrama.redditslide.Activities.SubredditView)7 Dialog (android.app.Dialog)6 ActivityNotFoundException (android.content.ActivityNotFoundException)5 List (java.util.List)5 NetworkException (net.dean.jraw.http.NetworkException)5