导航菜单

页面标题

页面副标题

⁡⁡⁡⁡⁡⁡⁡鲸⁡⁡⁡⁡⁡⁡⁡⁡鱼⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡借⁡条⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡ v4.1.2 - Downloader.java 源代码

正在查看: ⁡⁡⁡⁡⁡⁡⁡鲸⁡⁡⁡⁡⁡⁡⁡⁡鱼⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡借⁡条⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡⁡ v4.1.2 应用的 Downloader.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.download.library;

import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.StatFs;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Base64;
import android.util.SparseArray;
import com.alipay.alipaysecuritysdk.common.exception.ErrorCode;
import com.just.agentweb.AgentWebPermissions;
import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;
import kotlin.jvm.internal.LongCompanionObject;

public class Downloader extends AsyncTask implements IDownloader<DownloadTask>, ExecuteTask {
    private static final int BUFFER_SIZE = 8192;
    public static final int ERROR_LOAD = 16393;
    public static final int ERROR_MD5 = 16401;
    public static final int ERROR_NETWORK_CONNECTION = 16384;
    public static final int ERROR_RESOURCE_NOT_FOUND = 16400;
    public static final int ERROR_RESPONSE_STATUS = 16385;
    public static final int ERROR_SERVICE = 20483;
    public static final int ERROR_SHUTDOWN = 16391;
    public static final int ERROR_STORAGE = 16386;
    public static final int ERROR_TIME_OUT = 16387;
    public static final int ERROR_TOO_MANY_REDIRECTS = 16392;
    public static final int ERROR_USER_CANCEL = 16390;
    public static final int ERROR_USER_PAUSE = 16388;
    public static final int HTTP_RANGE_NOT_SATISFIABLE = 4016;
    private static final int HTTP_TEMP_REDIRECT = 307;
    private static final int MAX_REDIRECTS = 7;
    public static final int SUCCESSFUL = 8192;
    protected volatile DownloadTask mDownloadTask;
    protected volatile Throwable mThrowable;
    private static final String TAG = "Download-" + Downloader.class.getSimpleName();
    protected static final SparseArray<String> DOWNLOAD_MESSAGE = new SparseArray<>(13);
    private static final Handler HANDLER = new Handler(Looper.getMainLooper());
    private volatile long mLoaded = 0;
    protected volatile long mTotals = -1;
    private long mLastLoaded = 0;
    private long mUsedTime = 0;
    private long mLastTime = 0;
    private volatile long mBeginTime = 0;
    private volatile long mAverageSpeed = 0;
    protected long mDownloadTimeOut = LongCompanionObject.MAX_VALUE;
    protected long mConnectTimeOut = 10000;
    protected volatile boolean enableProgress = false;
    protected boolean mCallbackInMainThread = false;
    protected boolean quickProgress = false;
    private StringBuffer mDownloadMessage = new StringBuffer();

    @Override
    public boolean download(DownloadTask downloadTask) {
        return true;
    }

    static long access$014(Downloader downloader, long j) {
        long j2 = downloader.mLoaded + j;
        downloader.mLoaded = j2;
        return j2;
    }

    static {
        DOWNLOAD_MESSAGE.append(16384, "Network connection error . ");
        DOWNLOAD_MESSAGE.append(ERROR_RESPONSE_STATUS, "Response code non-200 or non-206 . ");
        DOWNLOAD_MESSAGE.append(16386, "Insufficient memory space . ");
        DOWNLOAD_MESSAGE.append(ERROR_SHUTDOWN, "Shutdown . ");
        DOWNLOAD_MESSAGE.append(ERROR_TIME_OUT, "Download time is overtime . ");
        DOWNLOAD_MESSAGE.append(ERROR_USER_CANCEL, "The user canceled the download . ");
        DOWNLOAD_MESSAGE.append(ERROR_RESOURCE_NOT_FOUND, "Resource not found . ");
        DOWNLOAD_MESSAGE.append(ERROR_USER_PAUSE, "paused . ");
        DOWNLOAD_MESSAGE.append(ERROR_LOAD, "IO Error . ");
        DOWNLOAD_MESSAGE.append(ERROR_SERVICE, "Service Unavailable . ");
        DOWNLOAD_MESSAGE.append(ERROR_TOO_MANY_REDIRECTS, "Too many redirects . ");
        DOWNLOAD_MESSAGE.append(ERROR_MD5, "Md5 check fails . ");
        DOWNLOAD_MESSAGE.append(8192, "Download successful . ");
    }

    protected Downloader() {
    }

    static ExecuteTask create(DownloadTask downloadTask) {
        Downloader downloader = new Downloader();
        downloader.mDownloadTask = downloadTask;
        downloader.mTotals = downloadTask.getTotalsLength();
        downloader.mDownloadTimeOut = downloadTask.getDownloadTimeOut();
        downloader.mConnectTimeOut = downloadTask.getConnectTimeOut();
        downloader.quickProgress = downloadTask.isQuickProgress();
        downloader.enableProgress = downloadTask.isEnableIndicator() || downloadTask.getDownloadingListener() != null;
        return downloader;
    }

    void checkIsNullTask(DownloadTask downloadTask) {
        if (downloadTask == null) {
            throw new NullPointerException("downloadTask can't be null.");
        }
        if (downloadTask.getContext() == null) {
            throw new NullPointerException("context can't be null.");
        }
    }

    private boolean checkSpace() {
        DownloadTask downloadTask = this.mDownloadTask;
        if (downloadTask.getTotalsLength() - downloadTask.getFile().length() <= getFsAvailableSize(downloadTask.getFile().getParent()) - 104857600) {
            return true;
        }
        Runtime.getInstance().logError(TAG, " 空间不足");
        return false;
    }

    public static long getFsAvailableSize(String str) {
        long blockSize;
        long availableBlocks;
        if (TextUtils.isEmpty(str)) {
            return 0L;
        }
        try {
            StatFs statFs = new StatFs(str);
            if (Build.VERSION.SDK_INT >= 18) {
                blockSize = statFs.getBlockSizeLong();
                availableBlocks = statFs.getAvailableBlocksLong();
            } else {
                blockSize = statFs.getBlockSize();
                availableBlocks = statFs.getAvailableBlocks();
            }
            return blockSize * availableBlocks;
        } catch (Throwable th) {
            th.printStackTrace();
            return 0L;
        }
    }

    private boolean checkNet() {
        DownloadTask downloadTask = this.mDownloadTask;
        if (!downloadTask.isForceDownload()) {
            return Runtime.getInstance().checkWifi(downloadTask.getContext());
        }
        return Runtime.getInstance().checkNetwork(downloadTask.getContext());
    }

    protected Integer doInBackground() {
        String str = "";
        DownloadTask downloadTask = this.mDownloadTask;
        boolean isPausing = downloadTask.isPausing();
        Integer valueOf = Integer.valueOf(ERROR_USER_PAUSE);
        if (isPausing) {
            downloadTask.pause();
            return valueOf;
        }
        if (downloadTask.isPaused()) {
            return valueOf;
        }
        if (downloadTask.isCanceled()) {
            return Integer.valueOf(ERROR_USER_CANCEL);
        }
        if (downloadTask.isDataURI()) {
            return Integer.valueOf(transferDataFromUrl());
        }
        this.mBeginTime = SystemClock.elapsedRealtime();
        if (!checkNet()) {
            Runtime.getInstance().logError(TAG, " Network error,isForceDownload:" + this.mDownloadTask.isForceDownload());
            downloadTask.error();
            return 16384;
        }
        StringBuffer stringBuffer = this.mDownloadMessage;
        stringBuffer.append("\r\n");
        stringBuffer.append("=============");
        stringBuffer.append("\n");
        StringBuffer stringBuffer2 = this.mDownloadMessage;
        stringBuffer2.append("Download Message");
        stringBuffer2.append("\n");
        StringBuffer stringBuffer3 = this.mDownloadMessage;
        stringBuffer3.append("downloadTask id=");
        stringBuffer3.append(downloadTask.getId());
        stringBuffer3.append("\n");
        StringBuffer stringBuffer4 = this.mDownloadMessage;
        stringBuffer4.append("url=");
        stringBuffer4.append(downloadTask.getUrl());
        stringBuffer4.append("\n");
        try {
            StringBuffer stringBuffer5 = this.mDownloadMessage;
            stringBuffer5.append("file=");
            stringBuffer5.append(downloadTask.getFile() == null ? "" : downloadTask.getFile().getCanonicalPath());
            stringBuffer5.append("\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
        String name = Thread.currentThread().getName();
        Thread.currentThread().setName("pool-download-thread-" + Runtime.getInstance().generateGlobalThreadId());
        try {
            downloadTask.setStatus(1002);
            IOException e2 = null;
            int i = 0;
            int i2 = ERROR_LOAD;
            while (i <= downloadTask.retry) {
                try {
                    i2 = doDownload();
                } catch (IOException e3) {
                    e2 = e3;
                    this.mThrowable = e2;
                    if (Runtime.getInstance().isDebug()) {
                        e2.printStackTrace();
                    }
                    i2 = ERROR_LOAD;
                }
                if (e2 == null) {
                    break;
                }
                if (i == downloadTask.retry) {
                    downloadTask.error();
                    this.mDownloadTask.setThrowable(e2);
                }
                StringBuffer stringBuffer6 = this.mDownloadMessage;
                stringBuffer6.append("download error message: ");
                stringBuffer6.append(e2.getMessage());
                stringBuffer6.append("\n");
                i++;
                if (i <= downloadTask.retry) {
                    StringBuffer stringBuffer7 = this.mDownloadMessage;
                    stringBuffer7.append("download error , retry ");
                    stringBuffer7.append(i);
                    stringBuffer7.append("\n");
                }
            }
            try {
                StringBuffer stringBuffer8 = this.mDownloadMessage;
                stringBuffer8.append("final output file=");
                if (downloadTask.getFile() != null) {
                    str = downloadTask.getFile().getCanonicalPath();
                }
                stringBuffer8.append(str);
                stringBuffer8.append("\n");
            } catch (IOException e4) {
                e4.printStackTrace();
            }
            if (downloadTask.getHeaders() != null && !downloadTask.getHeaders().isEmpty()) {
                StringBuffer stringBuffer9 = this.mDownloadMessage;
                stringBuffer9.append("custom request headers=");
                stringBuffer9.append(downloadTask.getHeaders().toString());
                stringBuffer9.append("\n");
            }
            StringBuffer stringBuffer10 = this.mDownloadMessage;
            stringBuffer10.append("error=");
            stringBuffer10.append("0x" + Integer.toHexString(i2));
            stringBuffer10.append("\n");
            StringBuffer stringBuffer11 = this.mDownloadMessage;
            stringBuffer11.append("error table: ERROR_NETWORK_CONNECTION = 0x4000,ERROR_RESPONSE_STATUS = 0x4001,ERROR_STORAGE = 0x4002,ERROR_TIME_OUT = 0x4003,ERROR_USER_PAUSE = 0x4004,ERROR_USER_CANCEL = 0x4006,ERROR_SHUTDOWN = 0x4007,ERROR_TOO_MANY_REDIRECTS = 0x4008,ERROR_LOAD = 0x4009,ERROR_RESOURCE_NOT_FOUND = 0x4010,ERROR_MD5 = 0x4011,ERROR_SERVICE = 0x5003,SUCCESSFUL = 0x2000,HTTP_RANGE_NOT_SATISFIABLE = 4016");
            stringBuffer11.append("\n");
            StringBuffer stringBuffer12 = this.mDownloadMessage;
            stringBuffer12.append("error message=");
            stringBuffer12.append(DOWNLOAD_MESSAGE.get(i2));
            stringBuffer12.append("\n");
            StringBuffer stringBuffer13 = this.mDownloadMessage;
            stringBuffer13.append("mLoaded=");
            stringBuffer13.append(this.mLoaded);
            stringBuffer13.append("\n");
            StringBuffer stringBuffer14 = this.mDownloadMessage;
            stringBuffer14.append("mLastLoaded=");
            stringBuffer14.append(this.mLastLoaded);
            stringBuffer14.append("\n");
            StringBuffer stringBuffer15 = this.mDownloadMessage;
            stringBuffer15.append("mLoaded+mLastLoaded=");
            stringBuffer15.append(this.mLoaded + this.mLastLoaded);
            stringBuffer15.append("\n");
            StringBuffer stringBuffer16 = this.mDownloadMessage;
            stringBuffer16.append("totals=");
            stringBuffer16.append(this.mTotals);
            stringBuffer16.append("\n");
            if (downloadTask.getStatus() == 1005 || i2 == 16401) {
                StringBuffer stringBuffer17 = this.mDownloadMessage;
                stringBuffer17.append("isCalculateMD5=");
                stringBuffer17.append(downloadTask.isCalculateMD5());
                stringBuffer17.append("\n");
                if (!TextUtils.isEmpty(downloadTask.fileMD5)) {
                    StringBuffer stringBuffer18 = this.mDownloadMessage;
                    stringBuffer18.append("FileMD5=");
                    stringBuffer18.append(downloadTask.fileMD5);
                    stringBuffer18.append("\n");
                } else {
                    StringBuffer stringBuffer19 = this.mDownloadMessage;
                    stringBuffer19.append("FileMD5=");
                    stringBuffer19.append("''");
                    stringBuffer19.append("\n");
                }
            }
            if (!TextUtils.isEmpty(downloadTask.getTargetCompareMD5())) {
                StringBuffer stringBuffer20 = this.mDownloadMessage;
                stringBuffer20.append("targetCompareMD5=");
                stringBuffer20.append(downloadTask.getTargetCompareMD5());
                stringBuffer20.append("\n");
            }
            StringBuffer stringBuffer21 = this.mDownloadMessage;
            stringBuffer21.append("current downloadTask status=");
            stringBuffer21.append(downloadTask.getStatus());
            stringBuffer21.append("\n");
            StringBuffer stringBuffer22 = this.mDownloadMessage;
            stringBuffer22.append("status table: STATUS_NEW = 1000,STATUS_PENDDING = 1001,STATUS_DOWNLOADING = 1002,STATUS_PAUSING = 1003,STATUS_PAUSED = 1004,STATUS_SUCCESSFUL = 1005,STATUS_CANCELED = 1006,STATUS_ERROR = 1007");
            stringBuffer22.append("\n");
            StringBuffer stringBuffer23 = this.mDownloadMessage;
            stringBuffer23.append("used time=");
            stringBuffer23.append(downloadTask.getUsedTime());
            stringBuffer23.append("ms");
            stringBuffer23.append("\n");
            this.mDownloadMessage.append("\r\n");
            Runtime.getInstance().log(TAG, "\r\n" + this.mDownloadMessage.toString());
            Thread.currentThread().setName(name);
            return Integer.valueOf(i2);
        } catch (Throwable th) {
            Thread.currentThread().setName(name);
            throw th;
        }
    }

    private int transferDataFromUrl() {
        LoadingRandomAccessFile loadingRandomAccessFile;
        DownloadTask downloadTask = this.mDownloadTask;
        String url = downloadTask.getUrl();
        if (!url.startsWith("data") || !url.contains(",")) {
            return ERROR_LOAD;
        }
        String extractContent = extractContent();
        if (TextUtils.isEmpty(extractContent)) {
            return ERROR_LOAD;
        }
        byte[] decode = Base64.decode(extractContent, 0);
        downloadTask.setContentLength(decode.length);
        downloadTask.setTotalsLength(decode.length);
        Closeable closeable = null;
        try {
            try {
                loadingRandomAccessFile = new LoadingRandomAccessFile(downloadTask.getFile());
            } catch (Throwable th) {
                th = th;
            }
        } catch (IOException e) {
            e = e;
        }
        try {
            loadingRandomAccessFile.seek(0L);
            loadingRandomAccessFile.write(decode);
            progressFinaly();
            closeIO(loadingRandomAccessFile);
            return 8192;
        } catch (IOException e2) {
            e = e2;
            closeable = loadingRandomAccessFile;
            e.printStackTrace();
            progressFinaly();
            closeIO(closeable);
            return 8192;
        } catch (Throwable th2) {
            th = th2;
            closeable = loadingRandomAccessFile;
            progressFinaly();
            closeIO(closeable);
            throw th;
        }
    }

    String extractContent() {
        String str;
        int indexOf;
        int i;
        DownloadTask downloadTask = this.mDownloadTask;
        if (!downloadTask.isDataURI() || (indexOf = (str = downloadTask.mUrl).indexOf(",", 5)) <= 5) {
            return "";
        }
        for (int i2 = indexOf; i2 >= 5; i2--) {
            String valueOf = String.valueOf(str.charAt(i2));
            if (valueOf.equals(";") || valueOf.equals(":")) {
                i = i2 + 1;
                break;
            }
        }
        i = -1;
        String substring = str.substring(i, indexOf);
        if (!substring.equalsIgnoreCase("base64")) {
            Runtime.getInstance().log(TAG, "unsupport chartset:" + substring);
            return "";
        }
        return str.substring(str.indexOf(",", 5) + 1);
    }

    private int doDownload() throws IOException {
        boolean z;
        DownloadTask downloadTask = this.mDownloadTask;
        downloadTask.updateTime(this.mBeginTime);
        downloadTask.resetConnectTimes();
        HttpURLConnection httpURLConnection = null;
        URL url = TextUtils.isEmpty(downloadTask.redirect) ? new URL(downloadTask.getUrl()) : new URL(downloadTask.getRedirect());
        int i = 0;
        while (true) {
            int i2 = i + 1;
            if (i > 7) {
                downloadTask.error();
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
                return ERROR_TOO_MANY_REDIRECTS;
            }
            try {
                StringBuffer stringBuffer = this.mDownloadMessage;
                stringBuffer.append("redirectionCount=");
                stringBuffer.append(i2);
                stringBuffer.append("\n");
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
                if (downloadTask.connectTimes <= 0) {
                    httpURLConnection = createUrlConnection(url);
                    settingHeaders(downloadTask, httpURLConnection);
                    try {
                        httpURLConnection.connect();
                        if (!downloadTask.isPausing()) {
                            downloadTask.pause();
                            if (httpURLConnection != null) {
                                httpURLConnection.disconnect();
                            }
                            return ERROR_USER_PAUSE;
                        }
                        if (downloadTask.isPaused()) {
                            if (httpURLConnection != null) {
                                httpURLConnection.disconnect();
                            }
                            return ERROR_USER_PAUSE;
                        }
                        if (downloadTask.isCanceled()) {
                            if (httpURLConnection != null) {
                                httpURLConnection.disconnect();
                            }
                            return ERROR_USER_CANCEL;
                        }
                        try {
                            z = "chunked".equalsIgnoreCase(httpURLConnection.getHeaderField("Transfer-Encoding"));
                        } catch (Throwable th) {
                            th.printStackTrace();
                            z = false;
                        }
                        long headerFieldLong = getHeaderFieldLong(httpURLConnection, "Content-Length");
                        boolean z2 = headerFieldLong > 0;
                        boolean z3 = (z && z2) || !(z || z2);
                        int responseCode = httpURLConnection.getResponseCode();
                        Runtime.getInstance().log(TAG, "responseCode:" + responseCode);
                        StringBuffer stringBuffer2 = this.mDownloadMessage;
                        stringBuffer2.append("responseCode=");
                        stringBuffer2.append(responseCode);
                        stringBuffer2.append("\n");
                        if (responseCode == 206 && !z2) {
                            downloadTask.successful();
                            if (httpURLConnection != null) {
                                httpURLConnection.disconnect();
                            }
                            return 8192;
                        }
                        if (responseCode != 200) {
                            if (responseCode == 206) {
                                if (z3) {
                                    Runtime.getInstance().logError(TAG, " error , giving up ,  EncodingChunked:" + z + "  hasLength:" + z2 + " response length:" + headerFieldLong + " responseCode:" + responseCode);
                                    downloadTask.error();
                                    if (httpURLConnection != null) {
                                        httpURLConnection.disconnect();
                                    }
                                    return ERROR_LOAD;
                                }
                                if (this.mTotals <= 0) {
                                    this.mTotals = downloadTask.getFile().length() + headerFieldLong;
                                }
                                if (this.mTotals > 0 && downloadTask.getFile().length() + headerFieldLong != this.mTotals) {
                                    downloadTask.error();
                                    Runtime.getInstance().logError(TAG, "length error, this.mTotals:" + this.mTotals + " contentLength:" + headerFieldLong + " file length:" + downloadTask.getFile().length());
                                    if (httpURLConnection != null) {
                                        httpURLConnection.disconnect();
                                    }
                                    return ERROR_LOAD;
                                }
                                downloadTask.setTotalsLength(this.mTotals);
                                if (!checkSpace()) {
                                    downloadTask.error();
                                    if (httpURLConnection != null) {
                                        httpURLConnection.disconnect();
                                    }
                                    return 16386;
                                }
                                Runtime.getInstance().log(TAG, "last:" + this.mLastLoaded + " totals:" + this.mTotals);
                                StringBuffer stringBuffer3 = this.mDownloadMessage;
                                stringBuffer3.append("last=");
                                stringBuffer3.append(this.mLastLoaded);
                                stringBuffer3.append(" totals=");
                                stringBuffer3.append(this.mTotals);
                                stringBuffer3.append("\n");
                                int transferData = transferData(getInputStream(httpURLConnection), new LoadingRandomAccessFile(downloadTask.getFile()), true);
                                if (httpURLConnection != null) {
                                    httpURLConnection.disconnect();
                                }
                                return transferData;
                            }
                            if (responseCode != 307) {
                                if (responseCode == 404) {
                                    if (httpURLConnection != null) {
                                        httpURLConnection.disconnect();
                                    }
                                    return ERROR_RESOURCE_NOT_FOUND;
                                }
                                if (responseCode != 4016) {
                                    switch (responseCode) {
                                        case ErrorCode.E_UNSUPPORT_DEVICE:
                                        case ErrorCode.E_VOS_NOT_START:
                                        case ErrorCode.E_T0_NOT_START:
                                            break;
                                        default:
                                            switch (responseCode) {
                                                case 500:
                                                case 501:
                                                case 502:
                                                case 503:
                                                    downloadTask.error();
                                                    if (httpURLConnection != null) {
                                                        httpURLConnection.disconnect();
                                                    }
                                                    return ERROR_SERVICE;
                                                default:
                                                    downloadTask.error();
                                                    if (httpURLConnection != null) {
                                                        httpURLConnection.disconnect();
                                                    }
                                                    return ERROR_RESPONSE_STATUS;
                                            }
                                    }
                                } else if (downloadTask.getFile() != null) {
                                    Runtime.getInstance().log(TAG, "range not satisfiable .");
                                    StringBuffer stringBuffer4 = this.mDownloadMessage;
                                    stringBuffer4.append("range not satisfiable .");
                                    stringBuffer4.append("\n");
                                    downloadTask.getFile().delete();
                                    downloadTask.getFile().createNewFile();
                                }
                            }
                            String headerField = httpURLConnection.getHeaderField(AgentWebPermissions.ACTION_LOCATION);
                            if (TextUtils.isEmpty(headerField)) {
                                downloadTask.error();
                                if (httpURLConnection != null) {
                                    httpURLConnection.disconnect();
                                }
                                return ERROR_SERVICE;
                            }
                            StringBuffer stringBuffer5 = this.mDownloadMessage;
                            stringBuffer5.append("original url=");
                            stringBuffer5.append(httpURLConnection.getURL().toString());
                            stringBuffer5.append("  ,redirect url=" + headerField);
                            stringBuffer5.append("\n");
                            try {
                                URL url2 = new URL(url, headerField);
                                downloadTask.setRedirect(url2.toString());
                                url = url2;
                            } catch (MalformedURLException unused) {
                                downloadTask.error();
                                if (httpURLConnection != null) {
                                    httpURLConnection.disconnect();
                                }
                                return ERROR_SERVICE;
                            }
                        } else {
                            if (z3) {
                                Runtime.getInstance().logError(TAG, " error , giving up ,  EncodingChunked:" + z + "  hasLength:" + z2 + " response length:" + headerFieldLong + " responseCode:" + responseCode);
                                downloadTask.error();
                                if (httpURLConnection != null) {
                                    httpURLConnection.disconnect();
                                }
                                return ERROR_LOAD;
                            }
                            this.mTotals = headerFieldLong;
                            if (downloadTask.connectTimes <= 0) {
                                start(httpURLConnection);
                                downloadTask.connectTimes++;
                                if (downloadTask.getFile().length() > 0 && !z) {
                                    if (downloadTask.getFile().length() == headerFieldLong) {
                                        StringBuffer stringBuffer6 = this.mDownloadMessage;
                                        stringBuffer6.append("file already exist, file name=");
                                        stringBuffer6.append(downloadTask.getFile().getName());
                                        stringBuffer6.append(", file length==contentLength");
                                        stringBuffer6.append(",contentLength=");
                                        stringBuffer6.append(headerFieldLong);
                                        stringBuffer6.append("\n");
                                        String md5 = Runtime.getInstance().md5(downloadTask.getFile());
                                        int compare = Runtime.getInstance().getFileComparator().compare(downloadTask.getUrl(), downloadTask.getFile(), downloadTask.getTargetCompareMD5(), md5);
                                        StringBuffer stringBuffer7 = this.mDownloadMessage;
                                        stringBuffer7.append("compareResult=");
                                        stringBuffer7.append(compare);
                                        stringBuffer7.append("\n");
                                        StringBuffer stringBuffer8 = this.mDownloadMessage;
                                        stringBuffer8.append("compare Result table:");
                                        stringBuffer8.append("COMPARE_RESULT_SUCCESSFUL = 1");
                                        stringBuffer8.append(",COMPARE_RESULT_REDOWNLOAD_COVER = 2");
                                        stringBuffer8.append(",COMPARE_RESULT_REDOWNLOAD_RENAME = 3");
                                        stringBuffer8.append("\n");
                                        if (compare == 1) {
                                            downloadTask.setFileMD5(md5);
                                            this.mLastLoaded = headerFieldLong;
                                            publishProgressUpdate(1);
                                            downloadTask.successful();
                                            if (httpURLConnection == null) {
                                                return 8192;
                                            }
                                            httpURLConnection.disconnect();
                                            return 8192;
                                        }
                                        if (compare == 2) {
                                            downloadTask.getFile().delete();
                                            downloadTask.getFile().createNewFile();
                                        } else {
                                            int i3 = 1;
                                            while (true) {
                                                if (i3 < Integer.MAX_VALUE) {
                                                    File file = new File(downloadTask.getFile().getParent(), "(" + i3 + ")" + downloadTask.getFile().getName());
                                                    if (!file.exists()) {
                                                        StringBuffer stringBuffer9 = this.mDownloadMessage;
                                                        stringBuffer9.append("target file is not exist, create new target file ,file name=");
                                                        stringBuffer9.append(file.getName());
                                                        stringBuffer9.append("\n");
                                                        file.createNewFile();
                                                        downloadTask.setFileSafe(file);
                                                    } else if (file.length() >= headerFieldLong) {
                                                        Runtime.getInstance().log(TAG, "rename download , targetFile exists:" + file.getName());
                                                        i3++;
                                                    } else {
                                                        StringBuffer stringBuffer10 = this.mDownloadMessage;
                                                        stringBuffer10.append("origin file name=");
                                                        stringBuffer10.append(downloadTask.getFile().getName());
                                                        stringBuffer10.append(" target file name=");
                                                        stringBuffer10.append(file.getName());
                                                        stringBuffer10.append(",current target file length=");
                                                        stringBuffer10.append(file.length());
                                                        stringBuffer10.append("\n");
                                                        downloadTask.setFileSafe(file);
                                                    }
                                                }
                                            }
                                        }
                                    } else if (downloadTask.getFile().length() >= headerFieldLong) {
                                        StringBuffer stringBuffer11 = this.mDownloadMessage;
                                        stringBuffer11.append("file length error .");
                                        stringBuffer11.append("\n");
                                        downloadTask.getFile().delete();
                                        downloadTask.getFile().createNewFile();
                                    }
                                }
                            }
                        }
                        i = i2;
                    } catch (IOException e) {
                        throw e;
                    }
                } else {
                    httpURLConnection = createUrlConnection(url);
                    settingHeaders(downloadTask, httpURLConnection);
                    rangeHeaders(downloadTask, httpURLConnection);
                    try {
                        httpURLConnection.connect();
                        if (!downloadTask.isPausing()) {
                        }
                    } catch (IOException e2) {
                        throw e2;
                    }
                }
            } catch (Throwable th2) {
                if (httpURLConnection != null) {
                    httpURLConnection.disconnect();
                }
                throw th2;
            }
        }
    }

    private void rangeHeaders(DownloadTask downloadTask, HttpURLConnection httpURLConnection) {
        if (downloadTask.getFile() != null && downloadTask.getFile().length() > 0) {
            StringBuilder sb = new StringBuilder();
            sb.append("bytes=");
            long length = downloadTask.getFile().length();
            this.mLastLoaded = length;
            sb.append(length);
            sb.append("-");
            httpURLConnection.setRequestProperty("Range", sb.toString());
        }
        StringBuffer stringBuffer = this.mDownloadMessage;
        stringBuffer.append("range=");
        stringBuffer.append(this.mLastLoaded);
        stringBuffer.append("\n");
        httpURLConnection.setRequestProperty("Connection", "close");
    }

    private final void start(HttpURLConnection httpURLConnection) throws IOException {
        DownloadTask downloadTask = this.mDownloadTask;
        if (TextUtils.isEmpty(downloadTask.getContentDisposition())) {
            downloadTask.setContentDisposition(httpURLConnection.getHeaderField("Content-Disposition"));
            String fileNameByContentDisposition = Runtime.getInstance().getFileNameByContentDisposition(downloadTask.getContentDisposition());
            if (!TextUtils.isEmpty(fileNameByContentDisposition) && !downloadTask.getFile().getName().equals(fileNameByContentDisposition)) {
                File file = new File(downloadTask.getFile().getParent(), fileNameByContentDisposition);
                if (file.exists()) {
                    downloadTask.setFileSafe(file);
                    updateNotifierTitle();
                } else {
                    File file2 = downloadTask.getFile();
                    if (downloadTask.getFile().renameTo(file)) {
                        downloadTask.setFileSafe(file);
                        updateNotifierTitle();
                        StringBuffer stringBuffer = this.mDownloadMessage;
                        stringBuffer.append("origin=");
                        stringBuffer.append(file2.getName());
                        stringBuffer.append(" rename=");
                        stringBuffer.append(file.getName());
                        stringBuffer.append("\n");
                        file2.delete();
                    }
                }
            }
        }
        if (TextUtils.isEmpty(downloadTask.getMimetype())) {
            downloadTask.setMimetype(httpURLConnection.getHeaderField("Content-Type"));
        }
        if (TextUtils.isEmpty(downloadTask.getUserAgent())) {
            String headerField = httpURLConnection.getHeaderField("User-Agent");
            if (headerField == null) {
                headerField = "";
            }
            downloadTask.setUserAgent(headerField);
        }
        downloadTask.setContentLength(getHeaderFieldLong(httpURLConnection, "Content-Length"));
        onStart();
    }

    private void updateNotifierTitle() {
        DownloadTask downloadTask = this.mDownloadTask;
        DownloadNotifier downloadNotifier = downloadTask.mDownloadNotifier;
        if (downloadNotifier != null) {
            downloadNotifier.updateTitle(downloadTask);
        }
    }

    protected void onStart() throws IOException {
        final DownloadTask downloadTask = this.mDownloadTask;
        if (downloadTask == null || downloadTask.getDownloadListener() == null) {
            return;
        }
        HANDLER.post(new Runnable() {
            @Override
            public void run() {
                downloadTask.getDownloadListener().onStart(downloadTask.mUrl, downloadTask.mUserAgent, downloadTask.mContentDisposition, downloadTask.mMimetype, downloadTask.mTotalsLength, downloadTask);
            }
        });
    }

    private InputStream getInputStream(HttpURLConnection httpURLConnection) throws IOException {
        if ("gzip".equalsIgnoreCase(httpURLConnection.getContentEncoding())) {
            return new GZIPInputStream(httpURLConnection.getInputStream());
        }
        if ("deflate".equalsIgnoreCase(httpURLConnection.getContentEncoding())) {
            return new InflaterInputStream(httpURLConnection.getInputStream(), new Inflater(true));
        }
        return httpURLConnection.getInputStream();
    }

    private long getHeaderFieldLong(HttpURLConnection httpURLConnection, String str) {
        String headerField = httpURLConnection.getHeaderField(str);
        if (headerField == null) {
            return -1L;
        }
        try {
            return Long.parseLong(headerField);
        } catch (NumberFormatException e) {
            if (Runtime.getInstance().isDebug()) {
                e.printStackTrace();
            }
            return -1L;
        }
    }

    private void saveEtag(HttpURLConnection httpURLConnection) {
        String headerField = httpURLConnection.getHeaderField("ETag");
        if (TextUtils.isEmpty(headerField)) {
            return;
        }
        String md5 = Runtime.getInstance().md5(this.mDownloadTask.getUrl());
        Runtime.getInstance().log(TAG, "save etag:" + headerField);
        Runtime.getInstance().getStorageEngine(this.mDownloadTask.mContext).save(md5, headerField);
    }

    private String getEtag() {
        String str = Runtime.getInstance().getStorageEngine(this.mDownloadTask.mContext).get(Runtime.getInstance().md5(this.mDownloadTask.getUrl()), "-1");
        if (TextUtils.isEmpty(str) || "-1".equals(str)) {
            return null;
        }
        return str;
    }

    private HttpURLConnection createUrlConnection(URL url) throws IOException {
        DownloadTask downloadTask = this.mDownloadTask;
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout((int) this.mConnectTimeOut);
        httpURLConnection.setInstanceFollowRedirects(false);
        httpURLConnection.setReadTimeout((int) downloadTask.getBlockMaxTime());
        httpURLConnection.setRequestProperty("Accept", "*/*");
        httpURLConnection.setRequestProperty("Accept-Encoding", "deflate,gzip");
        return httpURLConnection;
    }

    private void settingHeaders(DownloadTask downloadTask, HttpURLConnection httpURLConnection) {
        Map<String, String> headers = downloadTask.getHeaders();
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                if (!TextUtils.isEmpty(entry.getKey()) && !TextUtils.isEmpty(entry.getValue())) {
                    httpURLConnection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
        }
        String etag = getEtag();
        if (TextUtils.isEmpty(etag)) {
            return;
        }
        Runtime.getInstance().log(TAG, "Etag:" + etag);
        httpURLConnection.setRequestProperty("If-Match", getEtag());
    }

    @Override
    protected void onProgressUpdate(Integer... numArr) {
        DownloadTask downloadTask = this.mDownloadTask;
        DownloadNotifier downloadNotifier = downloadTask.mDownloadNotifier;
        try {
            long elapsedRealtime = SystemClock.elapsedRealtime() - this.mBeginTime;
            this.mUsedTime = elapsedRealtime;
            if (elapsedRealtime == 0) {
                this.mAverageSpeed = 0L;
            } else {
                this.mAverageSpeed = (this.mLoaded * 1000) / this.mUsedTime;
            }
            if (numArr != null && numArr.length > 0 && numArr[0].intValue() == 1 && downloadNotifier != null) {
                if (this.mTotals > 0) {
                    downloadNotifier.onDownloading((int) (((this.mLastLoaded + this.mLoaded) / Float.valueOf(this.mTotals).floatValue()) * 100.0f));
                } else {
                    downloadNotifier.onDownloaded(this.mLastLoaded + this.mLoaded);
                }
            }
            if (downloadTask.getDownloadListener() != null) {
                downloadTask.getDownloadingListener().onProgress(downloadTask.getUrl(), this.mLastLoaded + this.mLoaded, this.mTotals, downloadTask.getUsedTime());
            }
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }

    private int transferData(InputStream inputStream, RandomAccessFile randomAccessFile, boolean z) throws IOException {
        int i;
        byte[] bArr = new byte[8192];
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 8192);
        DownloadTask downloadTask = this.mDownloadTask;
        this.mLoaded = 0L;
        try {
            if (z) {
                randomAccessFile.seek(randomAccessFile.length());
            } else {
                randomAccessFile.seek(0L);
                this.mLastLoaded = 0L;
            }
            while (!downloadTask.isPausing() && !downloadTask.isCanceled() && !downloadTask.isPaused()) {
                try {
                    int read = bufferedInputStream.read(bArr, 0, 8192);
                    if (read == -1) {
                        break;
                    }
                    randomAccessFile.write(bArr, 0, read);
                    if (SystemClock.elapsedRealtime() - this.mBeginTime > this.mDownloadTimeOut) {
                        this.mDownloadTask.error();
                        i = ERROR_TIME_OUT;
                        break;
                    }
                } catch (IOException e) {
                    downloadTask.error();
                    throw e;
                }
            }
            if (downloadTask.isPausing()) {
                downloadTask.pause();
            } else if (!downloadTask.isPaused()) {
                if (!downloadTask.isCanceled()) {
                    if (downloadTask.isCalculateMD5()) {
                        this.mDownloadTask.setFileMD5(Runtime.getInstance().md5(this.mDownloadTask.mFile));
                    }
                    if (!TextUtils.isEmpty(downloadTask.getTargetCompareMD5())) {
                        if (TextUtils.isEmpty(downloadTask.fileMD5)) {
                            this.mDownloadTask.setFileMD5(Runtime.getInstance().md5(this.mDownloadTask.mFile));
                        }
                        if (!downloadTask.getTargetCompareMD5().equalsIgnoreCase(downloadTask.getFileMD5())) {
                            downloadTask.error();
                            i = ERROR_MD5;
                        }
                    }
                    progressFinaly();
                    downloadTask.successful();
                    return 8192;
                }
                i = ERROR_USER_CANCEL;
                return i;
            }
            return ERROR_USER_PAUSE;
        } finally {
            closeIO(randomAccessFile);
            closeIO(bufferedInputStream);
            closeIO(inputStream);
        }
    }

    public void closeIO(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public final DownloadTask cancel() {
        DownloadTask downloadTask = this.mDownloadTask;
        downloadTask.cancel();
        return downloadTask;
    }

    @Override
    public int status() {
        DownloadTask downloadTask = this.mDownloadTask;
        if (downloadTask == null) {
            return 1000;
        }
        return downloadTask.getStatus();
    }

    private final DownloadTask pause() {
        DownloadTask downloadTask = this.mDownloadTask;
        downloadTask.pausing();
        return downloadTask;
    }

    @Override
    public DownloadTask cancelDownload() {
        return cancel();
    }

    @Override
    public DownloadTask pauseDownload() {
        return pause();
    }

    @Override
    public DownloadTask getDownloadTask() {
        return this.mDownloadTask;
    }

    private final class LoadingRandomAccessFile extends RandomAccessFile {
        public LoadingRandomAccessFile(File file) throws FileNotFoundException {
            super(file, "rw");
        }

        @Override
        public void write(byte[] bArr, int i, int i2) throws IOException {
            super.write(bArr, i, i2);
            Downloader.access$014(Downloader.this, i2);
            DownloadTask downloadTask = Downloader.this.mDownloadTask;
            if (downloadTask != null) {
                downloadTask.setLoaded(Downloader.this.mLastLoaded + Downloader.this.mLoaded);
            }
            Downloader.this.onProgress();
        }
    }

    private void progressFinaly() {
        this.mLastTime = SystemClock.elapsedRealtime();
        publishProgressUpdate(1);
    }

    public void onProgress() {
        if (this.enableProgress) {
            if (this.quickProgress) {
                long elapsedRealtime = SystemClock.elapsedRealtime();
                if (elapsedRealtime - this.mLastTime < 1200) {
                    publishProgressUpdate(0);
                    return;
                } else {
                    this.mLastTime = elapsedRealtime;
                    publishProgressUpdate(1);
                    return;
                }
            }
            long elapsedRealtime2 = SystemClock.elapsedRealtime();
            if (elapsedRealtime2 - this.mLastTime < 1200) {
                return;
            }
            this.mLastTime = elapsedRealtime2;
            publishProgressUpdate(1);
        }
    }

    private void publishProgressUpdate(int i) {
        if (this.mCallbackInMainThread) {
            publishProgress(Integer.valueOf(i));
        } else {
            onProgressUpdate(Integer.valueOf(i));
        }
    }
}