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


package sjm.xuitls.http.loader;

import android.text.TextUtils;
import com.baidu.speech.utils.auth.RangeFileAsyncHttpResponseHandler;
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;
import sjm.xuitls.cache.DiskCacheEntity;
import sjm.xuitls.cache.DiskCacheFile;
import sjm.xuitls.cache.LruDiskCache;
import sjm.xuitls.common.Callback;
import sjm.xuitls.common.util.IOUtil;
import sjm.xuitls.common.util.LogUtil;
import sjm.xuitls.common.util.ProcessLock;
import sjm.xuitls.ex.FileLockedException;
import sjm.xuitls.ex.HttpException;
import sjm.xuitls.http.RequestParams;
import sjm.xuitls.http.request.UriRequest;

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;

    @Override // sjm.xuitls.http.loader.Loader
    public void save2Cache(UriRequest uriRequest) {
    }

    @Override // sjm.xuitls.http.loader.Loader
    public Loader<File> newInstance() {
        return new FileLoader();
    }

    @Override // sjm.xuitls.http.loader.Loader
    public void setParams(RequestParams requestParams) {
        if (requestParams != null) {
            this.params = requestParams;
            this.isAutoResume = requestParams.isAutoResume();
            this.isAutoRename = requestParams.isAutoRename();
        }
    }

    /* access modifiers changed from: protected */
    public File load(InputStream inputStream) throws Throwable {
        Throwable th;
        BufferedOutputStream bufferedOutputStream;
        FileOutputStream fileOutputStream;
        Throwable th2;
        FileInputStream fileInputStream;
        BufferedInputStream bufferedInputStream = 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 bufferedInputStream2 = new BufferedInputStream(inputStream);
                try {
                    BufferedOutputStream bufferedOutputStream2 = new BufferedOutputStream(fileOutputStream);
                    try {
                        if (this.progressHandler == null || this.progressHandler.updateProgress(j2, length, true)) {
                            byte[] bArr = new byte[4096];
                            while (true) {
                                int read = bufferedInputStream2.read(bArr);
                                if (read == -1) {
                                    bufferedOutputStream2.flush();
                                    DiskCacheFile diskCacheFile2 = this.diskCacheFile;
                                    if (diskCacheFile2 != null) {
                                        file = diskCacheFile2.commit();
                                    }
                                    if (this.progressHandler != null) {
                                        this.progressHandler.updateProgress(j2, length, true);
                                    }
                                    IOUtil.closeQuietly(bufferedInputStream2);
                                    IOUtil.closeQuietly(bufferedOutputStream2);
                                    return autoRename(file);
                                } else if (file.getParentFile().exists()) {
                                    bufferedOutputStream2.write(bArr, 0, read);
                                    length = ((long) read) + length;
                                    if (this.progressHandler != null && !this.progressHandler.updateProgress(j2, length, false)) {
                                        bufferedOutputStream2.flush();
                                        throw new Callback.CancelledException("download stopped!");
                                    }
                                } else {
                                    file.getParentFile().mkdirs();
                                    throw new IOException("parent be deleted!");
                                }
                            }
                        } else {
                            throw new Callback.CancelledException("download stopped!");
                        }
                    } catch (Throwable th5) {
                        bufferedOutputStream = bufferedOutputStream2;
                        th = th5;
                        bufferedInputStream = bufferedInputStream2;
                        IOUtil.closeQuietly(bufferedInputStream);
                        IOUtil.closeQuietly(bufferedOutputStream);
                        throw th;
                    }
                } catch (Throwable th6) {
                    th = th6;
                    bufferedOutputStream = null;
                    bufferedInputStream = bufferedInputStream2;
                    IOUtil.closeQuietly(bufferedInputStream);
                    IOUtil.closeQuietly(bufferedOutputStream);
                    throw th;
                }
            } else {
                throw new IOException("could not create the file: " + this.tempSaveFilePath);
            }
        } catch (Throwable th7) {
            th = th7;
            bufferedOutputStream = null;
            IOUtil.closeQuietly(bufferedInputStream);
            IOUtil.closeQuietly(bufferedOutputStream);
            throw th;
        }
    }

    @Override // sjm.xuitls.http.loader.Loader
    public File load(UriRequest uriRequest) throws Throwable {
        File file;
        File file2;
        ProcessLock processLock = null;
        try {
            String saveFilePath2 = this.params.getSaveFilePath();
            this.saveFilePath = saveFilePath2;
            this.diskCacheFile = null;
            if (!TextUtils.isEmpty(saveFilePath2)) {
                this.tempSaveFilePath = this.saveFilePath + ".tmp";
            } else if (this.progressHandler == null || this.progressHandler.updateProgress(0, 0, false)) {
                initDiskCacheFile(uriRequest);
            } else {
                throw new Callback.CancelledException("download stopped!");
            }
            if (this.progressHandler == null || this.progressHandler.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 file3 = new File(this.tempSaveFilePath);
                    long length = file3.length();
                    if (length <= 512) {
                        IOUtil.deleteFileOrDir(file3);
                    } else {
                        j = length - 512;
                    }
                }
                RequestParams requestParams = this.params;
                requestParams.setHeader(Command.HTTP_HEADER_RANGE, "bytes=" + j + "-");
                if (this.progressHandler == null || this.progressHandler.updateProgress(0, 0, false)) {
                    uriRequest.sendRequest();
                    this.contentLength = uriRequest.getContentLength();
                    if (this.isAutoRename) {
                        this.responseFileName = getResponseFileName(uriRequest);
                    }
                    if (this.isAutoResume) {
                        this.isAutoResume = isSupportRange(uriRequest);
                    }
                    if (this.progressHandler == null || this.progressHandler.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;
                if (diskCacheFile3 != null) {
                    file2 = diskCacheFile3.commit();
                } else {
                    file2 = new File(this.tempSaveFilePath);
                }
                if (file2 == null || !file2.exists()) {
                    IOUtil.deleteFileOrDir(file2);
                    throw new IllegalStateException("cache file not found" + uriRequest.getCacheKey());
                }
                if (this.isAutoRename) {
                    this.responseFileName = getResponseFileName(uriRequest);
                }
                file = autoRename(file2);
            } else {
                throw e;
            }
        } catch (Throwable th2) {
            IOUtil.closeQuietly((Closeable) null);
            IOUtil.closeQuietly(this.diskCacheFile);
            throw th2;
        }
    }

    private void initDiskCacheFile(UriRequest uriRequest) throws Throwable {
        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 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 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);
        if (responseHeader2 == null || !responseHeader2.contains("bytes")) {
            return false;
        }
        return true;
    }

    @Override // sjm.xuitls.http.loader.Loader
    public File loadFromCache(DiskCacheEntity diskCacheEntity) throws Throwable {
        return LruDiskCache.getDiskCache(this.params.getCacheDirName()).getDiskCacheFile(diskCacheEntity.getKey());
    }
}