package xyz.stream.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.widget.Toast;
import androidx.core.content.FileProvider;
import androidx.media3.common.C;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import xyz.stream.utils.entity.InstallEntity;

/* JADX INFO: loaded from: classes3.dex */
public abstract class h {

    /* JADX INFO: renamed from: a, reason: collision with root package name */
    public static final int[] f36140a = {2, 3, 5};

    /* JADX INFO: renamed from: b, reason: collision with root package name */
    public static final int[] f36141b = {1, 2, 3, 5, 10};

    public static void a(File file, File file2) throws IOException {
        FileOutputStream fileOutputStream;
        byte[] bArr;
        File parentFile = file2.getParentFile();
        if (parentFile != null && !parentFile.exists() && !parentFile.mkdirs()) {
            throw new IOException("Failed to create target parent dir");
        }
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            try {
                fileOutputStream = new FileOutputStream(file2, false);
                try {
                    bArr = new byte[8192];
                } finally {
                }
            } finally {
            }
            while (true) {
                int i10 = fileInputStream.read(bArr);
                if (i10 == -1) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    fileInputStream.close();
                    return;
                }
                fileOutputStream.write(bArr, 0, i10);
            }
        } catch (IOException e10) {
            b("Copy file failed: " + e10.getMessage());
            throw e10;
        }
    }

    public static void b(String str) {
        if (str == null) {
            str = "null";
        }
        f.p().y("XyzStream", str);
    }

    public static void c(String str) {
        if (str == null) {
            str = "null";
        }
        f.p().y("XyzStream", str);
    }

    public static String d(int i10) {
        if (i10 == 1) {
            return "home";
        }
        if (i10 == 2) {
            return "movie";
        }
        if (i10 == 3) {
            return "series";
        }
        if (i10 == 5) {
            return "kids";
        }
        switch (i10) {
            case 9:
                return "18plus";
            case 10:
                return "loading_page";
            case 11:
                return "sports";
            default:
                return "";
        }
    }

    public static void e(Activity activity, String str) {
        File file;
        Exception e10;
        File fileG;
        File externalStoragePublicDirectory;
        File externalStoragePublicDirectory2;
        if (activity == null || str == null || str.isEmpty()) {
            c("Install APK error: Apk file path is null or empty.");
            if (activity != null) {
                Toast.makeText(activity, "Install Error: Apk file not exist.", 1).show();
                return;
            }
            return;
        }
        File file2 = new File(str);
        if (!file2.exists() || !file2.isFile()) {
            c("Install APK error: Apk file not exist. path=".concat(str));
            Toast.makeText(activity, "Install Error: Apk file not exist.", 1).show();
            return;
        }
        String absolutePath = file2.getAbsolutePath();
        if (h(activity.getFilesDir(), absolutePath) || h(activity.getCacheDir(), absolutePath)) {
            try {
                externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            } catch (Exception e11) {
                file = null;
                e10 = e11;
            }
            if (externalStoragePublicDirectory != null) {
                file = new File(externalStoragePublicDirectory, "latest.write_test");
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(file);
                    fileOutputStream.write(0);
                    fileOutputStream.close();
                    file.delete();
                    externalStoragePublicDirectory2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
                } catch (Exception e12) {
                    e10 = e12;
                    if ((e10 instanceof FileNotFoundException) && e10.getMessage() != null && e10.getMessage().contains("EPERM")) {
                        b("Public Download EPERM");
                    }
                    if (file != null) {
                        try {
                            if (file.exists()) {
                                file.delete();
                            }
                        } catch (Exception e13) {
                            b("canWritePublicDownload cleanup failed: " + e13.getMessage());
                        }
                    }
                }
                if (externalStoragePublicDirectory2 != null) {
                    try {
                        fileG = g(new File(externalStoragePublicDirectory2, file2.getName()));
                        if (!f(file2, fileG)) {
                            a(file2, fileG);
                        }
                        i(file2.getAbsolutePath(), fileG.getAbsolutePath());
                        file2 = fileG;
                    } catch (IOException e14) {
                        b("Install APK fallback to internal file: " + e14.getMessage());
                    }
                } else {
                    b("Install APK fallback to internal file: public downloads dir is null");
                }
            }
            b("Install APK cannot write public download, fallback to internal file");
            File externalFilesDir = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
            if (externalFilesDir == null) {
                b("Install APK fallback to internal file: external downloads dir is null");
            } else {
                File file3 = new File(externalFilesDir, "apk_install");
                if (file3.exists() || file3.mkdirs()) {
                    try {
                        fileG = g(new File(file3, file2.getName()));
                        if (!f(file2, fileG)) {
                            a(file2, fileG);
                        }
                        i(file2.getAbsolutePath(), fileG.getAbsolutePath());
                        file2 = fileG;
                    } catch (IOException e15) {
                        b("Install APK fallback to internal file: " + e15.getMessage());
                    }
                } else {
                    b("Install APK fallback to internal file: create install dir failed");
                }
            }
        }
        if (Build.VERSION.SDK_INT >= 26 && !activity.getPackageManager().canRequestPackageInstalls()) {
            activity.startActivityForResult(new Intent("android.settings.MANAGE_UNKNOWN_APP_SOURCES", Uri.parse("package:" + activity.getPackageName())), 65793);
            return;
        }
        Uri uriForFile = FileProvider.getUriForFile(activity, activity.getPackageName() + ".fileProvider", file2);
        if (uriForFile == null) {
            Toast.makeText(activity, "Install Error: Invalid apk uri.", 1).show();
            return;
        }
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.setDataAndType(uriForFile, "application/vnd.android.package-archive");
        intent.setFlags(268435456);
        intent.addFlags(1);
        intent.addFlags(C.BUFFER_FLAG_NOT_DEPENDED_ON);
        intent.setClipData(ClipData.newRawUri("apk", uriForFile));
        try {
            Iterator<ResolveInfo> it = activity.getPackageManager().queryIntentActivities(intent, C.DEFAULT_BUFFER_SEGMENT_SIZE).iterator();
            while (it.hasNext()) {
                ActivityInfo activityInfo = it.next().activityInfo;
                if (activityInfo != null) {
                    activity.grantUriPermission(activityInfo.packageName, uriForFile, 1);
                }
            }
        } catch (Exception e16) {
            b("Install APK grant uri permission failed: " + e16.getMessage());
        }
        try {
            activity.startActivityForResult(intent, 65794);
        } catch (Exception e17) {
            c("Install APK error: " + e17.getMessage());
            Toast.makeText(activity, "Install Error: " + e17.getMessage(), 1).show();
        }
    }

    public static boolean f(File file, File file2) {
        return (file2.exists() && file.getAbsolutePath().equals(file2.getAbsolutePath())) || (file2.exists() && file.length() == file2.length() && file.lastModified() <= file2.lastModified());
    }

    public static File g(File file) throws IOException {
        if (!file.exists() || file.canWrite()) {
            return file;
        }
        File parentFile = file.getParentFile();
        if (parentFile == null) {
            throw new IOException("Target file parent is null");
        }
        String name = file.getName();
        int iLastIndexOf = name.lastIndexOf(46);
        String strSubstring = iLastIndexOf > 0 ? name.substring(0, iLastIndexOf) : name;
        String strSubstring2 = iLastIndexOf > 0 ? name.substring(iLastIndexOf) : "";
        for (int i10 = 1; i10 <= 20; i10++) {
            File file2 = new File(parentFile, strSubstring + "_" + i10 + strSubstring2);
            if (!file2.exists() || file2.canWrite()) {
                return file2;
            }
        }
        throw new IOException("No writable target file in dir: " + parentFile.getAbsolutePath());
    }

    public static boolean h(File file, String str) {
        if (file != null) {
            if (str.startsWith(file.getAbsolutePath() + File.separator)) {
                return true;
            }
        }
        return false;
    }

    public static void i(String str, String str2) {
        InstallEntity installEntity;
        try {
            if (!str.equals(str2) && (installEntity = (InstallEntity) f0.o().k(InstallEntity.class, "sp_install_entity")) != null && str.equals(installEntity.getSourcePath())) {
                installEntity.setInstallPath(str2);
                installEntity.setSourcePath(str);
                f0.o().B(installEntity, "sp_install_entity");
            }
        } catch (Exception e10) {
            b("Install APK sync install path failed: " + e10.getMessage());
        }
    }
}
