Search in sources :

Example 16 with ApiCallException

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

the class FileViewFragment method loadReactions.

private Map<String, Reactions> loadReactions(List<Comment> comments) {
    List<String> commentIds = new ArrayList<>();
    for (Comment c : comments) {
        commentIds.add(c.getId());
    }
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Map<String, Reactions>> future = executor.submit(() -> {
        Comments.checkCommentsEndpointStatus();
        JSONObject jsonParams = new JSONObject();
        jsonParams.put("comment_ids", TextUtils.join(",", commentIds));
        AccountManager am = AccountManager.get(getContext());
        Account odyseeAccount = Helper.getOdyseeAccount(am.getAccounts());
        if (odyseeAccount != null) {
            jsonParams.put("auth_token", am.peekAuthToken(odyseeAccount, "auth_token_type"));
        }
        if (!Lbry.ownChannels.isEmpty()) {
            jsonParams.put("channel_id", Lbry.ownChannels.get(0).getClaimId());
            jsonParams.put("channel_name", Lbry.ownChannels.get(0).getName());
            try {
                JSONObject jsonChannelSign = Comments.channelSignName(jsonParams, jsonParams.getString("channel_id"), jsonParams.getString("channel_name"));
                if (jsonChannelSign.has("signature") && jsonChannelSign.has("signing_ts")) {
                    jsonParams.put("signature", jsonChannelSign.getString("signature"));
                    jsonParams.put("signing_ts", jsonChannelSign.getString("signing_ts"));
                }
            } catch (ApiCallException | JSONException e) {
                e.printStackTrace();
            }
        }
        Map<String, Reactions> result = new HashMap<>();
        try {
            Response response = Comments.performRequest(jsonParams, "reaction.List");
            String responseString = response.body().string();
            response.close();
            JSONObject jsonResponse = new JSONObject(responseString);
            if (jsonResponse.has("result")) {
                JSONObject jsonResult = jsonResponse.getJSONObject("result");
                if (jsonResult.has("others_reactions")) {
                    JSONObject responseOthersReactions = jsonResult.getJSONObject("others_reactions");
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                        responseOthersReactions.keys().forEachRemaining(key -> {
                            try {
                                result.put(key, getMyReactions(jsonResult, responseOthersReactions, key));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        });
                    } else {
                        // Android versions prior to API 24 lack forEachRemaining()
                        Iterator<String> itr = responseOthersReactions.keys();
                        while (itr.hasNext()) {
                            try {
                                String nextKey = itr.next();
                                result.put(nextKey, getMyReactions(jsonResult, responseOthersReactions, nextKey));
                            } catch (JSONException e) {
                                Log.e(TAG, "loadReactions for Comment: ".concat(e.getLocalizedMessage()));
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    });
    try {
        return future.get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
        return null;
    }
}
Also used : Comment(com.odysee.app.model.Comment) ReactToComment(com.odysee.app.runnable.ReactToComment) Account(android.accounts.Account) ApiCallException(com.odysee.app.exceptions.ApiCallException) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Reactions(com.odysee.app.model.Reactions) JSONException(org.json.JSONException) IOException(java.io.IOException) Response(okhttp3.Response) JSONObject(org.json.JSONObject) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ExecutorService(java.util.concurrent.ExecutorService) AccountManager(android.accounts.AccountManager) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap)

Example 17 with ApiCallException

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

the class LoadSharedUserStateTask method doInBackground.

protected Boolean doInBackground(Void... params) {
    // Get the previous saved state
    try {
        SQLiteDatabase db = null;
        JSONObject result = (JSONObject) Lbry.authenticatedGenericApiCall(Lbry.METHOD_PREFERENCE_GET, Lbry.buildSingleParam("key", KEY), authToken);
        if (result != null) {
            MainActivity activity = null;
            if (context instanceof MainActivity) {
                activity = (MainActivity) context;
                db = activity.getDbHelper().getWritableDatabase();
            }
            // get the built in collections
            Map<String, OdyseeCollection> allCollections = null;
            OdyseeCollection favoritesPlaylist = null;
            OdyseeCollection watchlaterPlaylist = null;
            if (db != null) {
                allCollections = DatabaseHelper.loadAllCollections(db);
                favoritesPlaylist = allCollections.get(OdyseeCollection.BUILT_IN_ID_FAVORITES);
                watchlaterPlaylist = allCollections.get(OdyseeCollection.BUILT_IN_ID_WATCHLATER);
            }
            JSONObject shared = result.getJSONObject("shared");
            if (shared.has("type") && "object".equalsIgnoreCase(shared.getString("type")) && shared.has("value")) {
                JSONObject value = shared.getJSONObject("value");
                JSONArray tags = value.has("tags") && !value.isNull("tags") ? value.getJSONArray("tags") : null;
                JSONArray blocked = value.has("blocked") && !value.isNull("blocked") ? value.getJSONArray("blocked") : null;
                JSONObject builtInCollections = Helper.getJSONObject("builtinCollections", value);
                OdyseeCollection favoritesCollection = OdyseeCollection.fromJSONObject(OdyseeCollection.BUILT_IN_ID_FAVORITES, OdyseeCollection.VISIBILITY_PRIVATE, Helper.getJSONObject(OdyseeCollection.BUILT_IN_ID_FAVORITES, builtInCollections));
                OdyseeCollection watchLaterCollection = OdyseeCollection.fromJSONObject(OdyseeCollection.BUILT_IN_ID_WATCHLATER, OdyseeCollection.VISIBILITY_PRIVATE, Helper.getJSONObject(OdyseeCollection.BUILT_IN_ID_WATCHLATER, builtInCollections));
                if (activity != null) {
                    if (favoritesPlaylist == null || favoritesCollection.getUpdatedAtTimestamp() > favoritesPlaylist.getUpdatedAtTimestamp()) {
                        // only replace the locally saved collections if there are items
                        DatabaseHelper.saveCollection(favoritesCollection, db);
                    }
                    if (watchlaterPlaylist == null || watchLaterCollection.getUpdatedAtTimestamp() > watchlaterPlaylist.getUpdatedAtTimestamp()) {
                        DatabaseHelper.saveCollection(watchLaterCollection, db);
                    }
                }
                JSONObject unpublishedCollections = Helper.getJSONObject("unpublishedCollections", value);
                Iterator<String> pcIdsIterator = unpublishedCollections.keys();
                while (pcIdsIterator.hasNext()) {
                    String collectionId = pcIdsIterator.next();
                    JSONObject jsonCollection = Helper.getJSONObject(collectionId, unpublishedCollections);
                    OdyseeCollection thisCollection = OdyseeCollection.fromJSONObject(collectionId, OdyseeCollection.VISIBILITY_PRIVATE, jsonCollection);
                    boolean shouldSave = true;
                    if (allCollections.containsKey(collectionId)) {
                        OdyseeCollection priorLocalCollection = allCollections.get(collectionId);
                        shouldSave = thisCollection.getUpdatedAtTimestamp() > priorLocalCollection.getUpdatedAtTimestamp();
                    }
                    if (shouldSave) {
                        DatabaseHelper.saveCollection(thisCollection, db);
                    }
                }
                subscriptions = loadSubscriptionsFromSharedUserState(shared);
                if (db != null) {
                    for (Subscription subscription : subscriptions) {
                        try {
                            DatabaseHelper.createOrUpdateSubscription(subscription, db);
                        } catch (IllegalStateException ex) {
                        // pass
                        }
                    }
                }
                if (tags != null) {
                    if (db != null && tags.length() > 0) {
                        try {
                            DatabaseHelper.setAllTagsUnfollowed(db);
                        } catch (IllegalStateException ex) {
                        // pass
                        }
                    }
                    followedTags = new ArrayList<>();
                    for (int i = 0; i < tags.length(); i++) {
                        String tagName = tags.getString(i);
                        Tag tag = new Tag(tagName);
                        tag.setFollowed(true);
                        followedTags.add(tag);
                        try {
                            if (db != null) {
                                DatabaseHelper.createOrUpdateTag(tag, db);
                            }
                        } catch (SQLiteException | IllegalStateException ex) {
                        // pass
                        }
                    }
                }
                if (blocked != null) {
                    blockedChannels = new ArrayList<>();
                    if (db != null) {
                        for (int i = 0; i < blocked.length(); i++) {
                            LbryUri uri = LbryUri.tryParse(blocked.getString(i));
                            if (uri != null) {
                                blockedChannels.add(uri);
                                DatabaseHelper.createOrUpdateBlockedChannel(uri.getClaimId(), uri.getClaimName(), db);
                            }
                        }
                    }
                }
            }
        }
        return true;
    } catch (ApiCallException | JSONException ex) {
        // failed
        error = ex;
    }
    return false;
}
Also used : ApiCallException(com.odysee.app.exceptions.ApiCallException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) MainActivity(com.odysee.app.MainActivity) OdyseeCollection(com.odysee.app.model.OdyseeCollection) SQLiteException(android.database.sqlite.SQLiteException) JSONObject(org.json.JSONObject) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) Tag(com.odysee.app.model.Tag) Subscription(com.odysee.app.model.lbryinc.Subscription) LbryUri(com.odysee.app.utils.LbryUri)

Example 18 with ApiCallException

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

the class SyncApplyTask method doInBackground.

public Boolean doInBackground(Void... params) {
    Map<String, Object> options = new HashMap<>();
    options.put("password", Helper.isNullOrEmpty(password) ? "" : password);
    if (!fetch) {
        options.put("data", data);
        options.put("blocking", true);
    }
    try {
        JSONObject response = (JSONObject) Lbry.authenticatedGenericApiCall(Lbry.METHOD_SYNC_APPLY, options, Lbryio.AUTH_TOKEN);
        syncHash = Helper.getJSONString("hash", null, response);
        syncData = Helper.getJSONString("data", null, response);
    } catch (ApiCallException ex) {
        error = ex;
        return false;
    }
    return true;
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) ApiCallException(com.odysee.app.exceptions.ApiCallException) JSONObject(org.json.JSONObject)

Example 19 with ApiCallException

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

the class SyncGetTask method doInBackground.

protected WalletSync doInBackground(Void... params) {
    try {
        password = Helper.isNullOrEmpty(password) ? "" : password;
        JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_WALLET_STATUS, Lbryio.AUTH_TOKEN);
        boolean isLocked = Helper.getJSONBoolean("is_locked", false, result);
        boolean unlockSuccessful = !isLocked || (boolean) Lbry.authenticatedGenericApiCall(Lbry.METHOD_WALLET_UNLOCK, Lbry.buildSingleParam("password", password), Lbryio.AUTH_TOKEN);
        if (!unlockSuccessful) {
            throw new WalletException("The wallet could not be unlocked with the provided password.");
        }
        String hash = (String) Lbry.authenticatedGenericApiCall(Lbry.METHOD_SYNC_HASH, null, Lbryio.AUTH_TOKEN);
        try {
            JSONObject response = (JSONObject) Lbryio.parseResponse(Lbryio.call("sync", "get", Lbryio.buildSingleParam("hash", hash), Helper.METHOD_POST, null));
            WalletSync walletSync = new WalletSync(Helper.getJSONString("hash", null, response), Helper.getJSONString("data", null, response), Helper.getJSONBoolean("changed", false, response));
            if (applySyncChanges && (!hash.equalsIgnoreCase(walletSync.getHash()) || walletSync.isChanged())) {
                // Lbry.sync_apply({ password, data: response.data, blocking: true });
                try {
                    Map<String, Object> options = new HashMap<>();
                    options.put("password", Helper.isNullOrEmpty(password) ? "" : password);
                    options.put("data", walletSync.getData());
                    options.put("blocking", true);
                    JSONObject syncApplyResponse = (JSONObject) Lbry.authenticatedGenericApiCall(Lbry.METHOD_SYNC_APPLY, options, Lbryio.AUTH_TOKEN);
                    syncHash = Helper.getJSONString("hash", null, syncApplyResponse);
                    syncData = Helper.getJSONString("data", null, syncApplyResponse);
                    applySyncSuccessful = true;
                } catch (ApiCallException | ClassCastException ex) {
                    // sync_apply failed
                    syncApplyError = ex;
                }
            }
            if (Lbryio.isSignedIn() && !Lbryio.userHasSyncedWallet) {
                // indicate that the user owns a synced wallet (only if the user is signed in)
                Lbryio.userHasSyncedWallet = true;
            }
            return walletSync;
        } catch (LbryioResponseException ex) {
            // wallet sync data doesn't exist
            return null;
        }
    } catch (ApiCallException | WalletException | ClassCastException | LbryioRequestException ex) {
        error = ex;
        return null;
    }
}
Also used : WalletException(com.odysee.app.exceptions.WalletException) HashMap(java.util.HashMap) ApiCallException(com.odysee.app.exceptions.ApiCallException) LbryioRequestException(com.odysee.app.exceptions.LbryioRequestException) WalletSync(com.odysee.app.model.WalletSync) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) LbryioResponseException(com.odysee.app.exceptions.LbryioResponseException)

Example 20 with ApiCallException

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

the class PurchaseListTask method doInBackground.

protected List<Claim> doInBackground(Void... params) {
    List<Claim> claims = null;
    try {
        Map<String, Object> options = new HashMap<>();
        if (!Helper.isNullOrEmpty(claimId)) {
            options.put("claim_id", claimId);
        }
        if (page > 0) {
            options.put("page", page);
        }
        if (pageSize > 0) {
            options.put("page_size", pageSize);
        }
        options.put("resolve", true);
        JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PURCHASE_LIST, options);
        JSONArray items = result.getJSONArray("items");
        claims = new ArrayList<>();
        for (int i = 0; i < items.length(); i++) {
            Claim claim = Claim.fromJSONObject(items.getJSONObject(i).getJSONObject("claim"));
            if (!Helper.isNullOrEmpty(claim.getClaimId())) {
                claims.add(claim);
                Lbry.addClaimToCache(claim);
            }
        }
    } catch (ApiCallException | JSONException | ClassCastException ex) {
        error = ex;
    }
    return claims;
}
Also used : HashMap(java.util.HashMap) ApiCallException(com.odysee.app.exceptions.ApiCallException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) Claim(com.odysee.app.model.Claim)

Aggregations

ApiCallException (com.odysee.app.exceptions.ApiCallException)31 JSONObject (org.json.JSONObject)28 HashMap (java.util.HashMap)22 JSONException (org.json.JSONException)17 Claim (com.odysee.app.model.Claim)10 JSONArray (org.json.JSONArray)10 ArrayList (java.util.ArrayList)8 LbryRequestException (com.odysee.app.exceptions.LbryRequestException)7 LbryResponseException (com.odysee.app.exceptions.LbryResponseException)7 MainActivity (com.odysee.app.MainActivity)6 DecimalFormat (java.text.DecimalFormat)5 DecimalFormatSymbols (java.text.DecimalFormatSymbols)5 LinkedHashMap (java.util.LinkedHashMap)5 ExecutorService (java.util.concurrent.ExecutorService)5 AccountManager (android.accounts.AccountManager)4 Response (okhttp3.Response)4 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)3 View (android.view.View)3 TextView (android.widget.TextView)3 Subscription (com.odysee.app.model.lbryinc.Subscription)3