DownloadFileModule.java 9 KB
package com.sunvote.xpadcomm;

import android.os.Environment;
import android.os.Handler;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;

import com.sunvote.util.LogUtil;
import com.sunvote.xpadapp.utils.FileUtil;

/**
 * Created by Elvis on 2017/12/25 15:32
 * Email:Eluis@psunsky.com
 * 版权所有:长沙中天电子设计开发有限公司
 * Description: 人大通用版XPadAppRD
 */
public class DownloadFileModule {

    public static final String TAG = "DonwloadFileModule";
    public final static String FILEPATH = Environment.getExternalStorageDirectory().getPath() + File.separator + "sunvote" + File.separator;
    public final static int DEFAULT_OVERTIME = 60000;
    private static volatile DownloadFileModule instnce;
    private DownloadFileSendThread downloadFileSendThread;
    private DownloadFileReceiverThread downloadFileReceiverThread;
    private FileOutputStream fileOutputStream;
    private String ip;
    private int port;
    private int currentBlockId = -1;
    private long receiverSize = 0;
    private long fileLength = 0;
    private byte flag = -1;
    private int index = -1;
    private int keypadId = 0;
    private String fileName;
    private InetAddress servInetAddress;
    private long overTime = DEFAULT_OVERTIME ;
    private FileReciverInterface fileReciverInterface;
    private Handler handler ;
    private boolean work = false;
    private DownloadFileReceiverThread.OnDownloadCmdListener onDownloadCmdListener = new DownloadFileReceiverThread.OnDownloadCmdListener() {
        @Override
        public void onReceiverFileInfo(String filename, long length, byte fileFlag) {
            if(handler != null) {
                handler.removeCallbacks(checkTask);
                handler.postDelayed(checkTask, overTime);
            }
            if(flag != fileFlag) {
                flag = fileFlag;
                File folder = new File(FILEPATH);
                if (!folder.exists()) {
                    folder.mkdir();
                    if (folder.exists()) {
                        LogUtil.d(TAG, "create dir ok!");
                    }
                }
                fileName = filename;
                File saveFile = new File(FILEPATH + filename);
                if (saveFile.exists()) {
                    saveFile.delete();
                }
                try {
                    fileOutputStream = new FileOutputStream(saveFile);
                } catch (FileNotFoundException e) {
                    LogUtil.e(TAG, e);
                }
                fileLength = length;
                index = currentBlockId = 0;
                sendNextData((byte) 2, index);
                if (fileReciverInterface != null) {
                    fileReciverInterface.onDownload(0);
                }
            }
        }

        @Override
        public void onReceiverFileData(int blockId, byte[] datas, int start, int dataLen) {
            if(handler != null) {
                handler.removeCallbacks(checkTask);
                handler.postDelayed(checkTask, overTime);
            }
            if (blockId == currentBlockId) {
                if (fileOutputStream != null) {
                    try {
                        receiverSize += dataLen;
                        index++;
                        currentBlockId++;
                        fileOutputStream.write(datas, start, dataLen);
                        fileOutputStream.flush();
                        if (fileReciverInterface != null) {
                            long per = (receiverSize * 100 / fileLength);
                            fileReciverInterface.onDownload(per);
                        }
                        if(receiverSize >= fileLength){
                            try{
                                fileOutputStream.close();
                                fileOutputStream = null;
                            }catch (Exception ex){
                                LogUtil.e(TAG,ex);
                            }
                            unzip();
                        }
                        sendNextData((byte)2,index);
                    } catch (IOException e) {
                        LogUtil.e(TAG, e);
                    }
                }
            }
        }

        @Override
        public void onFileDownloadCompeleted() {
            if(handler != null) {
                handler.removeCallbacks(checkTask);
            }
            work = false;
            closeStream();
        }
    };

    public static DownloadFileModule getInstance() {
        if (instnce == null) {
            synchronized (DownloadFileModule.class) {
                if (instnce == null) {
                    instnce = new DownloadFileModule();
                }
            }
        }
        return instnce;
    }

    public void downloadFile(String ip, int port,int keypadId) {
        clean();
        this.ip = ip;
        this.port = port;
        this.keypadId = keypadId;
        downloadFileSendThread = new DownloadFileSendThread();
        downloadFileReceiverThread = new DownloadFileReceiverThread(DownloadFileReceiverThread.DEFAULT_PROT);
        downloadFileReceiverThread.setOnDownloadCmdListener(onDownloadCmdListener);
        downloadFileReceiverThread.start();
        sendNextData((byte)0x01,this.keypadId);
        handler = new Handler();
        handler.postDelayed(checkTask,overTime);
        work = true;
    }

    public void clean() {
        closeStream();
        resetData();
        work = false;
    }

    public boolean isWork() {
        return work;
    }

    private void unzip(){
        if (fileName.endsWith(".zip") || fileName.endsWith(".rar") || fileName.endsWith(".7z")) {
            String outDirName = "";
            boolean isAdd = false;
            if(fileName.startsWith("q")){
                isAdd = true;
            }
            if(isAdd){
                outDirName = fileName.substring(1,fileName.length() - 4);
            }else{
                outDirName = fileName.substring(0, fileName.length() - 4);
            }
            String uzipDirPath = FILEPATH + "/" + outDirName;

            if(!isAdd){
                createAndCleanFolder(uzipDirPath);
            }
            try {
                boolean ret = AntZipUtil.unZip(FILEPATH + fileName, uzipDirPath);
                if (fileReciverInterface != null) {
                    if(ret){
                        fileReciverInterface.onDownloadSuccess();
                    }else{
                        fileReciverInterface.onUnzipError();
                    }
                }
            } catch (Exception e) {
                LogUtil.e(TAG,e);
                if(fileReciverInterface != null){
                    fileReciverInterface.onUnzipError();
                }
            }
        }
    }

    private void resetData() {
        ip = null;
        port = 0;
        currentBlockId = -1;
        receiverSize = 0;
        fileLength = 0;
        flag = -1;
        index = -1;
        servInetAddress = null;
        fileName = null;
        keypadId = 0 ;
        handler = null;
    }

    private void closeStream() {
        if (downloadFileSendThread != null) {
            downloadFileSendThread.close();
            downloadFileSendThread = null;
        }
        if (downloadFileReceiverThread != null) {
            downloadFileReceiverThread.close();
            downloadFileReceiverThread = null;
        }

        if (fileOutputStream != null) {
            try {
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (IOException e) {
                LogUtil.e(TAG,e);
            }
            fileOutputStream = null;
        }
    }

    private void sendNextData(byte type ,int index) {
        downloadFileSendThread.sendData(flag,type,index,ip,port);
    }

    public void createAndCleanFolder(String folderName) {
        File unzipDir = new File(folderName);
        if (unzipDir.exists()) {
            try {
                LogUtil.d(TAG, "clear dir");
                FileUtil.deleteFileInDir(unzipDir);
            } catch (Exception e) {
                LogUtil.e(TAG, e);
            }
        } else {
            boolean ret = false;
            try {
                ret = unzipDir.mkdir();
            } catch (Exception e) {
                LogUtil.e(TAG, e);
            }
            if (ret) {
                LogUtil.d(TAG, "createFile Ok, unzip!");
            } else {
                LogUtil.d(TAG, "createFile fail !" + folderName);
            }
        }
    }

    public void setFileReciverInterface(FileReciverInterface fileReciverInterface) {
        this.fileReciverInterface = fileReciverInterface;
    }

    private Runnable checkTask = new Runnable() {
        @Override
        public void run() {
            if(fileReciverInterface != null){
                fileReciverInterface.onDownloadDataError();
            }
            clean();
        }
    };

    public void setOverTime(long overTime) {
        this.overTime = overTime;
    }
}