Search in sources :

Example 11 with Listing

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

the class ControllerHistory method reload.

public void reload() {
    lastIndex = 0;
    if (TextUtils.isEmpty(query)) {
        namesToFetch.clear();
        HistoryEntry currentEntry = historian.getFirst();
        while (currentEntry != null) {
            if (!currentEntry.isRemoved() && currentEntry.getTimestamp() > timeStart && currentEntry.getTimestamp() < timeEnd) {
                namesToFetch.add(currentEntry.getName());
            }
            currentEntry = currentEntry.getNext();
        }
    }
    if (namesToFetch.isEmpty()) {
        history = new Listing();
        eventHolder.call(new RxAdapterEvent<>(getData()));
        setIsLoading(false);
        return;
    }
    setIsLoading(true);
    StringBuilder builder = new StringBuilder();
    int finalIndex = lastIndex + 25 > namesToFetch.size() ? namesToFetch.size() : lastIndex + 25;
    while (lastIndex < finalIndex) {
        builder.append(namesToFetch.get(lastIndex));
        builder.append(SEPARATOR);
        lastIndex++;
    }
    reddit.info(builder.toString()).flatMap(UtilsRx.flatMapWrapError(response -> Listing.fromJson(ComponentStatic.getObjectMapper().readValue(response, JsonNode.class)))).subscribe(new FinalizingSubscriber<Listing>() {

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

        @Override
        public void next(Listing listing) {
            history = listing;
            eventHolder.call(new RxAdapterEvent<>(getData()));
        }

        @Override
        public void finish() {
            setIsLoading(false);
        }
    });
}
Also used : Listing(com.winsonchiu.reader.data.reddit.Listing) RxAdapterEvent(com.winsonchiu.reader.adapter.RxAdapterEvent)

Example 12 with Listing

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

the class FragmentHistory method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragment_history, container, false);
    layoutCoordinator = (CoordinatorLayout) view.findViewById(R.id.layout_coordinator);
    layoutAppBar = (AppBarLayout) view.findViewById(R.id.layout_app_bar);
    int styleColorBackground = AppSettings.THEME_DARK.equals(mListener.getThemeBackground()) ? R.style.MenuDark : R.style.MenuLight;
    ContextThemeWrapper contextThemeWrapper = new ContextThemeWrapper(new ThemeWrapper(getActivity(), UtilsColor.getThemeForColor(getResources(), themer.getColorPrimary(), mListener)), styleColorBackground);
    toolbar = (Toolbar) getActivity().getLayoutInflater().cloneInContext(contextThemeWrapper).inflate(R.layout.toolbar, layoutAppBar, false);
    layoutAppBar.addView(toolbar);
    ((AppBarLayout.LayoutParams) toolbar.getLayoutParams()).setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS);
    if (getFragmentManager().getBackStackEntryCount() <= 1) {
        toolbar.setNavigationIcon(R.drawable.ic_menu_white_24dp);
        toolbar.setNavigationOnClickListener(v -> mListener.openDrawer());
    } else {
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(v -> mListener.onNavigationBackClick());
    }
    toolbar.getNavigationIcon().mutate().setColorFilter(themer.getColorFilterPrimary());
    toolbar.setTitleTextColor(themer.getColorFilterPrimary().getColor());
    toolbar.setTitle(R.string.history);
    setUpOptionsMenu();
    swipeRefreshHistory = (SwipeRefreshLayout) view.findViewById(R.id.swipe_refresh_history);
    swipeRefreshHistory.setOnRefreshListener(() -> controllerHistory.reload());
    AdapterLink.ViewHolderHeader.EventListener eventListenerHeader = new AdapterLink.ViewHolderHeader.EventListener() {

        @Override
        public void onClickSubmit(Reddit.PostType postType) {
        }

        @Override
        public void showSidebar() {
        }
    };
    AdapterListener adapterListener = new AdapterListener() {

        @Override
        public void requestMore() {
            controllerHistory.loadMoreLinks().observeOn(AndroidSchedulers.mainThread()).subscribe(new ObserverError<Listing>() {

                @Override
                public void onError(Throwable e) {
                    Toast.makeText(getContext(), getContext().getString(R.string.error_loading_links), Toast.LENGTH_SHORT).show();
                }
            });
        }

        @Override
        public void scrollAndCenter(int position, int height) {
            UtilsAnimation.scrollToPositionWithCentering(position, recyclerHistory, false);
        }

        @Override
        public void hideToolbar() {
            AppBarLayout.Behavior behaviorAppBar = (AppBarLayout.Behavior) ((CoordinatorLayout.LayoutParams) layoutAppBar.getLayoutParams()).getBehavior();
            behaviorAppBar.onNestedFling(layoutCoordinator, layoutAppBar, null, 0, 1000, true);
        }

        @Override
        public void clearDecoration() {
            AppBarLayout.Behavior behaviorAppBar = (AppBarLayout.Behavior) ((CoordinatorLayout.LayoutParams) layoutAppBar.getLayoutParams()).getBehavior();
            behaviorAppBar.onNestedFling(layoutCoordinator, layoutAppBar, null, 0, 1000, true);
        }

        @Override
        public void requestDisallowInterceptTouchEventVertical(boolean disallow) {
            swipeRefreshHistory.requestDisallowInterceptTouchEvent(disallow);
            recyclerHistory.requestDisallowInterceptTouchEvent(disallow);
            itemTouchHelper.select(null, CustomItemTouchHelper.ACTION_STATE_IDLE);
        }

        @Override
        public void requestDisallowInterceptTouchEventHorizontal(boolean disallow) {
            itemTouchHelper.setDisallow(disallow);
        }
    };
    AdapterLink.ViewHolderLink.Listener listenerLink = new AdapterLink.ViewHolderLink.Listener() {

        @Override
        public void onSubmitComment(Link link, String text) {
        }

        @Override
        public void onDownloadImage(Link link) {
        }

        @Override
        public void onDownloadImage(Link link, String title, String fileName, String url) {
        }

        @Override
        public void onLoadUrl(Link link, boolean forceExternal) {
        }

        @Override
        public void onShowFullEditor(Link link) {
        }

        @Override
        public void onVote(Link link, AdapterLink.ViewHolderLink viewHolderLink, Likes vote) {
        }

        @Override
        public void onCopyText(Link link) {
        }

        @Override
        public void onEdit(Link link) {
        }

        @Override
        public void onDelete(Link link) {
        }

        @Override
        public void onReport(Link link) {
        }

        @Override
        public void onSave(Link link) {
        }

        @Override
        public void onShowComments(Link link, AdapterLink.ViewHolderLink viewHolderLink, Source source) {
        }

        @Override
        public void onShowError(String error) {
        }

        @Override
        public void onMarkNsfw(Link link) {
        }
    };
    if (adapterLinkList == null) {
        adapterLinkList = new AdapterHistoryLinkList(getActivity(), adapterListener, eventListenerHeader, listenerLink);
    }
    if (adapterLinkGrid == null) {
        adapterLinkGrid = new AdapterHistoryLinkGrid(getActivity(), adapterListener, eventListenerHeader, listenerLink);
    }
    if (AppSettings.MODE_LIST.equals(preferences.getString(AppSettings.INTERFACE_MODE, AppSettings.MODE_GRID))) {
        adapterLink = adapterLinkList;
    } else {
        adapterLink = adapterLinkGrid;
    }
    layoutManager = adapterLink.getLayoutManager();
    itemDecorationDivider = new ItemDecorationDivider(getActivity(), ItemDecorationDivider.VERTICAL_LIST);
    recyclerHistory = (RecyclerView) view.findViewById(R.id.recycler_history);
    recyclerHistory.setHasFixedSize(true);
    recyclerHistory.setItemAnimator(null);
    resetAdapter(adapterLink);
    itemTouchHelper = new CustomItemTouchHelper(new CustomItemTouchHelper.SimpleCallback(getActivity(), R.drawable.ic_visibility_off_white_24dp, ItemTouchHelper.START | ItemTouchHelper.END, ItemTouchHelper.START | ItemTouchHelper.END) {

        @Override
        public float getSwipeThreshold(RecyclerView.ViewHolder viewHolder) {
            if (layoutManager instanceof StaggeredGridLayoutManager) {
                return 1f / ((StaggeredGridLayoutManager) layoutManager).getSpanCount();
            }
            return 0.4f;
        }

        @Override
        public int getSwipeDirs(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            if (viewHolder.getAdapterPosition() == 0) {
                return 0;
            }
            ViewGroup.LayoutParams layoutParams = viewHolder.itemView.getLayoutParams();
            if (layoutParams instanceof StaggeredGridLayoutManager.LayoutParams && !((StaggeredGridLayoutManager.LayoutParams) layoutParams).isFullSpan()) {
                int spanCount = layoutManager instanceof StaggeredGridLayoutManager ? ((StaggeredGridLayoutManager) layoutManager).getSpanCount() : 2;
                int spanIndex = ((StaggeredGridLayoutManager.LayoutParams) layoutParams).getSpanIndex() % spanCount;
                if (spanIndex == 0) {
                    return ItemTouchHelper.END;
                } else if (spanIndex == spanCount - 1) {
                    return ItemTouchHelper.START;
                }
            }
            return super.getSwipeDirs(recyclerView, viewHolder);
        }

        @Override
        public boolean isLongPressDragEnabled() {
            return false;
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            return false;
        }

        @Override
        public void onSwiped(final RecyclerView.ViewHolder viewHolder, int direction) {
            final int position = viewHolder.getAdapterPosition();
            final Link link = controllerHistory.remove(position);
            if (snackbar != null) {
                snackbar.dismiss();
            }
            SpannableString text = new SpannableString(getString(R.string.history_entry_deleted));
            text.setSpan(new ForegroundColorSpan(themer.getColorFilterPrimary().getColor()), 0, text.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
            //noinspection ResourceType
            snackbar = Snackbar.make(recyclerHistory, text, UtilsAnimation.SNACKBAR_DURATION).setActionTextColor(themer.getColorFilterPrimary().getColor()).setAction(R.string.undo, new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    controllerHistory.add(position, link);
                    recyclerHistory.invalidate();
                }
            });
            snackbar.getView().setBackgroundColor(themer.getColorPrimary());
            snackbar.show();
        }
    });
    itemTouchHelper.attachToRecyclerView(recyclerHistory);
    if (layoutManager instanceof LinearLayoutManager) {
        recyclerHistory.setPadding(0, 0, 0, 0);
    } else {
        int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics());
        recyclerHistory.setPadding(padding, 0, padding, 0);
    }
    return view;
}
Also used : ItemDecorationDivider(com.winsonchiu.reader.utils.ItemDecorationDivider) AdapterLink(com.winsonchiu.reader.links.AdapterLink) AdapterListener(com.winsonchiu.reader.adapter.AdapterListener) StaggeredGridLayoutManager(android.support.v7.widget.StaggeredGridLayoutManager) SpannableString(android.text.SpannableString) LinearLayoutManager(android.support.v7.widget.LinearLayoutManager) Source(com.winsonchiu.reader.comments.Source) ContextThemeWrapper(android.view.ContextThemeWrapper) ThemeWrapper(com.winsonchiu.reader.theme.ThemeWrapper) CustomItemTouchHelper(com.winsonchiu.reader.utils.CustomItemTouchHelper) AppBarLayout(android.support.design.widget.AppBarLayout) AdapterListener(com.winsonchiu.reader.adapter.AdapterListener) ForegroundColorSpan(android.text.style.ForegroundColorSpan) ViewGroup(android.view.ViewGroup) SearchView(android.support.v7.widget.SearchView) ImageView(android.widget.ImageView) View(android.view.View) RecyclerView(android.support.v7.widget.RecyclerView) CoordinatorLayout(android.support.design.widget.CoordinatorLayout) SpannableString(android.text.SpannableString) ContextThemeWrapper(android.view.ContextThemeWrapper) Listing(com.winsonchiu.reader.data.reddit.Listing) RecyclerView(android.support.v7.widget.RecyclerView) Likes(com.winsonchiu.reader.data.reddit.Likes) AdapterLink(com.winsonchiu.reader.links.AdapterLink) Link(com.winsonchiu.reader.data.reddit.Link)

Example 13 with Listing

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

the class ControllerSearch method reloadSubreddits.

public void reloadSubreddits() {
    if (subscriptionSubreddits != null && !subscriptionSubreddits.isUnsubscribed()) {
        subscriptionSubreddits.unsubscribe();
        subscriptionSubreddits = null;
    }
    // TODO: Move this to asynchronous with Thread cancelling
    String queryTrimmed = query.toLowerCase().replaceAll("\\s", "");
    Listing subscribedResults = new Listing();
    List<Thing> resultsThatContainQueryInTitle = new ArrayList<>();
    List<Thing> resultsThatContainQueryInDescription = new ArrayList<>();
    for (Thing thing : subredditsSubscribed.getChildren()) {
        Subreddit subreddit = (Subreddit) thing;
        if (subreddit.getDisplayName().toLowerCase().startsWith(queryTrimmed)) {
            subscribedResults.getChildren().add(subreddit);
        } else if (subreddit.getDisplayName().toLowerCase().contains(queryTrimmed)) {
            resultsThatContainQueryInTitle.add(subreddit);
        } else if (subreddit.getPublicDescription().toLowerCase().contains(queryTrimmed)) {
            resultsThatContainQueryInDescription.add(subreddit);
        }
    }
    subscribedResults.addChildren(resultsThatContainQueryInTitle);
    subscribedResults.addChildren(resultsThatContainQueryInDescription);
    subreddits = subscribedResults;
    for (Listener listener : listeners) {
        listener.getAdapterSearchSubreddits().notifyDataSetChanged();
    }
    try {
        subscriptionSubreddits = reddit.subredditsSearch(URLEncoder.encode(query, Reddit.UTF_8).replaceAll("\\s", ""), sort.toString()).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) {
                Iterator<Thing> iterator = listing.getChildren().iterator();
                while (iterator.hasNext()) {
                    Subreddit subreddit = (Subreddit) iterator.next();
                    if (subreddit.getSubredditType().equalsIgnoreCase(Subreddit.PRIVATE) && !subreddit.isUserIsContributor()) {
                        iterator.remove();
                    }
                }
                subreddits.addChildren(listing.getChildren());
                for (final Listener listener : listeners) {
                    listener.getAdapterSearchSubreddits().notifyDataSetChanged();
                }
            }
        });
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
}
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) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JsonNode(com.fasterxml.jackson.databind.JsonNode) Listing(com.winsonchiu.reader.data.reddit.Listing) Observer(rx.Observer) Subreddit(com.winsonchiu.reader.data.reddit.Subreddit) Thing(com.winsonchiu.reader.data.reddit.Thing)

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