package xyz.stream.download;

import android.R;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import androidx.core.app.s0;
import androidx.media3.common.p;
import androidx.media3.common.s;
import androidx.media3.exoplayer.rtsp.SessionDescription;
import androidx.media3.exoplayer.upstream.CmcdData;
import com.google.android.gms.measurement.internal.u1;
import g0.h;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import xyz.stream.api.viewmodel.u;
import xyz.stream.download.db.DbHolder;
import xyz.stream.download.info.FileInfo;
import xyz.stream.download.service.DownloadService;

/* JADX INFO: loaded from: classes3.dex */
public class DownloadManager {
    public static final int COMPLETE = 46;
    public static final int FAIL = 47;
    public static final int LOADING = 44;
    public static final String PARENT_DOWNLOAD_PATH = "/video/";
    public static final int PAUSE = 45;
    public static final int PREPARE = 43;
    public static final int WAIT = 42;

    /* JADX INFO: renamed from: m, reason: collision with root package name */
    public static volatile DownloadManager f36043m;

    /* JADX INFO: renamed from: a, reason: collision with root package name */
    public Context f36044a;

    /* JADX INFO: renamed from: b, reason: collision with root package name */
    public String f36045b;

    /* JADX INFO: renamed from: c, reason: collision with root package name */
    public volatile ApiBridge f36046c;

    /* JADX INFO: renamed from: d, reason: collision with root package name */
    public DownloadProgressListener f36047d;
    public List<DownloadFile> downloadTaskList;

    /* JADX INFO: renamed from: f, reason: collision with root package name */
    public DownloadDao f36049f;

    /* JADX INFO: renamed from: g, reason: collision with root package name */
    public DownloadDatabase f36050g;

    /* JADX INFO: renamed from: h, reason: collision with root package name */
    public DownloadFile f36051h;

    /* JADX INFO: renamed from: i, reason: collision with root package name */
    public final HashMap f36052i = new HashMap();

    /* JADX INFO: renamed from: j, reason: collision with root package name */
    public final Handler f36053j = new Handler(Looper.getMainLooper());

    /* JADX INFO: renamed from: k, reason: collision with root package name */
    public final OkHttpClient f36054k = new OkHttpClient();

    /* JADX INFO: renamed from: l, reason: collision with root package name */
    public final BroadcastReceiver f36055l = new AnonymousClass1();

    /* JADX INFO: renamed from: e, reason: collision with root package name */
    public final ExecutorService f36048e = Executors.newFixedThreadPool(10);

    /* JADX INFO: renamed from: xyz.stream.download.DownloadManager$1, reason: invalid class name */
    public class AnonymousClass1 extends BroadcastReceiver {

        /* JADX INFO: renamed from: b, reason: collision with root package name */
        public static final /* synthetic */ int f36056b = 0;

        public AnonymousClass1() {
        }

        /* JADX WARN: Type inference failed for: r10v9, types: [xyz.stream.download.g] */
        @Override // android.content.BroadcastReceiver
        public void onReceive(Context context, Intent intent) {
            if (intent == null || !Objects.equals(intent.getAction(), "download_movie_helper_first_action")) {
                return;
            }
            FileInfo fileInfo = Build.VERSION.SDK_INT >= 33 ? (FileInfo) intent.getSerializableExtra(DownloadConstant.EXTRA_INTENT_DOWNLOAD, FileInfo.class) : (FileInfo) h.getSerializableExtra(intent, DownloadConstant.EXTRA_INTENT_DOWNLOAD, FileInfo.class);
            if (fileInfo == null) {
                return;
            }
            final int downloadLocation = fileInfo.getSize() > 0 ? (int) (((float) ((fileInfo.getDownloadLocation() * 1.0d) / fileInfo.getSize())) * 100.0f) : 0;
            final float downloadLocation2 = (fileInfo.getDownloadLocation() / 1024.0f) / 1024.0f;
            final float size = (fileInfo.getSize() / 1024.0f) / 1024.0f;
            final int downloadStatus = fileInfo.getDownloadStatus();
            final String id2 = fileInfo.getId();
            t4.d dVarG = t4.f.x(DownloadManager.this.downloadTaskList).e(new f(fileInfo.getFilePath(), 0)).g();
            ?? r10 = new Object() { // from class: xyz.stream.download.g
                public final void a(Object obj) {
                    DownloadFile downloadFile = (DownloadFile) obj;
                    DownloadManager downloadManager = DownloadManager.this;
                    downloadManager.getClass();
                    int i10 = downloadStatus;
                    int i11 = downloadLocation;
                    float f10 = downloadLocation2;
                    float f11 = size;
                    switch (i10) {
                        case 42:
                            downloadFile.setDownloadId(id2);
                            downloadFile.setStatus(Integer.valueOf(i10));
                            downloadManager.c(downloadFile);
                            return;
                        case 43:
                        case 46:
                            downloadManager.updateNotification(downloadManager.f36044a, downloadFile.getFileName(), 100, R.drawable.stat_sys_download_done);
                            break;
                        case 44:
                            downloadFile.setStatus(Integer.valueOf(i10));
                            downloadFile.setProgress(Integer.valueOf(i11));
                            downloadFile.setTotalBytes(Integer.valueOf((int) f11));
                            downloadFile.setCurrentBytes(Integer.valueOf((int) f10));
                            downloadManager.c(downloadFile);
                            downloadManager.updateNotification(downloadManager.f36044a, downloadFile.getFileName(), i11, R.drawable.stat_sys_download);
                            return;
                        case 45:
                            downloadFile.setStatus(Integer.valueOf(i10));
                            downloadFile.setCurrentBytes(Integer.valueOf((int) f10));
                            downloadFile.setTotalBytes(Integer.valueOf((int) f11));
                            downloadFile.setProgress(Integer.valueOf(i11));
                            downloadManager.c(downloadFile);
                            downloadManager.updateNotification(downloadManager.f36044a, downloadFile.getFileName(), i11, R.drawable.ic_media_pause);
                            return;
                        case 47:
                            break;
                        default:
                            return;
                    }
                    downloadFile.setStatus(Integer.valueOf(i10));
                    downloadManager.c(downloadFile);
                }
            };
            Object obj = dVarG.f32947a;
            if (obj != null) {
                r10.a(obj);
            }
        }
    }

    public interface ApiBridge {
        void deleteDownloadData(String str);

        String getDownloadUrl(String str, String str2);

        void getSubtitles(int i10, SubtitleCallback subtitleCallback);
    }

    public interface SubtitleCallback {
        void onSubtitleFetched(List<SubtitleInfo> list);
    }

    public static class SubtitleInfo {

        /* JADX INFO: renamed from: a, reason: collision with root package name */
        public final String f36060a;

        /* JADX INFO: renamed from: b, reason: collision with root package name */
        public final String f36061b;

        /* JADX INFO: renamed from: c, reason: collision with root package name */
        public final String f36062c;

        public SubtitleInfo(String str, String str2, String str3) {
            this.f36060a = str;
            this.f36061b = str2;
            this.f36062c = str3;
        }

        public String getName() {
            return this.f36060a;
        }

        public String getTurboUrl() {
            return this.f36061b;
        }

        public String getType() {
            return this.f36062c;
        }
    }

    public static void a(DownloadManager downloadManager, int i10, String str, List list) throws Throwable {
        downloadManager.getClass();
        if (list.isEmpty()) {
            return;
        }
        Iterator it = list.iterator();
        while (it.hasNext()) {
            SubtitleInfo subtitleInfo = (SubtitleInfo) it.next();
            if (subtitleInfo.getName() != null && !subtitleInfo.getName().isEmpty()) {
                if (Boolean.FALSE.equals(downloadManager.f36052i.get(Integer.valueOf(i10)))) {
                    return;
                }
                String turboUrl = subtitleInfo.getTurboUrl();
                String type = subtitleInfo.getType();
                String name = subtitleInfo.getName();
                if (!name.endsWith("." + type)) {
                    name = defpackage.e.j(name, ".", type);
                }
                File file = new File(defpackage.e.o(u.a.c(str), File.separator, name));
                if (!file.exists() || file.length() < 100) {
                    String string = UUID.randomUUID().toString();
                    if (!turboUrl.startsWith("http")) {
                        ApiBridge apiBridge = downloadManager.f36046c;
                        if (apiBridge != null) {
                            turboUrl = apiBridge.getDownloadUrl(string, turboUrl) + "&file-raw-data=1";
                        }
                    }
                    ve.b bVar = new ve.b(downloadManager, turboUrl, 27);
                    File parentFile = file.getParentFile();
                    if (parentFile == null || parentFile.exists() || parentFile.mkdirs()) {
                        downloadManager.f36054k.newCall(new Request.Builder().url(turboUrl).build()).enqueue(new Callback(turboUrl, bVar, file) { // from class: xyz.stream.download.DownloadManager.2

                            /* JADX INFO: renamed from: a, reason: collision with root package name */
                            public final /* synthetic */ Runnable f36058a;

                            /* JADX INFO: renamed from: b, reason: collision with root package name */
                            public final /* synthetic */ File f36059b;

                            {
                                this.f36058a = bVar;
                                this.f36059b = file;
                            }

                            @Override // okhttp3.Callback
                            public void onFailure(Call call, IOException iOException) {
                                this.f36058a.run();
                            }

                            /* JADX WARN: Removed duplicated region for block: B:57:0x0054 A[EXC_TOP_SPLITTER, SYNTHETIC] */
                            @Override // okhttp3.Callback
                            /*
                                Code decompiled incorrectly, please refer to instructions dump.
                            */
                            public void onResponse(Call call, Response response) {
                                FileOutputStream fileOutputStream;
                                byte[] bArr;
                                File file2 = this.f36059b;
                                boolean zIsSuccessful = response.isSuccessful();
                                Runnable runnable = this.f36058a;
                                if (zIsSuccessful) {
                                    try {
                                        try {
                                        } catch (Exception unused) {
                                            file2.getAbsolutePath();
                                        }
                                        if (response.body() != null) {
                                            try {
                                                ResponseBody responseBodyBody = response.body();
                                                Objects.requireNonNull(responseBodyBody);
                                                InputStream inputStreamByteStream = responseBodyBody.byteStream();
                                                try {
                                                    fileOutputStream = new FileOutputStream(file2);
                                                    try {
                                                        bArr = new byte[8192];
                                                    } finally {
                                                    }
                                                } finally {
                                                }
                                                while (true) {
                                                    int i11 = inputStreamByteStream.read(bArr);
                                                    if (i11 == -1) {
                                                        break;
                                                    } else {
                                                        fileOutputStream.write(bArr, 0, i11);
                                                    }
                                                }
                                                fileOutputStream.flush();
                                                fileOutputStream.close();
                                                inputStreamByteStream.close();
                                                response.close();
                                                return;
                                            } catch (Throwable th) {
                                                try {
                                                    response.close();
                                                } catch (Throwable th2) {
                                                    th.addSuppressed(th2);
                                                }
                                                throw th;
                                            }
                                        }
                                    } finally {
                                        runnable.run();
                                    }
                                }
                                response.close();
                            }
                        });
                    } else {
                        bVar.run();
                    }
                }
            }
        }
    }

    public static DownloadManager getInstance() {
        if (f36043m == null) {
            synchronized (DownloadManager.class) {
                try {
                    if (f36043m == null) {
                        f36043m = new DownloadManager();
                        return f36043m;
                    }
                } finally {
                }
            }
        }
        return f36043m;
    }

    public final String b(String str) {
        ApiBridge apiBridge = this.f36046c;
        return apiBridge == null ? str : u1.j(apiBridge.getDownloadUrl(UUID.randomUUID().toString(), str), "&file-raw-data=1");
    }

    public final void c(DownloadFile downloadFile) {
        this.f36053j.post(new e(this, downloadFile, 1));
    }

    public void deleteDownloadTask(Integer num) {
        this.f36053j.post(new d(this, num, 0));
    }

    public void destroy() {
        try {
            this.f36044a.unregisterReceiver(this.f36055l);
        } catch (IllegalArgumentException e10) {
            e10.getMessage();
        }
    }

    public void downloadSubtitles(String str, int i10) {
        ApiBridge apiBridge = this.f36046c;
        if (apiBridge == null) {
            return;
        }
        apiBridge.getSubtitles(i10, new s(this, i10, str));
    }

    @SuppressLint({"WrongConstant", "InlinedApi", "UnspecifiedRegisterReceiverFlag"})
    public void init(Context context, String str) {
        Context applicationContext = context.getApplicationContext();
        this.f36044a = applicationContext;
        this.f36045b = str;
        DownloadDatabase downloadDatabaseCreateFromFile = DownloadDatabase.createFromFile(applicationContext);
        this.f36050g = downloadDatabaseCreateFromFile;
        this.f36049f = downloadDatabaseCreateFromFile.dao();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("download_movie_helper_first_action");
        int i10 = Build.VERSION.SDK_INT;
        BroadcastReceiver broadcastReceiver = this.f36055l;
        if (i10 >= 26) {
            applicationContext.registerReceiver(broadcastReceiver, intentFilter, 2);
        } else {
            applicationContext.registerReceiver(broadcastReceiver, intentFilter);
        }
    }

    public void pauseDownloadTask(Integer num) {
        Object obj = t4.f.x(this.downloadTaskList).e(new c(0, num)).g().f32947a;
        if (obj == null) {
            obj = null;
        }
        DownloadFile downloadFile = (DownloadFile) obj;
        if (downloadFile == null) {
            return;
        }
        DownloadHelper.getInstance().pauseTask(downloadFile.getDownloadUrl(), new File(downloadFile.getFilePath()), "download_movie_helper_first_action").submit(this.f36044a);
    }

    public List<DownloadFile> queryDownloadTask(boolean z10) {
        try {
            return (List) this.f36048e.submit(new u(1, this, z10)).get();
        } catch (InterruptedException | ExecutionException e10) {
            e10.getMessage();
            e10.getMessage();
            return null;
        }
    }

    public void removeDownloadProgressListener() {
        this.f36047d = null;
    }

    public void resumeDownloadTask(Integer num) {
        Object obj = t4.f.x(this.downloadTaskList).e(new c(1, num)).g().f32947a;
        if (obj == null) {
            obj = null;
        }
        DownloadFile downloadFile = (DownloadFile) obj;
        if (downloadFile == null) {
            return;
        }
        String strB = b(downloadFile.getDownloadUrl());
        File file = new File(downloadFile.getFilePath());
        downloadFile.setStatus(42);
        DownloadHelper.getInstance().addTask(strB, file, "download_movie_helper_first_action").submit(this.f36044a);
        downloadSubtitles(file.getParent(), num.intValue());
        c(downloadFile);
    }

    public void setApiBridge(ApiBridge apiBridge) {
        this.f36046c = apiBridge;
    }

    public void setDownloadProgressListener(DownloadProgressListener downloadProgressListener) {
        this.f36047d = downloadProgressListener;
    }

    public void startDownload(int i10, int i11, String str, String str2, Integer num, String str3, Integer num2, String str4, String str5, String str6, String str7, String str8) {
        File file;
        String str9;
        String str10;
        String str11;
        String strB = b(str5);
        if (str6 == null) {
            file = new File(this.f36044a.getFilesDir().getAbsolutePath() + PARENT_DOWNLOAD_PATH + str7);
        } else {
            StringBuilder sb = new StringBuilder();
            sb.append(this.f36044a.getFilesDir().getAbsolutePath());
            sb.append(PARENT_DOWNLOAD_PATH);
            sb.append(str6);
            file = new File(defpackage.e.o(sb, File.separator, str7));
        }
        if (!file.exists()) {
            file.mkdirs();
        }
        StringBuilder sb2 = new StringBuilder();
        sb2.append(file.getAbsolutePath());
        String strP = defpackage.e.p(sb2, File.separator, str7, ".mp4");
        File file2 = new File(strP);
        Integer numValueOf = Integer.valueOf(i10);
        Integer numValueOf2 = Integer.valueOf(i11);
        if (str4 != null) {
            try {
                if (!str4.isEmpty()) {
                    int i12 = Integer.parseInt(str4);
                    if (i12 == 0) {
                        str11 = SessionDescription.SUPPORTED_SDP_VERSION;
                    } else {
                        int i13 = i12 / 60;
                        int i14 = i12 % 60;
                        String str12 = "";
                        if (i13 == 0) {
                            str9 = SessionDescription.SUPPORTED_SDP_VERSION;
                            str10 = "";
                        } else {
                            str9 = SessionDescription.SUPPORTED_SDP_VERSION;
                            try {
                                str10 = i13 + CmcdData.STREAMING_FORMAT_HLS;
                            } catch (Exception e10) {
                                e = e10;
                                e.getMessage();
                                str11 = str9;
                            }
                        }
                        if (i14 != 0) {
                            str12 = i14 + CmcdData.OBJECT_TYPE_MANIFEST;
                        }
                        str11 = str10 + str12;
                    }
                }
                str9 = SessionDescription.SUPPORTED_SDP_VERSION;
            } catch (Exception e11) {
                e = e11;
                str9 = SessionDescription.SUPPORTED_SDP_VERSION;
            }
            str11 = str9;
        } else {
            str9 = SessionDescription.SUPPORTED_SDP_VERSION;
            str11 = str9;
        }
        this.f36051h = new DownloadFile(numValueOf, num, "", str5, strP, str7, 42, numValueOf2, 0, 0, 0, str2, str3, num2, str, str11, str8);
        t4.d dVarG = t4.f.x(this.downloadTaskList).e(new p(i10, 11, num)).g();
        xyz.netfly.mobile.player.d dVar = new xyz.netfly.mobile.player.d(this, strB, file2, file, num, i10);
        Object obj = dVarG.f32947a;
        if (obj == null) {
            dVar.run();
            return;
        }
        DownloadFile downloadFile = (DownloadFile) obj;
        DownloadHelper.getInstance().addTask(strB, file2, "download_movie_helper_first_action").submit(this.f36044a);
        downloadSubtitles(file.getAbsolutePath(), num != null ? num.intValue() : i10);
        this.f36051h = downloadFile;
        this.downloadTaskList.remove(downloadFile);
        this.downloadTaskList.add(this.f36051h);
        c(downloadFile);
    }

    public boolean subtitleIsDownloaded(File file) {
        FileInfo fileInfo;
        return file.exists() && (fileInfo = DbHolder.getInstance(this.f36044a).getFileInfo(file.getAbsolutePath())) != null && fileInfo.getDownloadStatus() == 46;
    }

    public void updateNotification(Context context, String str, int i10, int i11) {
        String str2;
        s0 contentTitle = new s0(context, DownloadService.CHANNEL_ID).setContentTitle(str);
        if (i10 > 0) {
            str2 = i10 + "%";
        } else {
            str2 = "0%";
        }
        s0 contentText = contentTitle.setContentText(str2);
        contentText.Q.icon = i11;
        contentText.b(2, true);
        Intent intent = new Intent();
        intent.setClassName(context.getPackageName(), this.f36045b);
        contentText.setContentIntent(PendingIntent.getActivity(context, 0, intent, 201326592));
        if (i10 > 0 && i10 < 100) {
            contentText.f1665t = 100;
            contentText.f1666u = i10;
            contentText.f1667v = false;
        }
        ((NotificationManager) context.getSystemService("notification")).notify(1, contentText.a());
    }
}
