package a0;

import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import b0.AbstractC0399d;
import b0.D;
import com.ifpdos.sdk.httpd.binder.aidl.Headers;
import com.ifpdos.sdk.httpd.binder.aidl.RequestLine;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.NoRouteToHostException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/* JADX INFO: loaded from: classes.dex */
public class k implements x {

    /* JADX INFO: renamed from: p, reason: collision with root package name */
    private static final Pattern f1965p = Pattern.compile("^bytes (\\d+)-(\\d+)/(\\d+)$");

    /* JADX INFO: renamed from: q, reason: collision with root package name */
    private static final AtomicReference f1966q = new AtomicReference();

    /* JADX INFO: renamed from: a, reason: collision with root package name */
    private final boolean f1967a;

    /* JADX INFO: renamed from: b, reason: collision with root package name */
    private final int f1968b;

    /* JADX INFO: renamed from: c, reason: collision with root package name */
    private final int f1969c;

    /* JADX INFO: renamed from: d, reason: collision with root package name */
    private final String f1970d;

    /* JADX INFO: renamed from: e, reason: collision with root package name */
    private final HashMap f1971e;

    /* JADX INFO: renamed from: f, reason: collision with root package name */
    private final w f1972f;

    /* JADX INFO: renamed from: g, reason: collision with root package name */
    private h f1973g;

    /* JADX INFO: renamed from: h, reason: collision with root package name */
    private HttpURLConnection f1974h;

    /* JADX INFO: renamed from: i, reason: collision with root package name */
    private InputStream f1975i;

    /* JADX INFO: renamed from: j, reason: collision with root package name */
    private boolean f1976j;

    /* JADX INFO: renamed from: k, reason: collision with root package name */
    private long f1977k;

    /* JADX INFO: renamed from: l, reason: collision with root package name */
    private long f1978l;

    /* JADX INFO: renamed from: m, reason: collision with root package name */
    private long f1979m;

    /* JADX INFO: renamed from: n, reason: collision with root package name */
    private long f1980n;

    /* JADX INFO: renamed from: o, reason: collision with root package name */
    private a f1981o;

    public interface a {
        String a(String str);

        void b(String str, String[] strArr);
    }

    public k(String str, b0.w wVar, w wVar2, int i2, int i3, boolean z2) {
        this.f1970d = AbstractC0399d.c(str);
        this.f1972f = wVar2;
        this.f1971e = new HashMap();
        this.f1968b = i2;
        this.f1969c = i3;
        this.f1967a = z2;
    }

    private void c() {
        if (this.f1974h != null) {
            try {
                D.h(this.f1975i);
                this.f1974h.disconnect();
            } catch (Exception e2) {
                Log.e("DefaultHttpDataSource", "Unexpected error while disconnecting", e2);
            }
            this.f1974h = null;
        }
    }

    private static long d(HttpURLConnection httpURLConnection) {
        long j2;
        String headerField = httpURLConnection.getHeaderField(Headers.KEY_CONTENT_LENGTH);
        if (TextUtils.isEmpty(headerField)) {
            j2 = -1;
        } else {
            try {
                j2 = Long.parseLong(headerField);
            } catch (NumberFormatException unused) {
                Log.e("DefaultHttpDataSource", "Unexpected Content-Length [" + headerField + "]");
                j2 = -1;
            }
        }
        String headerField2 = httpURLConnection.getHeaderField("Content-Range");
        if (TextUtils.isEmpty(headerField2)) {
            return j2;
        }
        Matcher matcher = f1965p.matcher(headerField2);
        if (!matcher.find()) {
            return j2;
        }
        try {
            long j3 = (Long.parseLong(matcher.group(2)) - Long.parseLong(matcher.group(1))) + 1;
            if (j2 < 0) {
                return j3;
            }
            if (j2 == j3) {
                return j2;
            }
            Log.w("DefaultHttpDataSource", "Inconsistent headers [" + headerField + "] [" + headerField2 + "]");
            return Math.max(j2, j3);
        } catch (NumberFormatException unused2) {
            Log.e("DefaultHttpDataSource", "Unexpected Content-Range [" + headerField2 + "]");
            return j2;
        }
    }

    private static URL e(URL url, String str) throws ProtocolException {
        if (str == null) {
            throw new ProtocolException("Null location redirect");
        }
        URL url2 = new URL(url, str);
        String protocol = url2.getProtocol();
        if ("https".equals(protocol) || "http".equals(protocol)) {
            return url2;
        }
        throw new ProtocolException("Unsupported protocol redirect: " + protocol);
    }

    private HttpURLConnection f(h hVar) throws IOException {
        HttpURLConnection httpURLConnectionG;
        URL url = new URL(hVar.f1940a.toString().replace(" ", "%20"));
        byte[] bArr = hVar.f1941b;
        Log.d("DefaultHttpDataSource", "URL[" + url.toString() + "]");
        long j2 = hVar.f1943d;
        long j3 = hVar.f1944e;
        int i2 = 0;
        boolean z2 = (hVar.f1946g & 1) != 0;
        String str = "responseCode:";
        if (!this.f1967a) {
            Log.i("DefaultHttpDataSource", "makeConnection IN");
            HttpURLConnection httpURLConnectionG2 = g(url, bArr, j2, j3, z2, true);
            Log.i("DefaultHttpDataSource", "responseCode:" + httpURLConnectionG2.getResponseCode());
            return httpURLConnectionG2;
        }
        while (true) {
            int i3 = i2 + 1;
            if (i2 > 20) {
                throw new NoRouteToHostException("Too many redirects: " + i3);
            }
            String str2 = str;
            httpURLConnectionG = g(url, bArr, j2, j3, z2, false);
            int responseCode = httpURLConnectionG.getResponseCode();
            Log.i("DefaultHttpDataSource", str2 + responseCode);
            if (responseCode != 300 && responseCode != 301 && responseCode != 302 && responseCode != 303 && (bArr != null || (responseCode != 307 && responseCode != 308))) {
                break;
            }
            String headerField = httpURLConnectionG.getHeaderField("Location");
            httpURLConnectionG.disconnect();
            url = e(url, headerField);
            bArr = null;
            str = str2;
            i2 = i3;
        }
        return httpURLConnectionG;
    }

    private HttpURLConnection g(URL url, byte[] bArr, long j2, long j3, boolean z2, boolean z3) throws IOException {
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(this.f1968b);
        httpURLConnection.setReadTimeout(this.f1969c);
        a aVar = this.f1981o;
        if (aVar != null) {
            String strA = aVar.a(this.f1973g.f1940a.toString());
            if (!TextUtils.isEmpty(strA)) {
                i("Cookie", strA);
                Log.i("DefaultHttpDataSource", "RequestProperty Cookie:" + strA);
            }
        }
        synchronized (this.f1971e) {
            try {
                for (Map.Entry entry : this.f1971e.entrySet()) {
                    String str = (String) entry.getKey();
                    String queryParameter = Uri.parse(url.toString()).getQueryParameter("type");
                    if (!"Host".equals(str)) {
                        httpURLConnection.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
                        Log.i("DefaultHttpDataSource", "RequestProperty: " + ((String) entry.getKey()) + " " + ((String) entry.getValue()));
                    } else if (queryParameter != null && (queryParameter.contains("M3U8") || queryParameter.contains("m3u8"))) {
                        httpURLConnection.setRequestProperty((String) entry.getKey(), (String) entry.getValue());
                        Log.i("DefaultHttpDataSource", "Add Host header for M3U8 RequestProperty: " + ((String) entry.getKey()) + " " + ((String) entry.getValue()));
                    }
                }
            } catch (Throwable th) {
                throw th;
            }
        }
        if (j2 != 0 || j3 != -1) {
            String str2 = "bytes=" + j2 + "-";
            if (j3 != -1) {
                str2 = str2 + ((j2 + j3) - 1);
            }
            httpURLConnection.setRequestProperty("Range", str2);
            Log.i("DefaultHttpDataSource", "RequestProperty Range: " + str2);
        }
        httpURLConnection.setRequestProperty("User-Agent", this.f1970d);
        Log.i("DefaultHttpDataSource", "RequestProperty User-Agent: " + this.f1970d);
        if (!z2) {
            httpURLConnection.setRequestProperty("Accept-Encoding", "identity");
        }
        httpURLConnection.setInstanceFollowRedirects(z3);
        httpURLConnection.setDoOutput(bArr != null);
        if (bArr != null) {
            httpURLConnection.setRequestMethod(RequestLine.METHOD_POST);
            if (bArr.length == 0) {
                httpURLConnection.connect();
            } else {
                httpURLConnection.setFixedLengthStreamingMode(bArr.length);
                Log.i("DefaultHttpDataSource", "connect in");
                httpURLConnection.connect();
                Log.i("DefaultHttpDataSource", "connect out");
                OutputStream outputStream = httpURLConnection.getOutputStream();
                try {
                    try {
                        outputStream.write(bArr);
                    } catch (IOException unused) {
                        Log.e("DefaultHttpDataSource", "OutputStream write fail!");
                    }
                } finally {
                    D.h(outputStream);
                }
            }
        } else {
            Log.i("DefaultHttpDataSource", "connect in");
            httpURLConnection.connect();
            Log.i("DefaultHttpDataSource", "connect out");
        }
        return httpURLConnection;
    }

    private int h(byte[] bArr, int i2, int i3) throws IOException {
        if (i3 == 0) {
            return 0;
        }
        int i4 = this.f1975i.read(bArr, i2, i3);
        if (i4 == -1) {
            long j2 = this.f1978l;
            if (j2 == -1 || j2 == this.f1980n) {
                return -1;
            }
            throw new EOFException();
        }
        this.f1980n += (long) i4;
        w wVar = this.f1972f;
        if (wVar != null) {
            wVar.c(i4);
        }
        return i4;
    }

    private void j() throws IOException {
        if (this.f1979m == this.f1977k) {
            return;
        }
        byte[] bArr = (byte[]) f1966q.getAndSet(null);
        if (bArr == null) {
            bArr = new byte[4096];
        }
        while (true) {
            long j2 = this.f1979m;
            long j3 = this.f1977k;
            if (j2 == j3) {
                f1966q.set(bArr);
                return;
            }
            int i2 = this.f1975i.read(bArr, 0, (int) Math.min(j3 - j2, bArr.length));
            if (Thread.interrupted()) {
                throw new InterruptedIOException();
            }
            if (i2 == -1) {
                throw new EOFException();
            }
            this.f1979m += (long) i2;
            w wVar = this.f1972f;
            if (wVar != null) {
                wVar.c(i2);
            }
        }
    }

    @Override // a0.f
    public long a(h hVar) throws p {
        BufferedReader bufferedReader;
        IOException e2;
        StringBuffer stringBuffer;
        List<String> list;
        a aVar;
        this.f1973g = hVar;
        long j2 = 0;
        this.f1980n = 0L;
        this.f1979m = 0L;
        try {
            HttpURLConnection httpURLConnectionF = f(hVar);
            this.f1974h = httpURLConnectionF;
            try {
                int responseCode = httpURLConnectionF.getResponseCode();
                Log.d("DefaultHttpDataSource", "responseCode[" + responseCode + "], responseMessage:" + this.f1974h.getResponseMessage());
                if (responseCode >= 200 && responseCode <= 299) {
                    this.f1974h.getContentType();
                    if (responseCode == 200) {
                        long j3 = hVar.f1943d;
                        if (j3 != 0) {
                            j2 = j3;
                        }
                    }
                    this.f1977k = j2;
                    if ((hVar.f1946g & 1) == 0) {
                        long jD = d(this.f1974h);
                        long j4 = hVar.f1944e;
                        if (j4 == -1) {
                            j4 = jD != -1 ? jD - this.f1977k : -1L;
                        }
                        this.f1978l = j4;
                    } else {
                        this.f1978l = hVar.f1944e;
                    }
                    try {
                        this.f1975i = this.f1974h.getInputStream();
                        this.f1976j = true;
                        w wVar = this.f1972f;
                        if (wVar != null) {
                            wVar.b();
                        }
                        Map<String, List<String>> headerFields = this.f1974h.getHeaderFields();
                        if (headerFields != null && (list = headerFields.get("Set-Cookie")) != null && (aVar = this.f1981o) != null) {
                            aVar.b(hVar.f1940a.toString(), (String[]) list.toArray(new String[0]));
                        }
                        return this.f1978l;
                    } catch (IOException e3) {
                        c();
                        throw new p(e3, hVar, 1);
                    }
                }
                Map<String, List<String>> headerFields2 = this.f1974h.getHeaderFields();
                BufferedReader bufferedReader2 = null;
                try {
                    this.f1975i = this.f1974h.getErrorStream();
                    bufferedReader = new BufferedReader(new InputStreamReader(this.f1975i, "UTF-8"));
                    try {
                        try {
                            stringBuffer = new StringBuffer();
                        } catch (IOException e4) {
                            e2 = e4;
                            Log.e("DefaultHttpDataSource", "getErrorStream fail:", e2);
                            D.h(bufferedReader);
                            c();
                            throw new q(responseCode, headerFields2, hVar);
                        }
                    } catch (Throwable unused) {
                        bufferedReader2 = bufferedReader;
                    }
                } catch (IOException e5) {
                    bufferedReader = null;
                    e2 = e5;
                } catch (Throwable unused2) {
                }
                while (true) {
                    String line = bufferedReader.readLine();
                    if (line == null) {
                        Log.i("DefaultHttpDataSource", "Error info:" + stringBuffer.toString());
                        D.h(bufferedReader);
                        c();
                        throw new q(responseCode, headerFields2, hVar);
                    }
                    stringBuffer.append(line);
                    stringBuffer.append("\r\n");
                    bufferedReader2 = bufferedReader;
                    D.h(bufferedReader2);
                    c();
                    throw new q(responseCode, headerFields2, hVar);
                }
            } catch (IOException e6) {
                c();
                throw new p("Unable to connect to " + hVar.f1940a.toString(), e6, hVar, 1);
            }
        } catch (IOException e7) {
            throw new p("Unable to connect to " + hVar.f1940a.toString(), e7, hVar, 1);
        }
    }

    protected final long b() {
        long j2 = this.f1978l;
        return j2 == -1 ? j2 : j2 - this.f1980n;
    }

    @Override // a0.f
    public void close() {
        try {
            if (this.f1975i != null) {
                D.E(this.f1974h, b());
                try {
                    this.f1975i.close();
                } catch (IOException e2) {
                    throw new p(e2, this.f1973g, 3);
                }
            }
        } finally {
            this.f1975i = null;
            c();
            if (this.f1976j) {
                this.f1976j = false;
                w wVar = this.f1972f;
                if (wVar != null) {
                    wVar.a();
                }
            }
        }
    }

    @Override // a0.x
    public String getUri() {
        HttpURLConnection httpURLConnection = this.f1974h;
        if (httpURLConnection == null) {
            return null;
        }
        return httpURLConnection.getURL().toString();
    }

    public void i(String str, String str2) {
        AbstractC0399d.d(str);
        AbstractC0399d.d(str2);
        synchronized (this.f1971e) {
            this.f1971e.put(str, str2);
        }
    }

    @Override // a0.f
    public int read(byte[] bArr, int i2, int i3) throws p {
        try {
            j();
            return h(bArr, i2, i3);
        } catch (IOException e2) {
            throw new p(e2, this.f1973g, 2);
        }
    }

    public k(String str, b0.w wVar, w wVar2, int i2, int i3, boolean z2, a aVar) {
        this(str, wVar, wVar2, i2, i3, z2);
        this.f1981o = aVar;
    }
}
