package de.danoeh.antennapod.core.glide;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.Options;
import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.bumptech.glide.load.model.MultiModelLoaderFactory;
import com.bumptech.glide.signature.ObjectKey;
import de.danoeh.antennapod.core.feed.Chapter;
import de.danoeh.antennapod.core.util.EmbeddedChapterImage;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.ByteBuffer;
import org.apache.commons.io.IOUtils;

public final class ChapterImageModelLoader implements ModelLoader<EmbeddedChapterImage, ByteBuffer> {

    public static class Factory implements ModelLoaderFactory<EmbeddedChapterImage, ByteBuffer> {
        @Override
        public ModelLoader<EmbeddedChapterImage, ByteBuffer> build(MultiModelLoaderFactory unused) {
            return new ChapterImageModelLoader();
        }

        @Override
        public void teardown() {
            // Do nothing.
        }
    }

    @Nullable
    @Override
    public LoadData<ByteBuffer> buildLoadData(EmbeddedChapterImage model, int width, int height, Options options) {
        return new LoadData<>(new ObjectKey(model), new EmbeddedImageFetcher(model));
    }

    @Override
    public boolean handles(EmbeddedChapterImage model) {
        return true;
    }

    class EmbeddedImageFetcher implements DataFetcher<ByteBuffer> {
        private final EmbeddedChapterImage image;

        public EmbeddedImageFetcher(EmbeddedChapterImage image) {
            this.image = image;
        }

        @Override
        public void loadData(@NonNull Priority priority, @NonNull DataCallback<? super ByteBuffer> callback) {

            BufferedInputStream stream = null;
            try {
                if (image.getMedia().localFileAvailable()) {
                    File localFile = new File(image.getMedia().getLocalMediaUrl());
                    stream = new BufferedInputStream(new FileInputStream(localFile));
                } else {
                    URL url = new URL(image.getMedia().getStreamUrl());
                    stream = new BufferedInputStream(url.openStream());
                }
                byte[] imageContent = new byte[image.getLength()];
                stream.skip(image.getPosition());
                stream.read(imageContent, 0, image.getLength());
                callback.onDataReady(ByteBuffer.wrap(imageContent));
            } catch (IOException e) {
                callback.onLoadFailed(new IOException("Loading embedded cover did not work"));
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(stream);
            }
        }

        @Override public void cleanup() {
            // nothing to clean up
        }
        @Override public void cancel() {
            // cannot cancel
        }

        @NonNull
        @Override
        public Class<ByteBuffer> getDataClass() {
            return ByteBuffer.class;
        }

        @NonNull
        @Override
        public DataSource getDataSource() {
            return DataSource.LOCAL;
        }
    }
}

@@ -529,20 +529,139 @@
 ore.
-feed.Chapter
+ClientConfig;%0Aimport de.danoeh.antennapod.core.feed.Chapter;%0Aimport de.danoeh.antennapod.core.service.download.AntennapodHttpClient
 ;%0Aim
@@ -880,24 +880,102 @@
 ByteBuffer;%0A
+import okhttp3.OkHttpClient;%0Aimport okhttp3.Request;%0Aimport okhttp3.Response;%0A
 import org.a
@@ -1817,16 +1817,23 @@
  %7D%0A%0A    
+static 
 class Em
@@ -2494,16 +2494,45 @@
     
-%7D else %7B
+    stream.skip(image.getPosition());
 %0A   
@@ -2552,26 +2552,39 @@
     
-URL url
+byte%5B%5D imageContent
  = new 
-URL(
+byte%5B
 imag
@@ -2592,170 +2592,526 @@
 .get
-Media().getStreamUrl());%0A                    stream = new BufferedInputStream(url.openStream());%0A                %7D%0A                byte%5B%5D imageContent = new byte%5B
+Length()%5D;%0A                    stream.read(imageContent, 0, image.getLength());%0A                    callback.onDataReady(ByteBuffer.wrap(imageContent));%0A                %7D else %7B%0A                    Request.Builder httpReq = new Request.Builder();%0A                    httpReq.header(%22User-Agent%22, ClientConfig.USER_AGENT);%0A                    // Skipping would download the whole file%0A                    httpReq.header(%22Range%22, %22bytes=%22 + image.getPosition()%0A                            + %22-%22 + (image.getPosition() + 
 imag
@@ -3115,33 +3115,34 @@
 mage.getLength()
-%5D
+))
 ;%0A              
@@ -3147,107 +3147,390 @@
     
-stream.skip(image.getPosition());%0A                stream.read(imageContent, 0, image.getLength());%0A
+    httpReq.url(image.getMedia().getStreamUrl());%0A                    Response response = AntennapodHttpClient.getHttpClient().newCall(httpReq.build()).execute();%0A                    if (!response.isSuccessful() %7C%7C response.body() == null) %7B%0A                        throw new IOException(%22Invalid response: %22 + response.code() + %22 %22 + response.message());%0A                    %7D%0A    
     
@@ -3574,39 +3574,68 @@
 Buffer.wrap(
-imageContent));
+response.body().bytes()));%0A                %7D
 %0A           
@@ -3703,99 +3703,9 @@
 led(
-new IOException(%22Loading embedded cover did not work%22));%0A                e.printStackTrace(
+e
 );%0A 

Load range only