package com.dowse.base.util;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageInstaller;
import android.content.pm.PackageManager;
import com.dowse.base.log.DSLog;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;

/* loaded from: ds_base_2.0.9_23030112.aar:classes.jar:com/dowse/base/util/APKUtil.class */
public class APKUtil {
    private static final String TAG = "APKUpdate";

    private static void output(Process mProcess) {
        try {
            BufferedReader mReader = new BufferedReader(new InputStreamReader(mProcess.getInputStream()));
            while (true) {
                String msg = mReader.readLine();
                if (msg != null) {
                    DSLog.e(TAG, "mProcess result:" + msg);
                } else {
                    mReader.close();
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void installAPK2(Context context, String apkFilePath) {
        String installCmd = "pm install -r " + apkFilePath;
        try {
            Process mProcess = Runtime.getRuntime().exec(installCmd);
            mProcess.waitFor();
            int return_value = mProcess.exitValue();
            DSLog.e(TAG, "mProcess result exitValue:" + return_value);
            output(mProcess);
        } catch (Exception e) {
            e.printStackTrace();
            DSLog.e(TAG, "installAPK2 Exception " + e.getMessage());
        }
    }

    public static String getPackageName(Context context, String filePath) {
        String packageName = "";
        PackageManager pm = context.getPackageManager();
        PackageInfo info = pm.getPackageArchiveInfo(filePath, 1);
        if (info != null) {
            packageName = info.packageName;
        }
        return packageName;
    }

    @TargetApi(21)
    public static void installAPK(Context context, String apkFilePath) {
        DSLog.d(TAG, "--->>>install()--->>> apkFilePath:" + apkFilePath);
        PackageManager packageManager = context.getPackageManager();
        registerAndroidPackageReceiver(context);
        File apkFile = new File(apkFilePath);
        PackageInstaller packageInstaller = packageManager.getPackageInstaller();
        PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(1);
        sessionParams.setSize(apkFile.length());
        packageInstaller.registerSessionCallback(new PackageInstaller.SessionCallback() { // from class: com.dowse.base.util.APKUtil.1
            @Override // android.content.pm.PackageInstaller.SessionCallback
            public void onCreated(int sessionId) {
                DSLog.d(APKUtil.TAG, "--->>>onCreated()--->>> sessionId:" + sessionId);
            }

            @Override // android.content.pm.PackageInstaller.SessionCallback
            public void onBadgingChanged(int sessionId) {
                DSLog.d(APKUtil.TAG, "--->>>onBadgingChanged()--->>> sessionId:" + sessionId);
            }

            @Override // android.content.pm.PackageInstaller.SessionCallback
            public void onActiveChanged(int sessionId, boolean active) {
                DSLog.d(APKUtil.TAG, "--->>>onActiveChanged()--->>> sessionId:" + sessionId + ",active:" + active);
            }

            @Override // android.content.pm.PackageInstaller.SessionCallback
            public void onProgressChanged(int sessionId, float progress) {
                DSLog.d(APKUtil.TAG, "--->>>onProgressChanged()--->>> sessionId:" + sessionId + ",progress:" + progress);
            }

            @Override // android.content.pm.PackageInstaller.SessionCallback
            public void onFinished(int sessionId, boolean success) {
                DSLog.d(APKUtil.TAG, "--->>>onFinished()--->>> sessionId:" + sessionId + ",success: " + success);
            }
        });
        int sessionId = createSession(packageInstaller, sessionParams);
        if (sessionId != -1) {
            boolean copySuccess = copyInstallFile(packageInstaller, sessionId, apkFilePath);
            DSLog.d(TAG, "--->>>install28()--->>> copy Success apkFilePath:" + apkFilePath);
            if (copySuccess) {
                execInstallCommand(context, packageInstaller, sessionId);
                if (getPackageName(context, apkFilePath).equals("com.dowse.camera")) {
                    reboot(context);
                }
            }
        }
    }

    public static void reboot(Context context) {
        Intent reboot = new Intent("android.intent.action.REBOOT");
        reboot.putExtra("nowait", 1);
        reboot.putExtra("interval", 1);
        reboot.putExtra("window", 0);
        context.sendBroadcast(reboot);
    }

    @TargetApi(21)
    private static int createSession(PackageInstaller packageInstaller, PackageInstaller.SessionParams sessionParams) {
        int sessionId = -1;
        try {
            sessionId = packageInstaller.createSession(sessionParams);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sessionId;
    }

    private static void registerAndroidPackageReceiver(Context context) {
        IntentFilter installFilter = new IntentFilter();
        installFilter.addAction("android.content.pm.extra.STATUS");
        InstallResultReceiver installResultReceiver = new InstallResultReceiver();
        context.registerReceiver(installResultReceiver, installFilter);
    }

    @TargetApi(21)
    private static boolean copyInstallFile(PackageInstaller packageInstaller, int sessionId, String apkFilePath) {
        DSLog.d(TAG, "--->>>copyInstallFile()--->>> sessionId:" + sessionId + ", apkFilePath:" + apkFilePath);
        InputStream in = null;
        OutputStream out = null;
        PackageInstaller.Session session = null;
        boolean success = false;
        try {
            try {
                File apkFile = new File(apkFilePath);
                session = packageInstaller.openSession(sessionId);
                out = session.openWrite("base.apk", 0L, apkFile.length());
                in = new FileInputStream(apkFile);
                int total = 0;
                byte[] buffer = new byte[65536];
                while (true) {
                    int c = in.read(buffer);
                    if (c == -1) {
                        break;
                    }
                    total += c;
                    out.write(buffer, 0, c);
                }
                session.fsync(out);
                DSLog.i(TAG, "streamed " + total + " bytes");
                success = true;
                IoUtils.closeQuietly(out);
                IoUtils.closeQuietly(in);
                IoUtils.closeQuietly(session);
            } catch (IOException e) {
                e.printStackTrace();
                IoUtils.closeQuietly(out);
                IoUtils.closeQuietly(in);
                IoUtils.closeQuietly(session);
            }
            return success;
        } catch (Throwable th) {
            IoUtils.closeQuietly(out);
            IoUtils.closeQuietly(in);
            IoUtils.closeQuietly(session);
            throw th;
        }
    }

    @TargetApi(21)
    private static void execInstallCommand(Context context, PackageInstaller packageInstaller, int sessionId) {
        DSLog.d(TAG, "--->>>execInstallCommand()--->>> sessionId:" + sessionId);
        PackageInstaller.Session session = null;
        try {
            try {
                session = packageInstaller.openSession(sessionId);
                Intent intent = new Intent(context, InstallResultReceiver.class);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 134217728);
                session.commit(pendingIntent.getIntentSender());
                IoUtils.closeQuietly(session);
            } catch (IOException e) {
                e.printStackTrace();
                IoUtils.closeQuietly(session);
            }
        } catch (Throwable th) {
            IoUtils.closeQuietly(session);
            throw th;
        }
    }

    /* loaded from: ds_base_2.0.9_23030112.aar:classes.jar:com/dowse/base/util/APKUtil$IoUtils.class */
    public static final class IoUtils {
        public static void closeQuietly(Closeable c) {
            if (c != null) {
                try {
                    c.close();
                } catch (IOException ignored) {
                    ignored.printStackTrace();
                }
            }
        }
    }

    /* loaded from: ds_base_2.0.9_23030112.aar:classes.jar:com/dowse/base/util/APKUtil$InstallResultReceiver.class */
    public static class InstallResultReceiver extends BroadcastReceiver {
        @Override // android.content.BroadcastReceiver
        public void onReceive(Context context, Intent intent) {
            DSLog.d(APKUtil.TAG, "onReceive() -> intent: " + intent.getAction());
            if (intent != null) {
                int status = intent.getIntExtra("android.content.pm.extra.STATUS", 1);
                if (status == 0) {
                    DSLog.d(APKUtil.TAG, "onReceive -> install success");
                } else {
                    DSLog.d(APKUtil.TAG, "onReceive -> install fail");
                }
            }
            context.unregisterReceiver(this);
        }
    }

    public static void startAPK(Context mContext, String packageName) {
        Intent mainIntent = mContext.getPackageManager().getLaunchIntentForPackage(packageName);
        if (mainIntent == null) {
            return;
        }
        mainIntent.addFlags(268435456);
        try {
            mContext.startActivity(mainIntent);
            DSLog.d(TAG, "startAPK name = " + packageName);
        } catch (ActivityNotFoundException e) {
            DSLog.e(TAG, "Package not found!,start failed,package name = " + packageName);
        }
    }

    public static void stopAPK(Context mContext, String packageName) {
        ActivityManager mActivityManager = (ActivityManager) mContext.getSystemService("activity");
        try {
            Method method = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String.class);
            method.invoke(mActivityManager, packageName);
            DSLog.d(TAG, "stopAPK name = " + packageName);
        } catch (Exception e) {
            e.printStackTrace();
            DSLog.e(TAG, "forceStopPackage failed!,package name = " + packageName + ",exception:" + e.getMessage());
        }
    }

    public static int getVersionCode(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        long code = -1;
        try {
            PackageInfo info = manager.getPackageInfo(packageName, 0);
            code = info.getLongVersionCode();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return (int) code;
    }

    public static String getVersionName(Context context, String packageName) {
        PackageManager manager = context.getPackageManager();
        String name = "";
        try {
            PackageInfo info = manager.getPackageInfo(packageName, 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return name;
    }
}
