翰林优商.apk(点击下载) / FileLoader.java


package com.duoyou.task.sdk.xutils.http.loader;

import android.text.TextUtils;
import com.baidu.speech.utils.auth.RangeFileAsyncHttpResponseHandler;
import com.duoyou.task.sdk.xutils.cache.DiskCacheEntity;
import com.duoyou.task.sdk.xutils.cache.DiskCacheFile;
import com.duoyou.task.sdk.xutils.cache.LruDiskCache;
import com.duoyou.task.sdk.xutils.common.Callback;
import com.duoyou.task.sdk.xutils.common.util.IOUtil;
import com.duoyou.task.sdk.xutils.common.util.LogUtil;
import com.duoyou.task.sdk.xutils.common.util.ProcessLock;
import com.duoyou.task.sdk.xutils.ex.FileLockedException;
import com.duoyou.task.sdk.xutils.ex.HttpException;
import com.duoyou.task.sdk.xutils.http.ProgressHandler;
import com.duoyou.task.sdk.xutils.http.RequestParams;
import com.duoyou.task.sdk.xutils.http.request.UriRequest;
import com.mbridge.msdk.foundation.download.Command;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Date;

public class FileLoader extends Loader<File> {
    private static final int CHECK_SIZE = 512;
    private long contentLength;
    private DiskCacheFile diskCacheFile;
    private boolean isAutoRename;
    private boolean isAutoResume;
    private RequestParams params;
    private String responseFileName;
    private String saveFilePath;
    private String tempSaveFilePath;

    private File autoRename(File file) {
        if (this.isAutoRename && file.exists() && !TextUtils.isEmpty(this.responseFileName)) {
            File file2 = new File(file.getParent(), this.responseFileName);
            while (file2.exists()) {
                String parent = file.getParent();
                file2 = new File(parent, System.currentTimeMillis() + this.responseFileName);
            }
            return file.renameTo(file2) ? file2 : file;
        } else if (this.saveFilePath.equals(this.tempSaveFilePath)) {
            return file;
        } else {
            File file3 = new File(this.saveFilePath);
            return file.renameTo(file3) ? file3 : file;
        }
    }

    private static String getResponseFileName(UriRequest uriRequest) {
        int indexOf;
        if (uriRequest == null) {
            return null;
        }
        String responseHeader = uriRequest.getResponseHeader("Content-Disposition");
        if (!TextUtils.isEmpty(responseHeader) && (indexOf = responseHeader.indexOf("filename=")) > 0) {
            int i = indexOf + 9;
            int indexOf2 = responseHeader.indexOf(";", i);
            if (indexOf2 < 0) {
                indexOf2 = responseHeader.length();
            }
            if (indexOf2 > i) {
                try {
                    String decode = URLDecoder.decode(responseHeader.substring(i, indexOf2), uriRequest.getParams().getCharset());
                    return (!decode.startsWith("\"") || !decode.endsWith("\"")) ? decode : decode.substring(1, decode.length() - 1);
                } catch (UnsupportedEncodingException e) {
                    LogUtil.e(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    private void initDiskCacheFile(UriRequest uriRequest) {
        DiskCacheEntity diskCacheEntity = new DiskCacheEntity();
        diskCacheEntity.setKey(uriRequest.getCacheKey());
        DiskCacheFile createDiskCacheFile = LruDiskCache.getDiskCache(this.params.getCacheDirName()).createDiskCacheFile(diskCacheEntity);
        this.diskCacheFile = createDiskCacheFile;
        if (createDiskCacheFile != null) {
            String absolutePath = createDiskCacheFile.getAbsolutePath();
            this.saveFilePath = absolutePath;
            this.tempSaveFilePath = absolutePath;
            this.isAutoRename = false;
            return;
        }
        throw new IOException("create cache file error:" + uriRequest.getCacheKey());
    }

    private static boolean isSupportRange(UriRequest uriRequest) {
        if (uriRequest == null) {
            return false;
        }
        String responseHeader = uriRequest.getResponseHeader("Accept-Ranges");
        if (responseHeader != null) {
            return responseHeader.contains("bytes");
        }
        String responseHeader2 = uriRequest.getResponseHeader(RangeFileAsyncHttpResponseHandler.HEADER_CONTENT_RANGE);
        return responseHeader2 != null && responseHeader2.contains("bytes");
    }

    @Override // com.duoyou.task.sdk.xutils.http.loader.Loader
    public File load(UriRequest uriRequest) {
        File file;
        ProcessLock processLock = null;
        try {
            String saveFilePath2 = this.params.getSaveFilePath();
            this.saveFilePath = saveFilePath2;
            this.diskCacheFile = null;
            if (TextUtils.isEmpty(saveFilePath2)) {
                ProgressHandler progressHandler = this.progressHandler;
                if (progressHandler == null || progressHandler.updateProgress(0, 0, false)) {
                    initDiskCacheFile(uriRequest);
                } else {
                    throw new Callback.CancelledException("download stopped!");
                }
            } else {
                this.tempSaveFilePath = this.saveFilePath + ".tmp";
            }
            ProgressHandler progressHandler2 = this.progressHandler;
            if (progressHandler2 == null || progressHandler2.updateProgress(0, 0, false)) {
                processLock = ProcessLock.tryLock(this.saveFilePath + "_lock", true);
                if (processLock == null || !processLock.isValid()) {
                    throw new FileLockedException("download exists: " + this.saveFilePath);
                }
                this.params = uriRequest.getParams();
                long j = 0;
                if (this.isAutoResume) {
                    File file2 = new File(this.tempSaveFilePath);
                    long length = file2.length();
                    if (length <= 512) {
                        IOUtil.deleteFileOrDir(file2);
                    } else {
                        j = length - 512;
                    }
                }
                RequestParams requestParams = this.params;
                requestParams.setHeader(Command.HTTP_HEADER_RANGE, "bytes=" + j + "-");
                ProgressHandler progressHandler3 = this.progressHandler;
                if (progressHandler3 == null || progressHandler3.updateProgress(0, 0, false)) {
                    uriRequest.sendRequest();
                    this.contentLength = uriRequest.getContentLength();
                    if (this.isAutoRename) {
                        this.responseFileName = getResponseFileName(uriRequest);
                    }
                    if (this.isAutoResume) {
                        this.isAutoResume = isSupportRange(uriRequest);
                    }
                    ProgressHandler progressHandler4 = this.progressHandler;
                    if (progressHandler4 == null || progressHandler4.updateProgress(0, 0, false)) {
                        DiskCacheFile diskCacheFile2 = this.diskCacheFile;
                        if (diskCacheFile2 != null) {
                            try {
                                DiskCacheEntity cacheEntity = diskCacheFile2.getCacheEntity();
                                cacheEntity.setLastAccess(System.currentTimeMillis());
                                cacheEntity.setEtag(uriRequest.getETag());
                                cacheEntity.setExpires(uriRequest.getExpiration());
                                cacheEntity.setLastModify(new Date(uriRequest.getLastModified()));
                            } catch (Throwable th) {
                                LogUtil.e(th.getMessage(), th);
                            }
                        }
                        file = load(uriRequest.getInputStream());
                        IOUtil.closeQuietly(processLock);
                        IOUtil.closeQuietly(this.diskCacheFile);
                        return file;
                    }
                    throw new Callback.CancelledException("download stopped!");
                }
                throw new Callback.CancelledException("download stopped!");
            }
            throw new Callback.CancelledException("download stopped!");
        } catch (HttpException e) {
            if (e.getCode() == 416) {
                DiskCacheFile diskCacheFile3 = this.diskCacheFile;
                File commit = diskCacheFile3 != null ? diskCacheFile3.commit() : new File(this.tempSaveFilePath);
                if (commit == null || !commit.exists()) {
                    IOUtil.deleteFileOrDir(commit);
                    throw new IllegalStateException("cache file not found" + uriRequest.getCacheKey());
                }
                if (this.isAutoRename) {
                    this.responseFileName = getResponseFileName(uriRequest);
                }
                file = autoRename(commit);
            } else {
                throw e;
            }
        } catch (Throwable th2) {
            IOUtil.closeQuietly((Closeable) null);
            IOUtil.closeQuietly(this.diskCacheFile);
            throw th2;
        }
    }

    public File load(InputStream inputStream) {
        BufferedInputStream bufferedInputStream;
        Throwable th;
        FileOutputStream fileOutputStream;
        BufferedOutputStream bufferedOutputStream;
        BufferedOutputStream bufferedOutputStream2;
        FileInputStream fileInputStream;
        Throwable th2;
        BufferedOutputStream bufferedOutputStream3 = null;
        try {
            File file = new File(this.tempSaveFilePath);
            if (!file.isDirectory()) {
                if (!file.exists()) {
                    File parentFile = file.getParentFile();
                    if ((!parentFile.exists() && !parentFile.mkdirs()) || !parentFile.isDirectory()) {
                        throw new IOException("could not create the dir: " + parentFile.getAbsolutePath());
                    }
                }
                long length = file.length();
                if (this.isAutoResume && length > 0) {
                    long j = length - 512;
                    if (j > 0) {
                        try {
                            fileInputStream = new FileInputStream(file);
                            try {
                                if (Arrays.equals(IOUtil.readBytes(inputStream, 0, 512), IOUtil.readBytes(fileInputStream, j, 512))) {
                                    this.contentLength -= 512;
                                    IOUtil.closeQuietly(fileInputStream);
                                } else {
                                    IOUtil.closeQuietly(fileInputStream);
                                    IOUtil.deleteFileOrDir(file);
                                    throw new RuntimeException("need retry");
                                }
                            } catch (Throwable th3) {
                                th2 = th3;
                                IOUtil.closeQuietly(fileInputStream);
                                throw th2;
                            }
                        } catch (Throwable th4) {
                            th2 = th4;
                            fileInputStream = null;
                            IOUtil.closeQuietly(fileInputStream);
                            throw th2;
                        }
                    } else {
                        IOUtil.deleteFileOrDir(file);
                        throw new RuntimeException("need retry");
                    }
                }
                if (this.isAutoResume) {
                    fileOutputStream = new FileOutputStream(file, true);
                } else {
                    fileOutputStream = new FileOutputStream(file);
                    length = 0;
                }
                long j2 = this.contentLength + length;
                bufferedInputStream = new BufferedInputStream(inputStream);
                try {
                    bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
                } catch (Throwable th5) {
                    th = th5;
                    IOUtil.closeQuietly(bufferedInputStream);
                    IOUtil.closeQuietly(bufferedOutputStream3);
                    throw th;
                }
                try {
                    ProgressHandler progressHandler = this.progressHandler;
                    if (progressHandler != null) {
                        bufferedOutputStream2 = bufferedOutputStream;
                        try {
                            if (!progressHandler.updateProgress(j2, length, true)) {
                                throw new Callback.CancelledException("download stopped!");
                            }
                        } catch (Throwable th6) {
                            th = th6;
                            bufferedOutputStream3 = bufferedOutputStream2;
                            IOUtil.closeQuietly(bufferedInputStream);
                            IOUtil.closeQuietly(bufferedOutputStream3);
                            throw th;
                        }
                    } else {
                        bufferedOutputStream2 = bufferedOutputStream;
                    }
                    byte[] bArr = new byte[4096];
                    while (true) {
                        int read = bufferedInputStream.read(bArr);
                        if (read == -1) {
                            bufferedOutputStream2.flush();
                            DiskCacheFile diskCacheFile2 = this.diskCacheFile;
                            if (diskCacheFile2 != null) {
                                file = diskCacheFile2.commit();
                            }
                            ProgressHandler progressHandler2 = this.progressHandler;
                            if (progressHandler2 != null) {
                                progressHandler2.updateProgress(j2, length, true);
                            }
                            IOUtil.closeQuietly(bufferedInputStream);
                            IOUtil.closeQuietly(bufferedOutputStream2);
                            return autoRename(file);
                        } else if (file.getParentFile().exists()) {
                            bufferedOutputStream2.write(bArr, 0, read);
                            length = ((long) read) + length;
                            ProgressHandler progressHandler3 = this.progressHandler;
                            if (progressHandler3 != null) {
                                if (!progressHandler3.updateProgress(j2, length, false)) {
                                    bufferedOutputStream2.flush();
                                    throw new Callback.CancelledException("download stopped!");
                                }
                            }
                        } else {
                            file.getParentFile().mkdirs();
                            throw new IOException("parent be deleted!");
                        }
                    }
                } catch (Throwable th7) {
                    th = th7;
                    bufferedOutputStream2 = bufferedOutputStream;
                    bufferedOutputStream3 = bufferedOutputStream2;
                    IOUtil.closeQuietly(bufferedInputStream);
                    IOUtil.closeQuietly(bufferedOutputStream3);
                    throw th;
                }
            } else {
                throw new IOException("could not create the file: " + this.tempSaveFilePath);
            }
        } catch (Throwable th8) {
            th = th8;
            bufferedInputStream = null;
            IOUtil.closeQuietly(bufferedInputStream);
            IOUtil.closeQuietly(bufferedOutputStream3);
            throw th;
        }
    }

    @Override // com.duoyou.task.sdk.xutils.http.loader.Loader
    public File loadFromCache(DiskCacheEntity diskCacheEntity) {
        return LruDiskCache.getDiskCache(this.params.getCacheDirName()).getDiskCacheFile(diskCacheEntity.getKey());
    }

    @Override // com.duoyou.task.sdk.xutils.http.loader.Loader
    public Loader<File> newInstance() {
        return new FileLoader();
    }

    @Override // com.duoyou.task.sdk.xutils.http.loader.Loader
    public void save2Cache(UriRequest uriRequest) {
    }

    @Override // com.duoyou.task.sdk.xutils.http.loader.Loader
    public void setParams(RequestParams requestParams) {
        if (requestParams != null) {
            this.params = requestParams;
            this.isAutoResume = requestParams.isAutoResume();
            this.isAutoRename = requestParams.isAutoRename();
        }
    }
}