Search in sources :

Example 6 with Listing

use of com.winsonchiu.reader.data.reddit.Listing in project Reader by TheKeeperOfPie.

the class ControllerSearch method reloadLinksSubreddit.

public Observable<Listing> reloadLinksSubreddit() {
    if (subscriptionLinksSubreddit != null && !subscriptionLinksSubreddit.isUnsubscribed()) {
        subscriptionLinksSubreddit.unsubscribe();
        subscriptionLinksSubreddit = null;
    }
    Subreddit subreddit = controllerLinks.getSubreddit();
    String pathSubreddit = subreddit.getUrl();
    if (pathSubreddit.length() < 2) {
        pathSubreddit = "";
    }
    Observable<Listing> observable = reddit.search(pathSubreddit, query, sort.toString(), time.toString(), null, true).flatMap(UtilsRx.flatMapWrapError(response -> Listing.fromJson(ComponentStatic.getObjectMapper().readValue(response, JsonNode.class))));
    subscriptionSubreddits = observable.subscribe(new FinalizingSubscriber<Listing>() {

        @Override
        public void start() {
            setLoadingLinksSubreddit(true);
        }

        @Override
        public void next(Listing listing) {
            linksSubreddit = listing;
            eventHolder.callLinksSubreddit(new RxAdapterEvent<>(getLinksSubredditModel()));
            for (Listener listener : listeners) {
                listener.scrollToLinksSubreddit(0);
            }
        }

        @Override
        public void finish() {
            setLoadingLinksSubreddit(false);
        }
    });
    return observable;
}
Also used : Context(android.content.Context) CustomApplication(com.winsonchiu.reader.CustomApplication) Subreddit(com.winsonchiu.reader.data.reddit.Subreddit) ControllerLinks(com.winsonchiu.reader.links.ControllerLinks) ListIterator(java.util.ListIterator) UtilsRx(com.winsonchiu.reader.utils.UtilsRx) AppSettings(com.winsonchiu.reader.AppSettings) LinksModel(com.winsonchiu.reader.links.LinksModel) ArrayList(java.util.ArrayList) Observable(rx.Observable) HashSet(java.util.HashSet) Inject(javax.inject.Inject) Reddit(com.winsonchiu.reader.data.reddit.Reddit) JSONObject(org.json.JSONObject) ComponentStatic(com.winsonchiu.reader.dagger.components.ComponentStatic) Link(com.winsonchiu.reader.data.reddit.Link) JsonNode(com.fasterxml.jackson.databind.JsonNode) PreferenceManager(android.preference.PreferenceManager) Log(android.util.Log) AccountManager(android.accounts.AccountManager) BehaviorRelay(com.jakewharton.rxrelay.BehaviorRelay) Iterator(java.util.Iterator) ControllerUser(com.winsonchiu.reader.ControllerUser) Sort(com.winsonchiu.reader.data.reddit.Sort) Listing(com.winsonchiu.reader.data.reddit.Listing) Set(java.util.Set) TextUtils(android.text.TextUtils) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FinalizingSubscriber(com.winsonchiu.reader.rx.FinalizingSubscriber) IOException(java.io.IOException) Thing(com.winsonchiu.reader.data.reddit.Thing) Observer(rx.Observer) URLEncoder(java.net.URLEncoder) List(java.util.List) SharedPreferences(android.content.SharedPreferences) Replyable(com.winsonchiu.reader.data.reddit.Replyable) Time(com.winsonchiu.reader.data.reddit.Time) RxAdapterEvent(com.winsonchiu.reader.adapter.RxAdapterEvent) Nullable(android.support.annotation.Nullable) Comparator(java.util.Comparator) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) Subscription(rx.Subscription) JSONArray(org.json.JSONArray) Listing(com.winsonchiu.reader.data.reddit.Listing) JsonNode(com.fasterxml.jackson.databind.JsonNode) Subreddit(com.winsonchiu.reader.data.reddit.Subreddit) FinalizingSubscriber(com.winsonchiu.reader.rx.FinalizingSubscriber)

Example 7 with Listing

use of com.winsonchiu.reader.data.reddit.Listing in project Reader by TheKeeperOfPie.

the class ControllerSearch method setSort.

public Observable<Listing> setSort(Sort sort) {
    Listing listingSort = getCurrentPage() == PAGE_SUBREDDITS_RECOMMENDED ? subredditsRecommended : subreddits;
    if (Sort.ALPHABETICAL.equals(sort)) {
        if (Sort.ALPHABETICAL.equals(sortSubreddits)) {
            Collections.sort(listingSort.getChildren(), new Comparator<Thing>() {

                @Override
                public int compare(Thing lhs, Thing rhs) {
                    return ((Subreddit) rhs).getDisplayName().compareToIgnoreCase(((Subreddit) lhs).getDisplayName());
                }
            });
            sortSubreddits = null;
        } else {
            Collections.sort(listingSort.getChildren(), new Comparator<Thing>() {

                @Override
                public int compare(Thing lhs, Thing rhs) {
                    return ((Subreddit) lhs).getDisplayName().compareToIgnoreCase(((Subreddit) rhs).getDisplayName());
                }
            });
            sortSubreddits = Sort.ALPHABETICAL;
        }
        if (listingSort == subredditsSubscribed) {
            saveSubscriptions();
        } else if (listingSort == subredditsRecommended) {
            for (Listener listener : listeners) {
                listener.getAdapterSearchSubredditsRecommended().notifyDataSetChanged();
            }
        } else {
            for (Listener listener : listeners) {
                listener.getAdapterSearchSubreddits().notifyDataSetChanged();
            }
        }
    } else if (Sort.SUBSCRIBERS.equals(sort)) {
        if (Sort.SUBSCRIBERS.equals(sortSubreddits)) {
            Collections.sort(listingSort.getChildren(), new Comparator<Thing>() {

                @Override
                public int compare(Thing lhs, Thing rhs) {
                    long subscribersFirst = ((Subreddit) lhs).getSubscribers();
                    long subscribersSecond = ((Subreddit) rhs).getSubscribers();
                    return subscribersFirst < subscribersSecond ? -1 : (subscribersFirst == subscribersSecond ? 0 : 1);
                }
            });
            sortSubreddits = null;
        } else {
            Collections.sort(listingSort.getChildren(), new Comparator<Thing>() {

                @Override
                public int compare(Thing lhs, Thing rhs) {
                    long subscribersFirst = ((Subreddit) lhs).getSubscribers();
                    long subscribersSecond = ((Subreddit) rhs).getSubscribers();
                    return subscribersSecond < subscribersFirst ? -1 : (subscribersFirst == subscribersSecond ? 0 : 1);
                }
            });
            sortSubreddits = Sort.SUBSCRIBERS;
        }
        if (listingSort == subredditsSubscribed) {
            saveSubscriptions();
        } else if (listingSort == subredditsRecommended) {
            for (Listener listener : listeners) {
                listener.getAdapterSearchSubredditsRecommended().notifyDataSetChanged();
            }
        } else {
            for (Listener listener : listeners) {
                listener.getAdapterSearchSubreddits().notifyDataSetChanged();
            }
        }
    } else if (this.sort != sort) {
        this.sort = sort;
        eventHolder.getSort().call(sort);
        return reloadCurrentPage();
    }
    return Observable.empty();
}
Also used : Listing(com.winsonchiu.reader.data.reddit.Listing) Subreddit(com.winsonchiu.reader.data.reddit.Subreddit) Thing(com.winsonchiu.reader.data.reddit.Thing) Comparator(java.util.Comparator)

Example 8 with Listing

use of com.winsonchiu.reader.data.reddit.Listing in project Reader by TheKeeperOfPie.

the class ControllerSearch method reloadSubscriptionList.

public void reloadSubscriptionList() {
    Listing listing = new Listing();
    String subscriptionsJson = preferences.getString(AppSettings.SUBSCRIPTIONS + controllerUser.getUser().getName(), "");
    Log.d(TAG, "subscriptionsJson: " + subscriptionsJson);
    if (!TextUtils.isEmpty(subscriptionsJson)) {
        try {
            JsonNode jsonNode = ComponentStatic.getObjectMapper().readValue(subscriptionsJson, JsonNode.class);
            for (JsonNode node : jsonNode) {
                listing.getChildren().add(Subreddit.fromJson(node));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    subredditsSubscribed = listing;
    if (TextUtils.isEmpty(query)) {
        subreddits = subredditsSubscribed;
        for (Listener listener : listeners) {
            listener.getAdapterSearchSubreddits().notifyDataSetChanged();
        }
    }
    String url;
    if (controllerUser.hasUser()) {
        url = Reddit.OAUTH_URL + "/subreddits/mine/subscriber";
    } else {
        url = Reddit.OAUTH_URL + "/subreddits/default";
    }
    reddit.subreddits(url, null, 100).flatMap(UtilsRx.flatMapWrapError(response -> Listing.fromJson(ComponentStatic.getObjectMapper().readValue(response, JsonNode.class)))).subscribe(new Observer<Listing>() {

        @Override
        public void onCompleted() {
        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
        }

        @Override
        public void onNext(Listing listing) {
            subredditsLoaded.addChildren(listing.getChildren());
            subredditsLoaded.setAfter(listing.getAfter());
            if (listing.getChildren().size() == 100) {
                loadMoreSubscriptions();
            } else {
                loadContributorSubreddits();
            }
        }
    });
}
Also used : Listing(com.winsonchiu.reader.data.reddit.Listing) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException)

Example 9 with Listing

use of com.winsonchiu.reader.data.reddit.Listing in project Reader by TheKeeperOfPie.

the class ControllerComments method setLinkWithComments.

public void setLinkWithComments(Link link) {
    link.setBackgroundColor(this.link.getBackgroundColor());
    this.link = link;
    Listing listing = new Listing();
    // For some reason Reddit doesn't report the link author, so we'll do it manually
    for (Thing thing : link.getComments().getChildren()) {
        Comment comment = (Comment) thing;
        comment.setLinkAuthor(link.getAuthor());
    }
    // TODO: Make this logic cleaner
    if (link.getComments() != null) {
        listing.setChildren(new ArrayList<>(link.getComments().getChildren()));
    } else {
        listing.setChildren(new ArrayList<>());
    }
    listingComments = listing;
    if (sharedPreferences.getBoolean(AppSettings.PREF_COLLAPSE_COMMENT_THREADS, false)) {
        for (int index = listingComments.getChildren().size() - 1; index >= 0; index--) {
            if (((Comment) listingComments.getChildren().get(index)).getLevel() == 0) {
                collapseComment(index, false);
            }
        }
    }
    eventHolder.call(new RxAdapterEvent<>(getData()));
}
Also used : Comment(com.winsonchiu.reader.data.reddit.Comment) Listing(com.winsonchiu.reader.data.reddit.Listing) Thing(com.winsonchiu.reader.data.reddit.Thing)

Example 10 with Listing

use of com.winsonchiu.reader.data.reddit.Listing in project Reader by TheKeeperOfPie.

the class Receiver method checkInbox.

public void checkInbox(final Context context, @Nullable final ArrayList<String> names) {
    final ArrayList<String> readNames;
    if (names == null) {
        readNames = new ArrayList<>();
    } else {
        readNames = names;
    }
    new Thread(new Runnable() {

        @Override
        public void run() {
            final Listing messages = new Listing();
            Account[] accounts = accountManager.getAccountsByType(Reddit.ACCOUNT_TYPE);
            for (Account account : accounts) {
                final AccountManagerFuture<Bundle> futureAuth = accountManager.getAuthToken(account, Reddit.AUTH_TOKEN_FULL_ACCESS, null, true, null, null);
                try {
                    Bundle bundle = futureAuth.getResult();
                    final String tokenAuth = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                    Request request = new Request.Builder().url(Reddit.OAUTH_URL + "/message/unread").header(Reddit.USER_AGENT, Reddit.CUSTOM_USER_AGENT).header(Reddit.AUTHORIZATION, Reddit.BEARER + tokenAuth).header(Reddit.CONTENT_TYPE, Reddit.CONTENT_TYPE_APP_JSON).get().build();
                    String response = okHttpClient.newCall(request).execute().body().string();
                    Listing listing = Listing.fromJson(ComponentStatic.getObjectMapper().readValue(response, JsonNode.class));
                    messages.addChildren(listing.getChildren());
                    Log.d(TAG, account.name + " checkInbox response: " + response);
                } catch (OperationCanceledException | AuthenticatorException | IOException e) {
                    e.printStackTrace();
                }
            }
            NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
            Thing thing = null;
            for (int index = 0; index < messages.getChildren().size(); index++) {
                thing = messages.getChildren().get(index);
                if (readNames.contains(thing.getName())) {
                    reddit.markRead(thing.getName()).subscribe(new ObserverEmpty<>());
                    thing = null;
                } else {
                    readNames.add(thing.getName());
                    break;
                }
            }
            if (thing == null) {
                notificationManager.cancel(NOTIFICATION_INBOX);
                return;
            }
            int titleSuffixResource = messages.getChildren().size() == 1 ? R.string.new_message : R.string.new_messages;
            CharSequence content = "";
            CharSequence author = "";
            CharSequence dest = "";
            if (thing instanceof Message) {
                content = ((Message) thing).getBodyHtml();
                author = ((Message) thing).getAuthor();
                dest = ((Message) thing).getDest();
            } else if (thing instanceof Comment) {
                content = ((Comment) thing).getBodyHtml();
                author = ((Comment) thing).getAuthor();
                dest = ((Comment) thing).getDest();
            }
            Intent intentActivity = new Intent(context, ActivityMain.class);
            intentActivity.putExtra(ActivityMain.ACCOUNT, dest);
            intentActivity.putExtra(ActivityMain.NAV_ID, R.id.item_inbox);
            intentActivity.putExtra(ActivityMain.NAV_PAGE, ControllerInbox.UNREAD);
            PendingIntent pendingIntentActivity = PendingIntent.getActivity(context, 0, intentActivity, PendingIntent.FLAG_CANCEL_CURRENT);
            Intent intentRecheckInbox = new Intent(INTENT_INBOX);
            intentRecheckInbox.putExtra(READ_NAMES, readNames);
            PendingIntent pendingIntentRecheckInbox = PendingIntent.getBroadcast(context, 0, intentRecheckInbox, PendingIntent.FLAG_CANCEL_CURRENT);
            Themer themer = new Themer(context);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.mipmap.app_icon_white_outline).setContentTitle(messages.getChildren().size() + " " + context.getResources().getString(titleSuffixResource)).setContentText(context.getString(R.string.expand_to_read_first_message)).setStyle(new NotificationCompat.BigTextStyle().setSummaryText(context.getString(R.string.from) + " /u/" + author).bigText(content)).setContentIntent(pendingIntentActivity).addAction(new NotificationCompat.Action(R.drawable.ic_check_white_24dp, context.getString(R.string.mark_read), pendingIntentRecheckInbox)).setDeleteIntent(pendingIntentRecheckInbox).setAutoCancel(true).setCategory(NotificationCompat.CATEGORY_EMAIL).setColor(themer.getColorPrimary()).setLights(themer.getColorPrimary(), LED_MS_ON, LED_MS_OFF);
            notificationManager.notify(NOTIFICATION_INBOX, builder.build());
        }
    }).start();
}
Also used : Account(android.accounts.Account) Message(com.winsonchiu.reader.data.reddit.Message) OperationCanceledException(android.accounts.OperationCanceledException) NotificationManagerCompat(android.support.v4.app.NotificationManagerCompat) JsonNode(com.fasterxml.jackson.databind.JsonNode) NotificationCompat(android.support.v4.app.NotificationCompat) Thing(com.winsonchiu.reader.data.reddit.Thing) Comment(com.winsonchiu.reader.data.reddit.Comment) Bundle(android.os.Bundle) Request(okhttp3.Request) AuthenticatorException(android.accounts.AuthenticatorException) Themer(com.winsonchiu.reader.theme.Themer) Intent(android.content.Intent) PendingIntent(android.app.PendingIntent) IOException(java.io.IOException) Listing(com.winsonchiu.reader.data.reddit.Listing) PendingIntent(android.app.PendingIntent)

Aggregations

Listing (com.winsonchiu.reader.data.reddit.Listing)13 Thing (com.winsonchiu.reader.data.reddit.Thing)7 JsonNode (com.fasterxml.jackson.databind.JsonNode)6 IOException (java.io.IOException)6 RxAdapterEvent (com.winsonchiu.reader.adapter.RxAdapterEvent)5 Link (com.winsonchiu.reader.data.reddit.Link)5 Comment (com.winsonchiu.reader.data.reddit.Comment)4 Subreddit (com.winsonchiu.reader.data.reddit.Subreddit)4 AccountManager (android.accounts.AccountManager)3 Context (android.content.Context)3 SharedPreferences (android.content.SharedPreferences)3 PreferenceManager (android.preference.PreferenceManager)3 Nullable (android.support.annotation.Nullable)3 TextUtils (android.text.TextUtils)3 Log (android.util.Log)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)3 BehaviorRelay (com.jakewharton.rxrelay.BehaviorRelay)3 AppSettings (com.winsonchiu.reader.AppSettings)3 ControllerUser (com.winsonchiu.reader.ControllerUser)3 CustomApplication (com.winsonchiu.reader.CustomApplication)3