Search in sources :

Example 1 with InvalidSourceException

use of org.schabi.newpipe.extractor.subscription.SubscriptionExtractor.InvalidSourceException in project NewPipe by TeamNewPipe.

the class ImportExportJsonHelper method readFrom.

/**
 * Read a JSON source through the input stream and return the parsed subscription items.
 *
 * @param in            the input stream (e.g. a file)
 * @param eventListener listener for the events generated
 */
public static List<SubscriptionItem> readFrom(InputStream in, @Nullable ImportExportEventListener eventListener) throws InvalidSourceException {
    if (in == null)
        throw new InvalidSourceException("input is null");
    final List<SubscriptionItem> channels = new ArrayList<>();
    try {
        JsonObject parentObject = JsonParser.object().from(in);
        JsonArray channelsArray = parentObject.getArray(JSON_SUBSCRIPTIONS_ARRAY_KEY);
        if (eventListener != null)
            eventListener.onSizeReceived(channelsArray.size());
        if (channelsArray == null) {
            throw new InvalidSourceException("Channels array is null");
        }
        for (Object o : channelsArray) {
            if (o instanceof JsonObject) {
                JsonObject itemObject = (JsonObject) o;
                int serviceId = itemObject.getInt(JSON_SERVICE_ID_KEY, 0);
                String url = itemObject.getString(JSON_URL_KEY);
                String name = itemObject.getString(JSON_NAME_KEY);
                if (url != null && name != null && !url.isEmpty() && !name.isEmpty()) {
                    channels.add(new SubscriptionItem(serviceId, url, name));
                    if (eventListener != null)
                        eventListener.onItemCompleted(name);
                }
            }
        }
    } catch (Throwable e) {
        throw new InvalidSourceException("Couldn't parse json", e);
    }
    return channels;
}
Also used : InvalidSourceException(org.schabi.newpipe.extractor.subscription.SubscriptionExtractor.InvalidSourceException) JsonArray(com.grack.nanojson.JsonArray) SubscriptionItem(org.schabi.newpipe.extractor.subscription.SubscriptionItem) ArrayList(java.util.ArrayList) JsonObject(com.grack.nanojson.JsonObject) JsonObject(com.grack.nanojson.JsonObject)

Aggregations

JsonArray (com.grack.nanojson.JsonArray)1 JsonObject (com.grack.nanojson.JsonObject)1 ArrayList (java.util.ArrayList)1 InvalidSourceException (org.schabi.newpipe.extractor.subscription.SubscriptionExtractor.InvalidSourceException)1 SubscriptionItem (org.schabi.newpipe.extractor.subscription.SubscriptionItem)1