AppUpdateUtils.java 12.8 KB
package com.gimi.common.cinema.utils;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import com.gimi.common.cinema.model.AdsProof;
import com.gimi.common.cinema.model.AgentInfo;
import com.gimi.common.cinema.model.ApkMessage;
import com.gimi.common.cinema.model.PosterMessage;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.squareup.okhttp.Request;
import com.xgimi.gimicinema.BuildConfig;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.ParseException;

/**
 * Created by wugian on 2016/8/5
 */
public class AppUpdateUtils {
    private static final int APP_VERSION_UPDATE = 0x01;
    private static final int APP_VERSION_NEWEST = 0x04;
    private static final int DOWNLOAD_POSTER = 0x05;
    private static final int UPDATE_ADS_INFO = 0x06;
    private static final String API_ROOT = "http://api.qnbar.com";
    private static final String UPDATE_ADS_VIDEO_INFO = API_ROOT + "/Api/Agent/CheckAdVedio?checkCode=";
    private String updateApkUrl = API_ROOT + "/Api/Agent/CheckAppVersion?machineType=";// + XgimiDevice.getDeviceType() + "&imei=" + SystemUtils.getPID();
    private String updatePosterUrl = API_ROOT + "/Agent/GetPoster?imei=";// + SystemUtils.getPID();
    private String getAgentInfo = API_ROOT + "/Api/Agent/GetInfo?imei=";

    private Context context;
    private boolean showNoUpdate = true;
    private String adsVideoHash;
    private String sambaRootPath;
    private ApkMessage apkMessage;
    private PosterMessage posterMessage;
    private Handler handler;

    private static class AppUpdateHandler extends Handler {
        private final WeakReference<AppUpdateUtils> activity;

        AppUpdateHandler(AppUpdateUtils activity) {
            this.activity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            AppUpdateUtils a = activity.get();
            if (a != null) {
                switch (msg.what) {
                    case APP_VERSION_UPDATE:
                        a.doNewVersionUpdate();
                        break;
                    case APP_VERSION_NEWEST:
                        if (a.showNoUpdate) {
                            a.notNewVersionShow();
                        }
                        break;
                    case UPDATE_ADS_INFO:
                        a.updateAdsInfo();
                        break;
                    case DOWNLOAD_POSTER:
                        a.downloadPoster();
                        break;
                }
            }
        }
    }

    String pid;

    public AppUpdateUtils(Context context) {
        this.context = context;
        handler = new AppUpdateHandler(this);
        String deviceType = "8888";
        pid = SystemUtils.getPid(context, BuildConfig.MACHINE_TYPE);
        if (!BuildConfig.MACHINE_TYPE.equals("himedia")) {
            deviceType = XgimiDevice.getDeviceType();
        }
        updateApkUrl = API_ROOT + "/Api/Agent/CheckAppVersion?machineType="
                + deviceType + "&imei=" + pid;
        updatePosterUrl = API_ROOT + "/Agent/GetPoster?imei=" + pid;
    }

    //main false set true
    public void setShowNoUpdate(boolean showNoUpdate) {
        this.showNoUpdate = showNoUpdate;
    }

    public boolean updateAppVersion() {
        String verJson = null;
        try {
            verJson = OkHttpClientManager.getAsString(updateApkUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (TextUtils.isEmpty(verJson)) {
            return false;
        }
        try {
            Gson gson = new Gson();
            apkMessage = gson.fromJson(verJson, new TypeToken<ApkMessage>() {
            }.getType());
            if (apkMessage != null && apkMessage.getCode() == 0
                    && apkMessage.getData() != null) {
                if (apkMessage.getData().getVerCode() >
                        Config.getVerCode(context)) {
                    handler.sendEmptyMessage(APP_VERSION_UPDATE);
                } else {
                    handler.sendEmptyMessage(APP_VERSION_NEWEST);
                }
            } else {
                handler.sendEmptyMessage(APP_VERSION_NEWEST);
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        return true;
    }

    private void doNewVersionUpdate() {
        String verName = Config.getVerName(context);
        StringBuilder message = new StringBuilder();
        message.append("当前版本");
        message.append(verName);
        message.append(", 发现新版本");
        message.append(apkMessage.getData().getVerName());
        message.append(", 是否更新?");
        message.append("\n");
        String updateMsg = apkMessage.getData().getDescription();
        if (!TextUtils.isEmpty(updateMsg)) {
            if (updateMsg.contains("#")) {
                String[] split = updateMsg.split("#");
                for (String s : split) {
                    message.append("\n").append(s);
                }
            } else {
                message.append("\n").append(updateMsg);
            }
        }
        Dialog dialog = new AlertDialog.Builder(context)
                .setTitle("软件更新")
                .setMessage(message.toString())
                .setCancelable(false)
                // 设置内容
                .setPositiveButton("更新",// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog1, int which) {
                                String url = apkMessage.getData().getAppUrl();
                                if (!TextUtils.isEmpty(url)) {
                                    UpdateManager updateManager =
                                            new UpdateManager(context, url);
                                    updateManager.showDownloadDialog();
                                } else {
                                    dialog1.dismiss();
                                }
                            }
                        }).create();// 创建
        // 显示对话框
        dialog.show();
    }

    private void notNewVersionShow() {
        String verName = Config.getVerName(context);
        String string = "当前版本" +
                verName +
                "已是最新版本";
        Dialog dialog = new AlertDialog.Builder(context)
                .setTitle("软件更新")
                .setMessage(string)// 设置内容
                .setPositiveButton("确定",// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog1, int which) {
                                dialog1.dismiss();
                            }
                        }).create();// 创建
        // 显示对话框
        dialog.show();
    }

    public void updatePoster() {
        String verJson = null;
        try {
            verJson = OkHttpClientManager.getAsString(updatePosterUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (TextUtils.isEmpty(verJson)) {
            return;
        }
        try {
            Gson gson = new Gson();
            posterMessage = gson.fromJson(
                    verJson, new TypeToken<PosterMessage>() {
                    }.getType());
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
        if (posterMessage != null) {
            if (posterMessage.getCode() == 0) {
                handler.sendEmptyMessage(DOWNLOAD_POSTER);
            }
        }
    }

    private void downloadPoster() {
        File cacheDir = context.getCacheDir();
        File file = new File(String.valueOf(cacheDir));
        String[] child = file.list();
        String currentName = "";
        String oldPoster = "";
        for (String aChild : child) {
            if (aChild.endsWith("jpg")) {
                currentName = aChild.substring(0, aChild.indexOf("."));
                oldPoster = cacheDir + "/" + aChild;
            }
        }
        if (!currentName.equals(posterMessage.getData().getVersionId())) {
            //noinspection ResultOfMethodCallIgnored
            new File(oldPoster).delete();
            downImages(posterMessage.getData().getPosterUrl(), cacheDir
                    + "/" + posterMessage.getData().getVersionId() + ".jpg");
        }
    }

    private void downImages(String urlPath, String savePath) {
        OkHttpClientManager.downloadAsyn(urlPath, savePath,
                new OkHttpClientManager.ResultCallback<String>() {
                    @Override
                    public void onError(Request request, Exception e) {
                        Log.e("APpUpdateUtils", "success:" + e.getMessage());
                    }

                    @Override
                    public void onResponse(String response) {
                        Log.e("APpUpdateUtils", "success:" + response);
                    }
                });
    }


    public void updateVideoInfo(String sambaRootPath, String adsVideoHash) {
        this.sambaRootPath = sambaRootPath;
        this.adsVideoHash = adsVideoHash;
        if (TextUtils.isEmpty(adsVideoHash)) {
            return;
        }
        String verJson = null;
        try {
            verJson = OkHttpClientManager.getAsString(
                    UPDATE_ADS_VIDEO_INFO + adsVideoHash);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (TextUtils.isEmpty(verJson)) {
            return;
        }
        try {
            Gson gson = new Gson();
            AdsProof ads = gson.fromJson(verJson, new TypeToken<AdsProof>() {
            }.getType());
            if (ads != null) {
                if (ads.getCode() == 0) {
                    handler.sendEmptyMessage(UPDATE_ADS_INFO);
                }
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        }
    }

    private void updateAdsInfo() {
        AdsVideoUtils.writeAdsVideoInfo(sambaRootPath, adsVideoHash);
    }

    public void updateAgentInfo() {
        String verJson = null;
        try {
            verJson = OkHttpClientManager.getAsString(getAgentInfo + pid);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (TextUtils.isEmpty(verJson)) {
            return;
        }

        AgentInfo agentInfo = new AgentInfo();
        agentInfo.setCode(-3);
        try {
            agentInfo = new Gson().fromJson(verJson, AgentInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (agentInfo.getCode() == 0) {
            AgentInfo.DataBean.AgentBean agentBean = agentInfo.getData().getAgent();
            Utils.saveString(context, "agent-dist-time", agentBean.getDistTime());
            Utils.saveString(context, "agent-add-time", agentBean.getAddTime());
            String agentIdStr = agentBean.getAgentId();
            String agentType = agentBean.getAgentType();
            try {
                int i = Integer.parseInt(agentIdStr);
                Utils.saveInt(context, "agent-id", i);
                int agent = Integer.parseInt(agentType);
                Utils.saveInt(context, "agent-type", agent);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            long l = System.currentTimeMillis() / 1000;
            try {
                l = OkHttpClientManager.getSysTime(getAgentInfo + pid);
            } catch (IOException | ParseException e) {
                e.printStackTrace();
            }
            Utils.saveString(context, "agent-info-success", l + "");

//            long distTime = Long.parseLong(agentInfo.getData().getAgent().getDistTime());
//            long addTime = Long.parseLong(agentInfo.getData().getAgent().getAddTime());

//            if (l < distTime && l > addTime) {
//                AuthUtils.resetAuth(context);
//                AuthUtils.resetOfflineAccessCount(context);
//            }
        }
    }


    public void updateTestGroup() {
        String verJson = null;
        try {
            verJson = OkHttpClientManager.getAsString("https://raw.githubusercontent.com/wugian/abc/master/cinema/config");
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (TextUtils.isEmpty(verJson)) {
            return;
        }
        try {
            int i = Integer.parseInt(verJson.trim());
            Utils.saveInt(context, "test-limit", i);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }
}