package coil.fetch;

import A4.d;
import B4.a;
import C4.c;
import C4.e;
import S4.p;
import S4.w;
import android.net.Uri;
import android.os.NetworkOnMainThreadException;
import android.webkit.MimeTypeMap;
import coil.ImageLoader;
import coil.decode.DataSource;
import coil.decode.ImageSource;
import coil.decode.ImageSources;
import coil.disk.DiskCache;
import coil.fetch.Fetcher;
import coil.network.CacheResponse;
import coil.network.CacheStrategy;
import coil.network.HttpException;
import coil.request.Options;
import coil.util.Calls;
import coil.util.Utils;
import java.io.EOFException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import kotlin.jvm.internal.o;
import m3.AbstractC2467b;
import n2.AbstractC2613d;
import okhttp3.CacheControl;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.connection.RealCall;
import p5.AbstractC2732b;
import p5.AbstractC2749t;
import p5.I;
import p5.J;
import w4.h;

/* JADX INFO: loaded from: classes.dex */
public final class HttpUriFetcher implements Fetcher {
    private static final CacheControl CACHE_CONTROL_FORCE_NETWORK_NO_CACHE;
    private static final CacheControl CACHE_CONTROL_NO_NETWORK_NO_CACHE;
    public static final Companion Companion = new Companion(null);
    private static final String MIME_TYPE_TEXT_PLAIN = "text/plain";
    private final h callFactory;
    private final h diskCache;
    private final Options options;
    private final boolean respectCacheHeaders;
    private final String url;

    public static final class Companion {
        public /* synthetic */ Companion(kotlin.jvm.internal.h hVar) {
            this();
        }

        private Companion() {
        }
    }

    public static final class Factory implements Fetcher.Factory<Uri> {
        private final h callFactory;
        private final h diskCache;
        private final boolean respectCacheHeaders;

        public Factory(h hVar, h hVar2, boolean z6) {
            this.callFactory = hVar;
            this.diskCache = hVar2;
            this.respectCacheHeaders = z6;
        }

        private final boolean isApplicable(Uri uri) {
            return o.c(uri.getScheme(), "http") || o.c(uri.getScheme(), "https");
        }

        @Override // coil.fetch.Fetcher.Factory
        public Fetcher create(Uri uri, Options options, ImageLoader imageLoader) {
            if (isApplicable(uri)) {
                return new HttpUriFetcher(uri.toString(), options, this.callFactory, this.diskCache, this.respectCacheHeaders);
            }
            return null;
        }
    }

    /* JADX INFO: renamed from: coil.fetch.HttpUriFetcher$executeNetworkRequest$1, reason: invalid class name */
    @e(c = "coil.fetch.HttpUriFetcher", f = "HttpUriFetcher.kt", l = {224}, m = "executeNetworkRequest")
    public static final class AnonymousClass1 extends c {
        int label;
        /* synthetic */ Object result;

        public AnonymousClass1(d dVar) {
            super(dVar);
        }

        @Override // C4.a
        public final Object invokeSuspend(Object obj) {
            this.result = obj;
            this.label |= Integer.MIN_VALUE;
            return HttpUriFetcher.this.executeNetworkRequest(null, this);
        }
    }

    /* JADX INFO: renamed from: coil.fetch.HttpUriFetcher$fetch$1, reason: invalid class name and case insensitive filesystem */
    @e(c = "coil.fetch.HttpUriFetcher", f = "HttpUriFetcher.kt", l = {77, 106}, m = "fetch")
    public static final class C12491 extends c {
        Object L$0;
        Object L$1;
        Object L$2;
        int label;
        /* synthetic */ Object result;

        public C12491(d dVar) {
            super(dVar);
        }

        @Override // C4.a
        public final Object invokeSuspend(Object obj) {
            this.result = obj;
            this.label |= Integer.MIN_VALUE;
            return HttpUriFetcher.this.fetch(this);
        }
    }

    static {
        CacheControl.Builder builder = new CacheControl.Builder();
        builder.f21942a = true;
        builder.f21943b = true;
        CACHE_CONTROL_FORCE_NETWORK_NO_CACHE = builder.a();
        CacheControl.Builder builder2 = new CacheControl.Builder();
        builder2.f21942a = true;
        builder2.f21945d = true;
        CACHE_CONTROL_NO_NETWORK_NO_CACHE = builder2.a();
    }

    public HttpUriFetcher(String str, Options options, h hVar, h hVar2, boolean z6) {
        this.url = str;
        this.options = options;
        this.callFactory = hVar;
        this.diskCache = hVar2;
        this.respectCacheHeaders = z6;
    }

    /* JADX INFO: Access modifiers changed from: private */
    /* JADX WARN: Removed duplicated region for block: B:7:0x0013  */
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    public final Object executeNetworkRequest(Request request, d dVar) {
        AnonymousClass1 anonymousClass1;
        Response responseD;
        if (dVar instanceof AnonymousClass1) {
            anonymousClass1 = (AnonymousClass1) dVar;
            int i6 = anonymousClass1.label;
            if ((i6 & Integer.MIN_VALUE) != 0) {
                anonymousClass1.label = i6 - Integer.MIN_VALUE;
            } else {
                anonymousClass1 = new AnonymousClass1(dVar);
            }
        }
        Object objAwait = anonymousClass1.result;
        a aVar = a.f492a;
        int i7 = anonymousClass1.label;
        if (i7 == 0) {
            AbstractC2467b.l(objAwait);
            if (Utils.isMainThread()) {
                if (this.options.getNetworkCachePolicy().getReadEnabled()) {
                    throw new NetworkOnMainThreadException();
                }
                responseD = ((Call.Factory) this.callFactory.getValue()).a(request).d();
                if (!responseD.c() || responseD.f22143d == 304) {
                    return responseD;
                }
                ResponseBody responseBody = responseD.f22146j;
                if (responseBody != null) {
                    Utils.closeQuietly(responseBody);
                }
                throw new HttpException(responseD);
            }
            RealCall realCallA = ((Call.Factory) this.callFactory.getValue()).a(request);
            anonymousClass1.label = 1;
            objAwait = Calls.await(realCallA, anonymousClass1);
            if (objAwait == aVar) {
                return aVar;
            }
        } else {
            if (i7 != 1) {
                throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
            }
            AbstractC2467b.l(objAwait);
        }
        responseD = (Response) objAwait;
        if (responseD.c()) {
        }
        return responseD;
    }

    private final String getDiskCacheKey() {
        String diskCacheKey = this.options.getDiskCacheKey();
        return diskCacheKey == null ? this.url : diskCacheKey;
    }

    private final AbstractC2749t getFileSystem() {
        Object value = this.diskCache.getValue();
        o.e(value);
        return ((DiskCache) value).getFileSystem();
    }

    private final boolean isCacheable(Request request, Response response) {
        if (this.options.getDiskCachePolicy().getWriteEnabled()) {
            return !this.respectCacheHeaders || CacheStrategy.Companion.isCacheable(request, response);
        }
        return false;
    }

    private final Request newRequest() throws EOFException {
        Request.Builder builder = new Request.Builder();
        builder.i(this.url);
        builder.f(this.options.getHeaders());
        for (Map.Entry<Class<?>, Object> entry : this.options.getTags().asMap().entrySet()) {
            Class<?> key = entry.getKey();
            o.f(key, "null cannot be cast to non-null type java.lang.Class<kotlin.Any>");
            Class<?> cls = key;
            Object value = entry.getValue();
            if (value == null) {
                builder.f22135e.remove(cls);
            } else {
                if (builder.f22135e.isEmpty()) {
                    builder.f22135e = new LinkedHashMap();
                }
                LinkedHashMap linkedHashMap = builder.f22135e;
                Object objCast = cls.cast(value);
                o.e(objCast);
                linkedHashMap.put(cls, objCast);
            }
        }
        boolean readEnabled = this.options.getDiskCachePolicy().getReadEnabled();
        boolean readEnabled2 = this.options.getNetworkCachePolicy().getReadEnabled();
        if (!readEnabled2 && readEnabled) {
            builder.c(CacheControl.f21929p);
        } else if (!readEnabled2 || readEnabled) {
            if (!readEnabled2 && !readEnabled) {
                builder.c(CACHE_CONTROL_NO_NETWORK_NO_CACHE);
            }
        } else if (this.options.getDiskCachePolicy().getWriteEnabled()) {
            builder.c(CacheControl.f21928o);
        } else {
            builder.c(CACHE_CONTROL_FORCE_NETWORK_NO_CACHE);
        }
        return builder.b();
    }

    private final DiskCache.Snapshot readFromDiskCache() {
        DiskCache diskCache;
        if (!this.options.getDiskCachePolicy().getReadEnabled() || (diskCache = (DiskCache) this.diskCache.getValue()) == null) {
            return null;
        }
        return diskCache.openSnapshot(getDiskCacheKey());
    }

    private final CacheResponse toCacheResponse(DiskCache.Snapshot snapshot) throws Throwable {
        Throwable th;
        CacheResponse cacheResponse;
        try {
            J jC = AbstractC2732b.c(getFileSystem().source(snapshot.getMetadata()));
            try {
                cacheResponse = new CacheResponse(jC);
                try {
                    jC.close();
                    th = null;
                } catch (Throwable th2) {
                    th = th2;
                }
            } catch (Throwable th3) {
                try {
                    jC.close();
                } catch (Throwable th4) {
                    AbstractC2613d.b(th3, th4);
                }
                th = th3;
                cacheResponse = null;
            }
            if (th == null) {
                return cacheResponse;
            }
            throw th;
        } catch (IOException unused) {
            return null;
        }
    }

    private final DataSource toDataSource(Response response) {
        return response.f22147k != null ? DataSource.NETWORK : DataSource.DISK;
    }

    private final ImageSource toImageSource(DiskCache.Snapshot snapshot) {
        return ImageSources.create(snapshot.getData(), getFileSystem(), getDiskCacheKey(), snapshot);
    }

    private final DiskCache.Snapshot writeToDiskCache(DiskCache.Snapshot snapshot, Request request, Response response, CacheResponse cacheResponse) {
        DiskCache.Editor editorOpenEditor;
        Throwable th;
        Throwable th2 = null;
        if (isCacheable(request, response)) {
            if (snapshot != null) {
                editorOpenEditor = snapshot.closeAndOpenEditor();
            } else {
                DiskCache diskCache = (DiskCache) this.diskCache.getValue();
                editorOpenEditor = diskCache != null ? diskCache.openEditor(getDiskCacheKey()) : null;
            }
            try {
                if (editorOpenEditor != null) {
                    try {
                        if (response.f22143d != 304 || cacheResponse == null) {
                            I iB = AbstractC2732b.b(getFileSystem().sink(editorOpenEditor.getMetadata(), false));
                            try {
                                new CacheResponse(response).writeTo(iB);
                                try {
                                    iB.close();
                                    th = null;
                                } catch (Throwable th3) {
                                    th = th3;
                                }
                            } catch (Throwable th4) {
                                try {
                                    iB.close();
                                } catch (Throwable th5) {
                                    AbstractC2613d.b(th4, th5);
                                }
                                th = th4;
                            }
                            if (th != null) {
                                throw th;
                            }
                            I iB2 = AbstractC2732b.b(getFileSystem().sink(editorOpenEditor.getData(), false));
                            try {
                                ResponseBody responseBody = response.f22146j;
                                o.e(responseBody);
                                responseBody.c().v(iB2);
                                try {
                                    iB2.close();
                                } catch (Throwable th6) {
                                    th2 = th6;
                                }
                            } catch (Throwable th7) {
                                th2 = th7;
                                try {
                                    iB2.close();
                                } catch (Throwable th8) {
                                    AbstractC2613d.b(th2, th8);
                                }
                            }
                            if (th2 != null) {
                                throw th2;
                            }
                        } else {
                            Response.Builder builderD = response.d();
                            builderD.c(CacheStrategy.Companion.combineHeaders(cacheResponse.getResponseHeaders(), response.f22145f));
                            Response responseA = builderD.a();
                            I iB3 = AbstractC2732b.b(getFileSystem().sink(editorOpenEditor.getMetadata(), false));
                            try {
                                new CacheResponse(responseA).writeTo(iB3);
                                try {
                                    iB3.close();
                                } catch (Throwable th9) {
                                    th2 = th9;
                                }
                            } catch (Throwable th10) {
                                th2 = th10;
                                try {
                                    iB3.close();
                                } catch (Throwable th11) {
                                    AbstractC2613d.b(th2, th11);
                                }
                            }
                            if (th2 != null) {
                                throw th2;
                            }
                        }
                        DiskCache.Snapshot snapshotCommitAndOpenSnapshot = editorOpenEditor.commitAndOpenSnapshot();
                        Utils.closeQuietly(response);
                        return snapshotCommitAndOpenSnapshot;
                    } catch (Exception e6) {
                        Utils.abortQuietly(editorOpenEditor);
                        throw e6;
                    }
                }
            } catch (Throwable th12) {
                Utils.closeQuietly(response);
                throw th12;
            }
        } else if (snapshot != null) {
            Utils.closeQuietly(snapshot);
            return null;
        }
        return null;
    }

    /* JADX WARN: Removed duplicated region for block: B:56:0x0129 A[Catch: Exception -> 0x013c, TryCatch #1 {Exception -> 0x013c, blocks: (B:72:0x0189, B:54:0x011b, B:56:0x0129, B:58:0x0137, B:61:0x0140, B:63:0x014a, B:65:0x0156, B:67:0x016e), top: B:82:0x011b }] */
    /* JADX WARN: Removed duplicated region for block: B:63:0x014a A[Catch: Exception -> 0x013c, TryCatch #1 {Exception -> 0x013c, blocks: (B:72:0x0189, B:54:0x011b, B:56:0x0129, B:58:0x0137, B:61:0x0140, B:63:0x014a, B:65:0x0156, B:67:0x016e), top: B:82:0x011b }] */
    /* JADX WARN: Removed duplicated region for block: B:79:0x01ad  */
    /* JADX WARN: Removed duplicated region for block: B:7:0x0013  */
    @Override // coil.fetch.Fetcher
    /*
        Code decompiled incorrectly, please refer to instructions dump.
    */
    public Object fetch(d dVar) throws Exception {
        C12491 c12491;
        DiskCache.Snapshot snapshot;
        Exception e6;
        CacheStrategy cacheStrategyCompute;
        DiskCache.Snapshot snapshotWriteToDiskCache;
        CacheStrategy cacheStrategy;
        HttpUriFetcher httpUriFetcher;
        Response response;
        Response response2;
        Exception e7;
        HttpUriFetcher httpUriFetcher2;
        if (dVar instanceof C12491) {
            c12491 = (C12491) dVar;
            int i6 = c12491.label;
            if ((i6 & Integer.MIN_VALUE) != 0) {
                c12491.label = i6 - Integer.MIN_VALUE;
            } else {
                c12491 = new C12491(dVar);
            }
        }
        Object obj = c12491.result;
        a aVar = a.f492a;
        int i7 = c12491.label;
        if (i7 == 0) {
            AbstractC2467b.l(obj);
            DiskCache.Snapshot fromDiskCache = readFromDiskCache();
            try {
                if (fromDiskCache != null) {
                    Long l = getFileSystem().metadata(fromDiskCache.getMetadata()).f23118d;
                    if (l != null && l.longValue() == 0) {
                        return new SourceResult(toImageSource(fromDiskCache), getMimeType$coil_base_release(this.url, null), DataSource.DISK);
                    }
                    if (!this.respectCacheHeaders) {
                        ImageSource imageSource = toImageSource(fromDiskCache);
                        String str = this.url;
                        CacheResponse cacheResponse = toCacheResponse(fromDiskCache);
                        return new SourceResult(imageSource, getMimeType$coil_base_release(str, cacheResponse != null ? cacheResponse.getContentType() : null), DataSource.DISK);
                    }
                    cacheStrategyCompute = new CacheStrategy.Factory(newRequest(), toCacheResponse(fromDiskCache)).compute();
                    if (cacheStrategyCompute.getNetworkRequest() == null && cacheStrategyCompute.getCacheResponse() != null) {
                        return new SourceResult(toImageSource(fromDiskCache), getMimeType$coil_base_release(this.url, cacheStrategyCompute.getCacheResponse().getContentType()), DataSource.DISK);
                    }
                } else {
                    cacheStrategyCompute = new CacheStrategy.Factory(newRequest(), null).compute();
                }
                Request networkRequest = cacheStrategyCompute.getNetworkRequest();
                o.e(networkRequest);
                c12491.L$0 = this;
                c12491.L$1 = fromDiskCache;
                c12491.L$2 = cacheStrategyCompute;
                c12491.label = 1;
                Object objExecuteNetworkRequest = executeNetworkRequest(networkRequest, c12491);
                if (objExecuteNetworkRequest != aVar) {
                    CacheStrategy cacheStrategy2 = cacheStrategyCompute;
                    snapshotWriteToDiskCache = fromDiskCache;
                    obj = objExecuteNetworkRequest;
                    cacheStrategy = cacheStrategy2;
                    httpUriFetcher = this;
                    response = (Response) obj;
                    ResponseBody responseBodyRequireBody = Utils.requireBody(response);
                    snapshotWriteToDiskCache = httpUriFetcher.writeToDiskCache(snapshotWriteToDiskCache, cacheStrategy.getNetworkRequest(), response, cacheStrategy.getCacheResponse());
                    if (snapshotWriteToDiskCache == null) {
                    }
                }
                return aVar;
            } catch (Exception e8) {
                snapshot = fromDiskCache;
                e6 = e8;
                if (snapshot != null) {
                    Utils.closeQuietly(snapshot);
                }
                throw e6;
            }
        }
        if (i7 != 1) {
            if (i7 != 2) {
                throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
            }
            response2 = (Response) c12491.L$2;
            snapshotWriteToDiskCache = (DiskCache.Snapshot) c12491.L$1;
            httpUriFetcher2 = (HttpUriFetcher) c12491.L$0;
            try {
                AbstractC2467b.l(obj);
                Response response3 = (Response) obj;
                ResponseBody responseBodyRequireBody2 = Utils.requireBody(response3);
                return new SourceResult(httpUriFetcher2.toImageSource(responseBodyRequireBody2), httpUriFetcher2.getMimeType$coil_base_release(httpUriFetcher2.url, responseBodyRequireBody2.b()), httpUriFetcher2.toDataSource(response3));
            } catch (Exception e9) {
                e7 = e9;
                Utils.closeQuietly(response2);
                throw e7;
            }
        }
        CacheStrategy cacheStrategy3 = (CacheStrategy) c12491.L$2;
        snapshot = (DiskCache.Snapshot) c12491.L$1;
        httpUriFetcher = (HttpUriFetcher) c12491.L$0;
        try {
            AbstractC2467b.l(obj);
            cacheStrategy = cacheStrategy3;
            snapshotWriteToDiskCache = snapshot;
            try {
                response = (Response) obj;
                ResponseBody responseBodyRequireBody3 = Utils.requireBody(response);
                try {
                    snapshotWriteToDiskCache = httpUriFetcher.writeToDiskCache(snapshotWriteToDiskCache, cacheStrategy.getNetworkRequest(), response, cacheStrategy.getCacheResponse());
                    if (snapshotWriteToDiskCache == null) {
                        ImageSource imageSource2 = httpUriFetcher.toImageSource(snapshotWriteToDiskCache);
                        String str2 = httpUriFetcher.url;
                        CacheResponse cacheResponse2 = httpUriFetcher.toCacheResponse(snapshotWriteToDiskCache);
                        return new SourceResult(imageSource2, httpUriFetcher.getMimeType$coil_base_release(str2, cacheResponse2 != null ? cacheResponse2.getContentType() : null), DataSource.NETWORK);
                    }
                    if (responseBodyRequireBody3.c().p(1L)) {
                        return new SourceResult(httpUriFetcher.toImageSource(responseBodyRequireBody3), httpUriFetcher.getMimeType$coil_base_release(httpUriFetcher.url, responseBodyRequireBody3.b()), httpUriFetcher.toDataSource(response));
                    }
                    Utils.closeQuietly(response);
                    Request requestNewRequest = httpUriFetcher.newRequest();
                    c12491.L$0 = httpUriFetcher;
                    c12491.L$1 = snapshotWriteToDiskCache;
                    c12491.L$2 = response;
                    c12491.label = 2;
                    Object objExecuteNetworkRequest2 = httpUriFetcher.executeNetworkRequest(requestNewRequest, c12491);
                    if (objExecuteNetworkRequest2 != aVar) {
                        response2 = response;
                        obj = objExecuteNetworkRequest2;
                        httpUriFetcher2 = httpUriFetcher;
                        Response response32 = (Response) obj;
                        ResponseBody responseBodyRequireBody22 = Utils.requireBody(response32);
                        return new SourceResult(httpUriFetcher2.toImageSource(responseBodyRequireBody22), httpUriFetcher2.getMimeType$coil_base_release(httpUriFetcher2.url, responseBodyRequireBody22.b()), httpUriFetcher2.toDataSource(response32));
                    }
                    return aVar;
                } catch (Exception e10) {
                    response2 = response;
                    e7 = e10;
                    Utils.closeQuietly(response2);
                    throw e7;
                }
            } catch (Exception e11) {
                e6 = e11;
                snapshot = snapshotWriteToDiskCache;
                if (snapshot != null) {
                }
                throw e6;
            }
        } catch (Exception e12) {
            e6 = e12;
            if (snapshot != null) {
            }
            throw e6;
        }
    }

    public final String getMimeType$coil_base_release(String str, MediaType mediaType) {
        String mimeTypeFromUrl;
        String str2 = mediaType != null ? mediaType.f22046a : null;
        if ((str2 == null || w.A0(str2, MIME_TYPE_TEXT_PLAIN, false)) && (mimeTypeFromUrl = Utils.getMimeTypeFromUrl(MimeTypeMap.getSingleton(), str)) != null) {
            return mimeTypeFromUrl;
        }
        if (str2 != null) {
            return p.j1(';', str2, str2);
        }
        return null;
    }

    private final ImageSource toImageSource(ResponseBody responseBody) {
        return ImageSources.create(responseBody.c(), this.options.getContext());
    }
}
