金坛河长通 v1.1.6版本的 MD5 值为:20e883288031684b3415ea19cd21af4d

以下内容为反编译后的 Downloader.java 源代码,内容仅作参考


package com.yanzhenjie.nohttp.download;

import android.support.v4.media.session.PlaybackStateCompat;
import android.text.TextUtils;
import android.util.Log;
import com.yanzhenjie.nohttp.Connection;
import com.yanzhenjie.nohttp.Headers;
import com.yanzhenjie.nohttp.HttpConnection;
import com.yanzhenjie.nohttp.Logger;
import com.yanzhenjie.nohttp.NetworkExecutor;
import com.yanzhenjie.nohttp.NoHttp;
import com.yanzhenjie.nohttp.error.NetworkError;
import com.yanzhenjie.nohttp.error.ServerError;
import com.yanzhenjie.nohttp.error.StorageReadWriteError;
import com.yanzhenjie.nohttp.error.StorageSpaceNotEnoughError;
import com.yanzhenjie.nohttp.error.TimeoutError;
import com.yanzhenjie.nohttp.error.URLError;
import com.yanzhenjie.nohttp.error.UnKnownHostError;
import com.yanzhenjie.nohttp.tools.HeaderUtils;
import com.yanzhenjie.nohttp.tools.IOUtils;
import com.yanzhenjie.nohttp.tools.NetUtils;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URLDecoder;
import java.net.UnknownHostException;

public class Downloader {
    private HttpConnection mHttpConnection;

    public Downloader(NetworkExecutor executor) {
        this.mHttpConnection = new HttpConnection(executor);
    }

    private void validateParam(DownloadRequest downloadRequest, DownloadListener downloadListener) {
        if (downloadRequest == null) {
            throw new IllegalArgumentException("DownloadRequest == null.");
        }
        if (downloadListener == null) {
            throw new IllegalArgumentException("DownloadListener == null.");
        }
    }

    private void validateDevice(String savePathDir) throws Exception {
        if (!NetUtils.isNetworkAvailable()) {
            throw new NetworkError("Network is not available, please check network and permission: INTERNET, ACCESS_WIFI_STATE, ACCESS_NETWORK_STATE.");
        }
        if (!IOUtils.createFolder(savePathDir)) {
            throw new StorageReadWriteError("SD card isn't available, please check SD card and permission: WRITE_EXTERNAL_STORAGE.\nYou must pay attention to Android6.0 RunTime Permissions: https://github.com/yanzhenjie/AndPermission.\nFailed to create folder: " + savePathDir);
        }
    }

    private Connection getConnectionRetry(DownloadRequest downloadRequest) throws Exception {
        Connection connection = this.mHttpConnection.getConnection(downloadRequest);
        Exception exception = connection.exception();
        if (exception != null) {
            throw exception;
        }
        Headers responseHeaders = connection.responseHeaders();
        int responseCode = responseHeaders.getResponseCode();
        if (responseCode == 416) {
            downloadRequest.removeHeader("Range");
            return this.mHttpConnection.getConnection(downloadRequest);
        }
        return connection;
    }

    private String getRealFileName(DownloadRequest request, Headers responseHeaders) throws IOException {
        String fileName = null;
        String contentDisposition = responseHeaders.getContentDisposition();
        if (!TextUtils.isEmpty(contentDisposition)) {
            fileName = HeaderUtils.parseHeadValue(contentDisposition, "filename", null);
            if (!TextUtils.isEmpty(fileName)) {
                try {
                    fileName = URLDecoder.decode(fileName, request.getParamsEncoding());
                } catch (UnsupportedEncodingException e) {
                }
                if (fileName.startsWith("\"") && fileName.endsWith("\"")) {
                    fileName = fileName.substring(1, fileName.length() - 1);
                }
            }
        }
        if (TextUtils.isEmpty(fileName)) {
            String url = request.url();
            URI uri = URI.create(url);
            String path = uri.getPath();
            if (TextUtils.isEmpty(path)) {
                String fileName2 = Integer.toString(url.hashCode());
                return fileName2;
            }
            String[] slash = path.split("/");
            String fileName3 = slash[slash.length - 1];
            return fileName3;
        }
        return fileName;
    }

    public void download(int what, DownloadRequest request, DownloadListener downloadListener) {
        File tempFile;
        long rangeSize;
        Headers responseHeaders;
        long contentLength;
        validateParam(request, downloadListener);
        Connection connection = null;
        RandomAccessFile randomAccessFile = null;
        String savePathDir = request.getFileDir();
        String fileName = request.getFileName();
        try {
            try {
                if (TextUtils.isEmpty(savePathDir)) {
                    savePathDir = NoHttp.getContext().getFilesDir().getAbsolutePath();
                }
                validateDevice(savePathDir);
                request.removeHeader("Range");
                if (TextUtils.isEmpty(fileName)) {
                    connection = getConnectionRetry(request);
                    Exception tempE = connection.exception();
                    if (tempE != null) {
                        throw tempE;
                    }
                    responseHeaders = connection.responseHeaders();
                    fileName = getRealFileName(request, responseHeaders);
                    tempFile = new File(savePathDir, fileName + ".nohttp");
                    if (request.isRange() && tempFile.exists() && tempFile.length() > 0) {
                        connection.close();
                        rangeSize = tempFile.length();
                        request.setHeader("Range", "bytes=" + rangeSize + "-");
                        connection = getConnectionRetry(request);
                        Exception tempE2 = connection.exception();
                        if (tempE2 != null) {
                            throw tempE2;
                        }
                        responseHeaders = connection.responseHeaders();
                        if (!request.containsHeader("Range")) {
                            IOUtils.delFileOrFolder(tempFile);
                            rangeSize = 0;
                        }
                    } else {
                        IOUtils.delFileOrFolder(tempFile);
                        rangeSize = 0;
                    }
                } else {
                    tempFile = new File(savePathDir, fileName + ".nohttp");
                    if (request.isRange() && tempFile.exists() && tempFile.length() > 0) {
                        rangeSize = tempFile.length();
                        request.setHeader("Range", "bytes=" + rangeSize + "-");
                    } else {
                        IOUtils.delFileOrFolder(tempFile);
                        rangeSize = 0;
                    }
                    connection = getConnectionRetry(request);
                    Exception tempE3 = connection.exception();
                    if (tempE3 != null) {
                        throw tempE3;
                    }
                    responseHeaders = connection.responseHeaders();
                    if (!request.containsHeader("Range")) {
                        IOUtils.delFileOrFolder(tempFile);
                        rangeSize = 0;
                    }
                }
                Logger.i("----------Response Start----------");
                int responseCode = responseHeaders.getResponseCode();
                InputStream serverStream = connection.serverStream();
                if (responseCode >= 400) {
                    ServerError error = new ServerError("Download failed, the server response code is " + responseCode + ": " + request.url());
                    error.setErrorBody(IOUtils.toString(serverStream));
                    throw error;
                }
                if (responseCode == 206) {
                    String range = responseHeaders.getContentRange();
                    try {
                        contentLength = Long.parseLong(range.substring(range.indexOf(47) + 1));
                    } catch (Throwable th) {
                        throw new ServerError("ResponseCode is 206, but content-Range error in Server HTTP header information: " + range + ".");
                    }
                } else {
                    if (responseCode == 304) {
                        int httpContentLength = responseHeaders.getContentLength();
                        long rangeSize2 = httpContentLength;
                        downloadListener.onStart(what, true, rangeSize2, responseHeaders, httpContentLength);
                        downloadListener.onProgress(what, 100, httpContentLength, 0L);
                        Logger.d("-------Download finish-------");
                        downloadListener.onFinish(what, savePathDir + File.separator + fileName);
                        Logger.i("----------Response End----------");
                        IOUtils.closeQuietly((Closeable) null);
                        IOUtils.closeQuietly(connection);
                        return;
                    }
                    rangeSize = 0;
                    contentLength = responseHeaders.getContentLength();
                }
                File lastFile = new File(savePathDir, fileName);
                if (lastFile.exists()) {
                    if (!request.isDeleteOld()) {
                        long rangeSize3 = lastFile.length();
                        long contentLength2 = lastFile.length();
                        downloadListener.onStart(what, true, rangeSize3, responseHeaders, contentLength2);
                        downloadListener.onProgress(what, 100, lastFile.length(), 0L);
                        Logger.d("-------Download finish-------");
                        downloadListener.onFinish(what, lastFile.getAbsolutePath());
                        Logger.i("----------Response End----------");
                        IOUtils.closeQuietly((Closeable) null);
                        IOUtils.closeQuietly(connection);
                        return;
                    }
                    IOUtils.delFileOrFolder(lastFile);
                }
                if (IOUtils.getDirSize(savePathDir) < contentLength) {
                    throw new StorageSpaceNotEnoughError("The folder is not enough space to save the downloaded file: " + savePathDir + ".");
                }
                if (responseCode != 206 && !IOUtils.createNewFile(tempFile)) {
                    throw new StorageReadWriteError("SD card isn't available, please check SD card and permission: WRITE_EXTERNAL_STORAGE.\nYou must pay attention to Android6.0 RunTime Permissions: https://github.com/yanzhenjie/AndPermission.\nFailed to create file: " + tempFile);
                }
                if (request.isCanceled()) {
                    Log.w("NoHttpDownloader", "Download request is canceled.");
                    downloadListener.onCancel(what);
                    Logger.i("----------Response End----------");
                    IOUtils.closeQuietly((Closeable) null);
                    IOUtils.closeQuietly(connection);
                    return;
                }
                Logger.d("-------Download start-------");
                downloadListener.onStart(what, rangeSize > 0, rangeSize, responseHeaders, contentLength);
                RandomAccessFile randomAccessFile2 = new RandomAccessFile(tempFile, "rws");
                try {
                    randomAccessFile2.seek(rangeSize);
                    byte[] buffer = new byte[8096];
                    int oldProgress = 0;
                    long count = rangeSize;
                    long startTime = System.currentTimeMillis();
                    long speedCount = 0;
                    long oldSpeed = 0;
                    while (true) {
                        int len = serverStream.read(buffer);
                        if (len == -1) {
                            break;
                        }
                        if (request.isCanceled()) {
                            Log.i("NoHttpDownloader", "Download request is canceled.");
                            downloadListener.onCancel(what);
                            break;
                        }
                        randomAccessFile2.write(buffer, 0, len);
                        count += len;
                        speedCount += len;
                        long time = Math.max(System.currentTimeMillis() - startTime, 1L);
                        long speed = (1000 * speedCount) / time;
                        boolean speedChanged = oldSpeed != speed && time >= 300;
                        if (contentLength != 0) {
                            int progress = (int) ((100 * count) / contentLength);
                            if (progress != oldProgress && speedChanged) {
                                downloadListener.onProgress(what, progress, count, speed);
                                speedCount = 0;
                                oldSpeed = speed;
                                startTime = System.currentTimeMillis();
                            } else if (speedChanged) {
                                downloadListener.onProgress(what, oldProgress, count, speed);
                                speedCount = 0;
                                oldSpeed = speed;
                                startTime = System.currentTimeMillis();
                            } else if (progress != oldProgress) {
                                downloadListener.onProgress(what, progress, count, oldSpeed);
                            }
                            oldProgress = progress;
                        } else if (speedChanged) {
                            downloadListener.onProgress(what, 0, count, speed);
                            speedCount = 0;
                            oldSpeed = speed;
                            startTime = System.currentTimeMillis();
                        } else {
                            downloadListener.onProgress(what, 0, count, oldSpeed);
                        }
                    }
                    if (!request.isCanceled()) {
                        tempFile.renameTo(lastFile);
                        Logger.d("-------Download finish-------");
                        downloadListener.onFinish(what, lastFile.getAbsolutePath());
                    }
                    Logger.i("----------Response End----------");
                    IOUtils.closeQuietly(randomAccessFile2);
                    IOUtils.closeQuietly(connection);
                } catch (MalformedURLException e) {
                    e = e;
                    randomAccessFile = randomAccessFile2;
                    Logger.e((Throwable) e);
                    downloadListener.onDownloadError(what, new URLError(e.getMessage()));
                    Logger.i("----------Response End----------");
                    IOUtils.closeQuietly(randomAccessFile);
                    IOUtils.closeQuietly(connection);
                } catch (SocketTimeoutException e2) {
                    e = e2;
                    randomAccessFile = randomAccessFile2;
                    Logger.e((Throwable) e);
                    downloadListener.onDownloadError(what, new TimeoutError(e.getMessage()));
                    Logger.i("----------Response End----------");
                    IOUtils.closeQuietly(randomAccessFile);
                    IOUtils.closeQuietly(connection);
                } catch (UnknownHostException e3) {
                    e = e3;
                    randomAccessFile = randomAccessFile2;
                    Logger.e((Throwable) e);
                    downloadListener.onDownloadError(what, new UnKnownHostError(e.getMessage()));
                    Logger.i("----------Response End----------");
                    IOUtils.closeQuietly(randomAccessFile);
                    IOUtils.closeQuietly(connection);
                } catch (IOException e4) {
                    e = e4;
                    randomAccessFile = randomAccessFile2;
                    Exception newException = e;
                    if (!IOUtils.canWrite(savePathDir)) {
                        newException = new StorageReadWriteError("SD card isn't available, please check SD card and permission: WRITE_EXTERNAL_STORAGE.\nYou must pay attention to Android6.0 RunTime Permissions: https://github.com/yanzhenjie/AndPermission.\nFailed to create folder: " + savePathDir);
                    } else if (IOUtils.getDirSize(savePathDir) < PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID) {
                        newException = new StorageSpaceNotEnoughError("The folder is not enough space to save the downloaded file: " + savePathDir + ".");
                    }
                    Logger.e((Throwable) newException);
                    downloadListener.onDownloadError(what, newException);
                    Logger.i("----------Response End----------");
                    IOUtils.closeQuietly(randomAccessFile);
                    IOUtils.closeQuietly(connection);
                } catch (Exception e5) {
                    e = e5;
                    randomAccessFile = randomAccessFile2;
                    if (!NetUtils.isNetworkAvailable()) {
                        e = new NetworkError("Network is not available, please check network and permission: INTERNET, ACCESS_WIFI_STATE, ACCESS_NETWORK_STATE.");
                    }
                    Logger.e((Throwable) e);
                    downloadListener.onDownloadError(what, e);
                    Logger.i("----------Response End----------");
                    IOUtils.closeQuietly(randomAccessFile);
                    IOUtils.closeQuietly(connection);
                } catch (Throwable th2) {
                    th = th2;
                    randomAccessFile = randomAccessFile2;
                    Logger.i("----------Response End----------");
                    IOUtils.closeQuietly(randomAccessFile);
                    IOUtils.closeQuietly(connection);
                    throw th;
                }
            } catch (Throwable th3) {
                th = th3;
            }
        } catch (MalformedURLException e6) {
            e = e6;
        } catch (SocketTimeoutException e7) {
            e = e7;
        } catch (UnknownHostException e8) {
            e = e8;
        } catch (IOException e9) {
            e = e9;
        } catch (Exception e10) {
            e = e10;
        }
    }
}