Search in sources :

Example 6 with ApiCallException

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

the class SaveSharedUserStateTask method doInBackground.

protected Boolean doInBackground(Void... params) {
    boolean loadedSubs = false;
    boolean loadedBlocked = false;
    SQLiteDatabase db = null;
    if (context instanceof MainActivity) {
        db = ((MainActivity) context).getDbHelper().getReadableDatabase();
    }
    // data to save
    // current subscriptions
    List<Subscription> subs = new ArrayList<>();
    try {
        if (db != null) {
            subs = new ArrayList<>(DatabaseHelper.getSubscriptions(db));
            loadedSubs = true;
        }
    } catch (SQLiteException ex) {
    // pass
    }
    List<String> subscriptionUrls = new ArrayList<>();
    try {
        for (Subscription subscription : subs) {
            LbryUri uri = LbryUri.parse(LbryUri.normalize(subscription.getUrl()));
            subscriptionUrls.add(uri.toString());
        }
    } catch (LbryUriException ex) {
        error = ex;
        return false;
    }
    // followed tags
    List<String> followedTags = Helper.getTagsForTagObjects(Lbry.followedTags);
    // blocked channels
    List<LbryUri> blockedChannels = new ArrayList<>();
    try {
        if (db != null) {
            blockedChannels = new ArrayList<>(DatabaseHelper.getBlockedChannels(db));
            loadedBlocked = true;
        }
    } catch (SQLiteException ex) {
    // pass
    }
    List<String> blockedChannelUrls = new ArrayList<>();
    for (LbryUri uri : blockedChannels) {
        blockedChannelUrls.add(uri.toString());
    }
    Map<String, OdyseeCollection> allCollections = null;
    OdyseeCollection favoritesPlaylist = null;
    OdyseeCollection watchlaterPlaylist = null;
    if (db != null) {
        allCollections = DatabaseHelper.loadAllCollections(db);
        // get the built in collections
        favoritesPlaylist = allCollections.get(OdyseeCollection.BUILT_IN_ID_FAVORITES);
        watchlaterPlaylist = allCollections.get(OdyseeCollection.BUILT_IN_ID_WATCHLATER);
    }
    // Get the previous saved state
    try {
        boolean isExistingValid = false;
        JSONObject sharedObject = null;
        JSONObject result = (JSONObject) Lbry.authenticatedGenericApiCall(Lbry.METHOD_PREFERENCE_GET, Lbry.buildSingleParam("key", KEY), authToken);
        if (result != null) {
            JSONObject shared = result.getJSONObject("shared");
            if (shared.has("type") && "object".equalsIgnoreCase(shared.getString("type")) && shared.has("value")) {
                isExistingValid = true;
                JSONObject value = shared.getJSONObject("value");
                if (loadedSubs) {
                    // make sure the subs were actually loaded from the local store before overwriting the data
                    value.put("subscriptions", Helper.jsonArrayFromList(subscriptionUrls));
                    value.put("following", buildUpdatedNotificationsDisabledStates(subs));
                }
                value.put("tags", Helper.jsonArrayFromList(followedTags));
                if (loadedBlocked) {
                    // make sure blocked list was actually loaded from the local store before overwriting
                    value.put("blocked", Helper.jsonArrayFromList(blockedChannelUrls));
                }
                // handle builtInCollections
                // check favorites last updated at, and compare
                JSONObject builtinCollections = Helper.getJSONObject("builtinCollections", value);
                if (builtinCollections != null) {
                    if (favoritesPlaylist != null) {
                        JSONObject priorFavorites = Helper.getJSONObject(favoritesPlaylist.getId(), builtinCollections);
                        long priorFavUpdatedAt = Helper.getJSONLong("updatedAt", 0, priorFavorites);
                        if (priorFavUpdatedAt < favoritesPlaylist.getUpdatedAtTimestamp()) {
                            // the current playlist is newer, so we replace
                            builtinCollections.put(favoritesPlaylist.getId(), favoritesPlaylist.toJSONObject());
                        }
                    }
                    if (watchlaterPlaylist != null) {
                        JSONObject priorWatchLater = Helper.getJSONObject(watchlaterPlaylist.getId(), builtinCollections);
                        long priorWatchLaterUpdatedAt = Helper.getJSONLong("updatedAt", 0, priorWatchLater);
                        if (priorWatchLaterUpdatedAt < watchlaterPlaylist.getUpdatedAtTimestamp()) {
                            // the current playlist is newer, so we replace
                            builtinCollections.put(watchlaterPlaylist.getId(), watchlaterPlaylist.toJSONObject());
                        }
                    }
                }
                // handle unpublishedCollections
                JSONObject unpublishedCollections = Helper.getJSONObject("unpublishedCollections", value);
                if (unpublishedCollections != null && allCollections != null) {
                    for (Map.Entry<String, OdyseeCollection> entry : allCollections.entrySet()) {
                        String collectionId = entry.getKey();
                        if (Arrays.asList(OdyseeCollection.BUILT_IN_ID_FAVORITES, OdyseeCollection.BUILT_IN_ID_WATCHLATER).contains(collectionId)) {
                            continue;
                        }
                        OdyseeCollection localCollection = entry.getValue();
                        if (localCollection.getVisibility() != OdyseeCollection.VISIBILITY_PRIVATE) {
                            continue;
                        }
                        JSONObject priorCollection = Helper.getJSONObject(collectionId, unpublishedCollections);
                        if (priorCollection != null) {
                            long priorCollectionUpdatedAt = Helper.getJSONLong("updatedAt", 0, priorCollection);
                            if (priorCollectionUpdatedAt < localCollection.getUpdatedAtTimestamp()) {
                                unpublishedCollections.put(collectionId, localCollection.toJSONObject());
                            }
                        } else {
                            unpublishedCollections.put(collectionId, localCollection.toJSONObject());
                        }
                    }
                }
                sharedObject = shared;
            }
        }
        if (!isExistingValid) {
            // build a  new object
            JSONObject value = new JSONObject();
            value.put("subscriptions", Helper.jsonArrayFromList(subscriptionUrls));
            value.put("tags", Helper.jsonArrayFromList(followedTags));
            value.put("following", buildUpdatedNotificationsDisabledStates(subs));
            value.put("blocked", Helper.jsonArrayFromList(blockedChannelUrls));
            JSONObject builtinCollections = new JSONObject();
            if (favoritesPlaylist != null) {
                builtinCollections.put(favoritesPlaylist.getId(), favoritesPlaylist.toJSONObject());
            }
            if (watchlaterPlaylist != null) {
                builtinCollections.put(watchlaterPlaylist.getId(), watchlaterPlaylist.toJSONObject());
            }
            value.put("builtinCollections", builtinCollections);
            JSONObject unpublishedCollections = new JSONObject();
            if (allCollections != null) {
                for (Map.Entry<String, OdyseeCollection> entry : allCollections.entrySet()) {
                    String collectionId = entry.getKey();
                    if (Arrays.asList(OdyseeCollection.BUILT_IN_ID_FAVORITES, OdyseeCollection.BUILT_IN_ID_WATCHLATER).contains(collectionId)) {
                        continue;
                    }
                    OdyseeCollection localCollection = entry.getValue();
                    if (localCollection.getVisibility() != OdyseeCollection.VISIBILITY_PRIVATE) {
                        continue;
                    }
                    unpublishedCollections.put(collectionId, localCollection.toJSONObject());
                }
            }
            value.put("unpublishedCollections", unpublishedCollections);
            sharedObject = new JSONObject();
            sharedObject.put("type", "object");
            sharedObject.put("value", value);
            sharedObject.put("version", VERSION);
        }
        Map<String, Object> options = new HashMap<>();
        options.put("key", KEY);
        options.put("value", sharedObject.toString());
        Lbry.authenticatedGenericApiCall(Lbry.METHOD_PREFERENCE_SET, options, authToken);
        return true;
    } catch (ApiCallException | JSONException ex) {
        // failed
        error = ex;
    }
    return false;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) MainActivity(com.odysee.app.MainActivity) Subscription(com.odysee.app.model.lbryinc.Subscription) LbryUri(com.odysee.app.utils.LbryUri) ApiCallException(com.odysee.app.exceptions.ApiCallException) JSONException(org.json.JSONException) SQLiteException(android.database.sqlite.SQLiteException) OdyseeCollection(com.odysee.app.model.OdyseeCollection) LbryUriException(com.odysee.app.exceptions.LbryUriException) JSONObject(org.json.JSONObject) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) Map(java.util.Map)

Example 7 with ApiCallException

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

the class AbandonChannelTask method doInBackground.

public Boolean doInBackground(Void... params) {
    successfulClaimIds = new ArrayList<>();
    failedClaimIds = new ArrayList<>();
    failedExceptions = new ArrayList<>();
    for (String claimId : claimIds) {
        try {
            Map<String, Object> options = new HashMap<>();
            options.put("claim_id", claimId);
            options.put("blocking", true);
            JSONObject result = (JSONObject) Lbry.authenticatedGenericApiCall(Lbry.METHOD_CHANNEL_ABANDON, options, authToken);
            successfulClaimIds.add(claimId);
        } catch (ApiCallException ex) {
            failedClaimIds.add(claimId);
            failedExceptions.add(ex);
        }
    }
    return true;
}
Also used : JSONObject(org.json.JSONObject) HashMap(java.util.HashMap) ApiCallException(com.odysee.app.exceptions.ApiCallException) JSONObject(org.json.JSONObject)

Example 8 with ApiCallException

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

the class ClaimListTask method doInBackground.

protected List<Claim> doInBackground(Void... params) {
    List<Claim> claims = null;
    try {
        Map<String, Object> options = new HashMap<>();
        if (types != null && types.size() > 0) {
            options.put("claim_type", types);
        }
        options.put("page", 1);
        options.put("page_size", 999);
        options.put("resolve", true);
        JSONObject result;
        if (!Helper.isNullOrEmpty(authToken)) {
            result = (JSONObject) Lbry.authenticatedGenericApiCall(Lbry.METHOD_CLAIM_LIST, options, authToken);
        } else {
            result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_CLAIM_LIST, options);
        }
        JSONArray items = result.getJSONArray("items");
        claims = new ArrayList<>();
        for (int i = 0; i < items.length(); i++) {
            claims.add(Claim.fromJSONObject(items.getJSONObject(i)));
        }
    } catch (ApiCallException | JSONException 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)

Example 9 with ApiCallException

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

the class FetchSubscriptionsTask method doInBackground.

protected List<Subscription> doInBackground(Void... params) {
    List<Subscription> subscriptions = new ArrayList<>();
    SQLiteDatabase db = null;
    try {
        if (context instanceof MainActivity) {
            db = ((MainActivity) context).getDbHelper().getWritableDatabase();
            if (db != null) {
                subscriptions = new ArrayList<>(DatabaseHelper.getSubscriptions(db));
            }
            // obtain subscriptions from the wallet shared object
            List<Subscription> sharedStateSubs = new ArrayList<>();
            JSONObject result = (JSONObject) Lbry.authenticatedGenericApiCall(Lbry.METHOD_PREFERENCE_GET, Lbry.buildSingleParam("key", "shared"), authToken);
            JSONObject shared = result.getJSONObject("shared");
            if (shared.has("type") && "object".equalsIgnoreCase(shared.getString("type")) && shared.has("value")) {
                sharedStateSubs = new ArrayList<>(LoadSharedUserStateTask.loadSubscriptionsFromSharedUserState(shared));
            }
            for (Subscription sub : sharedStateSubs) {
                // merge with subscriptions in local store
                if (!subscriptions.contains(sub)) {
                    subscriptions.add(sub);
                }
                if (db != null) {
                    DatabaseHelper.createOrUpdateSubscription(sub, db);
                }
            }
        }
    } catch (ClassCastException | ApiCallException | JSONException | IllegalStateException ex) {
        error = ex;
        return null;
    }
    return subscriptions;
}
Also used : JSONObject(org.json.JSONObject) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) ApiCallException(com.odysee.app.exceptions.ApiCallException) ArrayList(java.util.ArrayList) JSONException(org.json.JSONException) MainActivity(com.odysee.app.MainActivity) Subscription(com.odysee.app.model.lbryinc.Subscription)

Example 10 with ApiCallException

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

the class PublishClaimTask method doInBackground.

protected Claim doInBackground(Void... params) {
    Claim.StreamMetadata metadata = (Claim.StreamMetadata) claim.getValue();
    DecimalFormat amountFormat = new DecimalFormat(Helper.SDK_AMOUNT_FORMAT, new DecimalFormatSymbols(Locale.US));
    Map<String, Object> options = new HashMap<>();
    options.put("blocking", true);
    options.put("name", claim.getName());
    options.put("bid", amountFormat.format(new BigDecimal(claim.getAmount()).doubleValue()));
    options.put("title", Helper.isNullOrEmpty(claim.getTitle()) ? "" : claim.getTitle());
    options.put("description", Helper.isNullOrEmpty(claim.getDescription()) ? "" : claim.getDescription());
    options.put("thumbnail_url", Helper.isNullOrEmpty(claim.getThumbnailUrl()) ? "" : claim.getThumbnailUrl());
    if (!Helper.isNullOrEmpty(filePath)) {
        options.put("file_path", filePath);
    }
    if (claim.getTags() != null && claim.getTags().size() > 0) {
        options.put("tags", new ArrayList<>(claim.getTags()));
    }
    if (metadata.getFee() != null) {
        options.put("fee_currency", metadata.getFee().getCurrency());
        options.put("fee_amount", amountFormat.format(new BigDecimal(metadata.getFee().getAmount()).doubleValue()));
    }
    if (claim.getSigningChannel() != null) {
        options.put("channel_id", claim.getSigningChannel().getClaimId());
    }
    if (metadata.getLanguages() != null && metadata.getLanguages().size() > 0) {
        options.put("languages", metadata.getLanguages());
    }
    if (!Helper.isNullOrEmpty(metadata.getLicense())) {
        options.put("license", metadata.getLicense());
    }
    if (!Helper.isNullOrEmpty(metadata.getLicenseUrl())) {
        options.put("license_url", metadata.getLicenseUrl());
    }
    if (metadata.getReleaseTime() > 0) {
        options.put("release_time", metadata.getReleaseTime());
    } else if (claim.getTimestamp() > 0) {
        options.put("release_time", claim.getTimestamp());
    } else {
        options.put("release_time", Double.valueOf(Math.floor(System.currentTimeMillis() / 1000.0)).intValue());
    }
    Claim claimResult = null;
    try {
        JSONObject result = (JSONObject) Lbry.genericApiCall(Lbry.METHOD_PUBLISH, options);
        if (result.has("outputs")) {
            JSONArray outputs = result.getJSONArray("outputs");
            for (int i = 0; i < outputs.length(); i++) {
                JSONObject output = outputs.getJSONObject(i);
                if (output.has("claim_id") && output.has("claim_op")) {
                    claimResult = Claim.claimFromOutput(output);
                    break;
                }
            }
        }
    } catch (ApiCallException | ClassCastException | JSONException ex) {
        error = ex;
    }
    return claimResult;
}
Also used : DecimalFormatSymbols(java.text.DecimalFormatSymbols) HashMap(java.util.HashMap) ApiCallException(com.odysee.app.exceptions.ApiCallException) DecimalFormat(java.text.DecimalFormat) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) BigDecimal(java.math.BigDecimal) 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