Search in sources :

Example 1 with Search

use of com.odysee.app.callable.Search in project odysee-android by OdyseeTeam.

the class FileViewFragment method loadRelatedContent.

private void loadRelatedContent() {
    // reset the list view
    View root = getView();
    if (fileClaim != null && root != null) {
        Context context = getContext();
        List<Claim> loadingPlaceholders = new ArrayList<>();
        int loadingPlaceholdersLength = Claim.TYPE_COLLECTION.equalsIgnoreCase(fileClaim.getValueType()) ? fileClaim.getClaimIds().size() : 15;
        for (int i = 0; i < loadingPlaceholdersLength; i++) {
            Claim placeholder = new Claim();
            placeholder.setLoadingPlaceholder(true);
            loadingPlaceholders.add(placeholder);
        }
        relatedContentAdapter = new ClaimListAdapter(loadingPlaceholders, context);
        relatedContentAdapter.setContextGroupId(FILE_CONTEXT_GROUP_ID);
        RecyclerView relatedContentList = root.findViewById(R.id.file_view_related_content_list);
        relatedContentList.setAdapter(relatedContentAdapter);
        ProgressBar relatedLoading = root.findViewById(R.id.file_view_related_content_progress);
        boolean canShowMatureContent = false;
        if (context != null) {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
            canShowMatureContent = sp.getBoolean(MainActivity.PREFERENCE_KEY_SHOW_MATURE_CONTENT, false);
        }
        if (!Claim.TYPE_COLLECTION.equalsIgnoreCase(fileClaim.getValueType())) {
            String title = fileClaim.getTitle();
            String claimId = fileClaim.getClaimId();
            final boolean nsfw = canShowMatureContent;
            relatedLoading.setVisibility(View.VISIBLE);
            // Making a request which explicitly uses a certain value form the amount of results needed
            // and no processing any possible exception, so using a callable instead of an AsyncTask
            // makes sense for all Android API Levels
            Thread t = new Thread(new Runnable() {

                @Override
                public void run() {
                    ExecutorService executor = Executors.newSingleThreadExecutor();
                    LighthouseSearch callable = new LighthouseSearch(title, RELATED_CONTENT_SIZE, 0, nsfw, claimId);
                    Future<List<Claim>> future = executor.submit(callable);
                    try {
                        List<Claim> result = future.get();
                        if (executor != null && !executor.isShutdown()) {
                            executor.shutdown();
                        }
                        MainActivity a = (MainActivity) getActivity();
                        if (a != null) {
                            a.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    relatedContentRequestSuccedded(result);
                                    relatedLoading.setVisibility(View.GONE);
                                }
                            });
                        }
                    } catch (InterruptedException | ExecutionException e) {
                        if (executor != null && !executor.isShutdown()) {
                            executor.shutdown();
                        }
                        e.printStackTrace();
                    }
                }
            });
            t.start();
        } else {
            TextView relatedOrPlayList = root.findViewById(R.id.related_or_playlist);
            relatedOrPlayList.setText(fileClaim.getTitle());
            relatedOrPlayList.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_cast_connected, 0, 0, 0);
            relatedOrPlayList.setPadding(0, 0, 0, 16);
            relatedOrPlayList.setTypeface(null, Typeface.BOLD);
            Map<String, Object> claimSearchOptions = new HashMap<>(3);
            claimSearchOptions.put("claim_ids", fileClaim.getClaimIds());
            claimSearchOptions.put("not_tags", canShowMatureContent ? null : new ArrayList<>(Predefined.MATURE_TAGS));
            claimSearchOptions.put("page_size", fileClaim.getClaimIds().size());
            ExecutorService executor = Executors.newSingleThreadExecutor();
            Future<List<Claim>> future = executor.submit(new Search(claimSearchOptions));
            try {
                List<Claim> playlistClaimItems = future.get();
                if (playlistClaimItems != null) {
                    relatedContentAdapter.setItems(playlistClaimItems);
                    relatedContentAdapter.setListener(FileViewFragment.this);
                    View v = getView();
                    if (v != null) {
                        relatedContentList.setAdapter(relatedContentAdapter);
                        relatedContentAdapter.notifyDataSetChanged();
                        Helper.setViewVisibility(v.findViewById(R.id.file_view_no_related_content), relatedContentAdapter == null || relatedContentAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
                    }
                    scrollToCommentHash();
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MainActivity(com.odysee.app.MainActivity) ClaimListAdapter(com.odysee.app.adapter.ClaimListAdapter) LighthouseSearch(com.odysee.app.callable.LighthouseSearch) Search(com.odysee.app.callable.Search) LighthouseSearch(com.odysee.app.callable.LighthouseSearch) ArrayList(java.util.ArrayList) List(java.util.List) TextView(android.widget.TextView) ExecutionException(java.util.concurrent.ExecutionException) ProgressBar(android.widget.ProgressBar) TrackSelectionOverride(com.google.android.exoplayer2.trackselection.TrackSelectionOverrides.TrackSelectionOverride) AttributeProviderContext(org.commonmark.renderer.html.AttributeProviderContext) Context(android.content.Context) SharedPreferences(android.content.SharedPreferences) SolidIconView(com.odysee.app.ui.controls.SolidIconView) PlayerView(com.google.android.exoplayer2.ui.PlayerView) NestedScrollView(androidx.core.widget.NestedScrollView) AdapterView(android.widget.AdapterView) RecyclerView(androidx.recyclerview.widget.RecyclerView) PhotoView(com.github.chrisbanes.photoview.PhotoView) ImageView(android.widget.ImageView) View(android.view.View) WebView(android.webkit.WebView) TextView(android.widget.TextView) SuppressLint(android.annotation.SuppressLint) AnyThread(androidx.annotation.AnyThread) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) Future(java.util.concurrent.Future) CompletableFuture(java.util.concurrent.CompletableFuture) ScheduledFuture(java.util.concurrent.ScheduledFuture) RecyclerView(androidx.recyclerview.widget.RecyclerView) JSONObject(org.json.JSONObject) Claim(com.odysee.app.model.Claim)

Example 2 with Search

use of com.odysee.app.callable.Search in project odysee-android by OdyseeTeam.

the class SearchFragment method search.

public void search(String query, int from) {
    boolean queryChanged = checkQuery(query);
    if (query.equals("")) {
        return;
    }
    if (!queryChanged && from > 0) {
        currentFrom = from;
    }
    if (queryChanged) {
        logSearch(query);
    }
    searchLoading = true;
    Context context = getContext();
    boolean canShowMatureContent = false;
    if (context != null) {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getContext());
        canShowMatureContent = sp.getBoolean(MainActivity.PREFERENCE_KEY_SHOW_MATURE_CONTENT, false);
    }
    // modify the request so it returns channels on top
    if (currentQuery != null) {
        final String[] split = currentQuery.split(" ");
        if (split.length == 1 && !currentQuery.startsWith("@")) {
            currentQuery = "@".concat(query);
        }
    }
    Activity a = getActivity();
    if (a != null) {
        a.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                loadingView.setVisibility(View.VISIBLE);
            }
        });
    }
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Callable<List<Claim>> c = new LighthouseSearch(currentQuery, PAGE_SIZE, currentFrom, canShowMatureContent, null);
    Thread t = new Thread(new Runnable() {

        @Override
        public void run() {
            Future<List<Claim>> future = executor.submit(c);
            try {
                List<Claim> results = future.get();
                List<Claim> sanitizedClaims = new ArrayList<>(results.size());
                for (Claim item : results) {
                    if (!item.getValueType().equalsIgnoreCase(Claim.TYPE_REPOST)) {
                        sanitizedClaims.add(item);
                    }
                }
                if (a != null) {
                    a.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            Context context = getContext();
                            if (context != null) {
                                if (resultListAdapter == null) {
                                    resultListAdapter = new ClaimListAdapter(sanitizedClaims, context);
                                    resultListAdapter.setContextGroupId(SEARCH_CONTEXT_GROUP_ID);
                                    resultListAdapter.addFeaturedItem(buildFeaturedItem(query));
                                    resolveFeaturedItem(buildVanityUrl(query));
                                    resultListAdapter.setListener(SearchFragment.this);
                                    if (resultList != null) {
                                        resultList.setAdapter(resultListAdapter);
                                    }
                                } else {
                                    resultList.setVisibility(View.VISIBLE);
                                    resultListAdapter.addItems(sanitizedClaims);
                                }
                                resultListAdapter.filterBlockedChannels(Lbryio.blockedChannels);
                                checkNothingToBeShown();
                            }
                        }
                    });
                }
                // Lighthouse doesn't return "valueType" of the claim, so another request is needed
                // to determine if an item is a playlist and get the items on the playlist.
                List<String> claimIds = new ArrayList<>();
                for (Claim sanitizedClaim : sanitizedClaims) {
                    if (!sanitizedClaim.getValueType().equalsIgnoreCase(Claim.TYPE_CHANNEL)) {
                        claimIds.add(sanitizedClaim.getClaimId());
                    }
                }
                Map<String, Object> claimSearchOptions = new HashMap<>(2);
                claimSearchOptions.put("claim_ids", claimIds);
                claimSearchOptions.put("page_size", claimIds.size());
                Future<List<Claim>> futureSearch = executor.submit(new Search(claimSearchOptions));
                List<Claim> totalResults = futureSearch.get();
                // For each claim returned from Lighthouse, replace it by the one using Search API
                for (int i = 0; i < sanitizedClaims.size(); i++) {
                    if (!Claim.TYPE_CHANNEL.equalsIgnoreCase(sanitizedClaims.get(i).getValueType())) {
                        int finalI = i;
                        Claim found = totalResults.stream().filter(filteredClaim -> {
                            return sanitizedClaims.get(finalI).getClaimId().equalsIgnoreCase(filteredClaim.getClaimId());
                        }).findAny().orElse(null);
                        if (found != null) {
                            sanitizedClaims.set(i, found);
                            if (a != null && resultListAdapter != null) {
                                a.runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        if (!found.getValueType().equalsIgnoreCase(Claim.TYPE_REPOST)) {
                                            resultListAdapter.setItem(found.getClaimId(), found);
                                        } else {
                                            resultListAdapter.removeItem(found);
                                        }
                                    }
                                });
                            }
                        }
                    }
                }
                contentHasReachedEnd = results.size() < PAGE_SIZE;
                searchLoading = false;
                if (a != null) {
                    a.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            loadingView.setVisibility(View.GONE);
                            int itemCount = resultListAdapter == null ? 0 : resultListAdapter.getItemCount();
                            if (itemCount == 0) {
                                filterLink.setVisibility(View.GONE);
                            } else {
                                filterLink.setVisibility(View.VISIBLE);
                            }
                        }
                    });
                }
            } catch (ExecutionException | InterruptedException e) {
                e.printStackTrace();
            } finally {
                if (!executor.isShutdown()) {
                    executor.shutdown();
                }
            }
        }
    });
    t.start();
}
Also used : Context(android.content.Context) Context(android.content.Context) Chip(com.google.android.material.chip.Chip) java.util(java.util) Setter(lombok.Setter) Bundle(android.os.Bundle) ResolveTask(com.odysee.app.tasks.claim.ResolveTask) NonNull(androidx.annotation.NonNull) ClaimListResultHandler(com.odysee.app.tasks.claim.ClaimListResultHandler) Lbry(com.odysee.app.utils.Lbry) ChipGroup(com.google.android.material.chip.ChipGroup) MenuItem(android.view.MenuItem) LighthouseSearch(com.odysee.app.callable.LighthouseSearch) AppCompatSpinner(androidx.appcompat.widget.AppCompatSpinner) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) MainActivity(com.odysee.app.MainActivity) LbryUri(com.odysee.app.utils.LbryUri) View(android.view.View) Search(com.odysee.app.callable.Search) LbryFile(com.odysee.app.model.LbryFile) RecyclerView(androidx.recyclerview.widget.RecyclerView) ContextCompat(androidx.core.content.ContextCompat) AsyncTask(android.os.AsyncTask) LayoutInflater(android.view.LayoutInflater) java.util.concurrent(java.util.concurrent) Helper(com.odysee.app.utils.Helper) ClaimListAdapter(com.odysee.app.adapter.ClaimListAdapter) Claim(com.odysee.app.model.Claim) ViewGroup(android.view.ViewGroup) Lbryio(com.odysee.app.utils.Lbryio) DownloadActionListener(com.odysee.app.listener.DownloadActionListener) ClaimCacheKey(com.odysee.app.model.ClaimCacheKey) SharedPreferences(android.content.SharedPreferences) android.widget(android.widget) BaseFragment(com.odysee.app.ui.BaseFragment) LbryAnalytics(com.odysee.app.utils.LbryAnalytics) PreferenceManager(androidx.preference.PreferenceManager) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Activity(android.app.Activity) R(com.odysee.app.R) SharedPreferences(android.content.SharedPreferences) MainActivity(com.odysee.app.MainActivity) Activity(android.app.Activity) ClaimListAdapter(com.odysee.app.adapter.ClaimListAdapter) LighthouseSearch(com.odysee.app.callable.LighthouseSearch) LighthouseSearch(com.odysee.app.callable.LighthouseSearch) Search(com.odysee.app.callable.Search) Claim(com.odysee.app.model.Claim)

Aggregations

Context (android.content.Context)2 SharedPreferences (android.content.SharedPreferences)2 View (android.view.View)2 RecyclerView (androidx.recyclerview.widget.RecyclerView)2 MainActivity (com.odysee.app.MainActivity)2 ClaimListAdapter (com.odysee.app.adapter.ClaimListAdapter)2 LighthouseSearch (com.odysee.app.callable.LighthouseSearch)2 Search (com.odysee.app.callable.Search)2 Claim (com.odysee.app.model.Claim)2 JSONObject (org.json.JSONObject)2 SuppressLint (android.annotation.SuppressLint)1 Activity (android.app.Activity)1 AsyncTask (android.os.AsyncTask)1 Bundle (android.os.Bundle)1 LayoutInflater (android.view.LayoutInflater)1 MenuItem (android.view.MenuItem)1 ViewGroup (android.view.ViewGroup)1 WebView (android.webkit.WebView)1 android.widget (android.widget)1 AdapterView (android.widget.AdapterView)1