Search in sources :

Example 1 with LbryioRequestException

use of com.odysee.app.exceptions.LbryioRequestException in project odysee-android by OdyseeTeam.

the class RewardsFragment method fetchRewards.

private void fetchRewards() {
    Helper.setViewVisibility(rewardList, View.INVISIBLE);
    rewardsLoading.setVisibility(View.VISIBLE);
    Activity activity = getActivity();
    String authToken;
    AccountManager am = AccountManager.get(getContext());
    Account odyseeAccount = Helper.getOdyseeAccount(am.getAccounts());
    if (odyseeAccount != null) {
        authToken = am.peekAuthToken(odyseeAccount, "auth_token_type");
    } else {
        authToken = "";
    }
    Map<String, String> options = new HashMap<>();
    options.put("multiple_rewards_per_type", "true");
    if (odyseeAccount != null && authToken != null) {
        options.put("auth_token", authToken);
    }
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        Supplier<List<Reward>> supplier = new FetchRewardsSupplier(options);
        CompletableFuture<List<Reward>> cf = CompletableFuture.supplyAsync(supplier, executorService);
        cf.exceptionally(e -> {
            if (activity != null) {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        ((MainActivity) activity).showError(e.getMessage());
                    }
                });
            }
            return null;
        }).thenAccept(rewards -> {
            Lbryio.updateRewardsLists(rewards);
            if (activity != null) {
                activity.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        rewardsLoading.setVisibility(View.GONE);
                        if (adapter == null) {
                            adapter = new RewardListAdapter(rewards, getContext());
                            adapter.setClickListener(RewardsFragment.this);
                            adapter.setDisplayMode(RewardListAdapter.DISPLAY_MODE_UNCLAIMED);
                            rewardList.setAdapter(adapter);
                        } else {
                            adapter.setRewards(rewards);
                        }
                        Helper.setViewVisibility(rewardList, View.VISIBLE);
                    }
                });
            }
        });
    } else {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                Callable<List<Reward>> callable = new Callable<List<Reward>>() {

                    @Override
                    public List<Reward> call() {
                        List<Reward> rewards = null;
                        try {
                            JSONArray results = (JSONArray) Lbryio.parseResponse(Lbryio.call("reward", "list", options, null));
                            rewards = new ArrayList<>();
                            if (results != null) {
                                for (int i = 0; i < results.length(); i++) {
                                    rewards.add(Reward.fromJSONObject(results.getJSONObject(i)));
                                }
                            }
                        } catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException ex) {
                            if (activity != null) {
                                activity.runOnUiThread(new Runnable() {

                                    @Override
                                    public void run() {
                                        ((MainActivity) activity).showError(ex.getMessage());
                                    }
                                });
                            }
                        }
                        return rewards;
                    }
                };
                Future<List<Reward>> future = executorService.submit(callable);
                try {
                    List<Reward> rewards = future.get();
                    if (rewards != null) {
                        Lbryio.updateRewardsLists(rewards);
                        if (activity != null) {
                            activity.runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    rewardsLoading.setVisibility(View.GONE);
                                    if (adapter == null) {
                                        adapter = new RewardListAdapter(rewards, getContext());
                                        adapter.setClickListener(RewardsFragment.this);
                                        adapter.setDisplayMode(RewardListAdapter.DISPLAY_MODE_UNCLAIMED);
                                        rewardList.setAdapter(adapter);
                                    } else {
                                        adapter.setRewards(rewards);
                                    }
                                    Helper.setViewVisibility(rewardList, View.VISIBLE);
                                }
                            });
                        }
                    }
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
Also used : Typeface(android.graphics.Typeface) Context(android.content.Context) Bundle(android.os.Bundle) ProgressBar(android.widget.ProgressBar) NonNull(androidx.annotation.NonNull) ClaimRewardTask(com.odysee.app.tasks.lbryinc.ClaimRewardTask) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) CompletableFuture(java.util.concurrent.CompletableFuture) ClaimRewardSupplier(com.odysee.app.supplier.ClaimRewardSupplier) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) MaterialButton(com.google.android.material.button.MaterialButton) MainActivity(com.odysee.app.MainActivity) Map(java.util.Map) View(android.view.View) LbryioRequestException(com.odysee.app.exceptions.LbryioRequestException) RecyclerView(androidx.recyclerview.widget.RecyclerView) Build(android.os.Build) RewardListAdapter(com.odysee.app.adapter.RewardListAdapter) ExecutorService(java.util.concurrent.ExecutorService) LbryioResponseException(com.odysee.app.exceptions.LbryioResponseException) AccountManager(android.accounts.AccountManager) AsyncTask(android.os.AsyncTask) Account(android.accounts.Account) LayoutInflater(android.view.LayoutInflater) DecimalFormat(java.text.DecimalFormat) Helper(com.odysee.app.utils.Helper) FetchRewardsSupplier(com.odysee.app.supplier.FetchRewardsSupplier) ViewGroup(android.view.ViewGroup) Executors(java.util.concurrent.Executors) Color(android.graphics.Color) ExecutionException(java.util.concurrent.ExecutionException) Lbryio(com.odysee.app.utils.Lbryio) List(java.util.List) TextView(android.widget.TextView) Reward(com.odysee.app.model.lbryinc.Reward) BaseFragment(com.odysee.app.ui.BaseFragment) LbryAnalytics(com.odysee.app.utils.LbryAnalytics) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) Activity(android.app.Activity) Snackbar(com.google.android.material.snackbar.Snackbar) EditText(android.widget.EditText) R(com.odysee.app.R) JSONArray(org.json.JSONArray) Account(android.accounts.Account) HashMap(java.util.HashMap) RewardListAdapter(com.odysee.app.adapter.RewardListAdapter) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) MainActivity(com.odysee.app.MainActivity) Activity(android.app.Activity) MainActivity(com.odysee.app.MainActivity) Callable(java.util.concurrent.Callable) FetchRewardsSupplier(com.odysee.app.supplier.FetchRewardsSupplier) ExecutorService(java.util.concurrent.ExecutorService) CompletableFuture(java.util.concurrent.CompletableFuture) Future(java.util.concurrent.Future) AccountManager(android.accounts.AccountManager) ArrayList(java.util.ArrayList) List(java.util.List) Reward(com.odysee.app.model.lbryinc.Reward)

Example 2 with LbryioRequestException

use of com.odysee.app.exceptions.LbryioRequestException in project odysee-android by OdyseeTeam.

the class Lbryio method getAuthToken.

public static String getAuthToken(Context context) throws LbryioRequestException, LbryioResponseException {
    // fetch a new auth token
    if (Helper.isNullOrEmpty(Lbry.INSTALLATION_ID)) {
        throw new LbryioRequestException("The LBRY installation ID is not set.");
    }
    generatingAuthToken = true;
    /*if (BuildConfig.DEBUG) {
            Log.d(TAG, "Generating a new auth token");
        }*/
    Map<String, String> options = new HashMap<>();
    options.put("auth_token", "");
    options.put("language", "en");
    options.put("app_id", Lbry.INSTALLATION_ID);
    Response response = Lbryio.call("user", "new", options, "post", context);
    try {
        JSONObject json = (JSONObject) parseResponse(response);
        /*if (BuildConfig.DEBUG) {
                Log.d(TAG, String.format("/user/new response: %s", json.toString(2)));
            }*/
        if (!json.has(AUTH_TOKEN_PARAM)) {
            throw new LbryioResponseException("auth_token was not set in the response");
        }
        AUTH_TOKEN = json.getString(AUTH_TOKEN_PARAM);
        broadcastAuthTokenGenerated(context);
    } catch (JSONException | ClassCastException ex) {
        LbryAnalytics.logError(String.format("/user/new failed: %s", ex.getMessage()), ex.getClass().getName());
        throw new LbryioResponseException("auth_token was not set in the response", ex);
    } finally {
        generatingAuthToken = false;
    }
    return AUTH_TOKEN;
}
Also used : Response(okhttp3.Response) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) LbryioRequestException(com.odysee.app.exceptions.LbryioRequestException) JSONException(org.json.JSONException) LbryioResponseException(com.odysee.app.exceptions.LbryioResponseException)

Example 3 with LbryioRequestException

use of com.odysee.app.exceptions.LbryioRequestException in project odysee-android by OdyseeTeam.

the class Lbryio method loadExchangeRate.

public static void loadExchangeRate() {
    try {
        JSONObject response = (JSONObject) parseResponse(Lbryio.call("lbc", "exchange_rate", null));
        LBCUSDRate = Helper.getJSONDouble("lbc_usd", 0, response);
    } catch (LbryioResponseException | LbryioRequestException | ClassCastException ex) {
    // pass
    }
}
Also used : JSONObject(org.json.JSONObject) LbryioRequestException(com.odysee.app.exceptions.LbryioRequestException) LbryioResponseException(com.odysee.app.exceptions.LbryioResponseException)

Example 4 with LbryioRequestException

use of com.odysee.app.exceptions.LbryioRequestException in project odysee-android by OdyseeTeam.

the class MainActivity method fetchRewards.

private void fetchRewards() {
    String authToken;
    AccountManager am = AccountManager.get(this);
    Account odyseeAccount = Helper.getOdyseeAccount(am.getAccounts());
    if (odyseeAccount != null) {
        authToken = am.peekAuthToken(odyseeAccount, "auth_token_type");
    } else {
        authToken = "";
    }
    Map<String, String> options = new HashMap<>();
    options.put("multiple_rewards_per_type", "true");
    if (odyseeAccount != null && authToken != null) {
        options.put("auth_token", authToken);
    }
    ExecutorService executorService = Executors.newSingleThreadExecutor();
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
        Supplier<List<Reward>> supplier = new FetchRewardsSupplier(options);
        CompletableFuture<List<Reward>> cf = CompletableFuture.supplyAsync(supplier, executorService);
        cf.exceptionally(e -> {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    showError(e.getMessage());
                }
            });
            return null;
        }).thenAccept(rewards -> {
            Lbryio.updateRewardsLists(rewards);
            if (Lbryio.totalUnclaimedRewardAmount > 0) {
                updateRewardsUsdValue();
            }
        });
    } else {
        Thread t = new Thread(new Runnable() {

            @Override
            public void run() {
                Callable<List<Reward>> callable = new Callable<List<Reward>>() {

                    @Override
                    public List<Reward> call() {
                        List<Reward> rewards = null;
                        try {
                            JSONArray results = (JSONArray) Lbryio.parseResponse(Lbryio.call("reward", "list", options, null));
                            rewards = new ArrayList<>();
                            if (results != null) {
                                for (int i = 0; i < results.length(); i++) {
                                    rewards.add(Reward.fromJSONObject(results.getJSONObject(i)));
                                }
                            }
                        } catch (ClassCastException | LbryioRequestException | LbryioResponseException | JSONException ex) {
                            runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    showError(ex.getMessage());
                                }
                            });
                        }
                        return rewards;
                    }
                };
                Future<List<Reward>> future = executorService.submit(callable);
                try {
                    List<Reward> rewards = future.get();
                    if (rewards != null) {
                        Lbryio.updateRewardsLists(rewards);
                        if (Lbryio.totalUnclaimedRewardAmount > 0) {
                            updateRewardsUsdValue();
                        }
                    }
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
Also used : Bundle(android.os.Bundle) NonNull(androidx.annotation.NonNull) SecretKeySpec(javax.crypto.spec.SecretKeySpec) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) OnBackPressedCallback(androidx.activity.OnBackPressedCallback) JSONException(org.json.JSONException) Future(java.util.concurrent.Future) FetchChannelsListener(com.odysee.app.listener.FetchChannelsListener) Handler(android.os.Handler) MediaStore(android.provider.MediaStore) Map(java.util.Map) ContextCompat(androidx.core.content.ContextCompat) Log(android.util.Log) WindowInsetsCompat(androidx.core.view.WindowInsetsCompat) RewardVerified(com.odysee.app.model.lbryinc.RewardVerified) Account(android.accounts.Account) IntentFilter(android.content.IntentFilter) FileViewFragment(com.odysee.app.ui.findcontent.FileViewFragment) Helper(com.odysee.app.utils.Helper) ActivityResultCallback(androidx.activity.result.ActivityResultCallback) SyncGetTask(com.odysee.app.tasks.wallet.SyncGetTask) WindowInsetsController(android.view.WindowInsetsController) Lbryio(com.odysee.app.utils.Lbryio) OnApplyWindowInsetsListener(androidx.core.view.OnApplyWindowInsetsListener) DialogFragment(androidx.fragment.app.DialogFragment) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UrlSuggestion(com.odysee.app.model.UrlSuggestion) SSLParameters(javax.net.ssl.SSLParameters) ClaimRewardTask(com.odysee.app.tasks.lbryinc.ClaimRewardTask) PlayerView(com.google.android.exoplayer2.ui.PlayerView) LbryUriException(com.odysee.app.exceptions.LbryUriException) Supplier(java.util.function.Supplier) PlayerNotificationManager(com.google.android.exoplayer2.ui.PlayerNotificationManager) ExoPlayer(com.google.android.exoplayer2.ExoPlayer) Toast(android.widget.Toast) Menu(android.view.Menu) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LbryUri(com.odysee.app.utils.LbryUri) CipherOutputStream(javax.crypto.CipherOutputStream) PurchasedChecker(com.odysee.app.utils.PurchasedChecker) FragmentManager(androidx.fragment.app.FragmentManager) CustomTarget(com.bumptech.glide.request.target.CustomTarget) ComponentName(android.content.ComponentName) SyncSetTask(com.odysee.app.tasks.wallet.SyncSetTask) AppCompatDelegate(androidx.appcompat.app.AppCompatDelegate) FetchRewardsSupplier(com.odysee.app.supplier.FetchRewardsSupplier) InputStreamReader(java.io.InputStreamReader) CameraPermissionListener(com.odysee.app.listener.CameraPermissionListener) ExecutionException(java.util.concurrent.ExecutionException) SettingsFragment(com.odysee.app.ui.other.SettingsFragment) OkHttpClient(okhttp3.OkHttpClient) SharedPreferences(android.content.SharedPreferences) AndroidPurchaseTask(com.odysee.app.tasks.lbryinc.AndroidPurchaseTask) PreferenceManager(androidx.preference.PreferenceManager) EditText(android.widget.EditText) NotificationDeleteTask(com.odysee.app.tasks.lbryinc.NotificationDeleteTask) ImageButton(android.widget.ImageButton) FetchRecentUrlHistoryTask(com.odysee.app.tasks.localdata.FetchRecentUrlHistoryTask) PackageManager(android.content.pm.PackageManager) Date(java.util.Date) WindowManager(android.view.WindowManager) Animator(android.animation.Animator) MediaSessionCompat(android.support.v4.media.session.MediaSessionCompat) Player(com.google.android.exoplayer2.Player) WalletBalance(com.odysee.app.model.WalletBalance) TypefaceSpan(android.text.style.TypefaceSpan) CustomTabsIntent(androidx.browser.customtabs.CustomTabsIntent) LoadSharedUserStateTask(com.odysee.app.tasks.wallet.LoadSharedUserStateTask) SQLiteException(android.database.sqlite.SQLiteException) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) SelectionModeListener(com.odysee.app.listener.SelectionModeListener) Locale(java.util.Locale) MergeSubscriptionsTask(com.odysee.app.tasks.MergeSubscriptionsTask) ActivityInfo(android.content.pm.ActivityInfo) Button(android.widget.Button) RecyclerView(androidx.recyclerview.widget.RecyclerView) RewardVerifiedHandler(com.odysee.app.tasks.RewardVerifiedHandler) AsyncTask(android.os.AsyncTask) UrlSuggestionListAdapter(com.odysee.app.adapter.UrlSuggestionListAdapter) KeyStore(java.security.KeyStore) GenericTaskHandler(com.odysee.app.tasks.GenericTaskHandler) Claim(com.odysee.app.model.Claim) MediaButtonReceiver(androidx.media.session.MediaButtonReceiver) Key(java.security.Key) WalletBalanceListener(com.odysee.app.listener.WalletBalanceListener) WindowInsets(android.view.WindowInsets) Toolbar(androidx.appcompat.widget.Toolbar) GetLocalNotificationsSupplier(com.odysee.app.supplier.GetLocalNotificationsSupplier) ListView(android.widget.ListView) PictureInPictureParams(android.app.PictureInPictureParams) EditorInfo(android.view.inputmethod.EditorInfo) ServerHandshake(org.java_websocket.handshake.ServerHandshake) TextInputEditText(com.google.android.material.textfield.TextInputEditText) AlertDialog(androidx.appcompat.app.AlertDialog) ResolveTask(com.odysee.app.tasks.claim.ResolveTask) ClaimListResultHandler(com.odysee.app.tasks.claim.ClaimListResultHandler) Lbry(com.odysee.app.utils.Lbry) SaveSharedUserStateTask(com.odysee.app.tasks.wallet.SaveSharedUserStateTask) CompletableFuture(java.util.concurrent.CompletableFuture) Cipher(javax.crypto.Cipher) NavigationBarView(com.google.android.material.navigation.NavigationBarView) MenuItem(android.view.MenuItem) InputMethodManager(android.view.inputmethod.InputMethodManager) Level(java.util.logging.Level) CipherInputStream(javax.crypto.CipherInputStream) MaterialButton(com.google.android.material.button.MaterialButton) LbryioRequestException(com.odysee.app.exceptions.LbryioRequestException) Build(android.os.Build) ExecutorService(java.util.concurrent.ExecutorService) LbryioResponseException(com.odysee.app.exceptions.LbryioResponseException) FollowingFragment(com.odysee.app.ui.findcontent.FollowingFragment) CustomTabColorSchemeParams(androidx.browser.customtabs.CustomTabColorSchemeParams) LibraryFragment(com.odysee.app.ui.library.LibraryFragment) ActivityResultLauncher(androidx.activity.result.ActivityResultLauncher) ContentScopeDialogFragment(com.odysee.app.dialog.ContentScopeDialogFragment) ApiCallException(com.odysee.app.exceptions.ApiCallException) LayoutInflater(android.view.LayoutInflater) SearchFragment(com.odysee.app.ui.findcontent.SearchFragment) Tag(com.odysee.app.model.Tag) DecimalFormat(java.text.DecimalFormat) PublicKey(java.security.PublicKey) FileInputStream(java.io.FileInputStream) ActionMode(androidx.appcompat.view.ActionMode) Color(android.graphics.Color) NotificationListSupplier(com.odysee.app.supplier.NotificationListSupplier) Bitmap(android.graphics.Bitmap) Transition(com.bumptech.glide.request.transition.Transition) Base64(android.util.Base64) LbryAnalytics(com.odysee.app.utils.LbryAnalytics) ViewTreeObserver(android.view.ViewTreeObserver) Activity(android.app.Activity) JSONArray(org.json.JSONArray) Arrays(java.util.Arrays) Uri(android.net.Uri) ImageView(android.widget.ImageView) Drawable(android.graphics.drawable.Drawable) AppCompatActivity(androidx.appcompat.app.AppCompatActivity) SecureRandom(java.security.SecureRandom) ActionBar(androidx.appcompat.app.ActionBar) Looper(android.os.Looper) NotificationManagerCompat(androidx.core.app.NotificationManagerCompat) Fragment(androidx.fragment.app.Fragment) AuthTokenInvalidatedException(com.odysee.app.exceptions.AuthTokenInvalidatedException) AccountManager(android.accounts.AccountManager) ViewCompat(androidx.core.view.ViewCompat) StartupStageAdapter(com.odysee.app.adapter.StartupStageAdapter) PublishFragment(com.odysee.app.ui.publish.PublishFragment) AnimatorListenerAdapter(android.animation.AnimatorListenerAdapter) NotificationUpdateSupplier(com.odysee.app.supplier.NotificationUpdateSupplier) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) ClaimCacheKey(com.odysee.app.model.ClaimCacheKey) InvitesFragment(com.odysee.app.ui.wallet.InvitesFragment) Nullable(androidx.annotation.Nullable) PrivateKey(java.security.PrivateKey) ActivityResultContracts(androidx.activity.result.contract.ActivityResultContracts) Subscription(com.odysee.app.model.lbryinc.Subscription) StoragePermissionListener(com.odysee.app.listener.StoragePermissionListener) LinearLayoutManager(androidx.recyclerview.widget.LinearLayoutManager) TextWatcher(android.text.TextWatcher) com.odysee.app.ui.channel(com.odysee.app.ui.channel) FetchClaimsListener(com.odysee.app.listener.FetchClaimsListener) MediaSessionConnector(com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector) Utils(com.odysee.app.utils.Utils) SimpleDateFormat(java.text.SimpleDateFormat) Callable(java.util.concurrent.Callable) Editable(android.text.Editable) ScreenOrientationListener(com.odysee.app.listener.ScreenOrientationListener) ArrayList(java.util.ArrayList) PIPModeListener(com.odysee.app.listener.PIPModeListener) PlaylistFragment(com.odysee.app.ui.library.PlaylistFragment) RewardsFragment(com.odysee.app.ui.wallet.RewardsFragment) SpannableString(android.text.SpannableString) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) SyncApplyTask(com.odysee.app.tasks.wallet.SyncApplyTask) File(java.io.File) Gravity(android.view.Gravity) DownloadActionListener(com.odysee.app.listener.DownloadActionListener) UnlockingTipsSupplier(com.odysee.app.supplier.UnlockingTipsSupplier) Configuration(android.content.res.Configuration) BufferedReader(java.io.BufferedReader) ValueAnimator(android.animation.ValueAnimator) FirebaseMessagingToken(com.odysee.app.utils.FirebaseMessagingToken) ScheduledFuture(java.util.concurrent.ScheduledFuture) SneakyThrows(lombok.SneakyThrows) ClaimListTask(com.odysee.app.tasks.claim.ClaimListTask) Spannable(android.text.Spannable) PendingIntent(android.app.PendingIntent) LbryNotification(com.odysee.app.model.lbryinc.LbryNotification) ActionBarDrawerToggle(androidx.appcompat.app.ActionBarDrawerToggle) NotificationChannel(android.app.NotificationChannel) View(android.view.View) URI(java.net.URI) WebView(android.webkit.WebView) Cache(com.google.android.exoplayer2.upstream.cache.Cache) ParseException(java.text.ParseException) BottomNavigationView(com.google.android.material.bottomnavigation.BottomNavigationView) OdyseeCollection(com.odysee.app.model.OdyseeCollection) NotificationManager(android.app.NotificationManager) StartupStage(com.odysee.app.model.StartupStage) FragmentTransaction(androidx.fragment.app.FragmentTransaction) WalletBalanceFetch(com.odysee.app.callable.WalletBalanceFetch) Logger(java.util.logging.Logger) BroadcastReceiver(android.content.BroadcastReceiver) WalletFragment(com.odysee.app.ui.wallet.WalletFragment) ViewGroup(android.view.ViewGroup) List(java.util.List) TextView(android.widget.TextView) Reward(com.odysee.app.model.lbryinc.Reward) FileProvider(androidx.core.content.FileProvider) BaseFragment(com.odysee.app.ui.BaseFragment) RelativeLayout(android.widget.RelativeLayout) NotNull(org.jetbrains.annotations.NotNull) Snackbar(com.google.android.material.snackbar.Snackbar) NotificationListAdapter(com.odysee.app.adapter.NotificationListAdapter) DecelerateInterpolator(android.view.animation.DecelerateInterpolator) Context(android.content.Context) Setter(lombok.Setter) KeyEvent(android.view.KeyEvent) WebSocketClient(org.java_websocket.client.WebSocketClient) Getter(lombok.Getter) Intent(android.content.Intent) LocalBroadcastManager(androidx.localbroadcastmanager.content.LocalBroadcastManager) HashMap(java.util.HashMap) OnAccountsUpdateListener(android.accounts.OnAccountsUpdateListener) ClipData(android.content.ClipData) SuppressLint(android.annotation.SuppressLint) ContentSources(com.odysee.app.utils.ContentSources) AddToListsDialogFragment(com.odysee.app.dialog.AddToListsDialogFragment) DialogInterface(android.content.DialogInterface) ActivityCompat(androidx.core.app.ActivityCompat) PopupWindow(android.widget.PopupWindow) WalletSync(com.odysee.app.model.WalletSync) TimeUnit(java.util.concurrent.TimeUnit) DefaultSyncTaskHandler(com.odysee.app.tasks.wallet.DefaultSyncTaskHandler) Glide(com.bumptech.glide.Glide) FilePickerListener(com.odysee.app.listener.FilePickerListener) AllContentFragment(com.odysee.app.ui.findcontent.AllContentFragment) DatabaseHelper(com.odysee.app.data.DatabaseHelper) Collections(java.util.Collections) PublishesFragment(com.odysee.app.ui.publish.PublishesFragment) ActivityResult(androidx.activity.result.ActivityResult) Account(android.accounts.Account) HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) ArrayList(java.util.ArrayList) SpannableString(android.text.SpannableString) Callable(java.util.concurrent.Callable) FetchRewardsSupplier(com.odysee.app.supplier.FetchRewardsSupplier) 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) AccountManager(android.accounts.AccountManager) ArrayList(java.util.ArrayList) List(java.util.List) Reward(com.odysee.app.model.lbryinc.Reward)

Example 5 with LbryioRequestException

use of com.odysee.app.exceptions.LbryioRequestException in project odysee-android by OdyseeTeam.

the class MainActivity method updateLocalNotifications.

private void updateLocalNotifications(List<LbryNotification> notifications) {
    findViewById(R.id.notification_list_empty_container).setVisibility(notifications.isEmpty() ? View.VISIBLE : View.GONE);
    findViewById(R.id.notifications_progress).setVisibility(View.GONE);
    loadUnseenNotificationsCount();
    if (notificationListAdapter == null) {
        notificationListAdapter = new NotificationListAdapter(notifications, MainActivity.this);
        notificationListAdapter.setSelectionModeListener(MainActivity.this);
        ((RecyclerView) findViewById(R.id.notifications_list)).setAdapter(notificationListAdapter);
    } else {
        notificationListAdapter.addNotifications(notifications);
    }
    resolveCommentAuthors(notificationListAdapter.getAuthorUrls());
    notificationListAdapter.setClickListener(new NotificationListAdapter.NotificationClickListener() {

        @Override
        public void onNotificationClicked(LbryNotification notification) {
            // set as seen and read
            Map<String, String> options = new HashMap<>();
            options.put("notification_ids", String.valueOf(notification.getRemoteId()));
            options.put("is_seen", "true");
            // so let's not mark the notification as read
            if (!notification.getTargetUrl().equalsIgnoreCase("lbry://?subscriptions")) {
                options.put("is_read", "true");
            } else {
                options.put("is_read", "false");
            }
            AccountManager am = AccountManager.get(getApplicationContext());
            if (am != null) {
                String at = am.peekAuthToken(Helper.getOdyseeAccount(am.getAccounts()), "auth_token_type");
                if (at != null)
                    options.put("auth_token", at);
            }
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                Supplier<Boolean> supplier = new NotificationUpdateSupplier(options);
                CompletableFuture.supplyAsync(supplier);
            } else {
                Thread t = new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Lbryio.call("notification", "edit", options, null);
                        } catch (LbryioResponseException | LbryioRequestException e) {
                            e.printStackTrace();
                        }
                    }
                });
                t.start();
            }
            if (!notification.getTargetUrl().equalsIgnoreCase("lbry://?subscriptions")) {
                markNotificationReadAndSeen(notification.getId());
            }
            String targetUrl = notification.getTargetUrl();
            if (targetUrl.startsWith(SPECIAL_URL_PREFIX)) {
                openSpecialUrl(targetUrl, "notification");
            } else {
                LbryUri target = LbryUri.tryParse(notification.getTargetUrl());
                if (target != null) {
                    if (target.isChannel()) {
                        openChannelUrl(notification.getTargetUrl(), "notification");
                    } else {
                        openFileUrl(notification.getTargetUrl(), "notification");
                    }
                }
            }
            hideNotifications(false);
        }
    });
}
Also used : LbryioRequestException(com.odysee.app.exceptions.LbryioRequestException) SpannableString(android.text.SpannableString) LbryNotification(com.odysee.app.model.lbryinc.LbryNotification) NotificationUpdateSupplier(com.odysee.app.supplier.NotificationUpdateSupplier) NotificationListAdapter(com.odysee.app.adapter.NotificationListAdapter) RecyclerView(androidx.recyclerview.widget.RecyclerView) AccountManager(android.accounts.AccountManager) Supplier(java.util.function.Supplier) FetchRewardsSupplier(com.odysee.app.supplier.FetchRewardsSupplier) GetLocalNotificationsSupplier(com.odysee.app.supplier.GetLocalNotificationsSupplier) NotificationListSupplier(com.odysee.app.supplier.NotificationListSupplier) NotificationUpdateSupplier(com.odysee.app.supplier.NotificationUpdateSupplier) UnlockingTipsSupplier(com.odysee.app.supplier.UnlockingTipsSupplier) LbryUri(com.odysee.app.utils.LbryUri) Map(java.util.Map) HashMap(java.util.HashMap) LbryioResponseException(com.odysee.app.exceptions.LbryioResponseException)

Aggregations

LbryioRequestException (com.odysee.app.exceptions.LbryioRequestException)17 LbryioResponseException (com.odysee.app.exceptions.LbryioResponseException)16 JSONObject (org.json.JSONObject)13 HashMap (java.util.HashMap)11 JSONException (org.json.JSONException)7 JSONArray (org.json.JSONArray)5 AccountManager (android.accounts.AccountManager)4 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 Supplier (java.util.function.Supplier)4 Response (okhttp3.Response)4 Account (android.accounts.Account)3 Activity (android.app.Activity)3 RecyclerView (androidx.recyclerview.widget.RecyclerView)3 MainActivity (com.odysee.app.MainActivity)3 LbryNotification (com.odysee.app.model.lbryinc.LbryNotification)3 Reward (com.odysee.app.model.lbryinc.Reward)3 FetchRewardsSupplier (com.odysee.app.supplier.FetchRewardsSupplier)3 Context (android.content.Context)2 Color (android.graphics.Color)2