Search in sources :

Example 1 with NetworkException

use of net.dean.jraw.http.NetworkException in project Slide by ccrama.

the class MainActivity method doSubOnlyStuff.

public void doSubOnlyStuff(final Subreddit subreddit) {
    findViewById(R.id.loader).setVisibility(View.GONE);
    if (subreddit.getSubredditType() != null) {
        canSubmit = !subreddit.getSubredditType().equals("RESTRICTED");
    } else {
        canSubmit = true;
    }
    if (subreddit.getSidebar() != null && !subreddit.getSidebar().isEmpty()) {
        findViewById(R.id.sidebar_text).setVisibility(View.VISIBLE);
        final String text = subreddit.getDataNode().get("description_html").asText().trim();
        setViews(text, subreddit.getDisplayName(), sidebarBody, sidebarOverflow);
        // get all subs that have Notifications enabled
        ArrayList<String> rawSubs = Reddit.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
        HashMap<String, Integer> subThresholds = new HashMap<>();
        for (String s : rawSubs) {
            try {
                String[] split = s.split(":");
                subThresholds.put(split[0].toLowerCase(Locale.ENGLISH), Integer.valueOf(split[1]));
            } catch (Exception ignored) {
            // do nothing
            }
        }
        // whether or not this subreddit was in the keySet
        boolean isNotified = subThresholds.keySet().contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH));
        ((AppCompatCheckBox) findViewById(R.id.notify_posts_state)).setChecked(isNotified);
    } else {
        findViewById(R.id.sidebar_text).setVisibility(View.GONE);
    }
    {
        View collection = findViewById(R.id.collection);
        if (Authentication.isLoggedIn) {
            collection.setOnClickListener(new View.OnClickListener() {

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

                        HashMap<String, MultiReddit> multis = new HashMap<String, MultiReddit>();

                        @Override
                        protected Void doInBackground(Void... params) {
                            if (UserSubscriptions.multireddits == null) {
                                UserSubscriptions.syncMultiReddits(MainActivity.this);
                            }
                            for (MultiReddit r : UserSubscriptions.multireddits) {
                                multis.put(r.getDisplayName(), r);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            new MaterialDialog.Builder(MainActivity.this).title(getString(R.string.multi_add_to, subreddit.getDisplayName())).items(multis.keySet()).itemsCallback(new MaterialDialog.ListCallback() {

                                @Override
                                public void onSelection(MaterialDialog dialog, View itemView, final int which, CharSequence text) {
                                    new AsyncTask<Void, Void, Void>() {

                                        @Override
                                        protected Void doInBackground(Void... params) {
                                            try {
                                                final String multiName = multis.keySet().toArray(new String[multis.size()])[which];
                                                List<String> subs = new ArrayList<String>();
                                                for (MultiSubreddit sub : multis.get(multiName).getSubreddits()) {
                                                    subs.add(sub.getDisplayName());
                                                }
                                                subs.add(subreddit.getDisplayName());
                                                new MultiRedditManager(Authentication.reddit).createOrUpdate(new MultiRedditUpdateRequest.Builder(Authentication.name, multiName).subreddits(subs).build());
                                                UserSubscriptions.syncMultiReddits(MainActivity.this);
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        drawerLayout.closeDrawers();
                                                        Snackbar s = Snackbar.make(mToolbar, getString(R.string.multi_subreddit_added, multiName), Snackbar.LENGTH_LONG);
                                                        View view = s.getView();
                                                        TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                        tv.setTextColor(Color.WHITE);
                                                        s.show();
                                                    }
                                                });
                                            } catch (final NetworkException | ApiException e) {
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        runOnUiThread(new Runnable() {

                                                            @Override
                                                            public void run() {
                                                                Snackbar.make(mToolbar, getString(R.string.multi_error), Snackbar.LENGTH_LONG).setAction(R.string.btn_ok, new View.OnClickListener() {

                                                                    @Override
                                                                    public void onClick(View v) {
                                                                    }
                                                                }).show();
                                                            }
                                                        });
                                                    }
                                                });
                                                e.printStackTrace();
                                            }
                                            return null;
                                        }
                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                }
                            }).show();
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });
        } else {
            collection.setVisibility(View.GONE);
        }
    }
    {
        final AppCompatCheckBox notifyStateCheckBox = (AppCompatCheckBox) findViewById(R.id.notify_posts_state);
        assert notifyStateCheckBox != null;
        notifyStateCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    final String sub = subreddit.getDisplayName();
                    if (!sub.equalsIgnoreCase("all") && !sub.equalsIgnoreCase("frontpage") && !sub.equalsIgnoreCase("friends") && !sub.equalsIgnoreCase("mod") && !sub.contains("+") && !sub.contains(".") && !sub.contains("/m/")) {
                        new AlertDialogWrapper.Builder(MainActivity.this).setTitle(getString(R.string.sub_post_notifs_title, sub)).setMessage(R.string.sub_post_notifs_msg).setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                new MaterialDialog.Builder(MainActivity.this).title(R.string.sub_post_notifs_threshold).items(new String[] { "1", "5", "10", "20", "40", "50" }).alwaysCallSingleChoiceCallback().itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {

                                    @Override
                                    public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                        ArrayList<String> subs = Reddit.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
                                        subs.add(sub + ":" + text);
                                        Reddit.appRestart.edit().putString(CheckForMail.SUBS_TO_GET, Reddit.arrayToString(subs)).commit();
                                        return true;
                                    }
                                }).cancelable(false).show();
                            }
                        }).setNegativeButton(R.string.btn_cancel, null).setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                notifyStateCheckBox.setChecked(false);
                            }
                        }).setOnCancelListener(new DialogInterface.OnCancelListener() {

                            @Override
                            public void onCancel(DialogInterface dialog) {
                                notifyStateCheckBox.setChecked(false);
                            }
                        }).show();
                    } else {
                        notifyStateCheckBox.setChecked(false);
                        Toast.makeText(MainActivity.this, R.string.sub_post_notifs_err, Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Intent cancelIntent = new Intent(MainActivity.this, CancelSubNotifs.class);
                    cancelIntent.putExtra(CancelSubNotifs.EXTRA_SUB, subreddit.getDisplayName());
                    startActivity(cancelIntent);
                }
            }
        });
    }
    {
        final TextView subscribe = (TextView) findViewById(R.id.subscribe);
        currentlySubbed = (!Authentication.isLoggedIn && usedArray.contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH))) || subreddit.isUserSubscriber();
        doSubscribeButtonText(currentlySubbed, subscribe);
        assert subscribe != null;
        subscribe.setOnClickListener(new View.OnClickListener() {

            private void doSubscribe() {
                if (Authentication.isLoggedIn) {
                    new AlertDialogWrapper.Builder(MainActivity.this).setTitle(getString(R.string.subscribe_to, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_add_subscribe, new DialogInterface.OnClickListener() {

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

                                @Override
                                public void onPostExecute(Boolean success) {
                                    if (!success) {
                                        // If subreddit was removed from account or not
                                        new AlertDialogWrapper.Builder(MainActivity.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                changeSubscription(subreddit, // Force add the subscription
                                                true);
                                                Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_subscribed), Snackbar.LENGTH_LONG);
                                                View view = s.getView();
                                                TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                tv.setTextColor(Color.WHITE);
                                                s.show();
                                            }
                                        }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }).setCancelable(false).show();
                                    } else {
                                        changeSubscription(subreddit, true);
                                    }
                                }

                                @Override
                                protected Boolean doInBackground(Void... params) {
                                    try {
                                        new AccountManager(Authentication.reddit).subscribe(subreddit);
                                    } catch (NetworkException e) {
                                        // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                        return false;
                                    }
                                    return true;
                                }
                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    }).setNeutralButton(R.string.btn_add_to_sublist, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            changeSubscription(subreddit, // Force add the subscription
                            true);
                            Snackbar s = Snackbar.make(mToolbar, R.string.sub_added, Snackbar.LENGTH_LONG);
                            View view = s.getView();
                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                            tv.setTextColor(Color.WHITE);
                            s.show();
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                } else {
                    changeSubscription(subreddit, true);
                }
            }

            private void doUnsubscribe() {
                if (Authentication.didOnline) {
                    new AlertDialogWrapper.Builder(MainActivity.this).setTitle(getString(R.string.unsubscribe_from, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_remove_unsubsribe, new DialogInterface.OnClickListener() {

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

                                @Override
                                public void onPostExecute(Boolean success) {
                                    if (!success) {
                                        // If subreddit was removed from account or not
                                        new AlertDialogWrapper.Builder(MainActivity.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                changeSubscription(subreddit, // Force add the subscription
                                                false);
                                                Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_unsubscribed), Snackbar.LENGTH_LONG);
                                                View view = s.getView();
                                                TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                                                tv.setTextColor(Color.WHITE);
                                                s.show();
                                            }
                                        }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        }).setCancelable(false).show();
                                    } else {
                                        changeSubscription(subreddit, false);
                                    }
                                }

                                @Override
                                protected Boolean doInBackground(Void... params) {
                                    try {
                                        new AccountManager(Authentication.reddit).unsubscribe(subreddit);
                                    } catch (NetworkException e) {
                                        // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                        return false;
                                    }
                                    return true;
                                }
                            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        }
                    }).setNeutralButton(R.string.just_unsub, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            changeSubscription(subreddit, // Force add the subscription
                            false);
                            Snackbar s = Snackbar.make(mToolbar, R.string.misc_unsubscribed, Snackbar.LENGTH_LONG);
                            View view = s.getView();
                            TextView tv = view.findViewById(android.support.design.R.id.snackbar_text);
                            tv.setTextColor(Color.WHITE);
                            s.show();
                        }
                    }).setNegativeButton(R.string.btn_cancel, null).show();
                } else {
                    changeSubscription(subreddit, false);
                }
            }

            @Override
            public void onClick(View v) {
                if (!currentlySubbed) {
                    doSubscribe();
                    doSubscribeButtonText(currentlySubbed, subscribe);
                } else {
                    doUnsubscribe();
                    doSubscribeButtonText(currentlySubbed, subscribe);
                }
            }
        });
    }
    if (!subreddit.getPublicDescription().isEmpty()) {
        findViewById(R.id.sub_title).setVisibility(View.VISIBLE);
        setViews(subreddit.getDataNode().get("public_description_html").asText(), subreddit.getDisplayName().toLowerCase(Locale.ENGLISH), ((SpoilerRobotoTextView) findViewById(R.id.sub_title)), (CommentOverflow) findViewById(R.id.sub_title_overflow));
    } else {
        findViewById(R.id.sub_title).setVisibility(View.GONE);
    }
    ((ImageView) findViewById(R.id.subimage)).setImageResource(0);
    if (subreddit.getDataNode().has("icon_img") && !subreddit.getDataNode().get("icon_img").asText().isEmpty()) {
        findViewById(R.id.subimage).setVisibility(View.VISIBLE);
        ((Reddit) getApplication()).getImageLoader().displayImage(subreddit.getDataNode().get("icon_img").asText(), (ImageView) findViewById(R.id.subimage));
    } else {
        findViewById(R.id.subimage).setVisibility(View.GONE);
    }
    ((TextView) findViewById(R.id.subscribers)).setText(getString(R.string.subreddit_subscribers_string, subreddit.getLocalizedSubscriberCount()));
    findViewById(R.id.subscribers).setVisibility(View.VISIBLE);
    ((TextView) findViewById(R.id.active_users)).setText(getString(R.string.subreddit_active_users_string_new, subreddit.getLocalizedAccountsActive()));
    findViewById(R.id.active_users).setVisibility(View.VISIBLE);
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CaseInsensitiveArrayList(me.ccrama.redditslide.CaseInsensitiveArrayList) MultiReddit(net.dean.jraw.models.MultiReddit) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) MultiRedditUpdateRequest(net.dean.jraw.http.MultiRedditUpdateRequest) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) ImageView(android.widget.ImageView) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) AccountManager(net.dean.jraw.managers.AccountManager) Snackbar(android.support.design.widget.Snackbar) DialogInterface(android.content.DialogInterface) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) NetworkException(net.dean.jraw.http.NetworkException) Intent(android.content.Intent) ImageView(android.widget.ImageView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) AutoCompleteTextView(android.widget.AutoCompleteTextView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) View(android.view.View) CardView(android.support.v7.widget.CardView) TextView(android.widget.TextView) ListView(android.widget.ListView) ApiException(net.dean.jraw.ApiException) ActivityNotFoundException(android.content.ActivityNotFoundException) NetworkException(net.dean.jraw.http.NetworkException) Point(android.graphics.Point) AppCompatCheckBox(android.support.v7.widget.AppCompatCheckBox) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) CompoundButton(android.widget.CompoundButton) ApiException(net.dean.jraw.ApiException)

Example 2 with NetworkException

use of net.dean.jraw.http.NetworkException in project Slide by ccrama.

the class SubredditView method doSubOnlyStuff.

private void doSubOnlyStuff(final Subreddit subreddit) {
    if (!isFinishing()) {
        findViewById(R.id.loader).setVisibility(View.GONE);
        if (subreddit.getDataNode().has("subreddit_type") && !subreddit.getDataNode().get("subreddit_type").isNull()) {
            canSubmit = !subreddit.getDataNode().get("subreddit_type").asText().toUpperCase().equals("RESTRICTED");
        }
        if (subreddit.getSidebar() != null && !subreddit.getSidebar().isEmpty()) {
            findViewById(R.id.sidebar_text).setVisibility(View.VISIBLE);
            final String text = subreddit.getDataNode().get("description_html").asText().trim();
            final SpoilerRobotoTextView body = (SpoilerRobotoTextView) findViewById(R.id.sidebar_text);
            CommentOverflow overflow = (CommentOverflow) findViewById(R.id.commentOverflow);
            setViews(text, subreddit.getDisplayName(), body, overflow);
            // get all subs that have Notifications enabled
            ArrayList<String> rawSubs = Reddit.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
            HashMap<String, Integer> subThresholds = new HashMap<>();
            for (String s : rawSubs) {
                try {
                    String[] split = s.split(":");
                    subThresholds.put(split[0].toLowerCase(Locale.ENGLISH), Integer.valueOf(split[1]));
                } catch (Exception ignored) {
                // do nothing
                }
            }
            // whether or not this subreddit was in the keySet
            boolean isNotified = subThresholds.keySet().contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH));
            ((AppCompatCheckBox) findViewById(R.id.notify_posts_state)).setChecked(isNotified);
        } else {
            findViewById(R.id.sidebar_text).setVisibility(View.GONE);
        }
        View collection = findViewById(R.id.collection);
        if (Authentication.isLoggedIn) {
            collection.setOnClickListener(new View.OnClickListener() {

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

                        HashMap<String, MultiReddit> multis = new HashMap<String, MultiReddit>();

                        @Override
                        protected Void doInBackground(Void... params) {
                            if (UserSubscriptions.multireddits == null) {
                                UserSubscriptions.syncMultiReddits(SubredditView.this);
                            }
                            for (MultiReddit r : UserSubscriptions.multireddits) {
                                multis.put(r.getDisplayName(), r);
                            }
                            return null;
                        }

                        @Override
                        protected void onPostExecute(Void aVoid) {
                            new MaterialDialog.Builder(SubredditView.this).title("Add /r/" + subreddit.getDisplayName() + " to").items(multis.keySet()).itemsCallback(new MaterialDialog.ListCallback() {

                                @Override
                                public void onSelection(MaterialDialog dialog, View itemView, final int which, CharSequence text) {
                                    new AsyncTask<Void, Void, Void>() {

                                        @Override
                                        protected Void doInBackground(Void... params) {
                                            try {
                                                final String multiName = multis.keySet().toArray(new String[multis.size()])[which];
                                                List<String> subs = new ArrayList<String>();
                                                for (MultiSubreddit sub : multis.get(multiName).getSubreddits()) {
                                                    subs.add(sub.getDisplayName());
                                                }
                                                subs.add(subreddit.getDisplayName());
                                                new MultiRedditManager(Authentication.reddit).createOrUpdate(new MultiRedditUpdateRequest.Builder(Authentication.name, multiName).subreddits(subs).build());
                                                UserSubscriptions.syncMultiReddits(SubredditView.this);
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        drawerLayout.closeDrawers();
                                                        Snackbar s = Snackbar.make(mToolbar, getString(R.string.multi_subreddit_added, multiName), Snackbar.LENGTH_LONG);
                                                        View view = s.getView();
                                                        TextView tv = (TextView) view.findViewById(android.support.design.R.id.snackbar_text);
                                                        tv.setTextColor(Color.WHITE);
                                                        s.show();
                                                    }
                                                });
                                            } catch (final NetworkException | ApiException e) {
                                                runOnUiThread(new Runnable() {

                                                    @Override
                                                    public void run() {
                                                        runOnUiThread(new Runnable() {

                                                            @Override
                                                            public void run() {
                                                                Snackbar.make(mToolbar, getString(R.string.multi_error), Snackbar.LENGTH_LONG).setAction(R.string.btn_ok, new View.OnClickListener() {

                                                                    @Override
                                                                    public void onClick(View v) {
                                                                    }
                                                                }).show();
                                                            }
                                                        });
                                                    }
                                                });
                                                e.printStackTrace();
                                            }
                                            return null;
                                        }
                                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                }
                            }).show();
                        }
                    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }
            });
        } else {
            collection.setVisibility(View.GONE);
        }
        {
            final TextView subscribe = (TextView) findViewById(R.id.subscribe);
            currentlySubbed = (!Authentication.isLoggedIn && UserSubscriptions.getSubscriptions(this).contains(subreddit.getDisplayName().toLowerCase(Locale.ENGLISH))) || (Authentication.isLoggedIn && subreddit.isUserSubscriber());
            doSubscribeButtonText(currentlySubbed, subscribe);
            assert subscribe != null;
            subscribe.setOnClickListener(new View.OnClickListener() {

                private void doSubscribe() {
                    if (Authentication.isLoggedIn) {
                        new AlertDialogWrapper.Builder(SubredditView.this).setTitle(getString(R.string.subscribe_to, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_add_subscribe, new DialogInterface.OnClickListener() {

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

                                    @Override
                                    public void onPostExecute(Boolean success) {
                                        if (!success) {
                                            // If subreddit was removed from account or not
                                            new AlertDialogWrapper.Builder(SubredditView.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    changeSubscription(subreddit, // Force add the subscription
                                                    true);
                                                    Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_subscribed), 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();
                                                }
                                            }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                }
                                            }).setCancelable(false).show();
                                        } else {
                                            changeSubscription(subreddit, true);
                                        }
                                    }

                                    @Override
                                    protected Boolean doInBackground(Void... params) {
                                        try {
                                            new AccountManager(Authentication.reddit).subscribe(subreddit);
                                        } catch (NetworkException e) {
                                            // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                            return false;
                                        }
                                        return true;
                                    }
                                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                            }
                        }).setNegativeButton(R.string.btn_cancel, null).setNeutralButton(R.string.btn_add_to_sublist, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                changeSubscription(subreddit, // Force add the subscription
                                true);
                                Snackbar s = Snackbar.make(mToolbar, R.string.sub_added, 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();
                            }
                        }).show();
                    } else {
                        changeSubscription(subreddit, true);
                    }
                }

                @Override
                public void onClick(View v) {
                    if (!currentlySubbed) {
                        doSubscribe();
                        doSubscribeButtonText(currentlySubbed, subscribe);
                    } else {
                        doUnsubscribe();
                        doSubscribeButtonText(currentlySubbed, subscribe);
                    }
                }

                private void doUnsubscribe() {
                    if (Authentication.didOnline) {
                        new AlertDialogWrapper.Builder(SubredditView.this).setTitle(getString(R.string.unsubscribe_from, subreddit.getDisplayName())).setPositiveButton(R.string.reorder_remove_unsubsribe, new DialogInterface.OnClickListener() {

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

                                    @Override
                                    public void onPostExecute(Boolean success) {
                                        if (!success) {
                                            // If subreddit was removed from account or not
                                            new AlertDialogWrapper.Builder(SubredditView.this).setTitle(R.string.force_change_subscription).setMessage(R.string.force_change_subscription_desc).setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    changeSubscription(subreddit, // Force add the subscription
                                                    false);
                                                    Snackbar s = Snackbar.make(mToolbar, getString(R.string.misc_unsubscribed), 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();
                                                }
                                            }).setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                }
                                            }).setCancelable(false).show();
                                        } else {
                                            changeSubscription(subreddit, false);
                                        }
                                    }

                                    @Override
                                    protected Boolean doInBackground(Void... params) {
                                        try {
                                            new AccountManager(Authentication.reddit).unsubscribe(subreddit);
                                        } catch (NetworkException e) {
                                            // Either network crashed or trying to unsubscribe to a subreddit that the account isn't subscribed to
                                            return false;
                                        }
                                        return true;
                                    }
                                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                            }
                        }).setNeutralButton(R.string.just_unsub, new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                changeSubscription(subreddit, // Force add the subscription
                                false);
                                Snackbar s = Snackbar.make(mToolbar, R.string.misc_unsubscribed, 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();
                            }
                        }).setNegativeButton(R.string.btn_cancel, null).show();
                    } else {
                        changeSubscription(subreddit, false);
                    }
                }
            });
        }
        {
            final AppCompatCheckBox notifyStateCheckBox = (AppCompatCheckBox) findViewById(R.id.notify_posts_state);
            assert notifyStateCheckBox != null;
            notifyStateCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        final String sub = subreddit.getDisplayName();
                        if (!sub.equalsIgnoreCase("all") && !sub.equalsIgnoreCase("frontpage") && !sub.equalsIgnoreCase("friends") && !sub.equalsIgnoreCase("mod") && !sub.contains("+") && !sub.contains(".") && !sub.contains("/m/")) {
                            new AlertDialogWrapper.Builder(SubredditView.this).setTitle(getString(R.string.sub_post_notifs_title, sub)).setMessage(R.string.sub_post_notifs_msg).setPositiveButton(R.string.btn_ok, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    new MaterialDialog.Builder(SubredditView.this).title(R.string.sub_post_notifs_threshold).items(new String[] { "1", "5", "10", "20", "40", "50" }).alwaysCallSingleChoiceCallback().itemsCallbackSingleChoice(0, new MaterialDialog.ListCallbackSingleChoice() {

                                        @Override
                                        public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
                                            ArrayList<String> subs = Reddit.stringToArray(Reddit.appRestart.getString(CheckForMail.SUBS_TO_GET, ""));
                                            subs.add(sub + ":" + text);
                                            Reddit.appRestart.edit().putString(CheckForMail.SUBS_TO_GET, Reddit.arrayToString(subs)).commit();
                                            return true;
                                        }
                                    }).cancelable(false).show();
                                }
                            }).setNegativeButton(R.string.btn_cancel, null).setNegativeButton(R.string.btn_cancel, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    notifyStateCheckBox.setChecked(false);
                                }
                            }).setOnCancelListener(new DialogInterface.OnCancelListener() {

                                @Override
                                public void onCancel(DialogInterface dialog) {
                                    notifyStateCheckBox.setChecked(false);
                                }
                            }).show();
                        } else {
                            notifyStateCheckBox.setChecked(false);
                            Toast.makeText(SubredditView.this, R.string.sub_post_notifs_err, Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Intent cancelIntent = new Intent(SubredditView.this, CancelSubNotifs.class);
                        cancelIntent.putExtra(CancelSubNotifs.EXTRA_SUB, subreddit.getDisplayName());
                        startActivity(cancelIntent);
                    }
                }
            });
        }
        if (!subreddit.getPublicDescription().isEmpty()) {
            findViewById(R.id.sub_title).setVisibility(View.VISIBLE);
            setViews(subreddit.getDataNode().get("public_description_html").asText(), subreddit.getDisplayName().toLowerCase(Locale.ENGLISH), ((SpoilerRobotoTextView) findViewById(R.id.sub_title)), (CommentOverflow) findViewById(R.id.sub_title_overflow));
        } else {
            findViewById(R.id.sub_title).setVisibility(View.GONE);
        }
        if (subreddit.getDataNode().has("icon_img") && !subreddit.getDataNode().get("icon_img").asText().isEmpty()) {
            ((Reddit) getApplication()).getImageLoader().displayImage(subreddit.getDataNode().get("icon_img").asText(), (ImageView) findViewById(R.id.subimage));
        } else {
            findViewById(R.id.subimage).setVisibility(View.GONE);
        }
        ((TextView) findViewById(R.id.subscribers)).setText(getString(R.string.subreddit_subscribers_string, subreddit.getLocalizedSubscriberCount()));
        findViewById(R.id.subscribers).setVisibility(View.VISIBLE);
        ((TextView) findViewById(R.id.active_users)).setText(getString(R.string.subreddit_active_users_string_new, subreddit.getLocalizedAccountsActive()));
        findViewById(R.id.active_users).setVisibility(View.VISIBLE);
    }
}
Also used : HashMap(java.util.HashMap) DialogInterface(android.content.DialogInterface) MultiSubreddit(net.dean.jraw.models.MultiSubreddit) MultiReddit(net.dean.jraw.models.MultiReddit) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) CommentOverflow(me.ccrama.redditslide.Views.CommentOverflow) List(java.util.List) ArrayList(java.util.ArrayList) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) TextView(android.widget.TextView) NetworkException(net.dean.jraw.http.NetworkException) MaterialDialog(com.afollestad.materialdialogs.MaterialDialog) AsyncTask(android.os.AsyncTask) Intent(android.content.Intent) ImageView(android.widget.ImageView) SpoilerRobotoTextView(me.ccrama.redditslide.SpoilerRobotoTextView) HorizontalScrollView(android.widget.HorizontalScrollView) SubmissionsView(me.ccrama.redditslide.Fragments.SubmissionsView) View(android.view.View) TextView(android.widget.TextView) ApiException(net.dean.jraw.ApiException) ActivityNotFoundException(android.content.ActivityNotFoundException) NetworkException(net.dean.jraw.http.NetworkException) AppCompatCheckBox(android.support.v7.widget.AppCompatCheckBox) MultiRedditManager(net.dean.jraw.managers.MultiRedditManager) AccountManager(net.dean.jraw.managers.AccountManager) CompoundButton(android.widget.CompoundButton) Snackbar(android.support.design.widget.Snackbar)

Example 3 with NetworkException

use of net.dean.jraw.http.NetworkException in project Slide by ccrama.

the class Reddit method setDefaultErrorHandler.

public static void setDefaultErrorHandler(Context base) {
    // START code adapted from https://github.com/QuantumBadger/RedReader/
    final Thread.UncaughtExceptionHandler androidHandler = Thread.getDefaultUncaughtExceptionHandler();
    final WeakReference<Context> cont = new WeakReference<>(base);
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

        public void uncaughtException(Thread thread, Throwable t) {
            if (cont.get() != null) {
                final Context c = cont.get();
                Writer writer = new StringWriter();
                PrintWriter printWriter = new PrintWriter(writer);
                t.printStackTrace(printWriter);
                String stacktrace = writer.toString().replace(";", ",");
                if (stacktrace.contains("UnknownHostException") || stacktrace.contains("SocketTimeoutException") || stacktrace.contains("ConnectException")) {
                    // is offline
                    final Handler mHandler = new Handler(Looper.getMainLooper());
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                new AlertDialogWrapper.Builder(c).setTitle(R.string.err_title).setMessage(R.string.err_connection_failed_msg).setNegativeButton(R.string.btn_close, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (!(c instanceof MainActivity)) {
                                            ((Activity) c).finish();
                                        }
                                    }
                                }).setPositiveButton(R.string.btn_offline, new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Reddit.appRestart.edit().putBoolean("forceoffline", true).apply();
                                        Reddit.forceRestart(c);
                                    }
                                }).show();
                            } catch (Exception ignored) {
                            }
                        }
                    });
                } else if (stacktrace.contains("403 Forbidden") || stacktrace.contains("401 Unauthorized")) {
                    // Un-authenticated
                    final Handler mHandler = new Handler(Looper.getMainLooper());
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                new AlertDialogWrapper.Builder(c).setTitle(R.string.err_title).setMessage(R.string.err_refused_request_msg).setNegativeButton("No", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (!(c instanceof MainActivity)) {
                                            ((Activity) c).finish();
                                        }
                                    }
                                }).setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        authentication.updateToken((c));
                                    }
                                }).show();
                            } catch (Exception ignored) {
                            }
                        }
                    });
                } else if (stacktrace.contains("404 Not Found") || stacktrace.contains("400 Bad Request")) {
                    final Handler mHandler = new Handler(Looper.getMainLooper());
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            try {
                                new AlertDialogWrapper.Builder(c).setTitle(R.string.err_title).setMessage(R.string.err_could_not_find_content_msg).setNegativeButton("Close", new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (!(c instanceof MainActivity)) {
                                            ((Activity) c).finish();
                                        }
                                    }
                                }).show();
                            } catch (Exception ignored) {
                            }
                        }
                    });
                } else if (t instanceof NetworkException) {
                    Toast.makeText(c, "Error " + ((NetworkException) t).getResponse().getStatusMessage() + ": " + (t).getMessage(), Toast.LENGTH_LONG).show();
                } else if (t instanceof NullPointerException && t.getMessage().contains("Attempt to invoke virtual method 'android.content.Context android.view.ViewGroup.getContext()' on a null object reference")) {
                    t.printStackTrace();
                } else if (t instanceof MaterialDialog.DialogException) {
                    t.printStackTrace();
                } else if (t instanceof IllegalArgumentException && t.getMessage().contains("pointerIndex out of range")) {
                    t.printStackTrace();
                } else {
                    appRestart.edit().putString("startScreen", "a").apply();
                    try {
                        SharedPreferences prefs = c.getSharedPreferences("STACKTRACE", Context.MODE_PRIVATE);
                        prefs.edit().putString("stacktrace", stacktrace).apply();
                    } catch (Throwable ignored) {
                    }
                    androidHandler.uncaughtException(thread, t);
                }
            } else {
                androidHandler.uncaughtException(thread, t);
            }
        }
    });
// END adaptation
}
Also used : DialogInterface(android.content.DialogInterface) MainActivity(me.ccrama.redditslide.Activities.MainActivity) Activity(android.app.Activity) SpannableString(android.text.SpannableString) MainActivity(me.ccrama.redditslide.Activities.MainActivity) StringWriter(java.io.StringWriter) AlertDialogWrapper(com.afollestad.materialdialogs.AlertDialogWrapper) WeakReference(java.lang.ref.WeakReference) NetworkException(net.dean.jraw.http.NetworkException) PrintWriter(java.io.PrintWriter) Context(android.content.Context) SharedPreferences(android.content.SharedPreferences) Handler(android.os.Handler) UnknownHostException(java.net.UnknownHostException) NetworkException(net.dean.jraw.http.NetworkException) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) StringWriter(java.io.StringWriter)

Example 4 with NetworkException

use of net.dean.jraw.http.NetworkException in project Slide by ccrama.

the class Authentication method doVerify.

public static void doVerify(String lastToken, RedditClient baseReddit, boolean single, Context mContext) {
    try {
        String token = lastToken;
        if (BuildConfig.DEBUG)
            LogUtil.v("TOKEN IS " + token);
        if (!token.isEmpty()) {
            Credentials credentials = Credentials.installedApp(CLIENT_ID, REDIRECT_URL);
            OAuthHelper oAuthHelper = baseReddit.getOAuthHelper();
            oAuthHelper.setRefreshToken(token);
            try {
                OAuthData finalData;
                if (!single && authentication.contains("backedCreds") && authentication.getLong("expires", 0) > Calendar.getInstance().getTimeInMillis()) {
                    finalData = oAuthHelper.refreshToken(credentials, authentication.getString("backedCreds", ""));
                } else {
                    // does a request
                    finalData = oAuthHelper.refreshToken(credentials);
                    if (!single) {
                        authentication.edit().putLong("expires", Calendar.getInstance().getTimeInMillis() + 3000000).apply();
                    }
                }
                baseReddit.authenticate(finalData);
                if (!single) {
                    authentication.edit().putString("backedCreds", finalData.getDataNode().toString()).apply();
                    refresh = oAuthHelper.getRefreshToken();
                    if (BuildConfig.DEBUG) {
                        LogUtil.v("ACCESS TOKEN IS " + finalData.getAccessToken());
                    }
                    Authentication.isLoggedIn = true;
                    UserSubscriptions.doCachedModSubs();
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (e instanceof NetworkException) {
                    Toast.makeText(mContext, "Error " + ((NetworkException) e).getResponse().getStatusMessage() + ": " + (e).getMessage(), Toast.LENGTH_LONG).show();
                }
            }
            didOnline = true;
        } else if (!single) {
            if (BuildConfig.DEBUG)
                LogUtil.v("NOT LOGGED IN");
            final Credentials fcreds = Credentials.userlessApp(CLIENT_ID, UUID.randomUUID());
            OAuthData authData;
            try {
                authData = reddit.getOAuthHelper().easyAuth(fcreds);
                authentication.edit().putLong("expires", Calendar.getInstance().getTimeInMillis() + 3000000).apply();
                authentication.edit().putString("backedCreds", authData.getDataNode().toString()).apply();
                reddit.authenticate(authData);
                Authentication.name = "LOGGEDOUT";
                Reddit.notFirst = true;
                didOnline = true;
            } catch (Exception e) {
                e.printStackTrace();
                if (e instanceof NetworkException) {
                    Toast.makeText(mContext, "Error " + ((NetworkException) e).getResponse().getStatusMessage() + ": " + (e).getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        }
        if (!single)
            authedOnce = true;
    } catch (Exception e) {
    // TODO fail
    }
}
Also used : OAuthHelper(net.dean.jraw.http.oauth.OAuthHelper) NetworkException(net.dean.jraw.http.NetworkException) Credentials(net.dean.jraw.http.oauth.Credentials) OAuthData(net.dean.jraw.http.oauth.OAuthData) NetworkException(net.dean.jraw.http.NetworkException)

Example 5 with NetworkException

use of net.dean.jraw.http.NetworkException in project Slide by ccrama.

the class MarkAsReadService method onHandleIntent.

@Override
protected void onHandleIntent(Intent intent) {
    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    manager.cancel(intent.getIntExtra(NOTIFICATION_ID, -1));
    String[] messages = null;
    Bundle extras = intent.getExtras();
    if (extras != null)
        messages = extras.getStringArray(CheckForMail.MESSAGE_EXTRA);
    InboxManager inboxManager = new InboxManager(Authentication.reddit);
    if (messages != null && NetworkUtil.isConnected(getBaseContext())) {
        for (String message : messages) {
            try {
                inboxManager.setRead(message, true);
            } catch (NetworkException e) {
                e.printStackTrace();
                return;
            }
        }
    }
}
Also used : InboxManager(net.dean.jraw.managers.InboxManager) NotificationManager(android.app.NotificationManager) Bundle(android.os.Bundle) NetworkException(net.dean.jraw.http.NetworkException)

Aggregations

NetworkException (net.dean.jraw.http.NetworkException)7 DialogInterface (android.content.DialogInterface)3 AlertDialogWrapper (com.afollestad.materialdialogs.AlertDialogWrapper)3 HashMap (java.util.HashMap)3 ApiException (net.dean.jraw.ApiException)3 MultiRedditManager (net.dean.jraw.managers.MultiRedditManager)3 MultiReddit (net.dean.jraw.models.MultiReddit)3 MultiSubreddit (net.dean.jraw.models.MultiSubreddit)3 ActivityNotFoundException (android.content.ActivityNotFoundException)2 Intent (android.content.Intent)2 AsyncTask (android.os.AsyncTask)2 Snackbar (android.support.design.widget.Snackbar)2 AppCompatCheckBox (android.support.v7.widget.AppCompatCheckBox)2 View (android.view.View)2 CompoundButton (android.widget.CompoundButton)2 HorizontalScrollView (android.widget.HorizontalScrollView)2 ImageView (android.widget.ImageView)2 TextView (android.widget.TextView)2 MaterialDialog (com.afollestad.materialdialogs.MaterialDialog)2 ArrayList (java.util.ArrayList)2